blob: 299f0dad4a9a79b70b939d6581a09eb42294198c [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
Marco Brohetcb5cdb42014-07-11 22:41:53 +020032import subprocess
33import sys
Michael W1bb2f922019-02-27 17:46:28 +010034import yaml
Anthony Kingb8607632015-05-01 22:06:37 +030035
Michael W2ae05622019-02-28 15:27:22 +010036from lxml import etree
Marco Brohetcb5cdb42014-07-11 22:41:53 +020037from xml.dom import minidom
38
Anthony Kingd0d56cf2015-06-05 10:48:38 +010039# ################################# GLOBALS ################################## #
40
41_DIR = os.path.dirname(os.path.realpath(__file__))
Tom Powell44256852016-07-06 15:23:25 -070042_COMMITS_CREATED = False
Anthony Kingd0d56cf2015-06-05 10:48:38 +010043
Anthony Kingb8607632015-05-01 22:06:37 +030044# ################################ FUNCTIONS ################################# #
45
46
47def run_subprocess(cmd, silent=False):
48 p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
49 universal_newlines=True)
50 comm = p.communicate()
51 exit_code = p.returncode
52 if exit_code != 0 and not silent:
53 print("There was an error running the subprocess.\n"
54 "cmd: %s\n"
55 "exit code: %d\n"
56 "stdout: %s\n"
57 "stderr: %s" % (cmd, exit_code, comm[0], comm[1]),
58 file=sys.stderr)
59 return comm, exit_code
60
Marco Brohet6b6b4e52014-07-20 00:05:16 +020061
Michael W2ae05622019-02-28 15:27:22 +010062def add_target_paths(config_files, repo, base_path, project_path):
Michael W1bb2f922019-02-27 17:46:28 +010063 # Add or remove the files given in the config files to the commit
64 count = 0
65 file_paths = []
66 for f in config_files:
67 fh = open(f, "r")
68 try:
69 config = yaml.load(fh)
70 for tf in config['files']:
71 if project_path in tf['source']:
72 target_path = tf['translation']
73 lang_codes = tf['languages_mapping']['android_code']
74 for l in lang_codes:
75 lpath = get_target_path(tf['translation'], tf['source'],
76 lang_codes[l], project_path)
77 file_paths.append(lpath)
78 except yaml.YAMLError as e:
79 print(e, '\n Could not parse YAML.')
80 exit()
81 fh.close()
82
Michael W2ae05622019-02-28 15:27:22 +010083 # Strip all comments
84 for f in file_paths:
85 clean_file(base_path, project_path, f)
86
87 # Modified and untracked files
88 modified = repo.git.ls_files(m=True, o=True)
Michael W1bb2f922019-02-27 17:46:28 +010089 for m in modified.split('\n'):
90 if m in file_paths:
91 repo.git.add(m)
92 count += 1
93
94 deleted = repo.git.ls_files(d=True)
95 for d in deleted.split('\n'):
96 if d in file_paths:
97 repo.git.rm(d)
98 count += 1
99
100 return count
101
102
103def split_path(path):
104 # Split the given string to path and filename
105 if '/' in path:
106 original_file_name = path[1:][path.rfind("/"):]
107 original_path = path[:path.rfind("/")]
108 else:
109 original_file_name = path
110 original_path = ''
111
112 return original_path, original_file_name
113
114
115def get_target_path(pattern, source, lang, project_path):
116 # Make strings like '/%original_path%-%android_code%/%original_file_name%' valid file paths
117 # based on the source string's path
118 original_path, original_file_name = split_path(source)
119
120 target_path = pattern #.lstrip('/')
121 target_path = target_path.replace('%original_path%', original_path)
122 target_path = target_path.replace('%android_code%', lang)
123 target_path = target_path.replace('%original_file_name%', original_file_name)
124 target_path = target_path.replace(project_path, '')
125 target_path = target_path.lstrip('/')
126 return target_path
127
128
Michael W2ae05622019-02-28 15:27:22 +0100129def clean_file(base_path, project_path, filename):
130 path = base_path + '/' + project_path + '/' + filename
131
132 # We don't want to create every file, just work with those already existing
133 if not os.path.isfile(path):
134 return
135
136 try:
137 fh = open(path, 'r+')
138 except:
139 print('Something went wrong while opening file %s' % (path))
140 return
141
142 XML = fh.read()
143 tree = etree.fromstring(XML)
144
145 header = ''
146 comments = tree.xpath('//comment()')
147 for c in comments:
148 p = c.getparent()
149 if p is None:
150 # Keep all comments in header
151 header += str(c).replace('\\n', '\n').replace('\\t', '\t') + '\n'
152 continue
153 p.remove(c)
154
155 content = ''
156
157 # Take the original xml declaration and prepend it
158 declaration = XML.split('\n')[0]
159 if '<?' in declaration:
160 content = declaration + '\n'
161
162 content += etree.tostring(tree, pretty_print=True, encoding="utf-8", xml_declaration=False)
163
164 if header != '':
165 content = content.replace('?>\n', '?>\n' + header)
166
167 # Sometimes spaces are added, we don't want them
168 content = re.sub("[ ]*<\/resources>", "</resources>", content)
169
170 # Overwrite file with content stripped by all comments
171 fh.seek(0)
172 fh.write(content)
173 fh.truncate()
174 fh.close()
175
176 # Remove files which don't have any translated strings
177 empty_contents = {
178 '<resources/>',
179 '<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"/>',
180 ('<resources xmlns:android='
181 '"http://schemas.android.com/apk/res/android"/>'),
182 ('<resources xmlns:android="http://schemas.android.com/apk/res/android"'
183 ' xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"/>'),
184 ('<resources xmlns:tools="http://schemas.android.com/tools"'
185 ' xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"/>'),
186 '<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">\n</resources>',
187 '<resources>\n</resources>'
188 }
189 for line in empty_contents:
190 if line in content:
191 print('Removing ' + path)
192 os.remove(path)
193 break
194
Michael W1bb2f922019-02-27 17:46:28 +0100195def push_as_commit(config_files, base_path, path, name, branch, username):
Anthony Kingb8607632015-05-01 22:06:37 +0300196 print('Committing %s on branch %s' % (name, branch))
Marco Brohetcb5cdb42014-07-11 22:41:53 +0200197
198 # Get path
Michael W1bb2f922019-02-27 17:46:28 +0100199 project_path = path
Michael Bestas118fcaf2015-06-04 23:02:20 +0300200 path = os.path.join(base_path, path)
Anthony Kingb8607632015-05-01 22:06:37 +0300201 if not path.endswith('.git'):
202 path = os.path.join(path, '.git')
Marco Brohetcb5cdb42014-07-11 22:41:53 +0200203
Marco Brohet6b6b4e52014-07-20 00:05:16 +0200204 # Create repo object
Marco Brohetcb5cdb42014-07-11 22:41:53 +0200205 repo = git.Repo(path)
Marco Brohet6b6b4e52014-07-20 00:05:16 +0200206
Marco Brohet6b6b4e52014-07-20 00:05:16 +0200207 # Add all files to commit
Michael W2ae05622019-02-28 15:27:22 +0100208 count = add_target_paths(config_files, repo, base_path, project_path)
Michael W1bb2f922019-02-27 17:46:28 +0100209
210 if count == 0:
211 print('Nothing to commit')
212 return
Marco Brohet6b6b4e52014-07-20 00:05:16 +0200213
214 # Create commit; if it fails, probably empty so skipping
Marco Brohetcb5cdb42014-07-11 22:41:53 +0200215 try:
Michael Bestas80b22ef2018-11-14 23:12:33 +0200216 repo.git.commit(m='Automatic translation import')
Marco Brohetcb5cdb42014-07-11 22:41:53 +0200217 except:
Anthony Kingb8607632015-05-01 22:06:37 +0300218 print('Failed to create commit for %s, probably empty: skipping'
219 % name, file=sys.stderr)
Marco Brohetcb5cdb42014-07-11 22:41:53 +0200220 return
Marco Brohet6b6b4e52014-07-20 00:05:16 +0200221
222 # Push commit
Michael Bestasf96f67b2014-10-21 00:43:37 +0300223 try:
Abhisek Devkotab78def42016-12-27 13:06:52 -0800224 repo.git.push('ssh://%s@review.lineageos.org:29418/%s' % (username, name),
Anthony Kingb8607632015-05-01 22:06:37 +0300225 'HEAD:refs/for/%s%%topic=translation' % branch)
226 print('Successfully pushed commit for %s' % name)
Michael Bestasf96f67b2014-10-21 00:43:37 +0300227 except:
Anthony Kingb8607632015-05-01 22:06:37 +0300228 print('Failed to push commit for %s' % name, file=sys.stderr)
Marco Brohetcb5cdb42014-07-11 22:41:53 +0200229
Tom Powell44256852016-07-06 15:23:25 -0700230 _COMMITS_CREATED = True
231
Anthony Kingb8607632015-05-01 22:06:37 +0300232
Michael Wd13658a2019-01-13 14:05:37 +0100233def submit_gerrit(branch, username):
234 # Find all open translation changes
235 cmd = ['ssh', '-p', '29418',
236 '{}@review.lineageos.org'.format(username),
237 'gerrit', 'query',
238 'status:open',
239 'branch:{}'.format(branch),
240 'message:"Automatic translation import"',
241 'topic:translation',
Michael W6e0a7032019-02-27 17:04:16 +0100242 '--current-patch-set',
243 '--format=JSON']
244 commits = 0
Michael Wd13658a2019-01-13 14:05:37 +0100245 msg, code = run_subprocess(cmd)
246 if code != 0:
247 print('Failed: {0}'.format(msg[1]))
248 return
249
Michael W6e0a7032019-02-27 17:04:16 +0100250 # Each line is one valid JSON object, except the last one, which is empty
251 for line in msg[0].strip('\n').split('\n'):
252 js = json.loads(line)
253 # We get valid JSON, but not every result line is one we want
254 if not 'currentPatchSet' in js or not 'revision' in js['currentPatchSet']:
255 continue
Michael Wd13658a2019-01-13 14:05:37 +0100256 # Add Code-Review +2 and Verified+1 labels and submit
257 cmd = ['ssh', '-p', '29418',
258 '{}@review.lineageos.org'.format(username),
259 'gerrit', 'review',
260 '--verified +1',
261 '--code-review +2',
Michael W6e0a7032019-02-27 17:04:16 +0100262 '--submit', js['currentPatchSet']['revision']]
Michael Wd13658a2019-01-13 14:05:37 +0100263 msg, code = run_subprocess(cmd, True)
264 if code != 0:
265 errorText = msg[1].replace('\n\n', '; ').replace('\n', '')
Michael W6e0a7032019-02-27 17:04:16 +0100266 print('Submitting commit {0} failed: {1}'.format(js['url'], errorText))
Michael Wd13658a2019-01-13 14:05:37 +0100267 else:
Michael W6e0a7032019-02-27 17:04:16 +0100268 print('Success when submitting commit {0}'.format(js['url']))
269
270 commits += 1
271
272 if commits == 0:
273 print("Nothing to submit!")
274 return
Michael Wd13658a2019-01-13 14:05:37 +0100275
276
Anthony Kingb8607632015-05-01 22:06:37 +0300277def check_run(cmd):
Michael Bestas97677e12015-02-08 13:11:59 +0200278 p = subprocess.Popen(cmd, stdout=sys.stdout, stderr=sys.stderr)
279 ret = p.wait()
280 if ret != 0:
Anthony Kingb8607632015-05-01 22:06:37 +0300281 print('Failed to run cmd: %s' % ' '.join(cmd), file=sys.stderr)
Michael Bestas97677e12015-02-08 13:11:59 +0200282 sys.exit(ret)
283
Marco Brohet6b6b4e52014-07-20 00:05:16 +0200284
Michael Bestas118fcaf2015-06-04 23:02:20 +0300285def find_xml(base_path):
286 for dp, dn, file_names in os.walk(base_path):
Anthony Kingb8607632015-05-01 22:06:37 +0300287 for f in file_names:
288 if os.path.splitext(f)[1] == '.xml':
289 yield os.path.join(dp, f)
Marco Brohet6b6b4e52014-07-20 00:05:16 +0200290
Anthony Kingb8607632015-05-01 22:06:37 +0300291# ############################################################################ #
Marco Brohet6b6b4e52014-07-20 00:05:16 +0200292
Michael Bestas6b6db122015-02-08 13:22:22 +0200293
Anthony Kingb8607632015-05-01 22:06:37 +0300294def parse_args():
295 parser = argparse.ArgumentParser(
Abhisek Devkotab78def42016-12-27 13:06:52 -0800296 description="Synchronising LineageOS' translations with Crowdin")
Michael Bestasfd5d1362015-12-18 20:34:32 +0200297 parser.add_argument('-u', '--username', help='Gerrit username')
Abhisek Devkotab78def42016-12-27 13:06:52 -0800298 parser.add_argument('-b', '--branch', help='LineageOS branch',
Anthony Kingb8607632015-05-01 22:06:37 +0300299 required=True)
Michael Bestas2f8c4a52015-08-05 21:33:50 +0300300 parser.add_argument('-c', '--config', help='Custom yaml config')
Michael Bestasfd5d1362015-12-18 20:34:32 +0200301 parser.add_argument('--upload-sources', action='store_true',
302 help='Upload sources to Crowdin')
303 parser.add_argument('--upload-translations', action='store_true',
304 help='Upload translations to Crowdin')
305 parser.add_argument('--download', action='store_true',
306 help='Download translations from Crowdin')
Michael Wd13658a2019-01-13 14:05:37 +0100307 parser.add_argument('-s', '--submit', action='store_true',
308 help='Merge open translation commits')
Anthony Kingb8607632015-05-01 22:06:37 +0300309 return parser.parse_args()
Michael Bestas6b6db122015-02-08 13:22:22 +0200310
Anthony Kingb8607632015-05-01 22:06:37 +0300311# ################################# PREPARE ################################## #
Marco Brohet6b6b4e52014-07-20 00:05:16 +0200312
Anthony Kingb8607632015-05-01 22:06:37 +0300313
314def check_dependencies():
Michael Bestaseb4629a2018-11-14 23:03:18 +0200315 # Check for Java version of crowdin
316 cmd = ['dpkg-query', '-W', 'crowdin']
Anthony Kingb8607632015-05-01 22:06:37 +0300317 if run_subprocess(cmd, silent=True)[1] != 0:
Michael Bestaseb4629a2018-11-14 23:03:18 +0200318 print('You have not installed crowdin.', file=sys.stderr)
Anthony Kingb8607632015-05-01 22:06:37 +0300319 return False
Anthony Kingb8607632015-05-01 22:06:37 +0300320 return True
Marco Brohetcb5cdb42014-07-11 22:41:53 +0200321
Marco Brohetcb5cdb42014-07-11 22:41:53 +0200322
Michael Bestas118fcaf2015-06-04 23:02:20 +0300323def load_xml(x):
Anthony Kingb8607632015-05-01 22:06:37 +0300324 try:
325 return minidom.parse(x)
326 except IOError:
327 print('You have no %s.' % x, file=sys.stderr)
328 return None
329 except Exception:
330 # TODO: minidom should not be used.
331 print('Malformed %s.' % x, file=sys.stderr)
332 return None
Marco Brohet6b6b4e52014-07-20 00:05:16 +0200333
Michael Bestas4b26c4e2014-10-23 23:21:59 +0300334
Michael Bestas2f8c4a52015-08-05 21:33:50 +0300335def check_files(files):
Anthony Kingb8607632015-05-01 22:06:37 +0300336 for f in files:
337 if not os.path.isfile(f):
338 print('You have no %s.' % f, file=sys.stderr)
339 return False
Anthony Kingb8607632015-05-01 22:06:37 +0300340 return True
Michael Bestas4b26c4e2014-10-23 23:21:59 +0300341
Anthony Kingb8607632015-05-01 22:06:37 +0300342# ################################### MAIN ################################### #
Michael Bestas4b26c4e2014-10-23 23:21:59 +0300343
Michael Bestas4b26c4e2014-10-23 23:21:59 +0300344
Michael Bestasfd5d1362015-12-18 20:34:32 +0200345def upload_sources_crowdin(branch, config):
Michael Bestas2f8c4a52015-08-05 21:33:50 +0300346 if config:
Michael Bestasfd5d1362015-12-18 20:34:32 +0200347 print('\nUploading sources to Crowdin (custom config)')
Michael Bestaseb4629a2018-11-14 23:03:18 +0200348 check_run(['crowdin',
Michael Bestas03bc7052016-03-12 03:19:10 +0200349 '--config=%s/config/%s' % (_DIR, config),
Michael Bestas44fbb352015-12-17 02:01:42 +0200350 'upload', 'sources', '--branch=%s' % branch])
Michael Bestas2f8c4a52015-08-05 21:33:50 +0300351 else:
Michael Bestasfd5d1362015-12-18 20:34:32 +0200352 print('\nUploading sources to Crowdin (AOSP supported languages)')
Michael Bestaseb4629a2018-11-14 23:03:18 +0200353 check_run(['crowdin',
Michael Bestas03bc7052016-03-12 03:19:10 +0200354 '--config=%s/config/%s.yaml' % (_DIR, branch),
Michael Bestas44fbb352015-12-17 02:01:42 +0200355 'upload', 'sources', '--branch=%s' % branch])
Anthony King69a95382015-02-08 18:44:10 +0000356
Michael Bestasfd5d1362015-12-18 20:34:32 +0200357 print('\nUploading sources to Crowdin (non-AOSP supported languages)')
Michael Bestaseb4629a2018-11-14 23:03:18 +0200358 check_run(['crowdin',
Michael Bestas03bc7052016-03-12 03:19:10 +0200359 '--config=%s/config/%s_aosp.yaml' % (_DIR, branch),
Michael Bestas44fbb352015-12-17 02:01:42 +0200360 'upload', 'sources', '--branch=%s' % branch])
Anthony Kingb8607632015-05-01 22:06:37 +0300361
362
Michael Bestasfd5d1362015-12-18 20:34:32 +0200363def upload_translations_crowdin(branch, config):
Michael Bestas2f8c4a52015-08-05 21:33:50 +0300364 if config:
Michael Bestasfd5d1362015-12-18 20:34:32 +0200365 print('\nUploading translations to Crowdin (custom config)')
Michael Bestaseb4629a2018-11-14 23:03:18 +0200366 check_run(['crowdin',
Michael Bestas03bc7052016-03-12 03:19:10 +0200367 '--config=%s/config/%s' % (_DIR, config),
Michael Bestasfd5d1362015-12-18 20:34:32 +0200368 'upload', 'translations', '--branch=%s' % branch,
369 '--no-import-duplicates', '--import-eq-suggestions',
370 '--auto-approve-imported'])
371 else:
372 print('\nUploading translations to Crowdin '
373 '(AOSP supported languages)')
Michael Bestaseb4629a2018-11-14 23:03:18 +0200374 check_run(['crowdin',
Michael Bestas03bc7052016-03-12 03:19:10 +0200375 '--config=%s/config/%s.yaml' % (_DIR, branch),
Michael Bestasfd5d1362015-12-18 20:34:32 +0200376 'upload', 'translations', '--branch=%s' % branch,
377 '--no-import-duplicates', '--import-eq-suggestions',
378 '--auto-approve-imported'])
379
380 print('\nUploading translations to Crowdin '
381 '(non-AOSP supported languages)')
Michael Bestaseb4629a2018-11-14 23:03:18 +0200382 check_run(['crowdin',
Michael Bestas03bc7052016-03-12 03:19:10 +0200383 '--config=%s/config/%s_aosp.yaml' % (_DIR, branch),
Michael Bestasfd5d1362015-12-18 20:34:32 +0200384 'upload', 'translations', '--branch=%s' % branch,
385 '--no-import-duplicates', '--import-eq-suggestions',
386 '--auto-approve-imported'])
387
388
Michael Bestas80b22ef2018-11-14 23:12:33 +0200389def download_crowdin(base_path, branch, xml, username, config):
Michael Bestasfd5d1362015-12-18 20:34:32 +0200390 if config:
391 print('\nDownloading translations from Crowdin (custom config)')
Michael Bestaseb4629a2018-11-14 23:03:18 +0200392 check_run(['crowdin',
Michael Bestas03bc7052016-03-12 03:19:10 +0200393 '--config=%s/config/%s' % (_DIR, config),
Michael Bestas44fbb352015-12-17 02:01:42 +0200394 'download', '--branch=%s' % branch])
Michael Bestas2f8c4a52015-08-05 21:33:50 +0300395 else:
Michael Bestasfd5d1362015-12-18 20:34:32 +0200396 print('\nDownloading translations from Crowdin '
397 '(AOSP supported languages)')
Michael Bestaseb4629a2018-11-14 23:03:18 +0200398 check_run(['crowdin',
Michael Bestas03bc7052016-03-12 03:19:10 +0200399 '--config=%s/config/%s.yaml' % (_DIR, branch),
Michael Bestas44fbb352015-12-17 02:01:42 +0200400 'download', '--branch=%s' % branch])
Michael Bestas50579d22014-08-09 17:49:14 +0300401
Michael Bestasfd5d1362015-12-18 20:34:32 +0200402 print('\nDownloading translations from Crowdin '
Michael Bestas2f8c4a52015-08-05 21:33:50 +0300403 '(non-AOSP supported languages)')
Michael Bestaseb4629a2018-11-14 23:03:18 +0200404 check_run(['crowdin',
Michael Bestas03bc7052016-03-12 03:19:10 +0200405 '--config=%s/config/%s_aosp.yaml' % (_DIR, branch),
Michael Bestas44fbb352015-12-17 02:01:42 +0200406 'download', '--branch=%s' % branch])
Marco Brohetcb5cdb42014-07-11 22:41:53 +0200407
Michael Bestas99f5fce2015-06-04 22:07:51 +0300408 print('\nCreating a list of pushable translations')
Michael Bestas919053f2014-10-20 23:30:54 +0300409 # Get all files that Crowdin pushed
Anthony Kingb8607632015-05-01 22:06:37 +0300410 paths = []
Michael Bestas2f8c4a52015-08-05 21:33:50 +0300411 if config:
Michael Bestas03bc7052016-03-12 03:19:10 +0200412 files = ['%s/config/%s' % (_DIR, config)]
Michael Bestas2f8c4a52015-08-05 21:33:50 +0300413 else:
Michael Bestas03bc7052016-03-12 03:19:10 +0200414 files = ['%s/config/%s.yaml' % (_DIR, branch),
415 '%s/config/%s_aosp.yaml' % (_DIR, branch)]
Michael Bestas6c327e62015-05-02 01:58:01 +0300416 for c in files:
Michael Bestaseb4629a2018-11-14 23:03:18 +0200417 cmd = ['crowdin', '--config=%s' % c, 'list', 'project',
Michael Bestas44fbb352015-12-17 02:01:42 +0200418 '--branch=%s' % branch]
Anthony Kingb8607632015-05-01 22:06:37 +0300419 comm, ret = run_subprocess(cmd)
420 if ret != 0:
421 sys.exit(ret)
422 for p in str(comm[0]).split("\n"):
423 paths.append(p.replace('/%s' % branch, ''))
Michael Bestas50579d22014-08-09 17:49:14 +0300424
Michael Bestas99f5fce2015-06-04 22:07:51 +0300425 print('\nUploading translations to Gerrit')
Anthony Kingb8607632015-05-01 22:06:37 +0300426 items = [x for sub in xml for x in sub.getElementsByTagName('project')]
Michael Bestas919053f2014-10-20 23:30:54 +0300427 all_projects = []
428
Anthony Kingb8607632015-05-01 22:06:37 +0300429 for path in paths:
430 path = path.strip()
Michael Bestas919053f2014-10-20 23:30:54 +0300431 if not path:
432 continue
433
Anthony Kingb8607632015-05-01 22:06:37 +0300434 if "/res" not in path:
435 print('WARNING: Cannot determine project root dir of '
436 '[%s], skipping.' % path)
Anthony King69a95382015-02-08 18:44:10 +0000437 continue
Michael W67f14932019-03-11 09:59:32 +0100438
439 # Usually the project root is everything before /res
440 # but there are special cases where /res is part of the repo name as well
441 parts = path.split("/res")
442 if len(parts) == 2:
443 result = parts[0]
444 elif len(parts) == 3:
445 result = parts[0] + '/res' + parts[1]
446 else:
447 print('WARNING: Splitting the path not successful for [%s], skipping' % path)
448 continue
449
450 result = result.strip('/')
Anthony Kingb8607632015-05-01 22:06:37 +0300451 if result == path.strip('/'):
452 print('WARNING: Cannot determine project root dir of '
453 '[%s], skipping.' % path)
454 continue
Marco Brohet6b6b4e52014-07-20 00:05:16 +0200455
Michael Bestasc899b8c2015-03-03 00:53:19 +0200456 if result in all_projects:
Michael Bestasc899b8c2015-03-03 00:53:19 +0200457 continue
Michael Bestas50579d22014-08-09 17:49:14 +0300458
Anthony Kingb8607632015-05-01 22:06:37 +0300459 # When a project has multiple translatable files, Crowdin will
460 # give duplicates.
461 # We don't want that (useless empty commits), so we save each
462 # project in all_projects and check if it's already in there.
Michael Bestasc899b8c2015-03-03 00:53:19 +0200463 all_projects.append(result)
Anthony King69a95382015-02-08 18:44:10 +0000464
Michael Bestas42e25e32016-03-12 20:18:39 +0200465 # Search android/default.xml or config/%(branch)_extra_packages.xml
Anthony Kingb8607632015-05-01 22:06:37 +0300466 # for the project's name
Michael W1f187762019-03-11 19:38:00 +0100467 resultPath = None
468 resultProject = None
Anthony Kingb8607632015-05-01 22:06:37 +0300469 for project in items:
470 path = project.attributes['path'].value
471 if not (result + '/').startswith(path +'/'):
Michael Bestasc899b8c2015-03-03 00:53:19 +0200472 continue
Michael W1f187762019-03-11 19:38:00 +0100473 # We want the longest match, so projects in subfolders of other projects are also
474 # taken into account
475 if resultPath is None or len(path) > len(resultPath):
476 resultPath = path
477 resultProject = project
Anthony King69a95382015-02-08 18:44:10 +0000478
Michael W1f187762019-03-11 19:38:00 +0100479 # Just in case no project was found
480 if resultPath is None:
481 continue
Anthony King69a95382015-02-08 18:44:10 +0000482
Michael W1f187762019-03-11 19:38:00 +0100483 if result != resultPath:
484 if resultPath in all_projects:
485 continue
486 result = resultPath
487 all_projects.append(result)
488
489 br = resultProject.getAttribute('revision') or branch
490
491 push_as_commit(files, base_path, result,
492 resultProject.getAttribute('name'), br, username)
Anthony King69a95382015-02-08 18:44:10 +0000493
Anthony King69a95382015-02-08 18:44:10 +0000494
Anthony Kingb8607632015-05-01 22:06:37 +0300495def main():
Anthony Kingb8607632015-05-01 22:06:37 +0300496 args = parse_args()
497 default_branch = args.branch
Michael Bestas118fcaf2015-06-04 23:02:20 +0300498
Michael Wd13658a2019-01-13 14:05:37 +0100499 if args.submit:
500 if args.username is None:
501 print('Argument -u/--username is required for submitting!')
502 sys.exit(1)
503 submit_gerrit(default_branch, args.username)
504 sys.exit(0)
505
Michael Bestaseb4629a2018-11-14 23:03:18 +0200506 base_path_branch_suffix = default_branch.replace('-', '_').replace('.', '_').upper()
507 base_path_env = 'LINEAGE_CROWDIN_BASE_PATH_%s' % base_path_branch_suffix
508 base_path = os.getenv(base_path_env)
Michael Bestas118fcaf2015-06-04 23:02:20 +0300509 if base_path is None:
Anthony Kingd0d56cf2015-06-05 10:48:38 +0100510 cwd = os.getcwd()
Michael Bestaseb4629a2018-11-14 23:03:18 +0200511 print('You have not set %s. Defaulting to %s' % (base_path_env, cwd))
Michael Bestas118fcaf2015-06-04 23:02:20 +0300512 base_path = cwd
Michael Bestas118fcaf2015-06-04 23:02:20 +0300513 if not os.path.isdir(base_path):
Michael Bestaseb4629a2018-11-14 23:03:18 +0200514 print('%s is not a real directory: %s' % (base_path_env, base_path))
Michael Bestas118fcaf2015-06-04 23:02:20 +0300515 sys.exit(1)
Anthony Kingb8607632015-05-01 22:06:37 +0300516
Michael Bestas99f5fce2015-06-04 22:07:51 +0300517 if not check_dependencies():
518 sys.exit(1)
Anthony Kingb8607632015-05-01 22:06:37 +0300519
Michael Bestas118fcaf2015-06-04 23:02:20 +0300520 xml_android = load_xml(x='%s/android/default.xml' % base_path)
Anthony Kingb8607632015-05-01 22:06:37 +0300521 if xml_android is None:
522 sys.exit(1)
523
Michael Bestas42e25e32016-03-12 20:18:39 +0200524 xml_extra = load_xml(x='%s/config/%s_extra_packages.xml'
Anthony Kingd0d56cf2015-06-05 10:48:38 +0100525 % (_DIR, default_branch))
Anthony Kingb8607632015-05-01 22:06:37 +0300526 if xml_extra is None:
527 sys.exit(1)
528
Michael Bestas19dc3352018-02-03 20:24:00 +0200529 xml_snippet = load_xml(x='%s/android/snippets/lineage.xml' % base_path)
530 if xml_snippet is None:
531 xml_snippet = load_xml(x='%s/android/snippets/cm.xml' % base_path)
532 if xml_snippet is None:
533 xml_snippet = load_xml(x='%s/android/snippets/hal_cm_all.xml' % base_path)
534 if xml_snippet is not None:
535 xml_files = (xml_android, xml_snippet, xml_extra)
Michael Bestas687679f2016-12-07 23:20:12 +0200536 else:
537 xml_files = (xml_android, xml_extra)
538
Michael Bestas2f8c4a52015-08-05 21:33:50 +0300539 if args.config:
Michael Bestas03bc7052016-03-12 03:19:10 +0200540 files = ['%s/config/%s' % (_DIR, args.config)]
Michael Bestas2f8c4a52015-08-05 21:33:50 +0300541 else:
Michael Bestas03bc7052016-03-12 03:19:10 +0200542 files = ['%s/config/%s.yaml' % (_DIR, default_branch),
543 '%s/config/%s_aosp.yaml' % (_DIR, default_branch)]
Michael Bestas2f8c4a52015-08-05 21:33:50 +0300544 if not check_files(files):
Anthony Kingb8607632015-05-01 22:06:37 +0300545 sys.exit(1)
546
Michael Bestasfd5d1362015-12-18 20:34:32 +0200547 if args.download and args.username is None:
548 print('Argument -u/--username is required for translations download')
549 sys.exit(1)
550
551 if args.upload_sources:
552 upload_sources_crowdin(default_branch, args.config)
553 if args.upload_translations:
554 upload_translations_crowdin(default_branch, args.config)
555 if args.download:
Michael Bestas687679f2016-12-07 23:20:12 +0200556 download_crowdin(base_path, default_branch, xml_files,
Michael Bestas80b22ef2018-11-14 23:12:33 +0200557 args.username, args.config)
Tom Powell44256852016-07-06 15:23:25 -0700558
559 if _COMMITS_CREATED:
560 print('\nDone!')
561 sys.exit(0)
Tom Powellf42586f2016-07-11 11:02:54 -0700562 else:
Tom Powell44256852016-07-06 15:23:25 -0700563 print('\nNothing to commit')
564 sys.exit(-1)
Anthony Kingb8607632015-05-01 22:06:37 +0300565
566if __name__ == '__main__':
567 main()