-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathdevcode.js
More file actions
99 lines (84 loc) · 3.14 KB
/
devcode.js
File metadata and controls
99 lines (84 loc) · 3.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
/*
* devcode
* https://github.com/livedata/grunt-devcode
*
* Written by Krzysztof Antczak
* Licensed under the Apache 2.0 license.
*/
/*jshint node:true*/
'use strict';
module.exports = init;
var grunt = require('grunt'),
path = require('path');
var _ = grunt.util._;
var defaultEnv = {};
function init(grunt)
{
grunt.registerMultiTask('devcode', 'Remove code blocks based on environment configuration', function()
{
var context = _.extend({},defaultEnv,process.env), files;
context.NODE_ENV = context.NODE_ENV || 'development';
var options = this.options();
context.NODE_ENV = options.env || context.NODE_ENV;
var cOpen = options.block.open || 'devcode';
var cClose = options.block.close || 'endcode';
var srcDir = path.resolve(process.cwd(), options.source);
var dstDir = path.resolve(process.cwd(), options.dest);
var _this = this;
var replaceCode = function ( files, type )
{
if ( type == 'html' || typeof type == 'undefined' )
{
var startblock = '<!--\\s*'+cOpen+':\\s*([^-]+)-->';
var endblock = '<!--\\s*'+cClose+'\\s*-->';
}
else if ( type == 'js' || type == 'css' )
{
var startblock = '\/\/\\s*'+cOpen+':\\s*?([^\\n]+)';
var endblock = '\/\/\\s*'+cClose+'\\s*';
}
files.forEach(function(file)
{
var sfile = path.resolve(srcDir,file);
var tfile = path.resolve(dstDir,file);
var obody = grunt.file.read(sfile);
var regex = new RegExp(startblock + '[\\s\\S]*?' + endblock + '[\\s\\r\\n]?', 'g');
// replace code according to current environment
var body = obody.replace(regex, function($0, $1)
{
var m = $1.replace(/^\s+|\s+$/g, ''); // trim
if ( m.indexOf('!') == -1 )
{
if ( context.NODE_ENV != m ) return ''; else return $0;
}
else
{
if ( '!'+context.NODE_ENV == m ) return ''; else return $0;
}
});
if ( options.clean == true ) // remove devcode tags
{
body = body.replace(new RegExp('^.*'+startblock + '\\n?', 'gm'), '');
body = body.replace(new RegExp(endblock + '\\n?', 'gm'), '');
}
if ( obody != body )
{
console.log ( 'Writing ', tfile );
grunt.file.write(tfile, body);
}
});
};
if ( options.html == true )
{
replaceCode(grunt.file.expand({filter : "isFile"}, srcDir), 'html');
}
if ( options.js == true )
{
replaceCode(grunt.file.expand({filter : "isFile"}, srcDir), 'js');
}
if ( options.css == true )
{
replaceCode(grunt.file.expand({filter : "isFile"}, srcDir), 'css');
}
});
};