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 = path.relative(gruntFilePath, cwd);
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('============================================================================');
176 grunt.log.debug(`= Node version: ${process.versions.node}`);
177 grunt.log.debug(`= grunt version: ${grunt.package.version}`);
178 grunt.log.debug(`= process.cwd: '` + process.cwd() + `'`);
179 grunt.log.debug(`= process.env.PWD: '${process.env.PWD}'`);
180 grunt.log.debug(`= path.sep '${path.sep}'`);
181 grunt.log.debug('============================================================================');
182 grunt.log.debug(`= gruntFilePath: '${gruntFilePath}'`);
183 grunt.log.debug(`= relativeCwd: '${relativeCwd}'`);
184 grunt.log.debug(`= componentDirectory: '${componentDirectory}'`);
185 grunt.log.debug(`= inComponent: '${inComponent}'`);
186 grunt.log.debug(`= runDir: '${runDir}'`);
187 grunt.log.debug(`= fullRunDir: '${fullRunDir}'`);
188 grunt.log.debug('============================================================================');
191 grunt.log.ok(`Running tasks for component directory ${componentDirectory}`);
195 if (grunt.option('files')) {
196 // Accept a comma separated list of files to process.
197 files = grunt.option('files').split(',');
200 // If the cwd is the amd directory in the current component then it will be empty.
201 // If the cwd is a child of the component's AMD directory, the relative directory will not start with ..
202 const inAMD = !path.relative(`${componentDirectory}/amd`, cwd).startsWith('..');
204 // Globbing pattern for matching all AMD JS source files.
207 amdSrc.push(componentDirectory + "/amd/src/*.js");
208 amdSrc.push(componentDirectory + "/amd/src/**/*.js");
210 amdSrc = ComponentList.getAmdSrcGlobList();
215 yuiSrc.push(componentDirectory + "/yui/src/**/*.js");
217 yuiSrc = ComponentList.getYuiSrcGlobList(gruntFilePath + '/');
221 * Function to generate the destination for the uglify task
222 * (e.g. build/file.min.js). This function will be passed to
223 * the rename property of files array when building dynamically:
224 * http://gruntjs.com/configuring-tasks#building-the-files-object-dynamically
226 * @param {String} destPath the current destination
227 * @param {String} srcPath the matched src path
228 * @return {String} The rewritten destination path.
230 var babelRename = function(destPath, srcPath) {
231 destPath = srcPath.replace('src', 'build');
232 destPath = destPath.replace('.js', '.min.js');
237 * Find thirdpartylibs.xml and generate an array of paths contained within
238 * them (used to generate ignore files and so on).
240 * @return {array} The list of thirdparty paths.
242 var getThirdPartyPathsFromXML = function() {
243 const thirdpartyfiles = ComponentList.getThirdPartyLibsList(gruntFilePath + '/');
244 const libs = ['node_modules/', 'vendor/'];
246 thirdpartyfiles.forEach(function(file) {
247 const dirname = path.dirname(file);
249 const doc = new DOMParser().parseFromString(grunt.file.read(file));
250 const nodes = xpath.select("/libraries/library/location/text()", doc);
252 nodes.forEach(function(node) {
253 let lib = path.posix.join(dirname, node.toString());
254 if (grunt.file.isDir(lib)) {
255 // Ensure trailing slash on dirs.
256 lib = lib.replace(/\/?$/, '/');
259 // Look for duplicate paths before adding to array.
260 if (libs.indexOf(lib) === -1) {
270 * Get the list of feature files to pass to the gherkin linter.
274 const getGherkinLintTargets = () => {
276 // Specific files were requested. Only check these.
281 return [`${runDir}/tests/behat/*.feature`];
284 return ['**/tests/behat/*.feature'];
287 // Project configuration.
290 // Even though warnings dont stop the build we don't display warnings by default because
291 // at this moment we've got too many core warnings.
292 // To display warnings call: grunt eslint --show-lint-warnings
293 // To fail on warnings call: grunt eslint --max-lint-warnings=0
294 // Also --max-lint-warnings=-1 can be used to display warnings but not fail.
296 quiet: (!grunt.option('show-lint-warnings')) && (typeof grunt.option('max-lint-warnings') === 'undefined'),
297 maxWarnings: ((typeof grunt.option('max-lint-warnings') !== 'undefined') ? grunt.option('max-lint-warnings') : -1)
299 amd: {src: files ? files : amdSrc},
300 // Check YUI module source files.
301 yui: {src: files ? files : yuiSrc},
308 'transform-es2015-modules-amd-lazy',
309 'system-import-transformer',
310 // This plugin modifies the Babel transpiling for "export default"
311 // so that if it's used then only the exported value is returned
312 // by the generated AMD module.
314 // It also adds the Moodle plugin name to the AMD module definition
315 // so that it can be imported as expected in other modules.
316 path.resolve('babel-plugin-add-module-to-define.js'),
317 '@babel/plugin-syntax-dynamic-import',
318 '@babel/plugin-syntax-import-meta',
319 ['@babel/plugin-proposal-class-properties', {'loose': false}],
320 '@babel/plugin-proposal-json-strings'
324 // This minification plugin needs to be disabled because it breaks the
325 // source map generation and causes invalid source maps to be output.
329 ['@babel/preset-env', {
348 src: files ? files : amdSrc,
356 "theme/boost/style/moodle.css": "theme/boost/scss/preset/default.scss",
357 "theme/classic/style/moodle.css": "theme/classic/scss/classicgrunt.scss"
361 includePaths: ["theme/boost/scss/", "theme/classic/scss/"]
366 nospawn: true // We need not to spawn so config can be changed dynamically.
370 ? ['amd/src/*.js', 'amd/src/**/*.js']
371 : ['**/amd/src/**/*.js'],
375 files: [inComponent ? 'scss/**/*.scss' : 'theme/boost/scss/**/*.scss'],
390 ? ['yui/src/*.json', 'yui/src/**/*.js']
391 : ['**/yui/src/**/*.js'],
395 files: [inComponent ? 'tests/behat/*.feature' : '**/tests/behat/*.feature'],
396 tasks: ['gherkinlint']
402 // Shifter takes a relative path.
403 paths: files ? files : [runDir]
408 files: getGherkinLintTargets(),
414 * Generate ignore files (utilising thirdpartylibs.xml data)
416 tasks.ignorefiles = function() {
417 // An array of paths to third party directories.
418 const thirdPartyPaths = getThirdPartyPathsFromXML();
419 // Generate .eslintignore.
420 const eslintIgnores = [
421 '# Generated by "grunt ignorefiles"',
422 '*/**/yui/src/*/meta/',
424 ].concat(thirdPartyPaths);
425 grunt.file.write('.eslintignore', eslintIgnores.join('\n'));
427 // Generate .stylelintignore.
428 const stylelintIgnores = [
429 '# Generated by "grunt ignorefiles"',
431 'theme/boost/style/moodle.css',
432 'theme/classic/style/moodle.css',
433 ].concat(thirdPartyPaths);
434 grunt.file.write('.stylelintignore', stylelintIgnores.join('\n'));
438 * Shifter task. Is configured with a path to a specific file or a directory,
439 * in the case of a specific file it will work out the right module to be built.
441 * Note that this task runs the invidiaul shifter jobs async (becase it spawns
442 * so be careful to to call done().
444 tasks.shifter = function() {
445 var done = this.async(),
446 options = grunt.config('shifter.options');
448 // Run the shifter processes one at a time to avoid confusing output.
449 async.eachSeries(options.paths, function(src, filedone) {
451 args.push(path.normalize(__dirname + '/node_modules/shifter/bin/shifter'));
453 // Always ignore the node_modules directory.
454 args.push('--excludes', 'node_modules');
456 // Determine the most appropriate options to run with based upon the current location.
457 if (grunt.file.isMatch('**/yui/**/*.js', src)) {
458 // When passed a JS file, build our containing module (this happen with
460 grunt.log.debug('Shifter passed a specific JS file');
461 src = path.dirname(path.dirname(src));
462 options.recursive = false;
463 } else if (grunt.file.isMatch('**/yui/src', src)) {
464 // When in a src directory --walk all modules.
465 grunt.log.debug('In a src directory');
467 options.recursive = false;
468 } else if (grunt.file.isMatch('**/yui/src/*', src)) {
469 // When in module, only build our module.
470 grunt.log.debug('In a module directory');
471 options.recursive = false;
472 } else if (grunt.file.isMatch('**/yui/src/*/js', src)) {
473 // When in module src, only build our module.
474 grunt.log.debug('In a source directory');
475 src = path.dirname(src);
476 options.recursive = false;
479 if (grunt.option('watch')) {
480 grunt.fail.fatal('The --watch option has been removed, please use `grunt watch` instead');
483 // Add the stderr option if appropriate
484 if (grunt.option('verbose')) {
485 args.push('--lint-stderr');
488 if (grunt.option('no-color')) {
489 args.push('--color=false');
492 var execShifter = function() {
494 grunt.log.ok("Running shifter on " + src);
498 opts: {cwd: src, stdio: 'inherit', env: process.env}
499 }, function(error, result, code) {
501 grunt.fail.fatal('Shifter failed with code: ' + code);
503 grunt.log.ok('Shifter build complete.');
509 // Actually run shifter.
510 if (!options.recursive) {
513 // Check that there are yui modules otherwise shifter ends with exit code 1.
514 if (grunt.file.expand({cwd: src}, '**/yui/src/**/*.js').length > 0) {
515 args.push('--recursive');
518 grunt.log.ok('No YUI modules to build.');
525 tasks.gherkinlint = function() {
526 const done = this.async();
527 const options = grunt.config('gherkinlint.options');
529 // Grab the gherkin-lint linter and required scaffolding.
530 const linter = require('gherkin-lint/src/linter.js');
531 const featureFinder = require('gherkin-lint/src/feature-finder.js');
532 const configParser = require('gherkin-lint/src/config-parser.js');
533 const formatter = require('gherkin-lint/src/formatters/stylish.js');
536 const results = linter.lint(
537 featureFinder.getFeatureFiles(grunt.file.expand(options.files)),
538 configParser.getConfiguration(configParser.defaultConfigFileName)
541 // Print the results out uncondtionally.
542 formatter.printResults(results);
544 // Report on the results.
545 // The done function takes a bool whereby a falsey statement causes the task to fail.
546 done(results.every(result => result.errors.length === 0));
549 tasks.startup = function() {
550 // Are we in a YUI directory?
551 if (path.basename(path.resolve(cwd, '../../')) == 'yui') {
552 grunt.task.run('yui');
553 // Are we in an AMD directory?
555 grunt.task.run('amd');
558 grunt.task.run('css');
559 grunt.task.run('js');
560 grunt.task.run('gherkinlint');
565 * This is a wrapper task to handle the grunt watch command. It attempts to use
566 * Watchman to monitor for file changes, if it's installed, because it's much faster.
568 * If Watchman isn't installed then it falls back to the grunt-contrib-watch file
569 * watcher for backwards compatibility.
571 tasks.watch = function() {
572 var watchTaskDone = this.async();
573 var watchInitialised = false;
574 var watchTaskQueue = {};
575 var processingQueue = false;
577 // Grab the tasks and files that have been queued up and execute them.
578 var processWatchTaskQueue = function() {
579 if (!Object.keys(watchTaskQueue).length || processingQueue) {
580 // If there is nothing in the queue or we're already processing then wait.
584 processingQueue = true;
586 // Grab all tasks currently in the queue.
587 var queueToProcess = watchTaskQueue;
592 Object.keys(queueToProcess),
593 function(task, next) {
594 var files = queueToProcess[task];
595 var filesOption = '--files=' + files.join(',');
596 grunt.log.ok('Running task ' + task + ' for files ' + filesOption);
598 // Spawn the task in a child process so that it doesn't kill this one
602 // Spawn with the grunt bin.
604 // Run from current working dir and inherit stdio from process.
609 args: [task, filesOption]
611 function(err, res, code) {
613 // The grunt task failed.
614 grunt.log.error(err);
617 // Move on to the next task.
623 // No longer processing.
624 processingQueue = false;
625 // Once all of the tasks are done then recurse just in case more tasks
626 // were queued while we were processing.
627 processWatchTaskQueue();
632 const originalWatchConfig = grunt.config.get(['watch']);
633 const watchConfig = Object.keys(originalWatchConfig).reduce(function(carry, key) {
634 if (key == 'options') {
638 const value = originalWatchConfig[key];
640 const taskNames = value.tasks;
641 const files = value.files;
643 if (value.excludes) {
644 excludes = value.excludes;
647 taskNames.forEach(function(taskName) {
657 watchmanClient.on('error', function(error) {
658 // We have to add an error handler here and parse the error string because the
659 // example way from the docs to check if Watchman is installed doesn't actually work!!
660 // See: https://github.com/facebook/watchman/issues/509
661 if (error.message.match('Watchman was not found')) {
662 // If watchman isn't installed then we should fallback to the other watch task.
663 grunt.log.ok('It is recommended that you install Watchman for better performance using the "watch" command.');
665 // Fallback to the old grunt-contrib-watch task.
666 grunt.renameTask('watch-grunt', 'watch');
667 grunt.task.run(['watch']);
668 // This task is finished.
671 grunt.log.error(error);
677 watchmanClient.on('subscription', function(resp) {
678 if (resp.subscription !== 'grunt-watch') {
682 resp.files.forEach(function(file) {
683 grunt.log.ok('File changed: ' + file.name);
685 var fullPath = fullRunDir + '/' + file.name;
686 Object.keys(watchConfig).forEach(function(task) {
688 const fileGlobs = watchConfig[task].files;
689 var match = fileGlobs.some(function(fileGlob) {
690 return grunt.file.isMatch(`**/${fileGlob}`, fullPath);
694 // If we are watching a subdirectory then the file.name will be relative
695 // to that directory. However the grunt tasks expect the file paths to be
696 // relative to the Gruntfile.js location so let's normalise them before
697 // adding them to the queue.
698 var relativePath = fullPath.replace(gruntFilePath + '/', '');
699 if (task in watchTaskQueue) {
700 if (!watchTaskQueue[task].includes(relativePath)) {
701 watchTaskQueue[task] = watchTaskQueue[task].concat(relativePath);
704 watchTaskQueue[task] = [relativePath];
710 processWatchTaskQueue();
713 process.on('SIGINT', function() {
714 // Let the user know that they may need to manually stop the Watchman daemon if they
715 // no longer want it running.
716 if (watchInitialised) {
717 grunt.log.ok('The Watchman daemon may still be running and may need to be stopped manually.');
723 // Initiate the watch on the current directory.
724 watchmanClient.command(['watch-project', fullRunDir], function(watchError, watchResponse) {
726 grunt.log.error('Error initiating watch:', watchError);
731 if ('warning' in watchResponse) {
732 grunt.log.error('warning: ', watchResponse.warning);
735 var watch = watchResponse.watch;
736 var relativePath = watchResponse.relative_path;
737 watchInitialised = true;
739 watchmanClient.command(['clock', watch], function(clockError, clockResponse) {
741 grunt.log.error('Failed to query clock:', clockError);
746 // Generate the expression query used by watchman.
747 // Documentation is limited, but see https://facebook.github.io/watchman/docs/expr/allof.html for examples.
748 // We generate an expression to match any value in the files list of all of our tasks, but excluding
749 // all value in the excludes list of that task.
754 // ['match', validPath, 'wholename'],
755 // ['match', validPath, 'wholename'],
759 // ['match', invalidPath, 'wholename'],
760 // ['match', invalidPath, 'wholename'],
764 var matchWholeName = fileGlob => ['match', fileGlob, 'wholename'];
765 var matches = Object.keys(watchConfig).map(function(task) {
767 matchAll.push(['anyof'].concat(watchConfig[task].files.map(matchWholeName)));
769 if (watchConfig[task].excludes.length) {
770 matchAll.push(['not', ['anyof'].concat(watchConfig[task].excludes.map(matchWholeName))]);
773 return ['allof'].concat(matchAll);
776 matches = ['anyof'].concat(matches);
780 // Which fields we're interested in.
781 fields: ["name", "size", "type"],
782 // Add our time constraint.
783 since: clockResponse.clock
787 /* eslint-disable camelcase */
788 sub.relative_root = relativePath;
791 watchmanClient.command(['subscribe', watch, 'grunt-watch', sub], function(subscribeError) {
792 if (subscribeError) {
793 // Probably an error in the subscription criteria.
794 grunt.log.error('failed to subscribe: ', subscribeError);
799 grunt.log.ok('Listening for changes to files in ' + fullRunDir);
805 // On watch, we dynamically modify config to build only affected files. This
806 // method is slightly complicated to deal with multiple changed files at once (copied
807 // from the grunt-contrib-watch readme).
808 var changedFiles = Object.create(null);
809 var onChange = grunt.util._.debounce(function() {
810 var files = Object.keys(changedFiles);
811 grunt.config('eslint.amd.src', files);
812 grunt.config('eslint.yui.src', files);
813 grunt.config('shifter.options.paths', files);
814 grunt.config('gherkinlint.options.files', files);
815 grunt.config('babel.dist.files', [{expand: true, src: files, rename: babelRename}]);
816 changedFiles = Object.create(null);
819 grunt.event.on('watch', function(action, filepath) {
820 changedFiles[filepath] = action;
824 // Register NPM tasks.
825 grunt.loadNpmTasks('grunt-contrib-uglify');
826 grunt.loadNpmTasks('grunt-contrib-watch');
827 grunt.loadNpmTasks('grunt-sass');
828 grunt.loadNpmTasks('grunt-eslint');
829 grunt.loadNpmTasks('grunt-stylelint');
830 grunt.loadNpmTasks('grunt-babel');
832 // Rename the grunt-contrib-watch "watch" task because we're going to wrap it.
833 grunt.renameTask('watch', 'watch-grunt');
835 // Register JS tasks.
836 grunt.registerTask('shifter', 'Run Shifter against the current directory', tasks.shifter);
837 grunt.registerTask('gherkinlint', 'Run gherkinlint against the current directory', tasks.gherkinlint);
838 grunt.registerTask('ignorefiles', 'Generate ignore files for linters', tasks.ignorefiles);
839 grunt.registerTask('watch', 'Run tasks on file changes', tasks.watch);
840 grunt.registerTask('yui', ['eslint:yui', 'shifter']);
841 grunt.registerTask('amd', ['eslint:amd', 'babel']);
842 grunt.registerTask('js', ['amd', 'yui']);
844 // Register CSS tasks.
845 registerStyleLintTasks(grunt, files, fullRunDir);
847 // Register the startup task.
848 grunt.registerTask('startup', 'Run the correct tasks for the current directory', tasks.startup);
850 // Register the default task.
851 grunt.registerTask('default', ['startup']);