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 configure: ".grunt/jsdoc/jsdoc.conf.js",
365 "theme/boost/style/moodle.css": "theme/boost/scss/preset/default.scss",
366 "theme/classic/style/moodle.css": "theme/classic/scss/classicgrunt.scss"
370 implementation: sass,
371 includePaths: ["theme/boost/scss/", "theme/classic/scss/"]
376 nospawn: true // We need not to spawn so config can be changed dynamically.
380 ? ['amd/src/*.js', 'amd/src/**/*.js']
381 : ['**/amd/src/**/*.js'],
385 files: [inComponent ? 'scss/**/*.scss' : 'theme/boost/scss/**/*.scss'],
400 ? ['yui/src/*.json', 'yui/src/**/*.js']
401 : ['**/yui/src/**/*.js'],
405 files: [inComponent ? 'tests/behat/*.feature' : '**/tests/behat/*.feature'],
406 tasks: ['gherkinlint']
412 // Shifter takes a relative path.
413 paths: files ? files : [runDir]
418 files: getGherkinLintTargets(),
424 * Generate ignore files (utilising thirdpartylibs.xml data)
426 tasks.ignorefiles = function() {
427 // An array of paths to third party directories.
428 const thirdPartyPaths = getThirdPartyPathsFromXML();
429 // Generate .eslintignore.
430 const eslintIgnores = [
431 '# Generated by "grunt ignorefiles"',
432 '*/**/yui/src/*/meta/',
434 ].concat(thirdPartyPaths);
435 grunt.file.write('.eslintignore', eslintIgnores.join('\n') + '\n');
437 // Generate .stylelintignore.
438 const stylelintIgnores = [
439 '# Generated by "grunt ignorefiles"',
441 'theme/boost/style/moodle.css',
442 'theme/classic/style/moodle.css',
443 ].concat(thirdPartyPaths);
444 grunt.file.write('.stylelintignore', stylelintIgnores.join('\n') + '\n');
448 * Shifter task. Is configured with a path to a specific file or a directory,
449 * in the case of a specific file it will work out the right module to be built.
451 * Note that this task runs the invidiaul shifter jobs async (becase it spawns
452 * so be careful to to call done().
454 tasks.shifter = function() {
455 var done = this.async(),
456 options = grunt.config('shifter.options');
458 // Run the shifter processes one at a time to avoid confusing output.
459 async.eachSeries(options.paths, function(src, filedone) {
461 args.push(path.normalize(__dirname + '/node_modules/shifter/bin/shifter'));
463 // Always ignore the node_modules directory.
464 args.push('--excludes', 'node_modules');
466 // Determine the most appropriate options to run with based upon the current location.
467 if (grunt.file.isMatch('**/yui/**/*.js', src)) {
468 // When passed a JS file, build our containing module (this happen with
470 grunt.log.debug('Shifter passed a specific JS file');
471 src = path.dirname(path.dirname(src));
472 options.recursive = false;
473 } else if (grunt.file.isMatch('**/yui/src', src)) {
474 // When in a src directory --walk all modules.
475 grunt.log.debug('In a src directory');
477 options.recursive = false;
478 } else if (grunt.file.isMatch('**/yui/src/*', src)) {
479 // When in module, only build our module.
480 grunt.log.debug('In a module directory');
481 options.recursive = false;
482 } else if (grunt.file.isMatch('**/yui/src/*/js', src)) {
483 // When in module src, only build our module.
484 grunt.log.debug('In a source directory');
485 src = path.dirname(src);
486 options.recursive = false;
489 if (grunt.option('watch')) {
490 grunt.fail.fatal('The --watch option has been removed, please use `grunt watch` instead');
493 // Add the stderr option if appropriate
494 if (grunt.option('verbose')) {
495 args.push('--lint-stderr');
498 if (grunt.option('no-color')) {
499 args.push('--color=false');
502 var execShifter = function() {
504 grunt.log.ok("Running shifter on " + src);
508 opts: {cwd: src, stdio: 'inherit', env: process.env}
509 }, function(error, result, code) {
511 grunt.fail.fatal('Shifter failed with code: ' + code);
513 grunt.log.ok('Shifter build complete.');
519 // Actually run shifter.
520 if (!options.recursive) {
523 // Check that there are yui modules otherwise shifter ends with exit code 1.
524 if (grunt.file.expand({cwd: src}, '**/yui/src/**/*.js').length > 0) {
525 args.push('--recursive');
528 grunt.log.ok('No YUI modules to build.');
535 tasks.gherkinlint = function() {
536 const done = this.async();
537 const options = grunt.config('gherkinlint.options');
539 // Grab the gherkin-lint linter and required scaffolding.
540 const linter = require('gherkin-lint/dist/linter.js');
541 const featureFinder = require('gherkin-lint/dist/feature-finder.js');
542 const configParser = require('gherkin-lint/dist/config-parser.js');
543 const formatter = require('gherkin-lint/dist/formatters/stylish.js');
547 featureFinder.getFeatureFiles(grunt.file.expand(options.files)),
548 configParser.getConfiguration(configParser.defaultConfigFileName)
551 // Print the results out uncondtionally.
552 formatter.printResults(results);
557 // Report on the results.
558 // The done function takes a bool whereby a falsey statement causes the task to fail.
559 return results.every(result => result.errors.length === 0);
561 .then(done); // eslint-disable-line promise/no-callback-in-promise
564 tasks.startup = function() {
565 // Are we in a YUI directory?
566 if (path.basename(path.resolve(cwd, '../../')) == 'yui') {
567 grunt.task.run('yui');
568 // Are we in an AMD directory?
570 grunt.task.run('amd');
573 grunt.task.run('css');
574 grunt.task.run('js');
575 grunt.task.run('gherkinlint');
580 * This is a wrapper task to handle the grunt watch command. It attempts to use
581 * Watchman to monitor for file changes, if it's installed, because it's much faster.
583 * If Watchman isn't installed then it falls back to the grunt-contrib-watch file
584 * watcher for backwards compatibility.
586 tasks.watch = function() {
587 var watchTaskDone = this.async();
588 var watchInitialised = false;
589 var watchTaskQueue = {};
590 var processingQueue = false;
592 // Grab the tasks and files that have been queued up and execute them.
593 var processWatchTaskQueue = function() {
594 if (!Object.keys(watchTaskQueue).length || processingQueue) {
595 // If there is nothing in the queue or we're already processing then wait.
599 processingQueue = true;
601 // Grab all tasks currently in the queue.
602 var queueToProcess = watchTaskQueue;
607 Object.keys(queueToProcess),
608 function(task, next) {
609 var files = queueToProcess[task];
610 var filesOption = '--files=' + files.join(',');
611 grunt.log.ok('Running task ' + task + ' for files ' + filesOption);
613 // Spawn the task in a child process so that it doesn't kill this one
617 // Spawn with the grunt bin.
619 // Run from current working dir and inherit stdio from process.
624 args: [task, filesOption]
626 function(err, res, code) {
628 // The grunt task failed.
629 grunt.log.error(err);
632 // Move on to the next task.
638 // No longer processing.
639 processingQueue = false;
640 // Once all of the tasks are done then recurse just in case more tasks
641 // were queued while we were processing.
642 processWatchTaskQueue();
647 const originalWatchConfig = grunt.config.get(['watch']);
648 const watchConfig = Object.keys(originalWatchConfig).reduce(function(carry, key) {
649 if (key == 'options') {
653 const value = originalWatchConfig[key];
655 const taskNames = value.tasks;
656 const files = value.files;
658 if (value.excludes) {
659 excludes = value.excludes;
662 taskNames.forEach(function(taskName) {
672 watchmanClient.on('error', function(error) {
673 // We have to add an error handler here and parse the error string because the
674 // example way from the docs to check if Watchman is installed doesn't actually work!!
675 // See: https://github.com/facebook/watchman/issues/509
676 if (error.message.match('Watchman was not found')) {
677 // If watchman isn't installed then we should fallback to the other watch task.
678 grunt.log.ok('It is recommended that you install Watchman for better performance using the "watch" command.');
680 // Fallback to the old grunt-contrib-watch task.
681 grunt.renameTask('watch-grunt', 'watch');
682 grunt.task.run(['watch']);
683 // This task is finished.
686 grunt.log.error(error);
692 watchmanClient.on('subscription', function(resp) {
693 if (resp.subscription !== 'grunt-watch') {
697 resp.files.forEach(function(file) {
698 grunt.log.ok('File changed: ' + file.name);
700 var fullPath = fullRunDir + '/' + file.name;
701 Object.keys(watchConfig).forEach(function(task) {
703 const fileGlobs = watchConfig[task].files;
704 var match = fileGlobs.some(function(fileGlob) {
705 return grunt.file.isMatch(`**/${fileGlob}`, fullPath);
709 // If we are watching a subdirectory then the file.name will be relative
710 // to that directory. However the grunt tasks expect the file paths to be
711 // relative to the Gruntfile.js location so let's normalise them before
712 // adding them to the queue.
713 var relativePath = fullPath.replace(gruntFilePath + '/', '');
714 if (task in watchTaskQueue) {
715 if (!watchTaskQueue[task].includes(relativePath)) {
716 watchTaskQueue[task] = watchTaskQueue[task].concat(relativePath);
719 watchTaskQueue[task] = [relativePath];
725 processWatchTaskQueue();
728 process.on('SIGINT', function() {
729 // Let the user know that they may need to manually stop the Watchman daemon if they
730 // no longer want it running.
731 if (watchInitialised) {
732 grunt.log.ok('The Watchman daemon may still be running and may need to be stopped manually.');
738 // Initiate the watch on the current directory.
739 watchmanClient.command(['watch-project', fullRunDir], function(watchError, watchResponse) {
741 grunt.log.error('Error initiating watch:', watchError);
746 if ('warning' in watchResponse) {
747 grunt.log.error('warning: ', watchResponse.warning);
750 var watch = watchResponse.watch;
751 var relativePath = watchResponse.relative_path;
752 watchInitialised = true;
754 watchmanClient.command(['clock', watch], function(clockError, clockResponse) {
756 grunt.log.error('Failed to query clock:', clockError);
761 // Generate the expression query used by watchman.
762 // Documentation is limited, but see https://facebook.github.io/watchman/docs/expr/allof.html for examples.
763 // We generate an expression to match any value in the files list of all of our tasks, but excluding
764 // all value in the excludes list of that task.
769 // ['match', validPath, 'wholename'],
770 // ['match', validPath, 'wholename'],
774 // ['match', invalidPath, 'wholename'],
775 // ['match', invalidPath, 'wholename'],
779 var matchWholeName = fileGlob => ['match', fileGlob, 'wholename'];
780 var matches = Object.keys(watchConfig).map(function(task) {
782 matchAll.push(['anyof'].concat(watchConfig[task].files.map(matchWholeName)));
784 if (watchConfig[task].excludes.length) {
785 matchAll.push(['not', ['anyof'].concat(watchConfig[task].excludes.map(matchWholeName))]);
788 return ['allof'].concat(matchAll);
791 matches = ['anyof'].concat(matches);
795 // Which fields we're interested in.
796 fields: ["name", "size", "type"],
797 // Add our time constraint.
798 since: clockResponse.clock
802 /* eslint-disable camelcase */
803 sub.relative_root = relativePath;
806 watchmanClient.command(['subscribe', watch, 'grunt-watch', sub], function(subscribeError) {
807 if (subscribeError) {
808 // Probably an error in the subscription criteria.
809 grunt.log.error('failed to subscribe: ', subscribeError);
814 grunt.log.ok('Listening for changes to files in ' + fullRunDir);
820 // On watch, we dynamically modify config to build only affected files. This
821 // method is slightly complicated to deal with multiple changed files at once (copied
822 // from the grunt-contrib-watch readme).
823 var changedFiles = Object.create(null);
824 var onChange = grunt.util._.debounce(function() {
825 var files = Object.keys(changedFiles);
826 grunt.config('eslint.amd.src', files);
827 grunt.config('eslint.yui.src', files);
828 grunt.config('shifter.options.paths', files);
829 grunt.config('gherkinlint.options.files', files);
830 grunt.config('babel.dist.files', [{expand: true, src: files, rename: babelRename}]);
831 changedFiles = Object.create(null);
834 grunt.event.on('watch', function(action, filepath) {
835 changedFiles[filepath] = action;
839 // Register NPM tasks.
840 grunt.loadNpmTasks('grunt-contrib-uglify');
841 grunt.loadNpmTasks('grunt-contrib-watch');
842 grunt.loadNpmTasks('grunt-sass');
843 grunt.loadNpmTasks('grunt-eslint');
844 grunt.loadNpmTasks('grunt-stylelint');
845 grunt.loadNpmTasks('grunt-babel');
846 grunt.loadNpmTasks('grunt-jsdoc');
848 // Rename the grunt-contrib-watch "watch" task because we're going to wrap it.
849 grunt.renameTask('watch', 'watch-grunt');
851 // Register JS tasks.
852 grunt.registerTask('shifter', 'Run Shifter against the current directory', tasks.shifter);
853 grunt.registerTask('gherkinlint', 'Run gherkinlint against the current directory', tasks.gherkinlint);
854 grunt.registerTask('ignorefiles', 'Generate ignore files for linters', tasks.ignorefiles);
855 grunt.registerTask('watch', 'Run tasks on file changes', tasks.watch);
856 grunt.registerTask('yui', ['eslint:yui', 'shifter']);
857 grunt.registerTask('amd', ['ignorefiles', 'eslint:amd', 'babel']);
858 grunt.registerTask('js', ['amd', 'yui']);
860 // Register CSS tasks.
861 registerStyleLintTasks(grunt, files, fullRunDir);
863 // Register the startup task.
864 grunt.registerTask('startup', 'Run the correct tasks for the current directory', tasks.startup);
866 // Register the default task.
867 grunt.registerTask('default', ['startup']);