Debian Codegraph @

third_party/python/moz.l10n/moz/l10n/resource/dtd/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 UNICODE, compile
19 from typing import Any
20
21 from moz.l10n.message import Message, PatternMessage
22
23 from ..data import Entry, Resource
24 from .parse import name, re_comment
25
26 re_name = compile(name, UNICODE)
27
28
29 def dtd_serialize(
30 resource: Resource[str, Any] | Resource[Message, Any],
31 trim_comments: bool = False,
32 ) -> Iterator[str]:
33 """
34 Serialize a resource as the contents of a DTD file.
35
36 Section identifiers will be prepended to their constituent message identifiers.
37 Multi-part identifiers will be joined with `.` between each part.
38
39 Metadata is not supported.
40
41 Yields each entity, comment, and empty line separately.
42 Re-parsing a serialized DTD file is not guaranteed to result in the same Resource,
43 as the serialization may lose information about message sections and metadata.
44 """
45
46 at_empty_line = True
47
48 def comment(comment: str, meta: Any, standalone: bool) -> Iterator[str]:
49 nonlocal at_empty_line
50 if trim_comments:
51 return
52 if meta:
53 raise ValueError("Metadata is not supported")
54 if comment:
55 if standalone and not at_empty_line:
56 yield "\n"
57 # Comments can't include --, so add a zero width space between and after dashes beyond the first
58 lines = [
59 line.rstrip().replace("--", "-\u200b-\u200b")
60 for line in comment.strip("\n").split("\n")
61 ]
62 cstr = "<!--" if not lines[0] or lines[0].startswith(" ") else "<!-- "
63 cstr += lines[0]
64 for line in lines[1:]:
65 cstr += "\n"
66 if line and not line.isspace():
67 if not line.startswith(" "):
68 cstr += " "
69 cstr += line
70 yield cstr + " -->\n"
71 if standalone:
72 yield "\n"
73 at_empty_line = True
74
75 yield from comment(resource.comment, resource.meta, True)
76 for section in resource.sections:
77 yield from comment(section.comment, section.meta, True)
78 id_prefix = ".".join(section.id) + "." if section.id else ""
79 for entry in section.entries:
80 if isinstance(entry, Entry):
81 yield from comment(entry.comment, entry.meta, False)
82 name = id_prefix + ".".join(entry.id)
83 if not re_name.fullmatch(name):
84 raise ValueError(f"Unsupported DTD name: {name}")
85 msg = entry.value
86 if isinstance(msg, str):
87 value = msg
88 elif isinstance(msg, PatternMessage) and all(
89 isinstance(p, str) for p in msg.pattern
90 ):
91 value = "".join(msg.pattern) # type: ignore[arg-type]
92 else:
93 raise ValueError(f"Unsupported message for {name}: {msg}")
94
95 if '"' in value and "'" not in value:
96 quoted = f"'{value}'"
97 else:
98 quoted = value.replace('"', "&quot;")
99 quoted = f'"{quoted}"'
100 quoted = re_comment.sub("", quoted)
101
102 yield f"<!ENTITY {name} {quoted}>\n"
103 at_empty_line = False
104 else:
105 yield from comment(entry.comment, None, True)