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 review comments on patch set 2 Created July 1, 2016, 7:47 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
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 os
8 import zipfile
9
10 import packager
11 import packagerChrome
12
13 MANIFEST = 'AppxManifest.xml'
14 CONTENT_TYPES = '[Content_Types].xml'
15 BLOCKMAP = 'AppxBlockMap.xml'
16 BLOCKSIZE = 64 * 1024
17
18
19 def _get_template_for(filename):
20 return packager.getTemplate('edge/{}.tmpl'.format(filename))
21
22
23 def _sha256(block):
24 h = hashlib.new('sha256')
Sebastian Noack 2016/07/05 14:30:37 According to the Python documentation the named co
Vasily Kuznetsov 2016/07/07 16:23:49 Changed the constructor. About one-liner: it seems
Sebastian Noack 2016/07/08 13:59:11 You can just pass the data to the constructor:
Vasily Kuznetsov 2016/07/08 16:47:39 Somehow I missed the section in the documentation
25 h.update(block)
26 return base64.b64encode(h.digest())
27
28
29 def _lfh_size(filename):
30 """Compute the size of zip local file header for `filename`."""
31 try:
32 filename = filename.encode('utf-8')
33 except UnicodeDecodeError:
34 pass # filename is already a byte string.
35 return zipfile.sizeFileHeader + len(filename)
36
37
38 def _make_blockmap_entry(filename, data):
39 blocks = [data[i:i + BLOCKSIZE] for i in range(0, len(data), BLOCKSIZE)]
40 return {
41 'name': filename.replace('/', '\\'),
42 'size': len(data),
43 'lfh_size': _lfh_size(filename),
44 'blocks': [{'hash': _sha256(block), 'compressed_size': len(block)}
Sebastian Noack 2016/07/05 14:30:38 From the documentation it seems we can simply omit
Vasily Kuznetsov 2016/07/07 16:23:50 Done.
45 for block in blocks]
46 }
47
48
49 def create_appx_blockmap(files):
50 """Create APPX blockmap for the list of files."""
51 template = _get_template_for(BLOCKMAP)
52 files = [_make_blockmap_entry(n, d) for n, d in files.items()]
53 return template.render(files=files).encode('utf-8')
54
55
56 def create_appx_manifest(params, files):
57 """Create AppxManifest.xml."""
58 template = _get_template_for(MANIFEST)
59 params = dict(params)
60 metadata = params['metadata']
61 params['package_identity'] = dict(metadata.items('package_identity'))
62 params.update(metadata.items('general'))
63 for size in ['44', '50', '150']:
64 path = 'Assets/logo_{}.png'.format(size)
Sebastian Noack 2016/07/05 14:30:38 Where does those files come from? Don't you move e
Vasily Kuznetsov 2016/07/07 16:23:50 These are separately added after everything is mov
65 if path not in files:
66 raise KeyError('{} is not found in files'.format(path))
67 params['logo_{}'.format(size)] = path.replace('/', '\\')
Sebastian Noack 2016/07/05 14:30:38 As per our coding style please use the + operator
Vasily Kuznetsov 2016/07/07 16:23:51 Done.
68 return template.render(params).encode('utf-8')
69
70
71 def move_files_to_extension(files):
72 """Move all files into `Extension` folder for APPX packaging."""
73 # We sort the files to ensure that 'Extension/xyz' is moved before 'xyz'.
74 # If 'xyz' is moved first, it would overwrite 'Extension/xyz' and its
75 # original content would be lost.
76 names = sorted(files.keys(), key=len, reverse=True)
77 for filename in names:
78 files['Extension/' + filename] = files[filename]
Sebastian Noack 2016/07/05 14:30:38 If you use files.pop() this would make the next li
Vasily Kuznetsov 2016/07/07 16:23:49 Wow! I didn't realize you can `.pop()` from a dict
79 del files[filename]
80
81
82 def create_content_types_map():
83 """Create [Content_Types].xml -- a mime type map."""
84 content_types_template = _get_template_for(CONTENT_TYPES)
85 return content_types_template.render().encode('utf-8')
86
87
88 class Files(packager.Files):
89 """Files subclass that zips without compression."""
90
91 # We don't support AppxBlockmap.xml generation for compressed zip files at
92 # the moment. The only way to reliably calculate the compressed size of
93 # each 64k chunk in the zip file is to override the relevant parts of
94 # `zipfile` library. We have chosen to not do it for now, so zip() below
95 # doesn't perform any compression.
96
97 # TODO: Replace zip() below with a compressing version:
98 # https://issues.adblockplus.org/ticket/4149
99
100 def zip(self, outFile, sortKey=None): # noqa: preserve API.
Sebastian Noack 2016/07/05 14:30:38 The code duplication here isn't great. Perhaps jus
Vasily Kuznetsov 2016/07/07 16:23:50 We'll have to redo this again when we implement ou
101 """Pack files into zip archive producing matching appx block map."""
102 zf = zipfile.ZipFile(outFile, 'w', zipfile.ZIP_STORED)
103 for name in sorted(self, key=sortKey):
104 zf.writestr(name, self[name])
105 zf.writestr(BLOCKMAP, create_appx_blockmap(self))
106 zf.close()
107
108
109 def createBuild(baseDir, type='edge', outFile=None, # noqa: preserve API.
110 buildNum=None, releaseBuild=False, keyFile=None,
111 devenv=False):
112
113 metadata = packager.readMetadata(baseDir, type)
114 version = packager.getBuildVersion(baseDir, metadata, releaseBuild,
115 buildNum)
116
117 outfile = outFile or packager.getDefaultFileName(metadata, version, 'appx')
118
119 params = {
120 'type': type,
121 'baseDir': baseDir,
122 'releaseBuild': releaseBuild,
123 'version': version,
124 'devenv': devenv,
125 'metadata': metadata,
126 }
127
128 files = Files(packagerChrome.getPackageFiles(params),
129 packagerChrome.getIgnoredFiles(params))
130
131 if metadata.has_section('mapping'):
132 mapped = metadata.items('mapping')
133 files.readMappedFiles(mapped)
134 files.read(baseDir, skip=[filename for filename, _ in mapped])
135 else:
136 files.read(baseDir)
137
138 if metadata.has_section('convert_js'):
139 packagerChrome.convertJS(params, files)
140
141 if metadata.has_section('preprocess'):
142 files.preprocess(metadata.options('preprocess'), {'needsExt': True})
143
144 if metadata.has_section('import_locales'):
145 packagerChrome.importGeckoLocales(params, files)
146
147 files['manifest.json'] = packagerChrome.createManifest(params, files)
148
149 move_files_to_extension(files)
150
151 if metadata.has_section('appx_assets'):
152 for name, path in metadata.items('appx_assets'):
153 path = os.path.join(baseDir, path)
154 files.read(path, 'Assets/{}'.format(name))
155
156 files[MANIFEST] = create_appx_manifest(params, files)
157 files[CONTENT_TYPES] = create_content_types_map()
158
159 files.zip(outfile)
OLDNEW

Powered by Google App Engine
This is Rietveld