Merge branch 'MDL-62291-master' of git://github.com/junpataleta/moodle
[moodle.git] / Gruntfile.js
blobe0afa2dd8a1e5c9da8da1c8c1317ae15e87d1537
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 module.exports = function(grunt) {
28     var path = require('path'),
29         tasks = {},
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);
41     }
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);
50         } else {
51             grunt.fail.fatal('Setting root to ' + root + ' failed - path does not exist');
52         }
53     }
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'];
60     /**
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
65      *
66      * @param {String} destPath the current destination
67      * @param {String} srcPath the  matched src path
68      * @return {String} The rewritten destination path.
69      */
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);
74         return destPath;
75     };
77     /**
78      * Find thirdpartylibs.xml and generate an array of paths contained within
79      * them (used to generate ignore files and so on).
80      *
81      * @return {array} The list of thirdparty paths.
82      */
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(/\/?$/, '/');
98             }
100             // Look for duplicate paths before adding to array.
101             if (libs.indexOf(lib) === -1) {
102                 libs.push(lib);
103             }
104           });
105         });
106         return libs;
107     };
109     // Project configuration.
110     grunt.initConfig({
111         eslint: {
112             // Even though warnings dont stop the build we don't display warnings by default because
113             // at this moment we've got too many core warnings.
114             options: {quiet: !grunt.option('show-lint-warnings')},
115             amd: {src: amdSrc},
116             // Check YUI module source files.
117             yui: {src: ['**/yui/src/**/*.js', '!*/**/yui/src/*/meta/*.js']}
118         },
119         uglify: {
120             amd: {
121                 files: [{
122                     expand: true,
123                     src: amdSrc,
124                     rename: uglifyRename
125                 }],
126                 options: {report: 'none'}
127             }
128         },
129         less: {
130             bootstrapbase: {
131                 files: {
132                     "theme/bootstrapbase/style/moodle.css": "theme/bootstrapbase/less/moodle.less",
133                     "theme/bootstrapbase/style/editor.css": "theme/bootstrapbase/less/editor.less",
134                 },
135                 options: {
136                     compress: false // We must not compress to keep the comments.
137                 }
138            }
139         },
140         watch: {
141             options: {
142                 nospawn: true // We need not to spawn so config can be changed dynamically.
143             },
144             amd: {
145                 files: ['**/amd/src/**/*.js'],
146                 tasks: ['amd']
147             },
148             bootstrapbase: {
149                 files: ["theme/bootstrapbase/less/**/*.less"],
150                 tasks: ["css"]
151             },
152             yui: {
153                 files: ['**/yui/src/**/*.js'],
154                 tasks: ['yui']
155             },
156             gherkinlint: {
157                 files: ['**/tests/behat/*.feature'],
158                 tasks: ['gherkinlint']
159             }
160         },
161         shifter: {
162             options: {
163                 recursive: true,
164                 paths: [cwd]
165             }
166         },
167         gherkinlint: {
168             options: {
169                 files: ['**/tests/behat/*.feature'],
170             }
171         },
172         stylelint: {
173             less: {
174                 options: {
175                     syntax: 'less',
176                     configOverrides: {
177                         rules: {
178                             // These rules have to be disabled in .stylelintrc for scss compat.
179                             "at-rule-no-unknown": true,
180                         }
181                     }
182                 },
183                 src: ['theme/**/*.less']
184             },
185             scss: {
186                 options: {syntax: 'scss'},
187                 src: ['*/**/*.scss']
188             },
189             css: {
190                 src: ['*/**/*.css'],
191                 options: {
192                     configOverrides: {
193                         rules: {
194                             // These rules have to be disabled in .stylelintrc for scss compat.
195                             "at-rule-no-unknown": true,
196                         }
197                     }
198                 }
199             }
200         }
201     });
203     /**
204      * Generate ignore files (utilising thirdpartylibs.xml data)
205      */
206     tasks.ignorefiles = function() {
207       // An array of paths to third party directories.
208       var thirdPartyPaths = getThirdPartyPathsFromXML();
209       // Generate .eslintignore.
210       var eslintIgnores = ['# Generated by "grunt ignorefiles"', '*/**/yui/src/*/meta/', '*/**/build/'].concat(thirdPartyPaths);
211       grunt.file.write('.eslintignore', eslintIgnores.join('\n'));
212       // Generate .stylelintignore.
213       var stylelintIgnores = [
214           '# Generated by "grunt ignorefiles"',
215           'theme/bootstrapbase/style/',
216           'theme/clean/style/custom.css',
217           'theme/more/style/custom.css'
218       ].concat(thirdPartyPaths);
219       grunt.file.write('.stylelintignore', stylelintIgnores.join('\n'));
220     };
222     /**
223      * Shifter task. Is configured with a path to a specific file or a directory,
224      * in the case of a specific file it will work out the right module to be built.
225      *
226      * Note that this task runs the invidiaul shifter jobs async (becase it spawns
227      * so be careful to to call done().
228      */
229     tasks.shifter = function() {
230         var done = this.async(),
231             options = grunt.config('shifter.options');
233         // Run the shifter processes one at a time to avoid confusing output.
234         async.eachSeries(options.paths, function(src, filedone) {
235             var args = [];
236             args.push(path.normalize(__dirname + '/node_modules/shifter/bin/shifter'));
238             // Always ignore the node_modules directory.
239             args.push('--excludes', 'node_modules');
241             // Determine the most appropriate options to run with based upon the current location.
242             if (grunt.file.isMatch('**/yui/**/*.js', src)) {
243                 // When passed a JS file, build our containing module (this happen with
244                 // watch).
245                 grunt.log.debug('Shifter passed a specific JS file');
246                 src = path.dirname(path.dirname(src));
247                 options.recursive = false;
248             } else if (grunt.file.isMatch('**/yui/src', src)) {
249                 // When in a src directory --walk all modules.
250                 grunt.log.debug('In a src directory');
251                 args.push('--walk');
252                 options.recursive = false;
253             } else if (grunt.file.isMatch('**/yui/src/*', src)) {
254                 // When in module, only build our module.
255                 grunt.log.debug('In a module directory');
256                 options.recursive = false;
257             } else if (grunt.file.isMatch('**/yui/src/*/js', src)) {
258                 // When in module src, only build our module.
259                 grunt.log.debug('In a source directory');
260                 src = path.dirname(src);
261                 options.recursive = false;
262             }
264             if (grunt.option('watch')) {
265                 grunt.fail.fatal('The --watch option has been removed, please use `grunt watch` instead');
266             }
268             // Add the stderr option if appropriate
269             if (grunt.option('verbose')) {
270                 args.push('--lint-stderr');
271             }
273             if (grunt.option('no-color')) {
274                 args.push('--color=false');
275             }
277             var execShifter = function() {
279                 grunt.log.ok("Running shifter on " + src);
280                 grunt.util.spawn({
281                     cmd: "node",
282                     args: args,
283                     opts: {cwd: src, stdio: 'inherit', env: process.env}
284                 }, function(error, result, code) {
285                     if (code) {
286                         grunt.fail.fatal('Shifter failed with code: ' + code);
287                     } else {
288                         grunt.log.ok('Shifter build complete.');
289                         filedone();
290                     }
291                 });
292             };
294             // Actually run shifter.
295             if (!options.recursive) {
296                 execShifter();
297             } else {
298                 // Check that there are yui modules otherwise shifter ends with exit code 1.
299                 if (grunt.file.expand({cwd: src}, '**/yui/src/**/*.js').length > 0) {
300                     args.push('--recursive');
301                     execShifter();
302                 } else {
303                     grunt.log.ok('No YUI modules to build.');
304                     filedone();
305                 }
306             }
307         }, done);
308     };
310     tasks.gherkinlint = function() {
311         var done = this.async(),
312             options = grunt.config('gherkinlint.options');
314         var args = grunt.file.expand(options.files);
315         args.unshift(path.normalize(__dirname + '/node_modules/.bin/gherkin-lint'));
316         grunt.util.spawn({
317             cmd: 'node',
318             args: args,
319             opts: {stdio: 'inherit', env: process.env}
320         }, function(error, result, code) {
321             // Propagate the exit code.
322             done(code === 0);
323         });
324     };
326     tasks.startup = function() {
327         // Are we in a YUI directory?
328         if (path.basename(path.resolve(cwd, '../../')) == 'yui') {
329             grunt.task.run('yui');
330         // Are we in an AMD directory?
331         } else if (inAMD) {
332             grunt.task.run('amd');
333         } else {
334             // Run them all!.
335             grunt.task.run('css');
336             grunt.task.run('js');
337             grunt.task.run('gherkinlint');
338         }
339     };
341     // On watch, we dynamically modify config to build only affected files. This
342     // method is slightly complicated to deal with multiple changed files at once (copied
343     // from the grunt-contrib-watch readme).
344     var changedFiles = Object.create(null);
345     var onChange = grunt.util._.debounce(function() {
346           var files = Object.keys(changedFiles);
347           grunt.config('eslint.amd.src', files);
348           grunt.config('eslint.yui.src', files);
349           grunt.config('uglify.amd.files', [{expand: true, src: files, rename: uglifyRename}]);
350           grunt.config('shifter.options.paths', files);
351           grunt.config('stylelint.less.src', files);
352           grunt.config('gherkinlint.options.files', files);
353           changedFiles = Object.create(null);
354     }, 200);
356     grunt.event.on('watch', function(action, filepath) {
357           changedFiles[filepath] = action;
358           onChange();
359     });
361     // Register NPM tasks.
362     grunt.loadNpmTasks('grunt-contrib-uglify');
363     grunt.loadNpmTasks('grunt-contrib-less');
364     grunt.loadNpmTasks('grunt-contrib-watch');
365     grunt.loadNpmTasks('grunt-eslint');
366     grunt.loadNpmTasks('grunt-stylelint');
368     // Register JS tasks.
369     grunt.registerTask('shifter', 'Run Shifter against the current directory', tasks.shifter);
370     grunt.registerTask('gherkinlint', 'Run gherkinlint against the current directory', tasks.gherkinlint);
371     grunt.registerTask('ignorefiles', 'Generate ignore files for linters', tasks.ignorefiles);
372     grunt.registerTask('yui', ['eslint:yui', 'shifter']);
373     grunt.registerTask('amd', ['eslint:amd', 'uglify']);
374     grunt.registerTask('js', ['amd', 'yui']);
376     // Register CSS taks.
377     grunt.registerTask('css', ['stylelint:scss', 'stylelint:less', 'less:bootstrapbase', 'stylelint:css']);
379     // Register the startup task.
380     grunt.registerTask('startup', 'Run the correct tasks for the current directory', tasks.startup);
382     // Register the default task.
383     grunt.registerTask('default', ['startup']);