-
-
Notifications
You must be signed in to change notification settings - Fork 964
/
base.py
365 lines (301 loc) · 11.1 KB
/
base.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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
# -*- coding: utf-8 -*-
#
# Copyright © 2012 - 2020 Michal Čihař <michal@cihar.com>
#
# This file is part of Weblate <https://weblate.org/>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
#
import os
import subprocess
from itertools import chain
from django.core.exceptions import ValidationError
from django.utils.functional import cached_property
from django.utils.translation import gettext as _
from weblate.addons.events import (
EVENT_COMPONENT_UPDATE,
EVENT_DAILY,
EVENT_POST_COMMIT,
EVENT_POST_PUSH,
EVENT_POST_UPDATE,
EVENT_STORE_POST_LOAD,
)
from weblate.addons.forms import BaseAddonForm
from weblate.trans.exceptions import FileParseError
from weblate.trans.tasks import perform_update
from weblate.trans.util import get_clean_env
from weblate.utils import messages
from weblate.utils.render import render_template
from weblate.utils.validators import validate_filename
class BaseAddon:
events = ()
settings_form = None
name = None
compat = {}
multiple = False
verbose = 'Base addon'
description = 'Base addon'
icon = 'cog.svg'
project_scope = False
repo_scope = False
has_summary = False
alert = None
trigger_update = False
"""Base class for Weblate addons."""
def __init__(self, storage=None):
self.instance = storage
self.alerts = []
@cached_property
def doc_anchor(self):
return self.get_doc_anchor()
@classmethod
def get_doc_anchor(cls):
return 'addon-{}'.format(cls.name.replace('.', '-'))
@cached_property
def has_settings(self):
return self.settings_form is not None
@classmethod
def get_identifier(cls):
return cls.name
@classmethod
def create_object(cls, component, **kwargs):
from weblate.addons.models import Addon
if component:
# Reallocate to repository
if cls.repo_scope and component.linked_component:
component = component.linked_component
# Clear addon cache
component.addons_cache = None
return Addon(
component=component,
name=cls.name,
project_scope=cls.project_scope,
repo_scope=cls.repo_scope,
**kwargs
)
@classmethod
def create(cls, component, **kwargs):
storage = cls.create_object(component, **kwargs)
storage.save(force_insert=True)
result = cls(storage)
result.post_configure()
return result
@classmethod
def get_add_form(cls, component, **kwargs):
"""Return configuration form for adding new addon."""
if cls.settings_form is None:
return None
storage = cls.create_object(component)
instance = cls(storage)
# pylint: disable=not-callable
return cls.settings_form(instance, **kwargs)
def get_settings_form(self, **kwargs):
"""Return configuration for for this addon."""
if self.settings_form is None:
return None
if 'data' not in kwargs:
kwargs['data'] = self.instance.configuration
# pylint: disable=not-callable
return self.settings_form(self, **kwargs)
def configure(self, settings):
"""Save configuration."""
self.instance.configuration = settings
self.instance.save()
self.post_configure()
def post_configure(self):
# Configure events to current status
self.instance.configure_events(self.events)
# Trigger post events to ensure direct processing
if self.project_scope:
components = self.instance.component.project.component_set.all()
elif self.repo_scope:
if self.instance.component.linked_component:
root = self.instance.component.linked_component
else:
root = self.instance.component
components = [root] + list(root.linked_childs)
else:
components = [self.instance.component]
if EVENT_POST_COMMIT in self.events:
for component in components:
self.post_commit(component)
if EVENT_POST_UPDATE in self.events:
for component in components:
self.post_update(component, '')
if EVENT_COMPONENT_UPDATE in self.events:
for component in components:
self.component_update(component)
if EVENT_POST_PUSH in self.events:
for component in components:
self.post_push(component)
if EVENT_DAILY in self.events:
for component in components:
self.daily(component)
def save_state(self):
"""Save addon state information."""
self.instance.save(update_fields=['state'])
@classmethod
def can_install(cls, component, user):
"""Check whether addon is compatible with given component."""
for key, values in cls.compat.items():
if getattr(component, key) not in values:
return False
return True
def pre_push(self, component):
return
def post_push(self, component):
return
def pre_update(self, component):
return
def post_update(self, component, previous_head):
return
def post_commit(self, component, translation=None):
return
def pre_commit(self, translation, author):
return
def post_add(self, translation):
return
def unit_pre_create(self, unit):
return
def store_post_load(self, translation, store):
return
def daily(self, component):
return
def component_update(self, component):
return
def execute_process(self, component, cmd, env=None):
component.log_debug('%s addon exec: %s', self.name, repr(cmd))
try:
output = subprocess.check_output(
cmd,
env=get_clean_env(env),
cwd=component.full_path,
stderr=subprocess.STDOUT,
)
component.log_debug('exec result: %s', repr(output))
except (OSError, subprocess.CalledProcessError) as err:
output = getattr(err, 'output', '').decode('utf-8')
component.log_error('failed to exec %s: %s', repr(cmd), err)
for line in output.splitlines():
component.log_error('program output: %s', line)
self.alerts.append(
{
'addon': self.name,
'command': ' '.join(cmd),
'output': output,
'error': str(err),
}
)
def trigger_alerts(self, component):
if self.alerts:
component.add_alert(self.alert, occurrences=self.alerts)
self.alerts = []
else:
component.delete_alert(self.alert)
def get_commit_message(self, component):
return render_template(
component.addon_message,
# Compatibility with older
hook_name=self.verbose,
addon_name=self.verbose,
component=component,
)
def commit_and_push(self, component, files=None):
if files is None:
files = list(
chain.from_iterable(
translation.filenames
for translation in component.translation_set.iterator()
)
)
files += self.extra_files
repository = component.repository
with repository.lock:
if repository.needs_commit():
repository.commit(self.get_commit_message(component), files=files)
component.push_if_needed(None)
def render_repo_filename(self, template, translation):
component = translation.component
# Render the template
filename = render_template(template, translation=translation)
# Validate filename (not absolute or linking to parent dir)
try:
validate_filename(filename)
except ValidationError:
return None
# Absolute path
filename = os.path.join(component.full_path, filename)
# Check if parent directory exists
dirname = os.path.dirname(filename)
if not os.path.exists(dirname):
os.makedirs(dirname)
# Validate if there is not a symlink out of the tree
try:
component.repository.resolve_symlinks(dirname)
if os.path.exists(filename):
component.repository.resolve_symlinks(filename)
except ValueError:
component.log_error('refused to write out of repository: %s', filename)
return None
return filename
@classmethod
def pre_install(cls, component, request):
if cls.trigger_update:
perform_update.delay('Component', component.pk, auto=True)
if component.repo_needs_merge():
messages.warning(
request,
_(
'The repository is outdated, you might not get '
'expected results until you update it.'
),
)
class TestAddon(BaseAddon):
"""Testing addong doing nothing."""
settings_form = BaseAddonForm
name = 'weblate.base.test'
verbose = 'Test addon'
description = 'Test addon'
class UpdateBaseAddon(BaseAddon):
"""Base class for addons updating translation files.
It hooks to post update and commits all changed translations.
"""
events = (EVENT_POST_UPDATE,)
def __init__(self, storage=None):
super(UpdateBaseAddon, self).__init__(storage)
self.extra_files = []
def update_translations(self, component, previous_head):
raise NotImplementedError()
def post_update(self, component, previous_head):
component.commit_pending('addon', None, skip_push=True)
try:
self.update_translations(component, previous_head)
except FileParseError:
# Ignore file parse error, it will be properly tracked as an alert
pass
self.commit_and_push(component)
class TestException(Exception):
pass
class TestCrashAddon(UpdateBaseAddon):
"""Testing addong doing nothing."""
name = 'weblate.base.crash'
verbose = 'Crash test addon'
description = 'Crash test addon'
def update_translations(self, component, previous_head):
if previous_head:
raise TestException('Test error')
class StoreBaseAddon(BaseAddon):
"""Base class for addons tweaking store."""
events = (EVENT_STORE_POST_LOAD,)
icon = 'wrench.svg'