forked from jquery/jquery
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Gruntfile.js
588 lines (506 loc) · 16.2 KB
/
Gruntfile.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
module.exports = function( grunt ) {
"use strict";
var distpaths = [
"dist/jquery.js",
"dist/jquery.min.map",
"dist/jquery.min.js"
],
gzip = require("gzip-js"),
readOptionalJSON = function( filepath ) {
var data = {};
try {
data = grunt.file.readJSON( filepath );
} catch(e) {}
return data;
},
srcHintOptions = readOptionalJSON("src/.jshintrc");
// The concatenated file won't pass onevar
// But our modules can
delete srcHintOptions.onevar;
grunt.initConfig({
pkg: grunt.file.readJSON("package.json"),
dst: readOptionalJSON("dist/.destination.json"),
compare_size: {
files: [ "dist/jquery.js", "dist/jquery.min.js" ],
options: {
compress: {
gz: function( contents ) {
return gzip.zip( contents, {} ).length;
}
},
cache: "dist/.sizecache.json"
}
},
selector: {
destFile: "src/selector-sizzle.js",
apiFile: "src/sizzle-jquery.js",
srcFile: "src/sizzle/dist/sizzle.js"
},
build: {
all: {
dest: "dist/jquery.js",
src: [
"src/intro.js",
"src/core.js",
{ flag: "sizzle", src: "src/selector-sizzle.js", alt: "src/selector-native.js" },
"src/callbacks.js",
"src/deferred.js",
"src/support.js",
"src/data.js",
"src/queue.js",
"src/attributes.js",
"src/event.js",
"src/traversing.js",
"src/manipulation.js",
{ flag: "wrap", src: "src/wrap.js" },
{ flag: "css", src: "src/css.js" },
"src/serialize.js",
{ flag: "event-alias", src: "src/event-alias.js" },
{ flag: "ajax", src: "src/ajax.js" },
{ flag: "ajax/script", src: "src/ajax/script.js", needs: ["ajax"] },
{ flag: "ajax/jsonp", src: "src/ajax/jsonp.js", needs: [ "ajax", "ajax/script" ] },
{ flag: "ajax/xhr", src: "src/ajax/xhr.js", needs: ["ajax"] },
{ flag: "effects", src: "src/effects.js", needs: ["css"] },
{ flag: "offset", src: "src/offset.js", needs: ["css"] },
{ flag: "dimensions", src: "src/dimensions.js", needs: ["css"] },
{ flag: "deprecated", src: "src/deprecated.js" },
"src/exports.js",
"src/outro.js"
]
}
},
jshint: {
dist: {
src: [ "dist/jquery.js" ],
options: srcHintOptions
},
grunt: {
src: [ "Gruntfile.js" ],
options: {
jshintrc: ".jshintrc"
}
},
tests: {
// TODO: Once .jshintignore is supported, use that instead.
// issue located here: https://github.com/gruntjs/grunt-contrib-jshint/issues/1
src: [ "test/data/{test,testinit,testrunner}.js", "test/unit/**/*.js" ],
options: {
jshintrc: "test/.jshintrc"
}
}
},
testswarm: {
tests: "ajax attributes callbacks core css data deferred dimensions effects event manipulation offset queue selector serialize support traversing Sizzle".split(" ")
},
watch: {
files: [ "<%= jshint.grunt.src %>", "<%= jshint.tests.src %>", "src/**/*.js" ],
tasks: "dev"
},
"pre-uglify": {
all: {
files: {
"dist/jquery.pre-min.js": [ "dist/jquery.js" ]
},
options: {
banner: "\n\n\n\n\n\n\n\n\n\n" + // banner line size must be preserved
"/*! jQuery v<%= pkg.version %> | " +
"(c) 2005, 2013 jQuery Foundation, Inc. | " +
"jquery.org/license\n" +
"//@ sourceMappingURL=jquery.min.map\n" +
"*/\n"
}
}
},
uglify: {
all: {
files: {
"dist/jquery.min.js": [ "dist/jquery.pre-min.js" ]
},
options: {
// Keep our hard-coded banner
preserveComments: "some",
sourceMap: "dist/jquery.min.map",
sourceMappingURL: "jquery.min.map",
report: "min",
beautify: {
ascii_only: true
},
compress: {
hoist_funs: false,
join_vars: false,
loops: false,
unused: false
},
mangle: {
// saves some bytes when gzipped
except: [ "undefined" ]
}
}
}
},
"post-uglify": {
all: {
files: {
"dist/jquery.min.map.tmp": [ "dist/jquery.min.map" ],
"dist/jquery.min.js.tmp": [ "dist/jquery.min.js" ]
},
options: {
tempFiles: [ "dist/jquery.min.map.tmp", "dist/jquery.min.js.tmp", "dist/jquery.pre-min.js" ]
}
}
}
});
grunt.registerTask( "testswarm", function( commit, configFile ) {
var jobName,
testswarm = require( "testswarm" ),
testUrls = [],
pull = /PR-(\d+)/.exec( commit ),
config = grunt.file.readJSON( configFile ).jquery,
tests = grunt.config([ this.name, "tests" ]);
if ( pull ) {
jobName = "jQuery pull <a href='https://github.com/jquery/jquery/pull/" +
pull[ 1 ] + "'>#" + pull[ 1 ] + "</a>";
} else {
jobName = "jQuery commit #<a href='https://github.com/jquery/jquery/commit/" +
commit + "'>" + commit.substr( 0, 10 ) + "</a>";
}
tests.forEach(function( test ) {
testUrls.push( config.testUrl + commit + "/test/index.html?module=" + test );
});
testswarm({
url: config.swarmUrl,
pollInterval: 10000,
timeout: 1000 * 60 * 30,
done: this.async()
}, {
authUsername: config.authUsername,
authToken: config.authToken,
jobName: jobName,
runMax: config.runMax,
"runNames[]": tests,
"runUrls[]": testUrls,
"browserSets[]": "popular-no-old-ie"
});
});
grunt.registerTask( "selector", "Build Sizzle-based selector module", function() {
var cfg = grunt.config("selector"),
name = cfg.destFile,
sizzle = {
api: grunt.file.read( cfg.apiFile ),
src: grunt.file.read( cfg.srcFile )
},
compiled, parts;
/**
sizzle-jquery.js -> sizzle between "EXPOSE" blocks,
replace define & window.Sizzle assignment
// EXPOSE
if ( typeof define === "function" && define.amd ) {
define(function() { return Sizzle; });
} else {
window.Sizzle = Sizzle;
}
// EXPOSE
Becomes...
Sizzle.attr = jQuery.attr;
jQuery.find = Sizzle;
jQuery.expr = Sizzle.selectors;
jQuery.expr[":"] = jQuery.expr.pseudos;
jQuery.unique = Sizzle.uniqueSort;
jQuery.text = Sizzle.getText;
jQuery.isXMLDoc = Sizzle.isXML;
jQuery.contains = Sizzle.contains;
*/
// Break into 3 pieces
parts = sizzle.src.split("// EXPOSE");
// Replace the if/else block with api
parts[1] = sizzle.api;
// Rejoin the pieces
compiled = parts.join("");
grunt.verbose.writeln("Injected " + cfg.apiFile + " into " + cfg.srcFile);
// Write concatenated source to file, and ensure newline-only termination
grunt.file.write( name, compiled.replace( /\x0d\x0a/g, "\x0a" ) );
// Fail task if errors were logged.
if ( this.errorCount ) {
return false;
}
// Otherwise, print a success message.
grunt.log.writeln( "File '" + name + "' created." );
});
// Special "alias" task to make custom build creation less grawlix-y
grunt.registerTask( "custom", function() {
var done = this.async(),
args = [].slice.call(arguments),
modules = args.length ? args[0].replace(/,/g, ":") : "";
// Translation example
//
// grunt custom:+ajax,-dimensions,-effects,-offset
//
// Becomes:
//
// grunt build:*:*:+ajax:-dimensions:-effects:-offset
grunt.log.writeln( "Creating custom build...\n" );
grunt.util.spawn({
grunt: true,
args: [ "build:*:*:" + modules, "pre-uglify", "uglify", "dist" ]
}, function( err, result ) {
if ( err ) {
grunt.verbose.error();
done( err );
return;
}
grunt.log.writeln( result.stdout.replace("Done, without errors.", "") );
done();
});
});
// Special concat/build task to handle various jQuery build requirements
grunt.registerMultiTask(
"build",
"Concatenate source (include/exclude modules with +/- flags), embed date/version",
function() {
// Concat specified files.
var compiled = "",
modules = this.flags,
optIn = !modules["*"],
explicit = optIn || Object.keys(modules).length > 1,
name = this.data.dest,
src = this.data.src,
deps = {},
excluded = {},
version = grunt.config( "pkg.version" ),
excluder = function( flag, needsFlag ) {
// optIn defaults implicit behavior to weak exclusion
if ( optIn && !modules[ flag ] && !modules[ "+" + flag ] ) {
excluded[ flag ] = false;
}
// explicit or inherited strong exclusion
if ( excluded[ needsFlag ] || modules[ "-" + flag ] ) {
excluded[ flag ] = true;
// explicit inclusion overrides weak exclusion
} else if ( excluded[ needsFlag ] === false &&
( modules[ flag ] || modules[ "+" + flag ] ) ) {
delete excluded[ needsFlag ];
// ...all the way down
if ( deps[ needsFlag ] ) {
deps[ needsFlag ].forEach(function( subDep ) {
modules[ needsFlag ] = true;
excluder( needsFlag, subDep );
});
}
}
};
// append commit id to version
if ( process.env.COMMIT ) {
version += " " + process.env.COMMIT;
}
// figure out which files to exclude based on these rules in this order:
// dependency explicit exclude
// > explicit exclude
// > explicit include
// > dependency implicit exclude
// > implicit exclude
// examples:
// * none (implicit exclude)
// *:* all (implicit include)
// *:*:-css all except css and dependents (explicit > implicit)
// *:*:-css:+effects same (excludes effects because explicit include is trumped by explicit exclude of dependency)
// *:+effects none except effects and its dependencies (explicit include trumps implicit exclude of dependency)
src.forEach(function( filepath ) {
var flag = filepath.flag;
if ( flag ) {
excluder(flag);
// check for dependencies
if ( filepath.needs ) {
deps[ flag ] = filepath.needs;
filepath.needs.forEach(function( needsFlag ) {
excluder( flag, needsFlag );
});
}
}
});
// append excluded modules to version
if ( Object.keys( excluded ).length ) {
version += " -" + Object.keys( excluded ).join( ",-" );
// set pkg.version to version with excludes, so minified file picks it up
grunt.config.set( "pkg.version", version );
}
// conditionally concatenate source
src.forEach(function( filepath ) {
var flag = filepath.flag,
specified = false,
omit = false,
messages = [];
if ( flag ) {
if ( excluded[ flag ] !== undefined ) {
messages.push([
( "Excluding " + flag ).red,
( "(" + filepath.src + ")" ).grey
]);
specified = true;
omit = !filepath.alt;
if ( !omit ) {
flag += " alternate";
filepath.src = filepath.alt;
}
}
if ( excluded[ flag ] === undefined ) {
messages.push([
( "Including " + flag ).green,
( "(" + filepath.src + ")" ).grey
]);
// If this module was actually specified by the
// builder, then set the flag to include it in the
// output list
if ( modules[ "+" + flag ] ) {
specified = true;
}
}
filepath = filepath.src;
// Only display the inclusion/exclusion list when handling
// an explicit list.
//
// Additionally, only display modules that have been specified
// by the user
if ( explicit && specified ) {
messages.forEach(function( message ) {
grunt.log.writetableln( [ 27, 30 ], message );
});
}
}
if ( !omit ) {
compiled += grunt.file.read( filepath );
}
});
// Embed Version
// Embed Date
compiled = compiled.replace( /@VERSION/g, version )
// yyyy-mm-ddThh:mmZ
.replace( /@DATE/g, ( new Date() ).toISOString().replace( /:\d+\.\d+Z$/, "Z" ) );
// Write concatenated source to file
grunt.file.write( name, compiled );
// Fail task if errors were logged.
if ( this.errorCount ) {
return false;
}
// Otherwise, print a success message.
grunt.log.writeln( "File '" + name + "' created." );
});
// Process files for distribution
grunt.registerTask( "dist", function() {
var stored, flags, paths, fs, nonascii;
// Check for stored destination paths
// ( set in dist/.destination.json )
stored = Object.keys( grunt.config( "dst" ) );
// Allow command line input as well
flags = Object.keys( this.flags );
// Combine all output target paths
paths = [].concat( stored, flags ).filter(function( path ) {
return path !== "*";
});
// Ensure the dist files are pure ASCII
fs = require( "fs" );
nonascii = false;
distpaths.forEach(function( filename ) {
var i, c,
text = fs.readFileSync( filename, "utf8" );
// Ensure files use only \n for line endings, not \r\n
if ( /\x0d\x0a/.test( text ) ) {
grunt.log.writeln( filename + ": Incorrect line endings (\\r\\n)" );
nonascii = true;
}
// Ensure only ASCII chars so script tags don't need a charset attribute
if ( text.length !== Buffer.byteLength( text, "utf8" ) ) {
grunt.log.writeln( filename + ": Non-ASCII characters detected:" );
for ( i = 0; i < text.length; i++ ) {
c = text.charCodeAt( i );
if ( c > 127 ) {
grunt.log.writeln( "- position " + i + ": " + c );
grunt.log.writeln( "-- " + text.substring( i - 20, i + 20 ) );
break;
}
}
nonascii = true;
}
// Modify map/min so that it points to files in the same folder;
// see https://github.com/mishoo/UglifyJS2/issues/47
if ( /\.map$/.test( filename ) ) {
text = text.replace( /"dist\//g, "\"" );
fs.writeFileSync( filename, text, "utf-8" );
// Use our hard-coded sourceMap directive instead of the autogenerated one (#13274; #13776)
} else if ( /\.min\.js$/.test( filename ) ) {
i = 0;
text = text.replace( /(?:\/\*|)\n?\/\/@\s*sourceMappingURL=.*(\n\*\/|)/g,
function( match ) {
if ( i++ ) {
return "";
}
return match;
});
fs.writeFileSync( filename, text, "utf-8" );
}
// Optionally copy dist files to other locations
paths.forEach(function( path ) {
var created;
if ( !/\/$/.test( path ) ) {
path += "/";
}
created = path + filename.replace( "dist/", "" );
grunt.file.write( created, text );
grunt.log.writeln( "File '" + created + "' created." );
});
});
return !nonascii;
});
// Work around grunt-contrib-uglify sourceMap issues (jQuery #13776)
grunt.registerMultiTask( "pre-uglify", function() {
var banner = this.options().banner;
this.files.forEach(function( mapping ) {
// Join src
var input = mapping.src.map(function( file ) {
var contents = grunt.file.read( file );
// Strip banners
return contents
// Remove the main jQuery banner, it'll be replaced by the new banner anyway.
.replace( /^\/\*!(?:.|\n)*?\*\/\n?/g, "" )
// Strip other banners preserving line count.
.replace( /^\/\*!(?:.|\n)*?\*\/\n?/gm, function ( match ) {
return match.replace( /[^\n]/gm, "" );
});
}).join("\n");
// Write temp file (with optional banner)
grunt.file.write( mapping.dest, ( banner || "" ) + input );
});
});
// Change the map file to point back to jquery.js instead of jquery.pre-min.js.
// The problem is caused by the pre-uglify task.
// Also, remove temporary files.
grunt.registerMultiTask( "post-uglify", function() {
var fs = require( "fs" );
this.files.forEach(function( mapping ) {
var mapFileName = mapping.src[ 0 ];
// Rename the file to a temporary name.
fs.renameSync( mapFileName, mapping.dest);
grunt.file.write( mapFileName, grunt.file.read( mapping.dest )
// The uglify task erroneously prepends dist/ to file names.
.replace( /"dist\//g, "\"" )
// Refer to the source jquery.js, not the temporary jquery.pre-min.js.
.replace( /\.pre-min\./g, "." )
// There's already a pragma at the beginning of the file, remove the one at the end.
.replace( /\/\/@ sourceMappingURL=jquery\.min\.map$/g, "" ));
});
// Remove temporary files.
this.options().tempFiles.forEach(function( fileName ) {
fs.unlink( fileName );
});
});
// Load grunt tasks from NPM packages
grunt.loadNpmTasks("grunt-compare-size");
grunt.loadNpmTasks("grunt-git-authors");
grunt.loadNpmTasks("grunt-update-submodules");
grunt.loadNpmTasks("grunt-contrib-watch");
grunt.loadNpmTasks("grunt-contrib-jshint");
grunt.loadNpmTasks("grunt-contrib-uglify");
// Default grunt
grunt.registerTask( "default", [ "update_submodules", "selector", "build:*:*", "jshint", "pre-uglify", "uglify", "post-uglify", "dist:*", "compare_size" ] );
// Short list as a high frequency watch task
grunt.registerTask( "dev", [ "selector", "build:*:*", "jshint" ] );
};