Merge branch 'MDL-56345-31' of https://github.com/lucisgit/moodle into MOODLE_31_STABLE
[moodle.git] / Gruntfile.js
blob7412970b956b896ee0a12483cc322584920d03a3
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         tasks = {},
29         cwd = process.env.PWD || process.cwd();
31     // Windows users can't run grunt in a subdirectory, so allow them to set
32     // the root by passing --root=path/to/dir.
33     if (grunt.option('root')) {
34         var root = grunt.option('root');
35         if (grunt.file.exists(__dirname, root)) {
36             cwd = path.join(__dirname, root);
37             grunt.log.ok('Setting root to '+cwd);
38         } else {
39             grunt.fail.fatal('Setting root to '+root+' failed - path does not exist');
40         }
41     }
43     var inAMD = path.basename(cwd) == 'amd';
45     // Globbing pattern for matching all AMD JS source files.
46     var amdSrc = [inAMD ? cwd + '/src/*.js' : '**/amd/src/*.js'];
48     /**
49      * Function to generate the destination for the uglify task
50      * (e.g. build/file.min.js). This function will be passed to
51      * the rename property of files array when building dynamically:
52      * http://gruntjs.com/configuring-tasks#building-the-files-object-dynamically
53      *
54      * @param {String} destPath the current destination
55      * @param {String} srcPath the  matched src path
56      * @return {String} The rewritten destination path.
57      */
58     var uglify_rename = function (destPath, srcPath) {
59         destPath = srcPath.replace('src', 'build');
60         destPath = destPath.replace('.js', '.min.js');
61         destPath = path.resolve(cwd, destPath);
62         return destPath;
63     };
65     // Project configuration.
66     grunt.initConfig({
67         jshint: {
68             options: {jshintrc: '.jshintrc'},
69             amd: { src: amdSrc }
70         },
71         uglify: {
72             amd: {
73                 files: [{
74                     expand: true,
75                     src: amdSrc,
76                     rename: uglify_rename
77                 }]
78             }
79         },
80         less: {
81             bootstrapbase: {
82                 files: {
83                     "theme/bootstrapbase/style/moodle.css": "theme/bootstrapbase/less/moodle.less",
84                     "theme/bootstrapbase/style/editor.css": "theme/bootstrapbase/less/editor.less",
85                 },
86                 options: {
87                     compress: true
88                 }
89            }
90         },
91         watch: {
92             options: {
93                 nospawn: true // We need not to spawn so config can be changed dynamically.
94             },
95             amd: {
96                 files: ['**/amd/src/**/*.js'],
97                 tasks: ['amd']
98             },
99             bootstrapbase: {
100                 files: ["theme/bootstrapbase/less/**/*.less"],
101                 tasks: ["less:bootstrapbase"]
102             },
103             yui: {
104                 files: ['**/yui/src/**/*.js'],
105                 tasks: ['shifter']
106             },
107         },
108         shifter: {
109             options: {
110                 recursive: true,
111                 paths: [cwd]
112             }
113         }
114     });
116     /**
117      * Shifter task. Is configured with a path to a specific file or a directory,
118      * in the case of a specific file it will work out the right module to be built.
119      *
120      * Note that this task runs the invidiaul shifter jobs async (becase it spawns
121      * so be careful to to call done().
122      */
123     tasks.shifter = function() {
124         var async = require('async'),
125             done = this.async(),
126             options = grunt.config('shifter.options');
128         // Run the shifter processes one at a time to avoid confusing output.
129         async.eachSeries(options.paths, function (src, filedone) {
130             var args = [];
131             args.push( path.normalize(__dirname + '/node_modules/shifter/bin/shifter'));
133             // Always ignore the node_modules directory.
134             args.push('--excludes', 'node_modules');
136             // Determine the most appropriate options to run with based upon the current location.
137             if (grunt.file.isMatch('**/yui/**/*.js', src)) {
138                 // When passed a JS file, build our containing module (this happen with
139                 // watch).
140                 grunt.log.debug('Shifter passed a specific JS file');
141                 src = path.dirname(path.dirname(src));
142                 options.recursive = false;
143             } else if (grunt.file.isMatch('**/yui/src', src)) {
144                 // When in a src directory --walk all modules.
145                 grunt.log.debug('In a src directory');
146                 args.push('--walk');
147                 options.recursive = false;
148             } else if (grunt.file.isMatch('**/yui/src/*', src)) {
149                 // When in module, only build our module.
150                 grunt.log.debug('In a module directory');
151                 options.recursive = false;
152             } else if (grunt.file.isMatch('**/yui/src/*/js', src)) {
153                 // When in module src, only build our module.
154                 grunt.log.debug('In a source directory');
155                 src = path.dirname(src);
156                 options.recursive = false;
157             }
159             if (grunt.option('watch')) {
160                 grunt.fail.fatal('The --watch option has been removed, please use `grunt watch` instead');
161             }
163             // Add the stderr option if appropriate
164             if (grunt.option('verbose')) {
165                 args.push('--lint-stderr');
166             }
168             if (grunt.option('no-color')) {
169                 args.push('--color=false');
170             }
172             var execShifter = function() {
174                 grunt.log.ok("Running shifter on " + src);
175                 grunt.util.spawn({
176                     cmd: "node",
177                     args: args,
178                     opts: {cwd: src, stdio: 'inherit', env: process.env}
179                 }, function (error, result, code) {
180                     if (code) {
181                         grunt.fail.fatal('Shifter failed with code: ' + code);
182                     } else {
183                         grunt.log.ok('Shifter build complete.');
184                         filedone();
185                     }
186                 });
187             };
189             // Actually run shifter.
190             if (!options.recursive) {
191                 execShifter();
192             } else {
193                 // Check that there are yui modules otherwise shifter ends with exit code 1.
194                 if (grunt.file.expand({cwd: src}, '**/yui/src/**/*.js').length > 0) {
195                     args.push('--recursive');
196                     execShifter();
197                 } else {
198                     grunt.log.ok('No YUI modules to build.');
199                     filedone();
200                 }
201             }
202         }, done);
203     };
205     tasks.startup = function() {
206         // Are we in a YUI directory?
207         if (path.basename(path.resolve(cwd, '../../')) == 'yui') {
208             grunt.task.run('shifter');
209         // Are we in an AMD directory?
210         } else if (inAMD) {
211             grunt.task.run('amd');
212         } else {
213             // Run them all!.
214             grunt.task.run('css');
215             grunt.task.run('js');
216         }
217     };
219     // On watch, we dynamically modify config to build only affected files. This
220     // method is slightly complicated to deal with multiple changed files at once (copied
221     // from the grunt-contrib-watch readme).
222     var changedFiles = Object.create(null);
223     var onChange = grunt.util._.debounce(function() {
224           var files = Object.keys(changedFiles);
225           grunt.config('jshint.amd.src', files);
226           grunt.config('uglify.amd.files', [{ expand: true, src: files, rename: uglify_rename }]);
227           grunt.config('shifter.options.paths', files);
228           changedFiles = Object.create(null);
229     }, 200);
231     grunt.event.on('watch', function(action, filepath) {
232           changedFiles[filepath] = action;
233           onChange();
234     });
236     // Register NPM tasks.
237     grunt.loadNpmTasks('grunt-contrib-uglify');
238     grunt.loadNpmTasks('grunt-contrib-jshint');
239     grunt.loadNpmTasks('grunt-contrib-less');
240     grunt.loadNpmTasks('grunt-contrib-watch');
242     // Register JS tasks.
243     grunt.registerTask('shifter', 'Run Shifter against the current directory', tasks.shifter);
244     grunt.registerTask('amd', ['jshint', 'uglify']);
245     grunt.registerTask('js', ['amd', 'shifter']);
247     // Register CSS taks.
248     grunt.registerTask('css', ['less:bootstrapbase']);
250     // Register the startup task.
251     grunt.registerTask('startup', 'Run the correct tasks for the current directory', tasks.startup);
253     // Register the default task.
254     grunt.registerTask('default', ['startup']);