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');
35 // Windows users can't run grunt in a subdirectory, so allow them to set
36 // the root by passing --root=path/to/dir.
37 if (grunt.option('root')) {
38 var root = grunt.option('root');
39 if (grunt.file.exists(__dirname, root)) {
40 cwd = path.join(__dirname, root);
41 grunt.log.ok('Setting root to ' + cwd);
43 grunt.fail.fatal('Setting root to ' + root + ' failed - path does not exist');
47 var inAMD = path.basename(cwd) == 'amd';
49 // Globbing pattern for matching all AMD JS source files.
50 var amdSrc = [inAMD ? cwd + '/src/*.js' : '**/amd/src/*.js'];
53 * Function to generate the destination for the uglify task
54 * (e.g. build/file.min.js). This function will be passed to
55 * the rename property of files array when building dynamically:
56 * http://gruntjs.com/configuring-tasks#building-the-files-object-dynamically
58 * @param {String} destPath the current destination
59 * @param {String} srcPath the matched src path
60 * @return {String} The rewritten destination path.
62 var uglifyRename = function(destPath, srcPath) {
63 destPath = srcPath.replace('src', 'build');
64 destPath = destPath.replace('.js', '.min.js');
65 destPath = path.resolve(cwd, destPath);
70 * Find thirdpartylibs.xml and generate an array of paths contained within
71 * them (used to generate ignore files and so on).
73 * @return {array} The list of thirdparty paths.
75 var getThirdPartyPathsFromXML = function() {
76 var thirdpartyfiles = grunt.file.expand('*/**/thirdpartylibs.xml');
77 var libs = ['node_modules/', 'vendor/'];
79 thirdpartyfiles.forEach(function(file) {
80 var dirname = path.dirname(file);
82 var doc = new DOMParser().parseFromString(grunt.file.read(file));
83 var nodes = xpath.select("/libraries/library/location/text()", doc);
85 nodes.forEach(function(node) {
86 var lib = path.join(dirname, node.toString());
87 if (grunt.file.isDir(lib)) {
88 // Ensure trailing slash on dirs.
89 lib = lib.replace(/\/?$/, '/');
92 // Look for duplicate paths before adding to array.
93 if (libs.indexOf(lib) === -1) {
101 // An array of paths to third party directories.
102 var thirdPartyPaths = getThirdPartyPathsFromXML();
105 * Determine if the file is a Moodle file, or its listed in
106 * the thirdpartylibs.xml file paths as a third party file.
108 * @param {string} file The file path to determine if thirdparty
109 * @return {bool} false If thid party file.
111 var isMoodleFile = function(file) {
112 if (grunt.file.isMatch(thirdPartyPaths, file)) {
118 // Project configuration.
121 options: {jshintrc: '.jshintrc'},
125 // Even though warnings dont stop the build we don't display warnings by default because
126 // at this moment we've got too many core warnings.
127 options: { quiet: !grunt.option('show-lint-warnings') },
128 // Check AMD files. We add some stricter rules which we can't apply to the default configuration due
132 filter: isMoodleFile,
134 rules: {'no-undef': 'error', 'no-unused-vars': 'error', 'no-empty': 'error', 'no-unused-expressions': 'error'}
137 // Check YUI module source files.
139 src: ['**/yui/src/**/*.js', '!*/**/yui/src/*/meta/*.js'],
155 "theme/bootstrapbase/style/moodle.css": "theme/bootstrapbase/less/moodle.less",
156 "theme/bootstrapbase/style/editor.css": "theme/bootstrapbase/less/editor.less",
165 nospawn: true // We need not to spawn so config can be changed dynamically.
168 files: ['**/amd/src/**/*.js'],
172 files: ["theme/bootstrapbase/less/**/*.less"],
173 tasks: ["less:bootstrapbase"]
176 files: ['**/yui/src/**/*.js'],
189 * Generate ignore files (utilising thirdpartylibs.xml data)
191 tasks.ignorefiles = function() {
192 // Generate .eslintignore.
193 var eslintIgnores = ['# Generated by "grunt ignorefiles"', '*/**/yui/src/*/meta/', '*/**/build/'].concat(thirdPartyPaths);
194 grunt.file.write('.eslintignore', eslintIgnores.join('\n'));
198 * Shifter task. Is configured with a path to a specific file or a directory,
199 * in the case of a specific file it will work out the right module to be built.
201 * Note that this task runs the invidiaul shifter jobs async (becase it spawns
202 * so be careful to to call done().
204 tasks.shifter = function() {
205 var done = this.async(),
206 options = grunt.config('shifter.options');
208 // Run the shifter processes one at a time to avoid confusing output.
209 async.eachSeries(options.paths, function(src, filedone) {
211 args.push(path.normalize(__dirname + '/node_modules/shifter/bin/shifter'));
213 // Always ignore the node_modules directory.
214 args.push('--excludes', 'node_modules');
216 // Determine the most appropriate options to run with based upon the current location.
217 if (grunt.file.isMatch('**/yui/**/*.js', src)) {
218 // When passed a JS file, build our containing module (this happen with
220 grunt.log.debug('Shifter passed a specific JS file');
221 src = path.dirname(path.dirname(src));
222 options.recursive = false;
223 } else if (grunt.file.isMatch('**/yui/src', src)) {
224 // When in a src directory --walk all modules.
225 grunt.log.debug('In a src directory');
227 options.recursive = false;
228 } else if (grunt.file.isMatch('**/yui/src/*', src)) {
229 // When in module, only build our module.
230 grunt.log.debug('In a module directory');
231 options.recursive = false;
232 } else if (grunt.file.isMatch('**/yui/src/*/js', src)) {
233 // When in module src, only build our module.
234 grunt.log.debug('In a source directory');
235 src = path.dirname(src);
236 options.recursive = false;
239 if (grunt.option('watch')) {
240 grunt.fail.fatal('The --watch option has been removed, please use `grunt watch` instead');
243 // Add the stderr option if appropriate
244 if (grunt.option('verbose')) {
245 args.push('--lint-stderr');
248 if (grunt.option('no-color')) {
249 args.push('--color=false');
252 var execShifter = function() {
254 grunt.log.ok("Running shifter on " + src);
258 opts: {cwd: src, stdio: 'inherit', env: process.env}
259 }, function(error, result, code) {
261 grunt.fail.fatal('Shifter failed with code: ' + code);
263 grunt.log.ok('Shifter build complete.');
269 // Actually run shifter.
270 if (!options.recursive) {
273 // Check that there are yui modules otherwise shifter ends with exit code 1.
274 if (grunt.file.expand({cwd: src}, '**/yui/src/**/*.js').length > 0) {
275 args.push('--recursive');
278 grunt.log.ok('No YUI modules to build.');
285 tasks.startup = function() {
286 // Are we in a YUI directory?
287 if (path.basename(path.resolve(cwd, '../../')) == 'yui') {
288 grunt.task.run('yui');
289 // Are we in an AMD directory?
291 grunt.task.run('amd');
294 grunt.task.run('css');
295 grunt.task.run('js');
299 // On watch, we dynamically modify config to build only affected files. This
300 // method is slightly complicated to deal with multiple changed files at once (copied
301 // from the grunt-contrib-watch readme).
302 var changedFiles = Object.create(null);
303 var onChange = grunt.util._.debounce(function() {
304 var files = Object.keys(changedFiles);
305 grunt.config('jshint.amd.src', files);
306 grunt.config('uglify.amd.files', [{ expand: true, src: files, rename: uglifyRename }]);
307 grunt.config('shifter.options.paths', files);
308 changedFiles = Object.create(null);
311 grunt.event.on('watch', function(action, filepath) {
312 changedFiles[filepath] = action;
316 // Register NPM tasks.
317 grunt.loadNpmTasks('grunt-contrib-uglify');
318 grunt.loadNpmTasks('grunt-contrib-jshint');
319 grunt.loadNpmTasks('grunt-contrib-less');
320 grunt.loadNpmTasks('grunt-contrib-watch');
321 grunt.loadNpmTasks('grunt-eslint');
323 // Register JS tasks.
324 grunt.registerTask('shifter', 'Run Shifter against the current directory', tasks.shifter);
325 grunt.registerTask('ignorefiles', 'Generate ignore files for linters', tasks.ignorefiles);
326 grunt.registerTask('yui', ['eslint:yui', 'shifter']);
327 grunt.registerTask('amd', ['eslint:amd', 'jshint', 'uglify']);
328 grunt.registerTask('js', ['amd', 'yui']);
330 // Register CSS taks.
331 grunt.registerTask('css', ['less:bootstrapbase']);
333 // Register the startup task.
334 grunt.registerTask('startup', 'Run the correct tasks for the current directory', tasks.startup);
336 // Register the default task.
337 grunt.registerTask('default', ['startup']);