/
txt.py
265 lines (219 loc) · 7.69 KB
/
txt.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
#
# Copyright © 2012–2022 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/>.
#
"""Plain text file formats."""
import os
from glob import glob
from itertools import chain
from typing import Callable, List, Optional, Tuple, Union
from django.utils.functional import cached_property
from django.utils.translation import gettext_lazy as _
from weblate.formats.base import TranslationFormat, TranslationUnit
from weblate.utils.errors import report_error
class MultiparserError(Exception):
def __init__(self, filename, original):
super().__init__()
self.filename = filename
self.original = original
def __str__(self):
return f"{self.filename}: {self.original}"
class TextItem:
"""Actual text unit object."""
def __init__(self, filename, line, text, flags=None):
self.filename = filename
self.line = line
self.text = text
self.flags = flags
@cached_property
def location(self):
return f"{self.filename}:{self.line}"
def getid(self):
return self.location
class TextParser:
"""Simple text parser returning all content as single unit."""
def __init__(self, storefile, filename=None, flags=None):
with open(storefile) as handle:
content = handle.read()
if filename:
self.filename = filename
else:
self.filename = os.path.basename(storefile)
self.units = [TextItem(self.filename, 1, content.strip(), flags)]
class TextSerializer:
def __init__(self, filename, units):
self.units = [unit for unit in units if unit.filename == filename]
def __call__(self, handle):
for unit in self.units:
handle.write(unit.text.encode())
handle.write(b"\n")
class MultiParser:
filenames: Tuple[Tuple[str, str], ...] = ()
def __init__(self, storefile):
if not isinstance(storefile, str):
raise ValueError("Needs string as a storefile!")
self.base = storefile
self.parsers = self.load_parser()
self.units = list(
chain.from_iterable(parser.units for parser in self.parsers.values())
)
def file_key(self, filename):
return filename
def load_parser(self):
result = {}
for name, flags in self.filenames:
filename = self.get_filename(name)
for match in sorted(glob(filename), key=self.file_key):
# Needed to allow overlapping globs, more specific first
if match in result:
continue
try:
result[match] = TextParser(
match, os.path.relpath(match, self.base), flags
)
except Exception as error:
raise MultiparserError(match, error)
return result
def get_filename(self, name):
return os.path.join(self.base, name)
class AppStoreParser(MultiParser):
filenames = (
("title.txt", "max-length:30"),
("short[_-]description.txt", "max-length:80"),
("full[_-]description.txt", "max-length:4000"),
("subtitle.txt", "max-length:80"),
("description.txt", "max-length:4000"),
("keywords.txt", "max-length:100"),
("video.txt", "max-length:256, url"),
("marketing_url.txt", "max-length:256, url"),
("privacy_url.txt", "max-length:256, url"),
("support_url.txt", "max-length:256, url"),
("changelogs/*.txt", "max-length:500"),
("*.txt", ""),
)
def file_key(self, filename):
parts = filename.rsplit("changelogs/", 1)
if len(parts) == 2:
try:
return "-{}".format(int(parts[1].split(".")[0]))
except ValueError:
pass
return filename
class TextUnit(TranslationUnit):
@cached_property
def locations(self):
"""Return comma separated list of locations."""
return self.mainunit.location
@cached_property
def source(self):
"""Return source string from a ttkit unit."""
if self.template is not None:
return self.template.text
return self.unit.text
@cached_property
def target(self):
"""Return target string from a ttkit unit."""
if self.unit is None:
return ""
return self.unit.text
@cached_property
def context(self):
"""Return context of message."""
return self.mainunit.location
@cached_property
def flags(self):
"""Return flags from unit."""
if self.mainunit.flags:
return self.mainunit.flags
return ""
def set_target(self, target: Union[str, List[str]]):
"""Set translation unit target."""
self._invalidate_target()
self.unit.text = target
def set_state(self, state):
"""Set fuzzy /approved flag on translated unit."""
return
class AppStoreFormat(TranslationFormat):
name = _("App store metadata files")
format_id = "appstore"
can_add_unit = False
monolingual = True
unit_class = TextUnit
simple_filename = False
language_format = "appstore"
create_style = "directory"
def load(self, storefile, template_store):
return AppStoreParser(storefile)
def create_unit(
self,
key: str,
source: Union[str, List[str]],
target: Optional[Union[str, List[str]]] = None,
):
raise ValueError("Create not supported")
@classmethod
def create_new_file(
cls,
filename: str,
language: str,
base: str,
callback: Optional[Callable] = None,
):
"""Handle creation of new translation file."""
os.makedirs(filename)
def add_unit(self, ttkit_unit):
"""Add new unit to underlying store."""
self.store.units.append(ttkit_unit)
def save(self):
"""Save underlying store to disk."""
for unit in self.store.units:
filename = self.store.get_filename(unit.filename)
if not unit.text:
if os.path.exists(filename):
os.unlink(filename)
continue
self.save_atomic(
filename,
TextSerializer(unit.filename, self.store.units),
)
def get_filenames(self):
return [self.store.get_filename(unit.filename) for unit in self.store.units]
@classmethod
def get_class(cls):
return None
@classmethod
def is_valid_base_for_new(
cls,
base: str,
monolingual: bool,
errors: Optional[List] = None,
fast: bool = False,
) -> bool:
"""Check whether base is valid."""
if not base:
return True
try:
if not fast:
AppStoreParser(base)
return True
except Exception:
report_error(cause="File parse error")
return False
def delete_unit(self, ttkit_unit) -> Optional[str]:
filename = self.store.get_filename(ttkit_unit.filename)
os.unlink(filename)
return filename