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 grunt.registerTask('scss', scssTasks);
129 cssTasks.push('stylelint:css');
131 grunt.registerTask('rawcss', cssTasks);
133 grunt.registerTask('css', ['scss', 'rawcss']);
137 * Grunt configuration.
139 * @param {Object} grunt
141 module.exports = function(grunt) {
142 const path = require('path');
144 const async = require('async');
145 const DOMParser = require('xmldom').DOMParser;
146 const xpath = require('xpath');
147 const semver = require('semver');
148 const watchman = require('fb-watchman');
149 const watchmanClient = new watchman.Client();
150 const fs = require('fs');
151 const ComponentList = require(path.resolve('GruntfileComponents.js'));
152 const sass = require('node-sass');
154 // Verify the node version is new enough.
155 var expected = semver.validRange(grunt.file.readJSON('package.json').engines.node);
156 var actual = semver.valid(process.version);
157 if (!semver.satisfies(actual, expected)) {
158 grunt.fail.fatal('Node version not satisfied. Require ' + expected + ', version installed: ' + actual);
161 // Detect directories:
162 // * gruntFilePath The real path on disk to this Gruntfile.js
163 // * cwd The current working directory, which can be overridden by the `root` option
164 // * relativeCwd The cwd, relative to the Gruntfile.js
165 // * componentDirectory The root directory of the component if the cwd is in a valid component
166 // * inComponent Whether the cwd is in a valid component
167 // * runDir The componentDirectory or cwd if not in a component, relative to Gruntfile.js
168 // * fullRunDir The full path to the runDir
169 const gruntFilePath = fs.realpathSync(process.cwd());
170 const cwd = getCwd(grunt);
171 const relativeCwd = path.relative(gruntFilePath, cwd);
172 const componentDirectory = ComponentList.getOwningComponentDirectory(relativeCwd);
173 const inComponent = !!componentDirectory;
174 const runDir = inComponent ? componentDirectory : relativeCwd;
175 const fullRunDir = fs.realpathSync(gruntFilePath + path.sep + runDir);
176 grunt.log.debug('============================================================================');
177 grunt.log.debug(`= Node version: ${process.versions.node}`);
178 grunt.log.debug(`= grunt version: ${grunt.package.version}`);
179 grunt.log.debug(`= process.cwd: '` + process.cwd() + `'`);
180 grunt.log.debug(`= process.env.PWD: '${process.env.PWD}'`);
181 grunt.log.debug(`= path.sep '${path.sep}'`);
182 grunt.log.debug('============================================================================');
183 grunt.log.debug(`= gruntFilePath: '${gruntFilePath}'`);
184 grunt.log.debug(`= relativeCwd: '${relativeCwd}'`);
185 grunt.log.debug(`= componentDirectory: '${componentDirectory}'`);
186 grunt.log.debug(`= inComponent: '${inComponent}'`);
187 grunt.log.debug(`= runDir: '${runDir}'`);
188 grunt.log.debug(`= fullRunDir: '${fullRunDir}'`);
189 grunt.log.debug('============================================================================');
192 grunt.log.ok(`Running tasks for component directory ${componentDirectory}`);
196 if (grunt.option('files')) {
197 // Accept a comma separated list of files to process.
198 files = grunt.option('files').split(',');
201 // If the cwd is the amd directory in the current component then it will be empty.
202 // If the cwd is a child of the component's AMD directory, the relative directory will not start with ..
203 const inAMD = !path.relative(`${componentDirectory}/amd`, cwd).startsWith('..');
205 // Globbing pattern for matching all AMD JS source files.
208 amdSrc.push(componentDirectory + "/amd/src/*.js");
209 amdSrc.push(componentDirectory + "/amd/src/**/*.js");
211 amdSrc = ComponentList.getAmdSrcGlobList();
216 yuiSrc.push(componentDirectory + "/yui/src/**/*.js");
218 yuiSrc = ComponentList.getYuiSrcGlobList(gruntFilePath + '/');
222 * Function to generate the destination for the uglify task
223 * (e.g. build/file.min.js). This function will be passed to
224 * the rename property of files array when building dynamically:
225 * http://gruntjs.com/configuring-tasks#building-the-files-object-dynamically
227 * @param {String} destPath the current destination
228 * @param {String} srcPath the matched src path
229 * @return {String} The rewritten destination path.
231 var babelRename = function(destPath, srcPath) {
232 destPath = srcPath.replace('src', 'build');
233 destPath = destPath.replace('.js', '.min.js');
238 * Find thirdpartylibs.xml and generate an array of paths contained within
239 * them (used to generate ignore files and so on).
241 * @return {array} The list of thirdparty paths.
243 var getThirdPartyPathsFromXML = function() {
244 const thirdpartyfiles = ComponentList.getThirdPartyLibsList(gruntFilePath + '/');
245 const libs = ['node_modules/', 'vendor/'];
247 thirdpartyfiles.forEach(function(file) {
248 const dirname = path.dirname(file);
250 const doc = new DOMParser().parseFromString(grunt.file.read(file));
251 const nodes = xpath.select("/libraries/library/location/text()", doc);
253 nodes.forEach(function(node) {
254 let lib = path.posix.join(dirname, node.toString());
255 if (grunt.file.isDir(lib)) {
256 // Ensure trailing slash on dirs.
257 lib = lib.replace(/\/?$/, '/');
260 // Look for duplicate paths before adding to array.
261 if (libs.indexOf(lib) === -1) {
271 * Get the list of feature files to pass to the gherkin linter.
275 const getGherkinLintTargets = () => {
277 // Specific files were requested. Only check these.
282 return [`${runDir}/tests/behat/*.feature`];
285 return ['**/tests/behat/*.feature'];
288 // Project configuration.
291 // Even though warnings dont stop the build we don't display warnings by default because
292 // at this moment we've got too many core warnings.
293 // To display warnings call: grunt eslint --show-lint-warnings
294 // To fail on warnings call: grunt eslint --max-lint-warnings=0
295 // Also --max-lint-warnings=-1 can be used to display warnings but not fail.
297 quiet: (!grunt.option('show-lint-warnings')) && (typeof grunt.option('max-lint-warnings') === 'undefined'),
298 maxWarnings: ((typeof grunt.option('max-lint-warnings') !== 'undefined') ? grunt.option('max-lint-warnings') : -1)
300 amd: {src: files ? files : amdSrc},
301 // Check YUI module source files.
302 yui: {src: files ? files : yuiSrc},
309 'transform-es2015-modules-amd-lazy',
310 'system-import-transformer',
311 // This plugin modifies the Babel transpiling for "export default"
312 // so that if it's used then only the exported value is returned
313 // by the generated AMD module.
315 // It also adds the Moodle plugin name to the AMD module definition
316 // so that it can be imported as expected in other modules.
317 path.resolve('babel-plugin-add-module-to-define.js'),
318 '@babel/plugin-syntax-dynamic-import',
319 '@babel/plugin-syntax-import-meta',
320 ['@babel/plugin-proposal-class-properties', {'loose': false}],
321 '@babel/plugin-proposal-json-strings'
325 // This minification plugin needs to be disabled because it breaks the
326 // source map generation and causes invalid source maps to be output.
330 ['@babel/preset-env', {
349 src: files ? files : amdSrc,
357 "theme/boost/style/moodle.css": "theme/boost/scss/preset/default.scss",
358 "theme/classic/style/moodle.css": "theme/classic/scss/classicgrunt.scss"
362 implementation: sass,
363 includePaths: ["theme/boost/scss/", "theme/classic/scss/"]
368 nospawn: true // We need not to spawn so config can be changed dynamically.
372 ? ['amd/src/*.js', 'amd/src/**/*.js']
373 : ['**/amd/src/**/*.js'],
377 files: [inComponent ? 'scss/**/*.scss' : 'theme/boost/scss/**/*.scss'],
392 ? ['yui/src/*.json', 'yui/src/**/*.js']
393 : ['**/yui/src/**/*.js'],
397 files: [inComponent ? 'tests/behat/*.feature' : '**/tests/behat/*.feature'],
398 tasks: ['gherkinlint']
404 // Shifter takes a relative path.
405 paths: files ? files : [runDir]
410 files: getGherkinLintTargets(),
416 * Generate ignore files (utilising thirdpartylibs.xml data)
418 tasks.ignorefiles = function() {
419 // An array of paths to third party directories.
420 const thirdPartyPaths = getThirdPartyPathsFromXML();
421 // Generate .eslintignore.
422 const eslintIgnores = [
423 '# Generated by "grunt ignorefiles"',
424 '*/**/yui/src/*/meta/',
426 ].concat(thirdPartyPaths);
427 grunt.file.write('.eslintignore', eslintIgnores.join('\n'));
429 // Generate .stylelintignore.
430 const stylelintIgnores = [
431 '# Generated by "grunt ignorefiles"',
433 'theme/boost/style/moodle.css',
434 'theme/classic/style/moodle.css',
435 ].concat(thirdPartyPaths);
436 grunt.file.write('.stylelintignore', stylelintIgnores.join('\n'));
440 * Shifter task. Is configured with a path to a specific file or a directory,
441 * in the case of a specific file it will work out the right module to be built.
443 * Note that this task runs the invidiaul shifter jobs async (becase it spawns
444 * so be careful to to call done().
446 tasks.shifter = function() {
447 var done = this.async(),
448 options = grunt.config('shifter.options');
450 // Run the shifter processes one at a time to avoid confusing output.
451 async.eachSeries(options.paths, function(src, filedone) {
453 args.push(path.normalize(__dirname + '/node_modules/shifter/bin/shifter'));
455 // Always ignore the node_modules directory.
456 args.push('--excludes', 'node_modules');
458 // Determine the most appropriate options to run with based upon the current location.
459 if (grunt.file.isMatch('**/yui/**/*.js', src)) {
460 // When passed a JS file, build our containing module (this happen with
462 grunt.log.debug('Shifter passed a specific JS file');
463 src = path.dirname(path.dirname(src));
464 options.recursive = false;
465 } else if (grunt.file.isMatch('**/yui/src', src)) {
466 // When in a src directory --walk all modules.
467 grunt.log.debug('In a src directory');
469 options.recursive = false;
470 } else if (grunt.file.isMatch('**/yui/src/*', src)) {
471 // When in module, only build our module.
472 grunt.log.debug('In a module directory');
473 options.recursive = false;
474 } else if (grunt.file.isMatch('**/yui/src/*/js', src)) {
475 // When in module src, only build our module.
476 grunt.log.debug('In a source directory');
477 src = path.dirname(src);
478 options.recursive = false;
481 if (grunt.option('watch')) {
482 grunt.fail.fatal('The --watch option has been removed, please use `grunt watch` instead');
485 // Add the stderr option if appropriate
486 if (grunt.option('verbose')) {
487 args.push('--lint-stderr');
490 if (grunt.option('no-color')) {
491 args.push('--color=false');
494 var execShifter = function() {
496 grunt.log.ok("Running shifter on " + src);
500 opts: {cwd: src, stdio: 'inherit', env: process.env}
501 }, function(error, result, code) {
503 grunt.fail.fatal('Shifter failed with code: ' + code);
505 grunt.log.ok('Shifter build complete.');
511 // Actually run shifter.
512 if (!options.recursive) {
515 // Check that there are yui modules otherwise shifter ends with exit code 1.
516 if (grunt.file.expand({cwd: src}, '**/yui/src/**/*.js').length > 0) {
517 args.push('--recursive');
520 grunt.log.ok('No YUI modules to build.');
527 tasks.gherkinlint = function() {
528 const done = this.async();
529 const options = grunt.config('gherkinlint.options');
531 // Grab the gherkin-lint linter and required scaffolding.
532 const linter = require('gherkin-lint/dist/linter.js');
533 const featureFinder = require('gherkin-lint/dist/feature-finder.js');
534 const configParser = require('gherkin-lint/dist/config-parser.js');
535 const formatter = require('gherkin-lint/dist/formatters/stylish.js');
539 featureFinder.getFeatureFiles(grunt.file.expand(options.files)),
540 configParser.getConfiguration(configParser.defaultConfigFileName)
543 // Print the results out uncondtionally.
544 formatter.printResults(results);
549 // Report on the results.
550 // The done function takes a bool whereby a falsey statement causes the task to fail.
551 return results.every(result => result.errors.length === 0);
553 .then(done); // eslint-disable-line promise/no-callback-in-promise
556 tasks.startup = function() {
557 // Are we in a YUI directory?
558 if (path.basename(path.resolve(cwd, '../../')) == 'yui') {
559 grunt.task.run('yui');
560 // Are we in an AMD directory?
562 grunt.task.run('amd');
565 grunt.task.run('css');
566 grunt.task.run('js');
567 grunt.task.run('gherkinlint');
572 * This is a wrapper task to handle the grunt watch command. It attempts to use
573 * Watchman to monitor for file changes, if it's installed, because it's much faster.
575 * If Watchman isn't installed then it falls back to the grunt-contrib-watch file
576 * watcher for backwards compatibility.
578 tasks.watch = function() {
579 var watchTaskDone = this.async();
580 var watchInitialised = false;
581 var watchTaskQueue = {};
582 var processingQueue = false;
584 // Grab the tasks and files that have been queued up and execute them.
585 var processWatchTaskQueue = function() {
586 if (!Object.keys(watchTaskQueue).length || processingQueue) {
587 // If there is nothing in the queue or we're already processing then wait.
591 processingQueue = true;
593 // Grab all tasks currently in the queue.
594 var queueToProcess = watchTaskQueue;
599 Object.keys(queueToProcess),
600 function(task, next) {
601 var files = queueToProcess[task];
602 var filesOption = '--files=' + files.join(',');
603 grunt.log.ok('Running task ' + task + ' for files ' + filesOption);
605 // Spawn the task in a child process so that it doesn't kill this one
609 // Spawn with the grunt bin.
611 // Run from current working dir and inherit stdio from process.
616 args: [task, filesOption]
618 function(err, res, code) {
620 // The grunt task failed.
621 grunt.log.error(err);
624 // Move on to the next task.
630 // No longer processing.
631 processingQueue = false;
632 // Once all of the tasks are done then recurse just in case more tasks
633 // were queued while we were processing.
634 processWatchTaskQueue();
639 const originalWatchConfig = grunt.config.get(['watch']);
640 const watchConfig = Object.keys(originalWatchConfig).reduce(function(carry, key) {
641 if (key == 'options') {
645 const value = originalWatchConfig[key];
647 const taskNames = value.tasks;
648 const files = value.files;
650 if (value.excludes) {
651 excludes = value.excludes;
654 taskNames.forEach(function(taskName) {
664 watchmanClient.on('error', function(error) {
665 // We have to add an error handler here and parse the error string because the
666 // example way from the docs to check if Watchman is installed doesn't actually work!!
667 // See: https://github.com/facebook/watchman/issues/509
668 if (error.message.match('Watchman was not found')) {
669 // If watchman isn't installed then we should fallback to the other watch task.
670 grunt.log.ok('It is recommended that you install Watchman for better performance using the "watch" command.');
672 // Fallback to the old grunt-contrib-watch task.
673 grunt.renameTask('watch-grunt', 'watch');
674 grunt.task.run(['watch']);
675 // This task is finished.
678 grunt.log.error(error);
684 watchmanClient.on('subscription', function(resp) {
685 if (resp.subscription !== 'grunt-watch') {
689 resp.files.forEach(function(file) {
690 grunt.log.ok('File changed: ' + file.name);
692 var fullPath = fullRunDir + '/' + file.name;
693 Object.keys(watchConfig).forEach(function(task) {
695 const fileGlobs = watchConfig[task].files;
696 var match = fileGlobs.some(function(fileGlob) {
697 return grunt.file.isMatch(`**/${fileGlob}`, fullPath);
701 // If we are watching a subdirectory then the file.name will be relative
702 // to that directory. However the grunt tasks expect the file paths to be
703 // relative to the Gruntfile.js location so let's normalise them before
704 // adding them to the queue.
705 var relativePath = fullPath.replace(gruntFilePath + '/', '');
706 if (task in watchTaskQueue) {
707 if (!watchTaskQueue[task].includes(relativePath)) {
708 watchTaskQueue[task] = watchTaskQueue[task].concat(relativePath);
711 watchTaskQueue[task] = [relativePath];
717 processWatchTaskQueue();
720 process.on('SIGINT', function() {
721 // Let the user know that they may need to manually stop the Watchman daemon if they
722 // no longer want it running.
723 if (watchInitialised) {
724 grunt.log.ok('The Watchman daemon may still be running and may need to be stopped manually.');
730 // Initiate the watch on the current directory.
731 watchmanClient.command(['watch-project', fullRunDir], function(watchError, watchResponse) {
733 grunt.log.error('Error initiating watch:', watchError);
738 if ('warning' in watchResponse) {
739 grunt.log.error('warning: ', watchResponse.warning);
742 var watch = watchResponse.watch;
743 var relativePath = watchResponse.relative_path;
744 watchInitialised = true;
746 watchmanClient.command(['clock', watch], function(clockError, clockResponse) {
748 grunt.log.error('Failed to query clock:', clockError);
753 // Generate the expression query used by watchman.
754 // Documentation is limited, but see https://facebook.github.io/watchman/docs/expr/allof.html for examples.
755 // We generate an expression to match any value in the files list of all of our tasks, but excluding
756 // all value in the excludes list of that task.
761 // ['match', validPath, 'wholename'],
762 // ['match', validPath, 'wholename'],
766 // ['match', invalidPath, 'wholename'],
767 // ['match', invalidPath, 'wholename'],
771 var matchWholeName = fileGlob => ['match', fileGlob, 'wholename'];
772 var matches = Object.keys(watchConfig).map(function(task) {
774 matchAll.push(['anyof'].concat(watchConfig[task].files.map(matchWholeName)));
776 if (watchConfig[task].excludes.length) {
777 matchAll.push(['not', ['anyof'].concat(watchConfig[task].excludes.map(matchWholeName))]);
780 return ['allof'].concat(matchAll);
783 matches = ['anyof'].concat(matches);
787 // Which fields we're interested in.
788 fields: ["name", "size", "type"],
789 // Add our time constraint.
790 since: clockResponse.clock
794 /* eslint-disable camelcase */
795 sub.relative_root = relativePath;
798 watchmanClient.command(['subscribe', watch, 'grunt-watch', sub], function(subscribeError) {
799 if (subscribeError) {
800 // Probably an error in the subscription criteria.
801 grunt.log.error('failed to subscribe: ', subscribeError);
806 grunt.log.ok('Listening for changes to files in ' + fullRunDir);
812 // On watch, we dynamically modify config to build only affected files. This
813 // method is slightly complicated to deal with multiple changed files at once (copied
814 // from the grunt-contrib-watch readme).
815 var changedFiles = Object.create(null);
816 var onChange = grunt.util._.debounce(function() {
817 var files = Object.keys(changedFiles);
818 grunt.config('eslint.amd.src', files);
819 grunt.config('eslint.yui.src', files);
820 grunt.config('shifter.options.paths', files);
821 grunt.config('gherkinlint.options.files', files);
822 grunt.config('babel.dist.files', [{expand: true, src: files, rename: babelRename}]);
823 changedFiles = Object.create(null);
826 grunt.event.on('watch', function(action, filepath) {
827 changedFiles[filepath] = action;
831 // Register NPM tasks.
832 grunt.loadNpmTasks('grunt-contrib-uglify');
833 grunt.loadNpmTasks('grunt-contrib-watch');
834 grunt.loadNpmTasks('grunt-sass');
835 grunt.loadNpmTasks('grunt-eslint');
836 grunt.loadNpmTasks('grunt-stylelint');
837 grunt.loadNpmTasks('grunt-babel');
839 // Rename the grunt-contrib-watch "watch" task because we're going to wrap it.
840 grunt.renameTask('watch', 'watch-grunt');
842 // Register JS tasks.
843 grunt.registerTask('shifter', 'Run Shifter against the current directory', tasks.shifter);
844 grunt.registerTask('gherkinlint', 'Run gherkinlint against the current directory', tasks.gherkinlint);
845 grunt.registerTask('ignorefiles', 'Generate ignore files for linters', tasks.ignorefiles);
846 grunt.registerTask('watch', 'Run tasks on file changes', tasks.watch);
847 grunt.registerTask('yui', ['eslint:yui', 'shifter']);
848 grunt.registerTask('amd', ['eslint:amd', 'babel']);
849 grunt.registerTask('js', ['amd', 'yui']);
851 // Register CSS tasks.
852 registerStyleLintTasks(grunt, files, fullRunDir);
854 // Register the startup task.
855 grunt.registerTask('startup', 'Run the correct tasks for the current directory', tasks.startup);
857 // Register the default task.
858 grunt.registerTask('default', ['startup']);