MDL-62497 javascript: add babel polyfill for es6 support
[moodle.git] / Gruntfile.js
CommitLineData
adeb96d2
DW
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.
12//
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/>.
0b777a06 15/* jshint node: true, browser: false */
3adb62b7 16/* eslint-env node */
adeb96d2
DW
17
18/**
19 * @copyright 2014 Andrew Nicols
20 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
21 */
22
23/**
24 * Grunt configuration
25 */
26
27module.exports = function(grunt) {
28 var path = require('path'),
e67585f8 29 tasks = {},
30db70ab
DP
30 cwd = process.env.PWD || process.cwd(),
31 async = require('async'),
32 DOMParser = require('xmldom').DOMParser,
d2c7175a
DP
33 xpath = require('xpath'),
34 semver = require('semver');
35
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)) {
fbd1877f 40 grunt.fail.fatal('Node version not satisfied. Require ' + expected + ', version installed: ' + actual);
d2c7175a 41 }
00cceb7f
DP
42
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);
b18478b9 49 grunt.log.ok('Setting root to ' + cwd);
00cceb7f 50 } else {
b18478b9 51 grunt.fail.fatal('Setting root to ' + root + ' failed - path does not exist');
00cceb7f
DP
52 }
53 }
54
55 var inAMD = path.basename(cwd) == 'amd';
adeb96d2 56
5cc5f311
DP
57 // Globbing pattern for matching all AMD JS source files.
58 var amdSrc = [inAMD ? cwd + '/src/*.js' : '**/amd/src/*.js'];
59
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 */
b18478b9 70 var uglifyRename = function(destPath, srcPath) {
5cc5f311
DP
71 destPath = srcPath.replace('src', 'build');
72 destPath = destPath.replace('.js', '.min.js');
73 destPath = path.resolve(cwd, destPath);
74 return destPath;
75 };
76
30db70ab
DP
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/'];
86
b18478b9 87 thirdpartyfiles.forEach(function(file) {
30db70ab
DP
88 var dirname = path.dirname(file);
89
90 var doc = new DOMParser().parseFromString(grunt.file.read(file));
91 var nodes = xpath.select("/libraries/library/location/text()", doc);
92
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 }
99
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 };
108
adeb96d2
DW
109 // Project configuration.
110 grunt.initConfig({
3adb62b7 111 eslint: {
30db70ab
DP
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.
037de719 114 options: {quiet: !grunt.option('show-lint-warnings')},
6f601313 115 amd: {src: amdSrc},
be4b3cc6 116 // Check YUI module source files.
6f601313 117 yui: {src: ['**/yui/src/**/*.js', '!*/**/yui/src/*/meta/*.js']}
3adb62b7 118 },
adeb96d2 119 uglify: {
5cc5f311
DP
120 amd: {
121 files: [{
122 expand: true,
123 src: amdSrc,
b18478b9 124 rename: uglifyRename
0e6e1917
DP
125 }],
126 options: {report: 'none'}
adeb96d2 127 }
a4a52e56 128 },
af9edb2e
BB
129 sass: {
130 dist: {
131 files: {
de213bf0
BB
132 "theme/boost/style/moodle.css": "theme/boost/scss/preset/default.scss",
133 "theme/classic/style/moodle.css": "theme/classic/scss/classicgrunt.scss"
af9edb2e
BB
134 }
135 },
136 options: {
de213bf0 137 includePaths: ["theme/boost/scss/", "theme/classic/scss/"]
af9edb2e
BB
138 }
139 },
8efbb7b1
DP
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 },
8efbb7b1
DP
148 yui: {
149 files: ['**/yui/src/**/*.js'],
a1587268 150 tasks: ['yui']
8efbb7b1 151 },
d44f7e46
RT
152 gherkinlint: {
153 files: ['**/tests/behat/*.feature'],
154 tasks: ['gherkinlint']
155 }
1aa454ed
DP
156 },
157 shifter: {
158 options: {
159 recursive: true,
160 paths: [cwd]
161 }
855fc5d8 162 },
8b02e2d9
DP
163 gherkinlint: {
164 options: {
165 files: ['**/tests/behat/*.feature'],
166 }
167 },
855fc5d8 168 stylelint: {
773e68b0 169 scss: {
5142f564 170 options: {syntax: 'scss'},
773e68b0 171 src: ['*/**/*.scss']
d5dff631
DP
172 },
173 css: {
174 src: ['*/**/*.css'],
175 options: {
176 configOverrides: {
177 rules: {
178 // These rules have to be disabled in .stylelintrc for scss compat.
179 "at-rule-no-unknown": true,
d5dff631
DP
180 }
181 }
182 }
855fc5d8 183 }
adeb96d2
DW
184 }
185 });
186
30db70ab
DP
187 /**
188 * Generate ignore files (utilising thirdpartylibs.xml data)
189 */
190 tasks.ignorefiles = function() {
f8731225
DP
191 // An array of paths to third party directories.
192 var thirdPartyPaths = getThirdPartyPathsFromXML();
30db70ab
DP
193 // Generate .eslintignore.
194 var eslintIgnores = ['# Generated by "grunt ignorefiles"', '*/**/yui/src/*/meta/', '*/**/build/'].concat(thirdPartyPaths);
195 grunt.file.write('.eslintignore', eslintIgnores.join('\n'));
a26d3673 196 // Generate .stylelintignore.
36650f11
DP
197 var stylelintIgnores = [
198 '# Generated by "grunt ignorefiles"',
3951d50a 199 '**/yui/build/*',
de213bf0
BB
200 'theme/boost/style/moodle.css',
201 'theme/classic/style/moodle.css',
36650f11 202 ].concat(thirdPartyPaths);
a26d3673 203 grunt.file.write('.stylelintignore', stylelintIgnores.join('\n'));
30db70ab
DP
204 };
205
1aa454ed
DP
206 /**
207 * Shifter task. Is configured with a path to a specific file or a directory,
208 * in the case of a specific file it will work out the right module to be built.
209 *
210 * Note that this task runs the invidiaul shifter jobs async (becase it spawns
211 * so be careful to to call done().
212 */
adeb96d2 213 tasks.shifter = function() {
30db70ab 214 var done = this.async(),
1aa454ed 215 options = grunt.config('shifter.options');
adeb96d2 216
1aa454ed 217 // Run the shifter processes one at a time to avoid confusing output.
b18478b9 218 async.eachSeries(options.paths, function(src, filedone) {
1aa454ed 219 var args = [];
b18478b9 220 args.push(path.normalize(__dirname + '/node_modules/shifter/bin/shifter'));
e67585f8 221
1aa454ed
DP
222 // Always ignore the node_modules directory.
223 args.push('--excludes', 'node_modules');
224
adeb96d2 225 // Determine the most appropriate options to run with based upon the current location.
1aa454ed
DP
226 if (grunt.file.isMatch('**/yui/**/*.js', src)) {
227 // When passed a JS file, build our containing module (this happen with
228 // watch).
229 grunt.log.debug('Shifter passed a specific JS file');
230 src = path.dirname(path.dirname(src));
231 options.recursive = false;
232 } else if (grunt.file.isMatch('**/yui/src', src)) {
233 // When in a src directory --walk all modules.
adeb96d2
DW
234 grunt.log.debug('In a src directory');
235 args.push('--walk');
1aa454ed
DP
236 options.recursive = false;
237 } else if (grunt.file.isMatch('**/yui/src/*', src)) {
238 // When in module, only build our module.
adeb96d2 239 grunt.log.debug('In a module directory');
adeb96d2 240 options.recursive = false;
1aa454ed
DP
241 } else if (grunt.file.isMatch('**/yui/src/*/js', src)) {
242 // When in module src, only build our module.
243 grunt.log.debug('In a source directory');
244 src = path.dirname(src);
245 options.recursive = false;
adeb96d2
DW
246 }
247
1aa454ed
DP
248 if (grunt.option('watch')) {
249 grunt.fail.fatal('The --watch option has been removed, please use `grunt watch` instead');
adeb96d2
DW
250 }
251
adeb96d2
DW
252 // Add the stderr option if appropriate
253 if (grunt.option('verbose')) {
254 args.push('--lint-stderr');
255 }
256
a07afffc
DP
257 if (grunt.option('no-color')) {
258 args.push('--color=false');
259 }
260
8f76bfb6
DM
261 var execShifter = function() {
262
1aa454ed
DP
263 grunt.log.ok("Running shifter on " + src);
264 grunt.util.spawn({
265 cmd: "node",
266 args: args,
267 opts: {cwd: src, stdio: 'inherit', env: process.env}
b18478b9 268 }, function(error, result, code) {
8f76bfb6
DM
269 if (code) {
270 grunt.fail.fatal('Shifter failed with code: ' + code);
271 } else {
272 grunt.log.ok('Shifter build complete.');
1aa454ed 273 filedone();
8f76bfb6
DM
274 }
275 });
276 };
277
adeb96d2 278 // Actually run shifter.
8f76bfb6
DM
279 if (!options.recursive) {
280 execShifter();
281 } else {
282 // Check that there are yui modules otherwise shifter ends with exit code 1.
1aa454ed
DP
283 if (grunt.file.expand({cwd: src}, '**/yui/src/**/*.js').length > 0) {
284 args.push('--recursive');
285 execShifter();
286 } else {
287 grunt.log.ok('No YUI modules to build.');
288 filedone();
289 }
8f76bfb6 290 }
1aa454ed 291 }, done);
adeb96d2
DW
292 };
293
8b02e2d9
DP
294 tasks.gherkinlint = function() {
295 var done = this.async(),
296 options = grunt.config('gherkinlint.options');
297
298 var args = grunt.file.expand(options.files);
299 args.unshift(path.normalize(__dirname + '/node_modules/.bin/gherkin-lint'));
300 grunt.util.spawn({
301 cmd: 'node',
302 args: args,
303 opts: {stdio: 'inherit', env: process.env}
304 }, function(error, result, code) {
305 // Propagate the exit code.
58923606 306 done(code === 0);
8b02e2d9
DP
307 });
308 };
309
adeb96d2
DW
310 tasks.startup = function() {
311 // Are we in a YUI directory?
e67585f8 312 if (path.basename(path.resolve(cwd, '../../')) == 'yui') {
a1587268 313 grunt.task.run('yui');
adeb96d2 314 // Are we in an AMD directory?
c9b6feea 315 } else if (inAMD) {
65d070ae 316 grunt.task.run('amd');
adeb96d2
DW
317 } else {
318 // Run them all!.
65d070ae
DP
319 grunt.task.run('css');
320 grunt.task.run('js');
d44f7e46 321 grunt.task.run('gherkinlint');
adeb96d2
DW
322 }
323 };
324
1aa454ed
DP
325 // On watch, we dynamically modify config to build only affected files. This
326 // method is slightly complicated to deal with multiple changed files at once (copied
327 // from the grunt-contrib-watch readme).
328 var changedFiles = Object.create(null);
329 var onChange = grunt.util._.debounce(function() {
330 var files = Object.keys(changedFiles);
a382101c
DP
331 grunt.config('eslint.amd.src', files);
332 grunt.config('eslint.yui.src', files);
70db37ba 333 grunt.config('uglify.amd.files', [{expand: true, src: files, rename: uglifyRename}]);
1aa454ed 334 grunt.config('shifter.options.paths', files);
d44f7e46 335 grunt.config('gherkinlint.options.files', files);
1aa454ed
DP
336 changedFiles = Object.create(null);
337 }, 200);
adeb96d2 338
8efbb7b1 339 grunt.event.on('watch', function(action, filepath) {
1aa454ed
DP
340 changedFiles[filepath] = action;
341 onChange();
8efbb7b1
DP
342 });
343
adeb96d2
DW
344 // Register NPM tasks.
345 grunt.loadNpmTasks('grunt-contrib-uglify');
8efbb7b1 346 grunt.loadNpmTasks('grunt-contrib-watch');
af9edb2e 347 grunt.loadNpmTasks('grunt-sass');
3adb62b7 348 grunt.loadNpmTasks('grunt-eslint');
855fc5d8 349 grunt.loadNpmTasks('grunt-stylelint');
adeb96d2 350
65d070ae 351 // Register JS tasks.
adeb96d2 352 grunt.registerTask('shifter', 'Run Shifter against the current directory', tasks.shifter);
8b02e2d9 353 grunt.registerTask('gherkinlint', 'Run gherkinlint against the current directory', tasks.gherkinlint);
30db70ab 354 grunt.registerTask('ignorefiles', 'Generate ignore files for linters', tasks.ignorefiles);
a1587268 355 grunt.registerTask('yui', ['eslint:yui', 'shifter']);
5f4d957c 356 grunt.registerTask('amd', ['eslint:amd', 'uglify']);
a1587268 357 grunt.registerTask('js', ['amd', 'yui']);
65d070ae
DP
358
359 // Register CSS taks.
cf89ac3d 360 grunt.registerTask('css', ['stylelint:scss', 'sass', 'stylelint:css']);
adeb96d2
DW
361
362 // Register the startup task.
363 grunt.registerTask('startup', 'Run the correct tasks for the current directory', tasks.startup);
364
365 // Register the default task.
366 grunt.registerTask('default', ['startup']);
367};