blob: d3de7a80a89addee86e53b187bded9d65739f61e [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 +020039from xml.dom import minidom
40
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:
71 config = yaml.load(fh)
72 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:
141 print('Something went wrong while opening file %s' % (path))
142 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
156 productStrings = tree.xpath("//string[@product]")
157 for ps in productStrings:
158 stringName = ps.get('name')
159 stringsWithSameName = tree.xpath("//string[@name='{0}']"
160 .format(stringName))
161
162 # We want to find strings with product='default' or no product attribute at all
163 hasProductDefault = False
164 for string in stringsWithSameName:
165 product = string.get('product')
166 if product is None or product == 'default':
167 hasProductDefault = True
168 break
169
170 # Every occurance of the string has to be removed when no string with the same name and
171 # 'product=default' (or no product attribute) was found
172 if not hasProductDefault:
173 print("{0}: Found string '{1}' with missing 'product=default' attribute"
174 .format(path, stringName))
175 for string in stringsWithSameName:
176 tree.remove(string)
177 productStrings.remove(string)
178
Michael W2ae05622019-02-28 15:27:22 +0100179 header = ''
180 comments = tree.xpath('//comment()')
181 for c in comments:
182 p = c.getparent()
183 if p is None:
184 # Keep all comments in header
185 header += str(c).replace('\\n', '\n').replace('\\t', '\t') + '\n'
186 continue
187 p.remove(c)
188
189 content = ''
190
191 # Take the original xml declaration and prepend it
192 declaration = XML.split('\n')[0]
193 if '<?' in declaration:
194 content = declaration + '\n'
195
196 content += etree.tostring(tree, pretty_print=True, encoding="utf-8", xml_declaration=False)
197
198 if header != '':
199 content = content.replace('?>\n', '?>\n' + header)
200
201 # Sometimes spaces are added, we don't want them
202 content = re.sub("[ ]*<\/resources>", "</resources>", content)
203
204 # Overwrite file with content stripped by all comments
205 fh.seek(0)
206 fh.write(content)
207 fh.truncate()
208 fh.close()
209
210 # Remove files which don't have any translated strings
Michael Wed3af932019-06-19 22:41:09 +0200211 contentList = list(tree)
212 if len(contentList) == 0:
213 print('Removing ' + path)
214 os.remove(path)
Michael W2ae05622019-02-28 15:27:22 +0100215
Michael Wb26b8662019-08-10 23:26:59 +0200216
217# For files we can't process due to errors, create a backup
218# and checkout the file to get it back to the previous state
219def reset_file(filepath, repo):
220 backupFile = None
221 parts = filepath.split("/")
222 found = False
223 for s in parts:
224 curPart = s
225 if not found and s.startswith("res"):
226 curPart = s + "_backup"
227 found = True
228 if backupFile is None:
229 backupFile = curPart
230 else:
231 backupFile = backupFile + '/' + curPart
232
233 path, filename = os.path.split(backupFile)
234 if not os.path.exists(path):
235 os.makedirs(path)
236 if os.path.exists(backupFile):
237 i = 1
238 while os.path.exists(backupFile + str(i)):
239 i+=1
240 backupFile = backupFile + str(i)
241 shutil.copy(filepath, backupFile)
242 repo.git.checkout(filepath)
243
244
Michael W1bb2f922019-02-27 17:46:28 +0100245def push_as_commit(config_files, base_path, path, name, branch, username):
Michael We3af0fc2020-01-19 12:51:55 +0100246 print('Committing %s on branch %s: ' % (name, branch), end='')
Marco Brohetcb5cdb42014-07-11 22:41:53 +0200247
248 # Get path
Michael W1bb2f922019-02-27 17:46:28 +0100249 project_path = path
Michael Bestas118fcaf2015-06-04 23:02:20 +0300250 path = os.path.join(base_path, path)
Anthony Kingb8607632015-05-01 22:06:37 +0300251 if not path.endswith('.git'):
252 path = os.path.join(path, '.git')
Marco Brohetcb5cdb42014-07-11 22:41:53 +0200253
Marco Brohet6b6b4e52014-07-20 00:05:16 +0200254 # Create repo object
Marco Brohetcb5cdb42014-07-11 22:41:53 +0200255 repo = git.Repo(path)
Marco Brohet6b6b4e52014-07-20 00:05:16 +0200256
Marco Brohet6b6b4e52014-07-20 00:05:16 +0200257 # Add all files to commit
Michael W2ae05622019-02-28 15:27:22 +0100258 count = add_target_paths(config_files, repo, base_path, project_path)
Michael W1bb2f922019-02-27 17:46:28 +0100259
260 if count == 0:
261 print('Nothing to commit')
262 return
Marco Brohet6b6b4e52014-07-20 00:05:16 +0200263
264 # Create commit; if it fails, probably empty so skipping
Marco Brohetcb5cdb42014-07-11 22:41:53 +0200265 try:
Michael Bestas80b22ef2018-11-14 23:12:33 +0200266 repo.git.commit(m='Automatic translation import')
Marco Brohetcb5cdb42014-07-11 22:41:53 +0200267 except:
Michael We3af0fc2020-01-19 12:51:55 +0100268 print('Failed, probably empty: skipping', file=sys.stderr)
Marco Brohetcb5cdb42014-07-11 22:41:53 +0200269 return
Marco Brohet6b6b4e52014-07-20 00:05:16 +0200270
271 # Push commit
Michael Bestasf96f67b2014-10-21 00:43:37 +0300272 try:
Abhisek Devkotab78def42016-12-27 13:06:52 -0800273 repo.git.push('ssh://%s@review.lineageos.org:29418/%s' % (username, name),
Anthony Kingb8607632015-05-01 22:06:37 +0300274 'HEAD:refs/for/%s%%topic=translation' % branch)
Michael We3af0fc2020-01-19 12:51:55 +0100275 print('Success')
Michael Bestasf96f67b2014-10-21 00:43:37 +0300276 except:
Michael We3af0fc2020-01-19 12:51:55 +0100277 print('Failed', file=sys.stderr)
Marco Brohetcb5cdb42014-07-11 22:41:53 +0200278
Tom Powell44256852016-07-06 15:23:25 -0700279 _COMMITS_CREATED = True
280
Anthony Kingb8607632015-05-01 22:06:37 +0300281
Michael Wd13658a2019-01-13 14:05:37 +0100282def submit_gerrit(branch, username):
283 # Find all open translation changes
284 cmd = ['ssh', '-p', '29418',
285 '{}@review.lineageos.org'.format(username),
286 'gerrit', 'query',
287 'status:open',
288 'branch:{}'.format(branch),
289 'message:"Automatic translation import"',
290 'topic:translation',
Michael W6e0a7032019-02-27 17:04:16 +0100291 '--current-patch-set',
292 '--format=JSON']
293 commits = 0
Michael Wd13658a2019-01-13 14:05:37 +0100294 msg, code = run_subprocess(cmd)
295 if code != 0:
296 print('Failed: {0}'.format(msg[1]))
297 return
298
Michael W6e0a7032019-02-27 17:04:16 +0100299 # Each line is one valid JSON object, except the last one, which is empty
300 for line in msg[0].strip('\n').split('\n'):
301 js = json.loads(line)
302 # We get valid JSON, but not every result line is one we want
303 if not 'currentPatchSet' in js or not 'revision' in js['currentPatchSet']:
304 continue
Michael Wd13658a2019-01-13 14:05:37 +0100305 # Add Code-Review +2 and Verified+1 labels and submit
306 cmd = ['ssh', '-p', '29418',
307 '{}@review.lineageos.org'.format(username),
308 'gerrit', 'review',
309 '--verified +1',
310 '--code-review +2',
Michael W6e0a7032019-02-27 17:04:16 +0100311 '--submit', js['currentPatchSet']['revision']]
Michael Wd13658a2019-01-13 14:05:37 +0100312 msg, code = run_subprocess(cmd, True)
Michael We3af0fc2020-01-19 12:51:55 +0100313 print('Submitting commit %s: ' % js[url], end='')
Michael Wd13658a2019-01-13 14:05:37 +0100314 if code != 0:
315 errorText = msg[1].replace('\n\n', '; ').replace('\n', '')
Michael We3af0fc2020-01-19 12:51:55 +0100316 print('Failed: %s' % errorText)
Michael Wd13658a2019-01-13 14:05:37 +0100317 else:
Michael We3af0fc2020-01-19 12:51:55 +0100318 print('Success')
Michael W6e0a7032019-02-27 17:04:16 +0100319
320 commits += 1
321
322 if commits == 0:
323 print("Nothing to submit!")
324 return
Michael Wd13658a2019-01-13 14:05:37 +0100325
326
Anthony Kingb8607632015-05-01 22:06:37 +0300327def check_run(cmd):
Michael Bestas97677e12015-02-08 13:11:59 +0200328 p = subprocess.Popen(cmd, stdout=sys.stdout, stderr=sys.stderr)
329 ret = p.wait()
330 if ret != 0:
Anthony Kingb8607632015-05-01 22:06:37 +0300331 print('Failed to run cmd: %s' % ' '.join(cmd), file=sys.stderr)
Michael Bestas97677e12015-02-08 13:11:59 +0200332 sys.exit(ret)
333
Marco Brohet6b6b4e52014-07-20 00:05:16 +0200334
Michael Bestas118fcaf2015-06-04 23:02:20 +0300335def find_xml(base_path):
336 for dp, dn, file_names in os.walk(base_path):
Anthony Kingb8607632015-05-01 22:06:37 +0300337 for f in file_names:
338 if os.path.splitext(f)[1] == '.xml':
339 yield os.path.join(dp, f)
Marco Brohet6b6b4e52014-07-20 00:05:16 +0200340
Anthony Kingb8607632015-05-01 22:06:37 +0300341# ############################################################################ #
Marco Brohet6b6b4e52014-07-20 00:05:16 +0200342
Michael Bestas6b6db122015-02-08 13:22:22 +0200343
Anthony Kingb8607632015-05-01 22:06:37 +0300344def parse_args():
345 parser = argparse.ArgumentParser(
Abhisek Devkotab78def42016-12-27 13:06:52 -0800346 description="Synchronising LineageOS' translations with Crowdin")
Michael Bestasfd5d1362015-12-18 20:34:32 +0200347 parser.add_argument('-u', '--username', help='Gerrit username')
Abhisek Devkotab78def42016-12-27 13:06:52 -0800348 parser.add_argument('-b', '--branch', help='LineageOS branch',
Anthony Kingb8607632015-05-01 22:06:37 +0300349 required=True)
Michael Bestas2f8c4a52015-08-05 21:33:50 +0300350 parser.add_argument('-c', '--config', help='Custom yaml config')
Michael Bestasfd5d1362015-12-18 20:34:32 +0200351 parser.add_argument('--upload-sources', action='store_true',
352 help='Upload sources to Crowdin')
353 parser.add_argument('--upload-translations', action='store_true',
354 help='Upload translations to Crowdin')
355 parser.add_argument('--download', action='store_true',
356 help='Download translations from Crowdin')
Michael Wd13658a2019-01-13 14:05:37 +0100357 parser.add_argument('-s', '--submit', action='store_true',
358 help='Merge open translation commits')
Anthony Kingb8607632015-05-01 22:06:37 +0300359 return parser.parse_args()
Michael Bestas6b6db122015-02-08 13:22:22 +0200360
Anthony Kingb8607632015-05-01 22:06:37 +0300361# ################################# PREPARE ################################## #
Marco Brohet6b6b4e52014-07-20 00:05:16 +0200362
Anthony Kingb8607632015-05-01 22:06:37 +0300363
364def check_dependencies():
Michael Bestaseb4629a2018-11-14 23:03:18 +0200365 # Check for Java version of crowdin
366 cmd = ['dpkg-query', '-W', 'crowdin']
Anthony Kingb8607632015-05-01 22:06:37 +0300367 if run_subprocess(cmd, silent=True)[1] != 0:
Michael Bestaseb4629a2018-11-14 23:03:18 +0200368 print('You have not installed crowdin.', file=sys.stderr)
Anthony Kingb8607632015-05-01 22:06:37 +0300369 return False
Anthony Kingb8607632015-05-01 22:06:37 +0300370 return True
Marco Brohetcb5cdb42014-07-11 22:41:53 +0200371
Marco Brohetcb5cdb42014-07-11 22:41:53 +0200372
Michael Bestas118fcaf2015-06-04 23:02:20 +0300373def load_xml(x):
Anthony Kingb8607632015-05-01 22:06:37 +0300374 try:
375 return minidom.parse(x)
376 except IOError:
377 print('You have no %s.' % x, file=sys.stderr)
378 return None
379 except Exception:
380 # TODO: minidom should not be used.
381 print('Malformed %s.' % x, file=sys.stderr)
382 return None
Marco Brohet6b6b4e52014-07-20 00:05:16 +0200383
Michael Bestas4b26c4e2014-10-23 23:21:59 +0300384
Michael Bestas2f8c4a52015-08-05 21:33:50 +0300385def check_files(files):
Anthony Kingb8607632015-05-01 22:06:37 +0300386 for f in files:
387 if not os.path.isfile(f):
388 print('You have no %s.' % f, file=sys.stderr)
389 return False
Anthony Kingb8607632015-05-01 22:06:37 +0300390 return True
Michael Bestas4b26c4e2014-10-23 23:21:59 +0300391
Anthony Kingb8607632015-05-01 22:06:37 +0300392# ################################### MAIN ################################### #
Michael Bestas4b26c4e2014-10-23 23:21:59 +0300393
Michael Bestas4b26c4e2014-10-23 23:21:59 +0300394
Michael Bestasfd5d1362015-12-18 20:34:32 +0200395def upload_sources_crowdin(branch, config):
Michael Bestas2f8c4a52015-08-05 21:33:50 +0300396 if config:
Michael Bestasfd5d1362015-12-18 20:34:32 +0200397 print('\nUploading sources to Crowdin (custom config)')
Michael Bestaseb4629a2018-11-14 23:03:18 +0200398 check_run(['crowdin',
Michael Bestas03bc7052016-03-12 03:19:10 +0200399 '--config=%s/config/%s' % (_DIR, config),
Michael Bestas44fbb352015-12-17 02:01:42 +0200400 'upload', 'sources', '--branch=%s' % branch])
Michael Bestas2f8c4a52015-08-05 21:33:50 +0300401 else:
Michael Bestasfd5d1362015-12-18 20:34:32 +0200402 print('\nUploading sources to Crowdin (AOSP supported languages)')
Michael Bestaseb4629a2018-11-14 23:03:18 +0200403 check_run(['crowdin',
Michael Bestas03bc7052016-03-12 03:19:10 +0200404 '--config=%s/config/%s.yaml' % (_DIR, branch),
Michael Bestas44fbb352015-12-17 02:01:42 +0200405 'upload', 'sources', '--branch=%s' % branch])
Anthony King69a95382015-02-08 18:44:10 +0000406
Michael Bestasfd5d1362015-12-18 20:34:32 +0200407 print('\nUploading sources to Crowdin (non-AOSP supported languages)')
Michael Bestaseb4629a2018-11-14 23:03:18 +0200408 check_run(['crowdin',
Michael Bestas03bc7052016-03-12 03:19:10 +0200409 '--config=%s/config/%s_aosp.yaml' % (_DIR, branch),
Michael Bestas44fbb352015-12-17 02:01:42 +0200410 'upload', 'sources', '--branch=%s' % branch])
Anthony Kingb8607632015-05-01 22:06:37 +0300411
412
Michael Bestasfd5d1362015-12-18 20:34:32 +0200413def upload_translations_crowdin(branch, config):
Michael Bestas2f8c4a52015-08-05 21:33:50 +0300414 if config:
Michael Bestasfd5d1362015-12-18 20:34:32 +0200415 print('\nUploading translations to Crowdin (custom config)')
Michael Bestaseb4629a2018-11-14 23:03:18 +0200416 check_run(['crowdin',
Michael Bestas03bc7052016-03-12 03:19:10 +0200417 '--config=%s/config/%s' % (_DIR, config),
Michael Bestasfd5d1362015-12-18 20:34:32 +0200418 'upload', 'translations', '--branch=%s' % branch,
419 '--no-import-duplicates', '--import-eq-suggestions',
420 '--auto-approve-imported'])
421 else:
422 print('\nUploading translations to Crowdin '
423 '(AOSP supported languages)')
Michael Bestaseb4629a2018-11-14 23:03:18 +0200424 check_run(['crowdin',
Michael Bestas03bc7052016-03-12 03:19:10 +0200425 '--config=%s/config/%s.yaml' % (_DIR, branch),
Michael Bestasfd5d1362015-12-18 20:34:32 +0200426 'upload', 'translations', '--branch=%s' % branch,
427 '--no-import-duplicates', '--import-eq-suggestions',
428 '--auto-approve-imported'])
429
430 print('\nUploading translations to Crowdin '
431 '(non-AOSP supported languages)')
Michael Bestaseb4629a2018-11-14 23:03:18 +0200432 check_run(['crowdin',
Michael Bestas03bc7052016-03-12 03:19:10 +0200433 '--config=%s/config/%s_aosp.yaml' % (_DIR, branch),
Michael Bestasfd5d1362015-12-18 20:34:32 +0200434 'upload', 'translations', '--branch=%s' % branch,
435 '--no-import-duplicates', '--import-eq-suggestions',
436 '--auto-approve-imported'])
437
438
Michael Bestas80b22ef2018-11-14 23:12:33 +0200439def download_crowdin(base_path, branch, xml, username, config):
Michael Bestasfd5d1362015-12-18 20:34:32 +0200440 if config:
441 print('\nDownloading translations from Crowdin (custom config)')
Michael Bestaseb4629a2018-11-14 23:03:18 +0200442 check_run(['crowdin',
Michael Bestas03bc7052016-03-12 03:19:10 +0200443 '--config=%s/config/%s' % (_DIR, config),
Michael Bestas44fbb352015-12-17 02:01:42 +0200444 'download', '--branch=%s' % branch])
Michael Bestas2f8c4a52015-08-05 21:33:50 +0300445 else:
Michael Bestasfd5d1362015-12-18 20:34:32 +0200446 print('\nDownloading translations from Crowdin '
447 '(AOSP supported languages)')
Michael Bestaseb4629a2018-11-14 23:03:18 +0200448 check_run(['crowdin',
Michael Bestas03bc7052016-03-12 03:19:10 +0200449 '--config=%s/config/%s.yaml' % (_DIR, branch),
Michael Bestas44fbb352015-12-17 02:01:42 +0200450 'download', '--branch=%s' % branch])
Michael Bestas50579d22014-08-09 17:49:14 +0300451
Michael Bestasfd5d1362015-12-18 20:34:32 +0200452 print('\nDownloading translations from Crowdin '
Michael Bestas2f8c4a52015-08-05 21:33:50 +0300453 '(non-AOSP supported languages)')
Michael Bestaseb4629a2018-11-14 23:03:18 +0200454 check_run(['crowdin',
Michael Bestas03bc7052016-03-12 03:19:10 +0200455 '--config=%s/config/%s_aosp.yaml' % (_DIR, branch),
Michael Bestas44fbb352015-12-17 02:01:42 +0200456 'download', '--branch=%s' % branch])
Marco Brohetcb5cdb42014-07-11 22:41:53 +0200457
Michael Bestas99f5fce2015-06-04 22:07:51 +0300458 print('\nCreating a list of pushable translations')
Michael Bestas919053f2014-10-20 23:30:54 +0300459 # Get all files that Crowdin pushed
Anthony Kingb8607632015-05-01 22:06:37 +0300460 paths = []
Michael Bestas2f8c4a52015-08-05 21:33:50 +0300461 if config:
Michael Bestas03bc7052016-03-12 03:19:10 +0200462 files = ['%s/config/%s' % (_DIR, config)]
Michael Bestas2f8c4a52015-08-05 21:33:50 +0300463 else:
Michael Bestas03bc7052016-03-12 03:19:10 +0200464 files = ['%s/config/%s.yaml' % (_DIR, branch),
465 '%s/config/%s_aosp.yaml' % (_DIR, branch)]
Michael Bestas6c327e62015-05-02 01:58:01 +0300466 for c in files:
Michael Bestaseb4629a2018-11-14 23:03:18 +0200467 cmd = ['crowdin', '--config=%s' % c, 'list', 'project',
Michael Bestas44fbb352015-12-17 02:01:42 +0200468 '--branch=%s' % branch]
Anthony Kingb8607632015-05-01 22:06:37 +0300469 comm, ret = run_subprocess(cmd)
470 if ret != 0:
471 sys.exit(ret)
472 for p in str(comm[0]).split("\n"):
473 paths.append(p.replace('/%s' % branch, ''))
Michael Bestas50579d22014-08-09 17:49:14 +0300474
Michael Bestas99f5fce2015-06-04 22:07:51 +0300475 print('\nUploading translations to Gerrit')
Anthony Kingb8607632015-05-01 22:06:37 +0300476 items = [x for sub in xml for x in sub.getElementsByTagName('project')]
Michael Bestas919053f2014-10-20 23:30:54 +0300477 all_projects = []
478
Anthony Kingb8607632015-05-01 22:06:37 +0300479 for path in paths:
480 path = path.strip()
Michael Bestas919053f2014-10-20 23:30:54 +0300481 if not path:
482 continue
483
Anthony Kingb8607632015-05-01 22:06:37 +0300484 if "/res" not in path:
485 print('WARNING: Cannot determine project root dir of '
486 '[%s], skipping.' % path)
Anthony King69a95382015-02-08 18:44:10 +0000487 continue
Michael W67f14932019-03-11 09:59:32 +0100488
489 # Usually the project root is everything before /res
490 # but there are special cases where /res is part of the repo name as well
491 parts = path.split("/res")
492 if len(parts) == 2:
493 result = parts[0]
494 elif len(parts) == 3:
495 result = parts[0] + '/res' + parts[1]
496 else:
497 print('WARNING: Splitting the path not successful for [%s], skipping' % path)
498 continue
499
500 result = result.strip('/')
Anthony Kingb8607632015-05-01 22:06:37 +0300501 if result == path.strip('/'):
502 print('WARNING: Cannot determine project root dir of '
503 '[%s], skipping.' % path)
504 continue
Marco Brohet6b6b4e52014-07-20 00:05:16 +0200505
Michael Bestasc899b8c2015-03-03 00:53:19 +0200506 if result in all_projects:
Michael Bestasc899b8c2015-03-03 00:53:19 +0200507 continue
Michael Bestas50579d22014-08-09 17:49:14 +0300508
Anthony Kingb8607632015-05-01 22:06:37 +0300509 # When a project has multiple translatable files, Crowdin will
510 # give duplicates.
511 # We don't want that (useless empty commits), so we save each
512 # project in all_projects and check if it's already in there.
Michael Bestasc899b8c2015-03-03 00:53:19 +0200513 all_projects.append(result)
Anthony King69a95382015-02-08 18:44:10 +0000514
Michael Bestas42e25e32016-03-12 20:18:39 +0200515 # Search android/default.xml or config/%(branch)_extra_packages.xml
Anthony Kingb8607632015-05-01 22:06:37 +0300516 # for the project's name
Michael W1f187762019-03-11 19:38:00 +0100517 resultPath = None
518 resultProject = None
Anthony Kingb8607632015-05-01 22:06:37 +0300519 for project in items:
520 path = project.attributes['path'].value
521 if not (result + '/').startswith(path +'/'):
Michael Bestasc899b8c2015-03-03 00:53:19 +0200522 continue
Michael W1f187762019-03-11 19:38:00 +0100523 # We want the longest match, so projects in subfolders of other projects are also
524 # taken into account
525 if resultPath is None or len(path) > len(resultPath):
526 resultPath = path
527 resultProject = project
Anthony King69a95382015-02-08 18:44:10 +0000528
Michael W1f187762019-03-11 19:38:00 +0100529 # Just in case no project was found
530 if resultPath is None:
531 continue
Anthony King69a95382015-02-08 18:44:10 +0000532
Michael W1f187762019-03-11 19:38:00 +0100533 if result != resultPath:
534 if resultPath in all_projects:
535 continue
536 result = resultPath
537 all_projects.append(result)
538
539 br = resultProject.getAttribute('revision') or branch
540
541 push_as_commit(files, base_path, result,
542 resultProject.getAttribute('name'), br, username)
Anthony King69a95382015-02-08 18:44:10 +0000543
Anthony King69a95382015-02-08 18:44:10 +0000544
Michael We3af0fc2020-01-19 12:51:55 +0100545def sig_handler(signal_received, frame):
546 print('')
547 print('SIGINT or CTRL-C detected. Exiting gracefully')
548 exit(0)
549
550
Anthony Kingb8607632015-05-01 22:06:37 +0300551def main():
Michael We3af0fc2020-01-19 12:51:55 +0100552 signal(SIGINT, sig_handler)
Anthony Kingb8607632015-05-01 22:06:37 +0300553 args = parse_args()
554 default_branch = args.branch
Michael Bestas118fcaf2015-06-04 23:02:20 +0300555
Michael Wd13658a2019-01-13 14:05:37 +0100556 if args.submit:
557 if args.username is None:
558 print('Argument -u/--username is required for submitting!')
559 sys.exit(1)
560 submit_gerrit(default_branch, args.username)
561 sys.exit(0)
562
Michael Bestaseb4629a2018-11-14 23:03:18 +0200563 base_path_branch_suffix = default_branch.replace('-', '_').replace('.', '_').upper()
564 base_path_env = 'LINEAGE_CROWDIN_BASE_PATH_%s' % base_path_branch_suffix
565 base_path = os.getenv(base_path_env)
Michael Bestas118fcaf2015-06-04 23:02:20 +0300566 if base_path is None:
Anthony Kingd0d56cf2015-06-05 10:48:38 +0100567 cwd = os.getcwd()
Michael Bestaseb4629a2018-11-14 23:03:18 +0200568 print('You have not set %s. Defaulting to %s' % (base_path_env, cwd))
Michael Bestas118fcaf2015-06-04 23:02:20 +0300569 base_path = cwd
Michael Bestas118fcaf2015-06-04 23:02:20 +0300570 if not os.path.isdir(base_path):
Michael Bestaseb4629a2018-11-14 23:03:18 +0200571 print('%s is not a real directory: %s' % (base_path_env, base_path))
Michael Bestas118fcaf2015-06-04 23:02:20 +0300572 sys.exit(1)
Anthony Kingb8607632015-05-01 22:06:37 +0300573
Michael Bestas99f5fce2015-06-04 22:07:51 +0300574 if not check_dependencies():
575 sys.exit(1)
Anthony Kingb8607632015-05-01 22:06:37 +0300576
Michael Bestas118fcaf2015-06-04 23:02:20 +0300577 xml_android = load_xml(x='%s/android/default.xml' % base_path)
Anthony Kingb8607632015-05-01 22:06:37 +0300578 if xml_android is None:
579 sys.exit(1)
580
Michael Bestas42e25e32016-03-12 20:18:39 +0200581 xml_extra = load_xml(x='%s/config/%s_extra_packages.xml'
Anthony Kingd0d56cf2015-06-05 10:48:38 +0100582 % (_DIR, default_branch))
Anthony Kingb8607632015-05-01 22:06:37 +0300583 if xml_extra is None:
584 sys.exit(1)
585
Michael Bestas19dc3352018-02-03 20:24:00 +0200586 xml_snippet = load_xml(x='%s/android/snippets/lineage.xml' % base_path)
587 if xml_snippet is None:
588 xml_snippet = load_xml(x='%s/android/snippets/cm.xml' % base_path)
589 if xml_snippet is None:
590 xml_snippet = load_xml(x='%s/android/snippets/hal_cm_all.xml' % base_path)
591 if xml_snippet is not None:
592 xml_files = (xml_android, xml_snippet, xml_extra)
Michael Bestas687679f2016-12-07 23:20:12 +0200593 else:
594 xml_files = (xml_android, xml_extra)
595
Michael Bestas2f8c4a52015-08-05 21:33:50 +0300596 if args.config:
Michael Bestas03bc7052016-03-12 03:19:10 +0200597 files = ['%s/config/%s' % (_DIR, args.config)]
Michael Bestas2f8c4a52015-08-05 21:33:50 +0300598 else:
Michael Bestas03bc7052016-03-12 03:19:10 +0200599 files = ['%s/config/%s.yaml' % (_DIR, default_branch),
600 '%s/config/%s_aosp.yaml' % (_DIR, default_branch)]
Michael Bestas2f8c4a52015-08-05 21:33:50 +0300601 if not check_files(files):
Anthony Kingb8607632015-05-01 22:06:37 +0300602 sys.exit(1)
603
Michael Bestasfd5d1362015-12-18 20:34:32 +0200604 if args.download and args.username is None:
605 print('Argument -u/--username is required for translations download')
606 sys.exit(1)
607
608 if args.upload_sources:
609 upload_sources_crowdin(default_branch, args.config)
610 if args.upload_translations:
611 upload_translations_crowdin(default_branch, args.config)
612 if args.download:
Michael Bestas687679f2016-12-07 23:20:12 +0200613 download_crowdin(base_path, default_branch, xml_files,
Michael Bestas80b22ef2018-11-14 23:12:33 +0200614 args.username, args.config)
Tom Powell44256852016-07-06 15:23:25 -0700615
616 if _COMMITS_CREATED:
617 print('\nDone!')
618 sys.exit(0)
Tom Powellf42586f2016-07-11 11:02:54 -0700619 else:
Tom Powell44256852016-07-06 15:23:25 -0700620 print('\nNothing to commit')
621 sys.exit(-1)
Anthony Kingb8607632015-05-01 22:06:37 +0300622
623if __name__ == '__main__':
624 main()