Debian Codegraph @

third_party/python/moz.l10n/moz/l10n/resource/xliff/parse.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 import defaultdict
18 from collections.abc import Iterator
19 from re import compile
20 from typing import List, Union, cast
21
22 from lxml import etree
23
24 from ...message import Expression, Message, PatternMessage
25 from ..data import Comment, Entry, Metadata, Resource, Section
26 from ..format import Format
27 from .common import attrib_as_metadata, element_as_metadata, pretty_name, xliff_ns
28 from .parse_trans_unit import parse_trans_unit
29 from .parse_xcode import parse_xliff_stringsdict
30
31
32 def xliff_parse(source: str | bytes) -> Resource[Message, str]:
33 """
34 Parse an XLIFF 1.2 file into a message resource.
35
36 Sections identify files and groups within them,
37 with the first identifier part parsed as the <file> "original" attribute,
38 and later parts as <group> "id" attributes.
39
40 An entry's value represents the <target> of a <trans-unit>,
41 and its comment the first <note>.
42 Other elements and attributes are represented by metadata.
43
44 Metadata keys encode XML element data, using XPath expressions as keys.
45 """
46 root = etree.fromstring(source.encode() if isinstance(source, str) else source)
47 version = root.attrib.get("version", None)
48 if version not in ("1.0", "1.1", "1.2"):
49 raise ValueError(f"Unsupported <xliff> version: {version}")
50 ns = root.nsmap.get(None, "")
51 if ns:
52 if ns in xliff_ns:
53 ns = f"{{{ns}}}"
54 else:
55 raise ValueError(f"Unsupported namespace: {ns}")
56
57 if root.tag != f"{ns}xliff":
58 raise ValueError(f"Unsupported root node: {root}")
59 if root.text and not root.text.isspace():
60 raise ValueError(f"Unexpected text in <xliff>: {root.text}")
61
62 res: Resource[Message, str] = Resource(Format.xliff, [])
63 root_comments = [
64 c.text for c in root.itersiblings(etree.Comment, preceding=True) if c.text
65 ]
66 if root_comments:
67 root_comments.reverse()
68 res.comment = comment_str(root_comments)
69 res.meta = attrib_as_metadata(root)
70 for key, uri in root.nsmap.items():
71 res.meta.append(Metadata(f"@xmlns:{key}" if key else "@xmlns", uri))
72
73 comment: list[str] = []
74 for file in root:
75 if file.tail and not file.tail.isspace():
76 raise ValueError(f"Unexpected text in <xliff>: {file.tail}")
77 if isinstance(file, etree._Comment):
78 comment.append(file.text)
79 elif file.tag == f"{ns}file":
80 file_name = file.attrib.get("original", None)
81 if file_name is None:
82 raise ValueError(f'Missing "original" attribute for <file>: {file}')
83 meta = attrib_as_metadata(file, None, ("original",))
84 entries: list[Entry[Message, str] | Comment] = []
85 body = None
86 for child in file:
87 if isinstance(child, etree._Comment):
88 entries.append(Comment(comment_str(child.text)))
89 elif child.tag == f"{ns}header":
90 meta += element_as_metadata(child, "header", True)
91 elif child.tag == f"{ns}body":
92 if body:
93 raise ValueError(f"Duplicate <body> in <file>: {file}")
94 body = child
95 else:
96 raise ValueError(
97 f"Unsupported <{child.tag}> element in <file>: {file}"
98 )
99 if child.tail and not child.tail.isspace():
100 raise ValueError(f"Unexpected text in <file>: {child.tail}")
101
102 section = Section((file_name,), entries, meta=meta)
103 if comment:
104 section.comment = comment_str(comment)
105 comment.clear()
106 res.sections.append(section)
107
108 if body is None:
109 raise ValueError(f"Missing <body> in <file>: {file}")
110 elif body.text and not body.text.isspace():
111 raise ValueError(f"Unexpected text in <body>: {body.text}")
112
113 if file_name.endswith(".stringsdict"):
114 plural_entries = parse_xliff_stringsdict(ns, body)
115 if plural_entries is not None:
116 entries += cast(
117 List[Union[Entry[Message, str], Comment]], plural_entries
118 )
119 continue
120
121 for unit in body:
122 if isinstance(unit, etree._Comment):
123 entries.append(Comment(comment_str(unit.text)))
124 elif unit.tag == f"{ns}trans-unit":
125 entries.append(parse_trans_unit(unit))
126 elif unit.tag == f"{ns}bin-unit":
127 entries.append(parse_bin_unit(unit))
128 elif unit.tag == f"{ns}group":
129 res.sections += parse_group(ns, [file_name], unit)
130 else:
131 raise ValueError(
132 f"Unsupported <{unit.tag}> element in <body>: {body}"
133 )
134 if unit.tail and not unit.tail.isspace():
135 raise ValueError(f"Unexpected text in <body>: {unit.tail}")
136 return res
137
138
139 def parse_group(
140 ns: str, parent: list[str], group: etree._Element
141 ) -> Iterator[Section[Message, str]]:
142 id = group.attrib.get("id", "")
143 path = [*parent, id]
144 meta = attrib_as_metadata(group, None, ("id",))
145 entries: list[Entry[Message, str] | Comment] = []
146 if group.text and not group.text.isspace():
147 raise ValueError(f"Unexpected text in <group>: {group.text}")
148
149 # Note that this is modified after being emitted,
150 # To ensure that nested groups are ordered by path
151 yield Section(tuple(path), entries, meta=meta)
152
153 seen: dict[str, int] = defaultdict(int)
154 for unit in group:
155 if isinstance(unit, etree._Comment):
156 entries.append(Comment(comment_str(unit.text)))
157 elif unit.tag == f"{ns}trans-unit":
158 entries.append(parse_trans_unit(unit))
159 elif unit.tag == f"{ns}bin-unit":
160 entries.append(parse_bin_unit(unit))
161 elif unit.tag == f"{ns}group":
162 yield from parse_group(ns, path, unit)
163 else:
164 name = pretty_name(unit, unit.tag)
165 idx = seen[name] + 1
166 unit_base = f"{name}[{idx}]" if idx > 1 else name
167 meta += element_as_metadata(unit, unit_base, True)
168 seen[name] = idx
169 if unit.tail and not unit.tail.isspace():
170 raise ValueError(f"Unexpected text in <group>: {unit.tail}")
171
172
173 def parse_bin_unit(unit: etree._Element) -> Entry[Message, str]:
174 id = unit.attrib.get("id", None)
175 if id is None:
176 raise ValueError(f'Missing "id" attribute for <bin-unit>: {unit}')
177 meta = attrib_as_metadata(unit, None, ("id",))
178 meta += element_as_metadata(unit, "", False)
179 msg = PatternMessage([Expression(None, attributes={"bin-unit": None})])
180 return Entry((id,), msg, meta=meta)
181
182
183 dash_indent = compile(r" .+(\n - .*)+ ")
184
185
186 def comment_str(body: list[str] | str) -> str:
187 if isinstance(body, str):
188 body = [body]
189 lines: list[str] = []
190 for comment in body:
191 if comment:
192 if dash_indent.fullmatch(comment):
193 # A dash is considered as a part of the indent if it's aligned
194 # with the last dash of <!-- in a top-level comment.
195 lines.append(comment.replace("\n - ", "\n").strip(" "))
196 else:
197 lines.append(
198 "\n".join(line.strip() for line in comment.splitlines()).strip("\n")
199 )
200 return "\n\n".join(lines).strip("\n")