Rietveld Code Review Tool
Help | Bug tracker | Discussion group | Source code

Side by Side Diff: packagerEdge.py

Issue 29345751: Issue 4028 - Add support for Edge extensions to buildtools (Closed)
Patch Set: Address comments on patch set 8 Created Oct. 11, 2016, 3:52 p.m.
Left:
Right:
Use n/p to move between diff chunks; N/P to move between comments.
Jump to:
View unified diff | Download patch
« no previous file with comments | « packagerChrome.py ('k') | templates/Info.plist.tmpl » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(Empty)
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
3 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
4
5 import base64
6 import hashlib
7 import json
8 import mimetypes
9 import os
10 import sys
11 import zipfile
12
13 import packager
14 import packagerChrome
15
16 # Files and directories expected inside of the .APPX archive.
17 MANIFEST = 'AppxManifest.xml'
18 CONTENT_TYPES = '[Content_Types].xml'
19 BLOCKMAP = 'AppxBlockMap.xml'
20 EXTENSION_DIR = 'Extension'
21 ASSETS_DIR = 'Assets'
22
23 # Size of uncompressed block in the APPX block map.
24 BLOCKSIZE = 64 * 1024
25
26 defaultLocale = packagerChrome.defaultLocale
27
28
29 def _get_template_for(filename):
30 return packager.getTemplate('edge/{}.tmpl'.format(filename))
31
32
33 def _lfh_size(filename):
34 """Compute the size of zip local file header for `filename`."""
35 try:
36 filename = filename.encode('utf-8')
37 except UnicodeDecodeError:
38 pass # filename is already a byte string.
39 return zipfile.sizeFileHeader + len(filename)
40
41
42 def _make_blockmap_entry(filename, data):
43 blocks = [data[i:i + BLOCKSIZE] for i in range(0, len(data), BLOCKSIZE)]
44 return {
45 'name': filename.replace('/', '\\'),
46 'size': len(data),
47 'lfh_size': _lfh_size(filename),
48 'blocks': [
49 {'hash': base64.b64encode(hashlib.sha256(block).digest())}
50 for block in blocks
51 ]
52 }
53
54
55 def create_appx_blockmap(files):
56 """Create APPX blockmap for the list of files."""
57 template = _get_template_for(BLOCKMAP)
58 files = [_make_blockmap_entry(n, d) for n, d in files.items()]
59 return template.render(files=files).encode('utf-8')
60
61
62 def load_translation(files, locale):
63 """Load translation strings for locale from files."""
64 path = '{}/_locales/{}/messages.json'.format(EXTENSION_DIR, locale)
65 return json.loads(files[path])
66
67
68 def create_appx_manifest(params, files):
69 """Create AppxManifest.xml."""
70 params = dict(params)
71 metadata = params['metadata']
72 w = params['windows_version'] = {}
73 w['min'], w['max'] = metadata.get('compat', 'windows').split('/')
74 params.update(metadata.items('general'))
75
76 translation = load_translation(files, defaultLocale)
77 params['display_name'] = translation['name']
78 params['description'] = translation['description']
79
80 for size in ['44', '50', '150']:
81 path = '{}/logo_{}.png'.format(ASSETS_DIR, size)
82 if path not in files:
83 raise KeyError(path + 'is not found in files')
84 params['logo_' + size] = path.replace('/', '\\')
85
86 expected_id = '{}.{}'.format(params['author'],
87 params['display_name']).replace(' ', '')
88 if params['app_id'] != expected_id:
89 sys.stderr.write(
90 "WARNING: app_id doesn't match author and display_name: "
91 "'{app_id}' and '{author}' + '{display_name}'\n".format(**params)
92 )
93
94 template = _get_template_for(MANIFEST)
95 return template.render(params).encode('utf-8')
96
97
98 def move_files_to_extension(files):
99 """Move all files into `Extension` folder for APPX packaging."""
100 # We sort the files to ensure that 'Extension/xyz' is moved before 'xyz'.
101 # If 'xyz' is moved first, it would overwrite 'Extension/xyz' and its
102 # original content would be lost.
103 names = sorted(files.keys(), key=len, reverse=True)
104 for filename in names:
105 files['{}/{}'.format(EXTENSION_DIR, filename)] = files.pop(filename)
106
107
108 def create_content_types_map(filenames):
109 """Create [Content_Types].xml -- a mime type map."""
110 params = {'defaults': {}, 'overrides': {}}
111 overrides = {
112 BLOCKMAP: 'application/vnd.ms-appx.blockmap+xml',
113 MANIFEST: 'application/vnd.ms-appx.manifest+xml'
114 }
115 for filename in filenames:
116 ext = os.path.splitext(filename)[1]
117 if ext:
118 content_type = mimetypes.guess_type(filename, strict=False)[0]
119 if content_type is not None:
120 params['defaults'][ext[1:]] = content_type
121 if filename in overrides:
122 params['overrides']['/' + filename] = overrides[filename]
123 content_types_template = _get_template_for(CONTENT_TYPES)
124 return content_types_template.render(params).encode('utf-8')
125
126
127 def createBuild(baseDir, type='edge', outFile=None, # noqa: preserve API.
128 buildNum=None, releaseBuild=False, keyFile=None,
129 devenv=False):
130
131 metadata = packager.readMetadata(baseDir, type)
132 version = packager.getBuildVersion(baseDir, metadata, releaseBuild,
133 buildNum)
134
135 outfile = outFile or packager.getDefaultFileName(metadata, version, 'appx')
136
137 params = {
138 'type': type,
139 'baseDir': baseDir,
140 'releaseBuild': releaseBuild,
141 'version': version,
Sebastian Noack 2016/10/12 14:43:27 As figured out during testing, and discussed on IR
Vasily Kuznetsov 2016/10/13 11:56:36 I've done it inside of appx manifest generation in
142 'devenv': devenv,
143 'metadata': metadata,
144 }
145
146 files = packager.Files(packagerChrome.getPackageFiles(params),
147 packagerChrome.getIgnoredFiles(params))
148
149 if metadata.has_section('mapping'):
150 mapped = metadata.items('mapping')
151 files.readMappedFiles(mapped)
152 files.read(baseDir, skip=[filename for filename, _ in mapped])
153 else:
154 files.read(baseDir)
155
156 if metadata.has_section('convert_js'):
157 packagerChrome.convertJS(params, files)
158
159 if metadata.has_section('preprocess'):
160 files.preprocess(metadata.options('preprocess'), {'needsExt': True})
161
162 if metadata.has_section('import_locales'):
163 packagerChrome.importGeckoLocales(params, files)
164
165 files['manifest.json'] = packagerChrome.createManifest(params, files)
166
167 move_files_to_extension(files)
168
169 if metadata.has_section('appx_assets'):
170 for name, path in metadata.items('appx_assets'):
171 path = os.path.join(baseDir, path)
172 files.read(path, '{}/{}'.format(ASSETS_DIR, name))
173
174 files[MANIFEST] = create_appx_manifest(params, files)
175 files[CONTENT_TYPES] = create_content_types_map(files.keys() + [BLOCKMAP])
176
177 # We don't support AppxBlockmap.xml generation for compressed zip files at
178 # the moment. The only way to reliably calculate the compressed size of
179 # each 64k chunk in the zip file is to override the relevant parts of
180 # `zipfile` library. We have chosen to not do it so we produce an
181 # uncompressed zip file that is later repackaged by Windows Store with
182 # compression.
183 files[BLOCKMAP] = create_appx_blockmap(files)
184 files.zip(outfile, compression=zipfile.ZIP_STORED)
OLDNEW
« no previous file with comments | « packagerChrome.py ('k') | templates/Info.plist.tmpl » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld