Merge branch 'install_310_STABLE' of https://git.in.moodle.com/amosbot/moodle-install...
[moodle.git] / Gruntfile.js
blob700e531c61c0a928f4750684e5bf80ae06ddc674
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         jsdoc: {
356             dist: {
357                 options: {
358                     configure: ".grunt/jsdoc/jsdoc.conf.js",
359                 },
360             },
361         },
362         sass: {
363             dist: {
364                 files: {
365                     "theme/boost/style/moodle.css": "theme/boost/scss/preset/default.scss",
366                     "theme/classic/style/moodle.css": "theme/classic/scss/classicgrunt.scss"
367                 }
368             },
369             options: {
370                 implementation: sass,
371                 includePaths: ["theme/boost/scss/", "theme/classic/scss/"]
372             }
373         },
374         watch: {
375             options: {
376                 nospawn: true // We need not to spawn so config can be changed dynamically.
377             },
378             amd: {
379                 files: inComponent
380                     ? ['amd/src/*.js', 'amd/src/**/*.js']
381                     : ['**/amd/src/**/*.js'],
382                 tasks: ['amd']
383             },
384             boost: {
385                 files: [inComponent ? 'scss/**/*.scss' : 'theme/boost/scss/**/*.scss'],
386                 tasks: ['scss']
387             },
388             rawcss: {
389                 files: [
390                     '**/*.css',
391                 ],
392                 excludes: [
393                     '**/moodle.css',
394                     '**/editor.css',
395                 ],
396                 tasks: ['rawcss']
397             },
398             yui: {
399                 files: inComponent
400                     ? ['yui/src/*.json', 'yui/src/**/*.js']
401                     : ['**/yui/src/**/*.js'],
402                 tasks: ['yui']
403             },
404             gherkinlint: {
405                 files: [inComponent ? 'tests/behat/*.feature' : '**/tests/behat/*.feature'],
406                 tasks: ['gherkinlint']
407             }
408         },
409         shifter: {
410             options: {
411                 recursive: true,
412                 // Shifter takes a relative path.
413                 paths: files ? files : [runDir]
414             }
415         },
416         gherkinlint: {
417             options: {
418                 files: getGherkinLintTargets(),
419             }
420         },
421     });
423     /**
424      * Generate ignore files (utilising thirdpartylibs.xml data)
425      */
426     tasks.ignorefiles = function() {
427         // An array of paths to third party directories.
428         const thirdPartyPaths = getThirdPartyPathsFromXML();
429         // Generate .eslintignore.
430         const eslintIgnores = [
431             '# Generated by "grunt ignorefiles"',
432             '*/**/yui/src/*/meta/',
433             '*/**/build/',
434         ].concat(thirdPartyPaths);
435         grunt.file.write('.eslintignore', eslintIgnores.join('\n') + '\n');
437         // Generate .stylelintignore.
438         const stylelintIgnores = [
439             '# Generated by "grunt ignorefiles"',
440             '**/yui/build/*',
441             'theme/boost/style/moodle.css',
442             'theme/classic/style/moodle.css',
443         ].concat(thirdPartyPaths);
444         grunt.file.write('.stylelintignore', stylelintIgnores.join('\n') + '\n');
445     };
447     /**
448      * Shifter task. Is configured with a path to a specific file or a directory,
449      * in the case of a specific file it will work out the right module to be built.
450      *
451      * Note that this task runs the invidiaul shifter jobs async (becase it spawns
452      * so be careful to to call done().
453      */
454     tasks.shifter = function() {
455         var done = this.async(),
456             options = grunt.config('shifter.options');
458         // Run the shifter processes one at a time to avoid confusing output.
459         async.eachSeries(options.paths, function(src, filedone) {
460             var args = [];
461             args.push(path.normalize(__dirname + '/node_modules/shifter/bin/shifter'));
463             // Always ignore the node_modules directory.
464             args.push('--excludes', 'node_modules');
466             // Determine the most appropriate options to run with based upon the current location.
467             if (grunt.file.isMatch('**/yui/**/*.js', src)) {
468                 // When passed a JS file, build our containing module (this happen with
469                 // watch).
470                 grunt.log.debug('Shifter passed a specific JS file');
471                 src = path.dirname(path.dirname(src));
472                 options.recursive = false;
473             } else if (grunt.file.isMatch('**/yui/src', src)) {
474                 // When in a src directory --walk all modules.
475                 grunt.log.debug('In a src directory');
476                 args.push('--walk');
477                 options.recursive = false;
478             } else if (grunt.file.isMatch('**/yui/src/*', src)) {
479                 // When in module, only build our module.
480                 grunt.log.debug('In a module directory');
481                 options.recursive = false;
482             } else if (grunt.file.isMatch('**/yui/src/*/js', src)) {
483                 // When in module src, only build our module.
484                 grunt.log.debug('In a source directory');
485                 src = path.dirname(src);
486                 options.recursive = false;
487             }
489             if (grunt.option('watch')) {
490                 grunt.fail.fatal('The --watch option has been removed, please use `grunt watch` instead');
491             }
493             // Add the stderr option if appropriate
494             if (grunt.option('verbose')) {
495                 args.push('--lint-stderr');
496             }
498             if (grunt.option('no-color')) {
499                 args.push('--color=false');
500             }
502             var execShifter = function() {
504                 grunt.log.ok("Running shifter on " + src);
505                 grunt.util.spawn({
506                     cmd: "node",
507                     args: args,
508                     opts: {cwd: src, stdio: 'inherit', env: process.env}
509                 }, function(error, result, code) {
510                     if (code) {
511                         grunt.fail.fatal('Shifter failed with code: ' + code);
512                     } else {
513                         grunt.log.ok('Shifter build complete.');
514                         filedone();
515                     }
516                 });
517             };
519             // Actually run shifter.
520             if (!options.recursive) {
521                 execShifter();
522             } else {
523                 // Check that there are yui modules otherwise shifter ends with exit code 1.
524                 if (grunt.file.expand({cwd: src}, '**/yui/src/**/*.js').length > 0) {
525                     args.push('--recursive');
526                     execShifter();
527                 } else {
528                     grunt.log.ok('No YUI modules to build.');
529                     filedone();
530                 }
531             }
532         }, done);
533     };
535     tasks.gherkinlint = function() {
536         const done = this.async();
537         const options = grunt.config('gherkinlint.options');
539         // Grab the gherkin-lint linter and required scaffolding.
540         const linter = require('gherkin-lint/dist/linter.js');
541         const featureFinder = require('gherkin-lint/dist/feature-finder.js');
542         const configParser = require('gherkin-lint/dist/config-parser.js');
543         const formatter = require('gherkin-lint/dist/formatters/stylish.js');
545         // Run the linter.
546         return linter.lint(
547             featureFinder.getFeatureFiles(grunt.file.expand(options.files)),
548             configParser.getConfiguration(configParser.defaultConfigFileName)
549         )
550         .then(results => {
551             // Print the results out uncondtionally.
552             formatter.printResults(results);
554             return results;
555         })
556         .then(results => {
557             // Report on the results.
558             // The done function takes a bool whereby a falsey statement causes the task to fail.
559             return results.every(result => result.errors.length === 0);
560         })
561         .then(done); // eslint-disable-line promise/no-callback-in-promise
562     };
564     tasks.startup = function() {
565         // Are we in a YUI directory?
566         if (path.basename(path.resolve(cwd, '../../')) == 'yui') {
567             grunt.task.run('yui');
568         // Are we in an AMD directory?
569         } else if (inAMD) {
570             grunt.task.run('amd');
571         } else {
572             // Run them all!.
573             grunt.task.run('css');
574             grunt.task.run('js');
575             grunt.task.run('gherkinlint');
576         }
577     };
579     /**
580      * This is a wrapper task to handle the grunt watch command. It attempts to use
581      * Watchman to monitor for file changes, if it's installed, because it's much faster.
582      *
583      * If Watchman isn't installed then it falls back to the grunt-contrib-watch file
584      * watcher for backwards compatibility.
585      */
586     tasks.watch = function() {
587         var watchTaskDone = this.async();
588         var watchInitialised = false;
589         var watchTaskQueue = {};
590         var processingQueue = false;
592         // Grab the tasks and files that have been queued up and execute them.
593         var processWatchTaskQueue = function() {
594             if (!Object.keys(watchTaskQueue).length || processingQueue) {
595                 // If there is nothing in the queue or we're already processing then wait.
596                 return;
597             }
599             processingQueue = true;
601             // Grab all tasks currently in the queue.
602             var queueToProcess = watchTaskQueue;
603             // Reset the queue.
604             watchTaskQueue = {};
606             async.forEachSeries(
607                 Object.keys(queueToProcess),
608                 function(task, next) {
609                     var files = queueToProcess[task];
610                     var filesOption = '--files=' + files.join(',');
611                     grunt.log.ok('Running task ' + task + ' for files ' + filesOption);
613                     // Spawn the task in a child process so that it doesn't kill this one
614                     // if it failed.
615                     grunt.util.spawn(
616                         {
617                             // Spawn with the grunt bin.
618                             grunt: true,
619                             // Run from current working dir and inherit stdio from process.
620                             opts: {
621                                 cwd: fullRunDir,
622                                 stdio: 'inherit'
623                             },
624                             args: [task, filesOption]
625                         },
626                         function(err, res, code) {
627                             if (code !== 0) {
628                                 // The grunt task failed.
629                                 grunt.log.error(err);
630                             }
632                             // Move on to the next task.
633                             next();
634                         }
635                     );
636                 },
637                 function() {
638                     // No longer processing.
639                     processingQueue = false;
640                     // Once all of the tasks are done then recurse just in case more tasks
641                     // were queued while we were processing.
642                     processWatchTaskQueue();
643                 }
644             );
645         };
647         const originalWatchConfig = grunt.config.get(['watch']);
648         const watchConfig = Object.keys(originalWatchConfig).reduce(function(carry, key) {
649             if (key == 'options') {
650                 return carry;
651             }
653             const value = originalWatchConfig[key];
655             const taskNames = value.tasks;
656             const files = value.files;
657             let excludes = [];
658             if (value.excludes) {
659                 excludes = value.excludes;
660             }
662             taskNames.forEach(function(taskName) {
663                 carry[taskName] = {
664                     files,
665                     excludes,
666                 };
667             });
669             return carry;
670         }, {});
672         watchmanClient.on('error', function(error) {
673             // We have to add an error handler here and parse the error string because the
674             // example way from the docs to check if Watchman is installed doesn't actually work!!
675             // See: https://github.com/facebook/watchman/issues/509
676             if (error.message.match('Watchman was not found')) {
677                 // If watchman isn't installed then we should fallback to the other watch task.
678                 grunt.log.ok('It is recommended that you install Watchman for better performance using the "watch" command.');
680                 // Fallback to the old grunt-contrib-watch task.
681                 grunt.renameTask('watch-grunt', 'watch');
682                 grunt.task.run(['watch']);
683                 // This task is finished.
684                 watchTaskDone(0);
685             } else {
686                 grunt.log.error(error);
687                 // Fatal error.
688                 watchTaskDone(1);
689             }
690         });
692         watchmanClient.on('subscription', function(resp) {
693             if (resp.subscription !== 'grunt-watch') {
694                 return;
695             }
697             resp.files.forEach(function(file) {
698                 grunt.log.ok('File changed: ' + file.name);
700                 var fullPath = fullRunDir + '/' + file.name;
701                 Object.keys(watchConfig).forEach(function(task) {
703                     const fileGlobs = watchConfig[task].files;
704                     var match = fileGlobs.some(function(fileGlob) {
705                         return grunt.file.isMatch(`**/${fileGlob}`, fullPath);
706                     });
708                     if (match) {
709                         // If we are watching a subdirectory then the file.name will be relative
710                         // to that directory. However the grunt tasks  expect the file paths to be
711                         // relative to the Gruntfile.js location so let's normalise them before
712                         // adding them to the queue.
713                         var relativePath = fullPath.replace(gruntFilePath + '/', '');
714                         if (task in watchTaskQueue) {
715                             if (!watchTaskQueue[task].includes(relativePath)) {
716                                 watchTaskQueue[task] = watchTaskQueue[task].concat(relativePath);
717                             }
718                         } else {
719                             watchTaskQueue[task] = [relativePath];
720                         }
721                     }
722                 });
723             });
725             processWatchTaskQueue();
726         });
728         process.on('SIGINT', function() {
729             // Let the user know that they may need to manually stop the Watchman daemon if they
730             // no longer want it running.
731             if (watchInitialised) {
732                 grunt.log.ok('The Watchman daemon may still be running and may need to be stopped manually.');
733             }
735             process.exit();
736         });
738         // Initiate the watch on the current directory.
739         watchmanClient.command(['watch-project', fullRunDir], function(watchError, watchResponse) {
740             if (watchError) {
741                 grunt.log.error('Error initiating watch:', watchError);
742                 watchTaskDone(1);
743                 return;
744             }
746             if ('warning' in watchResponse) {
747                 grunt.log.error('warning: ', watchResponse.warning);
748             }
750             var watch = watchResponse.watch;
751             var relativePath = watchResponse.relative_path;
752             watchInitialised = true;
754             watchmanClient.command(['clock', watch], function(clockError, clockResponse) {
755                 if (clockError) {
756                     grunt.log.error('Failed to query clock:', clockError);
757                     watchTaskDone(1);
758                     return;
759                 }
761                 // Generate the expression query used by watchman.
762                 // Documentation is limited, but see https://facebook.github.io/watchman/docs/expr/allof.html for examples.
763                 // We generate an expression to match any value in the files list of all of our tasks, but excluding
764                 // all value in the  excludes list of that task.
765                 //
766                 // [anyof, [
767                 //      [allof, [
768                 //          [anyof, [
769                 //              ['match', validPath, 'wholename'],
770                 //              ['match', validPath, 'wholename'],
771                 //          ],
772                 //          [not,
773                 //              [anyof, [
774                 //                  ['match', invalidPath, 'wholename'],
775                 //                  ['match', invalidPath, 'wholename'],
776                 //              ],
777                 //          ],
778                 //      ],
779                 var matchWholeName = fileGlob => ['match', fileGlob, 'wholename'];
780                 var matches = Object.keys(watchConfig).map(function(task) {
781                     const matchAll = [];
782                     matchAll.push(['anyof'].concat(watchConfig[task].files.map(matchWholeName)));
784                     if (watchConfig[task].excludes.length) {
785                         matchAll.push(['not', ['anyof'].concat(watchConfig[task].excludes.map(matchWholeName))]);
786                     }
788                     return ['allof'].concat(matchAll);
789                 });
791                 matches = ['anyof'].concat(matches);
793                 var sub = {
794                     expression: matches,
795                     // Which fields we're interested in.
796                     fields: ["name", "size", "type"],
797                     // Add our time constraint.
798                     since: clockResponse.clock
799                 };
801                 if (relativePath) {
802                     /* eslint-disable camelcase */
803                     sub.relative_root = relativePath;
804                 }
806                 watchmanClient.command(['subscribe', watch, 'grunt-watch', sub], function(subscribeError) {
807                     if (subscribeError) {
808                         // Probably an error in the subscription criteria.
809                         grunt.log.error('failed to subscribe: ', subscribeError);
810                         watchTaskDone(1);
811                         return;
812                     }
814                     grunt.log.ok('Listening for changes to files in ' + fullRunDir);
815                 });
816             });
817         });
818     };
820     // On watch, we dynamically modify config to build only affected files. This
821     // method is slightly complicated to deal with multiple changed files at once (copied
822     // from the grunt-contrib-watch readme).
823     var changedFiles = Object.create(null);
824     var onChange = grunt.util._.debounce(function() {
825         var files = Object.keys(changedFiles);
826         grunt.config('eslint.amd.src', files);
827         grunt.config('eslint.yui.src', files);
828         grunt.config('shifter.options.paths', files);
829         grunt.config('gherkinlint.options.files', files);
830         grunt.config('babel.dist.files', [{expand: true, src: files, rename: babelRename}]);
831         changedFiles = Object.create(null);
832     }, 200);
834     grunt.event.on('watch', function(action, filepath) {
835         changedFiles[filepath] = action;
836         onChange();
837     });
839     // Register NPM tasks.
840     grunt.loadNpmTasks('grunt-contrib-uglify');
841     grunt.loadNpmTasks('grunt-contrib-watch');
842     grunt.loadNpmTasks('grunt-sass');
843     grunt.loadNpmTasks('grunt-eslint');
844     grunt.loadNpmTasks('grunt-stylelint');
845     grunt.loadNpmTasks('grunt-babel');
846     grunt.loadNpmTasks('grunt-jsdoc');
848     // Rename the grunt-contrib-watch "watch" task because we're going to wrap it.
849     grunt.renameTask('watch', 'watch-grunt');
851     // Register JS tasks.
852     grunt.registerTask('shifter', 'Run Shifter against the current directory', tasks.shifter);
853     grunt.registerTask('gherkinlint', 'Run gherkinlint against the current directory', tasks.gherkinlint);
854     grunt.registerTask('ignorefiles', 'Generate ignore files for linters', tasks.ignorefiles);
855     grunt.registerTask('watch', 'Run tasks on file changes', tasks.watch);
856     grunt.registerTask('yui', ['eslint:yui', 'shifter']);
857     grunt.registerTask('amd', ['ignorefiles', 'eslint:amd', 'babel']);
858     grunt.registerTask('js', ['amd', 'yui']);
860     // Register CSS tasks.
861     registerStyleLintTasks(grunt, files, fullRunDir);
863     // Register the startup task.
864     grunt.registerTask('startup', 'Run the correct tasks for the current directory', tasks.startup);
866     // Register the default task.
867     grunt.registerTask('default', ['startup']);