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

Side by Side Diff: packagerChrome.py

Issue 29549786: Issue 5535 - Replace our module system with webpack (Closed)
Patch Set: Addressed Sebastian's feedback Created Sept. 23, 2017, 8:24 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 | « package-lock.json ('k') | packagerEdge.py » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
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 errno 5 import errno
6 import io 6 import io
7 import json 7 import json
8 import os 8 import os
9 import re 9 import re
10 import shutil
10 from StringIO import StringIO 11 from StringIO import StringIO
11 import struct 12 import struct
13 import subprocess
12 import sys 14 import sys
13 import collections 15 import tempfile
14 16
17 from ensure_dependencies import read_deps
15 from packager import (readMetadata, getDefaultFileName, getBuildVersion, 18 from packager import (readMetadata, getDefaultFileName, getBuildVersion,
16 getTemplate, Files) 19 getTemplate, Files)
17 20
18 defaultLocale = 'en_US' 21 defaultLocale = 'en_US'
19 22
20 23
21 def getIgnoredFiles(params): 24 def getIgnoredFiles(params):
22 return {'store.description'} 25 return {'store.description'}
23 26
24 27
(...skipping 107 matching lines...) Expand 10 before | Expand all | Expand 10 after
132 # Normalize JSON structure 135 # Normalize JSON structure
133 licenseComment = re.compile(r'/\*.*?\*/', re.S) 136 licenseComment = re.compile(r'/\*.*?\*/', re.S)
134 data = json.loads(re.sub(licenseComment, '', manifest, 1)) 137 data = json.loads(re.sub(licenseComment, '', manifest, 1))
135 if '_dummy' in data: 138 if '_dummy' in data:
136 del data['_dummy'] 139 del data['_dummy']
137 manifest = json.dumps(data, sort_keys=True, indent=2) 140 manifest = json.dumps(data, sort_keys=True, indent=2)
138 141
139 return manifest.encode('utf-8') 142 return manifest.encode('utf-8')
140 143
141 144
142 def convertJS(params, files): 145 def create_bundles(params, files):
143 output_files = collections.OrderedDict() 146 base_extension_path = params['baseDir']
144 args = {} 147 info_templates = {
148 'chrome': 'chromeInfo.js.tmpl',
149 'edge': 'edgeInfo.js.tmpl',
150 'gecko-webext': 'geckoInfo.js.tmpl'
151 }
152 info_module = None
145 153
146 for item in params['metadata'].items('convert_js'): 154 # Historically we didn't use relative paths when requiring modules, so in
147 name, value = item 155 # order for webpack to know where to find them we need to pass in a list
148 filename, arg = re.search(r'^(.*?)(?:\[(.*)\])?$', name).groups() 156 # of resolve paths - "./lib" and the "lib" directory of all immediate
149 if arg is None: 157 # dependencies (except adblockplus).
150 output_files[filename] = (value.split(), item.source) 158 # Going forward we should always use relative paths when requiring modules
151 else: 159 # and once we do that everywhere we can remove this logic.
152 args.setdefault(filename, {})[arg] = value 160 resolve_paths = [os.path.join(base_extension_path, 'lib')]
161 deps = read_deps(base_extension_path)
162 if deps:
163 for dep in deps:
164 if not dep.startswith('_') and dep != 'adblockplus':
165 dep_lib_path = os.path.join(base_extension_path, dep, 'lib')
166 if os.path.exists(dep_lib_path):
167 resolve_paths.append(dep_lib_path)
168 resolve_paths = ' '.join(resolve_paths)
153 169
154 template = getTemplate('modules.js.tmpl') 170 temp_dir = tempfile.mkdtemp()
171 try:
172 info_module = os.path.join(temp_dir, 'info.js')
173 template = getTemplate(info_templates[params['type']])
174 with open(info_module, 'w') as info_file:
175 info_file.write(
176 template.render(
177 basename=params['metadata'].get('general', 'basename'),
178 version=params['metadata'].get('general', 'version')
179 ).encode('utf-8')
180 )
155 181
156 for filename, (input_files, origin) in output_files.iteritems(): 182 for item in params['metadata'].items('bundles'):
157 if '/' in filename and not files.isIncluded(filename): 183 name, value = item
158 continue 184 base_item_path = os.path.dirname(item.source)
159 185
160 current_args = args.get(filename, {}) 186 bundle_file = os.path.relpath(os.path.join(base_item_path, name),
161 current_args['autoload'] = [module for module in 187 base_extension_path)
162 current_args.get('autoload', '').split(',') 188 entry_files = [
163 if module != ''] 189 os.path.join(
164 190 '.',
165 base_dir = os.path.dirname(origin) 191 os.path.relpath(os.path.join(base_item_path, module_path),
166 modules = [] 192 base_extension_path)
167 193 )
168 for input_filename in input_files: 194 for module_path in value.split()
169 module_name = os.path.splitext(os.path.basename(input_filename))[0] 195 ]
170 prefix = os.path.basename(os.path.dirname(input_filename)) 196 subprocess.check_call(
171 if prefix != 'lib': 197 ['npm', 'run-script', 'webpack', '--silent'],
172 module_name = '{}_{}'.format(prefix, module_name) 198 cwd=os.path.dirname(__file__),
173 with open(os.path.join(base_dir, input_filename), 'r') as file: 199 env={
174 modules.append((module_name, file.read().decode('utf-8'))) 200 'EXTENSION_PATH': base_extension_path,
175 files.pop(input_filename, None) 201 'ENTRY_POINTS': ' '.join(entry_files),
176 202 'OUTPUT_PATH': temp_dir,
177 files[filename] = template.render( 203 'BUNDLE_NAME': bundle_file,
178 args=current_args, 204 'RESOLVE_PATHS': resolve_paths,
179 basename=params['metadata'].get('general', 'basename'), 205 'INFO_PATH': info_module,
180 modules=modules, 206 'PATH': os.environ['PATH']
181 type=params['type'], 207 }
182 version=params['metadata'].get('general', 'version') 208 )
183 ).encode('utf-8') 209 for file_name in [bundle_file, bundle_file + '.map']:
210 with open(os.path.join(temp_dir, file_name), 'r') as f:
211 files[file_name] = f.read()
212 finally:
213 shutil.rmtree(temp_dir)
184 214
185 215
186 def toJson(data): 216 def toJson(data):
187 return json.dumps( 217 return json.dumps(
188 data, ensure_ascii=False, sort_keys=True, 218 data, ensure_ascii=False, sort_keys=True,
189 indent=2, separators=(',', ': ') 219 indent=2, separators=(',', ': ')
190 ).encode('utf-8') + '\n' 220 ).encode('utf-8') + '\n'
191 221
192 222
193 def import_string_webext(data, key, source): 223 def import_string_webext(data, key, source):
(...skipping 188 matching lines...) Expand 10 before | Expand all | Expand 10 after
382 'metadata': metadata, 412 'metadata': metadata,
383 } 413 }
384 414
385 mapped = metadata.items('mapping') if metadata.has_section('mapping') else [ ] 415 mapped = metadata.items('mapping') if metadata.has_section('mapping') else [ ]
386 files = Files(getPackageFiles(params), getIgnoredFiles(params), 416 files = Files(getPackageFiles(params), getIgnoredFiles(params),
387 process=lambda path, data: processFile(path, data, params)) 417 process=lambda path, data: processFile(path, data, params))
388 418
389 files.readMappedFiles(mapped) 419 files.readMappedFiles(mapped)
390 files.read(baseDir, skip=[opt for opt, _ in mapped]) 420 files.read(baseDir, skip=[opt for opt, _ in mapped])
391 421
392 if metadata.has_section('convert_js'): 422 if metadata.has_section('bundles'):
393 convertJS(params, files) 423 create_bundles(params, files)
394 424
395 if metadata.has_section('preprocess'): 425 if metadata.has_section('preprocess'):
396 files.preprocess( 426 files.preprocess(
397 [f for f, _ in metadata.items('preprocess')], 427 [f for f, _ in metadata.items('preprocess')],
398 {'needsExt': True} 428 {'needsExt': True}
399 ) 429 )
400 430
401 if metadata.has_section('import_locales'): 431 if metadata.has_section('import_locales'):
402 import_locales(params, files) 432 import_locales(params, files)
403 433
(...skipping 12 matching lines...) Expand all
416 params, 'testIndex.html.tmpl', ('general', 'testScripts') 446 params, 'testIndex.html.tmpl', ('general', 'testScripts')
417 ) 447 )
418 448
419 zipdata = files.zipToString() 449 zipdata = files.zipToString()
420 signature = None 450 signature = None
421 pubkey = None 451 pubkey = None
422 if keyFile != None: 452 if keyFile != None:
423 signature = signBinary(zipdata, keyFile) 453 signature = signBinary(zipdata, keyFile)
424 pubkey = getPublicKey(keyFile) 454 pubkey = getPublicKey(keyFile)
425 writePackage(outFile, pubkey, signature, zipdata) 455 writePackage(outFile, pubkey, signature, zipdata)
OLDNEW
« no previous file with comments | « package-lock.json ('k') | packagerEdge.py » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld