MDL-68445 behat: Bump to 3.6.x
[moodle.git] / Gruntfile.js
blob2049748afb74441eac51c6d7435c79b70d97cab7
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             // To display warnings call: grunt eslint --show-lint-warnings
116             // To fail on warnings call: grunt eslint --max-lint-warnings=0
117             // Also --max-lint-warnings=-1 can be used to display warnings but not fail.
118             options: {
119                 quiet: (!grunt.option('show-lint-warnings')) && (typeof grunt.option('max-lint-warnings') === 'undefined'),
120                 maxWarnings: ((typeof grunt.option('max-lint-warnings') !== 'undefined') ? grunt.option('max-lint-warnings') : -1)
121             },
122             amd: {src: amdSrc},
123             // Check YUI module source files.
124             yui: {src: ['**/yui/src/**/*.js', '!*/**/yui/src/*/meta/*.js']}
125         },
126         uglify: {
127             amd: {
128                 files: [{
129                     expand: true,
130                     src: amdSrc,
131                     rename: uglifyRename
132                 }],
133                 options: {report: 'none'}
134             }
135         },
136         sass: {
137             dist: {
138                 files: {
139                     "theme/boost/style/moodle.css": "theme/boost/scss/preset/default.scss",
140                     "theme/classic/style/moodle.css": "theme/classic/scss/classicgrunt.scss"
141                 }
142             },
143             options: {
144                 includePaths: ["theme/boost/scss/", "theme/classic/scss/"]
145             }
146         },
147         watch: {
148             options: {
149                 nospawn: true // We need not to spawn so config can be changed dynamically.
150             },
151             amd: {
152                 files: ['**/amd/src/**/*.js'],
153                 tasks: ['amd']
154             },
155             yui: {
156                 files: ['**/yui/src/**/*.js'],
157                 tasks: ['yui']
158             },
159             gherkinlint: {
160                 options: {
161                     nospawn: false,
162                 },
163                 files: ['**/tests/behat/*.feature'],
164                 tasks: ['gherkinlint']
165             }
166         },
167         shifter: {
168             options: {
169                 recursive: true,
170                 paths: [cwd]
171             }
172         },
173         gherkinlint: {
174             options: {
175                 files: ['**/tests/behat/*.feature'],
176             }
177         },
178         stylelint: {
179             scss: {
180                 options: {syntax: 'scss'},
181                 src: ['*/**/*.scss']
182             },
183             css: {
184                 src: ['*/**/*.css'],
185                 options: {
186                     configOverrides: {
187                         rules: {
188                             // These rules have to be disabled in .stylelintrc for scss compat.
189                             "at-rule-no-unknown": true,
190                         }
191                     }
192                 }
193             }
194         }
195     });
197     /**
198      * Generate ignore files (utilising thirdpartylibs.xml data)
199      */
200     tasks.ignorefiles = function() {
201       // An array of paths to third party directories.
202       var thirdPartyPaths = getThirdPartyPathsFromXML();
203       // Generate .eslintignore.
204       var eslintIgnores = ['# Generated by "grunt ignorefiles"', '*/**/yui/src/*/meta/', '*/**/build/'].concat(thirdPartyPaths);
205       grunt.file.write('.eslintignore', eslintIgnores.join('\n'));
206       // Generate .stylelintignore.
207       var stylelintIgnores = [
208           '# Generated by "grunt ignorefiles"',
209           '**/yui/build/*',
210           'theme/boost/style/moodle.css',
211           'theme/classic/style/moodle.css',
212       ].concat(thirdPartyPaths);
213       grunt.file.write('.stylelintignore', stylelintIgnores.join('\n'));
214     };
216     /**
217      * Shifter task. Is configured with a path to a specific file or a directory,
218      * in the case of a specific file it will work out the right module to be built.
219      *
220      * Note that this task runs the invidiaul shifter jobs async (becase it spawns
221      * so be careful to to call done().
222      */
223     tasks.shifter = function() {
224         var done = this.async(),
225             options = grunt.config('shifter.options');
227         // Run the shifter processes one at a time to avoid confusing output.
228         async.eachSeries(options.paths, function(src, filedone) {
229             var args = [];
230             args.push(path.normalize(__dirname + '/node_modules/shifter/bin/shifter'));
232             // Always ignore the node_modules directory.
233             args.push('--excludes', 'node_modules');
235             // Determine the most appropriate options to run with based upon the current location.
236             if (grunt.file.isMatch('**/yui/**/*.js', src)) {
237                 // When passed a JS file, build our containing module (this happen with
238                 // watch).
239                 grunt.log.debug('Shifter passed a specific JS file');
240                 src = path.dirname(path.dirname(src));
241                 options.recursive = false;
242             } else if (grunt.file.isMatch('**/yui/src', src)) {
243                 // When in a src directory --walk all modules.
244                 grunt.log.debug('In a src directory');
245                 args.push('--walk');
246                 options.recursive = false;
247             } else if (grunt.file.isMatch('**/yui/src/*', src)) {
248                 // When in module, only build our module.
249                 grunt.log.debug('In a module directory');
250                 options.recursive = false;
251             } else if (grunt.file.isMatch('**/yui/src/*/js', src)) {
252                 // When in module src, only build our module.
253                 grunt.log.debug('In a source directory');
254                 src = path.dirname(src);
255                 options.recursive = false;
256             }
258             if (grunt.option('watch')) {
259                 grunt.fail.fatal('The --watch option has been removed, please use `grunt watch` instead');
260             }
262             // Add the stderr option if appropriate
263             if (grunt.option('verbose')) {
264                 args.push('--lint-stderr');
265             }
267             if (grunt.option('no-color')) {
268                 args.push('--color=false');
269             }
271             var execShifter = function() {
273                 grunt.log.ok("Running shifter on " + src);
274                 grunt.util.spawn({
275                     cmd: "node",
276                     args: args,
277                     opts: {cwd: src, stdio: 'inherit', env: process.env}
278                 }, function(error, result, code) {
279                     if (code) {
280                         grunt.fail.fatal('Shifter failed with code: ' + code);
281                     } else {
282                         grunt.log.ok('Shifter build complete.');
283                         filedone();
284                     }
285                 });
286             };
288             // Actually run shifter.
289             if (!options.recursive) {
290                 execShifter();
291             } else {
292                 // Check that there are yui modules otherwise shifter ends with exit code 1.
293                 if (grunt.file.expand({cwd: src}, '**/yui/src/**/*.js').length > 0) {
294                     args.push('--recursive');
295                     execShifter();
296                 } else {
297                     grunt.log.ok('No YUI modules to build.');
298                     filedone();
299                 }
300             }
301         }, done);
302     };
304     tasks.gherkinlint = function() {
305         const done = this.async();
306         const options = grunt.config('gherkinlint.options');
308         // Grab the gherkin-lint linter and required scaffolding.
309         const linter = require('gherkin-lint/src/linter.js');
310         const featureFinder = require('gherkin-lint/src/feature-finder.js');
311         const configParser = require('gherkin-lint/src/config-parser.js');
312         const formatter = require('gherkin-lint/src/formatters/stylish.js');
314         // Run the linter.
315         const results = linter.lint(
316             featureFinder.getFeatureFiles(grunt.file.expand(options.files)),
317             configParser.getConfiguration(configParser.defaultConfigFileName)
318         );
320         // Print the results out uncondtionally.
321         formatter.printResults(results);
323         // Report on the results.
324         // The done function takes a bool whereby a falsey statement causes the task to fail.
325         done(results.every(result => result.errors.length === 0));
326     };
328     tasks.startup = function() {
329         // Are we in a YUI directory?
330         if (path.basename(path.resolve(cwd, '../../')) == 'yui') {
331             grunt.task.run('yui');
332         // Are we in an AMD directory?
333         } else if (inAMD) {
334             grunt.task.run('amd');
335         } else {
336             // Run them all!.
337             grunt.task.run('css');
338             grunt.task.run('js');
339             grunt.task.run('gherkinlint');
340         }
341     };
343     // On watch, we dynamically modify config to build only affected files. This
344     // method is slightly complicated to deal with multiple changed files at once (copied
345     // from the grunt-contrib-watch readme).
346     var changedFiles = Object.create(null);
347     var onChange = grunt.util._.debounce(function() {
348           var files = Object.keys(changedFiles);
349           grunt.config('eslint.amd.src', files);
350           grunt.config('eslint.yui.src', files);
351           grunt.config('uglify.amd.files', [{expand: true, src: files, rename: uglifyRename}]);
352           grunt.config('shifter.options.paths', files);
353           grunt.config('gherkinlint.options.files', files);
354           changedFiles = Object.create(null);
355     }, 200);
357     grunt.event.on('watch', function(action, filepath) {
358           changedFiles[filepath] = action;
359           onChange();
360     });
362     // Register NPM tasks.
363     grunt.loadNpmTasks('grunt-contrib-uglify');
364     grunt.loadNpmTasks('grunt-contrib-watch');
365     grunt.loadNpmTasks('grunt-sass');
366     grunt.loadNpmTasks('grunt-eslint');
367     grunt.loadNpmTasks('grunt-stylelint');
369     // Register JS tasks.
370     grunt.registerTask('shifter', 'Run Shifter against the current directory', tasks.shifter);
371     grunt.registerTask('gherkinlint', 'Run gherkinlint against the current directory', tasks.gherkinlint);
372     grunt.registerTask('ignorefiles', 'Generate ignore files for linters', tasks.ignorefiles);
373     grunt.registerTask('yui', ['eslint:yui', 'shifter']);
374     grunt.registerTask('amd', ['eslint:amd', 'uglify']);
375     grunt.registerTask('js', ['amd', 'yui']);
377     // Register CSS taks.
378     grunt.registerTask('css', ['stylelint:scss', 'sass', 'stylelint:css']);
380     // Register the startup task.
381     grunt.registerTask('startup', 'Run the correct tasks for the current directory', tasks.startup);
383     // Register the default task.
384     grunt.registerTask('default', ['startup']);