forked from adblockplus/buildtools
/
packagerEdge.py
195 lines (152 loc) · 6.86 KB
/
packagerEdge.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
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import base64
import hashlib
import json
import mimetypes
import os
import zipfile
import packager
import packagerChrome
# Files and directories expected inside of the .APPX archive.
MANIFEST = 'AppxManifest.xml'
CONTENT_TYPES = '[Content_Types].xml'
BLOCKMAP = 'AppxBlockMap.xml'
EXTENSION_DIR = 'Extension'
ASSETS_DIR = 'Assets'
# Size of uncompressed block in the APPX block map.
BLOCKSIZE = 64 * 1024
defaultLocale = packagerChrome.defaultLocale
def _get_template_for(filename):
return packager.getTemplate('edge/{}.tmpl'.format(filename))
def _lfh_size(filename):
"""Compute the size of zip local file header for `filename`."""
try:
filename = filename.encode('utf-8')
except UnicodeDecodeError:
pass # filename is already a byte string.
return zipfile.sizeFileHeader + len(filename)
def _make_blockmap_entry(filename, data):
blocks = [data[i:i + BLOCKSIZE] for i in range(0, len(data), BLOCKSIZE)]
return {
'name': filename.replace('/', '\\'),
'size': len(data),
'lfh_size': _lfh_size(filename),
'blocks': [
{'hash': base64.b64encode(hashlib.sha256(block).digest())}
for block in blocks
]
}
def create_appx_blockmap(files):
"""Create APPX blockmap for the list of files."""
# We don't support AppxBlockmap.xml generation for compressed zip files at
# the moment. The only way to reliably calculate the compressed size of
# each 64k chunk in the zip file is to override the relevant parts of
# `zipfile` library. We have chosen to not do it so we produce an
# uncompressed zip file that is later repackaged by Windows Store with
# compression.
template = _get_template_for(BLOCKMAP)
files = [_make_blockmap_entry(n, d) for n, d in files.items()]
return template.render(files=files).encode('utf-8')
def load_translation(files, locale):
"""Load translation strings for locale from files."""
path = '{}/_locales/{}/messages.json'.format(EXTENSION_DIR, locale)
return json.loads(files[path])
def pad_version(version):
"""Make sure version number has 4 groups of digits."""
groups = (version.split('.') + ['0', '0', '0'])[:4]
return '.'.join(groups)
def create_appx_manifest(params, files, release_build=False):
"""Create AppxManifest.xml."""
params = dict(params)
metadata = params['metadata']
w = params['windows_version'] = {}
w['min'], w['max'] = metadata.get('compat', 'windows').split('/')
params.update(metadata.items('general'))
params['version'] = pad_version(params['version'])
metadata_suffix = 'release' if release_build else 'devbuild'
app_extension_id = 'extension_id_' + metadata_suffix
if metadata.has_option('general', app_extension_id):
params['app_extension_id'] = metadata.get('general', app_extension_id)
else:
params['app_extension_id'] = 'EdgeExtension'
app_id = 'app_id_' + metadata_suffix
params['app_id'] = metadata.get('general', app_id)
translation = load_translation(files, defaultLocale)
name_key = 'name' if release_build else 'name_devbuild'
params['display_name'] = translation[name_key]['message']
params['description'] = translation['description']['message']
for size in ['44', '50', '150']:
path = '{}/logo_{}.png'.format(ASSETS_DIR, size)
if path not in files:
raise KeyError(path + ' is not found in files')
params['logo_' + size] = path.replace('/', '\\')
template = _get_template_for(MANIFEST)
return template.render(params).encode('utf-8')
def move_files_to_extension(files):
"""Move all files into `Extension` folder for APPX packaging."""
# We sort the files to ensure that 'Extension/xyz' is moved before 'xyz'.
# If 'xyz' is moved first, it would overwrite 'Extension/xyz' and its
# original content would be lost.
names = sorted(files.keys(), key=len, reverse=True)
for filename in names:
files['{}/{}'.format(EXTENSION_DIR, filename)] = files.pop(filename)
def create_content_types_map(filenames):
"""Create [Content_Types].xml -- a mime type map."""
params = {'defaults': {}, 'overrides': {}}
overrides = {
BLOCKMAP: 'application/vnd.ms-appx.blockmap+xml',
MANIFEST: 'application/vnd.ms-appx.manifest+xml'
}
types = mimetypes.MimeTypes()
types.add_type('application/octet-stream', '.otf')
for filename in filenames:
ext = os.path.splitext(filename)[1]
if ext:
content_type = types.guess_type(filename, strict=False)[0]
if content_type is not None:
params['defaults'][ext[1:]] = content_type
if filename in overrides:
params['overrides']['/' + filename] = overrides[filename]
content_types_template = _get_template_for(CONTENT_TYPES)
return content_types_template.render(params).encode('utf-8')
def createBuild(baseDir, type='edge', outFile=None, # noqa: preserve API.
buildNum=None, releaseBuild=False, keyFile=None,
devenv=False):
metadata = packager.readMetadata(baseDir, type)
version = packager.getBuildVersion(baseDir, metadata, releaseBuild,
buildNum)
outfile = outFile or packager.getDefaultFileName(metadata, version, 'appx')
params = {
'type': type,
'baseDir': baseDir,
'releaseBuild': releaseBuild,
'version': version,
'devenv': devenv,
'metadata': metadata,
}
files = packager.Files(packagerChrome.getPackageFiles(params),
packagerChrome.getIgnoredFiles(params))
if metadata.has_section('mapping'):
mapped = metadata.items('mapping')
files.readMappedFiles(mapped)
files.read(baseDir, skip=[filename for filename, _ in mapped])
else:
files.read(baseDir)
if metadata.has_section('convert_js'):
packagerChrome.convertJS(params, files)
if metadata.has_section('preprocess'):
files.preprocess(metadata.options('preprocess'), {'needsExt': True})
if metadata.has_section('import_locales'):
packagerChrome.importGeckoLocales(params, files)
files['manifest.json'] = packagerChrome.createManifest(params, files)
move_files_to_extension(files)
if metadata.has_section('appx_assets'):
for name, path in metadata.items('appx_assets'):
path = os.path.join(baseDir, path)
files.read(path, '{}/{}'.format(ASSETS_DIR, name))
files[MANIFEST] = create_appx_manifest(params, files, releaseBuild)
files[BLOCKMAP] = create_appx_blockmap(files)
files[CONTENT_TYPES] = create_content_types_map(files.keys() + [BLOCKMAP])
files.zip(outfile, compression=zipfile.ZIP_STORED)