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

Side by Side Diff: packagerChrome.py

Issue 29517660: Issue 5477 - Import everything from imported locales (Closed)
Patch Set: Created Aug. 16, 2017, 6:28 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 | « no previous file | 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 from StringIO import StringIO 10 from StringIO import StringIO
(...skipping 172 matching lines...) Expand 10 before | Expand all | Expand 10 after
183 ).encode('utf-8') 183 ).encode('utf-8')
184 184
185 185
186 def toJson(data): 186 def toJson(data):
187 return json.dumps( 187 return json.dumps(
188 data, ensure_ascii=False, sort_keys=True, 188 data, ensure_ascii=False, sort_keys=True,
189 indent=2, separators=(',', ': ') 189 indent=2, separators=(',', ': ')
190 ).encode('utf-8') + '\n' 190 ).encode('utf-8') + '\n'
191 191
192 192
193 def importGeckoLocales(params, files): 193 def set_full_dict(data, key, value, source, stringID):
194 """Sets data[key] to the desired {'message':value}, adds all additional
195 info from the source dict"""
196 data[key] = {'messages': value}
197 for k, v in source[stringID].items():
198 data[key].setdefault(k, v)
199
200
201 def set_message_only(data, key, value, *args):
202 """only set {'message': value} in data-dictionary, API-consitent with
203 set_full_dict()"""
204 data[key] = {'message': value}
205
206
207 def import_locales(params, files):
194 import localeTools 208 import localeTools
195 209
196 # FIXME: localeTools doesn't use real Chrome locales, it uses dash as 210 # FIXME: localeTools doesn't use real Chrome locales, it uses dash as
197 # separator instead. 211 # separator instead.
198 convert_locale_code = lambda code: code.replace('-', '_') 212 convert_locale_code = lambda code: code.replace('-', '_')
199 213
200 # We need to map Chrome locales to Gecko locales. Start by mapping Chrome 214 # We need to map Chrome locales to Gecko locales. Start by mapping Chrome
201 # locales to themselves, merely with the dash as separator. 215 # locales to themselves, merely with the dash as separator.
202 locale_mapping = {convert_locale_code(l): l for l in localeTools.chromeLocal es} 216 locale_mapping = {convert_locale_code(l): l for l in localeTools.chromeLocal es}
203 217
(...skipping 16 matching lines...) Expand all
220 fileName, keys = item 234 fileName, keys = item
221 parts = map(lambda n: source if n == '*' else n, fileName.split('/') ) 235 parts = map(lambda n: source if n == '*' else n, fileName.split('/') )
222 sourceFile = os.path.join(os.path.dirname(item.source), *parts) 236 sourceFile = os.path.join(os.path.dirname(item.source), *parts)
223 incompleteMarker = os.path.join(os.path.dirname(sourceFile), '.incom plete') 237 incompleteMarker = os.path.join(os.path.dirname(sourceFile), '.incom plete')
224 if not os.path.exists(sourceFile) or os.path.exists(incompleteMarker ): 238 if not os.path.exists(sourceFile) or os.path.exists(incompleteMarker ):
225 continue 239 continue
226 240
227 data = json.loads(files[targetFile].decode('utf-8')) 241 data = json.loads(files[targetFile].decode('utf-8'))
228 242
229 try: 243 try:
244 # .json and other formats provide translations differently and
245 # / or provide additional information like e.g. "placeholders".
246 # We want to adhere to that / preserve the addtional info
230 if sourceFile.endswith('.json'): 247 if sourceFile.endswith('.json'):
231 with io.open(sourceFile, 'r', encoding='utf-8') as handle: 248 with io.open(sourceFile, 'r', encoding='utf-8') as handle:
232 sourceData = {k: v['message'] for k, v in json.load(hand le).iteritems()} 249 sourceData = json.load(handle)
250
251 get_value = lambda x: x[stringID]['message']
Sebastian Noack 2017/08/17 16:32:34 PEP-8 discourages assignment of lambda functions t
tlucas 2017/08/18 07:34:15 Done.
252 set_translation = set_full_dict
233 else: 253 else:
234 sourceData = localeTools.readFile(sourceFile) 254 sourceData = localeTools.readFile(sourceFile)
255 get_value = lambda x: x[stringID]
256 set_translation = set_message_only
235 257
236 # Resolve wildcard imports 258 # Resolve wildcard imports
237 if keys == '*' or keys == '=*': 259 if keys == '*' or keys == '=*':
238 importList = sourceData.keys() 260 importList = sourceData.keys()
239 importList = filter(lambda k: not k.startswith('_'), importL ist) 261 importList = filter(lambda k: not k.startswith('_'), importL ist)
240 if keys == '=*': 262 if keys == '=*':
241 importList = map(lambda k: '=' + k, importList) 263 importList = map(lambda k: '=' + k, importList)
242 keys = ' '.join(importList) 264 keys = ' '.join(importList)
243 265
244 for stringID in keys.split(): 266 for stringID in keys.split():
245 noMangling = False 267 noMangling = False
246 if stringID.startswith('='): 268 if stringID.startswith('='):
247 stringID = stringID[1:] 269 stringID = stringID[1:]
248 noMangling = True 270 noMangling = True
249 271
250 if stringID in sourceData: 272 if stringID in sourceData:
251 if noMangling: 273 if noMangling:
252 key = re.sub(r'\W', '_', stringID) 274 key = re.sub(r'\W', '_', stringID)
253 else: 275 else:
254 key = re.sub(r'\..*', '', parts[-1]) + '_' + re.sub( r'\W', '_', stringID) 276 key = re.sub(r'\..*', '', parts[-1]) + '_' + re.sub( r'\W', '_', stringID)
255 if key in data: 277 if key in data:
256 print 'Warning: locale string %s defined multiple ti mes' % key 278 print 'Warning: locale string %s defined multiple ti mes' % key
257 279
258 # Remove access keys 280 # Remove access keys
259 value = sourceData[stringID] 281 value = get_value(sourceData)
260 match = re.search(r'^(.*?)\s*\(&.\)$', value) 282 match = re.search(r'^(.*?)\s*\(&.\)$', value)
261 if match: 283 if match:
262 value = match.group(1) 284 value = match.group(1)
263 else: 285 else:
264 index = value.find('&') 286 index = value.find('&')
265 if index >= 0: 287 if index >= 0:
266 value = value[0:index] + value[index + 1:] 288 value = value[0:index] + value[index + 1:]
267 data[key] = {'message': value} 289
290 set_translation(data, key, value, sourceData, stringID)
268 except Exception as e: 291 except Exception as e:
269 print 'Warning: error importing locale data from %s: %s' % (sour ceFile, e) 292 print 'Warning: error importing locale data from %s: %s' % (sour ceFile, e)
270 293
271 files[targetFile] = toJson(data) 294 files[targetFile] = toJson(data)
272 295
273 296
274 def truncate(text, length_limit): 297 def truncate(text, length_limit):
275 if len(text) <= length_limit: 298 if len(text) <= length_limit:
276 return text 299 return text
277 return text[:length_limit - 1].rstrip() + u'\u2026' 300 return text[:length_limit - 1].rstrip() + u'\u2026'
(...skipping 95 matching lines...) Expand 10 before | Expand all | Expand 10 after
373 if metadata.has_section('convert_js'): 396 if metadata.has_section('convert_js'):
374 convertJS(params, files) 397 convertJS(params, files)
375 398
376 if metadata.has_section('preprocess'): 399 if metadata.has_section('preprocess'):
377 files.preprocess( 400 files.preprocess(
378 [f for f, _ in metadata.items('preprocess')], 401 [f for f, _ in metadata.items('preprocess')],
379 {'needsExt': True} 402 {'needsExt': True}
380 ) 403 )
381 404
382 if metadata.has_section('import_locales'): 405 if metadata.has_section('import_locales'):
383 importGeckoLocales(params, files) 406 import_locales(params, files)
384 407
385 files['manifest.json'] = createManifest(params, files) 408 files['manifest.json'] = createManifest(params, files)
386 if type == 'chrome': 409 if type == 'chrome':
387 fixTranslationsForCWS(files) 410 fixTranslationsForCWS(files)
388 411
389 if devenv: 412 if devenv:
390 import buildtools 413 import buildtools
391 import random 414 import random
392 files.read(os.path.join(buildtools.__path__[0], 'chromeDevenvPoller__.js '), relpath='devenvPoller__.js') 415 files.read(os.path.join(buildtools.__path__[0], 'chromeDevenvPoller__.js '), relpath='devenvPoller__.js')
393 files['devenvVersion__'] = str(random.random()) 416 files['devenvVersion__'] = str(random.random())
394 417
395 if metadata.has_option('general', 'testScripts'): 418 if metadata.has_option('general', 'testScripts'):
396 files['qunit/index.html'] = createScriptPage( 419 files['qunit/index.html'] = createScriptPage(
397 params, 'testIndex.html.tmpl', ('general', 'testScripts') 420 params, 'testIndex.html.tmpl', ('general', 'testScripts')
398 ) 421 )
399 422
400 zipdata = files.zipToString() 423 zipdata = files.zipToString()
401 signature = None 424 signature = None
402 pubkey = None 425 pubkey = None
403 if keyFile != None: 426 if keyFile != None:
404 signature = signBinary(zipdata, keyFile) 427 signature = signBinary(zipdata, keyFile)
405 pubkey = getPublicKey(keyFile) 428 pubkey = getPublicKey(keyFile)
406 writePackage(outFile, pubkey, signature, zipdata) 429 writePackage(outFile, pubkey, signature, zipdata)
OLDNEW
« no previous file with comments | « no previous file | packagerEdge.py » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld