Debian Codegraph @

third_party/python/moz.l10n/moz/l10n/resource/xliff/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 typing import cast
19
20 from lxml import etree
21
22 from ...message import (
23 CatchallKey,
24 Expression,
25 FunctionAnnotation,
26 Markup,
27 Message,
28 Pattern,
29 PatternMessage,
30 SelectMessage,
31 VariableRef,
32 )
33 from ..data import Comment, Entry, Metadata, Resource
34 from .common import clark_name
35
36
37 def xliff_serialize(
38 resource: Resource[str, str] | Resource[Message, str],
39 trim_comments: bool = False,
40 ) -> Iterator[str]:
41 """
42 Serialize a resource as an XLIFF 1.2 file.
43
44 Sections identify files and groups within them,
45 with the first identifier part parsed as the <file> "original" attribute,
46 and later parts as <group> "id" attributes.
47
48 Metadata keys encode XML element data, using XPath expressions as keys.
49
50 For namespaced attribute and element names of the form `ns:foo`,
51 the resource should have an `xmlns:ns` metadata entry with its URI value.
52
53 SelectMessage values are only supported in .stringsdict files,
54 and their structure must closely match that generated by parse_xliff().
55 """
56
57 yield '<?xml version="1.0" encoding="utf-8"?>\n'
58 if resource.comment and not trim_comments:
59 yield f"\n<!--{comment_body(resource.comment, 0)}-->\n\n"
60
61 # The nsmap needs to be set during creation
62 # https://bugs.launchpad.net/lxml/+bug/555602
63 root_nsmap: dict[str | None, str] = {}
64 root_attrib: list[Metadata[str]] = []
65 for m in resource.meta:
66 k = m.key
67 v = m.value
68 if k == "@xmlns":
69 root_nsmap[None] = v
70 elif k.startswith("@xmlns:"):
71 root_nsmap[k[7:]] = v
72 elif k.startswith("@"):
73 root_attrib.append(m)
74 else:
75 raise ValueError(f"Unsupported root metadata key: {k}")
76 root = etree.Element(
77 "xliff",
78 attrib={clark_name(root_nsmap, m.key[1:]): m.value for m in root_attrib},
79 nsmap=root_nsmap,
80 )
81
82 prev: dict[tuple[str, ...], etree._Element] = {}
83 for section in resource.sections:
84 if not section.id:
85 raise ValueError("Anonymous sections are not supported")
86 parent_key = tuple(section.id)
87 if parent_key in prev:
88 raise ValueError(f"Duplicate section identifier: {parent_key}")
89 while parent_key and parent_key not in prev:
90 parent_key = parent_key[:-1]
91 parent = prev[parent_key] if parent_key else root
92 for id_part in section.id[len(parent_key) :]:
93 parent_key += (id_part,)
94 if parent == root:
95 file = etree.SubElement(root, "file", {"original": id_part})
96 assign_metadata(file, section.meta, trim_comments)
97 parent = etree.SubElement(file, "body")
98 else:
99 parent = etree.SubElement(parent, "group", {"id": id_part})
100 assign_metadata(parent, section.meta, trim_comments)
101 prev[parent_key] = parent
102 indent = 2 * len(section.id)
103 if section.comment:
104 comment = etree.Comment(comment_body(section.comment, indent))
105 parent.addprevious(comment)
106
107 indent += 2
108 for entry in section.entries:
109 if isinstance(entry, Comment):
110 if not trim_comments:
111 comment_str = comment_body(entry.comment, indent)
112 parent.append(etree.Comment(comment_str))
113 continue
114
115 if len(entry.id) != 1:
116 raise ValueError(f"Unsupported entry id: {entry.id}")
117 id = entry.id[0]
118 tag = "trans-unit"
119
120 # <bin-unit>
121 if isinstance(entry.value, PatternMessage):
122 pattern = entry.value.pattern
123 if (
124 len(pattern) == 1
125 and isinstance(pattern[0], Expression)
126 and "bin-unit" in pattern[0].attributes
127 ):
128 tag = "bin-unit"
129
130 if isinstance(entry.value, SelectMessage):
131 if section.id[0].endswith(".stringsdict"):
132 add_xliff_stringsdict_plural(parent, entry, trim_comments) # type: ignore [arg-type]
133 continue
134 else:
135 fn = section.id[0]
136 raise ValueError(f"Unsupported SelectMessage {id} in file: {fn}")
137
138 unit = etree.SubElement(parent, tag, {"id": id})
139 assign_metadata(unit, entry.meta, trim_comments)
140
141 msg = entry.value
142 target = None
143 source = None
144 if tag == "trans-unit" and msg:
145 target = unit.find("target")
146 if target is None:
147 source = unit.find("source")
148 if source is None:
149 raise ValueError(f"Invalid entry with no source: {entry}")
150 target = etree.Element("target")
151 source.addnext(target)
152 if isinstance(msg, str):
153 target.text = msg
154 elif isinstance(msg, PatternMessage) and not msg.declarations:
155 set_pattern(target, msg.pattern)
156 else:
157 raise ValueError(f"Unsupported message: {msg}")
158
159 if entry.comment and not trim_comments:
160 note = unit.find("note")
161 if note is None:
162 if target is None:
163 prev_el = unit.find("target") or unit.find("source")
164 if prev_el is None:
165 raise ValueError(f"Invalid entry with no source: {entry}")
166 else:
167 prev_el = target
168 note = etree.Element("note")
169 prev_el.addnext(note)
170 note.text = entry.comment
171
172 yield etree.tostring(root, encoding="unicode", pretty_print=True)
173
174
175 def add_xliff_stringsdict_plural(
176 parent: etree._Element, entry: Entry[SelectMessage, str], trim_comments: bool
177 ) -> None:
178 if entry.comment:
179 raise ValueError(f"Unsupported comment on SelectMessage: {entry.comment}")
180 msg = entry.value
181 if len(msg.selectors) != 1:
182 raise ValueError(f"Exactly one selector is required: {msg.selectors}")
183 sel = msg.selectors[0]
184 if (
185 not isinstance(sel.arg, VariableRef)
186 or not isinstance(sel.annotation, FunctionAnnotation)
187 or sel.annotation.name != "number"
188 ):
189 raise ValueError(f"Unsupported selector: {sel}")
190
191 id = entry.id[0]
192 id_base = f"/{id}:dict"
193 var_name = sel.arg.name
194
195 sel_source = sel.attributes.get("source", None)
196 if isinstance(sel_source, VariableRef):
197 raise ValueError(f"Unsupported format key source for {id}: {sel_source}")
198 meta_base = "format/"
199 meta = [m for m in entry.meta if m.key.startswith(meta_base)]
200 if sel_source:
201 xcode_id = f"{id_base}/NSStringLocalizedFormatKey:dict/:string"
202 unit = etree.SubElement(parent, "trans-unit", {"id": xcode_id})
203 assign_metadata(unit, meta, trim_comments, meta_base)
204 source = unit.find("source")
205 if source is None:
206 first = unit[0] if len(unit) > 0 else None
207 if first:
208 source = etree.Element("source")
209 first.addprevious(source)
210 else:
211 source = etree.SubElement(unit, "source")
212 source.text = sel_source
213 target = unit.find("target")
214 if target is None:
215 target = etree.Element("target")
216 source.addnext(target)
217 if not target.text:
218 target.text = sel_source
219 elif meta:
220 raise ValueError(
221 f"Format key source is required with format attributes for {id}"
222 )
223
224 for keys, pattern in msg.variants.items():
225 if len(keys) != 1:
226 raise ValueError(f"Unsupported variants keys for {id}: {keys}")
227 key = keys[0]
228 if isinstance(key, CatchallKey):
229 key = key.value or "other"
230 text = ""
231 for part in pattern:
232 if isinstance(part, str):
233 text += part
234 else:
235 part_source = part.attributes.get("source", None)
236 if isinstance(part_source, str):
237 text += part_source
238 elif isinstance(part, Expression) and part.arg is not None:
239 text += part.arg if isinstance(part.arg, str) else part.arg.name
240 else:
241 raise ValueError(f"Unsupported pattern part for {id}: {part}")
242 xcode_id = f"{id_base}/{var_name}:dict/{key}:dict/:string"
243 unit = etree.SubElement(parent, "trans-unit", {"id": xcode_id})
244 meta_base = f"{key}/"
245 meta = [m for m in entry.meta if m.key.startswith(meta_base)]
246 assign_metadata(unit, meta, trim_comments, meta_base)
247 source = unit.find("source")
248 if source is None:
249 raise ValueError(f"Missing {key}/source metadata for {id}")
250 target = unit.find("target")
251 if target is None:
252 target = etree.Element("target")
253 source.addnext(target)
254 target.text = text
255
256
257 def assign_metadata(
258 el: etree._Element, meta: list[Metadata[str]], trim_comments: bool, base: str = ""
259 ) -> None:
260 key_start = len(base)
261 done: list[str] = []
262 for m in meta:
263 key = m.key[key_start:] if key_start else m.key
264 if key == "":
265 if len(el) == 0:
266 el.text = (el.text or "") + m.value
267 else:
268 last = el[-1]
269 last.tail = (last.tail or "") + m.value
270 elif key == "comment()":
271 el.append(etree.Comment(m.value))
272 elif key.startswith("@"):
273 el.attrib[clark_name(el.nsmap, key[1:])] = m.value
274 else:
275 if "/" in key:
276 q = m.key
277 name_end = key.index("/")
278 else:
279 q = f"{m.key}/"
280 name_end = len(key)
281 if any(q.startswith(prev) for prev in done):
282 continue
283 name = key[0:name_end]
284 if "[" in name:
285 name = name[: name.index("[")]
286 child_root = base + key[0:name_end]
287 child_base = f"{child_root}/"
288 child_meta = [
289 m for m in meta if m.key == child_root or m.key.startswith(child_base)
290 ]
291 if not trim_comments or name != "note":
292 child = etree.SubElement(el, clark_name(el.nsmap, name))
293 assign_metadata(child, child_meta, trim_comments, child_base)
294 done.append(child_base)
295
296
297 def comment_body(content: str, indent: int) -> str:
298 # Comments can't include --, so add a zero width space between and after dashes beyond the first
299 cc = content.strip().replace("--", "-\u200b-\u200b")
300 if "\n" in cc:
301 sp = " " * (indent + 2)
302 ci = "\n".join(sp + line if line else "" for line in cc.split("\n"))
303 return f"\n{ci}\n{' ' * indent}"
304 else:
305 return f" {cc} "
306
307
308 def set_pattern(el: etree._Element, pattern: Pattern) -> None:
309 parent = el
310 prev = None
311 for part in pattern:
312 if isinstance(part, str):
313 if prev is None:
314 parent.text = (parent.text or "") + part
315 else:
316 prev.tail = (prev.tail or "") + part
317 elif isinstance(part, Markup):
318 name = clark_name(el.nsmap, part.name)
319 if part.kind == "close":
320 if part.options:
321 raise ValueError(
322 f"Options on closing markup are not supported: {part}"
323 )
324 if parent.tag != name or parent == el:
325 raise ValueError(f"Improper element nesting for {part} in {parent}")
326 node = parent
327 parent = cast(etree._Element, parent.getparent())
328 else:
329 attrib = {}
330 for key, value in part.options.items():
331 if isinstance(value, VariableRef):
332 raise ValueError(
333 f"Unsupported markup with variable option: {part}"
334 )
335 attrib[clark_name(el.nsmap, key)] = value
336 node = etree.SubElement(parent, name, attrib)
337 if part.kind == "standalone":
338 prev = node
339 else: # 'open'
340 parent = node
341 prev = None
342 elif isinstance(part, Expression):
343 raise ValueError(f"Unsupported expression: {part}")