Merge branch 'MDL-66980_37' of https://github.com/timhunt/moodle into MOODLE_37_STABLE
[moodle.git] / Gruntfile.js
blob815ff7ce73c587a0c4d477b471808f1044626917
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 /* eslint-env node */
28 module.exports = function(grunt) {
29     var path = require('path'),
30         tasks = {},
31         cwd = process.env.PWD || process.cwd(),
32         async = require('async'),
33         DOMParser = require('xmldom').DOMParser,
34         xpath = require('xpath'),
35         semver = require('semver');
37     // Verify the node version is new enough.
38     var expected = semver.validRange(grunt.file.readJSON('package.json').engines.node);
39     var actual = semver.valid(process.version);
40     if (!semver.satisfies(actual, expected)) {
41         grunt.fail.fatal('Node version not satisfied. Require ' + expected + ', version installed: ' + actual);
42     }
44     // Windows users can't run grunt in a subdirectory, so allow them to set
45     // the root by passing --root=path/to/dir.
46     if (grunt.option('root')) {
47         var root = grunt.option('root');
48         if (grunt.file.exists(__dirname, root)) {
49             cwd = path.join(__dirname, root);
50             grunt.log.ok('Setting root to ' + cwd);
51         } else {
52             grunt.fail.fatal('Setting root to ' + root + ' failed - path does not exist');
53         }
54     }
56     var inAMD = path.basename(cwd) == 'amd';
58     // Globbing pattern for matching all AMD JS source files.
59     var amdSrc = [inAMD ? cwd + '/src/*.js' : '**/amd/src/*.js'];
61     /**
62      * Function to generate the destination for the uglify task
63      * (e.g. build/file.min.js). This function will be passed to
64      * the rename property of files array when building dynamically:
65      * http://gruntjs.com/configuring-tasks#building-the-files-object-dynamically
66      *
67      * @param {String} destPath the current destination
68      * @param {String} srcPath the  matched src path
69      * @return {String} The rewritten destination path.
70      */
71     var uglifyRename = function(destPath, srcPath) {
72         destPath = srcPath.replace('src', 'build');
73         destPath = destPath.replace('.js', '.min.js');
74         destPath = path.resolve(cwd, destPath);
75         return destPath;
76     };
78     /**
79      * Find thirdpartylibs.xml and generate an array of paths contained within
80      * them (used to generate ignore files and so on).
81      *
82      * @return {array} The list of thirdparty paths.
83      */
84     var getThirdPartyPathsFromXML = function() {
85         var thirdpartyfiles = grunt.file.expand('*/**/thirdpartylibs.xml');
86         var libs = ['node_modules/', 'vendor/'];
88         thirdpartyfiles.forEach(function(file) {
89           var dirname = path.dirname(file);
91           var doc = new DOMParser().parseFromString(grunt.file.read(file));
92           var nodes = xpath.select("/libraries/library/location/text()", doc);
94           nodes.forEach(function(node) {
95             var lib = path.join(dirname, node.toString());
96             if (grunt.file.isDir(lib)) {
97                 // Ensure trailing slash on dirs.
98                 lib = lib.replace(/\/?$/, '/');
99             }
101             // Look for duplicate paths before adding to array.
102             if (libs.indexOf(lib) === -1) {
103                 libs.push(lib);
104             }
105           });
106         });
107         return libs;
108     };
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: {src: amdSrc},
117             // Check YUI module source files.
118             yui: {src: ['**/yui/src/**/*.js', '!*/**/yui/src/*/meta/*.js']}
119         },
120         uglify: {
121             amd: {
122                 files: [{
123                     expand: true,
124                     src: amdSrc,
125                     rename: uglifyRename
126                 }],
127                 options: {report: 'none'}
128             }
129         },
130         sass: {
131             dist: {
132                 files: {
133                     "theme/boost/style/moodle.css": "theme/boost/scss/preset/default.scss",
134                     "theme/classic/style/moodle.css": "theme/classic/scss/classicgrunt.scss"
135                 }
136             },
137             options: {
138                 includePaths: ["theme/boost/scss/", "theme/classic/scss/"]
139             }
140         },
141         watch: {
142             options: {
143                 nospawn: true // We need not to spawn so config can be changed dynamically.
144             },
145             amd: {
146                 files: ['**/amd/src/**/*.js'],
147                 tasks: ['amd']
148             },
149             yui: {
150                 files: ['**/yui/src/**/*.js'],
151                 tasks: ['yui']
152             },
153             gherkinlint: {
154                 files: ['**/tests/behat/*.feature'],
155                 tasks: ['gherkinlint']
156             }
157         },
158         shifter: {
159             options: {
160                 recursive: true,
161                 paths: [cwd]
162             }
163         },
164         gherkinlint: {
165             options: {
166                 files: ['**/tests/behat/*.feature'],
167             }
168         },
169         stylelint: {
170             scss: {
171                 options: {syntax: 'scss'},
172                 src: ['*/**/*.scss']
173             },
174             css: {
175                 src: ['*/**/*.css'],
176                 options: {
177                     configOverrides: {
178                         rules: {
179                             // These rules have to be disabled in .stylelintrc for scss compat.
180                             "at-rule-no-unknown": true,
181                         }
182                     }
183                 }
184             }
185         }
186     });
188     /**
189      * Generate ignore files (utilising thirdpartylibs.xml data)
190      */
191     tasks.ignorefiles = function() {
192       // An array of paths to third party directories.
193       var thirdPartyPaths = getThirdPartyPathsFromXML();
194       // Generate .eslintignore.
195       var eslintIgnores = ['# Generated by "grunt ignorefiles"', '*/**/yui/src/*/meta/', '*/**/build/'].concat(thirdPartyPaths);
196       grunt.file.write('.eslintignore', eslintIgnores.join('\n'));
197       // Generate .stylelintignore.
198       var stylelintIgnores = [
199           '# Generated by "grunt ignorefiles"',
200           '**/yui/build/*',
201           'theme/boost/style/moodle.css',
202           'theme/classic/style/moodle.css',
203       ].concat(thirdPartyPaths);
204       grunt.file.write('.stylelintignore', stylelintIgnores.join('\n'));
205     };
207     /**
208      * Shifter task. Is configured with a path to a specific file or a directory,
209      * in the case of a specific file it will work out the right module to be built.
210      *
211      * Note that this task runs the invidiaul shifter jobs async (becase it spawns
212      * so be careful to to call done().
213      */
214     tasks.shifter = function() {
215         var done = this.async(),
216             options = grunt.config('shifter.options');
218         // Run the shifter processes one at a time to avoid confusing output.
219         async.eachSeries(options.paths, function(src, filedone) {
220             var args = [];
221             args.push(path.normalize(__dirname + '/node_modules/shifter/bin/shifter'));
223             // Always ignore the node_modules directory.
224             args.push('--excludes', 'node_modules');
226             // Determine the most appropriate options to run with based upon the current location.
227             if (grunt.file.isMatch('**/yui/**/*.js', src)) {
228                 // When passed a JS file, build our containing module (this happen with
229                 // watch).
230                 grunt.log.debug('Shifter passed a specific JS file');
231                 src = path.dirname(path.dirname(src));
232                 options.recursive = false;
233             } else if (grunt.file.isMatch('**/yui/src', src)) {
234                 // When in a src directory --walk all modules.
235                 grunt.log.debug('In a src directory');
236                 args.push('--walk');
237                 options.recursive = false;
238             } else if (grunt.file.isMatch('**/yui/src/*', src)) {
239                 // When in module, only build our module.
240                 grunt.log.debug('In a module directory');
241                 options.recursive = false;
242             } else if (grunt.file.isMatch('**/yui/src/*/js', src)) {
243                 // When in module src, only build our module.
244                 grunt.log.debug('In a source directory');
245                 src = path.dirname(src);
246                 options.recursive = false;
247             }
249             if (grunt.option('watch')) {
250                 grunt.fail.fatal('The --watch option has been removed, please use `grunt watch` instead');
251             }
253             // Add the stderr option if appropriate
254             if (grunt.option('verbose')) {
255                 args.push('--lint-stderr');
256             }
258             if (grunt.option('no-color')) {
259                 args.push('--color=false');
260             }
262             var execShifter = function() {
264                 grunt.log.ok("Running shifter on " + src);
265                 grunt.util.spawn({
266                     cmd: "node",
267                     args: args,
268                     opts: {cwd: src, stdio: 'inherit', env: process.env}
269                 }, function(error, result, code) {
270                     if (code) {
271                         grunt.fail.fatal('Shifter failed with code: ' + code);
272                     } else {
273                         grunt.log.ok('Shifter build complete.');
274                         filedone();
275                     }
276                 });
277             };
279             // Actually run shifter.
280             if (!options.recursive) {
281                 execShifter();
282             } else {
283                 // Check that there are yui modules otherwise shifter ends with exit code 1.
284                 if (grunt.file.expand({cwd: src}, '**/yui/src/**/*.js').length > 0) {
285                     args.push('--recursive');
286                     execShifter();
287                 } else {
288                     grunt.log.ok('No YUI modules to build.');
289                     filedone();
290                 }
291             }
292         }, done);
293     };
295     tasks.gherkinlint = function() {
296         var done = this.async(),
297             options = grunt.config('gherkinlint.options');
299         var args = grunt.file.expand(options.files);
300         args.unshift(path.normalize(__dirname + '/node_modules/.bin/gherkin-lint'));
301         grunt.util.spawn({
302             cmd: 'node',
303             args: args,
304             opts: {stdio: 'inherit', env: process.env}
305         }, function(error, result, code) {
306             // Propagate the exit code.
307             done(code === 0);
308         });
309     };
311     tasks.startup = function() {
312         // Are we in a YUI directory?
313         if (path.basename(path.resolve(cwd, '../../')) == 'yui') {
314             grunt.task.run('yui');
315         // Are we in an AMD directory?
316         } else if (inAMD) {
317             grunt.task.run('amd');
318         } else {
319             // Run them all!.
320             grunt.task.run('css');
321             grunt.task.run('js');
322             grunt.task.run('gherkinlint');
323         }
324     };
326     // On watch, we dynamically modify config to build only affected files. This
327     // method is slightly complicated to deal with multiple changed files at once (copied
328     // from the grunt-contrib-watch readme).
329     var changedFiles = Object.create(null);
330     var onChange = grunt.util._.debounce(function() {
331           var files = Object.keys(changedFiles);
332           grunt.config('eslint.amd.src', files);
333           grunt.config('eslint.yui.src', files);
334           grunt.config('uglify.amd.files', [{expand: true, src: files, rename: uglifyRename}]);
335           grunt.config('shifter.options.paths', files);
336           grunt.config('gherkinlint.options.files', files);
337           changedFiles = Object.create(null);
338     }, 200);
340     grunt.event.on('watch', function(action, filepath) {
341           changedFiles[filepath] = action;
342           onChange();
343     });
345     // Register NPM tasks.
346     grunt.loadNpmTasks('grunt-contrib-uglify');
347     grunt.loadNpmTasks('grunt-contrib-watch');
348     grunt.loadNpmTasks('grunt-sass');
349     grunt.loadNpmTasks('grunt-eslint');
350     grunt.loadNpmTasks('grunt-stylelint');
352     // Register JS tasks.
353     grunt.registerTask('shifter', 'Run Shifter against the current directory', tasks.shifter);
354     grunt.registerTask('gherkinlint', 'Run gherkinlint against the current directory', tasks.gherkinlint);
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', 'sass', 'stylelint:css']);
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']);