Refactor: Data.prototype.access. Thanks to @RubyLouvre and @gibson042. Closes #1167
[jquery.git] / Gruntfile.js
blobf202ac8fe78677e06b90f1a3e1f34db36ed69389
1 module.exports = function( grunt ) {
3         "use strict";
5         var distpaths = [
6                         "dist/jquery.js",
7                         "dist/jquery.min.map",
8                         "dist/jquery.min.js"
9                 ],
10                 readOptionalJSON = function( filepath ) {
11                         var data = {};
12                         try {
13                                 data = grunt.file.readJSON( filepath );
14                         } catch(e) {}
15                         return data;
16                 };
18         grunt.initConfig({
19                 pkg: grunt.file.readJSON("package.json"),
20                 dst: readOptionalJSON("dist/.destination.json"),
21                 compare_size: {
22                         files: distpaths
23                 },
24                 selector: {
25                         destFile: "src/selector.js",
26                         apiFile: "src/sizzle-jquery.js",
27                         srcFile: "src/sizzle/sizzle.js"
28                 },
29                 build: {
30                         all:{
31                                 dest: "dist/jquery.js",
32                                 src: [
33                                         "src/intro.js",
34                                         "src/core.js",
35                                         "src/callbacks.js",
36                                         "src/deferred.js",
37                                         "src/support.js",
38                                         "src/data.js",
39                                         "src/queue.js",
40                                         "src/attributes.js",
41                                         "src/event.js",
42                                         "src/selector.js",
43                                         "src/traversing.js",
44                                         "src/manipulation.js",
46                                         { flag: "css", src: "src/css.js" },
47                                         "src/serialize.js",
48                                         { flag: "event-alias", src: "src/event-alias.js" },
49                                         { flag: "ajax", src: "src/ajax.js" },
50                                         { flag: "ajax/script", src: "src/ajax/script.js", needs: ["ajax"]  },
51                                         { flag: "ajax/jsonp", src: "src/ajax/jsonp.js", needs: [ "ajax", "ajax/script" ]  },
52                                         { flag: "ajax/xhr", src: "src/ajax/xhr.js", needs: ["ajax"]  },
53                                         { flag: "effects", src: "src/effects.js", needs: ["css"] },
54                                         { flag: "offset", src: "src/offset.js", needs: ["css"] },
55                                         { flag: "dimensions", src: "src/dimensions.js", needs: ["css"] },
56                                         { flag: "deprecated", src: "src/deprecated.js" },
58                                         "src/exports.js",
59                                         "src/outro.js"
60                                 ]
61                         }
62                 },
64                 jshint: {
65                         dist: {
66                                 src: [ "dist/jquery.js" ],
67                                 options: {
68                                         jshintrc: "src/.jshintrc"
69                                 }
70                         },
71                         grunt: {
72                                 src: [ "Gruntfile.js" ],
73                                 options: {
74                                         jshintrc: ".jshintrc"
75                                 }
76                         },
77                         tests: {
78                                 // TODO: Once .jshintignore is supported, use that instead.
79                                 // issue located here: https://github.com/gruntjs/grunt-contrib-jshint/issues/1
80                                 src: [ "test/data/{test,testinit,testrunner}.js", "test/unit/**/*.js" ],
81                                 options: {
82                                         jshintrc: "test/.jshintrc"
83                                 }
84                         }
85                 },
87                 testswarm: {
88                         tests: "ajax attributes callbacks core css data deferred dimensions effects event manipulation offset queue selector serialize support traversing Sizzle".split(" ")
89                 },
91                 watch: {
92                         files: [ "<%= jshint.grunt.src %>", "<%= jshint.tests.src %>", "src/**/*.js" ],
93                         tasks: "dev"
94                 },
96                 uglify: {
97                         all: {
98                                 files: {
99                                         "dist/jquery.min.js": [ "dist/jquery.js" ]
100                                 },
101                                 options: {
102                                         banner: "/*! jQuery v<%= pkg.version %> | (c) 2005, 2013 jQuery Foundation, Inc. | jquery.org/license */",
103                                         sourceMap: "dist/jquery.min.map",
104                                         beautify: {
105                                                 ascii_only: true
106                                         }
107                                 }
108                         }
109                 }
110         });
112         grunt.registerTask( "testswarm", function( commit, configFile ) {
113                 var jobName,
114                         testswarm = require( "testswarm" ),
115                         testUrls = [],
116                         pull = /PR-(\d+)/.exec( commit ),
117                         config = grunt.file.readJSON( configFile ).jquery,
118                         tests = grunt.config([ this.name, "tests" ]);
120                 if ( pull ) {
121                         jobName = "jQuery pull <a href='https://github.com/jquery/jquery/pull/" +
122                                 pull[ 1 ] + "'>#" + pull[ 1 ] + "</a>";
123                 } else {
124                         jobName = "jQuery commit #<a href='https://github.com/jquery/jquery/commit/" +
125                                 commit + "'>" + commit.substr( 0, 10 ) + "</a>";
126                 }
128                 tests.forEach(function( test ) {
129                         testUrls.push( config.testUrl + commit + "/test/index.html?module=" + test );
130                 });
132                 testswarm({
133                         url: config.swarmUrl,
134                         pollInterval: 10000,
135                         timeout: 1000 * 60 * 30,
136                         done: this.async()
137                 }, {
138                         authUsername: config.authUsername,
139                         authToken: config.authToken,
140                         jobName: jobName,
141                         runMax: config.runMax,
142                         "runNames[]": tests,
143                         "runUrls[]": testUrls,
144                         "browserSets[]": "popular-no-old-ie"
145                 });
146         });
148         // Build src/selector.js
149         grunt.registerTask( "selector", "Build src/selector.js", function() {
151                 var cfg = grunt.config("selector"),
152                         name = cfg.destFile,
153                         sizzle = {
154                                 api: grunt.file.read( cfg.apiFile ),
155                                 src: grunt.file.read( cfg.srcFile )
156                         },
157                         compiled, parts;
159                 /**
161                         sizzle-jquery.js -> sizzle between "EXPOSE" blocks,
162                         replace define & window.Sizzle assignment
165                         // EXPOSE
166                         if ( typeof define === "function" && define.amd ) {
167                                 define(function() { return Sizzle; });
168                         } else {
169                                 window.Sizzle = Sizzle;
170                         }
171                         // EXPOSE
173                         Becomes...
175                         Sizzle.attr = jQuery.attr;
176                         jQuery.find = Sizzle;
177                         jQuery.expr = Sizzle.selectors;
178                         jQuery.expr[":"] = jQuery.expr.pseudos;
179                         jQuery.unique = Sizzle.uniqueSort;
180                         jQuery.text = Sizzle.getText;
181                         jQuery.isXMLDoc = Sizzle.isXML;
182                         jQuery.contains = Sizzle.contains;
184                  */
186                 // Break into 3 pieces
187                 parts = sizzle.src.split("// EXPOSE");
188                 // Replace the if/else block with api
189                 parts[1] = sizzle.api;
190                 // Rejoin the pieces
191                 compiled = parts.join("");
193                 grunt.verbose.write("Injected sizzle-jquery.js into sizzle.js");
195                 // Write concatenated source to file, and ensure newline-only termination
196                 grunt.file.write( name, compiled.replace( /\x0d\x0a/g, "\x0a" ) );
198                 // Fail task if errors were logged.
199                 if ( this.errorCount ) {
200                         return false;
201                 }
203                 // Otherwise, print a success message.
204                 grunt.log.writeln( "File '" + name + "' created." );
205         });
208         // Special "alias" task to make custom build creation less grawlix-y
209         grunt.registerTask( "custom", function() {
210                 var done = this.async(),
211                                 args = [].slice.call(arguments),
212                                 modules = args.length ? args[0].replace(/,/g, ":") : "";
215                 // Translation example
216                 //
217                 //   grunt custom:+ajax,-dimensions,-effects,-offset
218                 //
219                 // Becomes:
220                 //
221                 //   grunt build:*:*:+ajax:-dimensions:-effects:-offset
223                 grunt.log.writeln( "Creating custom build...\n" );
225                 grunt.util.spawn({
226                         cmd: process.platform === "win32" ? "grunt.cmd" : "grunt",
227                         args: [ "build:*:*:" + modules, "uglify", "dist" ]
228                 }, function( err, result ) {
229                         if ( err ) {
230                                 grunt.verbose.error();
231                                 done( err );
232                                 return;
233                         }
235                         grunt.log.writeln( result.stdout.replace("Done, without errors.", "") );
237                         done();
238                 });
239         });
241         // Special concat/build task to handle various jQuery build requirements
242         //
243         grunt.registerMultiTask(
244                 "build",
245                 "Concatenate source (include/exclude modules with +/- flags), embed date/version",
246                 function() {
248                         // Concat specified files.
249                         var compiled = "",
250                                 modules = this.flags,
251                                 optIn = !modules["*"],
252                                 explicit = optIn || Object.keys(modules).length > 1,
253                                 name = this.data.dest,
254                                 src = this.data.src,
255                                 deps = {},
256                                 excluded = {},
257                                 version = grunt.config( "pkg.version" ),
258                                 excluder = function( flag, needsFlag ) {
259                                         // optIn defaults implicit behavior to weak exclusion
260                                         if ( optIn && !modules[ flag ] && !modules[ "+" + flag ] ) {
261                                                 excluded[ flag ] = false;
262                                         }
264                                         // explicit or inherited strong exclusion
265                                         if ( excluded[ needsFlag ] || modules[ "-" + flag ] ) {
266                                                 excluded[ flag ] = true;
268                                         // explicit inclusion overrides weak exclusion
269                                         } else if ( excluded[ needsFlag ] === false &&
270                                                 ( modules[ flag ] || modules[ "+" + flag ] ) ) {
272                                                 delete excluded[ needsFlag ];
274                                                 // ...all the way down
275                                                 if ( deps[ needsFlag ] ) {
276                                                         deps[ needsFlag ].forEach(function( subDep ) {
277                                                                 modules[ needsFlag ] = true;
278                                                                 excluder( needsFlag, subDep );
279                                                         });
280                                                 }
281                                         }
282                                 };
284                         // append commit id to version
285                         if ( process.env.COMMIT ) {
286                                 version += " " + process.env.COMMIT;
287                         }
289                         // figure out which files to exclude based on these rules in this order:
290                         //  dependency explicit exclude
291                         //  > explicit exclude
292                         //  > explicit include
293                         //  > dependency implicit exclude
294                         //  > implicit exclude
295                         // examples:
296                         //  *                  none (implicit exclude)
297                         //  *:*                all (implicit include)
298                         //  *:*:-css           all except css and dependents (explicit > implicit)
299                         //  *:*:-css:+effects  same (excludes effects because explicit include is trumped by explicit exclude of dependency)
300                         //  *:+effects         none except effects and its dependencies (explicit include trumps implicit exclude of dependency)
301                         src.forEach(function( filepath ) {
302                                 var flag = filepath.flag;
304                                 if ( flag ) {
306                                         excluder(flag);
308                                         // check for dependencies
309                                         if ( filepath.needs ) {
310                                                 deps[ flag ] = filepath.needs;
311                                                 filepath.needs.forEach(function( needsFlag ) {
312                                                         excluder( flag, needsFlag );
313                                                 });
314                                         }
315                                 }
316                         });
318                         // append excluded modules to version
319                         if ( Object.keys( excluded ).length ) {
320                                 version += " -" + Object.keys( excluded ).join( ",-" );
321                                 // set pkg.version to version with excludes, so minified file picks it up
322                                 grunt.config.set( "pkg.version", version );
323                         }
326                         // conditionally concatenate source
327                         src.forEach(function( filepath ) {
328                                 var flag = filepath.flag,
329                                                 specified = false,
330                                                 omit = false,
331                                                 message = "";
333                                 if ( flag ) {
334                                         if ( excluded[ flag ] !== undefined ) {
335                                                 message = ( "Excluding " + flag ).red;
336                                                 specified = true;
337                                                 omit = true;
338                                         } else {
339                                                 message = ( "Including " + flag ).green;
341                                                 // If this module was actually specified by the
342                                                 // builder, then st the flag to include it in the
343                                                 // output list
344                                                 if ( modules[ "+" + flag ] ) {
345                                                         specified = true;
346                                                 }
347                                         }
349                                         // Only display the inclusion/exclusion list when handling
350                                         // an explicit list.
351                                         //
352                                         // Additionally, only display modules that have been specified
353                                         // by the user
354                                         if ( explicit && specified ) {
355                                                 grunt.log.writetableln([ 27, 30 ], [
356                                                         message,
357                                                         ( "(" + filepath.src + ")").grey
358                                                 ]);
359                                         }
361                                         filepath = filepath.src;
362                                 }
364                                 if ( !omit ) {
365                                         compiled += grunt.file.read( filepath );
366                                 }
367                         });
369                         // Embed Version
370                         // Embed Date
371                         compiled = compiled.replace( /@VERSION/g, version )
372                                 .replace( "@DATE", function () {
373                                         var date = new Date();
375                                         // YYYY-MM-DD
376                                         return [
377                                                 date.getFullYear(),
378                                                 date.getMonth() + 1,
379                                                 date.getDate()
380                                         ].join( "-" );
381                                 });
383                         // Write concatenated source to file
384                         grunt.file.write( name, compiled );
386                         // Fail task if errors were logged.
387                         if ( this.errorCount ) {
388                                 return false;
389                         }
391                         // Otherwise, print a success message.
392                         grunt.log.writeln( "File '" + name + "' created." );
393                 });
395         // Process files for distribution
396         grunt.registerTask( "dist", function() {
397                 var flags, paths, stored;
399                 // Check for stored destination paths
400                 // ( set in dist/.destination.json )
401                 stored = Object.keys( grunt.config("dst") );
403                 // Allow command line input as well
404                 flags = Object.keys( this.flags );
406                 // Combine all output target paths
407                 paths = [].concat( stored, flags ).filter(function( path ) {
408                         return path !== "*";
409                 });
411                 // Ensure the dist files are pure ASCII
412                 var fs = require("fs"),
413                         nonascii = false;
415                 distpaths.forEach(function( filename ) {
416                         var i, c, map,
417                                 text = fs.readFileSync( filename, "utf8" );
419                         // Ensure files use only \n for line endings, not \r\n
420                         if ( /\x0d\x0a/.test( text ) ) {
421                                 grunt.log.writeln( filename + ": Incorrect line endings (\\r\\n)" );
422                                 nonascii = true;
423                         }
425                         // Ensure only ASCII chars so script tags don't need a charset attribute
426                         if ( text.length !== Buffer.byteLength( text, "utf8" ) ) {
427                                 grunt.log.writeln( filename + ": Non-ASCII characters detected:" );
428                                 for ( i = 0; i < text.length; i++ ) {
429                                         c = text.charCodeAt( i );
430                                         if ( c > 127 ) {
431                                                 grunt.log.writeln( "- position " + i + ": " + c );
432                                                 grunt.log.writeln( "-- " + text.substring( i - 20, i + 20 ) );
433                                                 break;
434                                         }
435                                 }
436                                 nonascii = true;
437                         }
439                         // Modify map/min so that it points to files in the same folder;
440                         // see https://github.com/mishoo/UglifyJS2/issues/47
441                         if ( /\.map$/.test( filename ) ) {
442                                 text = text.replace( /"dist\//g, "\"" );
443                                 fs.writeFileSync( filename, text, "utf-8" );
444                         } else if ( /\.min\.js$/.test( filename ) ) {
445                                 // Wrap sourceMap directive in multiline comments (#13274)
446                                 text = text.replace( /\n?(\/\/@\s*sourceMappingURL=)(.*)/,
447                                         function( _, directive, path ) {
448                                                 map = "\n" + directive + path.replace( /^dist\//, "" );
449                                                 return "";
450                                         });
451                                 if ( map ) {
452                                         text = text.replace( /(^\/\*[\w\W]*?)\s*\*\/|$/,
453                                                 function( _, comment ) {
454                                                         return ( comment || "\n/*" ) + map + "\n*/";
455                                                 });
456                                 }
457                                 fs.writeFileSync( filename, text, "utf-8" );
458                         }
460                         // Optionally copy dist files to other locations
461                         paths.forEach(function( path ) {
462                                 var created;
464                                 if ( !/\/$/.test( path ) ) {
465                                         path += "/";
466                                 }
468                                 created = path + filename.replace( "dist/", "" );
469                                 grunt.file.write( created, text );
470                                 grunt.log.writeln( "File '" + created + "' created." );
471                         });
472                 });
474                 return !nonascii;
475         });
477         // Load grunt tasks from NPM packages
478         grunt.loadNpmTasks("grunt-compare-size");
479         grunt.loadNpmTasks("grunt-git-authors");
480         grunt.loadNpmTasks("grunt-update-submodules");
481         grunt.loadNpmTasks("grunt-contrib-watch");
482         grunt.loadNpmTasks("grunt-contrib-jshint");
483         grunt.loadNpmTasks("grunt-contrib-uglify");
485         // Default grunt
486         grunt.registerTask( "default", [ "update_submodules", "selector", "build:*:*", "jshint", "uglify", "dist:*" ] );
488         // Short list as a high frequency watch task
489         grunt.registerTask( "dev", [ "selector", "build:*:*", "jshint" ] );