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

Side by Side Diff: mozharness/abb/transform_locales.py

Issue 29633713: Issue 6077 - Create script to modify the list of search engines dynamically (Closed)
Patch Set: refactored _transform_locales() Created Dec. 19, 2017, 4:49 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 | no next file » | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
1 # This file is part of Adblock Plus 1 # This file is part of Adblock Plus
2 # Copyright (C) 2006-present eyeo GmbH 2 # Copyright (C) 2006-present eyeo GmbH
3 # 3 #
4 # Adblock Plus is free software: you can redistribute it and/or modify 4 # Adblock Plus is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU General Public License version 3 as 5 # it under the terms of the GNU General Public License version 3 as
6 # published by the Free Software Foundation. 6 # published by the Free Software Foundation.
7 # 7 #
8 # Adblock Plus is distributed in the hope that it will be useful, 8 # Adblock Plus is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of 9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # GNU General Public License for more details. 11 # GNU General Public License for more details.
12 # 12 #
13 # You should have received a copy of the GNU General Public License 13 # You should have received a copy of the GNU General Public License
14 # along with Adblock Plus. If not, see <http://www.gnu.org/licenses/>. 14 # along with Adblock Plus. If not, see <http://www.gnu.org/licenses/>.
15 15
16 import json
16 import os 17 import os
17 import re 18 import re
18 import sys 19 import sys
19 20
20 _LOCALE_RE = re.compile("^([a-z]{2,3}(?:-[A-Z]{2})?)$") 21 _LOCALE_RE = re.compile("^([a-z]{2,3}(?:-[A-Z]{2})?)$")
21 _VALUES_LOCALE_RE = re.compile("^values-([a-z]{2,3}(?:-r[A-Z]{2})?)$") 22 _VALUES_LOCALE_RE = re.compile("^values-([a-z]{2,3}(?:-r[A-Z]{2})?)$")
22 23
24 _SEARCH_PROPS_RE = re.compile("^browser\.search\."
25 "(defaultenginename|order\.).*$")
26 _SHORTNAME_RE = re.compile("^<ShortName>(.*)</ShortName>$")
27
23 _PROPERTY_FORMAT_RE = re.compile("^(([^=]*)=)(.*)$") 28 _PROPERTY_FORMAT_RE = re.compile("^(([^=]*)=)(.*)$")
24 _ENTITY_FORMAT_RE = re.compile("^(\s*<!ENTITY\s*([^\"\s]*)\s*\")(.*)(\">)$") 29 _ENTITY_FORMAT_RE = re.compile("^(\s*<!ENTITY\s*([^\"\s]*)\s*\")(.*)(\">)$")
25 _STRING_FORMAT_RE = re.compile( 30 _STRING_FORMAT_RE = re.compile(
26 "^(\s*<string name=\"([^\"]*)\">)(.*)(</string>)$") 31 "^(\s*<string name=\"([^\"]*)\">)(.*)(</string>)$")
27 32
28 _MOZBUILD_PATH = os.path.join("python", "mozbuild") 33 _MOZBUILD_PATH = os.path.join("python", "mozbuild")
29 34
30 _CHROME_PATH = os.path.join("dist", "bin", "chrome") 35 _CHROME_PATH = os.path.join("dist", "bin", "chrome")
31 _RES_PATH = os.path.join("mobile", "android", "base", "res") 36 _RES_PATH = os.path.join("mobile", "android", "base", "res")
37 _L10N_PATH = os.path.join("abb-build", "l10n")
38 _LISTJSON_PATH = os.path.join(_LOCALES_PATH, "search", "list.json")
diegocarloslima 2018/01/03 14:25:07 This seems to cause an error, since _LOCALES_PATH
39 _LOCALES_PATH = os.path.join("mobile", "locales")
40 _SEARCHPLUGINS_PATH = os.path.join(_LOCALES_PATH, "searchplugins")
32 41
33 _BROWSER_DIR = "browser" 42 _BROWSER_DIR = "browser"
43 _REGION_PROPS_PATH = os.path.join(_BROWSER_DIR, "region.properties")
34 44
35 _APPSTRINGS_PROPS_PATH = os.path.join(_BROWSER_DIR, "appstrings.properties") 45 _APPSTRINGS_PROPS_PATH = os.path.join(_BROWSER_DIR, "appstrings.properties")
36 _STRINGS_XML_PATH = "strings.xml" 46 _STRINGS_XML_PATH = "strings.xml"
37 47
38 _DEFAULT_LOCALE = "en-US" 48 _DEFAULT_LOCALE = "en-US"
39 49
50 # Add Ecosia as secondary search engine.
51 # See https://issues.adblockplus.org/ticket/5518
52 _ECOSIA_ID = "ecosia"
53
54 _SEARCH_ENGINE_ORDER_DEFAULT = [
55 "duckduckgo",
56 "yahoo",
57 "google",
58 "wikipedia",
59 "amazondotcom"]
60
61 _SEARCH_ENGINE_ORDER_ECOSIA = [
62 "duckduckgo",
63 "yahoo",
64 "google",
65 "ecosia",
66 "wikipedia",
67 "amazon"]
68
69 _SEARCH_ENGINE_ORDER = {
70 "de": _SEARCH_ENGINE_ORDER_ECOSIA,
71 "en-GB": _SEARCH_ENGINE_ORDER_ECOSIA,
72 "en-US": _SEARCH_ENGINE_ORDER_ECOSIA,
73 "fr": _SEARCH_ENGINE_ORDER_ECOSIA,
74 "nl": _SEARCH_ENGINE_ORDER_ECOSIA,
75 "zh-CN": ["baidu",
76 "duckduckgo",
77 "yahoo",
78 "google",
79 "wikipedia",
80 "amazon"
81 ]
82 }
83
40 _FIREFOX_REPLACE_STR = "Firefox" 84 _FIREFOX_REPLACE_STR = "Firefox"
41 _ABB_REPLACEMENT_STR = "Adblock Browser" 85 _ABB_REPLACEMENT_STR = "Adblock Browser"
42 86
43 # Some string values that contain Firefox such as 'Firefox Sync' shouldn't be 87 # Some string values that contain Firefox such as 'Firefox Sync' shouldn't be
44 # replaced, so we keep a list of ids that are exceptions 88 # replaced, so we keep a list of ids that are exceptions
45 _ENTITY_EXCEPTIONS = [ 89 _ENTITY_EXCEPTIONS = [
46 "overlay_no_synced_devices", 90 "overlay_no_synced_devices",
47 "home_remote_tabs_need_to_sign_in", 91 "home_remote_tabs_need_to_sign_in",
48 "home_remote_tabs_need_to_finish_migrating", 92 "home_remote_tabs_need_to_finish_migrating",
49 "home_remote_tabs_need_to_verify", 93 "home_remote_tabs_need_to_verify",
(...skipping 52 matching lines...) Expand 10 before | Expand all | Expand 10 after
102 return None 146 return None
103 147
104 148
105 def _write_lines(filename, lines): 149 def _write_lines(filename, lines):
106 """Writes lines into file appending \\n""" 150 """Writes lines into file appending \\n"""
107 with open(filename, "w") as fd: 151 with open(filename, "w") as fd:
108 for l in lines: 152 for l in lines:
109 fd.write("%s\n" % l) 153 fd.write("%s\n" % l)
110 154
111 155
112 def _transform_locale(locale, path, logger): 156 def _transform_locale(data, locale, project_dir, locale_path, logger):
113 logger.info("Processing locale '%s'..." % locale) 157 logger.info("Processing locale '%s'..." % locale)
114 158
159 # Check for region.properties existence
160 region_file_path = os.path.join(locale_path, _REGION_PROPS_PATH)
161 _check_path_exists(region_file_path, logger)
162
115 # Check for appstrings.properties existence 163 # Check for appstrings.properties existence
116 appstrings_file_path = os.path.join(path, _APPSTRINGS_PROPS_PATH) 164 appstrings_file_path = os.path.join(locale_path, _APPSTRINGS_PROPS_PATH)
117 _check_path_exists(appstrings_file_path, logger) 165 _check_path_exists(appstrings_file_path, logger)
118 166
167 # Get whitelist and build regex
168 whitelist = _SEARCH_ENGINE_ORDER.get(locale,
169 _SEARCH_ENGINE_ORDER_DEFAULT)
170 white_re = re.compile("^(%s).*$" % "|".join(whitelist))
171
172 all_engine_ids = []
173 engine_ids = []
174 removed_engine_ids = []
175
176
diegocarloslima 2018/01/03 14:25:07 2 new lines here... seems that it should be just o
177 for item in data['locales'][locale]['default']['visibleDefaultEngines']:
178 all_engine_ids.append(item)
179 if len(item) > 0:
180 if white_re.match(item):
181 engine_ids.append(item)
182 else:
183 removed_engine_ids.append(item)
184
185 if _ECOSIA_ID in whitelist and _ECOSIA_ID not in all_engine_ids:
186 all_engine_ids.append(_ECOSIA_ID)
187 engine_ids.append(_ECOSIA_ID)
188
189 # Make sure we still have search engines left
190 if len(engine_ids) == 0:
191 logger.fatal("No search engines left over for '%s'" % locale)
192
193 data['locales'][locale]['default']['visibleDefaultEngines'] = all_engine_ids
194
195
196
diegocarloslima 2018/01/03 14:25:07 3 new lines here... seems that it should be just o
197 # 'Parse' XML to get matching 'ShortName' for all engine IDs
198 engine_names = {}
199 search_plugins_path = os.path.join(project_dir, _SEARCHPLUGINS_PATH)
200 for eid in engine_ids[:]:
201 xml_file_path = os.path.join(search_plugins_path, "%s.xml" % eid)
202 if not os.path.exists(xml_file_path):
203 logger.info("Missing xml file for plugin %s. Searched in path %s" %
204 (eid, xml_file_path))
205 engine_ids.remove(eid)
206 continue
207 short_name = None
208 with open(xml_file_path, "r") as fd:
209 for line in fd:
210 line = line.strip()
211 match = _SHORTNAME_RE.match(line)
212 if match:
213 short_name = match.group(1).strip()
214
215 if not short_name:
216 logger.fatal("No ShortName defined for '%s' in '%s" %
217 (eid, locale))
218 engine_names[eid] = short_name
219
220 logger.info("Removed search engine IDs: %s" %
221 ", ".join(removed_engine_ids))
222 logger.info("Remaining search engine IDs: %s" % ", ".join(engine_ids))
223
224 # Create search engine order with real engine names
225 engine_order = []
226 for eid in whitelist:
227 sn = _get_shortname_from_id(eid, engine_ids, engine_names)
228 if sn:
229 engine_order.append(sn)
230
231 logger.info("Resulting search engine ordered list: %s" %
232 (", ".join(engine_order)))
233
234 # Read region.properties and remove browser.search.* lines
235 props = []
236 with open(region_file_path, "r") as fd:
237 for line in fd:
238 line = line.rstrip("\r\n")
239 if not _SEARCH_PROPS_RE.match(line.strip()):
240 props.append(line)
241
242 # Append default search engine name
243 props.append("browser.search.defaultenginename=%s" % engine_order[0])
244
245 # Append search engine order
246 for i in range(0, len(engine_order)):
247 props.append("browser.search.order.%d=%s" % (i + 1, engine_order[i]))
248
249 # Write back region.properties
250 _write_lines(region_file_path, props)
251
119 # Replaces ocurrences of 'Firefox' by 'Adblock Browser' in 252 # Replaces ocurrences of 'Firefox' by 'Adblock Browser' in
120 # 'appstrings.properties' 253 # 'appstrings.properties'
121 lines = [] 254 lines = []
122 replacement_count = 0 255 replacement_count = 0
123 256
124 with open(appstrings_file_path, "r") as fd: 257 with open(appstrings_file_path, "r") as fd:
125 for line in fd: 258 for line in fd:
126 line = line.rstrip("\r\n") 259 line = line.rstrip("\r\n")
127 replacement = _replace_in_value(_PROPERTY_FORMAT_RE, line, 260 replacement = _replace_in_value(_PROPERTY_FORMAT_RE, line,
128 _FIREFOX_REPLACE_STR, 261 _FIREFOX_REPLACE_STR,
129 _ABB_REPLACEMENT_STR) 262 _ABB_REPLACEMENT_STR)
130 if replacement: 263 if replacement:
131 line = replacement 264 line = replacement
132 replacement_count += 1 265 replacement_count += 1
133 lines.append(line) 266 lines.append(line)
134 267
135 # Apply changes to appstrings.properties 268 # Apply changes to appstrings.properties
136 _write_lines(appstrings_file_path, lines) 269 _write_lines(appstrings_file_path, lines)
137 logger.info("Replaced %d ocurrences of %s in 'appstrings.properties'" % 270 logger.info("Replaced %d ocurrences of %s in 'appstrings.properties'" %
138 (replacement_count, _FIREFOX_REPLACE_STR)) 271 (replacement_count, _FIREFOX_REPLACE_STR))
139 272
140 273
141 def _generate_browser_search(locale, locale_path, res_path, build_dir): 274 def _generate_browser_search(locale, locale_path, res_path, project_dir):
142 raw_dir = "raw" if locale == _DEFAULT_LOCALE else ( 275 raw_dir = "raw" if locale == _DEFAULT_LOCALE else (
143 "raw-%s" % locale.replace("-", "-r")) 276 "raw-%s" % locale.replace("-", "-r"))
144 277
145 browser_path = os.path.join(locale_path, _BROWSER_DIR) 278 browser_path = os.path.join(locale_path, _BROWSER_DIR)
146 browsersearch_file_path = os.path.join(res_path, raw_dir, 279 browsersearch_file_path = os.path.join(res_path, raw_dir,
147 "browsersearch.json") 280 "browsersearch.json")
148 281
149 sys.path.append(os.path.join(build_dir, _MOZBUILD_PATH)) 282 sys.path.append(os.path.join(project_dir, _MOZBUILD_PATH))
150 import mozbuild.action.generate_browsersearch as generate_browsersearch 283 import mozbuild.action.generate_browsersearch as generate_browsersearch
151 284
152 # Call generate_browsersearch.py script to regenerate 285 # Call generate_browsersearch.py script to regenerate
153 # res/raw-LOCALE/browsersearch.json with the updated search engines 286 # res/raw-LOCALE/browsersearch.json with the updated search engines
154 generate_browsersearch.main(["--verbose", "--srcdir", browser_path, 287 generate_browsersearch.main(["--verbose", "--srcdir", browser_path,
155 browsersearch_file_path]) 288 browsersearch_file_path])
156 289
157 290
158 def _transform_values_locale(locale, path, logger): 291 def _transform_values_locale(locale, path, logger):
159 logger.info("Processing values-%s..." % locale) 292 logger.info("Processing values-%s..." % locale)
(...skipping 36 matching lines...) Expand 10 before | Expand all | Expand 10 after
196 print "INFO: %s" % s 329 print "INFO: %s" % s
197 330
198 def error(self, s): 331 def error(self, s):
199 print "ERROR: %s" % s 332 print "ERROR: %s" % s
200 333
201 def fatal(self, s): 334 def fatal(self, s):
202 print "FATAL: %s" % s 335 print "FATAL: %s" % s
203 exit(1) 336 exit(1)
204 337
205 338
206 def transform_locales(build_dir, obj_dir, logger=MinimalLogger()): 339 def transform_locales(project_dir, obj_dir, logger=MinimalLogger()):
207 chrome_path = os.path.join(obj_dir, _CHROME_PATH) 340 chrome_path = os.path.join(obj_dir, _CHROME_PATH)
208 _check_path_exists(chrome_path, logger) 341 _check_path_exists(chrome_path, logger)
209 342
210 res_path = os.path.join(obj_dir, _RES_PATH) 343 res_path = os.path.join(obj_dir, _RES_PATH)
211 _check_path_exists(res_path, logger) 344 _check_path_exists(res_path, logger)
212 345
346 list_json_path = os.path.join(project_dir, _LISTJSON_PATH)
347 _check_path_exists(list_json_path, logger)
348
213 locales = _get_locales_from_path(chrome_path, _LOCALE_RE) 349 locales = _get_locales_from_path(chrome_path, _LOCALE_RE)
214 values_locales = _get_locales_from_path(res_path, _VALUES_LOCALE_RE) 350 values_locales = _get_locales_from_path(res_path, _VALUES_LOCALE_RE)
215 351
216 locales_found_msg = "Found %d locales in %s" 352 locales_found_msg = "Found %d locales in %s"
217 logger.info(locales_found_msg % (len(locales), chrome_path)) 353 logger.info(locales_found_msg % (len(locales), chrome_path))
218 logger.info(locales_found_msg % (len(values_locales), res_path)) 354 logger.info(locales_found_msg % (len(values_locales), res_path))
219 355
220 for locale in locales: 356 # open the Mozilla list of search engines, put it into a buffer and
221 locale_path = os.path.join(chrome_path, locale, "locale", locale) 357 # close the JSON file after reading
222 if os.path.exists(locale_path): 358 with open(list_json_path, 'r') as json_file:
223 _transform_locale(locale, locale_path, logger) 359 data = json.load(jsonFile)
224 _generate_browser_search(locale, locale_path, res_path, build_dir)
225 else:
226 logger.error("Missing folder for locale '%s' in path: %s" %
227 (locale, locale_path))
228 360
229 for locale in values_locales: 361 # set default search engine order
230 locale_path = os.path.join(res_path, "values-" + locale) 362 data['default']['visibleDefaultEngines'] = _SEARCH_ENGINE_ORDER_DEFAULT
231 _transform_values_locale(locale, locale_path, logger) 363
364 for locale in locales:
365 locale_path = os.path.join(chrome_path, locale, "locale", locale)
366 if os.path.exists(locale_path):
367
368 # Mozilla default list does not contain locale bn-BD, so we crea te it
369 # and use the values from locale bn-IN
370 if locale == 'bn-BD':
371 data['locales'].update({locale: {'default': {'visibleDefault Engines': data['locales']
diegocarloslima 2018/01/03 14:25:07 This line is too big to be in compliance with PEP8
372 ['bn-IN']['default']['visibleDefaultE ngines']}}})
373 # Mozilla default list does not contain locale wo, so we use the
374 # default order. In case they will not support any other locales in
375 # the future, we want the build to fail, to decide which order t o use
376 elif locale == 'wo':
377 data['locales'].update({locale: {'default':
378 {'visibleDefaultEngines': _SEARCH_ENG INE_ORDER_DEFAULT}}})
379
380 _transform_locale(data, locale, project_dir, locale_path, logger )
381 _generate_browser_search(locale, locale_path, res_path, project_ dir)
382 else:
383 logger.error("Missing folder for locale '%s' in path: %s" %
384 (locale, locale_path))
385
386 # Save our changes to list.json
387 with open(list_json_path, 'w') as outfile:
388 json.dump(data, outfile, indent=4, sort_keys=True)
389
390 for locale in values_locales:
391 locale_path = os.path.join(res_path, "values-" + locale)
392 _transform_values_locale(locale, locale_path, logger)
393
OLDNEW
« no previous file with comments | « no previous file | no next file » | no next file with comments »

Powered by Google App Engine
This is Rietveld