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