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