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'));
153 // Verify the node version is new enough.
154 var expected = semver.validRange(grunt.file.readJSON('package.json').engines.node);
155 var actual = semver.valid(process.version);
156 if (!semver.satisfies(actual, expected)) {
157 grunt.fail.fatal('Node version not satisfied. Require ' + expected + ', version installed: ' + actual);
160 // Detect directories:
161 // * gruntFilePath The real path on disk to this Gruntfile.js
162 // * cwd The current working directory, which can be overridden by the `root` option
163 // * relativeCwd The cwd, relative to the Gruntfile.js
164 // * componentDirectory The root directory of the component if the cwd is in a valid component
165 // * inComponent Whether the cwd is in a valid component
166 // * runDir The componentDirectory or cwd if not in a component, relative to Gruntfile.js
167 // * fullRunDir The full path to the runDir
168 const gruntFilePath = fs.realpathSync(process.cwd());
169 const cwd = getCwd(grunt);
170 const relativeCwd = cwd.replace(new RegExp(`${gruntFilePath}/?`), '');
171 const componentDirectory = ComponentList.getOwningComponentDirectory(relativeCwd);
172 const inComponent = !!componentDirectory;
173 const runDir = inComponent ? componentDirectory : relativeCwd;
174 const fullRunDir = fs.realpathSync(gruntFilePath + path.sep + runDir);
175 grunt.log.debug(`The cwd was detected as ${cwd} with a fullRunDir of ${fullRunDir}`);
178 grunt.log.ok(`Running tasks for component directory ${componentDirectory}`);
182 if (grunt.option('files')) {
183 // Accept a comma separated list of files to process.
184 files = grunt.option('files').split(',');
187 const inAMD = path.basename(cwd) == 'amd';
189 // Globbing pattern for matching all AMD JS source files.
192 amdSrc.push(componentDirectory + "/amd/src/*.js");
193 amdSrc.push(componentDirectory + "/amd/src/**/*.js");
195 amdSrc = ComponentList.getAmdSrcGlobList();
200 yuiSrc.push(componentDirectory + "/yui/src/**/*.js");
202 yuiSrc = ComponentList.getYuiSrcGlobList(gruntFilePath + '/');
206 * Function to generate the destination for the uglify task
207 * (e.g. build/file.min.js). This function will be passed to
208 * the rename property of files array when building dynamically:
209 * http://gruntjs.com/configuring-tasks#building-the-files-object-dynamically
211 * @param {String} destPath the current destination
212 * @param {String} srcPath the matched src path
213 * @return {String} The rewritten destination path.
215 var babelRename = function(destPath, srcPath) {
216 destPath = srcPath.replace('src', 'build');
217 destPath = destPath.replace('.js', '.min.js');
222 * Find thirdpartylibs.xml and generate an array of paths contained within
223 * them (used to generate ignore files and so on).
225 * @return {array} The list of thirdparty paths.
227 var getThirdPartyPathsFromXML = function() {
228 const thirdpartyfiles = ComponentList.getThirdPartyLibsList(gruntFilePath + '/');
229 const libs = ['node_modules/', 'vendor/'];
231 thirdpartyfiles.forEach(function(file) {
232 const dirname = path.dirname(file);
234 const doc = new DOMParser().parseFromString(grunt.file.read(file));
235 const nodes = xpath.select("/libraries/library/location/text()", doc);
237 nodes.forEach(function(node) {
238 let lib = path.join(dirname, node.toString());
239 if (grunt.file.isDir(lib)) {
240 // Ensure trailing slash on dirs.
241 lib = lib.replace(/\/?$/, '/');
244 // Look for duplicate paths before adding to array.
245 if (libs.indexOf(lib) === -1) {
254 // Project configuration.
257 // Even though warnings dont stop the build we don't display warnings by default because
258 // at this moment we've got too many core warnings.
259 options: {quiet: !grunt.option('show-lint-warnings')},
260 amd: {src: files ? files : amdSrc},
261 // Check YUI module source files.
262 yui: {src: files ? files : yuiSrc},
269 'transform-es2015-modules-amd-lazy',
270 'system-import-transformer',
271 // This plugin modifies the Babel transpiling for "export default"
272 // so that if it's used then only the exported value is returned
273 // by the generated AMD module.
275 // It also adds the Moodle plugin name to the AMD module definition
276 // so that it can be imported as expected in other modules.
277 path.resolve('babel-plugin-add-module-to-define.js'),
278 '@babel/plugin-syntax-dynamic-import',
279 '@babel/plugin-syntax-import-meta',
280 ['@babel/plugin-proposal-class-properties', {'loose': false}],
281 '@babel/plugin-proposal-json-strings'
285 // This minification plugin needs to be disabled because it breaks the
286 // source map generation and causes invalid source maps to be output.
290 ['@babel/preset-env', {
309 src: files ? files : amdSrc,
317 "theme/boost/style/moodle.css": "theme/boost/scss/preset/default.scss",
318 "theme/classic/style/moodle.css": "theme/classic/scss/classicgrunt.scss"
322 includePaths: ["theme/boost/scss/", "theme/classic/scss/"]
327 nospawn: true // We need not to spawn so config can be changed dynamically.
331 ? ['amd/src/*.js', 'amd/src/**/*.js']
332 : ['**/amd/src/**/*.js'],
336 files: [inComponent ? 'scss/**/*.scss' : 'theme/boost/scss/**/*.scss'],
351 ? ['yui/src/*.json', 'yui/src/**/*.js']
352 : ['**/yui/src/**/*.js'],
356 files: [inComponent ? 'tests/behat/*.feature' : '**/tests/behat/*.feature'],
357 tasks: ['gherkinlint']
363 // Shifter takes a relative path.
364 paths: files ? files : [runDir]
369 files: files ? files : ['**/tests/behat/*.feature'],
375 * Generate ignore files (utilising thirdpartylibs.xml data)
377 tasks.ignorefiles = function() {
378 // An array of paths to third party directories.
379 const thirdPartyPaths = getThirdPartyPathsFromXML();
380 // Generate .eslintignore.
381 const eslintIgnores = [
382 '# Generated by "grunt ignorefiles"',
383 '*/**/yui/src/*/meta/',
385 ].concat(thirdPartyPaths);
386 grunt.file.write('.eslintignore', eslintIgnores.join('\n'));
388 // Generate .stylelintignore.
389 const stylelintIgnores = [
390 '# Generated by "grunt ignorefiles"',
392 'theme/boost/style/moodle.css',
393 'theme/classic/style/moodle.css',
394 ].concat(thirdPartyPaths);
395 grunt.file.write('.stylelintignore', stylelintIgnores.join('\n'));
399 * Shifter task. Is configured with a path to a specific file or a directory,
400 * in the case of a specific file it will work out the right module to be built.
402 * Note that this task runs the invidiaul shifter jobs async (becase it spawns
403 * so be careful to to call done().
405 tasks.shifter = function() {
406 var done = this.async(),
407 options = grunt.config('shifter.options');
409 // Run the shifter processes one at a time to avoid confusing output.
410 async.eachSeries(options.paths, function(src, filedone) {
412 args.push(path.normalize(__dirname + '/node_modules/shifter/bin/shifter'));
414 // Always ignore the node_modules directory.
415 args.push('--excludes', 'node_modules');
417 // Determine the most appropriate options to run with based upon the current location.
418 if (grunt.file.isMatch('**/yui/**/*.js', src)) {
419 // When passed a JS file, build our containing module (this happen with
421 grunt.log.debug('Shifter passed a specific JS file');
422 src = path.dirname(path.dirname(src));
423 options.recursive = false;
424 } else if (grunt.file.isMatch('**/yui/src', src)) {
425 // When in a src directory --walk all modules.
426 grunt.log.debug('In a src directory');
428 options.recursive = false;
429 } else if (grunt.file.isMatch('**/yui/src/*', src)) {
430 // When in module, only build our module.
431 grunt.log.debug('In a module directory');
432 options.recursive = false;
433 } else if (grunt.file.isMatch('**/yui/src/*/js', src)) {
434 // When in module src, only build our module.
435 grunt.log.debug('In a source directory');
436 src = path.dirname(src);
437 options.recursive = false;
440 if (grunt.option('watch')) {
441 grunt.fail.fatal('The --watch option has been removed, please use `grunt watch` instead');
444 // Add the stderr option if appropriate
445 if (grunt.option('verbose')) {
446 args.push('--lint-stderr');
449 if (grunt.option('no-color')) {
450 args.push('--color=false');
453 var execShifter = function() {
455 grunt.log.ok("Running shifter on " + src);
459 opts: {cwd: src, stdio: 'inherit', env: process.env}
460 }, function(error, result, code) {
462 grunt.fail.fatal('Shifter failed with code: ' + code);
464 grunt.log.ok('Shifter build complete.');
470 // Actually run shifter.
471 if (!options.recursive) {
474 // Check that there are yui modules otherwise shifter ends with exit code 1.
475 if (grunt.file.expand({cwd: src}, '**/yui/src/**/*.js').length > 0) {
476 args.push('--recursive');
479 grunt.log.ok('No YUI modules to build.');
486 tasks.gherkinlint = function() {
487 var done = this.async(),
488 options = grunt.config('gherkinlint.options');
490 var args = grunt.file.expand(options.files);
491 args.unshift(path.normalize(__dirname + '/node_modules/.bin/gherkin-lint'));
495 opts: {stdio: 'inherit', env: process.env}
496 }, function(error, result, code) {
497 // Propagate the exit code.
502 tasks.startup = function() {
503 // Are we in a YUI directory?
504 if (path.basename(path.resolve(cwd, '../../')) == 'yui') {
505 grunt.task.run('yui');
506 // Are we in an AMD directory?
508 grunt.task.run('amd');
511 grunt.task.run('css');
512 grunt.task.run('js');
513 grunt.task.run('gherkinlint');
518 * This is a wrapper task to handle the grunt watch command. It attempts to use
519 * Watchman to monitor for file changes, if it's installed, because it's much faster.
521 * If Watchman isn't installed then it falls back to the grunt-contrib-watch file
522 * watcher for backwards compatibility.
524 tasks.watch = function() {
525 var watchTaskDone = this.async();
526 var watchInitialised = false;
527 var watchTaskQueue = {};
528 var processingQueue = false;
530 // Grab the tasks and files that have been queued up and execute them.
531 var processWatchTaskQueue = function() {
532 if (!Object.keys(watchTaskQueue).length || processingQueue) {
533 // If there is nothing in the queue or we're already processing then wait.
537 processingQueue = true;
539 // Grab all tasks currently in the queue.
540 var queueToProcess = watchTaskQueue;
545 Object.keys(queueToProcess),
546 function(task, next) {
547 var files = queueToProcess[task];
548 var filesOption = '--files=' + files.join(',');
549 grunt.log.ok('Running task ' + task + ' for files ' + filesOption);
551 // Spawn the task in a child process so that it doesn't kill this one
555 // Spawn with the grunt bin.
557 // Run from current working dir and inherit stdio from process.
562 args: [task, filesOption]
564 function(err, res, code) {
566 // The grunt task failed.
567 grunt.log.error(err);
570 // Move on to the next task.
576 // No longer processing.
577 processingQueue = false;
578 // Once all of the tasks are done then recurse just in case more tasks
579 // were queued while we were processing.
580 processWatchTaskQueue();
585 const originalWatchConfig = grunt.config.get(['watch']);
586 const watchConfig = Object.keys(originalWatchConfig).reduce(function(carry, key) {
587 if (key == 'options') {
591 const value = originalWatchConfig[key];
593 const taskNames = value.tasks;
594 const files = value.files;
596 if (value.excludes) {
597 excludes = value.excludes;
600 taskNames.forEach(function(taskName) {
610 watchmanClient.on('error', function(error) {
611 // We have to add an error handler here and parse the error string because the
612 // example way from the docs to check if Watchman is installed doesn't actually work!!
613 // See: https://github.com/facebook/watchman/issues/509
614 if (error.message.match('Watchman was not found')) {
615 // If watchman isn't installed then we should fallback to the other watch task.
616 grunt.log.ok('It is recommended that you install Watchman for better performance using the "watch" command.');
618 // Fallback to the old grunt-contrib-watch task.
619 grunt.renameTask('watch-grunt', 'watch');
620 grunt.task.run(['watch']);
621 // This task is finished.
624 grunt.log.error(error);
630 watchmanClient.on('subscription', function(resp) {
631 if (resp.subscription !== 'grunt-watch') {
635 resp.files.forEach(function(file) {
636 grunt.log.ok('File changed: ' + file.name);
638 var fullPath = fullRunDir + '/' + file.name;
639 Object.keys(watchConfig).forEach(function(task) {
641 const fileGlobs = watchConfig[task].files;
642 var match = fileGlobs.some(function(fileGlob) {
643 return grunt.file.isMatch(`**/${fileGlob}`, fullPath);
647 // If we are watching a subdirectory then the file.name will be relative
648 // to that directory. However the grunt tasks expect the file paths to be
649 // relative to the Gruntfile.js location so let's normalise them before
650 // adding them to the queue.
651 var relativePath = fullPath.replace(gruntFilePath + '/', '');
652 if (task in watchTaskQueue) {
653 if (!watchTaskQueue[task].includes(relativePath)) {
654 watchTaskQueue[task] = watchTaskQueue[task].concat(relativePath);
657 watchTaskQueue[task] = [relativePath];
663 processWatchTaskQueue();
666 process.on('SIGINT', function() {
667 // Let the user know that they may need to manually stop the Watchman daemon if they
668 // no longer want it running.
669 if (watchInitialised) {
670 grunt.log.ok('The Watchman daemon may still be running and may need to be stopped manually.');
676 // Initiate the watch on the current directory.
677 watchmanClient.command(['watch-project', fullRunDir], function(watchError, watchResponse) {
679 grunt.log.error('Error initiating watch:', watchError);
684 if ('warning' in watchResponse) {
685 grunt.log.error('warning: ', watchResponse.warning);
688 var watch = watchResponse.watch;
689 var relativePath = watchResponse.relative_path;
690 watchInitialised = true;
692 watchmanClient.command(['clock', watch], function(clockError, clockResponse) {
694 grunt.log.error('Failed to query clock:', clockError);
699 // Generate the expression query used by watchman.
700 // Documentation is limited, but see https://facebook.github.io/watchman/docs/expr/allof.html for examples.
701 // We generate an expression to match any value in the files list of all of our tasks, but excluding
702 // all value in the excludes list of that task.
707 // ['match', validPath, 'wholename'],
708 // ['match', validPath, 'wholename'],
712 // ['match', invalidPath, 'wholename'],
713 // ['match', invalidPath, 'wholename'],
717 var matchWholeName = fileGlob => ['match', fileGlob, 'wholename'];
718 var matches = Object.keys(watchConfig).map(function(task) {
720 matchAll.push(['anyof'].concat(watchConfig[task].files.map(matchWholeName)));
722 if (watchConfig[task].excludes.length) {
723 matchAll.push(['not', ['anyof'].concat(watchConfig[task].excludes.map(matchWholeName))]);
726 return ['allof'].concat(matchAll);
729 matches = ['anyof'].concat(matches);
733 // Which fields we're interested in.
734 fields: ["name", "size", "type"],
735 // Add our time constraint.
736 since: clockResponse.clock
740 /* eslint-disable camelcase */
741 sub.relative_root = relativePath;
744 watchmanClient.command(['subscribe', watch, 'grunt-watch', sub], function(subscribeError) {
745 if (subscribeError) {
746 // Probably an error in the subscription criteria.
747 grunt.log.error('failed to subscribe: ', subscribeError);
752 grunt.log.ok('Listening for changes to files in ' + fullRunDir);
758 // On watch, we dynamically modify config to build only affected files. This
759 // method is slightly complicated to deal with multiple changed files at once (copied
760 // from the grunt-contrib-watch readme).
761 var changedFiles = Object.create(null);
762 var onChange = grunt.util._.debounce(function() {
763 var files = Object.keys(changedFiles);
764 grunt.config('eslint.amd.src', files);
765 grunt.config('eslint.yui.src', files);
766 grunt.config('shifter.options.paths', files);
767 grunt.config('gherkinlint.options.files', files);
768 grunt.config('babel.dist.files', [{expand: true, src: files, rename: babelRename}]);
769 changedFiles = Object.create(null);
772 grunt.event.on('watch', function(action, filepath) {
773 changedFiles[filepath] = action;
777 // Register NPM tasks.
778 grunt.loadNpmTasks('grunt-contrib-uglify');
779 grunt.loadNpmTasks('grunt-contrib-watch');
780 grunt.loadNpmTasks('grunt-sass');
781 grunt.loadNpmTasks('grunt-eslint');
782 grunt.loadNpmTasks('grunt-stylelint');
783 grunt.loadNpmTasks('grunt-babel');
785 // Rename the grunt-contrib-watch "watch" task because we're going to wrap it.
786 grunt.renameTask('watch', 'watch-grunt');
788 // Register JS tasks.
789 grunt.registerTask('shifter', 'Run Shifter against the current directory', tasks.shifter);
790 grunt.registerTask('gherkinlint', 'Run gherkinlint against the current directory', tasks.gherkinlint);
791 grunt.registerTask('ignorefiles', 'Generate ignore files for linters', tasks.ignorefiles);
792 grunt.registerTask('watch', 'Run tasks on file changes', tasks.watch);
793 grunt.registerTask('yui', ['eslint:yui', 'shifter']);
794 grunt.registerTask('amd', ['eslint:amd', 'babel']);
795 grunt.registerTask('js', ['amd', 'yui']);
797 // Register CSS tasks.
798 registerStyleLintTasks(grunt, files, fullRunDir);
800 // Register the startup task.
801 grunt.registerTask('startup', 'Run the correct tasks for the current directory', tasks.startup);
803 // Register the default task.
804 grunt.registerTask('default', ['startup']);