-
Notifications
You must be signed in to change notification settings - Fork 0
/
modularity-helper.py
executable file
·228 lines (161 loc) · 6.63 KB
/
modularity-helper.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
#!/usr/bin/python3
from os import getenv, chdir
from io import BytesIO
try:
from koji import ClientSession as ServerProxy
except ImportError:
from xmlrpc.client import ServerProxy
import subprocess
import logging
from babel.messages import pofile
from flask import Flask, request, jsonify
from tempfile import TemporaryDirectory
from ModulemdTranslationHelpers import get_module_catalog_from_tags
from ModulemdTranslationHelpers.Fedora import get_fedora_rawhide_version
from ModulemdTranslationHelpers.Fedora import get_tags_for_fedora_branch
from ModulemdTranslationHelpers.Fedora import KOJI_URL
from apscheduler.schedulers.background import BackgroundScheduler
from datetime import datetime, timedelta
application = Flask(__name__)
potfile_name = getenv('POTFILE_NAME',
default='fedora-modularity-translations.pot')
zanata_url = getenv('ZANATA_URL',
default='https://fedora.zanata.org')
zanata_project = getenv('ZANATA_PROJECT',
default='fedora-modularity-translations')
zanata_user = getenv('ZANATA_USER')
zanata_key = getenv('ZANATA_KEY')
koji_url = getenv('KOJI_URL', KOJI_URL)
def application_init():
# Validate that we have mandatory env vars
zanata_user = getenv('ZANATA_USER')
if not zanata_user:
raise PermissionError('No Zanata user specified')
zanata_key = getenv('ZANATA_KEY')
if not zanata_key:
raise PermissionError('No Zanata key specified')
flask_debug = getenv('FLASK_ENV')
if flask_debug is not None:
logging.basicConfig(level=logging.DEBUG)
else:
logging.basicConfig(level=logging.INFO)
scheduler = BackgroundScheduler()
# Update translatable strings every 30 minutes
scheduler.add_job(update_pot_for_all_branches,
'interval', minutes=30)
# And once, five seconds after startup
scheduler.add_job(update_pot_for_all_branches, 'date',
run_date=datetime.now()+timedelta(0, 5))
scheduler.start()
def get_branch(koji_session, args):
if 'branch' not in args:
input_branch = 'rawhide'
else:
input_branch = str(args['branch'])
if input_branch == 'rawhide':
branch = get_fedora_rawhide_version(koji_session)
else:
branch = input_branch
return branch
@application.route("/alive")
def heartbeat():
return jsonify({'result': 'Succeeded'})
@application.route("/strings")
def get_pot():
result = dict()
result['state'] = 'Failed'
koji_session = ServerProxy(koji_url)
result['branch'] = get_branch(koji_session, request.args)
# Retrieve content
tags = get_tags_for_fedora_branch(result['branch'])
catalog = get_module_catalog_from_tags(koji_session, tags)
potfile_io = BytesIO()
pofile.write_po(potfile_io, catalog, sort_by_file=True)
result['potfile'] = potfile_io.getvalue().decode('utf8')
result['state'] = 'Succeeded'
return jsonify(result)
def do_update_pot(koji_session, branch):
result = dict()
result['state'] = 'Failed'
result['branch'] = branch
application.logger.info('Updating translations for %s' % branch)
# Retrieve content
tags = get_tags_for_fedora_branch(branch)
catalog = get_module_catalog_from_tags(koji_session, tags)
with TemporaryDirectory() as tdir:
chdir(tdir)
# Create a temporary file to upload to Zanata
with open(potfile_name, 'wb') as potfile:
pofile.write_po(potfile, catalog, sort_by_file=True)
# Use the zanata-cli to upload the pot file
# It would be better to use the REST API directly here, but the XML
# payload format is not documented.
# Dump the user config locally so the key doesn't show up in the
# process table.
with open('zanata.ini', 'w') as inifile:
inifile.write('[servers]\n')
inifile.write('zanata.url=%s\n' % zanata_url)
inifile.write('zanata.username=%s\n' % zanata_user)
inifile.write('zanata.key=%s\n' % zanata_key)
# Ensure that the requested branch exists in Zanata
zanata_args = [
'/usr/bin/zanata-cli', '-B', '-e', 'put-version',
'--url', zanata_url,
'--version-project', zanata_project,
'--version-slug', branch,
'--user-config', 'zanata.ini',
]
status = subprocess.run(zanata_args, capture_output=True)
if status.returncode:
logging.warning("Error running Zanata CLI to ensure branch "
"existence.")
logging.warning("STDOUT: %s" % status.stdout.decode('utf-8'))
logging.warning("STDERR: %s" % status.stderr.decode('utf-8'))
result['errorcode'] = status.returncode
result['message'] = "Could not create branch in Zanata. " \
"Permission error?"
return result
# Update the translatable strings for this branch
zanata_args = [
'/usr/bin/zanata-cli', '-B', '-e', 'push',
'--url', zanata_url,
'--project', zanata_project,
'--project-type', 'gettext',
'--project-version', branch,
'--src-dir', tdir,
'--user-config', 'zanata.ini',
]
status = subprocess.run(zanata_args, capture_output=True)
if status.returncode:
logging.warning("Error running Zanata CLI to update translatable"
"strings.")
logging.warning("STDOUT: %s" % status.stdout.decode('utf-8'))
logging.warning("STDERR: %s" % status.stderr.decode('utf-8'))
result['errorcode'] = status.returncode
result['message'] = "Could not update strings in Zanata."
return result
result['state'] = 'Succeeded'
result['message'] = 'Uploaded translatable strings for %s to Zanata' % (
branch)
return result
@application.route("/strings/update")
def update_pot(branch=None):
koji_session = ServerProxy(koji_url)
if not branch:
branch = get_branch(koji_session, request.args)
result = do_update_pot(koji_session, branch)
return jsonify(result)
def update_pot_for_all_branches():
# Get the list of supported Fedora releases
# TODO: Detect this automatically
for branch in ['f28', 'f29', 'f30']:
koji_session = ServerProxy(koji_url)
result = do_update_pot(koji_session, branch)
if result['state'] == 'Failed':
application.logger.error("%d: %s" % (
result['errorcode'], result['message']))
application_init()
def main():
application.run()
if __name__ == "__main__":
main()