Left: | ||
Right: |
LEFT | RIGHT |
---|---|
1 # This Source Code Form is subject to the terms of the Mozilla Public | 1 # This Source Code Form is subject to the terms of the Mozilla Public |
2 # License, v. 2.0. If a copy of the MPL was not distributed with this | 2 # License, v. 2.0. If a copy of the MPL was not distributed with this |
3 # file, You can obtain one at http://mozilla.org/MPL/2.0/. | 3 # file, You can obtain one at http://mozilla.org/MPL/2.0/. |
4 | 4 |
5 import base64 | 5 import base64 |
6 import hashlib | 6 import hashlib |
7 import json | |
8 import mimetypes | |
7 import os | 9 import os |
8 import zipfile | 10 import zipfile |
9 | 11 |
10 import packager | 12 import packager |
11 import packagerChrome | 13 import packagerChrome |
12 | 14 |
15 # Files and directories expected inside of the .APPX archive. | |
13 MANIFEST = 'AppxManifest.xml' | 16 MANIFEST = 'AppxManifest.xml' |
14 CONTENT_TYPES = '[Content_Types].xml' | 17 CONTENT_TYPES = '[Content_Types].xml' |
15 BLOCKMAP = 'AppxBlockMap.xml' | 18 BLOCKMAP = 'AppxBlockMap.xml' |
16 BLOCKSIZE = 65536 | 19 EXTENSION_DIR = 'Extension' |
Wladimir Palant
2016/06/17 09:53:46
Maybe more obvious if hexadecimal - 0x10000?
Vasily Kuznetsov
2016/06/17 17:53:26
I'm not sure if it's actually more obvious. Becaus
| |
20 ASSETS_DIR = 'Assets' | |
17 | 21 |
18 # Size of the fixed part of Zip local file header. | 22 # Size of uncompressed block in the APPX block map. |
19 # See https://en.wikipedia.org/wiki/Zip_(file_format)#File_headers | 23 BLOCKSIZE = 64 * 1024 |
20 LFH_FIXED_SIZE = 30 | 24 |
Wladimir Palant
2016/06/17 09:53:46
zipfile.sizeFileHeader?
Vasily Kuznetsov
2016/06/17 17:53:27
Oh, I didn't know about this constant. It's not me
| |
25 defaultLocale = packagerChrome.defaultLocale | |
21 | 26 |
22 | 27 |
23 def _get_template_for(filename): | 28 def _get_template_for(filename): |
24 return packager.getTemplate('edge/{}.tmpl'.format(filename)) | 29 return packager.getTemplate('edge/{}.tmpl'.format(filename)) |
25 | 30 |
26 | 31 |
27 def _SHA256(block): | 32 def _lfh_size(filename): |
28 h = hashlib.new('sha256') | 33 """Compute the size of zip local file header for `filename`.""" |
29 h.update(block) | 34 try: |
30 return base64.b64encode(h.digest()) | 35 filename = filename.encode('utf-8') |
36 except UnicodeDecodeError: | |
37 pass # filename is already a byte string. | |
38 return zipfile.sizeFileHeader + len(filename) | |
31 | 39 |
32 | 40 |
33 def _make_blockmap_entry(filename, data): | 41 def _make_blockmap_entry(filename, data): |
34 blocks = [data[i:i + BLOCKSIZE] for i in range(0, len(data), BLOCKSIZE)] | 42 blocks = [data[i:i + BLOCKSIZE] for i in range(0, len(data), BLOCKSIZE)] |
35 return { | 43 return { |
36 'name': filename.replace('/', '\\'), | 44 'name': filename.replace('/', '\\'), |
37 'size': str(len(data)), | 45 'size': len(data), |
38 'lfh_size': str(LFH_FIXED_SIZE + len(filename)), | 46 'lfh_size': _lfh_size(filename), |
Wladimir Palant
2016/06/17 09:53:46
Assumption here: filename is ASCII. Maybe enforce
Vasily Kuznetsov
2016/06/17 17:53:26
If it's not ASCII, it gets encoded as utf-8. I imp
| |
39 'blocks': [{'hash': _SHA256(block), 'compressed_size': str(len(block))} | 47 'blocks': [ |
40 for block in blocks] | 48 {'hash': base64.b64encode(hashlib.sha256(block).digest())} |
Wladimir Palant
2016/06/17 09:53:46
No point stringifying all the numbers, the represe
Vasily Kuznetsov
2016/06/17 17:53:27
Done.
| |
49 for block in blocks | |
50 ] | |
41 } | 51 } |
42 | 52 |
43 | 53 |
44 def createAppxBlockmap(files): | 54 def create_appx_blockmap(files): |
45 """Create APPX blockmap for the list of files.""" | 55 """Create APPX blockmap for the list of files.""" |
56 # We don't support AppxBlockmap.xml generation for compressed zip files at | |
57 # the moment. The only way to reliably calculate the compressed size of | |
58 # each 64k chunk in the zip file is to override the relevant parts of | |
59 # `zipfile` library. We have chosen to not do it so we produce an | |
60 # uncompressed zip file that is later repackaged by Windows Store with | |
61 # compression. | |
46 template = _get_template_for(BLOCKMAP) | 62 template = _get_template_for(BLOCKMAP) |
47 files = [_make_blockmap_entry(n, d) for n, d in files.items()] | 63 files = [_make_blockmap_entry(n, d) for n, d in files.items()] |
48 return template.render(files=files).encode('utf-8') | 64 return template.render(files=files).encode('utf-8') |
49 | 65 |
50 | 66 |
51 def createAppxManifest(params): | 67 def load_translation(files, locale): |
68 """Load translation strings for locale from files.""" | |
69 path = '{}/_locales/{}/messages.json'.format(EXTENSION_DIR, locale) | |
70 return json.loads(files[path]) | |
71 | |
72 | |
73 def pad_version(version): | |
74 """Make sure version number has 4 groups of digits.""" | |
75 groups = (version.split('.') + ['0', '0', '0'])[:4] | |
76 return '.'.join(groups) | |
77 | |
78 | |
79 def create_appx_manifest(params, files, release_build=False): | |
52 """Create AppxManifest.xml.""" | 80 """Create AppxManifest.xml.""" |
53 template = _get_template_for(MANIFEST) | |
54 params = dict(params) | 81 params = dict(params) |
55 metadata = params['metadata'] | 82 metadata = params['metadata'] |
56 params['package_identity'] = dict(metadata.items('package_identity')) | 83 w = params['windows_version'] = {} |
84 w['min'], w['max'] = metadata.get('compat', 'windows').split('/') | |
57 params.update(metadata.items('general')) | 85 params.update(metadata.items('general')) |
86 params['version'] = pad_version(params['version']) | |
87 | |
88 translation = load_translation(files, defaultLocale) | |
89 name_key = 'name' if release_build else 'name_devbuild' | |
90 params['display_name'] = translation[name_key]['message'] | |
91 params['description'] = translation['description']['message'] | |
92 | |
58 for size in ['44', '50', '150']: | 93 for size in ['44', '50', '150']: |
59 params['logo_{}'.format(size)] = 'Assets\\logo_{}.png'.format(size) | 94 path = '{}/logo_{}.png'.format(ASSETS_DIR, size) |
Wladimir Palant
2016/06/17 09:53:46
We need to verify that these files actually exist.
Vasily Kuznetsov
2016/06/17 17:53:27
I started checking that they exist.
| |
95 if path not in files: | |
96 raise KeyError(path + 'is not found in files') | |
97 params['logo_' + size] = path.replace('/', '\\') | |
98 | |
99 template = _get_template_for(MANIFEST) | |
60 return template.render(params).encode('utf-8') | 100 return template.render(params).encode('utf-8') |
61 | 101 |
62 | 102 |
63 def convertToAppx(files): | 103 def move_files_to_extension(files): |
64 """Move all files into `Extension` folder for APPX packaging.""" | 104 """Move all files into `Extension` folder for APPX packaging.""" |
105 # We sort the files to ensure that 'Extension/xyz' is moved before 'xyz'. | |
106 # If 'xyz' is moved first, it would overwrite 'Extension/xyz' and its | |
107 # original content would be lost. | |
65 names = sorted(files.keys(), key=len, reverse=True) | 108 names = sorted(files.keys(), key=len, reverse=True) |
Wladimir Palant
2016/06/17 09:53:45
Why sort here? If the point is creating a copy of
Vasily Kuznetsov
2016/06/17 17:53:26
Sorting is to make sure that moving 'foo' to 'Exte
Wladimir Palant
2016/06/29 19:33:44
This makes sense but it's also non-obvious. You be
Vasily Kuznetsov
2016/07/01 19:51:27
Done
| |
66 for filename in names: | 109 for filename in names: |
67 files['Extension/' + filename] = files[filename] | 110 files['{}/{}'.format(EXTENSION_DIR, filename)] = files.pop(filename) |
68 del files[filename] | |
69 content_types_template = _get_template_for(CONTENT_TYPES) | |
70 files[CONTENT_TYPES] = content_types_template.render().encode('utf-8') | |
Wladimir Palant
2016/06/17 09:53:46
This function does two things - prefix file names
Vasily Kuznetsov
2016/06/17 17:53:27
Yeah, makes sense. I broke it up.
| |
71 | 111 |
72 | 112 |
73 class Files(packager.Files): | 113 def create_content_types_map(filenames): |
74 """Files subclass that zips without compression.""" | 114 """Create [Content_Types].xml -- a mime type map.""" |
75 | 115 params = {'defaults': {}, 'overrides': {}} |
76 # We don't support AppxBlockmap.xml generation for compressed zip files at | 116 overrides = { |
77 # the moment. The only way to reliably calculate the compressed size of | 117 BLOCKMAP: 'application/vnd.ms-appx.blockmap+xml', |
78 # each 64k chunk in the zip file is to override the relevant parts of | 118 MANIFEST: 'application/vnd.ms-appx.manifest+xml' |
79 # `zipfile` library. We have chosen to not do it for now, so zip() below | 119 } |
80 # doesn't perform any compression. | 120 for filename in filenames: |
81 | 121 ext = os.path.splitext(filename)[1] |
82 def zip(self, outFile, sortKey=None): | 122 if ext: |
Vasily Kuznetsov
2016/06/13 12:57:31
This can eventually be replaced with a compressing
Wladimir Palant
2016/06/17 09:53:46
Maybe add a TODO comment on that, so it's obvious?
Vasily Kuznetsov
2016/06/17 17:53:27
Done.
| |
83 """Pack files into zip archive producing matching appx block map.""" | 123 content_type = mimetypes.guess_type(filename, strict=False)[0] |
84 zf = zipfile.ZipFile(outFile, 'w', zipfile.ZIP_STORED) | 124 if content_type is not None: |
85 for name in sorted(self, key=sortKey): | 125 params['defaults'][ext[1:]] = content_type |
86 zf.writestr(name, self[name]) | 126 if filename in overrides: |
87 zf.writestr(BLOCKMAP, createAppxBlockmap(self)) | 127 params['overrides']['/' + filename] = overrides[filename] |
88 zf.close() | 128 content_types_template = _get_template_for(CONTENT_TYPES) |
129 return content_types_template.render(params).encode('utf-8') | |
89 | 130 |
90 | 131 |
91 def createBuild(baseDir, type='edge', outFile=None, buildNum=None, | 132 def createBuild(baseDir, type='edge', outFile=None, # noqa: preserve API. |
Vasily Kuznetsov
2016/06/13 12:57:31
This function has been copied from `packagerChrome
| |
92 releaseBuild=False, keyFile=None, devenv=False): | 133 buildNum=None, releaseBuild=False, keyFile=None, |
134 devenv=False): | |
93 | 135 |
94 metadata = packager.readMetadata(baseDir, type) | 136 metadata = packager.readMetadata(baseDir, type) |
95 version = packager.getBuildVersion(baseDir, metadata, releaseBuild, | 137 version = packager.getBuildVersion(baseDir, metadata, releaseBuild, |
96 buildNum) | 138 buildNum) |
97 | 139 |
98 if outFile is None: | 140 outfile = outFile or packager.getDefaultFileName(metadata, version, 'appx') |
99 outFile = packager.getDefaultFileName(metadata, version, 'appx') | |
100 | 141 |
101 params = { | 142 params = { |
102 'type': type, | 143 'type': type, |
103 'baseDir': baseDir, | 144 'baseDir': baseDir, |
104 'releaseBuild': releaseBuild, | 145 'releaseBuild': releaseBuild, |
105 'version': version, | 146 'version': version, |
106 'devenv': devenv, | 147 'devenv': devenv, |
107 'metadata': metadata, | 148 'metadata': metadata, |
108 } | 149 } |
109 | 150 |
110 files = Files(packagerChrome.getPackageFiles(params), | 151 files = packager.Files(packagerChrome.getPackageFiles(params), |
111 packagerChrome.getIgnoredFiles(params)) | 152 packagerChrome.getIgnoredFiles(params)) |
112 | 153 |
113 if metadata.has_section('mapping'): | 154 if metadata.has_section('mapping'): |
114 mapped = metadata.items('mapping') | 155 mapped = metadata.items('mapping') |
115 files.readMappedFiles(mapped) | 156 files.readMappedFiles(mapped) |
116 files.read(baseDir, skip=[filename for filename, _ in mapped]) | 157 files.read(baseDir, skip=[filename for filename, _ in mapped]) |
117 else: | 158 else: |
118 files.read(baseDir) | 159 files.read(baseDir) |
119 | 160 |
120 if metadata.has_section('convert_js'): | 161 if metadata.has_section('convert_js'): |
121 packagerChrome.convertJS(params, files) | 162 packagerChrome.convertJS(params, files) |
122 | 163 |
123 if metadata.has_section('preprocess'): | 164 if metadata.has_section('preprocess'): |
124 files.preprocess(metadata.options('preprocess'), {'needsExt': True}) | 165 files.preprocess(metadata.options('preprocess'), {'needsExt': True}) |
125 | 166 |
126 if metadata.has_section('import_locales'): | 167 if metadata.has_section('import_locales'): |
127 packagerChrome.importGeckoLocales(params, files) | 168 packagerChrome.importGeckoLocales(params, files) |
128 | 169 |
129 files['manifest.json'] = packagerChrome.createManifest(params, files) | 170 files['manifest.json'] = packagerChrome.createManifest(params, files) |
130 | 171 |
131 convertToAppx(files) | 172 move_files_to_extension(files) |
132 | 173 |
133 if metadata.has_section('appx_assets'): | 174 if metadata.has_section('appx_assets'): |
134 for name, path in metadata.items('appx_assets'): | 175 for name, path in metadata.items('appx_assets'): |
135 path = os.path.join(baseDir, path) | 176 path = os.path.join(baseDir, path) |
136 files.read(path, 'Assets/{}'.format(name)) | 177 files.read(path, '{}/{}'.format(ASSETS_DIR, name)) |
137 | 178 |
138 files[MANIFEST] = createAppxManifest(params) | 179 files[MANIFEST] = create_appx_manifest(params, files, releaseBuild) |
139 files.zip(outFile) | 180 files[BLOCKMAP] = create_appx_blockmap(files) |
181 files[CONTENT_TYPES] = create_content_types_map(files.keys() + [BLOCKMAP]) | |
182 | |
183 files.zip(outfile, compression=zipfile.ZIP_STORED) | |
LEFT | RIGHT |