MDL-57945 stylelint: Upgrade 7.12.0
[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)) {
40 grunt.fail.fatal('Node version too old. Require ' + expected + ', version installed: ' + actual);
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')},
be4b3cc6
DP
115 amd: {
116 src: amdSrc,
ad3f8cd1
DP
117 // Check AMD with some slightly stricter rules.
118 rules: {
119 'no-unused-vars': 'error',
120 'no-implicit-globals': 'error'
b18478b9 121 }
be4b3cc6
DP
122 },
123 // Check YUI module source files.
a1587268 124 yui: {
30db70ab 125 src: ['**/yui/src/**/*.js', '!*/**/yui/src/*/meta/*.js'],
ad3f8cd1
DP
126 options: {
127 // Disable some rules which we can't safely define for YUI rollups.
128 rules: {
129 'no-undef': 'off',
130 'no-unused-vars': 'off',
131 'no-unused-expressions': 'off'
132 }
133 }
a1587268 134 }
3adb62b7 135 },
adeb96d2 136 uglify: {
5cc5f311
DP
137 amd: {
138 files: [{
139 expand: true,
140 src: amdSrc,
b18478b9 141 rename: uglifyRename
0e6e1917
DP
142 }],
143 options: {report: 'none'}
adeb96d2 144 }
a4a52e56
DP
145 },
146 less: {
147 bootstrapbase: {
148 files: {
149 "theme/bootstrapbase/style/moodle.css": "theme/bootstrapbase/less/moodle.less",
150 "theme/bootstrapbase/style/editor.css": "theme/bootstrapbase/less/editor.less",
151 },
152 options: {
d99949ab 153 compress: false // We must not compress to keep the comments.
a4a52e56
DP
154 }
155 }
8efbb7b1
DP
156 },
157 watch: {
158 options: {
159 nospawn: true // We need not to spawn so config can be changed dynamically.
160 },
161 amd: {
162 files: ['**/amd/src/**/*.js'],
163 tasks: ['amd']
164 },
165 bootstrapbase: {
166 files: ["theme/bootstrapbase/less/**/*.less"],
855fc5d8 167 tasks: ["css"]
8efbb7b1
DP
168 },
169 yui: {
170 files: ['**/yui/src/**/*.js'],
a1587268 171 tasks: ['yui']
8efbb7b1 172 },
d44f7e46
RT
173 gherkinlint: {
174 files: ['**/tests/behat/*.feature'],
175 tasks: ['gherkinlint']
176 }
1aa454ed
DP
177 },
178 shifter: {
179 options: {
180 recursive: true,
181 paths: [cwd]
182 }
855fc5d8 183 },
8b02e2d9
DP
184 gherkinlint: {
185 options: {
186 files: ['**/tests/behat/*.feature'],
187 }
188 },
855fc5d8
DP
189 stylelint: {
190 less: {
b4fe4e25
DP
191 options: {
192 syntax: 'less',
193 configOverrides: {
194 rules: {
773e68b0
DP
195 // These rules have to be disabled in .stylelintrc for scss compat.
196 "at-rule-no-unknown": true,
b4fe4e25
DP
197 }
198 }
199 },
a26d3673 200 src: ['theme/**/*.less']
773e68b0
DP
201 },
202 scss: {
5142f564 203 options: {syntax: 'scss'},
773e68b0 204 src: ['*/**/*.scss']
d5dff631
DP
205 },
206 css: {
207 src: ['*/**/*.css'],
208 options: {
209 configOverrides: {
210 rules: {
211 // These rules have to be disabled in .stylelintrc for scss compat.
212 "at-rule-no-unknown": true,
d5dff631
DP
213 }
214 }
215 }
855fc5d8 216 }
adeb96d2
DW
217 }
218 });
219
30db70ab
DP
220 /**
221 * Generate ignore files (utilising thirdpartylibs.xml data)
222 */
223 tasks.ignorefiles = function() {
f8731225
DP
224 // An array of paths to third party directories.
225 var thirdPartyPaths = getThirdPartyPathsFromXML();
30db70ab
DP
226 // Generate .eslintignore.
227 var eslintIgnores = ['# Generated by "grunt ignorefiles"', '*/**/yui/src/*/meta/', '*/**/build/'].concat(thirdPartyPaths);
228 grunt.file.write('.eslintignore', eslintIgnores.join('\n'));
a26d3673 229 // Generate .stylelintignore.
36650f11
DP
230 var stylelintIgnores = [
231 '# Generated by "grunt ignorefiles"',
232 'theme/bootstrapbase/style/',
233 'theme/clean/style/custom.css',
234 'theme/more/style/custom.css'
235 ].concat(thirdPartyPaths);
a26d3673 236 grunt.file.write('.stylelintignore', stylelintIgnores.join('\n'));
30db70ab
DP
237 };
238
1aa454ed
DP
239 /**
240 * Shifter task. Is configured with a path to a specific file or a directory,
241 * in the case of a specific file it will work out the right module to be built.
242 *
243 * Note that this task runs the invidiaul shifter jobs async (becase it spawns
244 * so be careful to to call done().
245 */
adeb96d2 246 tasks.shifter = function() {
30db70ab 247 var done = this.async(),
1aa454ed 248 options = grunt.config('shifter.options');
adeb96d2 249
1aa454ed 250 // Run the shifter processes one at a time to avoid confusing output.
b18478b9 251 async.eachSeries(options.paths, function(src, filedone) {
1aa454ed 252 var args = [];
b18478b9 253 args.push(path.normalize(__dirname + '/node_modules/shifter/bin/shifter'));
e67585f8 254
1aa454ed
DP
255 // Always ignore the node_modules directory.
256 args.push('--excludes', 'node_modules');
257
adeb96d2 258 // Determine the most appropriate options to run with based upon the current location.
1aa454ed
DP
259 if (grunt.file.isMatch('**/yui/**/*.js', src)) {
260 // When passed a JS file, build our containing module (this happen with
261 // watch).
262 grunt.log.debug('Shifter passed a specific JS file');
263 src = path.dirname(path.dirname(src));
264 options.recursive = false;
265 } else if (grunt.file.isMatch('**/yui/src', src)) {
266 // When in a src directory --walk all modules.
adeb96d2
DW
267 grunt.log.debug('In a src directory');
268 args.push('--walk');
1aa454ed
DP
269 options.recursive = false;
270 } else if (grunt.file.isMatch('**/yui/src/*', src)) {
271 // When in module, only build our module.
adeb96d2 272 grunt.log.debug('In a module directory');
adeb96d2 273 options.recursive = false;
1aa454ed
DP
274 } else if (grunt.file.isMatch('**/yui/src/*/js', src)) {
275 // When in module src, only build our module.
276 grunt.log.debug('In a source directory');
277 src = path.dirname(src);
278 options.recursive = false;
adeb96d2
DW
279 }
280
1aa454ed
DP
281 if (grunt.option('watch')) {
282 grunt.fail.fatal('The --watch option has been removed, please use `grunt watch` instead');
adeb96d2
DW
283 }
284
adeb96d2
DW
285 // Add the stderr option if appropriate
286 if (grunt.option('verbose')) {
287 args.push('--lint-stderr');
288 }
289
a07afffc
DP
290 if (grunt.option('no-color')) {
291 args.push('--color=false');
292 }
293
8f76bfb6
DM
294 var execShifter = function() {
295
1aa454ed
DP
296 grunt.log.ok("Running shifter on " + src);
297 grunt.util.spawn({
298 cmd: "node",
299 args: args,
300 opts: {cwd: src, stdio: 'inherit', env: process.env}
b18478b9 301 }, function(error, result, code) {
8f76bfb6
DM
302 if (code) {
303 grunt.fail.fatal('Shifter failed with code: ' + code);
304 } else {
305 grunt.log.ok('Shifter build complete.');
1aa454ed 306 filedone();
8f76bfb6
DM
307 }
308 });
309 };
310
adeb96d2 311 // Actually run shifter.
8f76bfb6
DM
312 if (!options.recursive) {
313 execShifter();
314 } else {
315 // Check that there are yui modules otherwise shifter ends with exit code 1.
1aa454ed
DP
316 if (grunt.file.expand({cwd: src}, '**/yui/src/**/*.js').length > 0) {
317 args.push('--recursive');
318 execShifter();
319 } else {
320 grunt.log.ok('No YUI modules to build.');
321 filedone();
322 }
8f76bfb6 323 }
1aa454ed 324 }, done);
adeb96d2
DW
325 };
326
8b02e2d9
DP
327 tasks.gherkinlint = function() {
328 var done = this.async(),
329 options = grunt.config('gherkinlint.options');
330
331 var args = grunt.file.expand(options.files);
332 args.unshift(path.normalize(__dirname + '/node_modules/.bin/gherkin-lint'));
333 grunt.util.spawn({
334 cmd: 'node',
335 args: args,
336 opts: {stdio: 'inherit', env: process.env}
337 }, function(error, result, code) {
338 // Propagate the exit code.
58923606 339 done(code === 0);
8b02e2d9
DP
340 });
341 };
342
adeb96d2
DW
343 tasks.startup = function() {
344 // Are we in a YUI directory?
e67585f8 345 if (path.basename(path.resolve(cwd, '../../')) == 'yui') {
a1587268 346 grunt.task.run('yui');
adeb96d2 347 // Are we in an AMD directory?
c9b6feea 348 } else if (inAMD) {
65d070ae 349 grunt.task.run('amd');
adeb96d2
DW
350 } else {
351 // Run them all!.
65d070ae
DP
352 grunt.task.run('css');
353 grunt.task.run('js');
d44f7e46 354 grunt.task.run('gherkinlint');
adeb96d2
DW
355 }
356 };
357
1aa454ed
DP
358 // On watch, we dynamically modify config to build only affected files. This
359 // method is slightly complicated to deal with multiple changed files at once (copied
360 // from the grunt-contrib-watch readme).
361 var changedFiles = Object.create(null);
362 var onChange = grunt.util._.debounce(function() {
363 var files = Object.keys(changedFiles);
a382101c
DP
364 grunt.config('eslint.amd.src', files);
365 grunt.config('eslint.yui.src', files);
70db37ba 366 grunt.config('uglify.amd.files', [{expand: true, src: files, rename: uglifyRename}]);
1aa454ed 367 grunt.config('shifter.options.paths', files);
855fc5d8 368 grunt.config('stylelint.less.src', files);
d44f7e46 369 grunt.config('gherkinlint.options.files', files);
1aa454ed
DP
370 changedFiles = Object.create(null);
371 }, 200);
adeb96d2 372
8efbb7b1 373 grunt.event.on('watch', function(action, filepath) {
1aa454ed
DP
374 changedFiles[filepath] = action;
375 onChange();
8efbb7b1
DP
376 });
377
adeb96d2
DW
378 // Register NPM tasks.
379 grunt.loadNpmTasks('grunt-contrib-uglify');
a4a52e56 380 grunt.loadNpmTasks('grunt-contrib-less');
8efbb7b1 381 grunt.loadNpmTasks('grunt-contrib-watch');
3adb62b7 382 grunt.loadNpmTasks('grunt-eslint');
855fc5d8 383 grunt.loadNpmTasks('grunt-stylelint');
adeb96d2 384
65d070ae 385 // Register JS tasks.
adeb96d2 386 grunt.registerTask('shifter', 'Run Shifter against the current directory', tasks.shifter);
8b02e2d9 387 grunt.registerTask('gherkinlint', 'Run gherkinlint against the current directory', tasks.gherkinlint);
30db70ab 388 grunt.registerTask('ignorefiles', 'Generate ignore files for linters', tasks.ignorefiles);
a1587268 389 grunt.registerTask('yui', ['eslint:yui', 'shifter']);
5f4d957c 390 grunt.registerTask('amd', ['eslint:amd', 'uglify']);
a1587268 391 grunt.registerTask('js', ['amd', 'yui']);
65d070ae
DP
392
393 // Register CSS taks.
d5dff631 394 grunt.registerTask('css', ['stylelint:scss', 'stylelint:less', 'less:bootstrapbase', 'stylelint:css']);
adeb96d2
DW
395
396 // Register the startup task.
397 grunt.registerTask('startup', 'Run the correct tasks for the current directory', tasks.startup);
398
399 // Register the default task.
400 grunt.registerTask('default', ['startup']);
401};