Merge branch 'MDL-51075_30' of git://github.com/dmonllao/moodle into MOODLE_30_STABLE
[moodle.git] / Gruntfile.js
blob2d13f0d87b50a125f5a96e5d4a26c13c9aba5953
1 // This file is part of Moodle - http://moodle.org/
2 //
3 // Moodle is free software: you can redistribute it and/or modify
4 // it under the terms of the GNU General Public License as published by
5 // the Free Software Foundation, either version 3 of the License, or
6 // (at your option) any later version.
7 //
8 // Moodle is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11 // GNU General Public License for more details.
13 // You should have received a copy of the GNU General Public License
14 // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
15 /* jshint node: true, browser: false */
17 /**
18  * @copyright  2014 Andrew Nicols
19  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
20  */
22 /**
23  * Grunt configuration
24  */
26 module.exports = function(grunt) {
27     var path = require('path'),
28         fs = require('fs'),
29         tasks = {},
30         cwd = process.env.PWD || process.cwd();
32     // Windows users can't run grunt in a subdirectory, so allow them to set
33     // the root by passing --root=path/to/dir.
34     if (grunt.option('root')) {
35         var root = grunt.option('root');
36         if (grunt.file.exists(__dirname, root)) {
37             cwd = path.join(__dirname, root);
38             grunt.log.ok('Setting root to '+cwd);
39         } else {
40             grunt.fail.fatal('Setting root to '+root+' failed - path does not exist');
41         }
42     }
44     var inAMD = path.basename(cwd) == 'amd';
46     // Project configuration.
47     grunt.initConfig({
48         jshint: {
49             options: {jshintrc: '.jshintrc'},
50             files: [inAMD ? cwd + '/src/*.js' : '**/amd/src/*.js']
51         },
52         uglify: {
53             dynamic_mappings: {
54                 files: grunt.file.expandMapping(
55                     ['**/src/*.js', '!**/node_modules/**'],
56                     '',
57                     {
58                         cwd: cwd,
59                         rename: function(destBase, destPath) {
60                             destPath = destPath.replace('src', 'build');
61                             destPath = destPath.replace('.js', '.min.js');
62                             destPath = path.resolve(cwd, destPath);
63                             return destPath;
64                         }
65                     }
66                 )
67             }
68         },
69         less: {
70             bootstrapbase: {
71                 files: {
72                     "theme/bootstrapbase/style/moodle.css": "theme/bootstrapbase/less/moodle.less",
73                     "theme/bootstrapbase/style/editor.css": "theme/bootstrapbase/less/editor.less",
74                 },
75                 options: {
76                     compress: true
77                 }
78            }
79         }
80     });
82     tasks.shifter = function() {
83        var  exec = require('child_process').spawn,
84             done = this.async(),
85             args = [],
86             options = {
87                 recursive: true,
88                 watch: false,
89                 walk: false,
90                 module: false
91             },
92             shifter;
94             args.push( path.normalize(__dirname + '/node_modules/shifter/bin/shifter'));
96             // Determine the most appropriate options to run with based upon the current location.
97             if (path.basename(cwd) === 'src') {
98                 // Detect whether we're in a src directory.
99                 grunt.log.debug('In a src directory');
100                 args.push('--walk');
101                 options.walk = true;
102             } else if (path.basename(path.dirname(cwd)) === 'src') {
103                 // Detect whether we're in a module directory.
104                 grunt.log.debug('In a module directory');
105                 options.module = true;
106             }
108             if (grunt.option('watch')) {
109                 if (!options.walk && !options.module) {
110                     grunt.fail.fatal('Unable to watch unless in a src or module directory');
111                 }
113                 // It is not advisable to run with recursivity and watch - this
114                 // leads to building the build directory in a race-like fashion.
115                 grunt.log.debug('Detected a watch - disabling recursivity');
116                 options.recursive = false;
117                 args.push('--watch');
118             }
120             if (options.recursive) {
121                 args.push('--recursive');
122             }
124             // Always ignore the node_modules directory.
125             args.push('--excludes', 'node_modules');
127             // Add the stderr option if appropriate
128             if (grunt.option('verbose')) {
129                 args.push('--lint-stderr');
130             }
132             if (grunt.option('no-color')) {
133                 args.push('--color=false');
134             }
136             var execShifter = function() {
138                 shifter = exec("node", args, {
139                     cwd: cwd,
140                     stdio: 'inherit',
141                     env: process.env
142                 });
144                 // Tidy up after exec.
145                 shifter.on('exit', function (code) {
146                     if (code) {
147                         grunt.fail.fatal('Shifter failed with code: ' + code);
148                     } else {
149                         grunt.log.ok('Shifter build complete.');
150                         done();
151                     }
152                 });
153             };
155             // Actually run shifter.
156             if (!options.recursive) {
157                 execShifter();
158             } else {
159                 // Check that there are yui modules otherwise shifter ends with exit code 1.
160                 var found = false;
161                 var hasYuiModules = function(directory, callback) {
162                     fs.readdir(directory, function(err, files) {
163                         if (err) {
164                             return callback(err, null);
165                         }
167                         // If we already found a match there is no need to continue scanning.
168                         if (found === true) {
169                             return;
170                         }
172                         // We need to track the number of files to know when we return a result.
173                         var pending = files.length;
175                         // We first check files, so if there is a match we don't need further
176                         // async calls and we just return a true.
177                         for (var i = 0; i < files.length; i++) {
178                             if (files[i] === 'yui') {
179                                 return callback(null, true);
180                             }
181                         }
183                         // Iterate through subdirs if there were no matches.
184                         files.forEach(function (file) {
186                             var p = path.join(directory, file);
187                             stat = fs.statSync(p);
188                             if (!stat.isDirectory()) {
189                                 pending--;
190                             } else {
192                                 // We defer the pending-1 until we scan the whole dir and subdirs.
193                                 hasYuiModules(p, function(err, result) {
194                                     if (err) {
195                                         return callback(err);
196                                     }
198                                     if (result === true) {
199                                         // Once we get a true we notify the caller.
200                                         found = true;
201                                         return callback(null, true);
202                                     }
204                                     pending--;
205                                     if (pending === 0) {
206                                         // Notify the caller that the whole dir has been scaned and there are no matches.
207                                         return callback(null, false);
208                                     }
209                                 });
210                             }
212                             // No subdirs here, otherwise the return would be deferred until all subdirs are scanned.
213                             if (pending === 0) {
214                                 return callback(null, false);
215                             }
216                         });
217                     });
218                 };
220                 hasYuiModules(cwd, function(err, result) {
221                     if (err) {
222                         grunt.fail.fatal(err.message);
223                     }
225                     if (result === true) {
226                         execShifter();
227                     } else {
228                         grunt.log.ok('No YUI modules to build.');
229                         done();
230                     }
231                 });
232             }
233     };
235     tasks.startup = function() {
236         // Are we in a YUI directory?
237         if (path.basename(path.resolve(cwd, '../../')) == 'yui') {
238             grunt.task.run('shifter');
239         // Are we in an AMD directory?
240         } else if (inAMD) {
241             grunt.task.run('amd');
242         } else {
243             // Run them all!.
244             grunt.task.run('css');
245             grunt.task.run('js');
246         }
247     };
250     // Register NPM tasks.
251     grunt.loadNpmTasks('grunt-contrib-uglify');
252     grunt.loadNpmTasks('grunt-contrib-jshint');
253     grunt.loadNpmTasks('grunt-contrib-less');
255     // Register JS tasks.
256     grunt.registerTask('shifter', 'Run Shifter against the current directory', tasks.shifter);
257     grunt.registerTask('amd', ['jshint', 'uglify']);
258     grunt.registerTask('js', ['amd', 'shifter']);
260     // Register CSS taks.
261     grunt.registerTask('css', ['less:bootstrapbase']);
263     // Register the startup task.
264     grunt.registerTask('startup', 'Run the correct tasks for the current directory', tasks.startup);
266     // Register the default task.
267     grunt.registerTask('default', ['startup']);