Merge branch 'wip-mdl-55879' of https://github.com/rajeshtaneja/moodle
[moodle.git] / Gruntfile.js
blob08b28b675ff5f62bc479cd6fb768dc0e5e1909f7
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 */
16 /* eslint-env node */
18 /**
19  * @copyright  2014 Andrew Nicols
20  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
21  */
23 /**
24  * Grunt configuration
25  */
27 module.exports = function(grunt) {
28     var path = require('path'),
29         tasks = {},
30         cwd = process.env.PWD || process.cwd(),
31         async = require('async'),
32         DOMParser = require('xmldom').DOMParser,
33         xpath = require('xpath'),
34         semver = require('semver');
36     // Verify the node version is new enough.
37     var expected = semver.validRange(grunt.file.readJSON('package.json').engines.node);
38     var actual = semver.valid(process.version);
39     if (!semver.satisfies(actual, expected)) {
40         grunt.fail.fatal('Node version too old. Require ' + expected + ', version installed: ' + actual);
41     }
43     // Windows users can't run grunt in a subdirectory, so allow them to set
44     // the root by passing --root=path/to/dir.
45     if (grunt.option('root')) {
46         var root = grunt.option('root');
47         if (grunt.file.exists(__dirname, root)) {
48             cwd = path.join(__dirname, root);
49             grunt.log.ok('Setting root to ' + cwd);
50         } else {
51             grunt.fail.fatal('Setting root to ' + root + ' failed - path does not exist');
52         }
53     }
55     var inAMD = path.basename(cwd) == 'amd';
57     // Globbing pattern for matching all AMD JS source files.
58     var amdSrc = [inAMD ? cwd + '/src/*.js' : '**/amd/src/*.js'];
60     /**
61      * Function to generate the destination for the uglify task
62      * (e.g. build/file.min.js). This function will be passed to
63      * the rename property of files array when building dynamically:
64      * http://gruntjs.com/configuring-tasks#building-the-files-object-dynamically
65      *
66      * @param {String} destPath the current destination
67      * @param {String} srcPath the  matched src path
68      * @return {String} The rewritten destination path.
69      */
70     var uglifyRename = function(destPath, srcPath) {
71         destPath = srcPath.replace('src', 'build');
72         destPath = destPath.replace('.js', '.min.js');
73         destPath = path.resolve(cwd, destPath);
74         return destPath;
75     };
77     /**
78      * Find thirdpartylibs.xml and generate an array of paths contained within
79      * them (used to generate ignore files and so on).
80      *
81      * @return {array} The list of thirdparty paths.
82      */
83     var getThirdPartyPathsFromXML = function() {
84         var thirdpartyfiles = grunt.file.expand('*/**/thirdpartylibs.xml');
85         var libs = ['node_modules/', 'vendor/'];
87         thirdpartyfiles.forEach(function(file) {
88           var dirname = path.dirname(file);
90           var doc = new DOMParser().parseFromString(grunt.file.read(file));
91           var nodes = xpath.select("/libraries/library/location/text()", doc);
93           nodes.forEach(function(node) {
94             var lib = path.join(dirname, node.toString());
95             if (grunt.file.isDir(lib)) {
96                 // Ensure trailing slash on dirs.
97                 lib = lib.replace(/\/?$/, '/');
98             }
100             // Look for duplicate paths before adding to array.
101             if (libs.indexOf(lib) === -1) {
102                 libs.push(lib);
103             }
104           });
105         });
106         return libs;
107     };
110     // Project configuration.
111     grunt.initConfig({
112         eslint: {
113             // Even though warnings dont stop the build we don't display warnings by default because
114             // at this moment we've got too many core warnings.
115             options: {quiet: !grunt.option('show-lint-warnings')},
116             amd: {
117               src: amdSrc,
118               // Check AMD with some slightly stricter rules.
119               rules: {
120                 'no-unused-vars': 'error',
121                 'no-implicit-globals': 'error'
122               }
123             },
124             // Check YUI module source files.
125             yui: {
126                src: ['**/yui/src/**/*.js', '!*/**/yui/src/*/meta/*.js'],
127                options: {
128                    // Disable some rules which we can't safely define for YUI rollups.
129                    rules: {
130                      'no-undef': 'off',
131                      'no-unused-vars': 'off',
132                      'no-unused-expressions': 'off'
133                    }
134                }
135             }
136         },
137         uglify: {
138             amd: {
139                 files: [{
140                     expand: true,
141                     src: amdSrc,
142                     rename: uglifyRename
143                 }],
144                 options: {report: 'none'}
145             }
146         },
147         less: {
148             bootstrapbase: {
149                 files: {
150                     "theme/bootstrapbase/style/moodle.css": "theme/bootstrapbase/less/moodle.less",
151                     "theme/bootstrapbase/style/editor.css": "theme/bootstrapbase/less/editor.less",
152                 },
153                 options: {
154                     compress: false // We must not compress to keep the comments.
155                 }
156            }
157         },
158         watch: {
159             options: {
160                 nospawn: true // We need not to spawn so config can be changed dynamically.
161             },
162             amd: {
163                 files: ['**/amd/src/**/*.js'],
164                 tasks: ['amd']
165             },
166             bootstrapbase: {
167                 files: ["theme/bootstrapbase/less/**/*.less"],
168                 tasks: ["css"]
169             },
170             yui: {
171                 files: ['**/yui/src/**/*.js'],
172                 tasks: ['yui']
173             },
174         },
175         shifter: {
176             options: {
177                 recursive: true,
178                 paths: [cwd]
179             }
180         },
181         stylelint: {
182             less: {
183                 options: {
184                     syntax: 'less',
185                     configOverrides: {
186                         rules: {
187                             // TODO: MDL-55165 -Enable these rules once we make output-changing changes to less.
188                             "declaration-block-no-ignored-properties": null,
189                             "value-keyword-case": null,
190                             "declaration-block-no-duplicate-properties": null,
191                             "declaration-block-no-shorthand-property-overrides": null,
192                             "selector-type-no-unknown": null,
193                             "length-zero-no-unit": null,
194                             "color-hex-case": null,
195                             "color-hex-length": null,
196                             // These rules have to be disabled in .stylelintrc for scss compat.
197                             "at-rule-no-unknown": true,
198                             "no-browser-hacks": [true, {"severity": "warning"}]
199                         }
200                     }
201                 },
202                 src: ['theme/**/*.less']
203             },
204             scss: {
205                 options: {syntax: 'scss'},
206                 src: ['*/**/*.scss']
207             }
208         }
209     });
211     /**
212      * Generate ignore files (utilising thirdpartylibs.xml data)
213      */
214     tasks.ignorefiles = function() {
215       // An array of paths to third party directories.
216       var thirdPartyPaths = getThirdPartyPathsFromXML();
217       // Generate .eslintignore.
218       var eslintIgnores = ['# Generated by "grunt ignorefiles"', '*/**/yui/src/*/meta/', '*/**/build/'].concat(thirdPartyPaths);
219       grunt.file.write('.eslintignore', eslintIgnores.join('\n'));
220       // Generate .stylelintignore.
221       var stylelintIgnores = ['# Generated by "grunt ignorefiles"', 'theme/bootstrapbase/style/'].concat(thirdPartyPaths);
222       grunt.file.write('.stylelintignore', stylelintIgnores.join('\n'));
223     };
225     /**
226      * Shifter task. Is configured with a path to a specific file or a directory,
227      * in the case of a specific file it will work out the right module to be built.
228      *
229      * Note that this task runs the invidiaul shifter jobs async (becase it spawns
230      * so be careful to to call done().
231      */
232     tasks.shifter = function() {
233         var done = this.async(),
234             options = grunt.config('shifter.options');
236         // Run the shifter processes one at a time to avoid confusing output.
237         async.eachSeries(options.paths, function(src, filedone) {
238             var args = [];
239             args.push(path.normalize(__dirname + '/node_modules/shifter/bin/shifter'));
241             // Always ignore the node_modules directory.
242             args.push('--excludes', 'node_modules');
244             // Determine the most appropriate options to run with based upon the current location.
245             if (grunt.file.isMatch('**/yui/**/*.js', src)) {
246                 // When passed a JS file, build our containing module (this happen with
247                 // watch).
248                 grunt.log.debug('Shifter passed a specific JS file');
249                 src = path.dirname(path.dirname(src));
250                 options.recursive = false;
251             } else if (grunt.file.isMatch('**/yui/src', src)) {
252                 // When in a src directory --walk all modules.
253                 grunt.log.debug('In a src directory');
254                 args.push('--walk');
255                 options.recursive = false;
256             } else if (grunt.file.isMatch('**/yui/src/*', src)) {
257                 // When in module, only build our module.
258                 grunt.log.debug('In a module directory');
259                 options.recursive = false;
260             } else if (grunt.file.isMatch('**/yui/src/*/js', src)) {
261                 // When in module src, only build our module.
262                 grunt.log.debug('In a source directory');
263                 src = path.dirname(src);
264                 options.recursive = false;
265             }
267             if (grunt.option('watch')) {
268                 grunt.fail.fatal('The --watch option has been removed, please use `grunt watch` instead');
269             }
271             // Add the stderr option if appropriate
272             if (grunt.option('verbose')) {
273                 args.push('--lint-stderr');
274             }
276             if (grunt.option('no-color')) {
277                 args.push('--color=false');
278             }
280             var execShifter = function() {
282                 grunt.log.ok("Running shifter on " + src);
283                 grunt.util.spawn({
284                     cmd: "node",
285                     args: args,
286                     opts: {cwd: src, stdio: 'inherit', env: process.env}
287                 }, function(error, result, code) {
288                     if (code) {
289                         grunt.fail.fatal('Shifter failed with code: ' + code);
290                     } else {
291                         grunt.log.ok('Shifter build complete.');
292                         filedone();
293                     }
294                 });
295             };
297             // Actually run shifter.
298             if (!options.recursive) {
299                 execShifter();
300             } else {
301                 // Check that there are yui modules otherwise shifter ends with exit code 1.
302                 if (grunt.file.expand({cwd: src}, '**/yui/src/**/*.js').length > 0) {
303                     args.push('--recursive');
304                     execShifter();
305                 } else {
306                     grunt.log.ok('No YUI modules to build.');
307                     filedone();
308                 }
309             }
310         }, done);
311     };
313     tasks.startup = function() {
314         // Are we in a YUI directory?
315         if (path.basename(path.resolve(cwd, '../../')) == 'yui') {
316             grunt.task.run('yui');
317         // Are we in an AMD directory?
318         } else if (inAMD) {
319             grunt.task.run('amd');
320         } else {
321             // Run them all!.
322             grunt.task.run('css');
323             grunt.task.run('js');
324         }
325     };
327     // On watch, we dynamically modify config to build only affected files. This
328     // method is slightly complicated to deal with multiple changed files at once (copied
329     // from the grunt-contrib-watch readme).
330     var changedFiles = Object.create(null);
331     var onChange = grunt.util._.debounce(function() {
332           var files = Object.keys(changedFiles);
333           grunt.config('eslint.amd.src', files);
334           grunt.config('eslint.yui.src', files);
335           grunt.config('uglify.amd.files', [{expand: true, src: files, rename: uglifyRename}]);
336           grunt.config('shifter.options.paths', files);
337           grunt.config('stylelint.less.src', files);
338           changedFiles = Object.create(null);
339     }, 200);
341     grunt.event.on('watch', function(action, filepath) {
342           changedFiles[filepath] = action;
343           onChange();
344     });
346     // Register NPM tasks.
347     grunt.loadNpmTasks('grunt-contrib-uglify');
348     grunt.loadNpmTasks('grunt-contrib-less');
349     grunt.loadNpmTasks('grunt-contrib-watch');
350     grunt.loadNpmTasks('grunt-eslint');
351     grunt.loadNpmTasks('grunt-stylelint');
353     // Register JS tasks.
354     grunt.registerTask('shifter', 'Run Shifter against the current directory', tasks.shifter);
355     grunt.registerTask('ignorefiles', 'Generate ignore files for linters', tasks.ignorefiles);
356     grunt.registerTask('yui', ['eslint:yui', 'shifter']);
357     grunt.registerTask('amd', ['eslint:amd', 'uglify']);
358     grunt.registerTask('js', ['amd', 'yui']);
360     // Register CSS taks.
361     grunt.registerTask('css', ['stylelint:scss', 'stylelint:less', 'less:bootstrapbase']);
363     // Register the startup task.
364     grunt.registerTask('startup', 'Run the correct tasks for the current directory', tasks.startup);
366     // Register the default task.
367     grunt.registerTask('default', ['startup']);