MDL-67499 user: truncate long username/email during user deletion.
[moodle.git] / Gruntfile.js
blob1f24ad435c56727b461bce107b32cf28b30f945c
1 // This file is part of Moodle - http://moodle.org/
2 //
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.
7 //
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 */
16 /* eslint-env node */
18 /**
19  * @copyright  2014 Andrew Nicols
20  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
21  */
23 /**
24  * Grunt configuration
25  */
27 /* eslint-env node */
28 module.exports = function(grunt) {
29     var path = require('path'),
30         tasks = {},
31         cwd = process.env.PWD || process.cwd(),
32         async = require('async'),
33         DOMParser = require('xmldom').DOMParser,
34         xpath = require('xpath'),
35         semver = require('semver'),
36         watchman = require('fb-watchman'),
37         watchmanClient = new watchman.Client(),
38         gruntFilePath = process.cwd();
40     // Verify the node version is new enough.
41     var expected = semver.validRange(grunt.file.readJSON('package.json').engines.node);
42     var actual = semver.valid(process.version);
43     if (!semver.satisfies(actual, expected)) {
44         grunt.fail.fatal('Node version not satisfied. Require ' + expected + ', version installed: ' + actual);
45     }
47     // Windows users can't run grunt in a subdirectory, so allow them to set
48     // the root by passing --root=path/to/dir.
49     if (grunt.option('root')) {
50         var root = grunt.option('root');
51         if (grunt.file.exists(__dirname, root)) {
52             cwd = path.join(__dirname, root);
53             grunt.log.ok('Setting root to ' + cwd);
54         } else {
55             grunt.fail.fatal('Setting root to ' + root + ' failed - path does not exist');
56         }
57     }
59     var files = null;
60     if (grunt.option('files')) {
61         // Accept a comma separated list of files to process.
62         files = grunt.option('files').split(',');
63     }
65     var inAMD = path.basename(cwd) == 'amd';
67     // Globbing pattern for matching all AMD JS source files.
68     var amdSrc = [];
69     if (inAMD) {
70         amdSrc.push(cwd + "/src/*.js");
71         amdSrc.push(cwd + "/src/**/*.js");
72     } else {
73         amdSrc.push("**/amd/src/*.js");
74         amdSrc.push("**/amd/src/**/*.js");
75     }
77     /**
78      * Function to generate the destination for the uglify task
79      * (e.g. build/file.min.js). This function will be passed to
80      * the rename property of files array when building dynamically:
81      * http://gruntjs.com/configuring-tasks#building-the-files-object-dynamically
82      *
83      * @param {String} destPath the current destination
84      * @param {String} srcPath the  matched src path
85      * @return {String} The rewritten destination path.
86      */
87     var babelRename = function(destPath, srcPath) {
88         destPath = srcPath.replace('src', 'build');
89         destPath = destPath.replace('.js', '.min.js');
90         return destPath;
91     };
93     /**
94      * Find thirdpartylibs.xml and generate an array of paths contained within
95      * them (used to generate ignore files and so on).
96      *
97      * @return {array} The list of thirdparty paths.
98      */
99     var getThirdPartyPathsFromXML = function() {
100         var thirdpartyfiles = grunt.file.expand('*/**/thirdpartylibs.xml');
101         var libs = ['node_modules/', 'vendor/'];
103         thirdpartyfiles.forEach(function(file) {
104           var dirname = path.dirname(file);
106           var doc = new DOMParser().parseFromString(grunt.file.read(file));
107           var nodes = xpath.select("/libraries/library/location/text()", doc);
109           nodes.forEach(function(node) {
110             var lib = path.join(dirname, node.toString());
111             if (grunt.file.isDir(lib)) {
112                 // Ensure trailing slash on dirs.
113                 lib = lib.replace(/\/?$/, '/');
114             }
116             // Look for duplicate paths before adding to array.
117             if (libs.indexOf(lib) === -1) {
118                 libs.push(lib);
119             }
120           });
121         });
122         return libs;
123     };
125     // Project configuration.
126     grunt.initConfig({
127         eslint: {
128             // Even though warnings dont stop the build we don't display warnings by default because
129             // at this moment we've got too many core warnings.
130             options: {quiet: !grunt.option('show-lint-warnings')},
131             amd: {src: files ? files : amdSrc},
132             // Check YUI module source files.
133             yui: {src: files ? files : ['**/yui/src/**/*.js', '!*/**/yui/src/*/meta/*.js']}
134         },
135         babel: {
136             options: {
137                 sourceMaps: true,
138                 comments: false,
139                 plugins: [
140                     'transform-es2015-modules-amd-lazy',
141                     'system-import-transformer',
142                     // This plugin modifies the Babel transpiling for "export default"
143                     // so that if it's used then only the exported value is returned
144                     // by the generated AMD module.
145                     //
146                     // It also adds the Moodle plugin name to the AMD module definition
147                     // so that it can be imported as expected in other modules.
148                     path.resolve('babel-plugin-add-module-to-define.js'),
149                     '@babel/plugin-syntax-dynamic-import',
150                     '@babel/plugin-syntax-import-meta',
151                     ['@babel/plugin-proposal-class-properties', {'loose': false}],
152                     '@babel/plugin-proposal-json-strings'
153                 ],
154                 presets: [
155                     ['minify', {
156                         // This minification plugin needs to be disabled because it breaks the
157                         // source map generation and causes invalid source maps to be output.
158                         simplify: false,
159                         builtIns: false
160                     }],
161                     ['@babel/preset-env', {
162                         targets: {
163                             browsers: [
164                                 ">0.25%",
165                                 "last 2 versions",
166                                 "not ie <= 10",
167                                 "not op_mini all",
168                                 "not Opera > 0",
169                                 "not dead"
170                             ]
171                         },
172                         modules: false,
173                         useBuiltIns: false
174                     }]
175                 ]
176             },
177             dist: {
178                 files: [{
179                     expand: true,
180                     src: files ? files : amdSrc,
181                     rename: babelRename
182                 }]
183             }
184         },
185         sass: {
186             dist: {
187                 files: {
188                     "theme/boost/style/moodle.css": "theme/boost/scss/preset/default.scss",
189                     "theme/classic/style/moodle.css": "theme/classic/scss/classicgrunt.scss"
190                 }
191             },
192             options: {
193                 includePaths: ["theme/boost/scss/", "theme/classic/scss/"]
194             }
195         },
196         watch: {
197             options: {
198                 nospawn: true // We need not to spawn so config can be changed dynamically.
199             },
200             amd: {
201                 files: ['**/amd/src/**/*.js'],
202                 tasks: ['amd']
203             },
204             boost: {
205                 files: ['**/theme/boost/scss/**/*.scss'],
206                 tasks: ['scss']
207             },
208             rawcss: {
209                 files: ['**/*.css', '**/theme/**/!(moodle.css|editor.css)'],
210                 tasks: ['rawcss']
211             },
212             yui: {
213                 files: ['**/yui/src/**/*.js'],
214                 tasks: ['yui']
215             },
216             gherkinlint: {
217                 files: ['**/tests/behat/*.feature'],
218                 tasks: ['gherkinlint']
219             }
220         },
221         shifter: {
222             options: {
223                 recursive: true,
224                 paths: files ? files : [cwd]
225             }
226         },
227         gherkinlint: {
228             options: {
229                 files: files ? files : ['**/tests/behat/*.feature'],
230             }
231         },
232         stylelint: {
233             scss: {
234                 options: {syntax: 'scss'},
235                 src: files ? files : ['*/**/*.scss']
236             },
237             css: {
238                 src: files ? files : ['*/**/*.css'],
239                 options: {
240                     configOverrides: {
241                         rules: {
242                             // These rules have to be disabled in .stylelintrc for scss compat.
243                             "at-rule-no-unknown": true,
244                         }
245                     }
246                 }
247             }
248         }
249     });
251     /**
252      * Generate ignore files (utilising thirdpartylibs.xml data)
253      */
254     tasks.ignorefiles = function() {
255       // An array of paths to third party directories.
256       var thirdPartyPaths = getThirdPartyPathsFromXML();
257       // Generate .eslintignore.
258       var eslintIgnores = ['# Generated by "grunt ignorefiles"', '*/**/yui/src/*/meta/', '*/**/build/'].concat(thirdPartyPaths);
259       grunt.file.write('.eslintignore', eslintIgnores.join('\n'));
260       // Generate .stylelintignore.
261       var stylelintIgnores = [
262           '# Generated by "grunt ignorefiles"',
263           '**/yui/build/*',
264           'theme/boost/style/moodle.css',
265           'theme/classic/style/moodle.css',
266       ].concat(thirdPartyPaths);
267       grunt.file.write('.stylelintignore', stylelintIgnores.join('\n'));
268     };
270     /**
271      * Shifter task. Is configured with a path to a specific file or a directory,
272      * in the case of a specific file it will work out the right module to be built.
273      *
274      * Note that this task runs the invidiaul shifter jobs async (becase it spawns
275      * so be careful to to call done().
276      */
277     tasks.shifter = function() {
278         var done = this.async(),
279             options = grunt.config('shifter.options');
281         // Run the shifter processes one at a time to avoid confusing output.
282         async.eachSeries(options.paths, function(src, filedone) {
283             var args = [];
284             args.push(path.normalize(__dirname + '/node_modules/shifter/bin/shifter'));
286             // Always ignore the node_modules directory.
287             args.push('--excludes', 'node_modules');
289             // Determine the most appropriate options to run with based upon the current location.
290             if (grunt.file.isMatch('**/yui/**/*.js', src)) {
291                 // When passed a JS file, build our containing module (this happen with
292                 // watch).
293                 grunt.log.debug('Shifter passed a specific JS file');
294                 src = path.dirname(path.dirname(src));
295                 options.recursive = false;
296             } else if (grunt.file.isMatch('**/yui/src', src)) {
297                 // When in a src directory --walk all modules.
298                 grunt.log.debug('In a src directory');
299                 args.push('--walk');
300                 options.recursive = false;
301             } else if (grunt.file.isMatch('**/yui/src/*', src)) {
302                 // When in module, only build our module.
303                 grunt.log.debug('In a module directory');
304                 options.recursive = false;
305             } else if (grunt.file.isMatch('**/yui/src/*/js', src)) {
306                 // When in module src, only build our module.
307                 grunt.log.debug('In a source directory');
308                 src = path.dirname(src);
309                 options.recursive = false;
310             }
312             if (grunt.option('watch')) {
313                 grunt.fail.fatal('The --watch option has been removed, please use `grunt watch` instead');
314             }
316             // Add the stderr option if appropriate
317             if (grunt.option('verbose')) {
318                 args.push('--lint-stderr');
319             }
321             if (grunt.option('no-color')) {
322                 args.push('--color=false');
323             }
325             var execShifter = function() {
327                 grunt.log.ok("Running shifter on " + src);
328                 grunt.util.spawn({
329                     cmd: "node",
330                     args: args,
331                     opts: {cwd: src, stdio: 'inherit', env: process.env}
332                 }, function(error, result, code) {
333                     if (code) {
334                         grunt.fail.fatal('Shifter failed with code: ' + code);
335                     } else {
336                         grunt.log.ok('Shifter build complete.');
337                         filedone();
338                     }
339                 });
340             };
342             // Actually run shifter.
343             if (!options.recursive) {
344                 execShifter();
345             } else {
346                 // Check that there are yui modules otherwise shifter ends with exit code 1.
347                 if (grunt.file.expand({cwd: src}, '**/yui/src/**/*.js').length > 0) {
348                     args.push('--recursive');
349                     execShifter();
350                 } else {
351                     grunt.log.ok('No YUI modules to build.');
352                     filedone();
353                 }
354             }
355         }, done);
356     };
358     tasks.gherkinlint = function() {
359         const done = this.async();
360         const options = grunt.config('gherkinlint.options');
362         // Grab the gherkin-lint linter and required scaffolding.
363         const linter = require('gherkin-lint/src/linter.js');
364         const featureFinder = require('gherkin-lint/src/feature-finder.js');
365         const configParser = require('gherkin-lint/src/config-parser.js');
366         const formatter = require('gherkin-lint/src/formatters/stylish.js');
368         // Run the linter.
369         const results = linter.lint(
370             featureFinder.getFeatureFiles(grunt.file.expand(options.files)),
371             configParser.getConfiguration(configParser.defaultConfigFileName)
372         );
374         // Print the results out uncondtionally.
375         formatter.printResults(results);
377         // Report on the results.
378         // We exit 1 if there is at least one error, otherwise we exit cleanly.
379         if (results.some(result => result.errors.length > 0)) {
380             done(1);
381         } else {
382             done(0);
383         }
384     };
386     tasks.startup = function() {
387         // Are we in a YUI directory?
388         if (path.basename(path.resolve(cwd, '../../')) == 'yui') {
389             grunt.task.run('yui');
390         // Are we in an AMD directory?
391         } else if (inAMD) {
392             grunt.task.run('amd');
393         } else {
394             // Run them all!.
395             grunt.task.run('css');
396             grunt.task.run('js');
397             grunt.task.run('gherkinlint');
398         }
399     };
401     /**
402      * This is a wrapper task to handle the grunt watch command. It attempts to use
403      * Watchman to monitor for file changes, if it's installed, because it's much faster.
404      *
405      * If Watchman isn't installed then it falls back to the grunt-contrib-watch file
406      * watcher for backwards compatibility.
407      */
408     tasks.watch = function() {
409         var watchTaskDone = this.async();
410         var watchInitialised = false;
411         var watchTaskQueue = {};
412         var processingQueue = false;
414         // Grab the tasks and files that have been queued up and execute them.
415         var processWatchTaskQueue = function() {
416             if (!Object.keys(watchTaskQueue).length || processingQueue) {
417                 // If there is nothing in the queue or we're already processing then wait.
418                 return;
419             }
421             processingQueue = true;
423             // Grab all tasks currently in the queue.
424             var queueToProcess = watchTaskQueue;
425             // Reset the queue.
426             watchTaskQueue = {};
428             async.forEachSeries(
429                 Object.keys(queueToProcess),
430                 function(task, next) {
431                     var files = queueToProcess[task];
432                     var filesOption = '--files=' + files.join(',');
433                     grunt.log.ok('Running task ' + task + ' for files ' + filesOption);
435                     // Spawn the task in a child process so that it doesn't kill this one
436                     // if it failed.
437                     grunt.util.spawn(
438                         {
439                             // Spawn with the grunt bin.
440                             grunt: true,
441                             // Run from current working dir and inherit stdio from process.
442                             opts: {
443                                 cwd: cwd,
444                                 stdio: 'inherit'
445                             },
446                             args: [task, filesOption]
447                         },
448                         function(err, res, code) {
449                             if (code !== 0) {
450                                 // The grunt task failed.
451                                 grunt.log.error(err);
452                             }
454                             // Move on to the next task.
455                             next();
456                         }
457                     );
458                 },
459                 function() {
460                     // No longer processing.
461                     processingQueue = false;
462                     // Once all of the tasks are done then recurse just in case more tasks
463                     // were queued while we were processing.
464                     processWatchTaskQueue();
465                 }
466             );
467         };
469         var watchConfig = grunt.config.get(['watch']);
470         watchConfig = Object.keys(watchConfig).reduce(function(carry, key) {
471             if (key == 'options') {
472                 return carry;
473             }
475             var value = watchConfig[key];
476             var fileGlobs = value.files;
477             var taskNames = value.tasks;
479             taskNames.forEach(function(taskName) {
480                 carry[taskName] = fileGlobs;
481             });
483             return carry;
484         }, {});
486         watchmanClient.on('error', function(error) {
487             // We have to add an error handler here and parse the error string because the
488             // example way from the docs to check if Watchman is installed doesn't actually work!!
489             // See: https://github.com/facebook/watchman/issues/509
490             if (error.message.match('Watchman was not found')) {
491                 // If watchman isn't installed then we should fallback to the other watch task.
492                 grunt.log.ok('It is recommended that you install Watchman for better performance using the "watch" command.');
494                 // Fallback to the old grunt-contrib-watch task.
495                 grunt.renameTask('watch-grunt', 'watch');
496                 grunt.task.run(['watch']);
497                 // This task is finished.
498                 watchTaskDone(0);
499             } else {
500                 grunt.log.error(error);
501                 // Fatal error.
502                 watchTaskDone(1);
503             }
504         });
506         watchmanClient.on('subscription', function(resp) {
507             if (resp.subscription !== 'grunt-watch') {
508                 return;
509             }
511             resp.files.forEach(function(file) {
512                 grunt.log.ok('File changed: ' + file.name);
514                 var fullPath = cwd + '/' + file.name;
515                 Object.keys(watchConfig).forEach(function(task) {
516                     var fileGlobs = watchConfig[task];
517                     var match = fileGlobs.every(function(fileGlob) {
518                         return grunt.file.isMatch(fileGlob, fullPath);
519                     });
520                     if (match) {
521                         // If we are watching a subdirectory then the file.name will be relative
522                         // to that directory. However the grunt tasks  expect the file paths to be
523                         // relative to the Gruntfile.js location so let's normalise them before
524                         // adding them to the queue.
525                         var relativePath = fullPath.replace(gruntFilePath + '/', '');
526                         if (task in watchTaskQueue) {
527                             if (!watchTaskQueue[task].includes(relativePath)) {
528                                 watchTaskQueue[task] = watchTaskQueue[task].concat(relativePath);
529                             }
530                         } else {
531                             watchTaskQueue[task] = [relativePath];
532                         }
533                     }
534                 });
535             });
537             processWatchTaskQueue();
538         });
540         process.on('SIGINT', function() {
541             // Let the user know that they may need to manually stop the Watchman daemon if they
542             // no longer want it running.
543             if (watchInitialised) {
544                 grunt.log.ok('The Watchman daemon may still be running and may need to be stopped manually.');
545             }
547             process.exit();
548         });
550         // Initiate the watch on the current directory.
551         watchmanClient.command(['watch-project', cwd], function(watchError, watchResponse) {
552             if (watchError) {
553                 grunt.log.error('Error initiating watch:', watchError);
554                 watchTaskDone(1);
555                 return;
556             }
558             if ('warning' in watchResponse) {
559                 grunt.log.error('warning: ', watchResponse.warning);
560             }
562             var watch = watchResponse.watch;
563             var relativePath = watchResponse.relative_path;
564             watchInitialised = true;
566             watchmanClient.command(['clock', watch], function(clockError, clockResponse) {
567                 if (clockError) {
568                     grunt.log.error('Failed to query clock:', clockError);
569                     watchTaskDone(1);
570                     return;
571                 }
573                 // Use the matching patterns specified in the watch config.
574                 var matches = Object.keys(watchConfig).map(function(task) {
575                     var fileGlobs = watchConfig[task];
576                     var fileGlobMatches = fileGlobs.map(function(fileGlob) {
577                         return ['match', fileGlob, 'wholename'];
578                     });
580                     return ['allof'].concat(fileGlobMatches);
581                 });
583                 var sub = {
584                     expression: ["anyof"].concat(matches),
585                     // Which fields we're interested in.
586                     fields: ["name", "size", "type"],
587                     // Add our time constraint.
588                     since: clockResponse.clock
589                 };
591                 if (relativePath) {
592                     /* eslint-disable camelcase */
593                     sub.relative_root = relativePath;
594                 }
596                 watchmanClient.command(['subscribe', watch, 'grunt-watch', sub], function(subscribeError) {
597                     if (subscribeError) {
598                         // Probably an error in the subscription criteria.
599                         grunt.log.error('failed to subscribe: ', subscribeError);
600                         watchTaskDone(1);
601                         return;
602                     }
604                     grunt.log.ok('Listening for changes to files in ' + cwd);
605                 });
606             });
607         });
608     };
610     // On watch, we dynamically modify config to build only affected files. This
611     // method is slightly complicated to deal with multiple changed files at once (copied
612     // from the grunt-contrib-watch readme).
613     var changedFiles = Object.create(null);
614     var onChange = grunt.util._.debounce(function() {
615         var files = Object.keys(changedFiles);
616         grunt.config('eslint.amd.src', files);
617         grunt.config('eslint.yui.src', files);
618         grunt.config('shifter.options.paths', files);
619         grunt.config('gherkinlint.options.files', files);
620         grunt.config('babel.dist.files', [{expand: true, src: files, rename: babelRename}]);
621         changedFiles = Object.create(null);
622     }, 200);
624     grunt.event.on('watch', function(action, filepath) {
625         changedFiles[filepath] = action;
626         onChange();
627     });
629     // Register NPM tasks.
630     grunt.loadNpmTasks('grunt-contrib-uglify');
631     grunt.loadNpmTasks('grunt-contrib-watch');
632     grunt.loadNpmTasks('grunt-sass');
633     grunt.loadNpmTasks('grunt-eslint');
634     grunt.loadNpmTasks('grunt-stylelint');
635     grunt.loadNpmTasks('grunt-babel');
637     // Rename the grunt-contrib-watch "watch" task because we're going to wrap it.
638     grunt.renameTask('watch', 'watch-grunt');
640     // Register JS tasks.
641     grunt.registerTask('shifter', 'Run Shifter against the current directory', tasks.shifter);
642     grunt.registerTask('gherkinlint', 'Run gherkinlint against the current directory', tasks.gherkinlint);
643     grunt.registerTask('ignorefiles', 'Generate ignore files for linters', tasks.ignorefiles);
644     grunt.registerTask('watch', 'Run tasks on file changes', tasks.watch);
645     grunt.registerTask('yui', ['eslint:yui', 'shifter']);
646     grunt.registerTask('amd', ['eslint:amd', 'babel']);
647     grunt.registerTask('js', ['amd', 'yui']);
649     // Register CSS taks.
650     grunt.registerTask('css', ['stylelint:scss', 'sass', 'stylelint:css']);
651     grunt.registerTask('scss', ['stylelint:scss', 'sass']);
652     grunt.registerTask('rawcss', ['stylelint:css']);
654     // Register the startup task.
655     grunt.registerTask('startup', 'Run the correct tasks for the current directory', tasks.startup);
657     // Register the default task.
658     grunt.registerTask('default', ['startup']);