Merge branch 'MDL-68235' of git://github.com/Chocolate-lightning/moodle
[moodle.git] / Gruntfile.js
blob657bd772b6d53fc899ddf24d38dadd01894adbc9
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             // To display warnings call: grunt eslint --show-lint-warnings
293             // To fail on warnings call: grunt eslint --max-lint-warnings=0
294             // Also --max-lint-warnings=-1 can be used to display warnings but not fail.
295             options: {
296                 quiet: (!grunt.option('show-lint-warnings')) && (typeof grunt.option('max-lint-warnings') === 'undefined'),
297                 maxWarnings: ((typeof grunt.option('max-lint-warnings') !== 'undefined') ? grunt.option('max-lint-warnings') : -1)
298             },
299             amd: {src: files ? files : amdSrc},
300             // Check YUI module source files.
301             yui: {src: files ? files : yuiSrc},
302         },
303         babel: {
304             options: {
305                 sourceMaps: true,
306                 comments: false,
307                 plugins: [
308                     'transform-es2015-modules-amd-lazy',
309                     'system-import-transformer',
310                     // This plugin modifies the Babel transpiling for "export default"
311                     // so that if it's used then only the exported value is returned
312                     // by the generated AMD module.
313                     //
314                     // It also adds the Moodle plugin name to the AMD module definition
315                     // so that it can be imported as expected in other modules.
316                     path.resolve('babel-plugin-add-module-to-define.js'),
317                     '@babel/plugin-syntax-dynamic-import',
318                     '@babel/plugin-syntax-import-meta',
319                     ['@babel/plugin-proposal-class-properties', {'loose': false}],
320                     '@babel/plugin-proposal-json-strings'
321                 ],
322                 presets: [
323                     ['minify', {
324                         // This minification plugin needs to be disabled because it breaks the
325                         // source map generation and causes invalid source maps to be output.
326                         simplify: false,
327                         builtIns: false
328                     }],
329                     ['@babel/preset-env', {
330                         targets: {
331                             browsers: [
332                                 ">0.25%",
333                                 "last 2 versions",
334                                 "not ie <= 10",
335                                 "not op_mini all",
336                                 "not Opera > 0",
337                                 "not dead"
338                             ]
339                         },
340                         modules: false,
341                         useBuiltIns: false
342                     }]
343                 ]
344             },
345             dist: {
346                 files: [{
347                     expand: true,
348                     src: files ? files : amdSrc,
349                     rename: babelRename
350                 }]
351             }
352         },
353         sass: {
354             dist: {
355                 files: {
356                     "theme/boost/style/moodle.css": "theme/boost/scss/preset/default.scss",
357                     "theme/classic/style/moodle.css": "theme/classic/scss/classicgrunt.scss"
358                 }
359             },
360             options: {
361                 includePaths: ["theme/boost/scss/", "theme/classic/scss/"]
362             }
363         },
364         watch: {
365             options: {
366                 nospawn: true // We need not to spawn so config can be changed dynamically.
367             },
368             amd: {
369                 files: inComponent
370                     ? ['amd/src/*.js', 'amd/src/**/*.js']
371                     : ['**/amd/src/**/*.js'],
372                 tasks: ['amd']
373             },
374             boost: {
375                 files: [inComponent ? 'scss/**/*.scss' : 'theme/boost/scss/**/*.scss'],
376                 tasks: ['scss']
377             },
378             rawcss: {
379                 files: [
380                     '**/*.css',
381                 ],
382                 excludes: [
383                     '**/moodle.css',
384                     '**/editor.css',
385                 ],
386                 tasks: ['rawcss']
387             },
388             yui: {
389                 files: inComponent
390                     ? ['yui/src/*.json', 'yui/src/**/*.js']
391                     : ['**/yui/src/**/*.js'],
392                 tasks: ['yui']
393             },
394             gherkinlint: {
395                 files: [inComponent ? 'tests/behat/*.feature' : '**/tests/behat/*.feature'],
396                 tasks: ['gherkinlint']
397             }
398         },
399         shifter: {
400             options: {
401                 recursive: true,
402                 // Shifter takes a relative path.
403                 paths: files ? files : [runDir]
404             }
405         },
406         gherkinlint: {
407             options: {
408                 files: getGherkinLintTargets(),
409             }
410         },
411     });
413     /**
414      * Generate ignore files (utilising thirdpartylibs.xml data)
415      */
416     tasks.ignorefiles = function() {
417         // An array of paths to third party directories.
418         const thirdPartyPaths = getThirdPartyPathsFromXML();
419         // Generate .eslintignore.
420         const eslintIgnores = [
421             '# Generated by "grunt ignorefiles"',
422             '*/**/yui/src/*/meta/',
423             '*/**/build/',
424         ].concat(thirdPartyPaths);
425         grunt.file.write('.eslintignore', eslintIgnores.join('\n'));
427         // Generate .stylelintignore.
428         const stylelintIgnores = [
429             '# Generated by "grunt ignorefiles"',
430             '**/yui/build/*',
431             'theme/boost/style/moodle.css',
432             'theme/classic/style/moodle.css',
433         ].concat(thirdPartyPaths);
434         grunt.file.write('.stylelintignore', stylelintIgnores.join('\n'));
435     };
437     /**
438      * Shifter task. Is configured with a path to a specific file or a directory,
439      * in the case of a specific file it will work out the right module to be built.
440      *
441      * Note that this task runs the invidiaul shifter jobs async (becase it spawns
442      * so be careful to to call done().
443      */
444     tasks.shifter = function() {
445         var done = this.async(),
446             options = grunt.config('shifter.options');
448         // Run the shifter processes one at a time to avoid confusing output.
449         async.eachSeries(options.paths, function(src, filedone) {
450             var args = [];
451             args.push(path.normalize(__dirname + '/node_modules/shifter/bin/shifter'));
453             // Always ignore the node_modules directory.
454             args.push('--excludes', 'node_modules');
456             // Determine the most appropriate options to run with based upon the current location.
457             if (grunt.file.isMatch('**/yui/**/*.js', src)) {
458                 // When passed a JS file, build our containing module (this happen with
459                 // watch).
460                 grunt.log.debug('Shifter passed a specific JS file');
461                 src = path.dirname(path.dirname(src));
462                 options.recursive = false;
463             } else if (grunt.file.isMatch('**/yui/src', src)) {
464                 // When in a src directory --walk all modules.
465                 grunt.log.debug('In a src directory');
466                 args.push('--walk');
467                 options.recursive = false;
468             } else if (grunt.file.isMatch('**/yui/src/*', src)) {
469                 // When in module, only build our module.
470                 grunt.log.debug('In a module directory');
471                 options.recursive = false;
472             } else if (grunt.file.isMatch('**/yui/src/*/js', src)) {
473                 // When in module src, only build our module.
474                 grunt.log.debug('In a source directory');
475                 src = path.dirname(src);
476                 options.recursive = false;
477             }
479             if (grunt.option('watch')) {
480                 grunt.fail.fatal('The --watch option has been removed, please use `grunt watch` instead');
481             }
483             // Add the stderr option if appropriate
484             if (grunt.option('verbose')) {
485                 args.push('--lint-stderr');
486             }
488             if (grunt.option('no-color')) {
489                 args.push('--color=false');
490             }
492             var execShifter = function() {
494                 grunt.log.ok("Running shifter on " + src);
495                 grunt.util.spawn({
496                     cmd: "node",
497                     args: args,
498                     opts: {cwd: src, stdio: 'inherit', env: process.env}
499                 }, function(error, result, code) {
500                     if (code) {
501                         grunt.fail.fatal('Shifter failed with code: ' + code);
502                     } else {
503                         grunt.log.ok('Shifter build complete.');
504                         filedone();
505                     }
506                 });
507             };
509             // Actually run shifter.
510             if (!options.recursive) {
511                 execShifter();
512             } else {
513                 // Check that there are yui modules otherwise shifter ends with exit code 1.
514                 if (grunt.file.expand({cwd: src}, '**/yui/src/**/*.js').length > 0) {
515                     args.push('--recursive');
516                     execShifter();
517                 } else {
518                     grunt.log.ok('No YUI modules to build.');
519                     filedone();
520                 }
521             }
522         }, done);
523     };
525     tasks.gherkinlint = function() {
526         const done = this.async();
527         const options = grunt.config('gherkinlint.options');
529         // Grab the gherkin-lint linter and required scaffolding.
530         const linter = require('gherkin-lint/src/linter.js');
531         const featureFinder = require('gherkin-lint/src/feature-finder.js');
532         const configParser = require('gherkin-lint/src/config-parser.js');
533         const formatter = require('gherkin-lint/src/formatters/stylish.js');
535         // Run the linter.
536         const results = linter.lint(
537             featureFinder.getFeatureFiles(grunt.file.expand(options.files)),
538             configParser.getConfiguration(configParser.defaultConfigFileName)
539         );
541         // Print the results out uncondtionally.
542         formatter.printResults(results);
544         // Report on the results.
545         // The done function takes a bool whereby a falsey statement causes the task to fail.
546         done(results.every(result => result.errors.length === 0));
547     };
549     tasks.startup = function() {
550         // Are we in a YUI directory?
551         if (path.basename(path.resolve(cwd, '../../')) == 'yui') {
552             grunt.task.run('yui');
553         // Are we in an AMD directory?
554         } else if (inAMD) {
555             grunt.task.run('amd');
556         } else {
557             // Run them all!.
558             grunt.task.run('css');
559             grunt.task.run('js');
560             grunt.task.run('gherkinlint');
561         }
562     };
564     /**
565      * This is a wrapper task to handle the grunt watch command. It attempts to use
566      * Watchman to monitor for file changes, if it's installed, because it's much faster.
567      *
568      * If Watchman isn't installed then it falls back to the grunt-contrib-watch file
569      * watcher for backwards compatibility.
570      */
571     tasks.watch = function() {
572         var watchTaskDone = this.async();
573         var watchInitialised = false;
574         var watchTaskQueue = {};
575         var processingQueue = false;
577         // Grab the tasks and files that have been queued up and execute them.
578         var processWatchTaskQueue = function() {
579             if (!Object.keys(watchTaskQueue).length || processingQueue) {
580                 // If there is nothing in the queue or we're already processing then wait.
581                 return;
582             }
584             processingQueue = true;
586             // Grab all tasks currently in the queue.
587             var queueToProcess = watchTaskQueue;
588             // Reset the queue.
589             watchTaskQueue = {};
591             async.forEachSeries(
592                 Object.keys(queueToProcess),
593                 function(task, next) {
594                     var files = queueToProcess[task];
595                     var filesOption = '--files=' + files.join(',');
596                     grunt.log.ok('Running task ' + task + ' for files ' + filesOption);
598                     // Spawn the task in a child process so that it doesn't kill this one
599                     // if it failed.
600                     grunt.util.spawn(
601                         {
602                             // Spawn with the grunt bin.
603                             grunt: true,
604                             // Run from current working dir and inherit stdio from process.
605                             opts: {
606                                 cwd: fullRunDir,
607                                 stdio: 'inherit'
608                             },
609                             args: [task, filesOption]
610                         },
611                         function(err, res, code) {
612                             if (code !== 0) {
613                                 // The grunt task failed.
614                                 grunt.log.error(err);
615                             }
617                             // Move on to the next task.
618                             next();
619                         }
620                     );
621                 },
622                 function() {
623                     // No longer processing.
624                     processingQueue = false;
625                     // Once all of the tasks are done then recurse just in case more tasks
626                     // were queued while we were processing.
627                     processWatchTaskQueue();
628                 }
629             );
630         };
632         const originalWatchConfig = grunt.config.get(['watch']);
633         const watchConfig = Object.keys(originalWatchConfig).reduce(function(carry, key) {
634             if (key == 'options') {
635                 return carry;
636             }
638             const value = originalWatchConfig[key];
640             const taskNames = value.tasks;
641             const files = value.files;
642             let excludes = [];
643             if (value.excludes) {
644                 excludes = value.excludes;
645             }
647             taskNames.forEach(function(taskName) {
648                 carry[taskName] = {
649                     files,
650                     excludes,
651                 };
652             });
654             return carry;
655         }, {});
657         watchmanClient.on('error', function(error) {
658             // We have to add an error handler here and parse the error string because the
659             // example way from the docs to check if Watchman is installed doesn't actually work!!
660             // See: https://github.com/facebook/watchman/issues/509
661             if (error.message.match('Watchman was not found')) {
662                 // If watchman isn't installed then we should fallback to the other watch task.
663                 grunt.log.ok('It is recommended that you install Watchman for better performance using the "watch" command.');
665                 // Fallback to the old grunt-contrib-watch task.
666                 grunt.renameTask('watch-grunt', 'watch');
667                 grunt.task.run(['watch']);
668                 // This task is finished.
669                 watchTaskDone(0);
670             } else {
671                 grunt.log.error(error);
672                 // Fatal error.
673                 watchTaskDone(1);
674             }
675         });
677         watchmanClient.on('subscription', function(resp) {
678             if (resp.subscription !== 'grunt-watch') {
679                 return;
680             }
682             resp.files.forEach(function(file) {
683                 grunt.log.ok('File changed: ' + file.name);
685                 var fullPath = fullRunDir + '/' + file.name;
686                 Object.keys(watchConfig).forEach(function(task) {
688                     const fileGlobs = watchConfig[task].files;
689                     var match = fileGlobs.some(function(fileGlob) {
690                         return grunt.file.isMatch(`**/${fileGlob}`, fullPath);
691                     });
693                     if (match) {
694                         // If we are watching a subdirectory then the file.name will be relative
695                         // to that directory. However the grunt tasks  expect the file paths to be
696                         // relative to the Gruntfile.js location so let's normalise them before
697                         // adding them to the queue.
698                         var relativePath = fullPath.replace(gruntFilePath + '/', '');
699                         if (task in watchTaskQueue) {
700                             if (!watchTaskQueue[task].includes(relativePath)) {
701                                 watchTaskQueue[task] = watchTaskQueue[task].concat(relativePath);
702                             }
703                         } else {
704                             watchTaskQueue[task] = [relativePath];
705                         }
706                     }
707                 });
708             });
710             processWatchTaskQueue();
711         });
713         process.on('SIGINT', function() {
714             // Let the user know that they may need to manually stop the Watchman daemon if they
715             // no longer want it running.
716             if (watchInitialised) {
717                 grunt.log.ok('The Watchman daemon may still be running and may need to be stopped manually.');
718             }
720             process.exit();
721         });
723         // Initiate the watch on the current directory.
724         watchmanClient.command(['watch-project', fullRunDir], function(watchError, watchResponse) {
725             if (watchError) {
726                 grunt.log.error('Error initiating watch:', watchError);
727                 watchTaskDone(1);
728                 return;
729             }
731             if ('warning' in watchResponse) {
732                 grunt.log.error('warning: ', watchResponse.warning);
733             }
735             var watch = watchResponse.watch;
736             var relativePath = watchResponse.relative_path;
737             watchInitialised = true;
739             watchmanClient.command(['clock', watch], function(clockError, clockResponse) {
740                 if (clockError) {
741                     grunt.log.error('Failed to query clock:', clockError);
742                     watchTaskDone(1);
743                     return;
744                 }
746                 // Generate the expression query used by watchman.
747                 // Documentation is limited, but see https://facebook.github.io/watchman/docs/expr/allof.html for examples.
748                 // We generate an expression to match any value in the files list of all of our tasks, but excluding
749                 // all value in the  excludes list of that task.
750                 //
751                 // [anyof, [
752                 //      [allof, [
753                 //          [anyof, [
754                 //              ['match', validPath, 'wholename'],
755                 //              ['match', validPath, 'wholename'],
756                 //          ],
757                 //          [not,
758                 //              [anyof, [
759                 //                  ['match', invalidPath, 'wholename'],
760                 //                  ['match', invalidPath, 'wholename'],
761                 //              ],
762                 //          ],
763                 //      ],
764                 var matchWholeName = fileGlob => ['match', fileGlob, 'wholename'];
765                 var matches = Object.keys(watchConfig).map(function(task) {
766                     const matchAll = [];
767                     matchAll.push(['anyof'].concat(watchConfig[task].files.map(matchWholeName)));
769                     if (watchConfig[task].excludes.length) {
770                         matchAll.push(['not', ['anyof'].concat(watchConfig[task].excludes.map(matchWholeName))]);
771                     }
773                     return ['allof'].concat(matchAll);
774                 });
776                 matches = ['anyof'].concat(matches);
778                 var sub = {
779                     expression: matches,
780                     // Which fields we're interested in.
781                     fields: ["name", "size", "type"],
782                     // Add our time constraint.
783                     since: clockResponse.clock
784                 };
786                 if (relativePath) {
787                     /* eslint-disable camelcase */
788                     sub.relative_root = relativePath;
789                 }
791                 watchmanClient.command(['subscribe', watch, 'grunt-watch', sub], function(subscribeError) {
792                     if (subscribeError) {
793                         // Probably an error in the subscription criteria.
794                         grunt.log.error('failed to subscribe: ', subscribeError);
795                         watchTaskDone(1);
796                         return;
797                     }
799                     grunt.log.ok('Listening for changes to files in ' + fullRunDir);
800                 });
801             });
802         });
803     };
805     // On watch, we dynamically modify config to build only affected files. This
806     // method is slightly complicated to deal with multiple changed files at once (copied
807     // from the grunt-contrib-watch readme).
808     var changedFiles = Object.create(null);
809     var onChange = grunt.util._.debounce(function() {
810         var files = Object.keys(changedFiles);
811         grunt.config('eslint.amd.src', files);
812         grunt.config('eslint.yui.src', files);
813         grunt.config('shifter.options.paths', files);
814         grunt.config('gherkinlint.options.files', files);
815         grunt.config('babel.dist.files', [{expand: true, src: files, rename: babelRename}]);
816         changedFiles = Object.create(null);
817     }, 200);
819     grunt.event.on('watch', function(action, filepath) {
820         changedFiles[filepath] = action;
821         onChange();
822     });
824     // Register NPM tasks.
825     grunt.loadNpmTasks('grunt-contrib-uglify');
826     grunt.loadNpmTasks('grunt-contrib-watch');
827     grunt.loadNpmTasks('grunt-sass');
828     grunt.loadNpmTasks('grunt-eslint');
829     grunt.loadNpmTasks('grunt-stylelint');
830     grunt.loadNpmTasks('grunt-babel');
832     // Rename the grunt-contrib-watch "watch" task because we're going to wrap it.
833     grunt.renameTask('watch', 'watch-grunt');
835     // Register JS tasks.
836     grunt.registerTask('shifter', 'Run Shifter against the current directory', tasks.shifter);
837     grunt.registerTask('gherkinlint', 'Run gherkinlint against the current directory', tasks.gherkinlint);
838     grunt.registerTask('ignorefiles', 'Generate ignore files for linters', tasks.ignorefiles);
839     grunt.registerTask('watch', 'Run tasks on file changes', tasks.watch);
840     grunt.registerTask('yui', ['eslint:yui', 'shifter']);
841     grunt.registerTask('amd', ['eslint:amd', 'babel']);
842     grunt.registerTask('js', ['amd', 'yui']);
844     // Register CSS tasks.
845     registerStyleLintTasks(grunt, files, fullRunDir);
847     // Register the startup task.
848     grunt.registerTask('startup', 'Run the correct tasks for the current directory', tasks.startup);
850     // Register the default task.
851     grunt.registerTask('default', ['startup']);