Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(169)

Side by Side Diff: build/android/gyp/locale_pak_assets.py

Issue 2345143002: Move language pak files to assets. (Closed)
Patch Set: Move language pak files back to assets rather than res. Created 4 years, 3 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(Empty)
1 #!/usr/bin/env python
2 #
3 # Copyright 2016 The Chromium Authors. All rights reserved.
4 # Use of this source code is governed by a BSD-style license that can be
5 # found in the LICENSE file.
6 """Creates a srcjar for locale pak file paths.
7
8 Creates a srcjar with a class containing a mapping of supported languages to
9 corresponding locale pak files for each language so that these assets can be
10 enumerated and extracted as necessary.
agrieve 2016/09/21 01:06:42 nit: can you mention the motivation is that AssetM
estevenson 2016/09/21 19:50:55 Done.
11
12 The generated class implements:
13 //base/android/java/src/org/chromium/base/LocalePakFiles.java
14
15 Providing access to pak file paths via:
16 static String[] getPakFilesForLocale(String lang)
17 """
18
19 import argparse
20 import collections
21 import os
22 import string
23 import sys
24 import zipfile
25
26 sys.path.append(os.path.join(os.path.dirname(__file__), os.pardir))
27 from pylib.constants import host_paths
28 from util import build_utils
29
30 _APK_ASSET_PATH = 'assets'
31 _CLASSNAME = 'LocalePakFilesImpl'
32 _PAK_US = 'en-US.pak'
33 _PACKAGE_BASE = 'org.chromium.'
34 _THIS_FILE = os.path.abspath(__file__)
35
36 # This should stay in sync with:
37 # base/android/java/src/org/chromium/base/LocaleUtils.java
38 _CHROME_TO_ANDROID_LOCALE_MAP = {
39 'he': 'iw',
40 'id': 'in',
41 'fil': 'tl',
42 }
43
44 def _ToAsset(filename):
45 """Add asset base folder as parent to |filename|.
46
47 Args:
48 filename: File name to be changed.
49
50 Returns:
51 Path to |filename| with the asset folder as base."""
52 return os.path.join(_APK_ASSET_PATH, filename)
53
54
55 def _CreateLocalePakFilesJava(lang_to_locale_map, package, classname, target):
56 """Generate the java file contents for the locale pak file class.
57
58 Args:
59 lang_to_locale_map: Dict mapping language codes to pak files
60 e.g. {'am': ['assets/am.pak'], ...}.
61 package: Java package string.
62 classname: Java class name.
63 target: Target that ran the script.
64 """
65 file_tmpl = string.Template("""
66 // Copyright 2016 The Chromium Authors. All rights reserved.
67 // Use of this source code is governed by a BSD-style license that can be
68 // found in the LICENSE file.
69
70 // This file is generated by:
71 // ${THIS_FILE}
72 // From target:
73 // ${TARGET}
74
75 package ${PACKAGE};
76
77 import org.chromium.base.LocalePakFiles;
78
79 import java.util.HashMap;
80
81 public class ${CLASSNAME} implements LocalePakFiles {
82 private static final HashMap<String, String[]> paks;
83 static {
84 paks = new HashMap<String, String[]>();
85 ${INIT_CODE}
86 }
87
88 public String[] getPakFilesForLocale(String lang) {
89 return paks.get(lang);
90 }
91 }
92 """)
93
94 add_locale_tmpl = string.Template("""
95 paks.put("${LANG}", new String[${NUM_PAKFILES}]);""")
96
97 add_pakfile_tmpl = string.Template("""
98 paks.get("${LANG}")[${IDX}] = "${PATH}";""")
99
100 init_lines = []
101 for lang, pakfiles in lang_to_locale_map.iteritems():
102 init_lines.append(
103 add_locale_tmpl.substitute(LANG=lang, NUM_PAKFILES=len(pakfiles) + 1))
104 init_lines.extend([
105 add_pakfile_tmpl.substitute(LANG=lang, IDX=idx, PATH=path)
106 for idx, path in enumerate(pakfiles)])
107
108 # Add US pak file since english is the fallback locale.
109 init_lines.append(add_pakfile_tmpl.substitute(
110 LANG=lang, IDX=len(pakfiles), PATH=_ToAsset(_PAK_US)))
111
112 file_tmpl_vals = {
113 'TARGET': target,
114 'PACKAGE': package,
115 'CLASSNAME': classname,
116 'INIT_CODE': ''.join(init_lines),
117 'THIS_FILE': os.path.relpath(_THIS_FILE, host_paths.DIR_SOURCE_ROOT)
118 }
119
120 return file_tmpl.substitute(file_tmpl_vals)
121
122
123 def _ComputeLangToLocaleMappings(sources):
124 """Create mappings from lang -> pak file.
125
126 Args:
127 sources: list of locale paths e.g. ['locales/am.pak', ...]
128
129 Returns:
130 Dict of language codes to pak files e.g. {'am': ['assets/am.pak'], ...}
131 """
132 lang_to_locale_map = collections.defaultdict(list)
133 for src_path in sources:
134 basename = os.path.basename(src_path)
135 name = os.path.splitext(basename)[0]
136 lang = _CHROME_TO_ANDROID_LOCALE_MAP.get(name, name)[0:2]
137 lang_to_locale_map[lang].append(_ToAsset(basename))
138
139 return lang_to_locale_map
140
141
142 def _WriteJarOutput(output_path, in_zip_path, data):
143 """Write file data to a srcjar.
144
145 Args:
146 output_path: The output zip path.
147 in_zip_path: Destination path within the zip file.
148 contents: File data as a string.
149 """
150 path = os.path.dirname(output_path)
151 if path and not os.path.exists(path):
152 os.makedirs(path)
153 with zipfile.ZipFile(output_path, 'w') as srcjar:
154 build_utils.AddToZipHermetic(srcjar, in_zip_path, data=data)
155
156
157 def main():
158 parser = argparse.ArgumentParser()
159 build_utils.AddDepfileOption(parser)
160 parser.add_argument('--locale-paks', required=True,
161 help='List of pak file paths to be added to srcjar')
162 parser.add_argument('--srcjar', required=True, help='Path to output srcjar')
163 parser.add_argument('--target', required=True, help='Target invoking script')
164 parser.add_argument('--package-suffix', required=True,
165 help='Specifies package suffix for generated Java file. The generated '
166 'file will reside in org.chromium.PACKAGE_SUFFIX')
167 parser.add_argument('--print-languages',
168 action='store_true',
169 help='Print out the list of languages that cover the given locale paks '
170 '(using Android\'s language codes)')
171
172 args = parser.parse_args()
173
174 sources = build_utils.ParseGnList(args.locale_paks)
175
176 if args.depfile:
177 build_utils.WriteDepfile(args.depfile, args.srcjar, sources)
178
179 lang_to_locale_map = _ComputeLangToLocaleMappings(sources)
180 if args.print_languages:
181 print '\n'.join(sorted(lang_to_locale_map))
182
183 package = _PACKAGE_BASE + args.package_suffix
184 srcjar_contents = _CreateLocalePakFilesJava(
185 lang_to_locale_map, package, _CLASSNAME, args.target)
186 in_zip_path = os.path.join(
187 package.replace('.', '/'), _CLASSNAME + '.java')
188 _WriteJarOutput(args.srcjar, in_zip_path, srcjar_contents)
189
190
191 if __name__ == '__main__':
192 sys.exit(main())
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698