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
27 module.exports = function(grunt) {
28 var path = require('path'),
30 cwd = process.env.PWD || process.cwd(),
31 async = require('async'),
32 DOMParser = require('xmldom').DOMParser,
33 xpath = require('xpath'),
34 semver = require('semver');
36 // Verify the node version is new enough.
37 var expected = semver.validRange(grunt.file.readJSON('package.json').engines.node);
38 var actual = semver.valid(process.version);
39 if (!semver.satisfies(actual, expected)) {
40 grunt.fail.fatal('Node version too old. Require ' + expected + ', version installed: ' + actual);
43 // Windows users can't run grunt in a subdirectory, so allow them to set
44 // the root by passing --root=path/to/dir.
45 if (grunt.option('root')) {
46 var root = grunt.option('root');
47 if (grunt.file.exists(__dirname, root)) {
48 cwd = path.join(__dirname, root);
49 grunt.log.ok('Setting root to ' + cwd);
51 grunt.fail.fatal('Setting root to ' + root + ' failed - path does not exist');
55 var inAMD = path.basename(cwd) == 'amd';
57 // Globbing pattern for matching all AMD JS source files.
58 var amdSrc = [inAMD ? cwd + '/src/*.js' : '**/amd/src/*.js'];
61 * Function to generate the destination for the uglify task
62 * (e.g. build/file.min.js). This function will be passed to
63 * the rename property of files array when building dynamically:
64 * http://gruntjs.com/configuring-tasks#building-the-files-object-dynamically
66 * @param {String} destPath the current destination
67 * @param {String} srcPath the matched src path
68 * @return {String} The rewritten destination path.
70 var uglifyRename = function(destPath, srcPath) {
71 destPath = srcPath.replace('src', 'build');
72 destPath = destPath.replace('.js', '.min.js');
73 destPath = path.resolve(cwd, destPath);
78 * Find thirdpartylibs.xml and generate an array of paths contained within
79 * them (used to generate ignore files and so on).
81 * @return {array} The list of thirdparty paths.
83 var getThirdPartyPathsFromXML = function() {
84 var thirdpartyfiles = grunt.file.expand('*/**/thirdpartylibs.xml');
85 var libs = ['node_modules/', 'vendor/'];
87 thirdpartyfiles.forEach(function(file) {
88 var dirname = path.dirname(file);
90 var doc = new DOMParser().parseFromString(grunt.file.read(file));
91 var nodes = xpath.select("/libraries/library/location/text()", doc);
93 nodes.forEach(function(node) {
94 var lib = path.join(dirname, node.toString());
95 if (grunt.file.isDir(lib)) {
96 // Ensure trailing slash on dirs.
97 lib = lib.replace(/\/?$/, '/');
100 // Look for duplicate paths before adding to array.
101 if (libs.indexOf(lib) === -1) {
110 // Project configuration.
113 // Even though warnings dont stop the build we don't display warnings by default because
114 // at this moment we've got too many core warnings.
115 options: {quiet: !grunt.option('show-lint-warnings')},
118 // Check AMD with some slightly stricter rules.
120 'no-unused-vars': 'error',
121 'no-implicit-globals': 'error'
124 // Check YUI module source files.
126 src: ['**/yui/src/**/*.js', '!*/**/yui/src/*/meta/*.js'],
128 // Disable some rules which we can't safely define for YUI rollups.
131 'no-unused-vars': 'off',
132 'no-unused-expressions': 'off'
144 options: {report: 'none'}
150 "theme/bootstrapbase/style/moodle.css": "theme/bootstrapbase/less/moodle.less",
151 "theme/bootstrapbase/style/editor.css": "theme/bootstrapbase/less/editor.less",
154 compress: false // We must not compress to keep the comments.
160 nospawn: true // We need not to spawn so config can be changed dynamically.
163 files: ['**/amd/src/**/*.js'],
167 files: ["theme/bootstrapbase/less/**/*.less"],
171 files: ['**/yui/src/**/*.js'],
187 // These rules have to be disabled in .stylelintrc for scss compat.
188 "at-rule-no-unknown": true,
189 "no-browser-hacks": [true, {"severity": "warning"}]
193 src: ['theme/**/*.less']
196 options: {syntax: 'scss'},
204 // These rules have to be disabled in .stylelintrc for scss compat.
205 "at-rule-no-unknown": true,
206 "no-browser-hacks": [true, {"severity": "warning"}]
215 * Generate ignore files (utilising thirdpartylibs.xml data)
217 tasks.ignorefiles = function() {
218 // An array of paths to third party directories.
219 var thirdPartyPaths = getThirdPartyPathsFromXML();
220 // Generate .eslintignore.
221 var eslintIgnores = ['# Generated by "grunt ignorefiles"', '*/**/yui/src/*/meta/', '*/**/build/'].concat(thirdPartyPaths);
222 grunt.file.write('.eslintignore', eslintIgnores.join('\n'));
223 // Generate .stylelintignore.
224 var stylelintIgnores = ['# Generated by "grunt ignorefiles"', 'theme/bootstrapbase/style/'].concat(thirdPartyPaths);
225 grunt.file.write('.stylelintignore', stylelintIgnores.join('\n'));
229 * Shifter task. Is configured with a path to a specific file or a directory,
230 * in the case of a specific file it will work out the right module to be built.
232 * Note that this task runs the invidiaul shifter jobs async (becase it spawns
233 * so be careful to to call done().
235 tasks.shifter = function() {
236 var done = this.async(),
237 options = grunt.config('shifter.options');
239 // Run the shifter processes one at a time to avoid confusing output.
240 async.eachSeries(options.paths, function(src, filedone) {
242 args.push(path.normalize(__dirname + '/node_modules/shifter/bin/shifter'));
244 // Always ignore the node_modules directory.
245 args.push('--excludes', 'node_modules');
247 // Determine the most appropriate options to run with based upon the current location.
248 if (grunt.file.isMatch('**/yui/**/*.js', src)) {
249 // When passed a JS file, build our containing module (this happen with
251 grunt.log.debug('Shifter passed a specific JS file');
252 src = path.dirname(path.dirname(src));
253 options.recursive = false;
254 } else if (grunt.file.isMatch('**/yui/src', src)) {
255 // When in a src directory --walk all modules.
256 grunt.log.debug('In a src directory');
258 options.recursive = false;
259 } else if (grunt.file.isMatch('**/yui/src/*', src)) {
260 // When in module, only build our module.
261 grunt.log.debug('In a module directory');
262 options.recursive = false;
263 } else if (grunt.file.isMatch('**/yui/src/*/js', src)) {
264 // When in module src, only build our module.
265 grunt.log.debug('In a source directory');
266 src = path.dirname(src);
267 options.recursive = false;
270 if (grunt.option('watch')) {
271 grunt.fail.fatal('The --watch option has been removed, please use `grunt watch` instead');
274 // Add the stderr option if appropriate
275 if (grunt.option('verbose')) {
276 args.push('--lint-stderr');
279 if (grunt.option('no-color')) {
280 args.push('--color=false');
283 var execShifter = function() {
285 grunt.log.ok("Running shifter on " + src);
289 opts: {cwd: src, stdio: 'inherit', env: process.env}
290 }, function(error, result, code) {
292 grunt.fail.fatal('Shifter failed with code: ' + code);
294 grunt.log.ok('Shifter build complete.');
300 // Actually run shifter.
301 if (!options.recursive) {
304 // Check that there are yui modules otherwise shifter ends with exit code 1.
305 if (grunt.file.expand({cwd: src}, '**/yui/src/**/*.js').length > 0) {
306 args.push('--recursive');
309 grunt.log.ok('No YUI modules to build.');
316 tasks.startup = function() {
317 // Are we in a YUI directory?
318 if (path.basename(path.resolve(cwd, '../../')) == 'yui') {
319 grunt.task.run('yui');
320 // Are we in an AMD directory?
322 grunt.task.run('amd');
325 grunt.task.run('css');
326 grunt.task.run('js');
330 // On watch, we dynamically modify config to build only affected files. This
331 // method is slightly complicated to deal with multiple changed files at once (copied
332 // from the grunt-contrib-watch readme).
333 var changedFiles = Object.create(null);
334 var onChange = grunt.util._.debounce(function() {
335 var files = Object.keys(changedFiles);
336 grunt.config('eslint.amd.src', files);
337 grunt.config('eslint.yui.src', files);
338 grunt.config('uglify.amd.files', [{expand: true, src: files, rename: uglifyRename}]);
339 grunt.config('shifter.options.paths', files);
340 grunt.config('stylelint.less.src', files);
341 changedFiles = Object.create(null);
344 grunt.event.on('watch', function(action, filepath) {
345 changedFiles[filepath] = action;
349 // Register NPM tasks.
350 grunt.loadNpmTasks('grunt-contrib-uglify');
351 grunt.loadNpmTasks('grunt-contrib-less');
352 grunt.loadNpmTasks('grunt-contrib-watch');
353 grunt.loadNpmTasks('grunt-eslint');
354 grunt.loadNpmTasks('grunt-stylelint');
356 // Register JS tasks.
357 grunt.registerTask('shifter', 'Run Shifter against the current directory', tasks.shifter);
358 grunt.registerTask('ignorefiles', 'Generate ignore files for linters', tasks.ignorefiles);
359 grunt.registerTask('yui', ['eslint:yui', 'shifter']);
360 grunt.registerTask('amd', ['eslint:amd', 'uglify']);
361 grunt.registerTask('js', ['amd', 'yui']);
363 // Register CSS taks.
364 grunt.registerTask('css', ['stylelint:scss', 'stylelint:less', 'less:bootstrapbase', 'stylelint:css']);
366 // Register the startup task.
367 grunt.registerTask('startup', 'Run the correct tasks for the current directory', tasks.startup);
369 // Register the default task.
370 grunt.registerTask('default', ['startup']);