blob: 34c83e0dd221464e52b949e991e638d2505d2db4 [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
Marco Brohetcb5cdb42014-07-11 22:41:53 +020031import subprocess
32import sys
Michael W1bb2f922019-02-27 17:46:28 +010033import yaml
Anthony Kingb8607632015-05-01 22:06:37 +030034
Michael W2ae05622019-02-28 15:27:22 +010035from lxml import etree
Marco Brohetcb5cdb42014-07-11 22:41:53 +020036from xml.dom import minidom
37
Anthony Kingd0d56cf2015-06-05 10:48:38 +010038# ################################# GLOBALS ################################## #
39
40_DIR = os.path.dirname(os.path.realpath(__file__))
Tom Powell44256852016-07-06 15:23:25 -070041_COMMITS_CREATED = False
Anthony Kingd0d56cf2015-06-05 10:48:38 +010042
Anthony Kingb8607632015-05-01 22:06:37 +030043# ################################ FUNCTIONS ################################# #
44
45
46def run_subprocess(cmd, silent=False):
47 p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
48 universal_newlines=True)
49 comm = p.communicate()
50 exit_code = p.returncode
51 if exit_code != 0 and not silent:
52 print("There was an error running the subprocess.\n"
53 "cmd: %s\n"
54 "exit code: %d\n"
55 "stdout: %s\n"
56 "stderr: %s" % (cmd, exit_code, comm[0], comm[1]),
57 file=sys.stderr)
58 return comm, exit_code
59
Marco Brohet6b6b4e52014-07-20 00:05:16 +020060
Michael W2ae05622019-02-28 15:27:22 +010061def add_target_paths(config_files, repo, base_path, project_path):
Michael W1bb2f922019-02-27 17:46:28 +010062 # Add or remove the files given in the config files to the commit
63 count = 0
64 file_paths = []
65 for f in config_files:
66 fh = open(f, "r")
67 try:
68 config = yaml.load(fh)
69 for tf in config['files']:
70 if project_path in tf['source']:
71 target_path = tf['translation']
72 lang_codes = tf['languages_mapping']['android_code']
73 for l in lang_codes:
74 lpath = get_target_path(tf['translation'], tf['source'],
75 lang_codes[l], project_path)
76 file_paths.append(lpath)
77 except yaml.YAMLError as e:
78 print(e, '\n Could not parse YAML.')
79 exit()
80 fh.close()
81
Michael W2ae05622019-02-28 15:27:22 +010082 # Strip all comments
83 for f in file_paths:
84 clean_file(base_path, project_path, f)
85
86 # Modified and untracked files
87 modified = repo.git.ls_files(m=True, o=True)
Michael W1bb2f922019-02-27 17:46:28 +010088 for m in modified.split('\n'):
89 if m in file_paths:
90 repo.git.add(m)
91 count += 1
92
93 deleted = repo.git.ls_files(d=True)
94 for d in deleted.split('\n'):
95 if d in file_paths:
96 repo.git.rm(d)
97 count += 1
98
99 return count
100
101
102def split_path(path):
103 # Split the given string to path and filename
104 if '/' in path:
105 original_file_name = path[1:][path.rfind("/"):]
106 original_path = path[:path.rfind("/")]
107 else:
108 original_file_name = path
109 original_path = ''
110
111 return original_path, original_file_name
112
113
114def get_target_path(pattern, source, lang, project_path):
115 # Make strings like '/%original_path%-%android_code%/%original_file_name%' valid file paths
116 # based on the source string's path
117 original_path, original_file_name = split_path(source)
118
119 target_path = pattern #.lstrip('/')
120 target_path = target_path.replace('%original_path%', original_path)
121 target_path = target_path.replace('%android_code%', lang)
122 target_path = target_path.replace('%original_file_name%', original_file_name)
123 target_path = target_path.replace(project_path, '')
124 target_path = target_path.lstrip('/')
125 return target_path
126
127
Michael W2ae05622019-02-28 15:27:22 +0100128def clean_file(base_path, project_path, filename):
129 path = base_path + '/' + project_path + '/' + filename
130
131 # We don't want to create every file, just work with those already existing
132 if not os.path.isfile(path):
133 return
134
135 try:
136 fh = open(path, 'r+')
137 except:
138 print('Something went wrong while opening file %s' % (path))
139 return
140
141 XML = fh.read()
142 tree = etree.fromstring(XML)
143
144 header = ''
145 comments = tree.xpath('//comment()')
146 for c in comments:
147 p = c.getparent()
148 if p is None:
149 # Keep all comments in header
150 header += str(c).replace('\\n', '\n').replace('\\t', '\t') + '\n'
151 continue
152 p.remove(c)
153
154 content = ''
155
156 # Take the original xml declaration and prepend it
157 declaration = XML.split('\n')[0]
158 if '<?' in declaration:
159 content = declaration + '\n'
160
161 content += etree.tostring(tree, pretty_print=True, encoding="utf-8", xml_declaration=False)
162
163 if header != '':
164 content = content.replace('?>\n', '?>\n' + header)
165
166 # Sometimes spaces are added, we don't want them
167 content = re.sub("[ ]*<\/resources>", "</resources>", content)
168
169 # Overwrite file with content stripped by all comments
170 fh.seek(0)
171 fh.write(content)
172 fh.truncate()
173 fh.close()
174
175 # Remove files which don't have any translated strings
176 empty_contents = {
177 '<resources/>',
178 '<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"/>',
179 ('<resources xmlns:android='
180 '"http://schemas.android.com/apk/res/android"/>'),
181 ('<resources xmlns:android="http://schemas.android.com/apk/res/android"'
182 ' xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"/>'),
183 ('<resources xmlns:tools="http://schemas.android.com/tools"'
184 ' xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"/>'),
185 '<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">\n</resources>',
186 '<resources>\n</resources>'
187 }
188 for line in empty_contents:
189 if line in content:
190 print('Removing ' + path)
191 os.remove(path)
192 break
193
Michael W1bb2f922019-02-27 17:46:28 +0100194def push_as_commit(config_files, base_path, path, name, branch, username):
Anthony Kingb8607632015-05-01 22:06:37 +0300195 print('Committing %s on branch %s' % (name, branch))
Marco Brohetcb5cdb42014-07-11 22:41:53 +0200196
197 # Get path
Michael W1bb2f922019-02-27 17:46:28 +0100198 project_path = path
Michael Bestas118fcaf2015-06-04 23:02:20 +0300199 path = os.path.join(base_path, path)
Anthony Kingb8607632015-05-01 22:06:37 +0300200 if not path.endswith('.git'):
201 path = os.path.join(path, '.git')
Marco Brohetcb5cdb42014-07-11 22:41:53 +0200202
Marco Brohet6b6b4e52014-07-20 00:05:16 +0200203 # Create repo object
Marco Brohetcb5cdb42014-07-11 22:41:53 +0200204 repo = git.Repo(path)
Marco Brohet6b6b4e52014-07-20 00:05:16 +0200205
Marco Brohet6b6b4e52014-07-20 00:05:16 +0200206 # Add all files to commit
Michael W2ae05622019-02-28 15:27:22 +0100207 count = add_target_paths(config_files, repo, base_path, project_path)
Michael W1bb2f922019-02-27 17:46:28 +0100208
209 if count == 0:
210 print('Nothing to commit')
211 return
Marco Brohet6b6b4e52014-07-20 00:05:16 +0200212
213 # Create commit; if it fails, probably empty so skipping
Marco Brohetcb5cdb42014-07-11 22:41:53 +0200214 try:
Michael Bestas80b22ef2018-11-14 23:12:33 +0200215 repo.git.commit(m='Automatic translation import')
Marco Brohetcb5cdb42014-07-11 22:41:53 +0200216 except:
Anthony Kingb8607632015-05-01 22:06:37 +0300217 print('Failed to create commit for %s, probably empty: skipping'
218 % name, file=sys.stderr)
Marco Brohetcb5cdb42014-07-11 22:41:53 +0200219 return
Marco Brohet6b6b4e52014-07-20 00:05:16 +0200220
221 # Push commit
Michael Bestasf96f67b2014-10-21 00:43:37 +0300222 try:
Abhisek Devkotab78def42016-12-27 13:06:52 -0800223 repo.git.push('ssh://%s@review.lineageos.org:29418/%s' % (username, name),
Anthony Kingb8607632015-05-01 22:06:37 +0300224 'HEAD:refs/for/%s%%topic=translation' % branch)
225 print('Successfully pushed commit for %s' % name)
Michael Bestasf96f67b2014-10-21 00:43:37 +0300226 except:
Anthony Kingb8607632015-05-01 22:06:37 +0300227 print('Failed to push commit for %s' % name, file=sys.stderr)
Marco Brohetcb5cdb42014-07-11 22:41:53 +0200228
Tom Powell44256852016-07-06 15:23:25 -0700229 _COMMITS_CREATED = True
230
Anthony Kingb8607632015-05-01 22:06:37 +0300231
Michael Wd13658a2019-01-13 14:05:37 +0100232def submit_gerrit(branch, username):
233 # Find all open translation changes
234 cmd = ['ssh', '-p', '29418',
235 '{}@review.lineageos.org'.format(username),
236 'gerrit', 'query',
237 'status:open',
238 'branch:{}'.format(branch),
239 'message:"Automatic translation import"',
240 'topic:translation',
Michael W6e0a7032019-02-27 17:04:16 +0100241 '--current-patch-set',
242 '--format=JSON']
243 commits = 0
Michael Wd13658a2019-01-13 14:05:37 +0100244 msg, code = run_subprocess(cmd)
245 if code != 0:
246 print('Failed: {0}'.format(msg[1]))
247 return
248
Michael W6e0a7032019-02-27 17:04:16 +0100249 # Each line is one valid JSON object, except the last one, which is empty
250 for line in msg[0].strip('\n').split('\n'):
251 js = json.loads(line)
252 # We get valid JSON, but not every result line is one we want
253 if not 'currentPatchSet' in js or not 'revision' in js['currentPatchSet']:
254 continue
Michael Wd13658a2019-01-13 14:05:37 +0100255 # Add Code-Review +2 and Verified+1 labels and submit
256 cmd = ['ssh', '-p', '29418',
257 '{}@review.lineageos.org'.format(username),
258 'gerrit', 'review',
259 '--verified +1',
260 '--code-review +2',
Michael W6e0a7032019-02-27 17:04:16 +0100261 '--submit', js['currentPatchSet']['revision']]
Michael Wd13658a2019-01-13 14:05:37 +0100262 msg, code = run_subprocess(cmd, True)
263 if code != 0:
264 errorText = msg[1].replace('\n\n', '; ').replace('\n', '')
Michael W6e0a7032019-02-27 17:04:16 +0100265 print('Submitting commit {0} failed: {1}'.format(js['url'], errorText))
Michael Wd13658a2019-01-13 14:05:37 +0100266 else:
Michael W6e0a7032019-02-27 17:04:16 +0100267 print('Success when submitting commit {0}'.format(js['url']))
268
269 commits += 1
270
271 if commits == 0:
272 print("Nothing to submit!")
273 return
Michael Wd13658a2019-01-13 14:05:37 +0100274
275
Anthony Kingb8607632015-05-01 22:06:37 +0300276def check_run(cmd):
Michael Bestas97677e12015-02-08 13:11:59 +0200277 p = subprocess.Popen(cmd, stdout=sys.stdout, stderr=sys.stderr)
278 ret = p.wait()
279 if ret != 0:
Anthony Kingb8607632015-05-01 22:06:37 +0300280 print('Failed to run cmd: %s' % ' '.join(cmd), file=sys.stderr)
Michael Bestas97677e12015-02-08 13:11:59 +0200281 sys.exit(ret)
282
Marco Brohet6b6b4e52014-07-20 00:05:16 +0200283
Michael Bestas118fcaf2015-06-04 23:02:20 +0300284def find_xml(base_path):
285 for dp, dn, file_names in os.walk(base_path):
Anthony Kingb8607632015-05-01 22:06:37 +0300286 for f in file_names:
287 if os.path.splitext(f)[1] == '.xml':
288 yield os.path.join(dp, f)
Marco Brohet6b6b4e52014-07-20 00:05:16 +0200289
Anthony Kingb8607632015-05-01 22:06:37 +0300290# ############################################################################ #
Marco Brohet6b6b4e52014-07-20 00:05:16 +0200291
Michael Bestas6b6db122015-02-08 13:22:22 +0200292
Anthony Kingb8607632015-05-01 22:06:37 +0300293def parse_args():
294 parser = argparse.ArgumentParser(
Abhisek Devkotab78def42016-12-27 13:06:52 -0800295 description="Synchronising LineageOS' translations with Crowdin")
Michael Bestasfd5d1362015-12-18 20:34:32 +0200296 parser.add_argument('-u', '--username', help='Gerrit username')
Abhisek Devkotab78def42016-12-27 13:06:52 -0800297 parser.add_argument('-b', '--branch', help='LineageOS branch',
Anthony Kingb8607632015-05-01 22:06:37 +0300298 required=True)
Michael Bestas2f8c4a52015-08-05 21:33:50 +0300299 parser.add_argument('-c', '--config', help='Custom yaml config')
Michael Bestasfd5d1362015-12-18 20:34:32 +0200300 parser.add_argument('--upload-sources', action='store_true',
301 help='Upload sources to Crowdin')
302 parser.add_argument('--upload-translations', action='store_true',
303 help='Upload translations to Crowdin')
304 parser.add_argument('--download', action='store_true',
305 help='Download translations from Crowdin')
Michael Wd13658a2019-01-13 14:05:37 +0100306 parser.add_argument('-s', '--submit', action='store_true',
307 help='Merge open translation commits')
Anthony Kingb8607632015-05-01 22:06:37 +0300308 return parser.parse_args()
Michael Bestas6b6db122015-02-08 13:22:22 +0200309
Anthony Kingb8607632015-05-01 22:06:37 +0300310# ################################# PREPARE ################################## #
Marco Brohet6b6b4e52014-07-20 00:05:16 +0200311
Anthony Kingb8607632015-05-01 22:06:37 +0300312
313def check_dependencies():
Michael Bestaseb4629a2018-11-14 23:03:18 +0200314 # Check for Java version of crowdin
315 cmd = ['dpkg-query', '-W', 'crowdin']
Anthony Kingb8607632015-05-01 22:06:37 +0300316 if run_subprocess(cmd, silent=True)[1] != 0:
Michael Bestaseb4629a2018-11-14 23:03:18 +0200317 print('You have not installed crowdin.', file=sys.stderr)
Anthony Kingb8607632015-05-01 22:06:37 +0300318 return False
Anthony Kingb8607632015-05-01 22:06:37 +0300319 return True
Marco Brohetcb5cdb42014-07-11 22:41:53 +0200320
Marco Brohetcb5cdb42014-07-11 22:41:53 +0200321
Michael Bestas118fcaf2015-06-04 23:02:20 +0300322def load_xml(x):
Anthony Kingb8607632015-05-01 22:06:37 +0300323 try:
324 return minidom.parse(x)
325 except IOError:
326 print('You have no %s.' % x, file=sys.stderr)
327 return None
328 except Exception:
329 # TODO: minidom should not be used.
330 print('Malformed %s.' % x, file=sys.stderr)
331 return None
Marco Brohet6b6b4e52014-07-20 00:05:16 +0200332
Michael Bestas4b26c4e2014-10-23 23:21:59 +0300333
Michael Bestas2f8c4a52015-08-05 21:33:50 +0300334def check_files(files):
Anthony Kingb8607632015-05-01 22:06:37 +0300335 for f in files:
336 if not os.path.isfile(f):
337 print('You have no %s.' % f, file=sys.stderr)
338 return False
Anthony Kingb8607632015-05-01 22:06:37 +0300339 return True
Michael Bestas4b26c4e2014-10-23 23:21:59 +0300340
Anthony Kingb8607632015-05-01 22:06:37 +0300341# ################################### MAIN ################################### #
Michael Bestas4b26c4e2014-10-23 23:21:59 +0300342
Michael Bestas4b26c4e2014-10-23 23:21:59 +0300343
Michael Bestasfd5d1362015-12-18 20:34:32 +0200344def upload_sources_crowdin(branch, config):
Michael Bestas2f8c4a52015-08-05 21:33:50 +0300345 if config:
Michael Bestasfd5d1362015-12-18 20:34:32 +0200346 print('\nUploading sources to Crowdin (custom config)')
Michael Bestaseb4629a2018-11-14 23:03:18 +0200347 check_run(['crowdin',
Michael Bestas03bc7052016-03-12 03:19:10 +0200348 '--config=%s/config/%s' % (_DIR, config),
Michael Bestas44fbb352015-12-17 02:01:42 +0200349 'upload', 'sources', '--branch=%s' % branch])
Michael Bestas2f8c4a52015-08-05 21:33:50 +0300350 else:
Michael Bestasfd5d1362015-12-18 20:34:32 +0200351 print('\nUploading sources to Crowdin (AOSP supported languages)')
Michael Bestaseb4629a2018-11-14 23:03:18 +0200352 check_run(['crowdin',
Michael Bestas03bc7052016-03-12 03:19:10 +0200353 '--config=%s/config/%s.yaml' % (_DIR, branch),
Michael Bestas44fbb352015-12-17 02:01:42 +0200354 'upload', 'sources', '--branch=%s' % branch])
Anthony King69a95382015-02-08 18:44:10 +0000355
Michael Bestasfd5d1362015-12-18 20:34:32 +0200356 print('\nUploading sources to Crowdin (non-AOSP supported languages)')
Michael Bestaseb4629a2018-11-14 23:03:18 +0200357 check_run(['crowdin',
Michael Bestas03bc7052016-03-12 03:19:10 +0200358 '--config=%s/config/%s_aosp.yaml' % (_DIR, branch),
Michael Bestas44fbb352015-12-17 02:01:42 +0200359 'upload', 'sources', '--branch=%s' % branch])
Anthony Kingb8607632015-05-01 22:06:37 +0300360
361
Michael Bestasfd5d1362015-12-18 20:34:32 +0200362def upload_translations_crowdin(branch, config):
Michael Bestas2f8c4a52015-08-05 21:33:50 +0300363 if config:
Michael Bestasfd5d1362015-12-18 20:34:32 +0200364 print('\nUploading translations to Crowdin (custom config)')
Michael Bestaseb4629a2018-11-14 23:03:18 +0200365 check_run(['crowdin',
Michael Bestas03bc7052016-03-12 03:19:10 +0200366 '--config=%s/config/%s' % (_DIR, config),
Michael Bestasfd5d1362015-12-18 20:34:32 +0200367 'upload', 'translations', '--branch=%s' % branch,
368 '--no-import-duplicates', '--import-eq-suggestions',
369 '--auto-approve-imported'])
370 else:
371 print('\nUploading translations to Crowdin '
372 '(AOSP supported languages)')
Michael Bestaseb4629a2018-11-14 23:03:18 +0200373 check_run(['crowdin',
Michael Bestas03bc7052016-03-12 03:19:10 +0200374 '--config=%s/config/%s.yaml' % (_DIR, branch),
Michael Bestasfd5d1362015-12-18 20:34:32 +0200375 'upload', 'translations', '--branch=%s' % branch,
376 '--no-import-duplicates', '--import-eq-suggestions',
377 '--auto-approve-imported'])
378
379 print('\nUploading translations to Crowdin '
380 '(non-AOSP supported languages)')
Michael Bestaseb4629a2018-11-14 23:03:18 +0200381 check_run(['crowdin',
Michael Bestas03bc7052016-03-12 03:19:10 +0200382 '--config=%s/config/%s_aosp.yaml' % (_DIR, branch),
Michael Bestasfd5d1362015-12-18 20:34:32 +0200383 'upload', 'translations', '--branch=%s' % branch,
384 '--no-import-duplicates', '--import-eq-suggestions',
385 '--auto-approve-imported'])
386
387
Michael Bestas80b22ef2018-11-14 23:12:33 +0200388def download_crowdin(base_path, branch, xml, username, config):
Michael Bestasfd5d1362015-12-18 20:34:32 +0200389 if config:
390 print('\nDownloading translations from Crowdin (custom config)')
Michael Bestaseb4629a2018-11-14 23:03:18 +0200391 check_run(['crowdin',
Michael Bestas03bc7052016-03-12 03:19:10 +0200392 '--config=%s/config/%s' % (_DIR, config),
Michael Bestas44fbb352015-12-17 02:01:42 +0200393 'download', '--branch=%s' % branch])
Michael Bestas2f8c4a52015-08-05 21:33:50 +0300394 else:
Michael Bestasfd5d1362015-12-18 20:34:32 +0200395 print('\nDownloading translations from Crowdin '
396 '(AOSP supported languages)')
Michael Bestaseb4629a2018-11-14 23:03:18 +0200397 check_run(['crowdin',
Michael Bestas03bc7052016-03-12 03:19:10 +0200398 '--config=%s/config/%s.yaml' % (_DIR, branch),
Michael Bestas44fbb352015-12-17 02:01:42 +0200399 'download', '--branch=%s' % branch])
Michael Bestas50579d22014-08-09 17:49:14 +0300400
Michael Bestasfd5d1362015-12-18 20:34:32 +0200401 print('\nDownloading translations from Crowdin '
Michael Bestas2f8c4a52015-08-05 21:33:50 +0300402 '(non-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_aosp.yaml' % (_DIR, branch),
Michael Bestas44fbb352015-12-17 02:01:42 +0200405 'download', '--branch=%s' % branch])
Marco Brohetcb5cdb42014-07-11 22:41:53 +0200406
Michael Bestas99f5fce2015-06-04 22:07:51 +0300407 print('\nCreating a list of pushable translations')
Michael Bestas919053f2014-10-20 23:30:54 +0300408 # Get all files that Crowdin pushed
Anthony Kingb8607632015-05-01 22:06:37 +0300409 paths = []
Michael Bestas2f8c4a52015-08-05 21:33:50 +0300410 if config:
Michael Bestas03bc7052016-03-12 03:19:10 +0200411 files = ['%s/config/%s' % (_DIR, config)]
Michael Bestas2f8c4a52015-08-05 21:33:50 +0300412 else:
Michael Bestas03bc7052016-03-12 03:19:10 +0200413 files = ['%s/config/%s.yaml' % (_DIR, branch),
414 '%s/config/%s_aosp.yaml' % (_DIR, branch)]
Michael Bestas6c327e62015-05-02 01:58:01 +0300415 for c in files:
Michael Bestaseb4629a2018-11-14 23:03:18 +0200416 cmd = ['crowdin', '--config=%s' % c, 'list', 'project',
Michael Bestas44fbb352015-12-17 02:01:42 +0200417 '--branch=%s' % branch]
Anthony Kingb8607632015-05-01 22:06:37 +0300418 comm, ret = run_subprocess(cmd)
419 if ret != 0:
420 sys.exit(ret)
421 for p in str(comm[0]).split("\n"):
422 paths.append(p.replace('/%s' % branch, ''))
Michael Bestas50579d22014-08-09 17:49:14 +0300423
Michael Bestas99f5fce2015-06-04 22:07:51 +0300424 print('\nUploading translations to Gerrit')
Anthony Kingb8607632015-05-01 22:06:37 +0300425 items = [x for sub in xml for x in sub.getElementsByTagName('project')]
Michael Bestas919053f2014-10-20 23:30:54 +0300426 all_projects = []
427
Anthony Kingb8607632015-05-01 22:06:37 +0300428 for path in paths:
429 path = path.strip()
Michael Bestas919053f2014-10-20 23:30:54 +0300430 if not path:
431 continue
432
Anthony Kingb8607632015-05-01 22:06:37 +0300433 if "/res" not in path:
434 print('WARNING: Cannot determine project root dir of '
435 '[%s], skipping.' % path)
Anthony King69a95382015-02-08 18:44:10 +0000436 continue
Anthony Kingb8607632015-05-01 22:06:37 +0300437 result = path.split('/res')[0].strip('/')
438 if result == path.strip('/'):
439 print('WARNING: Cannot determine project root dir of '
440 '[%s], skipping.' % path)
441 continue
Marco Brohet6b6b4e52014-07-20 00:05:16 +0200442
Michael Bestasc899b8c2015-03-03 00:53:19 +0200443 if result in all_projects:
Michael Bestasc899b8c2015-03-03 00:53:19 +0200444 continue
Michael Bestas50579d22014-08-09 17:49:14 +0300445
Anthony Kingb8607632015-05-01 22:06:37 +0300446 # When a project has multiple translatable files, Crowdin will
447 # give duplicates.
448 # We don't want that (useless empty commits), so we save each
449 # project in all_projects and check if it's already in there.
Michael Bestasc899b8c2015-03-03 00:53:19 +0200450 all_projects.append(result)
Anthony King69a95382015-02-08 18:44:10 +0000451
Michael Bestas42e25e32016-03-12 20:18:39 +0200452 # Search android/default.xml or config/%(branch)_extra_packages.xml
Anthony Kingb8607632015-05-01 22:06:37 +0300453 # for the project's name
454 for project in items:
455 path = project.attributes['path'].value
456 if not (result + '/').startswith(path +'/'):
Michael Bestasc899b8c2015-03-03 00:53:19 +0200457 continue
Anthony Kingb8607632015-05-01 22:06:37 +0300458 if result != path:
459 if path in all_projects:
460 break
461 result = path
462 all_projects.append(result)
Anthony King69a95382015-02-08 18:44:10 +0000463
Anthony Kingb8607632015-05-01 22:06:37 +0300464 br = project.getAttribute('revision') or branch
Anthony King69a95382015-02-08 18:44:10 +0000465
Michael W1bb2f922019-02-27 17:46:28 +0100466 push_as_commit(files, base_path, result,
Michael Bestas80b22ef2018-11-14 23:12:33 +0200467 project.getAttribute('name'), br, username)
Anthony Kingb8607632015-05-01 22:06:37 +0300468 break
Anthony King69a95382015-02-08 18:44:10 +0000469
Anthony King69a95382015-02-08 18:44:10 +0000470
Anthony Kingb8607632015-05-01 22:06:37 +0300471def main():
Anthony Kingb8607632015-05-01 22:06:37 +0300472 args = parse_args()
473 default_branch = args.branch
Michael Bestas118fcaf2015-06-04 23:02:20 +0300474
Michael Wd13658a2019-01-13 14:05:37 +0100475 if args.submit:
476 if args.username is None:
477 print('Argument -u/--username is required for submitting!')
478 sys.exit(1)
479 submit_gerrit(default_branch, args.username)
480 sys.exit(0)
481
Michael Bestaseb4629a2018-11-14 23:03:18 +0200482 base_path_branch_suffix = default_branch.replace('-', '_').replace('.', '_').upper()
483 base_path_env = 'LINEAGE_CROWDIN_BASE_PATH_%s' % base_path_branch_suffix
484 base_path = os.getenv(base_path_env)
Michael Bestas118fcaf2015-06-04 23:02:20 +0300485 if base_path is None:
Anthony Kingd0d56cf2015-06-05 10:48:38 +0100486 cwd = os.getcwd()
Michael Bestaseb4629a2018-11-14 23:03:18 +0200487 print('You have not set %s. Defaulting to %s' % (base_path_env, cwd))
Michael Bestas118fcaf2015-06-04 23:02:20 +0300488 base_path = cwd
Michael Bestas118fcaf2015-06-04 23:02:20 +0300489 if not os.path.isdir(base_path):
Michael Bestaseb4629a2018-11-14 23:03:18 +0200490 print('%s is not a real directory: %s' % (base_path_env, base_path))
Michael Bestas118fcaf2015-06-04 23:02:20 +0300491 sys.exit(1)
Anthony Kingb8607632015-05-01 22:06:37 +0300492
Michael Bestas99f5fce2015-06-04 22:07:51 +0300493 if not check_dependencies():
494 sys.exit(1)
Anthony Kingb8607632015-05-01 22:06:37 +0300495
Michael Bestas118fcaf2015-06-04 23:02:20 +0300496 xml_android = load_xml(x='%s/android/default.xml' % base_path)
Anthony Kingb8607632015-05-01 22:06:37 +0300497 if xml_android is None:
498 sys.exit(1)
499
Michael Bestas42e25e32016-03-12 20:18:39 +0200500 xml_extra = load_xml(x='%s/config/%s_extra_packages.xml'
Anthony Kingd0d56cf2015-06-05 10:48:38 +0100501 % (_DIR, default_branch))
Anthony Kingb8607632015-05-01 22:06:37 +0300502 if xml_extra is None:
503 sys.exit(1)
504
Michael Bestas19dc3352018-02-03 20:24:00 +0200505 xml_snippet = load_xml(x='%s/android/snippets/lineage.xml' % base_path)
506 if xml_snippet is None:
507 xml_snippet = load_xml(x='%s/android/snippets/cm.xml' % base_path)
508 if xml_snippet is None:
509 xml_snippet = load_xml(x='%s/android/snippets/hal_cm_all.xml' % base_path)
510 if xml_snippet is not None:
511 xml_files = (xml_android, xml_snippet, xml_extra)
Michael Bestas687679f2016-12-07 23:20:12 +0200512 else:
513 xml_files = (xml_android, xml_extra)
514
Michael Bestas2f8c4a52015-08-05 21:33:50 +0300515 if args.config:
Michael Bestas03bc7052016-03-12 03:19:10 +0200516 files = ['%s/config/%s' % (_DIR, args.config)]
Michael Bestas2f8c4a52015-08-05 21:33:50 +0300517 else:
Michael Bestas03bc7052016-03-12 03:19:10 +0200518 files = ['%s/config/%s.yaml' % (_DIR, default_branch),
519 '%s/config/%s_aosp.yaml' % (_DIR, default_branch)]
Michael Bestas2f8c4a52015-08-05 21:33:50 +0300520 if not check_files(files):
Anthony Kingb8607632015-05-01 22:06:37 +0300521 sys.exit(1)
522
Michael Bestasfd5d1362015-12-18 20:34:32 +0200523 if args.download and args.username is None:
524 print('Argument -u/--username is required for translations download')
525 sys.exit(1)
526
527 if args.upload_sources:
528 upload_sources_crowdin(default_branch, args.config)
529 if args.upload_translations:
530 upload_translations_crowdin(default_branch, args.config)
531 if args.download:
Michael Bestas687679f2016-12-07 23:20:12 +0200532 download_crowdin(base_path, default_branch, xml_files,
Michael Bestas80b22ef2018-11-14 23:12:33 +0200533 args.username, args.config)
Tom Powell44256852016-07-06 15:23:25 -0700534
535 if _COMMITS_CREATED:
536 print('\nDone!')
537 sys.exit(0)
Tom Powellf42586f2016-07-11 11:02:54 -0700538 else:
Tom Powell44256852016-07-06 15:23:25 -0700539 print('\nNothing to commit')
540 sys.exit(-1)
Anthony Kingb8607632015-05-01 22:06:37 +0300541
542if __name__ == '__main__':
543 main()