Update Sizzle
[jquery.git] / grunt.js
blob02a688162d30225d103ff0846f47be992235723d
1 /**
2  * Resources
3  *
4  * https://gist.github.com/2489540
5  *
6  */
8 /*jshint node: true */
9 /*global config:true, task:true, process:true*/
10 module.exports = function( grunt ) {
12         // readOptionalJSON
13         // by Ben Alman
14         // https://gist.github.com/2876125
15         function readOptionalJSON( filepath ) {
16                 var data = {};
17                 try {
18                         data = grunt.file.readJSON( filepath );
19                         grunt.verbose.write( "Reading " + filepath + "..." ).ok();
20                 } catch(e) {}
21                 return data;
22         }
24         var task = grunt.task;
25         var file = grunt.file;
26         var utils = grunt.utils;
27         var log = grunt.log;
28         var verbose = grunt.verbose;
29         var fail = grunt.fail;
30         var option = grunt.option;
31         var config = grunt.config;
32         var template = grunt.template;
33         var distpaths = [
34                 "dist/jquery.js",
35                 "dist/jquery.min.js"
36         ];
38         grunt.initConfig({
39                 pkg: "<json:package.json>",
40                 dst: readOptionalJSON("dist/.destination.json"),
41                 meta: {
42                         banner: "/*! jQuery v@<%= pkg.version %> jquery.com | jquery.org/license */"
43                 },
44                 compare_size: {
45                         files: distpaths
46                 },
47                 selector: {
48                         "src/selector.js": [
49                                 "src/sizzle-jquery.js",
50                                 "src/sizzle/sizzle.js"
51                         ]
52                 },
53                 build: {
54                         "dist/jquery.js": [
55                                 "src/intro.js",
56                                 "src/core.js",
57                                 "src/callbacks.js",
58                                 "src/deferred.js",
59                                 "src/support.js",
60                                 "src/data.js",
61                                 "src/queue.js",
62                                 "src/attributes.js",
63                                 "src/event.js",
64                                 "src/selector.js",
65                                 "src/traversing.js",
66                                 "src/manipulation.js",
68                                 { flag: "deprecated", src: "src/deprecated.js" },
69                                 { flag: "css", src: "src/css.js" },
70                                 "src/serialize.js",
71                                 { flag: "ajax", src: "src/ajax.js" },
72                                 { flag: "ajax/jsonp", src: "src/ajax/jsonp.js", needs: [ "ajax", "ajax/script" ]  },
73                                 { flag: "ajax/script", src: "src/ajax/script.js", needs: ["ajax"]  },
74                                 { flag: "ajax/xhr", src: "src/ajax/xhr.js", needs: ["ajax"]  },
75                                 { flag: "effects", src: "src/effects.js", needs: ["css"] },
76                                 { flag: "offset", src: "src/offset.js", needs: ["css"] },
77                                 { flag: "dimensions", src: "src/dimensions.js", needs: ["css"] },
79                                 "src/exports.js",
80                                 "src/outro.js"
81                         ]
82                 },
83                 min: {
84                         "dist/jquery.min.js": [ "<banner>", "dist/jquery.js" ]
85                 },
87                 lint: {
88                         dist: "dist/jquery.js",
89                         grunt: "grunt.js",
90                         tests: "test/unit/**/*.js"
91                 },
93                 jshint: (function() {
94                         function jshintrc( path ) {
95                                 return readOptionalJSON( (path || "") + ".jshintrc" ) || {};
96                         }
98                         return {
99                                 options: jshintrc(),
100                                 dist: jshintrc( "src/" ),
101                                 tests: jshintrc( "test/" )
102                         };
103                 })(),
105                 qunit: {
106                         files: "test/index.html"
107                 },
108                 watch: {
109                         files: [
110                                 "<config:lint.dist>", "<config:lint.grunt>", "<config:lint.tests>",
111                                 "src/**/*.js"
112                         ],
113                         tasks: "dev"
114                 },
115                 uglify: {}
116         });
118         // Default grunt.
119         grunt.registerTask( "default", "submodules selector build:*:* lint min dist:* compare_size" );
121         // Short list as a high frequency watch task
122         grunt.registerTask( "dev", "selector build:*:* lint" );
124         // Load the "compare_size" task from NPM packages
125         grunt.loadNpmTasks( "grunt-compare-size" );
127         grunt.registerTask( "testswarm", function( commit, configFile ) {
128                 var testswarm = require( "testswarm" ),
129                         testUrls = [],
130                         config = grunt.file.readJSON( configFile ).jquery,
131                         tests = "ajax attributes callbacks core css data deferred dimensions effects event manipulation offset queue serialize support traversing Sizzle".split(" ");
133                 tests.forEach(function( test ) {
134                         testUrls.push( config.testUrl + commit + "/test/index.html?module=" + test );
135                 });
137                 testswarm({
138                         url: config.swarmUrl,
139                         pollInterval: 10000,
140                         timeout: 1000 * 60 * 30,
141                         done: this.async()
142                 }, {
143                         authUsername: config.authUsername,
144                         authToken: config.authToken,
145                         jobName: 'jQuery commit #<a href="https://github.com/jquery/jquery/commit/' + commit + '">' + commit.substr( 0, 10 ) + '</a>',
146                         runMax: config.runMax,
147                         "runNames[]": tests,
148                         "runUrls[]": testUrls,
149                         "browserSets[]": ["popular"]
150                 });
151         });
153         // Build src/selector.js
154         grunt.registerMultiTask( "selector", "Build src/selector.js", function() {
156                 var name = this.file.dest,
157                                 files = this.file.src,
158                                 sizzle = {
159                                         api: file.read( files[0] ),
160                                         src: file.read( files[1] )
161                                 },
162                                 compiled, parts;
164                 /**
166                         sizzle-jquery.js -> sizzle between "EXPOSE" blocks,
167                         replace define & window.Sizzle assignment
170                         // EXPOSE
171                         if ( typeof define === "function" && define.amd ) {
172                                 define(function() { return Sizzle; });
173                         } else {
174                                 window.Sizzle = Sizzle;
175                         }
176                         // EXPOSE
178                         Becomes...
180                         Sizzle.attr = jQuery.attr;
181                         jQuery.find = Sizzle;
182                         jQuery.expr = Sizzle.selectors;
183                         jQuery.expr[":"] = jQuery.expr.pseudos;
184                         jQuery.unique = Sizzle.uniqueSort;
185                         jQuery.text = Sizzle.getText;
186                         jQuery.isXMLDoc = Sizzle.isXML;
187                         jQuery.contains = Sizzle.contains;
189                  */
191                 // Break into 3 pieces
192                 parts = sizzle.src.split("// EXPOSE");
193                 // Replace the if/else block with api
194                 parts[1] = sizzle.api;
195                 // Rejoin the pieces
196                 compiled = parts.join("");
199                 verbose.write("Injected sizzle-jquery.js into sizzle.js");
201                 // Write concatenated source to file
202                 file.write( name, compiled );
204                 // Fail task if errors were logged.
205                 if ( this.errorCount ) {
206                         return false;
207                 }
209                 // Otherwise, print a success message.
210                 log.writeln( "File '" + name + "' created." );
211         });
214         // Special "alias" task to make custom build creation less grawlix-y
215         grunt.registerTask( "custom", function() {
216                 var done = this.async(),
217                                 args = [].slice.call(arguments),
218                                 modules = args.length ? args[0].replace(/,/g, ":") : "";
221                 // Translation example
222                 //
223                 //   grunt custom:+ajax,-dimensions,-effects,-offset
224                 //
225                 // Becomes:
226                 //
227                 //   grunt build:*:*:-ajax:-dimensions:-effects:-offset
229                 grunt.log.writeln( "Creating custom build...\n" );
231                 grunt.utils.spawn({
232                         cmd: "grunt",
233                         args: [ "build:*:*:" + modules, "min" ]
234                 }, function( err, result ) {
235                         if ( err ) {
236                                 grunt.verbose.error();
237                                 done( err );
238                                 return;
239                         }
241                         grunt.log.writeln( result.replace("Done, without errors.", "") );
243                         done();
244                 });
245         });
247         // Special concat/build task to handle various jQuery build requirements
248         //
249         grunt.registerMultiTask(
250                 "build",
251                 "Concatenate source (include/exclude modules with +/- flags), embed date/version",
252                 function() {
253                         // Concat specified files.
254                         var i,
255                                 compiled = "",
256                                 modules = this.flags,
257                                 explicit = Object.keys(modules).length > 1,
258                                 optIn = !modules["*"],
259                                 name = this.file.dest,
260                                 excluded = {},
261                                 version = config( "pkg.version" ),
262                                 excluder = function( flag, needsFlag ) {
263                                         // explicit > implicit, so set this first and let it be overridden by explicit
264                                         if ( optIn && !modules[ flag ] && !modules[ "+" + flag ] ) {
265                                                 excluded[ flag ] = false;
266                                         }
268                                         if ( excluded[ needsFlag ] || modules[ "-" + flag ] ) {
269                                                 // explicit exclusion from flag or dependency
270                                                 excluded[ flag ] = true;
271                                         } else if ( modules[ "+" + flag ] && ( excluded[ needsFlag ] === false ) ) {
272                                                 // explicit inclusion from flag or dependency overriding a weak inclusion
273                                                 delete excluded[ needsFlag ];
274                                         }
275                                 };
277                         // append commit id to version
278                         if ( process.env.COMMIT ) {
279                                 version += " " + process.env.COMMIT;
280                         }
282                         // figure out which files to exclude based on these rules in this order:
283                         //  explicit > implicit (explicit also means a dependency/dependent that was explicit)
284                         //  exclude > include
285                         // examples:
286                         //  *:                 none (implicit exclude)
287                         //  *:*                all (implicit include)
288                         //  *:*:-effects       all except effects (explicit > implicit)
289                         //  *:*:-css           all except css and its deps (explicit)
290                         //  *:*:-css:+effects  all except css and its deps (explicit exclude from dep. trumps explicit include)
291                         //  *:+effects         none except effects and its deps (explicit include from dep. trumps implicit exclude)
292                         this.file.src.forEach(function( filepath ) {
293                                 var flag = filepath.flag;
295                                 if ( flag ) {
297                                         excluder(flag);
299                                         // check for dependencies
300                                         if ( filepath.needs ) {
301                                                 filepath.needs.forEach(function( needsFlag ) {
302                                                         excluder( flag, needsFlag );
303                                                 });
304                                         }
305                                 }
306                         });
308                         // append excluded modules to version
309                         if ( Object.keys( excluded ).length ) {
310                                 version += " -" + Object.keys( excluded ).join( ",-" );
311                                 // set pkg.version to version with excludes, so minified file picks it up
312                                 grunt.config.set( "pkg.version", version );
313                         }
316                         // conditionally concatenate source
317                         this.file.src.forEach(function( filepath ) {
318                                 var flag = filepath.flag,
319                                                 specified = false,
320                                                 omit = false,
321                                                 message = "";
323                                 if ( flag ) {
324                                         if ( excluded[ flag ] !== undefined ) {
325                                                 message = ( "Excluding " + flag ).red;
326                                                 specified = true;
327                                                 omit = true;
328                                         } else {
329                                                 message = ( "Including " + flag ).green;
331                                                 // If this module was actually specified by the
332                                                 // builder, then st the flag to include it in the
333                                                 // output list
334                                                 if ( modules[ "+" + flag ] ) {
335                                                         specified = true;
336                                                 }
337                                         }
339                                         // Only display the inclusion/exclusion list when handling
340                                         // an explicit list.
341                                         //
342                                         // Additionally, only display modules that have been specified
343                                         // by the user
344                                         if ( explicit && specified ) {
345                                                 grunt.log.writetableln([ 27, 30 ], [
346                                                         message,
347                                                         ( "(" + filepath.src + ")").grey
348                                                 ]);
349                                         }
351                                         filepath = filepath.src;
352                                 }
354                                 if ( !omit ) {
355                                         compiled += file.read( filepath );
356                                 }
357                         });
359                         // Embed Date
360                         // Embed Version
361                         compiled = compiled.replace( "@DATE", new Date() )
362                                 .replace( /@VERSION/g, version );
364                         // Write concatenated source to file
365                         file.write( name, compiled );
367                         // Fail task if errors were logged.
368                         if ( this.errorCount ) {
369                                 return false;
370                         }
372                         // Otherwise, print a success message.
373                         log.writeln( "File '" + name + "' created." );
374                 });
376         grunt.registerTask( "submodules", function() {
377                 var done = this.async();
379                 grunt.verbose.write( "Updating submodules..." );
381                 // TODO: migrate remaining `make` to grunt tasks
382                 //
383                 grunt.utils.spawn({
384                         cmd: "make"
385                 }, function( err, result ) {
386                         if ( err ) {
387                                 grunt.verbose.error();
388                                 done( err );
389                                 return;
390                         }
392                         grunt.log.writeln( result );
394                         done();
395                 });
396         });
398         // Allow custom dist file locations
399         grunt.registerTask( "dist", function() {
400                 var flags, paths, stored;
402                 // Check for stored destination paths
403                 // ( set in dist/.destination.json )
404                 stored = Object.keys( config("dst") );
406                 // Allow command line input as well
407                 flags = Object.keys( this.flags );
409                 // Combine all output target paths
410                 paths = [].concat( stored, flags ).filter(function( path ) {
411                         return path !== "*";
412                 });
415                 // Proceed only if there are actual
416                 // paths to write to
417                 if ( paths.length ) {
419                         // 'distpaths' is declared at the top of the
420                         // module.exports function scope. It is an array
421                         // of default files that jQuery creates
422                         distpaths.forEach(function( filename ) {
423                                 paths.forEach(function( path ) {
424                                         var created;
426                                         if ( !/\/$/.test( path ) ) {
427                                                 path += "/";
428                                         }
430                                         created = path + filename.replace( "dist/", "" );
432                                         if ( !/^\//.test( path ) ) {
433                                                 log.error( "File '" + created + "' was NOT created." );
434                                                 return;
435                                         }
437                                         file.write( created, file.read(filename) );
439                                         log.writeln( "File '" + created + "' created." );
440                                 });
441                         });
442                 }
443         });