Debian Codegraph @

third_party/python/moz.l10n/moz/l10n/resource/android/serialize.py

raw
1 # Copyright Mozilla Foundation
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 from __future__ import annotations
16
17 from collections.abc import Iterator
18 from re import compile
19 from typing import Dict, cast
20
21 from lxml import etree
22
23 from ...message import (
24 CatchallKey,
25 Expression,
26 FunctionAnnotation,
27 Message,
28 Pattern,
29 PatternMessage,
30 SelectMessage,
31 VariableRef,
32 )
33 from ..data import Entry, Metadata, Resource
34 from .parse import plural_categories, resource_ref, xliff_g, xliff_ns, xml_name
35
36
37 def android_serialize(
38 resource: Resource[str, str] | Resource[Message, str],
39 trim_comments: bool = False,
40 ) -> Iterator[str]:
41 """
42 Serialize a resource as an Android strings XML file.
43
44 Section comments and metadata are not supported.
45 Resource and entry metadata must be stringifiable,
46 as they're stored in XML attributes.
47
48 Messages in '!ENTITY' sections are included in a !DOCTYPE declaration.
49 Otherwise, sections must be anonymous.
50
51 Multi-part message identifiers are only supported for <string-array>
52 values, for which the second part must be convertible to an int.
53
54 Expressions with a "translate": "no" attribute
55 will be wrapped with an <xliff:g> element.
56 If such an expression includes a "source" attribute,
57 that will be used as the element body
58 instead of the literal string or variable name;
59 any variable name will be assigned to the element's "id" attribute.
60
61 Markup with a "translate": "no" attribute on both the open and close elements
62 will be rendered as <xliff:g> elements.
63
64 Except for "entity" and "reference", function annotations are ignored.
65 """
66
67 yield '<?xml version="1.0" encoding="utf-8"?>\n'
68 if resource.comment and not trim_comments:
69 yield f"\n<!--{comment_body(resource.comment, 0)}-->\n\n"
70
71 # The nsmap needs to be set during creation
72 # https://bugs.launchpad.net/lxml/+bug/555602
73 root_nsmap: dict[str | None, str] = {}
74 root_attrib = {}
75 for m in resource.meta:
76 k = m.key
77 v = str(m.value)
78 if k == "xmlns":
79 root_nsmap[None] = v
80 elif k.startswith("xmlns:"):
81 root_nsmap[k[6:]] = v
82 else:
83 root_attrib[k] = v
84 root = etree.Element("resources", attrib=root_attrib, nsmap=root_nsmap)
85
86 entities = []
87 string_array = None
88 for section in resource.sections:
89 if section.meta:
90 raise ValueError("Section metadata is not supported")
91 if section.comment and not trim_comments:
92 add_comment(root, section.comment, True)
93 if section.id:
94 if section.id == ("!ENTITY",):
95 for entry in section.entries:
96 if isinstance(entry, Entry):
97 entities.append(entity_definition(entry))
98 continue
99 else:
100 raise ValueError(f"Unsupported section id: {section.id}")
101
102 for entry in section.entries:
103 if isinstance(entry, Entry):
104 if len(entry.id) not in (1, 2):
105 raise ValueError(f"Unsupported entry id: {entry.id or entry}")
106 name = entry.id[0]
107 if not xml_name.fullmatch(name):
108 raise ValueError(f"Invalid entry name: {name}")
109 if len(entry.id) == 1:
110 attrib = get_attrib(name, entry.meta)
111 if isinstance(entry.value, SelectMessage):
112 # <plurals>
113 el = etree.SubElement(root, "plurals", attrib=attrib)
114 if entry.comment and not trim_comments:
115 add_comment(el, entry.comment, False)
116 set_plural_message(el, entry.value)
117 else:
118 # <string>
119 if entry.comment and not trim_comments:
120 add_comment(root, entry.comment, False)
121 el = etree.SubElement(root, "string", attrib=attrib)
122 set_pattern_message(el, entry.value)
123 else:
124 # <string-array>
125 if string_array is None or name != string_array.get("name"):
126 string_array = etree.SubElement(
127 root, "string-array", attrib=get_attrib(name, entry.meta)
128 )
129 if entry.comment and not trim_comments:
130 add_comment(string_array, entry.comment, False)
131 set_string_array_item(string_array, entry)
132 elif not trim_comments:
133 add_comment(string_array or root, entry.comment, True)
134
135 etree.cleanup_namespaces(root, {"xliff": xliff_ns})
136
137 # Can't use the built-in pretty-printing,
138 # as standalone comments need a trailing empty line.
139 if len(root) == 0:
140 root.text = "\n"
141 else:
142 root.text = "\n "
143 for el in root:
144 if not el.tail:
145 el.tail = "\n "
146 if el.tag in ("plurals", "string-array"):
147 if len(el) == 0:
148 el.text = "\n "
149 else:
150 el.text = "\n "
151 for item in el:
152 item.tail = "\n "
153 el[-1].tail = "\n "
154 root[-1].tail = "\n"
155
156 if entities:
157 yield "<!DOCTYPE resources [\n"
158 for entity in entities:
159 yield f" {entity}\n"
160 yield "]>\n"
161 yield etree.tostring(root, encoding="unicode", method="html")
162 yield "\n"
163
164
165 def get_attrib(name: str, meta: list[Metadata[str]]) -> dict[str, str]:
166 res = {"name": name}
167 for m in meta:
168 if m.key == "name":
169 raise ValueError(f'Unsupported "name" metadata for {name}')
170 res[m.key] = m.value
171 return res
172
173
174 def comment_body(content: str, indent: int) -> str:
175 # Comments can't include --, so add a zero width space between and after dashes beyond the first
176 cc = content.strip().replace("--", "-\u200b-\u200b")
177 if "\n" in cc:
178 sp = " " * (indent + 2)
179 ci = "\n".join(sp + line if line else "" for line in cc.split("\n"))
180 return f"\n{ci}\n{' ' * indent}"
181 else:
182 return f" {cc} "
183
184
185 def add_comment(el: etree._Element, content: str, standalone: bool) -> None:
186 indent = 2 if el.tag == "resources" else 4
187 comment = etree.Comment(comment_body(content, indent))
188 comment.tail = ("\n\n" if standalone else "\n") + (" " * indent)
189 el.append(comment)
190
191
192 def entity_definition(entry: Entry[str, str] | Entry[Message, str]) -> str:
193 if len(entry.id) != 1 or not xml_name.fullmatch(entry.id[0]):
194 raise ValueError(f"Invalid entity identifier: {entry.id}")
195 name = entry.id[0]
196 if not xml_name.fullmatch(name):
197 raise ValueError(f"Invalid entity name: {name}")
198
199 # Characters not allowed in XML EntityValue text
200 escape = str.maketrans({"&": "&amp;", "%": "&#37;", '"': "&quot;"})
201
202 if isinstance(entry.value, str):
203 value = entry.value.translate(escape)
204 elif isinstance(entry.value, PatternMessage) and not entry.value.declarations:
205 value = ""
206 for part in entry.value.pattern:
207 if isinstance(part, str):
208 value += part.translate(escape)
209 else:
210 ref = entity_name(part) if isinstance(part, Expression) else None
211 if ref and xml_name.fullmatch(ref):
212 value += f"&{ref};"
213 else:
214 raise ValueError(f"Unsupported entity part: {part}")
215 else:
216 raise ValueError(f"Unsupported entity value: {entry.value}")
217
218 return f'<!ENTITY {name} "{value}">'
219
220
221 def set_string_array_item(
222 parent: etree._Element, entry: Entry[str, str] | Entry[Message, str]
223 ) -> None:
224 try:
225 num = int(entry.id[1])
226 except ValueError:
227 raise ValueError(f"Unsupported entry id: {entry.id}")
228 if num != len(parent):
229 raise ValueError(f"String-array keys must be ordered: {entry.id}")
230 if isinstance(entry.value, SelectMessage):
231 raise ValueError(f"Unsupported message type for {entry.id}: {entry.value}")
232 item = etree.SubElement(parent, "item")
233 set_pattern_message(item, entry.value)
234
235
236 def set_plural_message(plurals: etree._Element, msg: SelectMessage) -> None:
237 sel = msg.selectors[0] if len(msg.selectors) == 1 else None
238 if (
239 msg.declarations
240 or not sel
241 or not isinstance(sel.annotation, FunctionAnnotation)
242 or sel.annotation.name != "number"
243 ):
244 raise ValueError(f"Unsupported message: {msg}")
245 for keys, value in msg.variants.items():
246 key = keys[0] if len(keys) == 1 else None
247 if isinstance(key, CatchallKey):
248 key = key.value or "other"
249 if key not in plural_categories:
250 raise ValueError(f"Unsupported plural variant key: {keys}")
251 item = etree.SubElement(plurals, "item", attrib={"quantity": key})
252 set_pattern(item, value)
253 item.tail = "\n "
254 item.tail = "\n "
255
256
257 def set_pattern_message(el: etree._Element, msg: PatternMessage | str) -> None:
258 if isinstance(msg, str):
259 el.text = escape_backslash(msg)
260 escape_doublequote(el)
261 elif isinstance(msg, PatternMessage) and not msg.declarations:
262 set_pattern(el, msg.pattern)
263 else:
264 raise ValueError(f"Unsupported message: {msg}")
265
266
267 def set_pattern(el: etree._Element, pattern: Pattern) -> None:
268 node: etree._Element | None
269 if len(pattern) == 1 and isinstance(pattern[0], Expression):
270 annot = pattern[0].annotation
271 if isinstance(annot, FunctionAnnotation) and annot.name == "reference":
272 # A "string" could be an Android resource reference,
273 # which should not have its @ or ? sigil escaped.
274 arg = pattern[0].arg
275 if isinstance(arg, str) and resource_ref.fullmatch(arg):
276 el.text = arg
277 return
278 else:
279 raise ValueError(f"Invalid reference value: {arg}")
280
281 parent = el
282 node = None
283 for part in pattern:
284 if isinstance(part, str):
285 esc = escape_backslash(part)
286 if node is None:
287 parent.text = parent.text + esc if parent.text else esc
288 else:
289 node.tail = node.tail + esc if node.tail else esc
290 elif isinstance(part, Expression):
291 ent_name = entity_name(part)
292 if part.attributes.get("translate", None) == "no":
293 # <xliff:g>
294 attrib = (
295 cast(Dict[str, str], part.annotation.options)
296 if isinstance(part.annotation, FunctionAnnotation)
297 else None
298 )
299 nsmap = {"xliff": xliff_ns} if not el.nsmap.get("xliff", None) else None
300 node = etree.SubElement(parent, xliff_g, attrib=attrib, nsmap=nsmap)
301 if ent_name:
302 node.append(etree.Entity(ent_name))
303 elif "source" in part.attributes:
304 source = part.attributes["source"]
305 if source:
306 node.text = str(source)
307 else:
308 if isinstance(part.arg, str):
309 node.text = escape_backslash(part.arg)
310 elif isinstance(part.arg, VariableRef):
311 node.text = part.arg.name
312 elif ent_name:
313 node = etree.Entity(ent_name)
314 parent.append(node)
315 elif "source" in part.attributes:
316 source = part.attributes["source"]
317 if not isinstance(source, str):
318 raise ValueError(f"Unsupported expression source: {part}")
319 if node is None:
320 parent.text = parent.text + source if parent.text else source
321 else:
322 node.tail = node.tail + source if node.tail else source
323 else:
324 source = None
325 if isinstance(part.arg, str):
326 source = escape_backslash(part.arg)
327 elif isinstance(part.arg, VariableRef):
328 source = part.arg.name
329 if source is not None:
330 if node is None:
331 parent.text = parent.text + source if parent.text else source
332 else:
333 node.tail = node.tail + source if node.tail else source
334 else:
335 raise ValueError(f"Unsupported expression: {part}")
336 elif any(isinstance(value, VariableRef) for value in part.options.values()):
337 raise ValueError(f"Unsupported markup with variable option: {part}")
338 else:
339 if part.attributes.get("translate", None) == "no":
340 name = f"{{{xliff_ns}}}g"
341 elif ":" in part.name:
342 ns, local = part.name.split(":", 1)
343 xmlns = el.nsmap.get(ns, xliff_ns if ns == "xliff" else ns)
344 name = f"{{{xmlns}}}{local}"
345 else:
346 name = part.name
347 attrib = cast(Dict[str, str], part.options)
348 if part.kind == "standalone":
349 node = etree.SubElement(parent, name, attrib=attrib)
350 elif part.kind == "open":
351 parent = etree.SubElement(parent, name, attrib=attrib)
352 node = None
353 elif parent != el and name == parent.tag: # kind == 'close'
354 node = parent
355 parent = cast(etree._Element, parent.getparent())
356 else:
357 raise ValueError(f"Improper element nesting for {part} in {parent}")
358 escape_doublequote(el)
359
360
361 def entity_name(part: Expression) -> str | None:
362 if (
363 isinstance(part.annotation, FunctionAnnotation)
364 and part.annotation.name == "entity"
365 ):
366 name = part.arg.name if isinstance(part.arg, VariableRef) else None
367 if name:
368 return name
369 else:
370 raise ValueError(f"Invalid entity exression: {part}")
371 return None
372
373
374 # Special Android characters
375 android_escape = str.maketrans(
376 {"\\": r"\\", "\n": r"\n", "\t": r"\t", "'": r"\'", '"': r"\""}
377 )
378
379 # Control codes are not valid in XML, and nonstandard whitespace is hard to see.
380 control_chars = compile(r"[\x00-\x19\x7F-\x9F]|[^\S ]")
381
382
383 def escape_backslash(src: str) -> str:
384 res = src.translate(android_escape)
385 return control_chars.sub(lambda m: f"\\u{ord(m.group()):04d}", res)
386
387
388 def escape_doublequote(el: etree._Element, root: bool = True) -> None:
389 if el.text and (" " in el.text):
390 el.text = f'"{el.text}"'
391 for child in el:
392 escape_doublequote(child, False)
393 if child.tail and " " in child.tail:
394 child.tail = f'"{child.tail}"'
395 if root:
396 if el.text and el.text.startswith((" ", "@", "?")):
397 el.text = f'"{el.text}"'
398 if len(el) > 0:
399 last = el[-1]
400 if last.tail and last.tail.endswith(" "):
401 last.tail = f'"{last.tail}"'
402 elif el.text and el.text.endswith(" "):
403 el.text = f'"{el.text}"'