weekly release 3.9dev
[moodle.git] / Gruntfile.js
blobbd3918574e2996040e2d39a9cdf84398daac5768
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 /* eslint-env node */
25 /**
26  * Calculate the cwd, taking into consideration the `root` option (for Windows).
27  *
28  * @param {Object} grunt
29  * @returns {String} The current directory as best we can determine
30  */
31 const getCwd = grunt => {
32     const fs = require('fs');
33     const path = require('path');
35     let cwd = fs.realpathSync(process.env.PWD || process.cwd());
37     // Windows users can't run grunt in a subdirectory, so allow them to set
38     // the root by passing --root=path/to/dir.
39     if (grunt.option('root')) {
40         const root = grunt.option('root');
41         if (grunt.file.exists(__dirname, root)) {
42             cwd = fs.realpathSync(path.join(__dirname, root));
43             grunt.log.ok('Setting root to ' + cwd);
44         } else {
45             grunt.fail.fatal('Setting root to ' + root + ' failed - path does not exist');
46         }
47     }
49     return cwd;
52 /**
53  * Register any stylelint tasks.
54  *
55  * @param {Object} grunt
56  * @param {Array} files
57  * @param {String} fullRunDir
58  */
59 const registerStyleLintTasks = (grunt, files, fullRunDir) => {
60     const getCssConfigForFiles = files => {
61         return {
62             stylelint: {
63                 css: {
64                     // Use a fully-qualified path.
65                     src: files,
66                     options: {
67                         configOverrides: {
68                             rules: {
69                                 // These rules have to be disabled in .stylelintrc for scss compat.
70                                 "at-rule-no-unknown": true,
71                             }
72                         }
73                     }
74                 },
75             },
76         };
77     };
79     const getScssConfigForFiles = files => {
80         return {
81             stylelint: {
82                 scss: {
83                     options: {syntax: 'scss'},
84                     src: files,
85                 },
86             },
87         };
88     };
90     let hasCss = true;
91     let hasScss = true;
93     if (files) {
94         // Specific files were passed. Just set them up.
95         grunt.config.merge(getCssConfigForFiles(files));
96         grunt.config.merge(getScssConfigForFiles(files));
97     } else {
98         // The stylelint system does not handle the case where there was no file to lint.
99         // Check whether there are any files to lint in the current directory.
100         const glob = require('glob');
102         const scssSrc = [];
103         glob.sync(`${fullRunDir}/**/*.scss`).forEach(path => scssSrc.push(path));
105         if (scssSrc.length) {
106             grunt.config.merge(getScssConfigForFiles(scssSrc));
107         } else {
108             hasScss = false;
109         }
111         const cssSrc = [];
112         glob.sync(`${fullRunDir}/**/*.css`).forEach(path => cssSrc.push(path));
114         if (cssSrc.length) {
115             grunt.config.merge(getCssConfigForFiles(cssSrc));
116         } else {
117             hasCss = false;
118         }
119     }
121     const scssTasks = ['sass'];
122     if (hasScss) {
123         scssTasks.unshift('stylelint:scss');
124     }
125     grunt.registerTask('scss', scssTasks);
127     const cssTasks = [];
128     if (hasCss) {
129         cssTasks.push('stylelint:css');
130     }
131     grunt.registerTask('rawcss', cssTasks);
133     grunt.registerTask('css', ['scss', 'rawcss']);
137  * Grunt configuration.
139  * @param {Object} grunt
140  */
141 module.exports = function(grunt) {
142     const path = require('path');
143     const tasks = {};
144     const async = require('async');
145     const DOMParser = require('xmldom').DOMParser;
146     const xpath = require('xpath');
147     const semver = require('semver');
148     const watchman = require('fb-watchman');
149     const watchmanClient = new watchman.Client();
150     const fs = require('fs');
151     const ComponentList = require(path.resolve('GruntfileComponents.js'));
153     // Verify the node version is new enough.
154     var expected = semver.validRange(grunt.file.readJSON('package.json').engines.node);
155     var actual = semver.valid(process.version);
156     if (!semver.satisfies(actual, expected)) {
157         grunt.fail.fatal('Node version not satisfied. Require ' + expected + ', version installed: ' + actual);
158     }
160     // Detect directories:
161     // * gruntFilePath          The real path on disk to this Gruntfile.js
162     // * cwd                    The current working directory, which can be overridden by the `root` option
163     // * relativeCwd            The cwd, relative to the Gruntfile.js
164     // * componentDirectory     The root directory of the component if the cwd is in a valid component
165     // * inComponent            Whether the cwd is in a valid component
166     // * runDir                 The componentDirectory or cwd if not in a component, relative to Gruntfile.js
167     // * fullRunDir             The full path to the runDir
168     const gruntFilePath = fs.realpathSync(process.cwd());
169     const cwd = getCwd(grunt);
170     const relativeCwd = path.relative(gruntFilePath, cwd);
171     const componentDirectory = ComponentList.getOwningComponentDirectory(relativeCwd);
172     const inComponent = !!componentDirectory;
173     const runDir = inComponent ? componentDirectory : relativeCwd;
174     const fullRunDir = fs.realpathSync(gruntFilePath + path.sep + runDir);
175     grunt.log.debug('============================================================================');
176     grunt.log.debug(`= Node version:        ${process.versions.node}`);
177     grunt.log.debug(`= grunt version:       ${grunt.package.version}`);
178     grunt.log.debug(`= process.cwd:         '` + process.cwd() + `'`);
179     grunt.log.debug(`= process.env.PWD:     '${process.env.PWD}'`);
180     grunt.log.debug(`= path.sep             '${path.sep}'`);
181     grunt.log.debug('============================================================================');
182     grunt.log.debug(`= gruntFilePath:       '${gruntFilePath}'`);
183     grunt.log.debug(`= relativeCwd:         '${relativeCwd}'`);
184     grunt.log.debug(`= componentDirectory:  '${componentDirectory}'`);
185     grunt.log.debug(`= inComponent:         '${inComponent}'`);
186     grunt.log.debug(`= runDir:              '${runDir}'`);
187     grunt.log.debug(`= fullRunDir:          '${fullRunDir}'`);
188     grunt.log.debug('============================================================================');
190     if (inComponent) {
191         grunt.log.ok(`Running tasks for component directory ${componentDirectory}`);
192     }
194     let files = null;
195     if (grunt.option('files')) {
196         // Accept a comma separated list of files to process.
197         files = grunt.option('files').split(',');
198     }
200     // If the cwd is the amd directory in the current component then it will be empty.
201     // If the cwd is a child of the component's AMD directory, the relative directory will not start with ..
202     const inAMD = !path.relative(`${componentDirectory}/amd`, cwd).startsWith('..');
204     // Globbing pattern for matching all AMD JS source files.
205     let amdSrc = [];
206     if (inComponent) {
207         amdSrc.push(componentDirectory + "/amd/src/*.js");
208         amdSrc.push(componentDirectory + "/amd/src/**/*.js");
209     } else {
210         amdSrc = ComponentList.getAmdSrcGlobList();
211     }
213     let yuiSrc = [];
214     if (inComponent) {
215         yuiSrc.push(componentDirectory + "/yui/src/**/*.js");
216     } else {
217         yuiSrc = ComponentList.getYuiSrcGlobList(gruntFilePath + '/');
218     }
220     /**
221      * Function to generate the destination for the uglify task
222      * (e.g. build/file.min.js). This function will be passed to
223      * the rename property of files array when building dynamically:
224      * http://gruntjs.com/configuring-tasks#building-the-files-object-dynamically
225      *
226      * @param {String} destPath the current destination
227      * @param {String} srcPath the  matched src path
228      * @return {String} The rewritten destination path.
229      */
230     var babelRename = function(destPath, srcPath) {
231         destPath = srcPath.replace('src', 'build');
232         destPath = destPath.replace('.js', '.min.js');
233         return destPath;
234     };
236     /**
237      * Find thirdpartylibs.xml and generate an array of paths contained within
238      * them (used to generate ignore files and so on).
239      *
240      * @return {array} The list of thirdparty paths.
241      */
242     var getThirdPartyPathsFromXML = function() {
243         const thirdpartyfiles = ComponentList.getThirdPartyLibsList(gruntFilePath + '/');
244         const libs = ['node_modules/', 'vendor/'];
246         thirdpartyfiles.forEach(function(file) {
247             const dirname = path.dirname(file);
249             const doc = new DOMParser().parseFromString(grunt.file.read(file));
250             const nodes = xpath.select("/libraries/library/location/text()", doc);
252             nodes.forEach(function(node) {
253                 let lib = path.posix.join(dirname, node.toString());
254                 if (grunt.file.isDir(lib)) {
255                     // Ensure trailing slash on dirs.
256                     lib = lib.replace(/\/?$/, '/');
257                 }
259                 // Look for duplicate paths before adding to array.
260                 if (libs.indexOf(lib) === -1) {
261                     libs.push(lib);
262                 }
263             });
264         });
266         return libs;
267     };
269     /**
270      * Get the list of feature files to pass to the gherkin linter.
271      *
272      * @returns {Array}
273      */
274     const getGherkinLintTargets = () => {
275         if (files) {
276             // Specific files were requested. Only check these.
277             return files;
278         }
280         if (inComponent) {
281             return [`${runDir}/tests/behat/*.feature`];
282         }
284         return ['**/tests/behat/*.feature'];
285     };
287     // Project configuration.
288     grunt.initConfig({
289         eslint: {
290             // Even though warnings dont stop the build we don't display warnings by default because
291             // at this moment we've got too many core warnings.
292             options: {quiet: !grunt.option('show-lint-warnings')},
293             amd: {src: files ? files : amdSrc},
294             // Check YUI module source files.
295             yui: {src: files ? files : yuiSrc},
296         },
297         babel: {
298             options: {
299                 sourceMaps: true,
300                 comments: false,
301                 plugins: [
302                     'transform-es2015-modules-amd-lazy',
303                     'system-import-transformer',
304                     // This plugin modifies the Babel transpiling for "export default"
305                     // so that if it's used then only the exported value is returned
306                     // by the generated AMD module.
307                     //
308                     // It also adds the Moodle plugin name to the AMD module definition
309                     // so that it can be imported as expected in other modules.
310                     path.resolve('babel-plugin-add-module-to-define.js'),
311                     '@babel/plugin-syntax-dynamic-import',
312                     '@babel/plugin-syntax-import-meta',
313                     ['@babel/plugin-proposal-class-properties', {'loose': false}],
314                     '@babel/plugin-proposal-json-strings'
315                 ],
316                 presets: [
317                     ['minify', {
318                         // This minification plugin needs to be disabled because it breaks the
319                         // source map generation and causes invalid source maps to be output.
320                         simplify: false,
321                         builtIns: false
322                     }],
323                     ['@babel/preset-env', {
324                         targets: {
325                             browsers: [
326                                 ">0.25%",
327                                 "last 2 versions",
328                                 "not ie <= 10",
329                                 "not op_mini all",
330                                 "not Opera > 0",
331                                 "not dead"
332                             ]
333                         },
334                         modules: false,
335                         useBuiltIns: false
336                     }]
337                 ]
338             },
339             dist: {
340                 files: [{
341                     expand: true,
342                     src: files ? files : amdSrc,
343                     rename: babelRename
344                 }]
345             }
346         },
347         sass: {
348             dist: {
349                 files: {
350                     "theme/boost/style/moodle.css": "theme/boost/scss/preset/default.scss",
351                     "theme/classic/style/moodle.css": "theme/classic/scss/classicgrunt.scss"
352                 }
353             },
354             options: {
355                 includePaths: ["theme/boost/scss/", "theme/classic/scss/"]
356             }
357         },
358         watch: {
359             options: {
360                 nospawn: true // We need not to spawn so config can be changed dynamically.
361             },
362             amd: {
363                 files: inComponent
364                     ? ['amd/src/*.js', 'amd/src/**/*.js']
365                     : ['**/amd/src/**/*.js'],
366                 tasks: ['amd']
367             },
368             boost: {
369                 files: [inComponent ? 'scss/**/*.scss' : 'theme/boost/scss/**/*.scss'],
370                 tasks: ['scss']
371             },
372             rawcss: {
373                 files: [
374                     '**/*.css',
375                 ],
376                 excludes: [
377                     '**/moodle.css',
378                     '**/editor.css',
379                 ],
380                 tasks: ['rawcss']
381             },
382             yui: {
383                 files: inComponent
384                     ? ['yui/src/*.json', 'yui/src/**/*.js']
385                     : ['**/yui/src/**/*.js'],
386                 tasks: ['yui']
387             },
388             gherkinlint: {
389                 files: [inComponent ? 'tests/behat/*.feature' : '**/tests/behat/*.feature'],
390                 tasks: ['gherkinlint']
391             }
392         },
393         shifter: {
394             options: {
395                 recursive: true,
396                 // Shifter takes a relative path.
397                 paths: files ? files : [runDir]
398             }
399         },
400         gherkinlint: {
401             options: {
402                 files: getGherkinLintTargets(),
403             }
404         },
405     });
407     /**
408      * Generate ignore files (utilising thirdpartylibs.xml data)
409      */
410     tasks.ignorefiles = function() {
411         // An array of paths to third party directories.
412         const thirdPartyPaths = getThirdPartyPathsFromXML();
413         // Generate .eslintignore.
414         const eslintIgnores = [
415             '# Generated by "grunt ignorefiles"',
416             '*/**/yui/src/*/meta/',
417             '*/**/build/',
418         ].concat(thirdPartyPaths);
419         grunt.file.write('.eslintignore', eslintIgnores.join('\n'));
421         // Generate .stylelintignore.
422         const stylelintIgnores = [
423             '# Generated by "grunt ignorefiles"',
424             '**/yui/build/*',
425             'theme/boost/style/moodle.css',
426             'theme/classic/style/moodle.css',
427         ].concat(thirdPartyPaths);
428         grunt.file.write('.stylelintignore', stylelintIgnores.join('\n'));
429     };
431     /**
432      * Shifter task. Is configured with a path to a specific file or a directory,
433      * in the case of a specific file it will work out the right module to be built.
434      *
435      * Note that this task runs the invidiaul shifter jobs async (becase it spawns
436      * so be careful to to call done().
437      */
438     tasks.shifter = function() {
439         var done = this.async(),
440             options = grunt.config('shifter.options');
442         // Run the shifter processes one at a time to avoid confusing output.
443         async.eachSeries(options.paths, function(src, filedone) {
444             var args = [];
445             args.push(path.normalize(__dirname + '/node_modules/shifter/bin/shifter'));
447             // Always ignore the node_modules directory.
448             args.push('--excludes', 'node_modules');
450             // Determine the most appropriate options to run with based upon the current location.
451             if (grunt.file.isMatch('**/yui/**/*.js', src)) {
452                 // When passed a JS file, build our containing module (this happen with
453                 // watch).
454                 grunt.log.debug('Shifter passed a specific JS file');
455                 src = path.dirname(path.dirname(src));
456                 options.recursive = false;
457             } else if (grunt.file.isMatch('**/yui/src', src)) {
458                 // When in a src directory --walk all modules.
459                 grunt.log.debug('In a src directory');
460                 args.push('--walk');
461                 options.recursive = false;
462             } else if (grunt.file.isMatch('**/yui/src/*', src)) {
463                 // When in module, only build our module.
464                 grunt.log.debug('In a module directory');
465                 options.recursive = false;
466             } else if (grunt.file.isMatch('**/yui/src/*/js', src)) {
467                 // When in module src, only build our module.
468                 grunt.log.debug('In a source directory');
469                 src = path.dirname(src);
470                 options.recursive = false;
471             }
473             if (grunt.option('watch')) {
474                 grunt.fail.fatal('The --watch option has been removed, please use `grunt watch` instead');
475             }
477             // Add the stderr option if appropriate
478             if (grunt.option('verbose')) {
479                 args.push('--lint-stderr');
480             }
482             if (grunt.option('no-color')) {
483                 args.push('--color=false');
484             }
486             var execShifter = function() {
488                 grunt.log.ok("Running shifter on " + src);
489                 grunt.util.spawn({
490                     cmd: "node",
491                     args: args,
492                     opts: {cwd: src, stdio: 'inherit', env: process.env}
493                 }, function(error, result, code) {
494                     if (code) {
495                         grunt.fail.fatal('Shifter failed with code: ' + code);
496                     } else {
497                         grunt.log.ok('Shifter build complete.');
498                         filedone();
499                     }
500                 });
501             };
503             // Actually run shifter.
504             if (!options.recursive) {
505                 execShifter();
506             } else {
507                 // Check that there are yui modules otherwise shifter ends with exit code 1.
508                 if (grunt.file.expand({cwd: src}, '**/yui/src/**/*.js').length > 0) {
509                     args.push('--recursive');
510                     execShifter();
511                 } else {
512                     grunt.log.ok('No YUI modules to build.');
513                     filedone();
514                 }
515             }
516         }, done);
517     };
519     tasks.gherkinlint = function() {
520         const done = this.async();
521         const options = grunt.config('gherkinlint.options');
523         // Grab the gherkin-lint linter and required scaffolding.
524         const linter = require('gherkin-lint/src/linter.js');
525         const featureFinder = require('gherkin-lint/src/feature-finder.js');
526         const configParser = require('gherkin-lint/src/config-parser.js');
527         const formatter = require('gherkin-lint/src/formatters/stylish.js');
529         // Run the linter.
530         const results = linter.lint(
531             featureFinder.getFeatureFiles(grunt.file.expand(options.files)),
532             configParser.getConfiguration(configParser.defaultConfigFileName)
533         );
535         // Print the results out uncondtionally.
536         formatter.printResults(results);
538         // Report on the results.
539         // We exit 1 if there is at least one error, otherwise we exit cleanly.
540         if (results.some(result => result.errors.length > 0)) {
541             done(1);
542         } else {
543             done(0);
544         }
545     };
547     tasks.startup = function() {
548         // Are we in a YUI directory?
549         if (path.basename(path.resolve(cwd, '../../')) == 'yui') {
550             grunt.task.run('yui');
551         // Are we in an AMD directory?
552         } else if (inAMD) {
553             grunt.task.run('amd');
554         } else {
555             // Run them all!.
556             grunt.task.run('css');
557             grunt.task.run('js');
558             grunt.task.run('gherkinlint');
559         }
560     };
562     /**
563      * This is a wrapper task to handle the grunt watch command. It attempts to use
564      * Watchman to monitor for file changes, if it's installed, because it's much faster.
565      *
566      * If Watchman isn't installed then it falls back to the grunt-contrib-watch file
567      * watcher for backwards compatibility.
568      */
569     tasks.watch = function() {
570         var watchTaskDone = this.async();
571         var watchInitialised = false;
572         var watchTaskQueue = {};
573         var processingQueue = false;
575         // Grab the tasks and files that have been queued up and execute them.
576         var processWatchTaskQueue = function() {
577             if (!Object.keys(watchTaskQueue).length || processingQueue) {
578                 // If there is nothing in the queue or we're already processing then wait.
579                 return;
580             }
582             processingQueue = true;
584             // Grab all tasks currently in the queue.
585             var queueToProcess = watchTaskQueue;
586             // Reset the queue.
587             watchTaskQueue = {};
589             async.forEachSeries(
590                 Object.keys(queueToProcess),
591                 function(task, next) {
592                     var files = queueToProcess[task];
593                     var filesOption = '--files=' + files.join(',');
594                     grunt.log.ok('Running task ' + task + ' for files ' + filesOption);
596                     // Spawn the task in a child process so that it doesn't kill this one
597                     // if it failed.
598                     grunt.util.spawn(
599                         {
600                             // Spawn with the grunt bin.
601                             grunt: true,
602                             // Run from current working dir and inherit stdio from process.
603                             opts: {
604                                 cwd: fullRunDir,
605                                 stdio: 'inherit'
606                             },
607                             args: [task, filesOption]
608                         },
609                         function(err, res, code) {
610                             if (code !== 0) {
611                                 // The grunt task failed.
612                                 grunt.log.error(err);
613                             }
615                             // Move on to the next task.
616                             next();
617                         }
618                     );
619                 },
620                 function() {
621                     // No longer processing.
622                     processingQueue = false;
623                     // Once all of the tasks are done then recurse just in case more tasks
624                     // were queued while we were processing.
625                     processWatchTaskQueue();
626                 }
627             );
628         };
630         const originalWatchConfig = grunt.config.get(['watch']);
631         const watchConfig = Object.keys(originalWatchConfig).reduce(function(carry, key) {
632             if (key == 'options') {
633                 return carry;
634             }
636             const value = originalWatchConfig[key];
638             const taskNames = value.tasks;
639             const files = value.files;
640             let excludes = [];
641             if (value.excludes) {
642                 excludes = value.excludes;
643             }
645             taskNames.forEach(function(taskName) {
646                 carry[taskName] = {
647                     files,
648                     excludes,
649                 };
650             });
652             return carry;
653         }, {});
655         watchmanClient.on('error', function(error) {
656             // We have to add an error handler here and parse the error string because the
657             // example way from the docs to check if Watchman is installed doesn't actually work!!
658             // See: https://github.com/facebook/watchman/issues/509
659             if (error.message.match('Watchman was not found')) {
660                 // If watchman isn't installed then we should fallback to the other watch task.
661                 grunt.log.ok('It is recommended that you install Watchman for better performance using the "watch" command.');
663                 // Fallback to the old grunt-contrib-watch task.
664                 grunt.renameTask('watch-grunt', 'watch');
665                 grunt.task.run(['watch']);
666                 // This task is finished.
667                 watchTaskDone(0);
668             } else {
669                 grunt.log.error(error);
670                 // Fatal error.
671                 watchTaskDone(1);
672             }
673         });
675         watchmanClient.on('subscription', function(resp) {
676             if (resp.subscription !== 'grunt-watch') {
677                 return;
678             }
680             resp.files.forEach(function(file) {
681                 grunt.log.ok('File changed: ' + file.name);
683                 var fullPath = fullRunDir + '/' + file.name;
684                 Object.keys(watchConfig).forEach(function(task) {
686                     const fileGlobs = watchConfig[task].files;
687                     var match = fileGlobs.some(function(fileGlob) {
688                         return grunt.file.isMatch(`**/${fileGlob}`, fullPath);
689                     });
691                     if (match) {
692                         // If we are watching a subdirectory then the file.name will be relative
693                         // to that directory. However the grunt tasks  expect the file paths to be
694                         // relative to the Gruntfile.js location so let's normalise them before
695                         // adding them to the queue.
696                         var relativePath = fullPath.replace(gruntFilePath + '/', '');
697                         if (task in watchTaskQueue) {
698                             if (!watchTaskQueue[task].includes(relativePath)) {
699                                 watchTaskQueue[task] = watchTaskQueue[task].concat(relativePath);
700                             }
701                         } else {
702                             watchTaskQueue[task] = [relativePath];
703                         }
704                     }
705                 });
706             });
708             processWatchTaskQueue();
709         });
711         process.on('SIGINT', function() {
712             // Let the user know that they may need to manually stop the Watchman daemon if they
713             // no longer want it running.
714             if (watchInitialised) {
715                 grunt.log.ok('The Watchman daemon may still be running and may need to be stopped manually.');
716             }
718             process.exit();
719         });
721         // Initiate the watch on the current directory.
722         watchmanClient.command(['watch-project', fullRunDir], function(watchError, watchResponse) {
723             if (watchError) {
724                 grunt.log.error('Error initiating watch:', watchError);
725                 watchTaskDone(1);
726                 return;
727             }
729             if ('warning' in watchResponse) {
730                 grunt.log.error('warning: ', watchResponse.warning);
731             }
733             var watch = watchResponse.watch;
734             var relativePath = watchResponse.relative_path;
735             watchInitialised = true;
737             watchmanClient.command(['clock', watch], function(clockError, clockResponse) {
738                 if (clockError) {
739                     grunt.log.error('Failed to query clock:', clockError);
740                     watchTaskDone(1);
741                     return;
742                 }
744                 // Generate the expression query used by watchman.
745                 // Documentation is limited, but see https://facebook.github.io/watchman/docs/expr/allof.html for examples.
746                 // We generate an expression to match any value in the files list of all of our tasks, but excluding
747                 // all value in the  excludes list of that task.
748                 //
749                 // [anyof, [
750                 //      [allof, [
751                 //          [anyof, [
752                 //              ['match', validPath, 'wholename'],
753                 //              ['match', validPath, 'wholename'],
754                 //          ],
755                 //          [not,
756                 //              [anyof, [
757                 //                  ['match', invalidPath, 'wholename'],
758                 //                  ['match', invalidPath, 'wholename'],
759                 //              ],
760                 //          ],
761                 //      ],
762                 var matchWholeName = fileGlob => ['match', fileGlob, 'wholename'];
763                 var matches = Object.keys(watchConfig).map(function(task) {
764                     const matchAll = [];
765                     matchAll.push(['anyof'].concat(watchConfig[task].files.map(matchWholeName)));
767                     if (watchConfig[task].excludes.length) {
768                         matchAll.push(['not', ['anyof'].concat(watchConfig[task].excludes.map(matchWholeName))]);
769                     }
771                     return ['allof'].concat(matchAll);
772                 });
774                 matches = ['anyof'].concat(matches);
776                 var sub = {
777                     expression: matches,
778                     // Which fields we're interested in.
779                     fields: ["name", "size", "type"],
780                     // Add our time constraint.
781                     since: clockResponse.clock
782                 };
784                 if (relativePath) {
785                     /* eslint-disable camelcase */
786                     sub.relative_root = relativePath;
787                 }
789                 watchmanClient.command(['subscribe', watch, 'grunt-watch', sub], function(subscribeError) {
790                     if (subscribeError) {
791                         // Probably an error in the subscription criteria.
792                         grunt.log.error('failed to subscribe: ', subscribeError);
793                         watchTaskDone(1);
794                         return;
795                     }
797                     grunt.log.ok('Listening for changes to files in ' + fullRunDir);
798                 });
799             });
800         });
801     };
803     // On watch, we dynamically modify config to build only affected files. This
804     // method is slightly complicated to deal with multiple changed files at once (copied
805     // from the grunt-contrib-watch readme).
806     var changedFiles = Object.create(null);
807     var onChange = grunt.util._.debounce(function() {
808         var files = Object.keys(changedFiles);
809         grunt.config('eslint.amd.src', files);
810         grunt.config('eslint.yui.src', files);
811         grunt.config('shifter.options.paths', files);
812         grunt.config('gherkinlint.options.files', files);
813         grunt.config('babel.dist.files', [{expand: true, src: files, rename: babelRename}]);
814         changedFiles = Object.create(null);
815     }, 200);
817     grunt.event.on('watch', function(action, filepath) {
818         changedFiles[filepath] = action;
819         onChange();
820     });
822     // Register NPM tasks.
823     grunt.loadNpmTasks('grunt-contrib-uglify');
824     grunt.loadNpmTasks('grunt-contrib-watch');
825     grunt.loadNpmTasks('grunt-sass');
826     grunt.loadNpmTasks('grunt-eslint');
827     grunt.loadNpmTasks('grunt-stylelint');
828     grunt.loadNpmTasks('grunt-babel');
830     // Rename the grunt-contrib-watch "watch" task because we're going to wrap it.
831     grunt.renameTask('watch', 'watch-grunt');
833     // Register JS tasks.
834     grunt.registerTask('shifter', 'Run Shifter against the current directory', tasks.shifter);
835     grunt.registerTask('gherkinlint', 'Run gherkinlint against the current directory', tasks.gherkinlint);
836     grunt.registerTask('ignorefiles', 'Generate ignore files for linters', tasks.ignorefiles);
837     grunt.registerTask('watch', 'Run tasks on file changes', tasks.watch);
838     grunt.registerTask('yui', ['eslint:yui', 'shifter']);
839     grunt.registerTask('amd', ['eslint:amd', 'babel']);
840     grunt.registerTask('js', ['amd', 'yui']);
842     // Register CSS tasks.
843     registerStyleLintTasks(grunt, files, fullRunDir);
845     // Register the startup task.
846     grunt.registerTask('startup', 'Run the correct tasks for the current directory', tasks.startup);
848     // Register the default task.
849     grunt.registerTask('default', ['startup']);