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
28 module.exports = function(grunt) {
29 var path = require('path'),
31 cwd = process.env.PWD || process.cwd(),
32 async = require('async'),
33 DOMParser = require('xmldom').DOMParser,
34 xpath = require('xpath'),
35 semver = require('semver');
37 // Verify the node version is new enough.
38 var expected = semver.validRange(grunt.file.readJSON('package.json').engines.node);
39 var actual = semver.valid(process.version);
40 if (!semver.satisfies(actual, expected)) {
41 grunt.fail.fatal('Node version not satisfied. Require ' + expected + ', version installed: ' + actual);
44 // Windows users can't run grunt in a subdirectory, so allow them to set
45 // the root by passing --root=path/to/dir.
46 if (grunt.option('root')) {
47 var root = grunt.option('root');
48 if (grunt.file.exists(__dirname, root)) {
49 cwd = path.join(__dirname, root);
50 grunt.log.ok('Setting root to ' + cwd);
52 grunt.fail.fatal('Setting root to ' + root + ' failed - path does not exist');
56 var inAMD = path.basename(cwd) == 'amd';
58 // Globbing pattern for matching all AMD JS source files.
59 var amdSrc = [inAMD ? cwd + '/src/*.js' : '**/amd/src/*.js'];
62 * Function to generate the destination for the uglify task
63 * (e.g. build/file.min.js). This function will be passed to
64 * the rename property of files array when building dynamically:
65 * http://gruntjs.com/configuring-tasks#building-the-files-object-dynamically
67 * @param {String} destPath the current destination
68 * @param {String} srcPath the matched src path
69 * @return {String} The rewritten destination path.
71 var uglifyRename = function(destPath, srcPath) {
72 destPath = srcPath.replace('src', 'build');
73 destPath = destPath.replace('.js', '.min.js');
74 destPath = path.resolve(cwd, destPath);
79 * Find thirdpartylibs.xml and generate an array of paths contained within
80 * them (used to generate ignore files and so on).
82 * @return {array} The list of thirdparty paths.
84 var getThirdPartyPathsFromXML = function() {
85 var thirdpartyfiles = grunt.file.expand('*/**/thirdpartylibs.xml');
86 var libs = ['node_modules/', 'vendor/'];
88 thirdpartyfiles.forEach(function(file) {
89 var dirname = path.dirname(file);
91 var doc = new DOMParser().parseFromString(grunt.file.read(file));
92 var nodes = xpath.select("/libraries/library/location/text()", doc);
94 nodes.forEach(function(node) {
95 var lib = path.join(dirname, node.toString());
96 if (grunt.file.isDir(lib)) {
97 // Ensure trailing slash on dirs.
98 lib = lib.replace(/\/?$/, '/');
101 // Look for duplicate paths before adding to array.
102 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')},
117 // Check YUI module source files.
118 yui: {src: ['**/yui/src/**/*.js', '!*/**/yui/src/*/meta/*.js']}
127 options: {report: 'none'}
133 "theme/bootstrapbase/style/moodle.css": "theme/bootstrapbase/less/moodle.less",
134 "theme/bootstrapbase/style/editor.css": "theme/bootstrapbase/less/editor.less",
137 compress: false // We must not compress to keep the comments.
144 "theme/boost/style/moodle.css": "theme/boost/scss/preset/default.scss"
148 includePaths: ["theme/boost/scss/"]
153 nospawn: true // We need not to spawn so config can be changed dynamically.
156 files: ['**/amd/src/**/*.js'],
160 files: ["theme/bootstrapbase/less/**/*.less"],
164 files: ['**/yui/src/**/*.js'],
168 files: ['**/tests/behat/*.feature'],
169 tasks: ['gherkinlint']
180 files: ['**/tests/behat/*.feature'],
189 // These rules have to be disabled in .stylelintrc for scss compat.
190 "at-rule-no-unknown": true,
194 src: ['theme/**/*.less']
197 options: {syntax: 'scss'},
205 // These rules have to be disabled in .stylelintrc for scss compat.
206 "at-rule-no-unknown": true,
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 = [
225 '# Generated by "grunt ignorefiles"',
227 'theme/bootstrapbase/style/',
228 'theme/clean/style/custom.css',
229 'theme/more/style/custom.css',
230 'theme/boost/style/moodle.css'
231 ].concat(thirdPartyPaths);
232 grunt.file.write('.stylelintignore', stylelintIgnores.join('\n'));
236 * Shifter task. Is configured with a path to a specific file or a directory,
237 * in the case of a specific file it will work out the right module to be built.
239 * Note that this task runs the invidiaul shifter jobs async (becase it spawns
240 * so be careful to to call done().
242 tasks.shifter = function() {
243 var done = this.async(),
244 options = grunt.config('shifter.options');
246 // Run the shifter processes one at a time to avoid confusing output.
247 async.eachSeries(options.paths, function(src, filedone) {
249 args.push(path.normalize(__dirname + '/node_modules/shifter/bin/shifter'));
251 // Always ignore the node_modules directory.
252 args.push('--excludes', 'node_modules');
254 // Determine the most appropriate options to run with based upon the current location.
255 if (grunt.file.isMatch('**/yui/**/*.js', src)) {
256 // When passed a JS file, build our containing module (this happen with
258 grunt.log.debug('Shifter passed a specific JS file');
259 src = path.dirname(path.dirname(src));
260 options.recursive = false;
261 } else if (grunt.file.isMatch('**/yui/src', src)) {
262 // When in a src directory --walk all modules.
263 grunt.log.debug('In a src directory');
265 options.recursive = false;
266 } else if (grunt.file.isMatch('**/yui/src/*', src)) {
267 // When in module, only build our module.
268 grunt.log.debug('In a module directory');
269 options.recursive = false;
270 } else if (grunt.file.isMatch('**/yui/src/*/js', src)) {
271 // When in module src, only build our module.
272 grunt.log.debug('In a source directory');
273 src = path.dirname(src);
274 options.recursive = false;
277 if (grunt.option('watch')) {
278 grunt.fail.fatal('The --watch option has been removed, please use `grunt watch` instead');
281 // Add the stderr option if appropriate
282 if (grunt.option('verbose')) {
283 args.push('--lint-stderr');
286 if (grunt.option('no-color')) {
287 args.push('--color=false');
290 var execShifter = function() {
292 grunt.log.ok("Running shifter on " + src);
296 opts: {cwd: src, stdio: 'inherit', env: process.env}
297 }, function(error, result, code) {
299 grunt.fail.fatal('Shifter failed with code: ' + code);
301 grunt.log.ok('Shifter build complete.');
307 // Actually run shifter.
308 if (!options.recursive) {
311 // Check that there are yui modules otherwise shifter ends with exit code 1.
312 if (grunt.file.expand({cwd: src}, '**/yui/src/**/*.js').length > 0) {
313 args.push('--recursive');
316 grunt.log.ok('No YUI modules to build.');
323 tasks.gherkinlint = function() {
324 var done = this.async(),
325 options = grunt.config('gherkinlint.options');
327 var args = grunt.file.expand(options.files);
328 args.unshift(path.normalize(__dirname + '/node_modules/.bin/gherkin-lint'));
332 opts: {stdio: 'inherit', env: process.env}
333 }, function(error, result, code) {
334 // Propagate the exit code.
339 tasks.startup = function() {
340 // Are we in a YUI directory?
341 if (path.basename(path.resolve(cwd, '../../')) == 'yui') {
342 grunt.task.run('yui');
343 // Are we in an AMD directory?
345 grunt.task.run('amd');
348 grunt.task.run('css');
349 grunt.task.run('js');
350 grunt.task.run('gherkinlint');
354 // On watch, we dynamically modify config to build only affected files. This
355 // method is slightly complicated to deal with multiple changed files at once (copied
356 // from the grunt-contrib-watch readme).
357 var changedFiles = Object.create(null);
358 var onChange = grunt.util._.debounce(function() {
359 var files = Object.keys(changedFiles);
360 grunt.config('eslint.amd.src', files);
361 grunt.config('eslint.yui.src', files);
362 grunt.config('uglify.amd.files', [{expand: true, src: files, rename: uglifyRename}]);
363 grunt.config('shifter.options.paths', files);
364 grunt.config('stylelint.less.src', files);
365 grunt.config('gherkinlint.options.files', files);
366 changedFiles = Object.create(null);
369 grunt.event.on('watch', function(action, filepath) {
370 changedFiles[filepath] = action;
374 // Register NPM tasks.
375 grunt.loadNpmTasks('grunt-contrib-uglify');
376 grunt.loadNpmTasks('grunt-contrib-less');
377 grunt.loadNpmTasks('grunt-contrib-watch');
378 grunt.loadNpmTasks('grunt-sass');
379 grunt.loadNpmTasks('grunt-eslint');
380 grunt.loadNpmTasks('grunt-stylelint');
382 // Register JS tasks.
383 grunt.registerTask('shifter', 'Run Shifter against the current directory', tasks.shifter);
384 grunt.registerTask('gherkinlint', 'Run gherkinlint against the current directory', tasks.gherkinlint);
385 grunt.registerTask('ignorefiles', 'Generate ignore files for linters', tasks.ignorefiles);
386 grunt.registerTask('yui', ['eslint:yui', 'shifter']);
387 grunt.registerTask('amd', ['eslint:amd', 'uglify']);
388 grunt.registerTask('js', ['amd', 'yui']);
390 // Register CSS taks.
391 grunt.registerTask('css', ['stylelint:scss', 'sass', 'stylelint:less', 'less:bootstrapbase', 'stylelint:css']);
393 // Register the startup task.
394 grunt.registerTask('startup', 'Run the correct tasks for the current directory', tasks.startup);
396 // Register the default task.
397 grunt.registerTask('default', ['startup']);