blob: 56a5c62aef3e985a3ec7c96eccbeb7f797cad67e [file] [log] [blame]
Anthony Kingb8607632015-05-01 22:06:37 +03001#!/usr/bin/env python
Marco Brohetcb5cdb42014-07-11 22:41:53 +02002# -*- coding: utf-8 -*-
Michael Bestas1ab959b2014-07-26 16:01:01 +03003# crowdin_sync.py
Marco Brohetcb5cdb42014-07-11 22:41:53 +02004#
5# Updates Crowdin source translations and pushes translations
Eric Park6cf0bce2020-04-11 05:06:14 -04006# directly to BlissRoms's Gerrit.
Marco Brohetcb5cdb42014-07-11 22:41:53 +02007#
Michael Bestaseb4629a2018-11-14 23:03:18 +02008# Copyright (C) 2014-2016 The CyanogenMod Project
Michael W1bb2f922019-02-27 17:46:28 +01009# Copyright (C) 2017-2019 The LineageOS Project
Eric Park6cf0bce2020-04-11 05:06:14 -040010# Copyright (C) 2020 Team Bliss
Marco Brohetcb5cdb42014-07-11 22:41:53 +020011#
12# Licensed under the Apache License, Version 2.0 (the "License");
13# you may not use this file except in compliance with the License.
14# You may obtain a copy of the License at
15#
16# http://www.apache.org/licenses/LICENSE-2.0
17#
18# Unless required by applicable law or agreed to in writing, software
19# distributed under the License is distributed on an "AS IS" BASIS,
20# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21# See the License for the specific language governing permissions and
22# limitations under the License.
23
Anthony Kingb8607632015-05-01 22:06:37 +030024# ################################# IMPORTS ################################## #
25
26from __future__ import print_function
Marco Brohet6b6b4e52014-07-20 00:05:16 +020027
28import argparse
Michael W6e0a7032019-02-27 17:04:16 +010029import json
Marco Brohetcb5cdb42014-07-11 22:41:53 +020030import git
31import os
Michael Wbfa2f952019-03-10 19:53:10 +010032import re
Michael Wb26b8662019-08-10 23:26:59 +020033import shutil
Marco Brohetcb5cdb42014-07-11 22:41:53 +020034import subprocess
35import sys
Michael W1bb2f922019-02-27 17:46:28 +010036import yaml
Anthony Kingb8607632015-05-01 22:06:37 +030037
Michael W2ae05622019-02-28 15:27:22 +010038from lxml import etree
Michael We3af0fc2020-01-19 12:51:55 +010039from signal import signal, SIGINT
Marco Brohetcb5cdb42014-07-11 22:41:53 +020040
Anthony Kingd0d56cf2015-06-05 10:48:38 +010041# ################################# GLOBALS ################################## #
42
43_DIR = os.path.dirname(os.path.realpath(__file__))
Tom Powell44256852016-07-06 15:23:25 -070044_COMMITS_CREATED = False
Anthony Kingd0d56cf2015-06-05 10:48:38 +010045
Anthony Kingb8607632015-05-01 22:06:37 +030046# ################################ FUNCTIONS ################################# #
47
48
49def run_subprocess(cmd, silent=False):
50 p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
51 universal_newlines=True)
52 comm = p.communicate()
53 exit_code = p.returncode
54 if exit_code != 0 and not silent:
55 print("There was an error running the subprocess.\n"
56 "cmd: %s\n"
57 "exit code: %d\n"
58 "stdout: %s\n"
59 "stderr: %s" % (cmd, exit_code, comm[0], comm[1]),
60 file=sys.stderr)
61 return comm, exit_code
62
Marco Brohet6b6b4e52014-07-20 00:05:16 +020063
Michael W2ae05622019-02-28 15:27:22 +010064def add_target_paths(config_files, repo, base_path, project_path):
Michael W1bb2f922019-02-27 17:46:28 +010065 # Add or remove the files given in the config files to the commit
66 count = 0
67 file_paths = []
68 for f in config_files:
69 fh = open(f, "r")
70 try:
Michael W6633d752020-02-02 13:04:39 +010071 config = yaml.safe_load(fh)
Michael W1bb2f922019-02-27 17:46:28 +010072 for tf in config['files']:
73 if project_path in tf['source']:
74 target_path = tf['translation']
75 lang_codes = tf['languages_mapping']['android_code']
76 for l in lang_codes:
77 lpath = get_target_path(tf['translation'], tf['source'],
78 lang_codes[l], project_path)
79 file_paths.append(lpath)
80 except yaml.YAMLError as e:
81 print(e, '\n Could not parse YAML.')
82 exit()
83 fh.close()
84
Michael W2ae05622019-02-28 15:27:22 +010085 # Strip all comments
86 for f in file_paths:
Michael Wb26b8662019-08-10 23:26:59 +020087 clean_xml_file(base_path, project_path, f, repo)
Michael W2ae05622019-02-28 15:27:22 +010088
89 # Modified and untracked files
90 modified = repo.git.ls_files(m=True, o=True)
Michael W1bb2f922019-02-27 17:46:28 +010091 for m in modified.split('\n'):
92 if m in file_paths:
93 repo.git.add(m)
94 count += 1
95
96 deleted = repo.git.ls_files(d=True)
97 for d in deleted.split('\n'):
98 if d in file_paths:
99 repo.git.rm(d)
100 count += 1
101
102 return count
103
104
105def split_path(path):
106 # Split the given string to path and filename
107 if '/' in path:
108 original_file_name = path[1:][path.rfind("/"):]
109 original_path = path[:path.rfind("/")]
110 else:
111 original_file_name = path
112 original_path = ''
113
114 return original_path, original_file_name
115
116
117def get_target_path(pattern, source, lang, project_path):
118 # Make strings like '/%original_path%-%android_code%/%original_file_name%' valid file paths
119 # based on the source string's path
120 original_path, original_file_name = split_path(source)
121
122 target_path = pattern #.lstrip('/')
123 target_path = target_path.replace('%original_path%', original_path)
124 target_path = target_path.replace('%android_code%', lang)
125 target_path = target_path.replace('%original_file_name%', original_file_name)
126 target_path = target_path.replace(project_path, '')
127 target_path = target_path.lstrip('/')
128 return target_path
129
130
Michael Wb26b8662019-08-10 23:26:59 +0200131def clean_xml_file(base_path, project_path, filename, repo):
Michael W2ae05622019-02-28 15:27:22 +0100132 path = base_path + '/' + project_path + '/' + filename
133
134 # We don't want to create every file, just work with those already existing
135 if not os.path.isfile(path):
136 return
137
138 try:
139 fh = open(path, 'r+')
140 except:
Michael Wb8394d82020-03-28 20:49:37 +0100141 print('\nSomething went wrong while opening file %s' % (path))
Michael W2ae05622019-02-28 15:27:22 +0100142 return
143
144 XML = fh.read()
Michael Wb26b8662019-08-10 23:26:59 +0200145 try:
146 tree = etree.fromstring(XML)
147 except etree.XMLSyntaxError as err:
148 print('%s: XML Error: %s' % (filename, err.error_log))
149 filename, ext = os.path.splitext(path)
150 if ext == '.xml':
151 reset_file(path, repo)
152 return
Michael W2ae05622019-02-28 15:27:22 +0100153
Michael Wb1587982019-06-19 15:29:24 +0200154 # Remove strings with 'product=*' attribute but no 'product=default'
155 # This will ensure aapt2 will not throw an error when building these
Michael Wba72bd52020-03-28 20:31:35 +0100156 alreadyRemoved = []
Michael Wb1587982019-06-19 15:29:24 +0200157 productStrings = tree.xpath("//string[@product]")
158 for ps in productStrings:
Michael Wba72bd52020-03-28 20:31:35 +0100159 # if we already removed the items, don't process them
160 if ps in alreadyRemoved:
161 continue
Michael Wb1587982019-06-19 15:29:24 +0200162 stringName = ps.get('name')
163 stringsWithSameName = tree.xpath("//string[@name='{0}']"
164 .format(stringName))
165
166 # We want to find strings with product='default' or no product attribute at all
167 hasProductDefault = False
168 for string in stringsWithSameName:
169 product = string.get('product')
170 if product is None or product == 'default':
171 hasProductDefault = True
172 break
173
174 # Every occurance of the string has to be removed when no string with the same name and
175 # 'product=default' (or no product attribute) was found
176 if not hasProductDefault:
Michael Wb8394d82020-03-28 20:49:37 +0100177 print("\n{0}: Found string '{1}' with missing 'product=default' attribute"
178 .format(path, stringName), end='')
Michael Wb1587982019-06-19 15:29:24 +0200179 for string in stringsWithSameName:
180 tree.remove(string)
Michael Wba72bd52020-03-28 20:31:35 +0100181 alreadyRemoved.append(string)
Michael Wb1587982019-06-19 15:29:24 +0200182
Michael W2ae05622019-02-28 15:27:22 +0100183 header = ''
184 comments = tree.xpath('//comment()')
185 for c in comments:
186 p = c.getparent()
187 if p is None:
188 # Keep all comments in header
189 header += str(c).replace('\\n', '\n').replace('\\t', '\t') + '\n'
190 continue
191 p.remove(c)
192
193 content = ''
194
195 # Take the original xml declaration and prepend it
196 declaration = XML.split('\n')[0]
197 if '<?' in declaration:
198 content = declaration + '\n'
199
200 content += etree.tostring(tree, pretty_print=True, encoding="utf-8", xml_declaration=False)
201
202 if header != '':
203 content = content.replace('?>\n', '?>\n' + header)
204
205 # Sometimes spaces are added, we don't want them
206 content = re.sub("[ ]*<\/resources>", "</resources>", content)
207
208 # Overwrite file with content stripped by all comments
209 fh.seek(0)
210 fh.write(content)
211 fh.truncate()
212 fh.close()
213
214 # Remove files which don't have any translated strings
Michael Wed3af932019-06-19 22:41:09 +0200215 contentList = list(tree)
216 if len(contentList) == 0:
Michael Wb8394d82020-03-28 20:49:37 +0100217 print('\nRemoving ' + path)
Michael Wed3af932019-06-19 22:41:09 +0200218 os.remove(path)
Michael W2ae05622019-02-28 15:27:22 +0100219
Michael Wb26b8662019-08-10 23:26:59 +0200220
221# For files we can't process due to errors, create a backup
222# and checkout the file to get it back to the previous state
223def reset_file(filepath, repo):
224 backupFile = None
225 parts = filepath.split("/")
226 found = False
227 for s in parts:
228 curPart = s
229 if not found and s.startswith("res"):
230 curPart = s + "_backup"
231 found = True
232 if backupFile is None:
233 backupFile = curPart
234 else:
235 backupFile = backupFile + '/' + curPart
236
237 path, filename = os.path.split(backupFile)
238 if not os.path.exists(path):
239 os.makedirs(path)
240 if os.path.exists(backupFile):
241 i = 1
242 while os.path.exists(backupFile + str(i)):
243 i+=1
244 backupFile = backupFile + str(i)
245 shutil.copy(filepath, backupFile)
246 repo.git.checkout(filepath)
247
248
Michael W1bb2f922019-02-27 17:46:28 +0100249def push_as_commit(config_files, base_path, path, name, branch, username):
Michael Wb8394d82020-03-28 20:49:37 +0100250 print('\nCommitting %s on branch %s: ' % (name, branch), end='')
Marco Brohetcb5cdb42014-07-11 22:41:53 +0200251
252 # Get path
Michael W1bb2f922019-02-27 17:46:28 +0100253 project_path = path
Michael Bestas118fcaf2015-06-04 23:02:20 +0300254 path = os.path.join(base_path, path)
Anthony Kingb8607632015-05-01 22:06:37 +0300255 if not path.endswith('.git'):
256 path = os.path.join(path, '.git')
Marco Brohetcb5cdb42014-07-11 22:41:53 +0200257
Marco Brohet6b6b4e52014-07-20 00:05:16 +0200258 # Create repo object
Marco Brohetcb5cdb42014-07-11 22:41:53 +0200259 repo = git.Repo(path)
Marco Brohet6b6b4e52014-07-20 00:05:16 +0200260
Marco Brohet6b6b4e52014-07-20 00:05:16 +0200261 # Add all files to commit
Michael W2ae05622019-02-28 15:27:22 +0100262 count = add_target_paths(config_files, repo, base_path, project_path)
Michael W1bb2f922019-02-27 17:46:28 +0100263
264 if count == 0:
265 print('Nothing to commit')
266 return
Marco Brohet6b6b4e52014-07-20 00:05:16 +0200267
268 # Create commit; if it fails, probably empty so skipping
Marco Brohetcb5cdb42014-07-11 22:41:53 +0200269 try:
Michael Bestas80b22ef2018-11-14 23:12:33 +0200270 repo.git.commit(m='Automatic translation import')
Marco Brohetcb5cdb42014-07-11 22:41:53 +0200271 except:
Michael We3af0fc2020-01-19 12:51:55 +0100272 print('Failed, probably empty: skipping', file=sys.stderr)
Marco Brohetcb5cdb42014-07-11 22:41:53 +0200273 return
Marco Brohet6b6b4e52014-07-20 00:05:16 +0200274
275 # Push commit
Michael Bestasf96f67b2014-10-21 00:43:37 +0300276 try:
Eric Park6cf0bce2020-04-11 05:06:14 -0400277 repo.git.push('ssh://%s@review.blissroms.com:29418/%s' % (username, name),
Anthony Kingb8607632015-05-01 22:06:37 +0300278 'HEAD:refs/for/%s%%topic=translation' % branch)
Michael We3af0fc2020-01-19 12:51:55 +0100279 print('Success')
Michael Bestasf96f67b2014-10-21 00:43:37 +0300280 except:
Michael We3af0fc2020-01-19 12:51:55 +0100281 print('Failed', file=sys.stderr)
Marco Brohetcb5cdb42014-07-11 22:41:53 +0200282
Tom Powell44256852016-07-06 15:23:25 -0700283 _COMMITS_CREATED = True
284
Anthony Kingb8607632015-05-01 22:06:37 +0300285
Michael Wd13658a2019-01-13 14:05:37 +0100286def submit_gerrit(branch, username):
287 # Find all open translation changes
288 cmd = ['ssh', '-p', '29418',
Eric Park6cf0bce2020-04-11 05:06:14 -0400289 '{}@review.blissroms.com'.format(username),
Michael Wd13658a2019-01-13 14:05:37 +0100290 'gerrit', 'query',
291 'status:open',
292 'branch:{}'.format(branch),
293 'message:"Automatic translation import"',
294 'topic:translation',
Michael W6e0a7032019-02-27 17:04:16 +0100295 '--current-patch-set',
296 '--format=JSON']
297 commits = 0
Michael Wd13658a2019-01-13 14:05:37 +0100298 msg, code = run_subprocess(cmd)
299 if code != 0:
300 print('Failed: {0}'.format(msg[1]))
301 return
302
Michael W6e0a7032019-02-27 17:04:16 +0100303 # Each line is one valid JSON object, except the last one, which is empty
304 for line in msg[0].strip('\n').split('\n'):
305 js = json.loads(line)
306 # We get valid JSON, but not every result line is one we want
307 if not 'currentPatchSet' in js or not 'revision' in js['currentPatchSet']:
308 continue
Michael Wd13658a2019-01-13 14:05:37 +0100309 # Add Code-Review +2 and Verified+1 labels and submit
310 cmd = ['ssh', '-p', '29418',
Eric Park6cf0bce2020-04-11 05:06:14 -0400311 '{}@review.blissroms.com'.format(username),
Michael Wd13658a2019-01-13 14:05:37 +0100312 'gerrit', 'review',
313 '--verified +1',
314 '--code-review +2',
Michael W6e0a7032019-02-27 17:04:16 +0100315 '--submit', js['currentPatchSet']['revision']]
Michael Wd13658a2019-01-13 14:05:37 +0100316 msg, code = run_subprocess(cmd, True)
Michael We3af0fc2020-01-19 12:51:55 +0100317 print('Submitting commit %s: ' % js[url], end='')
Michael Wd13658a2019-01-13 14:05:37 +0100318 if code != 0:
319 errorText = msg[1].replace('\n\n', '; ').replace('\n', '')
Michael We3af0fc2020-01-19 12:51:55 +0100320 print('Failed: %s' % errorText)
Michael Wd13658a2019-01-13 14:05:37 +0100321 else:
Michael We3af0fc2020-01-19 12:51:55 +0100322 print('Success')
Michael W6e0a7032019-02-27 17:04:16 +0100323
324 commits += 1
325
326 if commits == 0:
327 print("Nothing to submit!")
328 return
Michael Wd13658a2019-01-13 14:05:37 +0100329
330
Anthony Kingb8607632015-05-01 22:06:37 +0300331def check_run(cmd):
Michael Bestas97677e12015-02-08 13:11:59 +0200332 p = subprocess.Popen(cmd, stdout=sys.stdout, stderr=sys.stderr)
333 ret = p.wait()
334 if ret != 0:
Anthony Kingb8607632015-05-01 22:06:37 +0300335 print('Failed to run cmd: %s' % ' '.join(cmd), file=sys.stderr)
Michael Bestas97677e12015-02-08 13:11:59 +0200336 sys.exit(ret)
337
Marco Brohet6b6b4e52014-07-20 00:05:16 +0200338
Michael Bestas118fcaf2015-06-04 23:02:20 +0300339def find_xml(base_path):
340 for dp, dn, file_names in os.walk(base_path):
Anthony Kingb8607632015-05-01 22:06:37 +0300341 for f in file_names:
342 if os.path.splitext(f)[1] == '.xml':
343 yield os.path.join(dp, f)
Marco Brohet6b6b4e52014-07-20 00:05:16 +0200344
Anthony Kingb8607632015-05-01 22:06:37 +0300345# ############################################################################ #
Marco Brohet6b6b4e52014-07-20 00:05:16 +0200346
Michael Bestas6b6db122015-02-08 13:22:22 +0200347
Anthony Kingb8607632015-05-01 22:06:37 +0300348def parse_args():
349 parser = argparse.ArgumentParser(
Eric Park6cf0bce2020-04-11 05:06:14 -0400350 description="Synchronising BlissRoms's translations with Crowdin")
Michael Bestasfd5d1362015-12-18 20:34:32 +0200351 parser.add_argument('-u', '--username', help='Gerrit username')
Eric Park6cf0bce2020-04-11 05:06:14 -0400352 parser.add_argument('-b', '--branch', help='BlissRoms branch',
Anthony Kingb8607632015-05-01 22:06:37 +0300353 required=True)
Michael Bestas2f8c4a52015-08-05 21:33:50 +0300354 parser.add_argument('-c', '--config', help='Custom yaml config')
Michael Bestasfd5d1362015-12-18 20:34:32 +0200355 parser.add_argument('--upload-sources', action='store_true',
356 help='Upload sources to Crowdin')
357 parser.add_argument('--upload-translations', action='store_true',
358 help='Upload translations to Crowdin')
359 parser.add_argument('--download', action='store_true',
360 help='Download translations from Crowdin')
Michael Wd13658a2019-01-13 14:05:37 +0100361 parser.add_argument('-s', '--submit', action='store_true',
362 help='Merge open translation commits')
Anthony Kingb8607632015-05-01 22:06:37 +0300363 return parser.parse_args()
Michael Bestas6b6db122015-02-08 13:22:22 +0200364
Anthony Kingb8607632015-05-01 22:06:37 +0300365# ################################# PREPARE ################################## #
Marco Brohet6b6b4e52014-07-20 00:05:16 +0200366
Anthony Kingb8607632015-05-01 22:06:37 +0300367
368def check_dependencies():
Michael Bestaseb4629a2018-11-14 23:03:18 +0200369 # Check for Java version of crowdin
370 cmd = ['dpkg-query', '-W', 'crowdin']
Anthony Kingb8607632015-05-01 22:06:37 +0300371 if run_subprocess(cmd, silent=True)[1] != 0:
Michael Bestaseb4629a2018-11-14 23:03:18 +0200372 print('You have not installed crowdin.', file=sys.stderr)
Anthony Kingb8607632015-05-01 22:06:37 +0300373 return False
Anthony Kingb8607632015-05-01 22:06:37 +0300374 return True
Marco Brohetcb5cdb42014-07-11 22:41:53 +0200375
Marco Brohetcb5cdb42014-07-11 22:41:53 +0200376
Michael Bestas118fcaf2015-06-04 23:02:20 +0300377def load_xml(x):
Anthony Kingb8607632015-05-01 22:06:37 +0300378 try:
Michael Wda610ba2020-03-22 18:38:19 +0100379 return etree.parse(x)
380 except etree.XMLSyntaxError:
381 print('Malformed %s.' % x, file=sys.stderr)
Anthony Kingb8607632015-05-01 22:06:37 +0300382 return None
383 except Exception:
Michael Wda610ba2020-03-22 18:38:19 +0100384 print('You have no %s.' % x, file=sys.stderr)
Anthony Kingb8607632015-05-01 22:06:37 +0300385 return None
Marco Brohet6b6b4e52014-07-20 00:05:16 +0200386
Michael Bestas4b26c4e2014-10-23 23:21:59 +0300387
Michael Bestas2f8c4a52015-08-05 21:33:50 +0300388def check_files(files):
Anthony Kingb8607632015-05-01 22:06:37 +0300389 for f in files:
390 if not os.path.isfile(f):
391 print('You have no %s.' % f, file=sys.stderr)
392 return False
Anthony Kingb8607632015-05-01 22:06:37 +0300393 return True
Michael Bestas4b26c4e2014-10-23 23:21:59 +0300394
Anthony Kingb8607632015-05-01 22:06:37 +0300395# ################################### MAIN ################################### #
Michael Bestas4b26c4e2014-10-23 23:21:59 +0300396
Michael Bestas4b26c4e2014-10-23 23:21:59 +0300397
Michael Bestasfd5d1362015-12-18 20:34:32 +0200398def upload_sources_crowdin(branch, config):
Michael Bestas2f8c4a52015-08-05 21:33:50 +0300399 if config:
Michael Bestasfd5d1362015-12-18 20:34:32 +0200400 print('\nUploading sources to Crowdin (custom config)')
Michael Bestaseb4629a2018-11-14 23:03:18 +0200401 check_run(['crowdin',
Michael Bestas03bc7052016-03-12 03:19:10 +0200402 '--config=%s/config/%s' % (_DIR, config),
Michael Bestas44fbb352015-12-17 02:01:42 +0200403 'upload', 'sources', '--branch=%s' % branch])
Michael Bestas2f8c4a52015-08-05 21:33:50 +0300404 else:
Michael Bestasfd5d1362015-12-18 20:34:32 +0200405 print('\nUploading sources to Crowdin (AOSP supported languages)')
Michael Bestaseb4629a2018-11-14 23:03:18 +0200406 check_run(['crowdin',
Michael Bestas03bc7052016-03-12 03:19:10 +0200407 '--config=%s/config/%s.yaml' % (_DIR, branch),
Michael Bestas44fbb352015-12-17 02:01:42 +0200408 'upload', 'sources', '--branch=%s' % branch])
Anthony King69a95382015-02-08 18:44:10 +0000409
Michael Bestasfd5d1362015-12-18 20:34:32 +0200410 print('\nUploading sources to Crowdin (non-AOSP supported languages)')
Michael Bestaseb4629a2018-11-14 23:03:18 +0200411 check_run(['crowdin',
Michael Bestas03bc7052016-03-12 03:19:10 +0200412 '--config=%s/config/%s_aosp.yaml' % (_DIR, branch),
Michael Bestas44fbb352015-12-17 02:01:42 +0200413 'upload', 'sources', '--branch=%s' % branch])
Anthony Kingb8607632015-05-01 22:06:37 +0300414
415
Michael Bestasfd5d1362015-12-18 20:34:32 +0200416def upload_translations_crowdin(branch, config):
Michael Bestas2f8c4a52015-08-05 21:33:50 +0300417 if config:
Michael Bestasfd5d1362015-12-18 20:34:32 +0200418 print('\nUploading translations to Crowdin (custom config)')
Michael Bestaseb4629a2018-11-14 23:03:18 +0200419 check_run(['crowdin',
Michael Bestas03bc7052016-03-12 03:19:10 +0200420 '--config=%s/config/%s' % (_DIR, config),
Michael Bestasfd5d1362015-12-18 20:34:32 +0200421 'upload', 'translations', '--branch=%s' % branch,
422 '--no-import-duplicates', '--import-eq-suggestions',
423 '--auto-approve-imported'])
424 else:
425 print('\nUploading translations to Crowdin '
426 '(AOSP supported languages)')
Michael Bestaseb4629a2018-11-14 23:03:18 +0200427 check_run(['crowdin',
Michael Bestas03bc7052016-03-12 03:19:10 +0200428 '--config=%s/config/%s.yaml' % (_DIR, branch),
Michael Bestasfd5d1362015-12-18 20:34:32 +0200429 'upload', 'translations', '--branch=%s' % branch,
430 '--no-import-duplicates', '--import-eq-suggestions',
431 '--auto-approve-imported'])
432
433 print('\nUploading translations to Crowdin '
434 '(non-AOSP supported languages)')
Michael Bestaseb4629a2018-11-14 23:03:18 +0200435 check_run(['crowdin',
Michael Bestas03bc7052016-03-12 03:19:10 +0200436 '--config=%s/config/%s_aosp.yaml' % (_DIR, branch),
Michael Bestasfd5d1362015-12-18 20:34:32 +0200437 'upload', 'translations', '--branch=%s' % branch,
438 '--no-import-duplicates', '--import-eq-suggestions',
439 '--auto-approve-imported'])
440
441
Michael Bestas80b22ef2018-11-14 23:12:33 +0200442def download_crowdin(base_path, branch, xml, username, config):
Michael Bestasfd5d1362015-12-18 20:34:32 +0200443 if config:
444 print('\nDownloading translations from Crowdin (custom config)')
Michael Bestaseb4629a2018-11-14 23:03:18 +0200445 check_run(['crowdin',
Michael Bestas03bc7052016-03-12 03:19:10 +0200446 '--config=%s/config/%s' % (_DIR, config),
Michael Bestas44fbb352015-12-17 02:01:42 +0200447 'download', '--branch=%s' % branch])
Michael Bestas2f8c4a52015-08-05 21:33:50 +0300448 else:
Michael Bestasfd5d1362015-12-18 20:34:32 +0200449 print('\nDownloading translations from Crowdin '
450 '(AOSP supported languages)')
Michael Bestaseb4629a2018-11-14 23:03:18 +0200451 check_run(['crowdin',
Michael Bestas03bc7052016-03-12 03:19:10 +0200452 '--config=%s/config/%s.yaml' % (_DIR, branch),
Michael Bestas44fbb352015-12-17 02:01:42 +0200453 'download', '--branch=%s' % branch])
Michael Bestas50579d22014-08-09 17:49:14 +0300454
Michael Bestasfd5d1362015-12-18 20:34:32 +0200455 print('\nDownloading translations from Crowdin '
Michael Bestas2f8c4a52015-08-05 21:33:50 +0300456 '(non-AOSP supported languages)')
Michael Bestaseb4629a2018-11-14 23:03:18 +0200457 check_run(['crowdin',
Michael Bestas03bc7052016-03-12 03:19:10 +0200458 '--config=%s/config/%s_aosp.yaml' % (_DIR, branch),
Michael Bestas44fbb352015-12-17 02:01:42 +0200459 'download', '--branch=%s' % branch])
Marco Brohetcb5cdb42014-07-11 22:41:53 +0200460
Michael Bestas99f5fce2015-06-04 22:07:51 +0300461 print('\nCreating a list of pushable translations')
Michael Bestas919053f2014-10-20 23:30:54 +0300462 # Get all files that Crowdin pushed
Anthony Kingb8607632015-05-01 22:06:37 +0300463 paths = []
Michael Bestas2f8c4a52015-08-05 21:33:50 +0300464 if config:
Michael Bestas03bc7052016-03-12 03:19:10 +0200465 files = ['%s/config/%s' % (_DIR, config)]
Michael Bestas2f8c4a52015-08-05 21:33:50 +0300466 else:
Michael Bestas03bc7052016-03-12 03:19:10 +0200467 files = ['%s/config/%s.yaml' % (_DIR, branch),
468 '%s/config/%s_aosp.yaml' % (_DIR, branch)]
Michael Bestas6c327e62015-05-02 01:58:01 +0300469 for c in files:
Michael Bestaseb4629a2018-11-14 23:03:18 +0200470 cmd = ['crowdin', '--config=%s' % c, 'list', 'project',
Michael Bestas44fbb352015-12-17 02:01:42 +0200471 '--branch=%s' % branch]
Anthony Kingb8607632015-05-01 22:06:37 +0300472 comm, ret = run_subprocess(cmd)
473 if ret != 0:
474 sys.exit(ret)
475 for p in str(comm[0]).split("\n"):
476 paths.append(p.replace('/%s' % branch, ''))
Michael Bestas50579d22014-08-09 17:49:14 +0300477
Michael Bestas99f5fce2015-06-04 22:07:51 +0300478 print('\nUploading translations to Gerrit')
Michael Wda610ba2020-03-22 18:38:19 +0100479 items = [x for xmlfile in xml for x in xmlfile.findall("//project")]
Michael Bestas919053f2014-10-20 23:30:54 +0300480 all_projects = []
481
Anthony Kingb8607632015-05-01 22:06:37 +0300482 for path in paths:
483 path = path.strip()
Michael Bestas919053f2014-10-20 23:30:54 +0300484 if not path:
485 continue
486
Anthony Kingb8607632015-05-01 22:06:37 +0300487 if "/res" not in path:
488 print('WARNING: Cannot determine project root dir of '
489 '[%s], skipping.' % path)
Anthony King69a95382015-02-08 18:44:10 +0000490 continue
Michael W67f14932019-03-11 09:59:32 +0100491
492 # Usually the project root is everything before /res
493 # but there are special cases where /res is part of the repo name as well
494 parts = path.split("/res")
495 if len(parts) == 2:
496 result = parts[0]
497 elif len(parts) == 3:
498 result = parts[0] + '/res' + parts[1]
499 else:
500 print('WARNING: Splitting the path not successful for [%s], skipping' % path)
501 continue
502
503 result = result.strip('/')
Anthony Kingb8607632015-05-01 22:06:37 +0300504 if result == path.strip('/'):
505 print('WARNING: Cannot determine project root dir of '
506 '[%s], skipping.' % path)
507 continue
Marco Brohet6b6b4e52014-07-20 00:05:16 +0200508
Michael Bestasc899b8c2015-03-03 00:53:19 +0200509 if result in all_projects:
Michael Bestasc899b8c2015-03-03 00:53:19 +0200510 continue
Michael Bestas50579d22014-08-09 17:49:14 +0300511
Anthony Kingb8607632015-05-01 22:06:37 +0300512 # When a project has multiple translatable files, Crowdin will
513 # give duplicates.
514 # We don't want that (useless empty commits), so we save each
515 # project in all_projects and check if it's already in there.
Michael Bestasc899b8c2015-03-03 00:53:19 +0200516 all_projects.append(result)
Anthony King69a95382015-02-08 18:44:10 +0000517
Michael Bestas42e25e32016-03-12 20:18:39 +0200518 # Search android/default.xml or config/%(branch)_extra_packages.xml
Anthony Kingb8607632015-05-01 22:06:37 +0300519 # for the project's name
Michael W1f187762019-03-11 19:38:00 +0100520 resultPath = None
521 resultProject = None
Anthony Kingb8607632015-05-01 22:06:37 +0300522 for project in items:
Michael Wda610ba2020-03-22 18:38:19 +0100523 path = project.get('path')
Anthony Kingb8607632015-05-01 22:06:37 +0300524 if not (result + '/').startswith(path +'/'):
Michael Bestasc899b8c2015-03-03 00:53:19 +0200525 continue
Michael W1f187762019-03-11 19:38:00 +0100526 # We want the longest match, so projects in subfolders of other projects are also
527 # taken into account
528 if resultPath is None or len(path) > len(resultPath):
529 resultPath = path
530 resultProject = project
Anthony King69a95382015-02-08 18:44:10 +0000531
Michael W1f187762019-03-11 19:38:00 +0100532 # Just in case no project was found
533 if resultPath is None:
534 continue
Anthony King69a95382015-02-08 18:44:10 +0000535
Michael W1f187762019-03-11 19:38:00 +0100536 if result != resultPath:
537 if resultPath in all_projects:
538 continue
539 result = resultPath
540 all_projects.append(result)
541
Michael Wda610ba2020-03-22 18:38:19 +0100542 br = resultProject.get('revision') or branch
Michael W1f187762019-03-11 19:38:00 +0100543
544 push_as_commit(files, base_path, result,
Michael Wda610ba2020-03-22 18:38:19 +0100545 resultProject.get('name'), br, username)
Anthony King69a95382015-02-08 18:44:10 +0000546
Anthony King69a95382015-02-08 18:44:10 +0000547
Michael We3af0fc2020-01-19 12:51:55 +0100548def sig_handler(signal_received, frame):
549 print('')
550 print('SIGINT or CTRL-C detected. Exiting gracefully')
551 exit(0)
552
553
Anthony Kingb8607632015-05-01 22:06:37 +0300554def main():
Michael We3af0fc2020-01-19 12:51:55 +0100555 signal(SIGINT, sig_handler)
Anthony Kingb8607632015-05-01 22:06:37 +0300556 args = parse_args()
557 default_branch = args.branch
Michael Bestas118fcaf2015-06-04 23:02:20 +0300558
Michael Wd13658a2019-01-13 14:05:37 +0100559 if args.submit:
560 if args.username is None:
561 print('Argument -u/--username is required for submitting!')
562 sys.exit(1)
563 submit_gerrit(default_branch, args.username)
564 sys.exit(0)
565
Michael Bestaseb4629a2018-11-14 23:03:18 +0200566 base_path_branch_suffix = default_branch.replace('-', '_').replace('.', '_').upper()
Eric Park6cf0bce2020-04-11 05:06:14 -0400567 base_path_env = 'BLISS_CROWDIN_BASE_PATH_%s' % base_path_branch_suffix
Michael Bestaseb4629a2018-11-14 23:03:18 +0200568 base_path = os.getenv(base_path_env)
Michael Bestas118fcaf2015-06-04 23:02:20 +0300569 if base_path is None:
Anthony Kingd0d56cf2015-06-05 10:48:38 +0100570 cwd = os.getcwd()
Michael Bestaseb4629a2018-11-14 23:03:18 +0200571 print('You have not set %s. Defaulting to %s' % (base_path_env, cwd))
Michael Bestas118fcaf2015-06-04 23:02:20 +0300572 base_path = cwd
Michael Bestas118fcaf2015-06-04 23:02:20 +0300573 if not os.path.isdir(base_path):
Michael Bestaseb4629a2018-11-14 23:03:18 +0200574 print('%s is not a real directory: %s' % (base_path_env, base_path))
Michael Bestas118fcaf2015-06-04 23:02:20 +0300575 sys.exit(1)
Anthony Kingb8607632015-05-01 22:06:37 +0300576
Michael Bestas99f5fce2015-06-04 22:07:51 +0300577 if not check_dependencies():
578 sys.exit(1)
Anthony Kingb8607632015-05-01 22:06:37 +0300579
Eric Park2bfe7232020-04-11 05:37:23 -0400580 xml_android = load_xml(x='%s/manifest/default.xml' % base_path)
Anthony Kingb8607632015-05-01 22:06:37 +0300581 if xml_android is None:
582 sys.exit(1)
583
Eric Parkf91d5802020-04-11 05:34:01 -0400584 xml_snippet = load_xml(x='%s/manifest/bliss.xml' % base_path)
Michael Bestas19dc3352018-02-03 20:24:00 +0200585 if xml_snippet is not None:
Eric Park3b19f0b2020-04-11 07:53:05 -0400586 xml_files = (xml_android, xml_snippet)
Michael Bestas687679f2016-12-07 23:20:12 +0200587 else:
Eric Park3b19f0b2020-04-11 07:53:05 -0400588 xml_files = (xml_android)
Michael Bestas687679f2016-12-07 23:20:12 +0200589
Michael Bestas2f8c4a52015-08-05 21:33:50 +0300590 if args.config:
Michael Bestas03bc7052016-03-12 03:19:10 +0200591 files = ['%s/config/%s' % (_DIR, args.config)]
Michael Bestas2f8c4a52015-08-05 21:33:50 +0300592 else:
Michael Bestas03bc7052016-03-12 03:19:10 +0200593 files = ['%s/config/%s.yaml' % (_DIR, default_branch),
594 '%s/config/%s_aosp.yaml' % (_DIR, default_branch)]
Michael Bestas2f8c4a52015-08-05 21:33:50 +0300595 if not check_files(files):
Anthony Kingb8607632015-05-01 22:06:37 +0300596 sys.exit(1)
597
Michael Bestasfd5d1362015-12-18 20:34:32 +0200598 if args.download and args.username is None:
599 print('Argument -u/--username is required for translations download')
600 sys.exit(1)
601
602 if args.upload_sources:
603 upload_sources_crowdin(default_branch, args.config)
604 if args.upload_translations:
605 upload_translations_crowdin(default_branch, args.config)
606 if args.download:
Michael Bestas687679f2016-12-07 23:20:12 +0200607 download_crowdin(base_path, default_branch, xml_files,
Michael Bestas80b22ef2018-11-14 23:12:33 +0200608 args.username, args.config)
Tom Powell44256852016-07-06 15:23:25 -0700609
610 if _COMMITS_CREATED:
611 print('\nDone!')
612 sys.exit(0)
Tom Powellf42586f2016-07-11 11:02:54 -0700613 else:
Tom Powell44256852016-07-06 15:23:25 -0700614 print('\nNothing to commit')
615 sys.exit(-1)
Anthony Kingb8607632015-05-01 22:06:37 +0300616
617if __name__ == '__main__':
618 main()