-
Notifications
You must be signed in to change notification settings - Fork 35
/
Copy pathgulpfile.js
650 lines (570 loc) · 21.4 KB
/
gulpfile.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
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
/* eslint-env node */
// eslint-disable-next-line spaced-comment
/// <reference types="node" />
"use strict";
/* eslint max-len: [error, 100], no-multi-spaces: off, object-curly-spacing: off */
// -----------------------------------------------------------------------------
// imports
// -----------------------------------------------------------------------------
const exec = require("child_process").exec;
const del = require("del");
const fs = require("fs");
const gulp = require("gulp");
const changed = require("gulp-changed");
const debug = require("gulp-debug"); // eslint-disable-line no-unused-vars
const gulpif = require("gulp-if");
const gulpIgnore = require("gulp-ignore");
const preprocess = require("gulp-preprocess");
const rename = require("gulp-rename");
const replace = require("gulp-replace");
const sourcemaps = require("gulp-sourcemaps");
const ts = require("gulp-typescript");
const zip = require("gulp-zip");
const mergeStream = require("merge-stream");
const nodePath = require("path");
const pify = require("pify");
const config = require("./config.json");
const promiseStat = pify(fs.stat);
const promiseLstat = pify(fs.stat);
const promiseReadlink = pify(fs.readlink);
// -----------------------------------------------------------------------------
// constants, utilities
// -----------------------------------------------------------------------------
const rootDir = `${__dirname}`;
const srcDirRelative = `src`;
const srcDir = `${rootDir}/${srcDirRelative}`; // eslint-disable-line no-unused-vars
const EXTENSION_NAME = "requestpolicy";
const EXTENSION_ID__AMO = "[email protected]";
const EXTENSION_ID__OFF_AMO = "[email protected]";
const ALPHABETICAL_ID__AMO = "rpcontinued";
const ALPHABETICAL_ID__OFF_AMO = "rpcontinuedOffAmo";
const fileFilter = (function() {
function _array(aAny) {
return Array.isArray(aAny) ? aAny : [aAny];
}
function _set(aAny) {
return new Set(_array(aAny));
}
// eslint-disable-next-line complexity
function pathMatches(aPath, aFilter) {
if (Array.isArray(aFilter)) {
return aFilter.some((filter) => pathMatches(aPath, filter));
}
let {name: stem, ext} = nodePath.parse(aPath);
if ("pathRegex" in aFilter) {
if (!_array(aFilter.pathRegex).some((p) => aPath.match(p))) return false;
}
if ("stem" in aFilter) {
if (!_set(aFilter.stem).has(stem)) return false;
}
if ("ext" in aFilter) {
if (!_set(aFilter.ext).has(ext)) return false;
}
return true;
}
const nonModulePaths = [
"conditional/legacy/bootstrap", // bootstrapped extension's entry point
"content/bootstrap-data/",
"content/bootstrap-environments/",
];
const nonModuleStems = [
];
function originalPath(aVinylFile) {
return aVinylFile.history[0];
}
function isModule(aVinylFile) {
return !pathMatches(originalPath(aVinylFile), [
{ext: ".jsm"},
{pathRegex: nonModulePaths},
{stem: nonModuleStems},
]);
}
// eslint-disable-next-line complexity
function fileMatches(aFilter, aVinylFile) {
if (Array.isArray(aFilter)) {
return aFilter.some((filter) => fileMatches(filter, aVinylFile));
}
if (!pathMatches(aVinylFile.path, aFilter)) return false;
if ("originalPath" in aFilter) {
if (!pathMatches(originalPath(aVinylFile), aFilter.originalPath)) return false;
}
if ("isModule" in aFilter) {
if (isModule(aVinylFile) !== aFilter.isModule) return false;
}
if ("not" in aFilter) {
if (fileMatches(aFilter.not, aVinylFile)) return false;
}
return true;
}
function conditionFactory(aFilter) {
return (aVinylFile) => fileMatches(aFilter, aVinylFile);
}
return {
include(aFilter) {
return gulpIgnore.include(conditionFactory(aFilter));
},
if(aFilter, aThen, aElse) {
return gulpif(conditionFactory(aFilter), aThen, aElse);
},
};
})();
function maxDate(dates) {
return dates.reduce(
// eslint-disable-next-line no-extra-parens
(max, current) => (current > max ? current : max),
new Date(0)
);
}
function promiseMaxDate(datePromises) {
const pMaxDate = Promise.
all(datePromises).
then((dates) => maxDate(dates));
pMaxDate.catch((e) => {
console.error(e);
});
return pMaxDate;
}
function promiseMtime(path) {
return promiseStat(path).then(({mtime}) => mtime);
}
function promiseMtimes(path, mtimes = []) {
return promiseLstat(path).then((stats) => {
const mtimes2 = mtimes.concat([stats.mtime]);
if (stats.isSymbolicLink()) {
// eslint-disable-next-line promise/no-nesting
const p = promiseReadlink(path).then(
(linkTarget) => promiseMtimes(linkTarget, mtimes2)
);
// eslint-disable-next-line promise/no-nesting
p.catch((e) => {
console.error(`readlink("${path}"):`, e);
});
return p;
}
return mtimes2;
});
}
const getDependenciesMtimes = (function() {
let pMtimes;
let dependencies = [
"config.json",
"gulpfile.js",
"package.json",
"tsconfig.json",
"src/conditional/legacy/webextension/tsconfig.json",
].map((filename) => `${rootDir}/${filename}`);
return function getDependenciesMtimes() {
if (!pMtimes) {
const pMtimeArrays = dependencies.map((dep) => promiseMtimes(dep));
pMtimes = Promise.all(pMtimeArrays).
then((mtimeArrays) => {
let mtimes = [];
mtimeArrays.forEach((mtimeArray) => {
mtimes = mtimes.concat(mtimeArray);
});
return mtimes;
});
}
return pMtimes;
};
})();
async function compareLastModifiedTime(stream, sourceFile, targetPath) {
const depsMaxDate = await getDependenciesMtimes().then(promiseMaxDate);
const sourceMaxDate = await promiseMtimes(sourceFile.path).then(promiseMaxDate);
const targetMtime = await promiseMtime(targetPath);
if (depsMaxDate > targetMtime || sourceMaxDate > targetMtime) {
stream.push(sourceFile);
}
}
function _sanitizeArgsForAddTask(aFn) {
return function(name, deps, fn) {
/* eslint-disable no-param-reassign */
if (fn === undefined && typeof deps === "function") {
fn = deps;
deps = [];
}
// eslint-disable-next-line no-invalid-this
aFn.call(this, name, deps, fn);
};
}
// ensure that the function passed to "gulp.task" always returns something
// (e.g. a promise, a stream)
gulp.task = (function() {
const origGulpTask = gulp.task;
return _sanitizeArgsForAddTask(function(name, deps, fn) {
if (fn !== undefined) {
const origFn = fn;
fn = (...args) => {
let rv = origFn(...args);
if (rv === undefined) {
throw new Error("Function returns undefined");
}
return rv;
};
}
// eslint-disable-next-line no-invalid-this
origGulpTask.call(this, name, deps, fn);
});
})();
const addGulpTasks = _sanitizeArgsForAddTask((namePrefix, forcedDeps, taskAdder) => {
const tasks = [];
const addTaskFn = _sanitizeArgsForAddTask((name, deps, taskFn) => {
name = `${namePrefix}:${name}`;
deps = forcedDeps.concat(deps);
tasks.push(name);
taskFn = taskFn.bind(null, namePrefix);
gulp.task(name, deps, taskFn);
});
taskAdder(addTaskFn, namePrefix);
// finally, when all tasks are added, add the meta-task
gulp.task(namePrefix, tasks);
});
const localesPath = "./src/conditional/webextension/_locales";
const locales = (function() {
let $locales = null;
return {
get() {
if ($locales === null) {
$locales = fs.readdirSync(localesPath);
}
return $locales;
},
};
})();
function getInstallRdfLocalizedSection() {
let lines = [];
const line = (str) => ` ${str}`;
function getValues(localeDirname, defaultValues=null) {
const filepath = `${localesPath}/${localeDirname}/messages.json`;
const fileContents = require(filepath);
const get = (key, fileKey) => (
fileKey in fileContents ? fileContents[fileKey].message :
defaultValues[key]
);
return {
locale: localeDirname.replace("_", "-"),
name: get("name", "extensionName"),
description: get("description", "extensionDescription"),
};
}
function addValues({locale, name, description}) {
lines = lines.concat([
line(`<em:localized>`),
line(` <Description>`),
line(` <em:locale>${locale}</em:locale>`),
line(` <em:name>${name}</em:name>`),
line(` <em:description>${description}</em:description>`),
line(` </Description>`),
line(`</em:localized>`),
]);
}
const defaultLocaleDirname = "en_US";
const defaultValues = getValues(defaultLocaleDirname);
addValues(defaultValues);
locales.get().forEach((localeDirname) => {
if (localeDirname === defaultLocaleDirname) return;
const values = getValues(localeDirname, defaultValues);
addValues(values);
});
return lines.join("\n");
}
// -----------------------------------------------------------------------------
// version strings
// -----------------------------------------------------------------------------
const versionData = {};
gulp.task("versionData:uniqueVersionSuffix", () => new Promise((resolve, reject) => {
exec(
`
rev_count=$(git rev-list HEAD | wc --lines);
commit_sha=$(git rev-parse --short HEAD);
echo ".\${rev_count}.r\${commit_sha}.pre";
`,
(err, out) => {
if (err) {
reject(err);
return;
}
versionData.uniqueVersionSuffix = out.trim();
resolve();
}
);
}));
gulp.task("versionData:nonUniqueVersion", () => {
versionData.nonUniqueVersion = config.version;
return Promise.resolve();
});
gulp.task("versionData:uniqueVersion", ["versionData:uniqueVersionSuffix"], () => {
versionData.uniqueVersion = `${config.version}${versionData.uniqueVersionSuffix}`;
return Promise.resolve();
});
// =============================================================================
// builds
// =============================================================================
/* eslint-disable max-len */
const BUILDS = [
{ alias: "ui-testing", isDev: true, forceCleanBuild: false, isAMO: false, channel: "nightly", version: "uniqueVersion" },
{ alias: "dev", isDev: true, forceCleanBuild: false, isAMO: false, channel: "nightly", version: "uniqueVersion" },
{ alias: "nightly", isDev: false, forceCleanBuild: true, isAMO: false, channel: "nightly", version: "uniqueVersion" },
{ alias: "beta", isDev: false, forceCleanBuild: true, isAMO: false, channel: "beta", version: "nonUniqueVersion" },
{ alias: "amo-nightly", isDev: false, forceCleanBuild: true, isAMO: true, channel: "nightly", version: "uniqueVersion" },
{ alias: "amo-beta", isDev: false, forceCleanBuild: true, isAMO: true, channel: "beta", version: "nonUniqueVersion" },
];
/* eslint-enable max-len */
const EXTENSION_TYPES = [
"legacy",
];
const DEFAULT_EXTENSION_TYPE = "legacy";
BUILDS.forEach((build) => {
gulp.task(`build:${build.alias}`, [`build:${DEFAULT_EXTENSION_TYPE}:${build.alias}`]);
gulp.task(`xpi:${build.alias}`, [`xpi:${DEFAULT_EXTENSION_TYPE}:${build.alias}`]);
EXTENSION_TYPES.forEach((extensionType) => {
const buildDirRelative = `build/${extensionType}/${build.alias}`;
const buildDir = `${rootDir}/${buildDirRelative}`;
const TASK_NAMES = {
ppContext: `buildData:${extensionType}:${build.alias}:preprocessContext`,
version: `versionData:${build.version}`,
};
// -------------------------------------------------------------------------
// clean, XPI
// -------------------------------------------------------------------------
gulp.task(`clean:${extensionType}:${build.alias}`, () => del([buildDir]));
gulp.task(`xpi:${extensionType}:${build.alias}`,
[`build:${extensionType}:${build.alias}`],
() => {
const xpiSuffix = "xpiSuffix" in build ? build.xpiSuffix :
`-${extensionType}-${build.alias}`;
let stream = gulp.src(`${buildDir}/**/*`, { base: buildDir }).
pipe(zip(`${EXTENSION_NAME}${xpiSuffix}.xpi`)).
pipe(gulp.dest("dist"));
return stream;
});
// -------------------------------------------------------------------------
// build data
// -------------------------------------------------------------------------
const buildData = {};
addGulpTasks(`buildData:${extensionType}:${build.alias}`, (addTask) => {
addTask("preprocessContext", [TASK_NAMES.version], () => {
const context = buildData.ppContext = {
"BUILD_ALIAS": build.alias,
"EXTENSION_ID": build.isAMO ? EXTENSION_ID__AMO : EXTENSION_ID__OFF_AMO,
"ALPHABETICAL_ID": build.isAMO ? ALPHABETICAL_ID__AMO : ALPHABETICAL_ID__OFF_AMO,
"EXTENSION_TYPE": extensionType,
"RELEASE_CHANNEL": build.channel,
"RP_HOMEPAGE_URL": config.homepage,
"RP_VERSION": versionData[build.version],
"LOCALES": JSON.stringify(locales.get()),
"INSTALL_RDF_LOCALIZED_SECTION": getInstallRdfLocalizedSection(),
};
if (build.isAMO) context.AMO = "TRUE";
return Promise.resolve();
});
});
// -------------------------------------------------------------------------
// build utilities
// -------------------------------------------------------------------------
const conditionalDirsRelative = [extensionType].
concat(build.alias === "ui-testing" ? ["ui-testing"] : []).
map((name) => `conditional/${name}`);
const conditionalDirsWithSrc = conditionalDirsRelative.
map((dir) => `${srcDir}/${dir}`);
// eslint-disable-next-line camelcase
function mergeInConditional_mapDirname(dirname) {
conditionalDirsRelative.forEach((dir) => {
// non-root files
dirname = dirname.replace(`${dir}/`, "");
// root files, e.g. conditional/legacy/bootstrap.js
dirname = dirname.replace(dir, "");
});
return dirname;
}
function mergeInConditional(path) {
path.dirname = mergeInConditional_mapDirname(path.dirname);
}
function inAnyRoot(aFilenames) {
const roots = [srcDir].concat(conditionalDirsWithSrc);
return aFilenames.reduce((accumulator, curFilename) => {
if (curFilename.startsWith("**")) {
throw new Error("paths passed must not start with '**'");
}
return accumulator.concat(roots.map((root) => `${root}/${curFilename}`));
}, []);
}
// ---------------------------------------------------------------------------
// main build tasks
// ---------------------------------------------------------------------------
const buildDeps = [];
if (build.forceCleanBuild) buildDeps.push(`clean:${extensionType}:${build.alias}`);
// eslint-disable-next-line complexity
addGulpTasks(`build:${extensionType}:${build.alias}`, buildDeps, (
addBuildTask, buildTaskPrefix
) => {
addBuildTask("copiedFiles", () => {
let files = [
"README",
"LICENSE",
"content/lib/third-party/static/**/*.js",
"skin/*.png",
"skin/*.svg",
];
switch (extensionType) {
case "legacy":
files = files.concat([
"chrome.manifest",
"content/**/*.xul",
"locale/*/*.dtd",
"locale/*/*.properties",
"webextension/background.html",
"webextension/lib/third-party/**/*.js",
]);
break;
}
files = inAnyRoot(files);
let stream = gulp.src(files, { base: srcDir }).
pipe(rename(mergeInConditional)).
pipe(gulp.dest(buildDir));
return stream;
});
// ---
function addPreprocessedFilesBuildTask(aFileType, aFiles) {
return addBuildTask(`${aFileType}TypePreprocessedFiles`, [TASK_NAMES.ppContext], () => {
let files = inAnyRoot(aFiles);
let stream = gulp.src(files, { base: srcDir }).
pipe(rename(mergeInConditional)).
pipe(preprocess({ context: buildData.ppContext, extension: aFileType })).
pipe(gulp.dest(buildDir));
return stream;
});
}
addPreprocessedFilesBuildTask("xml", [
"content/**/*.html",
].concat(
extensionType === "webextension" ? [
] : [],
extensionType === "legacy" ? [
"install.rdf",
] : []
));
addPreprocessedFilesBuildTask("js", [
"content/**/*.css",
].concat(
extensionType === "webextension" ? [
"_locales/**/messages.json",
"manifest.json",
] : extensionType === "legacy" ? [
"content/bootstrap-data/locales.json",
"content/bootstrap-data/manifest.json",
"content/_locales/**/messages.json",
"skin/*.css",
"webextension/manifest.json",
] : []
));
// ---
const tsConfigOverride = {
rootDir: srcDir,
outDir: srcDir, // virtual (!) output directory
// <hack>
// For whatever inexplicable reason, "content/settings/common.js" and
// "content/ui/request-log/tree-view.js" are removed by tsProject() if
// `isolatedModules` is false. However, when the two files are renamed
// to "common_.js" and "tree-view_.js", respectively, the files are created
// correctly in the build directory. This is very likely a bug in the
// "gulp-typescript" module.
isolatedModules: true,
// </hack>
};
if (build.isDev) tsConfigOverride.removeComments = false;
Object.freeze(tsConfigOverride);
const moduleRootInfos = {
"main": {
moduleRoot: "content",
tsConfigPath: "tsconfig.json",
additionalFiles: extensionType === "legacy" ? [
"bootstrap.js",
] : [],
},
"embedded-we": {
moduleRoot: "webextension",
tsConfigPath: "src/conditional/legacy/webextension/tsconfig.json",
additionalFiles: [],
},
};
function addJsBuildTask(aModuleRootAlias) {
const {
moduleRoot,
additionalFiles,
tsConfigPath,
} = moduleRootInfos[aModuleRootAlias];
const otherModuleRoots = Object.keys(moduleRootInfos).
filter((alias) => alias !== aModuleRootAlias).
map((alias) => moduleRootInfos[alias].moduleRoot);
const subRoots = otherModuleRoots.
filter((otherRoot) => otherRoot.startsWith(`${moduleRoot}/`));
const tsProject = ts.createProject(tsConfigPath, tsConfigOverride);
return addBuildTask(`js:${aModuleRootAlias}`, [TASK_NAMES.ppContext], () => {
let files = [`${moduleRoot}/**/*.*(js|jsm|ts)`].concat(additionalFiles);
files = inAnyRoot(files);
files.push("!**/third-party/static/**/*");
let subRootFiles = [];
for (let subRoot of subRoots) {
subRootFiles.push(`${subRoot}/**/*`);
subRootFiles.push(`${subRoot}/*`);
}
subRootFiles = inAnyRoot(subRootFiles);
files = files.concat(subRootFiles.map((file) => `!${file}`));
let stream = gulp.src(files, { base: srcDir }).
pipe(gulpif(!build.forceCleanBuild, changed(buildDir, {
hasChanged: compareLastModifiedTime,
transformPath(aPath) {
let path = mergeInConditional_mapDirname(aPath);
path = path.replace(/\.(ts)$/, ".js");
return path;
},
}))).
pipe(replace(
/console\.(error|warn|info|log|debug)\(\s*(["'`)]?)/g,
(match, fn, nextChar) => {
let argsPrefix =
nextChar === ")" ? `"[RequestPolicy]")` :
nextChar === "" ? `"[RequestPolicy] " + ` :
`${nextChar}[RequestPolicy] `;
return `console.${fn}(${argsPrefix}`;
}
)).
pipe(preprocess({ context: buildData.ppContext, extension: "js" })).
pipe(gulpif(build.isDev, sourcemaps.init()));
stream = mergeStream(
// non-jsm files
stream.
pipe(fileFilter.include({isModule: true})).
pipe(tsProject()).js,
// jsm files
stream.
pipe(fileFilter.include({isModule: false}))
);
stream = stream.
// WORKAROUND NOTICE:
// `mergeInConditional` is applied _after_ typescript because I had
// sourcemapping issues when it was the other way around.
// (gulp-typescript did not correctly respect the previously created
// sourcemap.)
pipe(rename(mergeInConditional)).
pipe(gulpif(build.isDev,
sourcemaps.write({
destPath: buildDir,
sourceRoot: `file://${srcDir}`,
}))).
pipe(gulp.dest(buildDir));
return stream;
});
}
addJsBuildTask("main");
if (extensionType === "legacy") {
addJsBuildTask("embedded-we");
}
});
});
});
// =============================================================================
// default task
// =============================================================================
gulp.task("default", ["xpi:nightly"]);