blob: f64e1d48a679fd4d83b1c5d4ff26a1117d95ea09 [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
Abhisek Devkotab78def42016-12-27 13:06:52 -08006# directly to LineageOS' 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
Marco Brohetcb5cdb42014-07-11 22:41:53 +020010#
11# Licensed under the Apache License, Version 2.0 (the "License");
12# you may not use this file except in compliance with the License.
13# You may obtain a copy of the License at
14#
15# http://www.apache.org/licenses/LICENSE-2.0
16#
17# Unless required by applicable law or agreed to in writing, software
18# distributed under the License is distributed on an "AS IS" BASIS,
19# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20# See the License for the specific language governing permissions and
21# limitations under the License.
22
Anthony Kingb8607632015-05-01 22:06:37 +030023# ################################# IMPORTS ################################## #
24
25from __future__ import print_function
Marco Brohet6b6b4e52014-07-20 00:05:16 +020026
27import argparse
Michael W6e0a7032019-02-27 17:04:16 +010028import json
Marco Brohetcb5cdb42014-07-11 22:41:53 +020029import git
30import os
Michael Wbfa2f952019-03-10 19:53:10 +010031import re
Michael Wb26b8662019-08-10 23:26:59 +020032import shutil
Marco Brohetcb5cdb42014-07-11 22:41:53 +020033import subprocess
34import sys
Michael W1bb2f922019-02-27 17:46:28 +010035import yaml
Anthony Kingb8607632015-05-01 22:06:37 +030036
Michael W2ae05622019-02-28 15:27:22 +010037from lxml import etree
Michael We3af0fc2020-01-19 12:51:55 +010038from signal import signal, SIGINT
Marco Brohetcb5cdb42014-07-11 22:41:53 +020039
Anthony Kingd0d56cf2015-06-05 10:48:38 +010040# ################################# GLOBALS ################################## #
41
42_DIR = os.path.dirname(os.path.realpath(__file__))
Tom Powell44256852016-07-06 15:23:25 -070043_COMMITS_CREATED = False
Anthony Kingd0d56cf2015-06-05 10:48:38 +010044
Anthony Kingb8607632015-05-01 22:06:37 +030045# ################################ FUNCTIONS ################################# #
46
47
48def run_subprocess(cmd, silent=False):
49 p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
50 universal_newlines=True)
51 comm = p.communicate()
52 exit_code = p.returncode
53 if exit_code != 0 and not silent:
54 print("There was an error running the subprocess.\n"
55 "cmd: %s\n"
56 "exit code: %d\n"
57 "stdout: %s\n"
58 "stderr: %s" % (cmd, exit_code, comm[0], comm[1]),
59 file=sys.stderr)
60 return comm, exit_code
61
Marco Brohet6b6b4e52014-07-20 00:05:16 +020062
Michael W2ae05622019-02-28 15:27:22 +010063def add_target_paths(config_files, repo, base_path, project_path):
Michael W1bb2f922019-02-27 17:46:28 +010064 # Add or remove the files given in the config files to the commit
65 count = 0
66 file_paths = []
67 for f in config_files:
68 fh = open(f, "r")
69 try:
Michael W6633d752020-02-02 13:04:39 +010070 config = yaml.safe_load(fh)
Michael W1bb2f922019-02-27 17:46:28 +010071 for tf in config['files']:
72 if project_path in tf['source']:
73 target_path = tf['translation']
74 lang_codes = tf['languages_mapping']['android_code']
75 for l in lang_codes:
76 lpath = get_target_path(tf['translation'], tf['source'],
77 lang_codes[l], project_path)
78 file_paths.append(lpath)
79 except yaml.YAMLError as e:
80 print(e, '\n Could not parse YAML.')
81 exit()
82 fh.close()
83
Michael W2ae05622019-02-28 15:27:22 +010084 # Strip all comments
85 for f in file_paths:
Michael Wb26b8662019-08-10 23:26:59 +020086 clean_xml_file(base_path, project_path, f, repo)
Michael W2ae05622019-02-28 15:27:22 +010087
88 # Modified and untracked files
89 modified = repo.git.ls_files(m=True, o=True)
Michael W1bb2f922019-02-27 17:46:28 +010090 for m in modified.split('\n'):
91 if m in file_paths:
92 repo.git.add(m)
93 count += 1
94
95 deleted = repo.git.ls_files(d=True)
96 for d in deleted.split('\n'):
97 if d in file_paths:
98 repo.git.rm(d)
99 count += 1
100
101 return count
102
103
104def split_path(path):
105 # Split the given string to path and filename
106 if '/' in path:
107 original_file_name = path[1:][path.rfind("/"):]
108 original_path = path[:path.rfind("/")]
109 else:
110 original_file_name = path
111 original_path = ''
112
113 return original_path, original_file_name
114
115
116def get_target_path(pattern, source, lang, project_path):
117 # Make strings like '/%original_path%-%android_code%/%original_file_name%' valid file paths
118 # based on the source string's path
119 original_path, original_file_name = split_path(source)
120
121 target_path = pattern #.lstrip('/')
122 target_path = target_path.replace('%original_path%', original_path)
123 target_path = target_path.replace('%android_code%', lang)
124 target_path = target_path.replace('%original_file_name%', original_file_name)
125 target_path = target_path.replace(project_path, '')
126 target_path = target_path.lstrip('/')
127 return target_path
128
129
Michael Wb26b8662019-08-10 23:26:59 +0200130def clean_xml_file(base_path, project_path, filename, repo):
Michael W2ae05622019-02-28 15:27:22 +0100131 path = base_path + '/' + project_path + '/' + filename
132
133 # We don't want to create every file, just work with those already existing
134 if not os.path.isfile(path):
135 return
136
137 try:
138 fh = open(path, 'r+')
139 except:
140 print('Something went wrong while opening file %s' % (path))
141 return
142
143 XML = fh.read()
Michael Wb26b8662019-08-10 23:26:59 +0200144 try:
145 tree = etree.fromstring(XML)
146 except etree.XMLSyntaxError as err:
147 print('%s: XML Error: %s' % (filename, err.error_log))
148 filename, ext = os.path.splitext(path)
149 if ext == '.xml':
150 reset_file(path, repo)
151 return
Michael W2ae05622019-02-28 15:27:22 +0100152
Michael Wb1587982019-06-19 15:29:24 +0200153 # Remove strings with 'product=*' attribute but no 'product=default'
154 # This will ensure aapt2 will not throw an error when building these
Michael Wba72bd52020-03-28 20:31:35 +0100155 alreadyRemoved = []
Michael Wb1587982019-06-19 15:29:24 +0200156 productStrings = tree.xpath("//string[@product]")
157 for ps in productStrings:
Michael Wba72bd52020-03-28 20:31:35 +0100158 # if we already removed the items, don't process them
159 if ps in alreadyRemoved:
160 continue
Michael Wb1587982019-06-19 15:29:24 +0200161 stringName = ps.get('name')
162 stringsWithSameName = tree.xpath("//string[@name='{0}']"
163 .format(stringName))
164
165 # We want to find strings with product='default' or no product attribute at all
166 hasProductDefault = False
167 for string in stringsWithSameName:
168 product = string.get('product')
169 if product is None or product == 'default':
170 hasProductDefault = True
171 break
172
173 # Every occurance of the string has to be removed when no string with the same name and
174 # 'product=default' (or no product attribute) was found
175 if not hasProductDefault:
176 print("{0}: Found string '{1}' with missing 'product=default' attribute"
177 .format(path, stringName))
178 for string in stringsWithSameName:
179 tree.remove(string)
Michael Wba72bd52020-03-28 20:31:35 +0100180 alreadyRemoved.append(string)
Michael Wb1587982019-06-19 15:29:24 +0200181
Michael W2ae05622019-02-28 15:27:22 +0100182 header = ''
183 comments = tree.xpath('//comment()')
184 for c in comments:
185 p = c.getparent()
186 if p is None:
187 # Keep all comments in header
188 header += str(c).replace('\\n', '\n').replace('\\t', '\t') + '\n'
189 continue
190 p.remove(c)
191
192 content = ''
193
194 # Take the original xml declaration and prepend it
195 declaration = XML.split('\n')[0]
196 if '<?' in declaration:
197 content = declaration + '\n'
198
199 content += etree.tostring(tree, pretty_print=True, encoding="utf-8", xml_declaration=False)
200
201 if header != '':
202 content = content.replace('?>\n', '?>\n' + header)
203
204 # Sometimes spaces are added, we don't want them
205 content = re.sub("[ ]*<\/resources>", "</resources>", content)
206
207 # Overwrite file with content stripped by all comments
208 fh.seek(0)
209 fh.write(content)
210 fh.truncate()
211 fh.close()
212
213 # Remove files which don't have any translated strings
Michael Wed3af932019-06-19 22:41:09 +0200214 contentList = list(tree)
215 if len(contentList) == 0:
216 print('Removing ' + path)
217 os.remove(path)
Michael W2ae05622019-02-28 15:27:22 +0100218
Michael Wb26b8662019-08-10 23:26:59 +0200219
220# For files we can't process due to errors, create a backup
221# and checkout the file to get it back to the previous state
222def reset_file(filepath, repo):
223 backupFile = None
224 parts = filepath.split("/")
225 found = False
226 for s in parts:
227 curPart = s
228 if not found and s.startswith("res"):
229 curPart = s + "_backup"
230 found = True
231 if backupFile is None:
232 backupFile = curPart
233 else:
234 backupFile = backupFile + '/' + curPart
235
236 path, filename = os.path.split(backupFile)
237 if not os.path.exists(path):
238 os.makedirs(path)
239 if os.path.exists(backupFile):
240 i = 1
241 while os.path.exists(backupFile + str(i)):
242 i+=1
243 backupFile = backupFile + str(i)
244 shutil.copy(filepath, backupFile)
245 repo.git.checkout(filepath)
246
247
Michael W1bb2f922019-02-27 17:46:28 +0100248def push_as_commit(config_files, base_path, path, name, branch, username):
Michael We3af0fc2020-01-19 12:51:55 +0100249 print('Committing %s on branch %s: ' % (name, branch), end='')
Marco Brohetcb5cdb42014-07-11 22:41:53 +0200250
251 # Get path
Michael W1bb2f922019-02-27 17:46:28 +0100252 project_path = path
Michael Bestas118fcaf2015-06-04 23:02:20 +0300253 path = os.path.join(base_path, path)
Anthony Kingb8607632015-05-01 22:06:37 +0300254 if not path.endswith('.git'):
255 path = os.path.join(path, '.git')
Marco Brohetcb5cdb42014-07-11 22:41:53 +0200256
Marco Brohet6b6b4e52014-07-20 00:05:16 +0200257 # Create repo object
Marco Brohetcb5cdb42014-07-11 22:41:53 +0200258 repo = git.Repo(path)
Marco Brohet6b6b4e52014-07-20 00:05:16 +0200259
Marco Brohet6b6b4e52014-07-20 00:05:16 +0200260 # Add all files to commit
Michael W2ae05622019-02-28 15:27:22 +0100261 count = add_target_paths(config_files, repo, base_path, project_path)
Michael W1bb2f922019-02-27 17:46:28 +0100262
263 if count == 0:
264 print('Nothing to commit')
265 return
Marco Brohet6b6b4e52014-07-20 00:05:16 +0200266
267 # Create commit; if it fails, probably empty so skipping
Marco Brohetcb5cdb42014-07-11 22:41:53 +0200268 try:
Michael Bestas80b22ef2018-11-14 23:12:33 +0200269 repo.git.commit(m='Automatic translation import')
Marco Brohetcb5cdb42014-07-11 22:41:53 +0200270 except:
Michael We3af0fc2020-01-19 12:51:55 +0100271 print('Failed, probably empty: skipping', file=sys.stderr)
Marco Brohetcb5cdb42014-07-11 22:41:53 +0200272 return
Marco Brohet6b6b4e52014-07-20 00:05:16 +0200273
274 # Push commit
Michael Bestasf96f67b2014-10-21 00:43:37 +0300275 try:
Abhisek Devkotab78def42016-12-27 13:06:52 -0800276 repo.git.push('ssh://%s@review.lineageos.org:29418/%s' % (username, name),
Anthony Kingb8607632015-05-01 22:06:37 +0300277 'HEAD:refs/for/%s%%topic=translation' % branch)
Michael We3af0fc2020-01-19 12:51:55 +0100278 print('Success')
Michael Bestasf96f67b2014-10-21 00:43:37 +0300279 except:
Michael We3af0fc2020-01-19 12:51:55 +0100280 print('Failed', file=sys.stderr)
Marco Brohetcb5cdb42014-07-11 22:41:53 +0200281
Tom Powell44256852016-07-06 15:23:25 -0700282 _COMMITS_CREATED = True
283
Anthony Kingb8607632015-05-01 22:06:37 +0300284
Michael Wd13658a2019-01-13 14:05:37 +0100285def submit_gerrit(branch, username):
286 # Find all open translation changes
287 cmd = ['ssh', '-p', '29418',
288 '{}@review.lineageos.org'.format(username),
289 'gerrit', 'query',
290 'status:open',
291 'branch:{}'.format(branch),
292 'message:"Automatic translation import"',
293 'topic:translation',
Michael W6e0a7032019-02-27 17:04:16 +0100294 '--current-patch-set',
295 '--format=JSON']
296 commits = 0
Michael Wd13658a2019-01-13 14:05:37 +0100297 msg, code = run_subprocess(cmd)
298 if code != 0:
299 print('Failed: {0}'.format(msg[1]))
300 return
301
Michael W6e0a7032019-02-27 17:04:16 +0100302 # Each line is one valid JSON object, except the last one, which is empty
303 for line in msg[0].strip('\n').split('\n'):
304 js = json.loads(line)
305 # We get valid JSON, but not every result line is one we want
306 if not 'currentPatchSet' in js or not 'revision' in js['currentPatchSet']:
307 continue
Michael Wd13658a2019-01-13 14:05:37 +0100308 # Add Code-Review +2 and Verified+1 labels and submit
309 cmd = ['ssh', '-p', '29418',
310 '{}@review.lineageos.org'.format(username),
311 'gerrit', 'review',
312 '--verified +1',
313 '--code-review +2',
Michael W6e0a7032019-02-27 17:04:16 +0100314 '--submit', js['currentPatchSet']['revision']]
Michael Wd13658a2019-01-13 14:05:37 +0100315 msg, code = run_subprocess(cmd, True)
Michael We3af0fc2020-01-19 12:51:55 +0100316 print('Submitting commit %s: ' % js[url], end='')
Michael Wd13658a2019-01-13 14:05:37 +0100317 if code != 0:
318 errorText = msg[1].replace('\n\n', '; ').replace('\n', '')
Michael We3af0fc2020-01-19 12:51:55 +0100319 print('Failed: %s' % errorText)
Michael Wd13658a2019-01-13 14:05:37 +0100320 else:
Michael We3af0fc2020-01-19 12:51:55 +0100321 print('Success')
Michael W6e0a7032019-02-27 17:04:16 +0100322
323 commits += 1
324
325 if commits == 0:
326 print("Nothing to submit!")
327 return
Michael Wd13658a2019-01-13 14:05:37 +0100328
329
Anthony Kingb8607632015-05-01 22:06:37 +0300330def check_run(cmd):
Michael Bestas97677e12015-02-08 13:11:59 +0200331 p = subprocess.Popen(cmd, stdout=sys.stdout, stderr=sys.stderr)
332 ret = p.wait()
333 if ret != 0:
Anthony Kingb8607632015-05-01 22:06:37 +0300334 print('Failed to run cmd: %s' % ' '.join(cmd), file=sys.stderr)
Michael Bestas97677e12015-02-08 13:11:59 +0200335 sys.exit(ret)
336
Marco Brohet6b6b4e52014-07-20 00:05:16 +0200337
Michael Bestas118fcaf2015-06-04 23:02:20 +0300338def find_xml(base_path):
339 for dp, dn, file_names in os.walk(base_path):
Anthony Kingb8607632015-05-01 22:06:37 +0300340 for f in file_names:
341 if os.path.splitext(f)[1] == '.xml':
342 yield os.path.join(dp, f)
Marco Brohet6b6b4e52014-07-20 00:05:16 +0200343
Anthony Kingb8607632015-05-01 22:06:37 +0300344# ############################################################################ #
Marco Brohet6b6b4e52014-07-20 00:05:16 +0200345
Michael Bestas6b6db122015-02-08 13:22:22 +0200346
Anthony Kingb8607632015-05-01 22:06:37 +0300347def parse_args():
348 parser = argparse.ArgumentParser(
Abhisek Devkotab78def42016-12-27 13:06:52 -0800349 description="Synchronising LineageOS' translations with Crowdin")
Michael Bestasfd5d1362015-12-18 20:34:32 +0200350 parser.add_argument('-u', '--username', help='Gerrit username')
Abhisek Devkotab78def42016-12-27 13:06:52 -0800351 parser.add_argument('-b', '--branch', help='LineageOS branch',
Anthony Kingb8607632015-05-01 22:06:37 +0300352 required=True)
Michael Bestas2f8c4a52015-08-05 21:33:50 +0300353 parser.add_argument('-c', '--config', help='Custom yaml config')
Michael Bestasfd5d1362015-12-18 20:34:32 +0200354 parser.add_argument('--upload-sources', action='store_true',
355 help='Upload sources to Crowdin')
356 parser.add_argument('--upload-translations', action='store_true',
357 help='Upload translations to Crowdin')
358 parser.add_argument('--download', action='store_true',
359 help='Download translations from Crowdin')
Michael Wd13658a2019-01-13 14:05:37 +0100360 parser.add_argument('-s', '--submit', action='store_true',
361 help='Merge open translation commits')
Anthony Kingb8607632015-05-01 22:06:37 +0300362 return parser.parse_args()
Michael Bestas6b6db122015-02-08 13:22:22 +0200363
Anthony Kingb8607632015-05-01 22:06:37 +0300364# ################################# PREPARE ################################## #
Marco Brohet6b6b4e52014-07-20 00:05:16 +0200365
Anthony Kingb8607632015-05-01 22:06:37 +0300366
367def check_dependencies():
Michael Bestaseb4629a2018-11-14 23:03:18 +0200368 # Check for Java version of crowdin
369 cmd = ['dpkg-query', '-W', 'crowdin']
Anthony Kingb8607632015-05-01 22:06:37 +0300370 if run_subprocess(cmd, silent=True)[1] != 0:
Michael Bestaseb4629a2018-11-14 23:03:18 +0200371 print('You have not installed crowdin.', file=sys.stderr)
Anthony Kingb8607632015-05-01 22:06:37 +0300372 return False
Anthony Kingb8607632015-05-01 22:06:37 +0300373 return True
Marco Brohetcb5cdb42014-07-11 22:41:53 +0200374
Marco Brohetcb5cdb42014-07-11 22:41:53 +0200375
Michael Bestas118fcaf2015-06-04 23:02:20 +0300376def load_xml(x):
Anthony Kingb8607632015-05-01 22:06:37 +0300377 try:
Michael Wda610ba2020-03-22 18:38:19 +0100378 return etree.parse(x)
379 except etree.XMLSyntaxError:
380 print('Malformed %s.' % x, file=sys.stderr)
Anthony Kingb8607632015-05-01 22:06:37 +0300381 return None
382 except Exception:
Michael Wda610ba2020-03-22 18:38:19 +0100383 print('You have no %s.' % x, file=sys.stderr)
Anthony Kingb8607632015-05-01 22:06:37 +0300384 return None
Marco Brohet6b6b4e52014-07-20 00:05:16 +0200385
Michael Bestas4b26c4e2014-10-23 23:21:59 +0300386
Michael Bestas2f8c4a52015-08-05 21:33:50 +0300387def check_files(files):
Anthony Kingb8607632015-05-01 22:06:37 +0300388 for f in files:
389 if not os.path.isfile(f):
390 print('You have no %s.' % f, file=sys.stderr)
391 return False
Anthony Kingb8607632015-05-01 22:06:37 +0300392 return True
Michael Bestas4b26c4e2014-10-23 23:21:59 +0300393
Anthony Kingb8607632015-05-01 22:06:37 +0300394# ################################### MAIN ################################### #
Michael Bestas4b26c4e2014-10-23 23:21:59 +0300395
Michael Bestas4b26c4e2014-10-23 23:21:59 +0300396
Michael Bestasfd5d1362015-12-18 20:34:32 +0200397def upload_sources_crowdin(branch, config):
Michael Bestas2f8c4a52015-08-05 21:33:50 +0300398 if config:
Michael Bestasfd5d1362015-12-18 20:34:32 +0200399 print('\nUploading sources to Crowdin (custom config)')
Michael Bestaseb4629a2018-11-14 23:03:18 +0200400 check_run(['crowdin',
Michael Bestas03bc7052016-03-12 03:19:10 +0200401 '--config=%s/config/%s' % (_DIR, config),
Michael Bestas44fbb352015-12-17 02:01:42 +0200402 'upload', 'sources', '--branch=%s' % branch])
Michael Bestas2f8c4a52015-08-05 21:33:50 +0300403 else:
Michael Bestasfd5d1362015-12-18 20:34:32 +0200404 print('\nUploading sources to Crowdin (AOSP supported languages)')
Michael Bestaseb4629a2018-11-14 23:03:18 +0200405 check_run(['crowdin',
Michael Bestas03bc7052016-03-12 03:19:10 +0200406 '--config=%s/config/%s.yaml' % (_DIR, branch),
Michael Bestas44fbb352015-12-17 02:01:42 +0200407 'upload', 'sources', '--branch=%s' % branch])
Anthony King69a95382015-02-08 18:44:10 +0000408
Michael Bestasfd5d1362015-12-18 20:34:32 +0200409 print('\nUploading sources to Crowdin (non-AOSP supported languages)')
Michael Bestaseb4629a2018-11-14 23:03:18 +0200410 check_run(['crowdin',
Michael Bestas03bc7052016-03-12 03:19:10 +0200411 '--config=%s/config/%s_aosp.yaml' % (_DIR, branch),
Michael Bestas44fbb352015-12-17 02:01:42 +0200412 'upload', 'sources', '--branch=%s' % branch])
Anthony Kingb8607632015-05-01 22:06:37 +0300413
414
Michael Bestasfd5d1362015-12-18 20:34:32 +0200415def upload_translations_crowdin(branch, config):
Michael Bestas2f8c4a52015-08-05 21:33:50 +0300416 if config:
Michael Bestasfd5d1362015-12-18 20:34:32 +0200417 print('\nUploading translations to Crowdin (custom config)')
Michael Bestaseb4629a2018-11-14 23:03:18 +0200418 check_run(['crowdin',
Michael Bestas03bc7052016-03-12 03:19:10 +0200419 '--config=%s/config/%s' % (_DIR, config),
Michael Bestasfd5d1362015-12-18 20:34:32 +0200420 'upload', 'translations', '--branch=%s' % branch,
421 '--no-import-duplicates', '--import-eq-suggestions',
422 '--auto-approve-imported'])
423 else:
424 print('\nUploading translations to Crowdin '
425 '(AOSP supported languages)')
Michael Bestaseb4629a2018-11-14 23:03:18 +0200426 check_run(['crowdin',
Michael Bestas03bc7052016-03-12 03:19:10 +0200427 '--config=%s/config/%s.yaml' % (_DIR, branch),
Michael Bestasfd5d1362015-12-18 20:34:32 +0200428 'upload', 'translations', '--branch=%s' % branch,
429 '--no-import-duplicates', '--import-eq-suggestions',
430 '--auto-approve-imported'])
431
432 print('\nUploading translations to Crowdin '
433 '(non-AOSP supported languages)')
Michael Bestaseb4629a2018-11-14 23:03:18 +0200434 check_run(['crowdin',
Michael Bestas03bc7052016-03-12 03:19:10 +0200435 '--config=%s/config/%s_aosp.yaml' % (_DIR, branch),
Michael Bestasfd5d1362015-12-18 20:34:32 +0200436 'upload', 'translations', '--branch=%s' % branch,
437 '--no-import-duplicates', '--import-eq-suggestions',
438 '--auto-approve-imported'])
439
440
Michael Bestas80b22ef2018-11-14 23:12:33 +0200441def download_crowdin(base_path, branch, xml, username, config):
Michael Bestasfd5d1362015-12-18 20:34:32 +0200442 if config:
443 print('\nDownloading translations from Crowdin (custom config)')
Michael Bestaseb4629a2018-11-14 23:03:18 +0200444 check_run(['crowdin',
Michael Bestas03bc7052016-03-12 03:19:10 +0200445 '--config=%s/config/%s' % (_DIR, config),
Michael Bestas44fbb352015-12-17 02:01:42 +0200446 'download', '--branch=%s' % branch])
Michael Bestas2f8c4a52015-08-05 21:33:50 +0300447 else:
Michael Bestasfd5d1362015-12-18 20:34:32 +0200448 print('\nDownloading translations from Crowdin '
449 '(AOSP supported languages)')
Michael Bestaseb4629a2018-11-14 23:03:18 +0200450 check_run(['crowdin',
Michael Bestas03bc7052016-03-12 03:19:10 +0200451 '--config=%s/config/%s.yaml' % (_DIR, branch),
Michael Bestas44fbb352015-12-17 02:01:42 +0200452 'download', '--branch=%s' % branch])
Michael Bestas50579d22014-08-09 17:49:14 +0300453
Michael Bestasfd5d1362015-12-18 20:34:32 +0200454 print('\nDownloading translations from Crowdin '
Michael Bestas2f8c4a52015-08-05 21:33:50 +0300455 '(non-AOSP supported languages)')
Michael Bestaseb4629a2018-11-14 23:03:18 +0200456 check_run(['crowdin',
Michael Bestas03bc7052016-03-12 03:19:10 +0200457 '--config=%s/config/%s_aosp.yaml' % (_DIR, branch),
Michael Bestas44fbb352015-12-17 02:01:42 +0200458 'download', '--branch=%s' % branch])
Marco Brohetcb5cdb42014-07-11 22:41:53 +0200459
Michael Bestas99f5fce2015-06-04 22:07:51 +0300460 print('\nCreating a list of pushable translations')
Michael Bestas919053f2014-10-20 23:30:54 +0300461 # Get all files that Crowdin pushed
Anthony Kingb8607632015-05-01 22:06:37 +0300462 paths = []
Michael Bestas2f8c4a52015-08-05 21:33:50 +0300463 if config:
Michael Bestas03bc7052016-03-12 03:19:10 +0200464 files = ['%s/config/%s' % (_DIR, config)]
Michael Bestas2f8c4a52015-08-05 21:33:50 +0300465 else:
Michael Bestas03bc7052016-03-12 03:19:10 +0200466 files = ['%s/config/%s.yaml' % (_DIR, branch),
467 '%s/config/%s_aosp.yaml' % (_DIR, branch)]
Michael Bestas6c327e62015-05-02 01:58:01 +0300468 for c in files:
Michael Bestaseb4629a2018-11-14 23:03:18 +0200469 cmd = ['crowdin', '--config=%s' % c, 'list', 'project',
Michael Bestas44fbb352015-12-17 02:01:42 +0200470 '--branch=%s' % branch]
Anthony Kingb8607632015-05-01 22:06:37 +0300471 comm, ret = run_subprocess(cmd)
472 if ret != 0:
473 sys.exit(ret)
474 for p in str(comm[0]).split("\n"):
475 paths.append(p.replace('/%s' % branch, ''))
Michael Bestas50579d22014-08-09 17:49:14 +0300476
Michael Bestas99f5fce2015-06-04 22:07:51 +0300477 print('\nUploading translations to Gerrit')
Michael Wda610ba2020-03-22 18:38:19 +0100478 items = [x for xmlfile in xml for x in xmlfile.findall("//project")]
Michael Bestas919053f2014-10-20 23:30:54 +0300479 all_projects = []
480
Anthony Kingb8607632015-05-01 22:06:37 +0300481 for path in paths:
482 path = path.strip()
Michael Bestas919053f2014-10-20 23:30:54 +0300483 if not path:
484 continue
485
Anthony Kingb8607632015-05-01 22:06:37 +0300486 if "/res" not in path:
487 print('WARNING: Cannot determine project root dir of '
488 '[%s], skipping.' % path)
Anthony King69a95382015-02-08 18:44:10 +0000489 continue
Michael W67f14932019-03-11 09:59:32 +0100490
491 # Usually the project root is everything before /res
492 # but there are special cases where /res is part of the repo name as well
493 parts = path.split("/res")
494 if len(parts) == 2:
495 result = parts[0]
496 elif len(parts) == 3:
497 result = parts[0] + '/res' + parts[1]
498 else:
499 print('WARNING: Splitting the path not successful for [%s], skipping' % path)
500 continue
501
502 result = result.strip('/')
Anthony Kingb8607632015-05-01 22:06:37 +0300503 if result == path.strip('/'):
504 print('WARNING: Cannot determine project root dir of '
505 '[%s], skipping.' % path)
506 continue
Marco Brohet6b6b4e52014-07-20 00:05:16 +0200507
Michael Bestasc899b8c2015-03-03 00:53:19 +0200508 if result in all_projects:
Michael Bestasc899b8c2015-03-03 00:53:19 +0200509 continue
Michael Bestas50579d22014-08-09 17:49:14 +0300510
Anthony Kingb8607632015-05-01 22:06:37 +0300511 # When a project has multiple translatable files, Crowdin will
512 # give duplicates.
513 # We don't want that (useless empty commits), so we save each
514 # project in all_projects and check if it's already in there.
Michael Bestasc899b8c2015-03-03 00:53:19 +0200515 all_projects.append(result)
Anthony King69a95382015-02-08 18:44:10 +0000516
Michael Bestas42e25e32016-03-12 20:18:39 +0200517 # Search android/default.xml or config/%(branch)_extra_packages.xml
Anthony Kingb8607632015-05-01 22:06:37 +0300518 # for the project's name
Michael W1f187762019-03-11 19:38:00 +0100519 resultPath = None
520 resultProject = None
Anthony Kingb8607632015-05-01 22:06:37 +0300521 for project in items:
Michael Wda610ba2020-03-22 18:38:19 +0100522 path = project.get('path')
Anthony Kingb8607632015-05-01 22:06:37 +0300523 if not (result + '/').startswith(path +'/'):
Michael Bestasc899b8c2015-03-03 00:53:19 +0200524 continue
Michael W1f187762019-03-11 19:38:00 +0100525 # We want the longest match, so projects in subfolders of other projects are also
526 # taken into account
527 if resultPath is None or len(path) > len(resultPath):
528 resultPath = path
529 resultProject = project
Anthony King69a95382015-02-08 18:44:10 +0000530
Michael W1f187762019-03-11 19:38:00 +0100531 # Just in case no project was found
532 if resultPath is None:
533 continue
Anthony King69a95382015-02-08 18:44:10 +0000534
Michael W1f187762019-03-11 19:38:00 +0100535 if result != resultPath:
536 if resultPath in all_projects:
537 continue
538 result = resultPath
539 all_projects.append(result)
540
Michael Wda610ba2020-03-22 18:38:19 +0100541 br = resultProject.get('revision') or branch
Michael W1f187762019-03-11 19:38:00 +0100542
543 push_as_commit(files, base_path, result,
Michael Wda610ba2020-03-22 18:38:19 +0100544 resultProject.get('name'), br, username)
Anthony King69a95382015-02-08 18:44:10 +0000545
Anthony King69a95382015-02-08 18:44:10 +0000546
Michael We3af0fc2020-01-19 12:51:55 +0100547def sig_handler(signal_received, frame):
548 print('')
549 print('SIGINT or CTRL-C detected. Exiting gracefully')
550 exit(0)
551
552
Anthony Kingb8607632015-05-01 22:06:37 +0300553def main():
Michael We3af0fc2020-01-19 12:51:55 +0100554 signal(SIGINT, sig_handler)
Anthony Kingb8607632015-05-01 22:06:37 +0300555 args = parse_args()
556 default_branch = args.branch
Michael Bestas118fcaf2015-06-04 23:02:20 +0300557
Michael Wd13658a2019-01-13 14:05:37 +0100558 if args.submit:
559 if args.username is None:
560 print('Argument -u/--username is required for submitting!')
561 sys.exit(1)
562 submit_gerrit(default_branch, args.username)
563 sys.exit(0)
564
Michael Bestaseb4629a2018-11-14 23:03:18 +0200565 base_path_branch_suffix = default_branch.replace('-', '_').replace('.', '_').upper()
566 base_path_env = 'LINEAGE_CROWDIN_BASE_PATH_%s' % base_path_branch_suffix
567 base_path = os.getenv(base_path_env)
Michael Bestas118fcaf2015-06-04 23:02:20 +0300568 if base_path is None:
Anthony Kingd0d56cf2015-06-05 10:48:38 +0100569 cwd = os.getcwd()
Michael Bestaseb4629a2018-11-14 23:03:18 +0200570 print('You have not set %s. Defaulting to %s' % (base_path_env, cwd))
Michael Bestas118fcaf2015-06-04 23:02:20 +0300571 base_path = cwd
Michael Bestas118fcaf2015-06-04 23:02:20 +0300572 if not os.path.isdir(base_path):
Michael Bestaseb4629a2018-11-14 23:03:18 +0200573 print('%s is not a real directory: %s' % (base_path_env, base_path))
Michael Bestas118fcaf2015-06-04 23:02:20 +0300574 sys.exit(1)
Anthony Kingb8607632015-05-01 22:06:37 +0300575
Michael Bestas99f5fce2015-06-04 22:07:51 +0300576 if not check_dependencies():
577 sys.exit(1)
Anthony Kingb8607632015-05-01 22:06:37 +0300578
Michael Bestas118fcaf2015-06-04 23:02:20 +0300579 xml_android = load_xml(x='%s/android/default.xml' % base_path)
Anthony Kingb8607632015-05-01 22:06:37 +0300580 if xml_android is None:
581 sys.exit(1)
582
Michael Bestas42e25e32016-03-12 20:18:39 +0200583 xml_extra = load_xml(x='%s/config/%s_extra_packages.xml'
Anthony Kingd0d56cf2015-06-05 10:48:38 +0100584 % (_DIR, default_branch))
Anthony Kingb8607632015-05-01 22:06:37 +0300585 if xml_extra is None:
586 sys.exit(1)
587
Michael Bestas19dc3352018-02-03 20:24:00 +0200588 xml_snippet = load_xml(x='%s/android/snippets/lineage.xml' % base_path)
589 if xml_snippet is None:
590 xml_snippet = load_xml(x='%s/android/snippets/cm.xml' % base_path)
591 if xml_snippet is None:
592 xml_snippet = load_xml(x='%s/android/snippets/hal_cm_all.xml' % base_path)
593 if xml_snippet is not None:
594 xml_files = (xml_android, xml_snippet, xml_extra)
Michael Bestas687679f2016-12-07 23:20:12 +0200595 else:
596 xml_files = (xml_android, xml_extra)
597
Michael Bestas2f8c4a52015-08-05 21:33:50 +0300598 if args.config:
Michael Bestas03bc7052016-03-12 03:19:10 +0200599 files = ['%s/config/%s' % (_DIR, args.config)]
Michael Bestas2f8c4a52015-08-05 21:33:50 +0300600 else:
Michael Bestas03bc7052016-03-12 03:19:10 +0200601 files = ['%s/config/%s.yaml' % (_DIR, default_branch),
602 '%s/config/%s_aosp.yaml' % (_DIR, default_branch)]
Michael Bestas2f8c4a52015-08-05 21:33:50 +0300603 if not check_files(files):
Anthony Kingb8607632015-05-01 22:06:37 +0300604 sys.exit(1)
605
Michael Bestasfd5d1362015-12-18 20:34:32 +0200606 if args.download and args.username is None:
607 print('Argument -u/--username is required for translations download')
608 sys.exit(1)
609
610 if args.upload_sources:
611 upload_sources_crowdin(default_branch, args.config)
612 if args.upload_translations:
613 upload_translations_crowdin(default_branch, args.config)
614 if args.download:
Michael Bestas687679f2016-12-07 23:20:12 +0200615 download_crowdin(base_path, default_branch, xml_files,
Michael Bestas80b22ef2018-11-14 23:12:33 +0200616 args.username, args.config)
Tom Powell44256852016-07-06 15:23:25 -0700617
618 if _COMMITS_CREATED:
619 print('\nDone!')
620 sys.exit(0)
Tom Powellf42586f2016-07-11 11:02:54 -0700621 else:
Tom Powell44256852016-07-06 15:23:25 -0700622 print('\nNothing to commit')
623 sys.exit(-1)
Anthony Kingb8607632015-05-01 22:06:37 +0300624
625if __name__ == '__main__':
626 main()