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 options: {quiet: !grunt.option('show-lint-warnings')},
293 amd: {src: files ? files : amdSrc},
294 // Check YUI module source files.
295 yui: {src: files ? files : yuiSrc},
302 'transform-es2015-modules-amd-lazy',
303 'system-import-transformer',
304 // This plugin modifies the Babel transpiling for "export default"
305 // so that if it's used then only the exported value is returned
306 // by the generated AMD module.
308 // It also adds the Moodle plugin name to the AMD module definition
309 // so that it can be imported as expected in other modules.
310 path.resolve('babel-plugin-add-module-to-define.js'),
311 '@babel/plugin-syntax-dynamic-import',
312 '@babel/plugin-syntax-import-meta',
313 ['@babel/plugin-proposal-class-properties', {'loose': false}],
314 '@babel/plugin-proposal-json-strings'
318 // This minification plugin needs to be disabled because it breaks the
319 // source map generation and causes invalid source maps to be output.
323 ['@babel/preset-env', {
342 src: files ? files : amdSrc,
350 "theme/boost/style/moodle.css": "theme/boost/scss/preset/default.scss",
351 "theme/classic/style/moodle.css": "theme/classic/scss/classicgrunt.scss"
355 includePaths: ["theme/boost/scss/", "theme/classic/scss/"]
360 nospawn: true // We need not to spawn so config can be changed dynamically.
364 ? ['amd/src/*.js', 'amd/src/**/*.js']
365 : ['**/amd/src/**/*.js'],
369 files: [inComponent ? 'scss/**/*.scss' : 'theme/boost/scss/**/*.scss'],
384 ? ['yui/src/*.json', 'yui/src/**/*.js']
385 : ['**/yui/src/**/*.js'],
389 files: [inComponent ? 'tests/behat/*.feature' : '**/tests/behat/*.feature'],
390 tasks: ['gherkinlint']
396 // Shifter takes a relative path.
397 paths: files ? files : [runDir]
402 files: getGherkinLintTargets(),
408 * Generate ignore files (utilising thirdpartylibs.xml data)
410 tasks.ignorefiles = function() {
411 // An array of paths to third party directories.
412 const thirdPartyPaths = getThirdPartyPathsFromXML();
413 // Generate .eslintignore.
414 const eslintIgnores = [
415 '# Generated by "grunt ignorefiles"',
416 '*/**/yui/src/*/meta/',
418 ].concat(thirdPartyPaths);
419 grunt.file.write('.eslintignore', eslintIgnores.join('\n'));
421 // Generate .stylelintignore.
422 const stylelintIgnores = [
423 '# Generated by "grunt ignorefiles"',
425 'theme/boost/style/moodle.css',
426 'theme/classic/style/moodle.css',
427 ].concat(thirdPartyPaths);
428 grunt.file.write('.stylelintignore', stylelintIgnores.join('\n'));
432 * Shifter task. Is configured with a path to a specific file or a directory,
433 * in the case of a specific file it will work out the right module to be built.
435 * Note that this task runs the invidiaul shifter jobs async (becase it spawns
436 * so be careful to to call done().
438 tasks.shifter = function() {
439 var done = this.async(),
440 options = grunt.config('shifter.options');
442 // Run the shifter processes one at a time to avoid confusing output.
443 async.eachSeries(options.paths, function(src, filedone) {
445 args.push(path.normalize(__dirname + '/node_modules/shifter/bin/shifter'));
447 // Always ignore the node_modules directory.
448 args.push('--excludes', 'node_modules');
450 // Determine the most appropriate options to run with based upon the current location.
451 if (grunt.file.isMatch('**/yui/**/*.js', src)) {
452 // When passed a JS file, build our containing module (this happen with
454 grunt.log.debug('Shifter passed a specific JS file');
455 src = path.dirname(path.dirname(src));
456 options.recursive = false;
457 } else if (grunt.file.isMatch('**/yui/src', src)) {
458 // When in a src directory --walk all modules.
459 grunt.log.debug('In a src directory');
461 options.recursive = false;
462 } else if (grunt.file.isMatch('**/yui/src/*', src)) {
463 // When in module, only build our module.
464 grunt.log.debug('In a module directory');
465 options.recursive = false;
466 } else if (grunt.file.isMatch('**/yui/src/*/js', src)) {
467 // When in module src, only build our module.
468 grunt.log.debug('In a source directory');
469 src = path.dirname(src);
470 options.recursive = false;
473 if (grunt.option('watch')) {
474 grunt.fail.fatal('The --watch option has been removed, please use `grunt watch` instead');
477 // Add the stderr option if appropriate
478 if (grunt.option('verbose')) {
479 args.push('--lint-stderr');
482 if (grunt.option('no-color')) {
483 args.push('--color=false');
486 var execShifter = function() {
488 grunt.log.ok("Running shifter on " + src);
492 opts: {cwd: src, stdio: 'inherit', env: process.env}
493 }, function(error, result, code) {
495 grunt.fail.fatal('Shifter failed with code: ' + code);
497 grunt.log.ok('Shifter build complete.');
503 // Actually run shifter.
504 if (!options.recursive) {
507 // Check that there are yui modules otherwise shifter ends with exit code 1.
508 if (grunt.file.expand({cwd: src}, '**/yui/src/**/*.js').length > 0) {
509 args.push('--recursive');
512 grunt.log.ok('No YUI modules to build.');
519 tasks.gherkinlint = function() {
520 const done = this.async();
521 const options = grunt.config('gherkinlint.options');
523 // Grab the gherkin-lint linter and required scaffolding.
524 const linter = require('gherkin-lint/src/linter.js');
525 const featureFinder = require('gherkin-lint/src/feature-finder.js');
526 const configParser = require('gherkin-lint/src/config-parser.js');
527 const formatter = require('gherkin-lint/src/formatters/stylish.js');
530 const results = linter.lint(
531 featureFinder.getFeatureFiles(grunt.file.expand(options.files)),
532 configParser.getConfiguration(configParser.defaultConfigFileName)
535 // Print the results out uncondtionally.
536 formatter.printResults(results);
538 // Report on the results.
539 // We exit 1 if there is at least one error, otherwise we exit cleanly.
540 if (results.some(result => result.errors.length > 0)) {
547 tasks.startup = function() {
548 // Are we in a YUI directory?
549 if (path.basename(path.resolve(cwd, '../../')) == 'yui') {
550 grunt.task.run('yui');
551 // Are we in an AMD directory?
553 grunt.task.run('amd');
556 grunt.task.run('css');
557 grunt.task.run('js');
558 grunt.task.run('gherkinlint');
563 * This is a wrapper task to handle the grunt watch command. It attempts to use
564 * Watchman to monitor for file changes, if it's installed, because it's much faster.
566 * If Watchman isn't installed then it falls back to the grunt-contrib-watch file
567 * watcher for backwards compatibility.
569 tasks.watch = function() {
570 var watchTaskDone = this.async();
571 var watchInitialised = false;
572 var watchTaskQueue = {};
573 var processingQueue = false;
575 // Grab the tasks and files that have been queued up and execute them.
576 var processWatchTaskQueue = function() {
577 if (!Object.keys(watchTaskQueue).length || processingQueue) {
578 // If there is nothing in the queue or we're already processing then wait.
582 processingQueue = true;
584 // Grab all tasks currently in the queue.
585 var queueToProcess = watchTaskQueue;
590 Object.keys(queueToProcess),
591 function(task, next) {
592 var files = queueToProcess[task];
593 var filesOption = '--files=' + files.join(',');
594 grunt.log.ok('Running task ' + task + ' for files ' + filesOption);
596 // Spawn the task in a child process so that it doesn't kill this one
600 // Spawn with the grunt bin.
602 // Run from current working dir and inherit stdio from process.
607 args: [task, filesOption]
609 function(err, res, code) {
611 // The grunt task failed.
612 grunt.log.error(err);
615 // Move on to the next task.
621 // No longer processing.
622 processingQueue = false;
623 // Once all of the tasks are done then recurse just in case more tasks
624 // were queued while we were processing.
625 processWatchTaskQueue();
630 const originalWatchConfig = grunt.config.get(['watch']);
631 const watchConfig = Object.keys(originalWatchConfig).reduce(function(carry, key) {
632 if (key == 'options') {
636 const value = originalWatchConfig[key];
638 const taskNames = value.tasks;
639 const files = value.files;
641 if (value.excludes) {
642 excludes = value.excludes;
645 taskNames.forEach(function(taskName) {
655 watchmanClient.on('error', function(error) {
656 // We have to add an error handler here and parse the error string because the
657 // example way from the docs to check if Watchman is installed doesn't actually work!!
658 // See: https://github.com/facebook/watchman/issues/509
659 if (error.message.match('Watchman was not found')) {
660 // If watchman isn't installed then we should fallback to the other watch task.
661 grunt.log.ok('It is recommended that you install Watchman for better performance using the "watch" command.');
663 // Fallback to the old grunt-contrib-watch task.
664 grunt.renameTask('watch-grunt', 'watch');
665 grunt.task.run(['watch']);
666 // This task is finished.
669 grunt.log.error(error);
675 watchmanClient.on('subscription', function(resp) {
676 if (resp.subscription !== 'grunt-watch') {
680 resp.files.forEach(function(file) {
681 grunt.log.ok('File changed: ' + file.name);
683 var fullPath = fullRunDir + '/' + file.name;
684 Object.keys(watchConfig).forEach(function(task) {
686 const fileGlobs = watchConfig[task].files;
687 var match = fileGlobs.some(function(fileGlob) {
688 return grunt.file.isMatch(`**/${fileGlob}`, fullPath);
692 // If we are watching a subdirectory then the file.name will be relative
693 // to that directory. However the grunt tasks expect the file paths to be
694 // relative to the Gruntfile.js location so let's normalise them before
695 // adding them to the queue.
696 var relativePath = fullPath.replace(gruntFilePath + '/', '');
697 if (task in watchTaskQueue) {
698 if (!watchTaskQueue[task].includes(relativePath)) {
699 watchTaskQueue[task] = watchTaskQueue[task].concat(relativePath);
702 watchTaskQueue[task] = [relativePath];
708 processWatchTaskQueue();
711 process.on('SIGINT', function() {
712 // Let the user know that they may need to manually stop the Watchman daemon if they
713 // no longer want it running.
714 if (watchInitialised) {
715 grunt.log.ok('The Watchman daemon may still be running and may need to be stopped manually.');
721 // Initiate the watch on the current directory.
722 watchmanClient.command(['watch-project', fullRunDir], function(watchError, watchResponse) {
724 grunt.log.error('Error initiating watch:', watchError);
729 if ('warning' in watchResponse) {
730 grunt.log.error('warning: ', watchResponse.warning);
733 var watch = watchResponse.watch;
734 var relativePath = watchResponse.relative_path;
735 watchInitialised = true;
737 watchmanClient.command(['clock', watch], function(clockError, clockResponse) {
739 grunt.log.error('Failed to query clock:', clockError);
744 // Generate the expression query used by watchman.
745 // Documentation is limited, but see https://facebook.github.io/watchman/docs/expr/allof.html for examples.
746 // We generate an expression to match any value in the files list of all of our tasks, but excluding
747 // all value in the excludes list of that task.
752 // ['match', validPath, 'wholename'],
753 // ['match', validPath, 'wholename'],
757 // ['match', invalidPath, 'wholename'],
758 // ['match', invalidPath, 'wholename'],
762 var matchWholeName = fileGlob => ['match', fileGlob, 'wholename'];
763 var matches = Object.keys(watchConfig).map(function(task) {
765 matchAll.push(['anyof'].concat(watchConfig[task].files.map(matchWholeName)));
767 if (watchConfig[task].excludes.length) {
768 matchAll.push(['not', ['anyof'].concat(watchConfig[task].excludes.map(matchWholeName))]);
771 return ['allof'].concat(matchAll);
774 matches = ['anyof'].concat(matches);
778 // Which fields we're interested in.
779 fields: ["name", "size", "type"],
780 // Add our time constraint.
781 since: clockResponse.clock
785 /* eslint-disable camelcase */
786 sub.relative_root = relativePath;
789 watchmanClient.command(['subscribe', watch, 'grunt-watch', sub], function(subscribeError) {
790 if (subscribeError) {
791 // Probably an error in the subscription criteria.
792 grunt.log.error('failed to subscribe: ', subscribeError);
797 grunt.log.ok('Listening for changes to files in ' + fullRunDir);
803 // On watch, we dynamically modify config to build only affected files. This
804 // method is slightly complicated to deal with multiple changed files at once (copied
805 // from the grunt-contrib-watch readme).
806 var changedFiles = Object.create(null);
807 var onChange = grunt.util._.debounce(function() {
808 var files = Object.keys(changedFiles);
809 grunt.config('eslint.amd.src', files);
810 grunt.config('eslint.yui.src', files);
811 grunt.config('shifter.options.paths', files);
812 grunt.config('gherkinlint.options.files', files);
813 grunt.config('babel.dist.files', [{expand: true, src: files, rename: babelRename}]);
814 changedFiles = Object.create(null);
817 grunt.event.on('watch', function(action, filepath) {
818 changedFiles[filepath] = action;
822 // Register NPM tasks.
823 grunt.loadNpmTasks('grunt-contrib-uglify');
824 grunt.loadNpmTasks('grunt-contrib-watch');
825 grunt.loadNpmTasks('grunt-sass');
826 grunt.loadNpmTasks('grunt-eslint');
827 grunt.loadNpmTasks('grunt-stylelint');
828 grunt.loadNpmTasks('grunt-babel');
830 // Rename the grunt-contrib-watch "watch" task because we're going to wrap it.
831 grunt.renameTask('watch', 'watch-grunt');
833 // Register JS tasks.
834 grunt.registerTask('shifter', 'Run Shifter against the current directory', tasks.shifter);
835 grunt.registerTask('gherkinlint', 'Run gherkinlint against the current directory', tasks.gherkinlint);
836 grunt.registerTask('ignorefiles', 'Generate ignore files for linters', tasks.ignorefiles);
837 grunt.registerTask('watch', 'Run tasks on file changes', tasks.watch);
838 grunt.registerTask('yui', ['eslint:yui', 'shifter']);
839 grunt.registerTask('amd', ['eslint:amd', 'babel']);
840 grunt.registerTask('js', ['amd', 'yui']);
842 // Register CSS tasks.
843 registerStyleLintTasks(grunt, files, fullRunDir);
845 // Register the startup task.
846 grunt.registerTask('startup', 'Run the correct tasks for the current directory', tasks.startup);
848 // Register the default task.
849 grunt.registerTask('default', ['startup']);