MDL-54948 core_upgrade: fix check_unoconv_version logic
[moodle.git] / Gruntfile.js
blobb7283412e4a107f0b7d3f6a9776fdea2528afcba
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');
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);
41             grunt.log.ok('Setting root to ' + cwd);
42         } else {
43             grunt.fail.fatal('Setting root to ' + root + ' failed - path does not exist');
44         }
45     }
47     var inAMD = path.basename(cwd) == 'amd';
49     // Globbing pattern for matching all AMD JS source files.
50     var amdSrc = [inAMD ? cwd + '/src/*.js' : '**/amd/src/*.js'];
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      */
62     var uglifyRename = function(destPath, srcPath) {
63         destPath = srcPath.replace('src', 'build');
64         destPath = destPath.replace('.js', '.min.js');
65         destPath = path.resolve(cwd, destPath);
66         return destPath;
67     };
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/'];
79         thirdpartyfiles.forEach(function(file) {
80           var dirname = path.dirname(file);
82           var doc = new DOMParser().parseFromString(grunt.file.read(file));
83           var nodes = xpath.select("/libraries/library/location/text()", doc);
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             }
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     };
102     // Project configuration.
103     grunt.initConfig({
104         jshint: {
105             options: {jshintrc: '.jshintrc'},
106             amd: { src: amdSrc }
107         },
108         eslint: {
109             // Even though warnings dont stop the build we don't display warnings by default because
110             // at this moment we've got too many core warnings.
111             options: { quiet: !grunt.option('show-lint-warnings') },
112             // Check AMD files. We add some stricter rules which we can't apply to the default configuration due
113             // to YUI rollups.
114             amd: {
115               src: amdSrc,
116               options: {
117                   rules: {'no-undef': 'error', 'no-unused-vars': 'error', 'no-empty': 'error', 'no-unused-expressions': 'error'}
118               }
119             },
120             // Check YUI module source files.
121             yui: {
122                src: ['**/yui/src/**/*.js', '!*/**/yui/src/*/meta/*.js'],
123             }
124         },
125         uglify: {
126             amd: {
127                 files: [{
128                     expand: true,
129                     src: amdSrc,
130                     rename: uglifyRename
131                 }]
132             }
133         },
134         less: {
135             bootstrapbase: {
136                 files: {
137                     "theme/bootstrapbase/style/moodle.css": "theme/bootstrapbase/less/moodle.less",
138                     "theme/bootstrapbase/style/editor.css": "theme/bootstrapbase/less/editor.less",
139                 },
140                 options: {
141                     compress: true
142                 }
143            }
144         },
145         watch: {
146             options: {
147                 nospawn: true // We need not to spawn so config can be changed dynamically.
148             },
149             amd: {
150                 files: ['**/amd/src/**/*.js'],
151                 tasks: ['amd']
152             },
153             bootstrapbase: {
154                 files: ["theme/bootstrapbase/less/**/*.less"],
155                 tasks: ["less:bootstrapbase"]
156             },
157             yui: {
158                 files: ['**/yui/src/**/*.js'],
159                 tasks: ['yui']
160             },
161         },
162         shifter: {
163             options: {
164                 recursive: true,
165                 paths: [cwd]
166             }
167         }
168     });
170     /**
171      * Generate ignore files (utilising thirdpartylibs.xml data)
172      */
173     tasks.ignorefiles = function() {
174       // An array of paths to third party directories.
175       var thirdPartyPaths = getThirdPartyPathsFromXML();
176       // Generate .eslintignore.
177       var eslintIgnores = ['# Generated by "grunt ignorefiles"', '*/**/yui/src/*/meta/', '*/**/build/'].concat(thirdPartyPaths);
178       grunt.file.write('.eslintignore', eslintIgnores.join('\n'));
179     };
181     /**
182      * Shifter task. Is configured with a path to a specific file or a directory,
183      * in the case of a specific file it will work out the right module to be built.
184      *
185      * Note that this task runs the invidiaul shifter jobs async (becase it spawns
186      * so be careful to to call done().
187      */
188     tasks.shifter = function() {
189         var done = this.async(),
190             options = grunt.config('shifter.options');
192         // Run the shifter processes one at a time to avoid confusing output.
193         async.eachSeries(options.paths, function(src, filedone) {
194             var args = [];
195             args.push(path.normalize(__dirname + '/node_modules/shifter/bin/shifter'));
197             // Always ignore the node_modules directory.
198             args.push('--excludes', 'node_modules');
200             // Determine the most appropriate options to run with based upon the current location.
201             if (grunt.file.isMatch('**/yui/**/*.js', src)) {
202                 // When passed a JS file, build our containing module (this happen with
203                 // watch).
204                 grunt.log.debug('Shifter passed a specific JS file');
205                 src = path.dirname(path.dirname(src));
206                 options.recursive = false;
207             } else if (grunt.file.isMatch('**/yui/src', src)) {
208                 // When in a src directory --walk all modules.
209                 grunt.log.debug('In a src directory');
210                 args.push('--walk');
211                 options.recursive = false;
212             } else if (grunt.file.isMatch('**/yui/src/*', src)) {
213                 // When in module, only build our module.
214                 grunt.log.debug('In a module directory');
215                 options.recursive = false;
216             } else if (grunt.file.isMatch('**/yui/src/*/js', src)) {
217                 // When in module src, only build our module.
218                 grunt.log.debug('In a source directory');
219                 src = path.dirname(src);
220                 options.recursive = false;
221             }
223             if (grunt.option('watch')) {
224                 grunt.fail.fatal('The --watch option has been removed, please use `grunt watch` instead');
225             }
227             // Add the stderr option if appropriate
228             if (grunt.option('verbose')) {
229                 args.push('--lint-stderr');
230             }
232             if (grunt.option('no-color')) {
233                 args.push('--color=false');
234             }
236             var execShifter = function() {
238                 grunt.log.ok("Running shifter on " + src);
239                 grunt.util.spawn({
240                     cmd: "node",
241                     args: args,
242                     opts: {cwd: src, stdio: 'inherit', env: process.env}
243                 }, function(error, result, code) {
244                     if (code) {
245                         grunt.fail.fatal('Shifter failed with code: ' + code);
246                     } else {
247                         grunt.log.ok('Shifter build complete.');
248                         filedone();
249                     }
250                 });
251             };
253             // Actually run shifter.
254             if (!options.recursive) {
255                 execShifter();
256             } else {
257                 // Check that there are yui modules otherwise shifter ends with exit code 1.
258                 if (grunt.file.expand({cwd: src}, '**/yui/src/**/*.js').length > 0) {
259                     args.push('--recursive');
260                     execShifter();
261                 } else {
262                     grunt.log.ok('No YUI modules to build.');
263                     filedone();
264                 }
265             }
266         }, done);
267     };
269     tasks.startup = function() {
270         // Are we in a YUI directory?
271         if (path.basename(path.resolve(cwd, '../../')) == 'yui') {
272             grunt.task.run('yui');
273         // Are we in an AMD directory?
274         } else if (inAMD) {
275             grunt.task.run('amd');
276         } else {
277             // Run them all!.
278             grunt.task.run('css');
279             grunt.task.run('js');
280         }
281     };
283     // On watch, we dynamically modify config to build only affected files. This
284     // method is slightly complicated to deal with multiple changed files at once (copied
285     // from the grunt-contrib-watch readme).
286     var changedFiles = Object.create(null);
287     var onChange = grunt.util._.debounce(function() {
288           var files = Object.keys(changedFiles);
289           grunt.config('jshint.amd.src', files);
290           grunt.config('uglify.amd.files', [{ expand: true, src: files, rename: uglifyRename }]);
291           grunt.config('shifter.options.paths', files);
292           changedFiles = Object.create(null);
293     }, 200);
295     grunt.event.on('watch', function(action, filepath) {
296           changedFiles[filepath] = action;
297           onChange();
298     });
300     // Register NPM tasks.
301     grunt.loadNpmTasks('grunt-contrib-uglify');
302     grunt.loadNpmTasks('grunt-contrib-jshint');
303     grunt.loadNpmTasks('grunt-contrib-less');
304     grunt.loadNpmTasks('grunt-contrib-watch');
305     grunt.loadNpmTasks('grunt-eslint');
307     // Register JS tasks.
308     grunt.registerTask('shifter', 'Run Shifter against the current directory', tasks.shifter);
309     grunt.registerTask('ignorefiles', 'Generate ignore files for linters', tasks.ignorefiles);
310     grunt.registerTask('yui', ['eslint:yui', 'shifter']);
311     grunt.registerTask('amd', ['eslint:amd', 'jshint', 'uglify']);
312     grunt.registerTask('js', ['amd', 'yui']);
314     // Register CSS taks.
315     grunt.registerTask('css', ['less:bootstrapbase']);
317     // Register the startup task.
318     grunt.registerTask('startup', 'Run the correct tasks for the current directory', tasks.startup);
320     // Register the default task.
321     grunt.registerTask('default', ['startup']);