MDL-55465 grunt: Add .stylelintignore
[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,
33 xpath = require('xpath');
00cceb7f
DP
34
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);
b18478b9 41 grunt.log.ok('Setting root to ' + cwd);
00cceb7f 42 } else {
b18478b9 43 grunt.fail.fatal('Setting root to ' + root + ' failed - path does not exist');
00cceb7f
DP
44 }
45 }
46
47 var inAMD = path.basename(cwd) == 'amd';
adeb96d2 48
5cc5f311
DP
49 // Globbing pattern for matching all AMD JS source files.
50 var amdSrc = [inAMD ? cwd + '/src/*.js' : '**/amd/src/*.js'];
51
52 /**
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
57 *
58 * @param {String} destPath the current destination
59 * @param {String} srcPath the matched src path
60 * @return {String} The rewritten destination path.
61 */
b18478b9 62 var uglifyRename = function(destPath, srcPath) {
5cc5f311
DP
63 destPath = srcPath.replace('src', 'build');
64 destPath = destPath.replace('.js', '.min.js');
65 destPath = path.resolve(cwd, destPath);
66 return destPath;
67 };
68
30db70ab
DP
69 /**
70 * Find thirdpartylibs.xml and generate an array of paths contained within
71 * them (used to generate ignore files and so on).
72 *
73 * @return {array} The list of thirdparty paths.
74 */
75 var getThirdPartyPathsFromXML = function() {
76 var thirdpartyfiles = grunt.file.expand('*/**/thirdpartylibs.xml');
77 var libs = ['node_modules/', 'vendor/'];
78
b18478b9 79 thirdpartyfiles.forEach(function(file) {
30db70ab
DP
80 var dirname = path.dirname(file);
81
82 var doc = new DOMParser().parseFromString(grunt.file.read(file));
83 var nodes = xpath.select("/libraries/library/location/text()", doc);
84
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(/\/?$/, '/');
90 }
91
92 // Look for duplicate paths before adding to array.
93 if (libs.indexOf(lib) === -1) {
94 libs.push(lib);
95 }
96 });
97 });
98 return libs;
99 };
100
30db70ab 101
adeb96d2
DW
102 // Project configuration.
103 grunt.initConfig({
3adb62b7 104 eslint: {
30db70ab
DP
105 // Even though warnings dont stop the build we don't display warnings by default because
106 // at this moment we've got too many core warnings.
037de719 107 options: {quiet: !grunt.option('show-lint-warnings')},
be4b3cc6
DP
108 amd: {
109 src: amdSrc,
ad3f8cd1
DP
110 // Check AMD with some slightly stricter rules.
111 rules: {
112 'no-unused-vars': 'error',
113 'no-implicit-globals': 'error'
b18478b9 114 }
be4b3cc6
DP
115 },
116 // Check YUI module source files.
a1587268 117 yui: {
30db70ab 118 src: ['**/yui/src/**/*.js', '!*/**/yui/src/*/meta/*.js'],
ad3f8cd1
DP
119 options: {
120 // Disable some rules which we can't safely define for YUI rollups.
121 rules: {
122 'no-undef': 'off',
123 'no-unused-vars': 'off',
124 'no-unused-expressions': 'off'
125 }
126 }
a1587268 127 }
3adb62b7 128 },
adeb96d2 129 uglify: {
5cc5f311
DP
130 amd: {
131 files: [{
132 expand: true,
133 src: amdSrc,
b18478b9 134 rename: uglifyRename
0e6e1917
DP
135 }],
136 options: {report: 'none'}
adeb96d2 137 }
a4a52e56
DP
138 },
139 less: {
140 bootstrapbase: {
141 files: {
142 "theme/bootstrapbase/style/moodle.css": "theme/bootstrapbase/less/moodle.less",
143 "theme/bootstrapbase/style/editor.css": "theme/bootstrapbase/less/editor.less",
144 },
145 options: {
146 compress: true
147 }
148 }
8efbb7b1
DP
149 },
150 watch: {
151 options: {
152 nospawn: true // We need not to spawn so config can be changed dynamically.
153 },
154 amd: {
155 files: ['**/amd/src/**/*.js'],
156 tasks: ['amd']
157 },
158 bootstrapbase: {
159 files: ["theme/bootstrapbase/less/**/*.less"],
855fc5d8 160 tasks: ["css"]
8efbb7b1
DP
161 },
162 yui: {
163 files: ['**/yui/src/**/*.js'],
a1587268 164 tasks: ['yui']
8efbb7b1 165 },
1aa454ed
DP
166 },
167 shifter: {
168 options: {
169 recursive: true,
170 paths: [cwd]
171 }
855fc5d8
DP
172 },
173 stylelint: {
174 less: {
b4fe4e25
DP
175 options: {
176 syntax: 'less',
177 configOverrides: {
178 rules: {
179 // TODO: MDL-55165 -Enable these rules once we make output-changing changes to less.
180 "declaration-block-no-ignored-properties": null,
181 "value-keyword-case": null,
182 "declaration-block-no-duplicate-properties": null,
183 "declaration-block-no-shorthand-property-overrides": null,
184 "selector-type-no-unknown": null,
185 "length-zero-no-unit": null,
186 "color-hex-case": null,
187 "color-hex-length": null
188 }
189 }
190 },
a26d3673 191 src: ['theme/**/*.less']
855fc5d8 192 }
adeb96d2
DW
193 }
194 });
195
30db70ab
DP
196 /**
197 * Generate ignore files (utilising thirdpartylibs.xml data)
198 */
199 tasks.ignorefiles = function() {
f8731225
DP
200 // An array of paths to third party directories.
201 var thirdPartyPaths = getThirdPartyPathsFromXML();
30db70ab
DP
202 // Generate .eslintignore.
203 var eslintIgnores = ['# Generated by "grunt ignorefiles"', '*/**/yui/src/*/meta/', '*/**/build/'].concat(thirdPartyPaths);
204 grunt.file.write('.eslintignore', eslintIgnores.join('\n'));
a26d3673
DP
205 // Generate .stylelintignore.
206 var stylelintIgnores = ['# Generated by "grunt ignorefiles"', 'theme/bootstrapbase/style/'].concat(thirdPartyPaths);
207 grunt.file.write('.stylelintignore', stylelintIgnores.join('\n'));
30db70ab
DP
208 };
209
1aa454ed
DP
210 /**
211 * Shifter task. Is configured with a path to a specific file or a directory,
212 * in the case of a specific file it will work out the right module to be built.
213 *
214 * Note that this task runs the invidiaul shifter jobs async (becase it spawns
215 * so be careful to to call done().
216 */
adeb96d2 217 tasks.shifter = function() {
30db70ab 218 var done = this.async(),
1aa454ed 219 options = grunt.config('shifter.options');
adeb96d2 220
1aa454ed 221 // Run the shifter processes one at a time to avoid confusing output.
b18478b9 222 async.eachSeries(options.paths, function(src, filedone) {
1aa454ed 223 var args = [];
b18478b9 224 args.push(path.normalize(__dirname + '/node_modules/shifter/bin/shifter'));
e67585f8 225
1aa454ed
DP
226 // Always ignore the node_modules directory.
227 args.push('--excludes', 'node_modules');
228
adeb96d2 229 // Determine the most appropriate options to run with based upon the current location.
1aa454ed
DP
230 if (grunt.file.isMatch('**/yui/**/*.js', src)) {
231 // When passed a JS file, build our containing module (this happen with
232 // watch).
233 grunt.log.debug('Shifter passed a specific JS file');
234 src = path.dirname(path.dirname(src));
235 options.recursive = false;
236 } else if (grunt.file.isMatch('**/yui/src', src)) {
237 // When in a src directory --walk all modules.
adeb96d2
DW
238 grunt.log.debug('In a src directory');
239 args.push('--walk');
1aa454ed
DP
240 options.recursive = false;
241 } else if (grunt.file.isMatch('**/yui/src/*', src)) {
242 // When in module, only build our module.
adeb96d2 243 grunt.log.debug('In a module directory');
adeb96d2 244 options.recursive = false;
1aa454ed
DP
245 } else if (grunt.file.isMatch('**/yui/src/*/js', src)) {
246 // When in module src, only build our module.
247 grunt.log.debug('In a source directory');
248 src = path.dirname(src);
249 options.recursive = false;
adeb96d2
DW
250 }
251
1aa454ed
DP
252 if (grunt.option('watch')) {
253 grunt.fail.fatal('The --watch option has been removed, please use `grunt watch` instead');
adeb96d2
DW
254 }
255
adeb96d2
DW
256 // Add the stderr option if appropriate
257 if (grunt.option('verbose')) {
258 args.push('--lint-stderr');
259 }
260
a07afffc
DP
261 if (grunt.option('no-color')) {
262 args.push('--color=false');
263 }
264
8f76bfb6
DM
265 var execShifter = function() {
266
1aa454ed
DP
267 grunt.log.ok("Running shifter on " + src);
268 grunt.util.spawn({
269 cmd: "node",
270 args: args,
271 opts: {cwd: src, stdio: 'inherit', env: process.env}
b18478b9 272 }, function(error, result, code) {
8f76bfb6
DM
273 if (code) {
274 grunt.fail.fatal('Shifter failed with code: ' + code);
275 } else {
276 grunt.log.ok('Shifter build complete.');
1aa454ed 277 filedone();
8f76bfb6
DM
278 }
279 });
280 };
281
adeb96d2 282 // Actually run shifter.
8f76bfb6
DM
283 if (!options.recursive) {
284 execShifter();
285 } else {
286 // Check that there are yui modules otherwise shifter ends with exit code 1.
1aa454ed
DP
287 if (grunt.file.expand({cwd: src}, '**/yui/src/**/*.js').length > 0) {
288 args.push('--recursive');
289 execShifter();
290 } else {
291 grunt.log.ok('No YUI modules to build.');
292 filedone();
293 }
8f76bfb6 294 }
1aa454ed 295 }, done);
adeb96d2
DW
296 };
297
298 tasks.startup = function() {
299 // Are we in a YUI directory?
e67585f8 300 if (path.basename(path.resolve(cwd, '../../')) == 'yui') {
a1587268 301 grunt.task.run('yui');
adeb96d2 302 // Are we in an AMD directory?
c9b6feea 303 } else if (inAMD) {
65d070ae 304 grunt.task.run('amd');
adeb96d2
DW
305 } else {
306 // Run them all!.
65d070ae
DP
307 grunt.task.run('css');
308 grunt.task.run('js');
adeb96d2
DW
309 }
310 };
311
1aa454ed
DP
312 // On watch, we dynamically modify config to build only affected files. This
313 // method is slightly complicated to deal with multiple changed files at once (copied
314 // from the grunt-contrib-watch readme).
315 var changedFiles = Object.create(null);
316 var onChange = grunt.util._.debounce(function() {
317 var files = Object.keys(changedFiles);
a382101c
DP
318 grunt.config('eslint.amd.src', files);
319 grunt.config('eslint.yui.src', files);
b18478b9 320 grunt.config('uglify.amd.files', [{ expand: true, src: files, rename: uglifyRename }]);
1aa454ed 321 grunt.config('shifter.options.paths', files);
855fc5d8 322 grunt.config('stylelint.less.src', files);
1aa454ed
DP
323 changedFiles = Object.create(null);
324 }, 200);
adeb96d2 325
8efbb7b1 326 grunt.event.on('watch', function(action, filepath) {
1aa454ed
DP
327 changedFiles[filepath] = action;
328 onChange();
8efbb7b1
DP
329 });
330
adeb96d2
DW
331 // Register NPM tasks.
332 grunt.loadNpmTasks('grunt-contrib-uglify');
a4a52e56 333 grunt.loadNpmTasks('grunt-contrib-less');
8efbb7b1 334 grunt.loadNpmTasks('grunt-contrib-watch');
3adb62b7 335 grunt.loadNpmTasks('grunt-eslint');
855fc5d8 336 grunt.loadNpmTasks('grunt-stylelint');
adeb96d2 337
65d070ae 338 // Register JS tasks.
adeb96d2 339 grunt.registerTask('shifter', 'Run Shifter against the current directory', tasks.shifter);
30db70ab 340 grunt.registerTask('ignorefiles', 'Generate ignore files for linters', tasks.ignorefiles);
a1587268 341 grunt.registerTask('yui', ['eslint:yui', 'shifter']);
5f4d957c 342 grunt.registerTask('amd', ['eslint:amd', 'uglify']);
a1587268 343 grunt.registerTask('js', ['amd', 'yui']);
65d070ae
DP
344
345 // Register CSS taks.
855fc5d8 346 grunt.registerTask('css', ['stylelint:less', 'less:bootstrapbase']);
adeb96d2
DW
347
348 // Register the startup task.
349 grunt.registerTask('startup', 'Run the correct tasks for the current directory', tasks.startup);
350
351 // Register the default task.
352 grunt.registerTask('default', ['startup']);
353};