1 // This file is part of Moodle - http://moodle.org/
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.
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 */
19 * @copyright 2014 Andrew Nicols
20 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 * Calculate the cwd, taking into consideration the `root` option (for Windows).
28 * @param {Object} grunt
29 * @returns {String} The current directory as best we can determine
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);
45 grunt.fail.fatal('Setting root to ' + root + ' failed - path does not exist');
53 * Register any stylelint tasks.
55 * @param {Object} grunt
56 * @param {Array} files
57 * @param {String} fullRunDir
59 const registerStyleLintTasks = (grunt, files, fullRunDir) => {
60 const getCssConfigForFiles = files => {
64 // Use a fully-qualified path.
69 // These rules have to be disabled in .stylelintrc for scss compat.
70 "at-rule-no-unknown": true,
79 const getScssConfigForFiles = files => {
83 options: {syntax: 'scss'},
94 // Specific files were passed. Just set them up.
95 grunt.config.merge(getCssConfigForFiles(files));
96 grunt.config.merge(getScssConfigForFiles(files));
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');
103 glob.sync(`${fullRunDir}/**/*.scss`).forEach(path => scssSrc.push(path));
105 if (scssSrc.length) {
106 grunt.config.merge(getScssConfigForFiles(scssSrc));
112 glob.sync(`${fullRunDir}/**/*.css`).forEach(path => cssSrc.push(path));
115 grunt.config.merge(getCssConfigForFiles(cssSrc));
121 const scssTasks = ['sass'];
123 scssTasks.unshift('stylelint:scss');
125 scssTasks.unshift('ignorefiles');
126 grunt.registerTask('scss', scssTasks);
128 const cssTasks = ['ignorefiles'];
130 cssTasks.push('stylelint:css');
132 grunt.registerTask('rawcss', cssTasks);
134 grunt.registerTask('css', ['scss', 'rawcss']);
138 * Grunt configuration.
140 * @param {Object} grunt
142 module.exports = function(grunt) {
143 const path = require('path');
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);
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('============================================================================');
193 grunt.log.ok(`Running tasks for component directory ${componentDirectory}`);
197 if (grunt.option('files')) {
198 // Accept a comma separated list of files to process.
199 files = grunt.option('files').split(',');
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.
209 amdSrc.push(componentDirectory + "/amd/src/*.js");
210 amdSrc.push(componentDirectory + "/amd/src/**/*.js");
212 amdSrc = ComponentList.getAmdSrcGlobList();
217 yuiSrc.push(componentDirectory + "/yui/src/**/*.js");
219 yuiSrc = ComponentList.getYuiSrcGlobList(gruntFilePath + '/');
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
228 * @param {String} destPath the current destination
229 * @param {String} srcPath the matched src path
230 * @return {String} The rewritten destination path.
232 var babelRename = function(destPath, srcPath) {
233 destPath = srcPath.replace('src', 'build');
234 destPath = destPath.replace('.js', '.min.js');
239 * Find thirdpartylibs.xml and generate an array of paths contained within
240 * them (used to generate ignore files and so on).
242 * @return {array} The list of thirdparty paths.
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(/\/?$/, '/');
261 // Look for duplicate paths before adding to array.
262 if (libs.indexOf(lib) === -1) {
272 * Get the list of feature files to pass to the gherkin linter.
276 const getGherkinLintTargets = () => {
278 // Specific files were requested. Only check these.
283 return [`${runDir}/tests/behat/*.feature`];
286 return ['**/tests/behat/*.feature'];
289 // Project configuration.
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.
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)
301 amd: {src: files ? files : amdSrc},
302 // Check YUI module source files.
303 yui: {src: files ? files : yuiSrc},
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.
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'
326 // This minification plugin needs to be disabled because it breaks the
327 // source map generation and causes invalid source maps to be output.
331 ['@babel/preset-env', {
350 src: files ? files : amdSrc,
358 "theme/boost/style/moodle.css": "theme/boost/scss/preset/default.scss",
359 "theme/classic/style/moodle.css": "theme/classic/scss/classicgrunt.scss"
363 implementation: sass,
364 includePaths: ["theme/boost/scss/", "theme/classic/scss/"]
369 nospawn: true // We need not to spawn so config can be changed dynamically.
373 ? ['amd/src/*.js', 'amd/src/**/*.js']
374 : ['**/amd/src/**/*.js'],
378 files: [inComponent ? 'scss/**/*.scss' : 'theme/boost/scss/**/*.scss'],
393 ? ['yui/src/*.json', 'yui/src/**/*.js']
394 : ['**/yui/src/**/*.js'],
398 files: [inComponent ? 'tests/behat/*.feature' : '**/tests/behat/*.feature'],
399 tasks: ['gherkinlint']
405 // Shifter takes a relative path.
406 paths: files ? files : [runDir]
411 files: getGherkinLintTargets(),
417 * Generate ignore files (utilising thirdpartylibs.xml data)
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/',
427 ].concat(thirdPartyPaths);
428 grunt.file.write('.eslintignore', eslintIgnores.join('\n') + '\n');
430 // Generate .stylelintignore.
431 const stylelintIgnores = [
432 '# Generated by "grunt ignorefiles"',
434 'theme/boost/style/moodle.css',
435 'theme/classic/style/moodle.css',
436 ].concat(thirdPartyPaths);
437 grunt.file.write('.stylelintignore', stylelintIgnores.join('\n') + '\n');
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.
444 * Note that this task runs the invidiaul shifter jobs async (becase it spawns
445 * so be careful to to call done().
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) {
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
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');
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;
482 if (grunt.option('watch')) {
483 grunt.fail.fatal('The --watch option has been removed, please use `grunt watch` instead');
486 // Add the stderr option if appropriate
487 if (grunt.option('verbose')) {
488 args.push('--lint-stderr');
491 if (grunt.option('no-color')) {
492 args.push('--color=false');
495 var execShifter = function() {
497 grunt.log.ok("Running shifter on " + src);
501 opts: {cwd: src, stdio: 'inherit', env: process.env}
502 }, function(error, result, code) {
504 grunt.fail.fatal('Shifter failed with code: ' + code);
506 grunt.log.ok('Shifter build complete.');
512 // Actually run shifter.
513 if (!options.recursive) {
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');
521 grunt.log.ok('No YUI modules to build.');
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');
540 featureFinder.getFeatureFiles(grunt.file.expand(options.files)),
541 configParser.getConfiguration(configParser.defaultConfigFileName)
544 // Print the results out uncondtionally.
545 formatter.printResults(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);
554 .then(done); // eslint-disable-line promise/no-callback-in-promise
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?
563 grunt.task.run('amd');
566 grunt.task.run('css');
567 grunt.task.run('js');
568 grunt.task.run('gherkinlint');
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.
576 * If Watchman isn't installed then it falls back to the grunt-contrib-watch file
577 * watcher for backwards compatibility.
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.
592 processingQueue = true;
594 // Grab all tasks currently in the queue.
595 var queueToProcess = watchTaskQueue;
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
610 // Spawn with the grunt bin.
612 // Run from current working dir and inherit stdio from process.
617 args: [task, filesOption]
619 function(err, res, code) {
621 // The grunt task failed.
622 grunt.log.error(err);
625 // Move on to the next task.
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();
640 const originalWatchConfig = grunt.config.get(['watch']);
641 const watchConfig = Object.keys(originalWatchConfig).reduce(function(carry, key) {
642 if (key == 'options') {
646 const value = originalWatchConfig[key];
648 const taskNames = value.tasks;
649 const files = value.files;
651 if (value.excludes) {
652 excludes = value.excludes;
655 taskNames.forEach(function(taskName) {
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.
679 grunt.log.error(error);
685 watchmanClient.on('subscription', function(resp) {
686 if (resp.subscription !== 'grunt-watch') {
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);
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);
712 watchTaskQueue[task] = [relativePath];
718 processWatchTaskQueue();
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.');
731 // Initiate the watch on the current directory.
732 watchmanClient.command(['watch-project', fullRunDir], function(watchError, watchResponse) {
734 grunt.log.error('Error initiating watch:', watchError);
739 if ('warning' in watchResponse) {
740 grunt.log.error('warning: ', watchResponse.warning);
743 var watch = watchResponse.watch;
744 var relativePath = watchResponse.relative_path;
745 watchInitialised = true;
747 watchmanClient.command(['clock', watch], function(clockError, clockResponse) {
749 grunt.log.error('Failed to query clock:', clockError);
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.
762 // ['match', validPath, 'wholename'],
763 // ['match', validPath, 'wholename'],
767 // ['match', invalidPath, 'wholename'],
768 // ['match', invalidPath, 'wholename'],
772 var matchWholeName = fileGlob => ['match', fileGlob, 'wholename'];
773 var matches = Object.keys(watchConfig).map(function(task) {
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))]);
781 return ['allof'].concat(matchAll);
784 matches = ['anyof'].concat(matches);
788 // Which fields we're interested in.
789 fields: ["name", "size", "type"],
790 // Add our time constraint.
791 since: clockResponse.clock
795 /* eslint-disable camelcase */
796 sub.relative_root = relativePath;
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);
807 grunt.log.ok('Listening for changes to files in ' + fullRunDir);
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);
827 grunt.event.on('watch', function(action, filepath) {
828 changedFiles[filepath] = action;
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']);