MDL-36580 backup: Use the encrypted_final_element for lti "secrets"
[moodle.git] / Gruntfile.js
blob5f2302e456260e4b5645d8154c6a337a43ae2e2c
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: {
116               src: amdSrc,
117               // Check AMD with some slightly stricter rules.
118               rules: {
119                 'no-unused-vars': 'error',
120                 'no-implicit-globals': 'error'
121               }
122             },
123             // Check YUI module source files.
124             yui: {
125                src: ['**/yui/src/**/*.js', '!*/**/yui/src/*/meta/*.js'],
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                }
134             }
135         },
136         uglify: {
137             amd: {
138                 files: [{
139                     expand: true,
140                     src: amdSrc,
141                     rename: uglifyRename
142                 }],
143                 options: {report: 'none'}
144             }
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: {
153                     compress: false // We must not compress to keep the comments.
154                 }
155            }
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"],
167                 tasks: ["css"]
168             },
169             yui: {
170                 files: ['**/yui/src/**/*.js'],
171                 tasks: ['yui']
172             },
173             gherkinlint: {
174                 files: ['**/tests/behat/*.feature'],
175                 tasks: ['gherkinlint']
176             }
177         },
178         shifter: {
179             options: {
180                 recursive: true,
181                 paths: [cwd]
182             }
183         },
184         gherkinlint: {
185             options: {
186                 files: ['**/tests/behat/*.feature'],
187             }
188         },
189         stylelint: {
190             less: {
191                 options: {
192                     syntax: 'less',
193                     configOverrides: {
194                         rules: {
195                             // These rules have to be disabled in .stylelintrc for scss compat.
196                             "at-rule-no-unknown": true,
197                             "no-browser-hacks": [true, {"severity": "warning"}]
198                         }
199                     }
200                 },
201                 src: ['theme/**/*.less']
202             },
203             scss: {
204                 options: {syntax: 'scss'},
205                 src: ['*/**/*.scss']
206             },
207             css: {
208                 src: ['*/**/*.css'],
209                 options: {
210                     configOverrides: {
211                         rules: {
212                             // These rules have to be disabled in .stylelintrc for scss compat.
213                             "at-rule-no-unknown": true,
214                             "no-browser-hacks": [true, {"severity": "warning"}]
215                         }
216                     }
217                 }
218             }
219         }
220     });
222     /**
223      * Generate ignore files (utilising thirdpartylibs.xml data)
224      */
225     tasks.ignorefiles = function() {
226       // An array of paths to third party directories.
227       var thirdPartyPaths = getThirdPartyPathsFromXML();
228       // Generate .eslintignore.
229       var eslintIgnores = ['# Generated by "grunt ignorefiles"', '*/**/yui/src/*/meta/', '*/**/build/'].concat(thirdPartyPaths);
230       grunt.file.write('.eslintignore', eslintIgnores.join('\n'));
231       // Generate .stylelintignore.
232       var stylelintIgnores = [
233           '# Generated by "grunt ignorefiles"',
234           'theme/bootstrapbase/style/',
235           'theme/clean/style/custom.css',
236           'theme/more/style/custom.css'
237       ].concat(thirdPartyPaths);
238       grunt.file.write('.stylelintignore', stylelintIgnores.join('\n'));
239     };
241     /**
242      * Shifter task. Is configured with a path to a specific file or a directory,
243      * in the case of a specific file it will work out the right module to be built.
244      *
245      * Note that this task runs the invidiaul shifter jobs async (becase it spawns
246      * so be careful to to call done().
247      */
248     tasks.shifter = function() {
249         var done = this.async(),
250             options = grunt.config('shifter.options');
252         // Run the shifter processes one at a time to avoid confusing output.
253         async.eachSeries(options.paths, function(src, filedone) {
254             var args = [];
255             args.push(path.normalize(__dirname + '/node_modules/shifter/bin/shifter'));
257             // Always ignore the node_modules directory.
258             args.push('--excludes', 'node_modules');
260             // Determine the most appropriate options to run with based upon the current location.
261             if (grunt.file.isMatch('**/yui/**/*.js', src)) {
262                 // When passed a JS file, build our containing module (this happen with
263                 // watch).
264                 grunt.log.debug('Shifter passed a specific JS file');
265                 src = path.dirname(path.dirname(src));
266                 options.recursive = false;
267             } else if (grunt.file.isMatch('**/yui/src', src)) {
268                 // When in a src directory --walk all modules.
269                 grunt.log.debug('In a src directory');
270                 args.push('--walk');
271                 options.recursive = false;
272             } else if (grunt.file.isMatch('**/yui/src/*', src)) {
273                 // When in module, only build our module.
274                 grunt.log.debug('In a module directory');
275                 options.recursive = false;
276             } else if (grunt.file.isMatch('**/yui/src/*/js', src)) {
277                 // When in module src, only build our module.
278                 grunt.log.debug('In a source directory');
279                 src = path.dirname(src);
280                 options.recursive = false;
281             }
283             if (grunt.option('watch')) {
284                 grunt.fail.fatal('The --watch option has been removed, please use `grunt watch` instead');
285             }
287             // Add the stderr option if appropriate
288             if (grunt.option('verbose')) {
289                 args.push('--lint-stderr');
290             }
292             if (grunt.option('no-color')) {
293                 args.push('--color=false');
294             }
296             var execShifter = function() {
298                 grunt.log.ok("Running shifter on " + src);
299                 grunt.util.spawn({
300                     cmd: "node",
301                     args: args,
302                     opts: {cwd: src, stdio: 'inherit', env: process.env}
303                 }, function(error, result, code) {
304                     if (code) {
305                         grunt.fail.fatal('Shifter failed with code: ' + code);
306                     } else {
307                         grunt.log.ok('Shifter build complete.');
308                         filedone();
309                     }
310                 });
311             };
313             // Actually run shifter.
314             if (!options.recursive) {
315                 execShifter();
316             } else {
317                 // Check that there are yui modules otherwise shifter ends with exit code 1.
318                 if (grunt.file.expand({cwd: src}, '**/yui/src/**/*.js').length > 0) {
319                     args.push('--recursive');
320                     execShifter();
321                 } else {
322                     grunt.log.ok('No YUI modules to build.');
323                     filedone();
324                 }
325             }
326         }, done);
327     };
329     tasks.gherkinlint = function() {
330         var done = this.async(),
331             options = grunt.config('gherkinlint.options');
333         var args = grunt.file.expand(options.files);
334         args.unshift(path.normalize(__dirname + '/node_modules/.bin/gherkin-lint'));
335         grunt.util.spawn({
336             cmd: 'node',
337             args: args,
338             opts: {stdio: 'inherit', env: process.env}
339         }, function(error, result, code) {
340             // Propagate the exit code.
341             done(code === 0);
342         });
343     };
345     tasks.startup = function() {
346         // Are we in a YUI directory?
347         if (path.basename(path.resolve(cwd, '../../')) == 'yui') {
348             grunt.task.run('yui');
349         // Are we in an AMD directory?
350         } else if (inAMD) {
351             grunt.task.run('amd');
352         } else {
353             // Run them all!.
354             grunt.task.run('css');
355             grunt.task.run('js');
356             grunt.task.run('gherkinlint');
357         }
358     };
360     // On watch, we dynamically modify config to build only affected files. This
361     // method is slightly complicated to deal with multiple changed files at once (copied
362     // from the grunt-contrib-watch readme).
363     var changedFiles = Object.create(null);
364     var onChange = grunt.util._.debounce(function() {
365           var files = Object.keys(changedFiles);
366           grunt.config('eslint.amd.src', files);
367           grunt.config('eslint.yui.src', files);
368           grunt.config('uglify.amd.files', [{expand: true, src: files, rename: uglifyRename}]);
369           grunt.config('shifter.options.paths', files);
370           grunt.config('stylelint.less.src', files);
371           grunt.config('gherkinlint.options.files', files);
372           changedFiles = Object.create(null);
373     }, 200);
375     grunt.event.on('watch', function(action, filepath) {
376           changedFiles[filepath] = action;
377           onChange();
378     });
380     // Register NPM tasks.
381     grunt.loadNpmTasks('grunt-contrib-uglify');
382     grunt.loadNpmTasks('grunt-contrib-less');
383     grunt.loadNpmTasks('grunt-contrib-watch');
384     grunt.loadNpmTasks('grunt-eslint');
385     grunt.loadNpmTasks('grunt-stylelint');
387     // Register JS tasks.
388     grunt.registerTask('shifter', 'Run Shifter against the current directory', tasks.shifter);
389     grunt.registerTask('gherkinlint', 'Run gherkinlint against the current directory', tasks.gherkinlint);
390     grunt.registerTask('ignorefiles', 'Generate ignore files for linters', tasks.ignorefiles);
391     grunt.registerTask('yui', ['eslint:yui', 'shifter']);
392     grunt.registerTask('amd', ['eslint:amd', 'uglify']);
393     grunt.registerTask('js', ['amd', 'yui']);
395     // Register CSS taks.
396     grunt.registerTask('css', ['stylelint:scss', 'stylelint:less', 'less:bootstrapbase', 'stylelint:css']);
398     // Register the startup task.
399     grunt.registerTask('startup', 'Run the correct tasks for the current directory', tasks.startup);
401     // Register the default task.
402     grunt.registerTask('default', ['startup']);