forked from downthemall/downthemall-legacy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
make.py
executable file
·577 lines (471 loc) · 15.1 KB
/
make.py
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
#!/usr/bin/env python3
""" Build a DownThemAll! xpi"""
# pylint: disable=too-few-public-methods,broad-except,invalid-name,missing-docstring
import os
import re
import sys
from fnmatch import fnmatch
from functools import wraps
from glob import glob
from io import BytesIO
from argparse import ArgumentParser
from time import strftime
from warnings import warn
from xml.dom.minidom import parseString as XML
from zipfile import ZipFile, ZIP_STORED, ZIP_DEFLATED
NS_RDF = "http://www.w3.org/1999/02/22-rdf-syntax-ns#"
NS_EM = "http://www.mozilla.org/2004/em-rdf#"
RELEASE_ID = "{DDC359D1-844A-42a7-9AA1-88A850A938A8}"
FILES = (
"install.rdf",
"icon*.png",
"bootstrap.js",
"MPL", "GPL", "LGPL", "LICENSE",
"chrome.manifest",
"chrome/content/about/about.xul",
"chrome/content/common/",
"chrome/content/dta/",
"chrome/content/integration/",
"chrome/content/preferences/",
"chrome/content/privacy/",
"chrome/content/mac/",
"chrome/content/unix/",
"chrome/content/win/",
"chrome/public/",
"chrome/skin/",
"chrome/locale/*/",
"modules/*.js*",
"modules/loaders/",
"modules/manager/",
"modules/support/",
"modules/thirdparty/",
)
TESTS = (
"modules/tests/",
"tests",
)
EXCLUDED = (
"chrome/locale/*/landingpage.dtd",
"chrome/locale/*/description.properties",
)
PLAIN = (
"*.png",
"*.jpg",
"*.gif",
)
try:
from xpisign.context import ZipFileMinorCompression as _Minor
class Minor(_Minor):
""" Compatiblity stub"""
@property
def compat(self):
"""Only a compat layer"""
return False
except ImportError:
warn("No optimal compression available")
class Minor(object):
""" Compatiblity stub"""
def __init__(self, *args):
pass
def __enter__(self):
pass
def __exit__(self, *args):
pass
@property
def compat(self):
"""Only a compat layer"""
return True
try:
from Mozilla.CompareLocales import compareDirs as compare_locales
except ImportError:
warn("CompareLocales is not available!")
compare_locales = None
class Reset(object):
"""
Reset the tracked file-like object stream position when done
"""
def __init__(self, filep):
self.filep = filep
self.position = 0
def __enter__(self):
self.position = self.filep.tell()
def __exit__(self, *args):
self.filep.seek(self.position, 0)
class WorkingDirectory(object):
"""
Change the working directory to make.py's path and restore when done
"""
def __init__(self):
self.workdir = "."
def __enter__(self):
self.workdir = os.getcwd()
try:
os.chdir(os.path.split(__file__)[0])
except Exception:
pass
def __exit__(self, *args):
os.chdir(self.workdir)
@staticmethod
def change(func):
"""
Decorator: Change the working directory before calling wrapped
function.
"""
@wraps(func)
def wrapper(*args, **kw):
""" Automatic changing of working directory"""
with WorkingDirectory():
return func(*args, **kw)
return wrapper
@WorkingDirectory.change
def check_locales(errors_only=False):
"""
Checks all chrome.manifest listed locales are complete and without errors.
"""
if not compare_locales:
return
listed = dict()
with open("chrome.manifest", "r", encoding="utf-8") as manip:
expr = re.compile(r"^locale\s+.+?\s+(.+?)\s+(.+?)\s*$")
for line in manip:
match = expr.match(line)
if not match:
continue
locale, loc = match.groups()
listed[locale] = loc
if not listed:
raise ValueError("did not read any locales")
if len(listed) == 1:
return
for locale in ("en-US", "en", "de", "fr"):
baseloc = listed.pop(locale, None)
if baseloc:
break
else:
raise ValueError("failed to determine base locale")
for locale, locpath in listed.items():
if not os.path.isdir(locpath):
raise ValueError("Listed locale not available {}".format(locale))
res = compare_locales(baseloc, locpath)
summary = res.getSummary()[None]
if "errors" in summary or (not errors_only and "missing" in summary):
raise ValueError("{}: {}\n{}".format(locale, summary, res.details))
def filesort(file):
"""
Package file sort keys
"""
if file in ("install.rdf",):
return 0, file
if file in ("bootstrap.js", "chrome.manifest"):
return 1, file
if fnmatch(file, "icon*.png"):
return 2, file
if fnmatch(file, "modules/*"):
return 3, file
if file in ("MPL", "GPL", "LGPL", "LICENSE"):
return 1000, file
return 500, file
def files(*args, **kw):
"""
Generator over all file listing the given patterns.
All arguments will be considered patterns.
excluded keyword arg may specify a list of patterns that won't be returned
"""
excluded = kw.pop("excluded", ())
def items(file):
"""Enumerate files"""
if os.path.isdir(file):
if not file.endswith("/"):
file += "/"
for i in files(file + "*"):
yield i
elif os.path.isfile(file) and \
not any(fnmatch(file, x) for x in excluded):
yield file.replace("\\", "/")
for p in args:
gg = glob(p)
if not gg:
raise ValueError("{} did not match anything!".format(p))
for g in gg:
for i in items(g):
yield i
def releaseversionjs(fp, **kw):
""" Preprocess version.js in release mode """
kw = kw
io = BytesIO()
with Reset(io):
for l in fp:
if b"const ID = " in l:
io.write(('const ID = "{}";\n'.format(RELEASE_ID)).encode("utf-8"))
else:
io.write(l)
io.truncate()
return io
def droptests(fp, **kw):
""" Drop tests from chrome.manifest """
kw = kw
io = BytesIO()
with Reset(io):
for l in fp:
if b"dta-tests" in l:
continue
io.write(l)
io.truncate()
return io
def localize(fp, **kw):
""" Generate em:localized """
kw = kw
def sort(f):
if "en-US" in f["locale"]:
return 0, f["locale"]
return 1, f["locale"]
def get_locale_strings():
locales = list()
for f in sorted(files("chrome/locale/*/description.properties")):
locale = dict(locale=(f.split("/", 3)[2],))
with open(f, "r", encoding="utf-8") as lp:
for l in lp:
l = l.strip()
if not l or l.startswith("#"):
continue
k, v = l.split("=", 1)
k = k.split(".")
k = k[-2] if len(k[-1]) < 3 else k[-1]
if not k or not v:
continue
if k not in locale:
locale[k] = list()
locale[k] += v,
locales += locale,
return locales
locales = get_locale_strings()
with Reset(fp):
rdf = XML(fp.read())
# kill old localized
for e in rdf.getElementsByTagNameNS(NS_EM, "localized"):
e.parentNode.removeChild(e)
def mapkey(k):
v = list()
for e in rdf.getElementsByTagNameNS(NS_EM, k):
v += e.firstChild.data,
return k, v
keys = ("locale", "name", "description", "creator", "homepageURL",
"developer", "translator", "contributor")
baseprops = dict(mapkey(k) for k in keys)
def add_props():
parent = rdf.getElementsByTagNameNS(NS_EM, "id")[0].parentNode
for props in sorted(locales, key=sort):
node = rdf.createElementNS(NS_EM, "em:localized")
desc = rdf.createElementNS(NS_RDF, "Description")
for k in keys:
vals = props.get(k, baseprops.get(k, list()))
for v in vals:
n = rdf.createElementNS(NS_EM, "em:" + k)
n.appendChild(rdf.createTextNode(v))
desc.appendChild(n)
parent.appendChild(rdf.createTextNode("\n\t\t"))
node.appendChild(desc)
parent.appendChild(node)
parent.appendChild(rdf.createTextNode("\n\t"))
add_props()
io = BytesIO()
with Reset(io):
io.write(rdf.toxml(encoding="utf-8"))
io.truncate()
rdf.unlink()
return io
def localized(fn):
""" Decorator: Wrap an install.rdf processor to also localize() """
@wraps(fn)
def wrapper(fp, **kw):
fp = fn(fp, **kw)
return localize(fp, **kw)
return wrapper
def releasify(fp, **kw):
""" Decorator: Transform into release version """
kw = kw
with Reset(fp):
rdf = XML(fp.read())
node = rdf.getElementsByTagNameNS(NS_EM, "id")[0].childNodes[0]
node.data = RELEASE_ID
io = BytesIO()
with Reset(io):
io.write(rdf.toxml(encoding="utf-8"))
io.truncate()
rdf.unlink()
return io
def set_uurl(fp, **kw):
""" Set the updateURL """
with Reset(fp):
rdf = XML(fp.read())
node = rdf.getElementsByTagNameNS(NS_EM, 'aboutURL')[0]
u = rdf.createElementNS(NS_EM, 'em:updateURL')
u.appendChild(rdf.createTextNode(kw.get("updateurl")))
node.parentNode.insertBefore(u, node)
node.parentNode.insertBefore(rdf.createTextNode('\n\t\t'), node)
io = BytesIO()
with Reset(io):
io.write(rdf.toxml(encoding="utf-8"))
io.truncate()
rdf.unlink()
return io
@localized
def releaserdf(fp, **kw):
""" Preprocesses install.rdf for release mode """
with Reset(fp):
rdf = XML(fp.read())
node = rdf.getElementsByTagNameNS(NS_EM, 'version')[0].childNodes[0]
if not re.match(r"^[\d.]+$", node.data) and not kw.get("force"):
raise ValueError("Invalid release version: {}".format(node.data))
return releasify(fp, **kw)
@localized
def betardf(fp, **kw):
""" Preprocess install.rdf for beta mode """
with Reset(fp):
rdf = XML(fp.read())
node = rdf.getElementsByTagNameNS(NS_EM, 'version')[0].firstChild
if not re.match(r"^\d\.\db\d+$", node.data):
raise ValueError("Invalid beta version: {}".format(node.data))
return set_uurl(releasify(fp, **kw), **kw)
@localized
def nightlyrdf(fp, **kw):
""" Preprocesses install.rdf for nightly mode """
rdf = XML(fp.read())
# update the version
node = rdf.getElementsByTagNameNS(NS_EM, 'version')[0].childNodes[0]
node.data += strftime(".%Y%m%d.%Hh%Mm%Ss")
# a new name
node = rdf.getElementsByTagNameNS(NS_EM, 'name')[0].childNodes[0]
node.data += " *nightly*"
io = BytesIO()
with Reset(io):
io.write(rdf.toxml(encoding="utf-8"))
io.truncate()
rdf.unlink()
return set_uurl(io, **kw)
@localized
def devrdf(fp, **kw):
""" Preprocesses install.rdf for default mode """
kw = kw
rdf = XML(fp.read())
node = rdf.getElementsByTagNameNS(NS_EM, 'name')[0].childNodes[0]
node.data += " *unofficial developer build*"
io = BytesIO()
with Reset(io):
io.write(rdf.toxml(encoding="utf-8"))
io.truncate()
rdf.unlink()
return io
@WorkingDirectory.change
def pack(xpi, patterns, **kw):
""" Build the actual XPI """
packing = sorted(set(files(*patterns, excluded=EXCLUDED)),
key=filesort)
with ZipFile(xpi, "w", ZIP_DEFLATED) as zp:
def write(fn, mode, modifier=None):
"""Write a file, propably modified"""
with open(fn, "rb") as fp:
if modifier:
with modifier(fp, **kw) as mp:
zp.writestr(fn, mp.read(), mode)
else:
zp.writestr(fn, fp.read(), mode)
with Minor(zp):
for f in packing:
if f == "modules/version.js" and \
kw.get("type", None) in ("release", "beta"):
write(f, ZIP_DEFLATED, releaseversionjs)
elif f == "install.rdf":
t = kw.get("type", None)
if t == "release":
write(f, ZIP_DEFLATED, releaserdf)
elif t == "beta":
write(f, ZIP_DEFLATED, betardf)
elif t == "nightly":
write(f, ZIP_DEFLATED, nightlyrdf)
else:
write(f, ZIP_DEFLATED, devrdf)
elif not kw.get("tests", False) and \
(f == "chrome.manifest" or f == "modules/main.js"):
write(f, ZIP_DEFLATED, droptests)
elif any(fnmatch(f, p) for p in PLAIN):
write(f, ZIP_STORED)
else:
write(f, ZIP_DEFLATED)
def create(args):
""" Process arguments and create the XPI """
parser = ArgumentParser()
parser.add_argument(
"--force",
dest="force",
help="force overwrite output file if exists",
action="store_true",
default=False
)
parser.add_argument(
"--release",
dest="type",
help="create release XPI",
action="store_const",
const="release"
)
parser.add_argument(
"--beta",
dest="type",
help="create release XPI",
action="store_const",
const="beta"
)
parser.add_argument(
"--nightly",
dest="type",
help="create nightly XPI",
action="store_const",
const="nightly"
)
parser.add_argument(
"--updateURL",
dest="updateurl",
help="nightly update url",
type=str,
default=None
)
parser.add_argument(
"--tests",
dest="tests",
help="ships tests as well",
action="store_true",
default=False
)
parser.add_argument(
"xpi",
nargs=1,
type=str,
help="output XPI"
)
args = parser.parse_args(args)
patterns = FILES
if args.tests:
patterns += TESTS
output = args.xpi.pop()
del args.xpi
if args.type in ("nightly", "beta") and not args.updateurl:
raise ValueError("Nightly/Beta requested but no update URL provided")
elif args.type == "release" and args.updateurl:
raise ValueError("Release versions cannot have an update URL")
if not args.force and os.path.exists(output):
raise ValueError("Output file already exists")
check_locales(errors_only=True)
with BytesIO() as io:
try:
with Reset(io):
pack(io, patterns, **args.__dict__)
except Exception as ex:
raise Exception("Failed packing: {}".format(ex)) from ex
try:
with open(output, "wb") as op:
op.write(io.read())
except Exception as ex:
raise Exception("Failed writing XPI: {}".format(ex)) from ex
if __name__ == "__main__":
create(sys.argv[1:])