Debian Codegraph @

third_party/python/moz.l10n/moz/l10n/resource/properties/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 re import Match, compile
18 from typing import Any, Callable, Iterator, Literal
19
20 from moz.l10n.message import Message, PatternMessage
21
22 from ..data import Entry, Resource
23
24 control_chars = compile(r"[\x00-\x19\x5C\x7F-\x9F]")
25 not_ascii_printable_chars = compile(r"[^\x20-\x5B\x5D-\x7E]")
26 special_key_trans = str.maketrans({" ": "\\ ", ":": "\\:", "=": "\\="})
27
28
29 def encode_char(m: Match[str]) -> str:
30 ch = m.group()
31 if ch == "\\":
32 return r"\\"
33 elif ch == "\t":
34 return r"\t"
35 elif ch == "\n":
36 return r"\n"
37 elif ch == "\f":
38 return r"\f"
39 elif ch == "\r":
40 return r"\r"
41 return f"\\u{ord(ch):04x}"
42
43
44 def properties_serialize(
45 resource: Resource[str, Any] | Resource[Message, Any],
46 encoding: Literal["iso-8859-1", "utf-8", "utf-16"] = "utf-8",
47 serialize_message: Callable[[Message], str] | None = None,
48 trim_comments: bool = False,
49 ) -> Iterator[str]:
50 """
51 Serialize a resource as the contents of a .properties file.
52
53 Section identifiers will be prepended to their constituent message identifiers.
54 Multi-part message identifiers will be joined with `.` between each part.
55
56 For non-string message values, a `serialize_message` callable must be provided.
57
58 Metadata is not supported.
59
60 Yields each entry, comment, and empty line separately.
61 Re-parsing a serialized .properties file is not guaranteed to result in the same Resource,
62 as the serialization may lose information about message sections and metadata.
63 """
64
65 at_empty_line = True
66
67 def comment(comment: str, meta: Any, standalone: bool) -> Iterator[str]:
68 nonlocal at_empty_line
69 if trim_comments:
70 return
71 if meta:
72 raise ValueError("Metadata is not supported")
73 if comment:
74 if standalone and not at_empty_line:
75 yield "\n"
76 for line in comment.strip("\n").split("\n"):
77 if not line or line.isspace():
78 yield "#\n"
79 else:
80 line = line.rstrip() + "\n"
81 yield f"#{line}" if line.startswith("#") else f"# {line}"
82 if standalone:
83 yield "\n"
84 at_empty_line = True
85
86 yield from comment(resource.comment, resource.meta, True)
87 for section in resource.sections:
88 yield from comment(section.comment, section.meta, True)
89 id_prefix = ".".join(section.id) + "." if section.id else ""
90 for entry in section.entries:
91 if isinstance(entry, Entry):
92 yield from comment(entry.comment, entry.meta, False)
93 key = id_prefix + ".".join(entry.id)
94 key = (
95 control_chars.sub(encode_char, key)
96 if encoding in {"utf-8", "utf-16"}
97 else not_ascii_printable_chars.sub(encode_char, key)
98 )
99 key = key.translate(special_key_trans)
100
101 value: str
102 msg = entry.value
103 if isinstance(msg, str):
104 value = msg
105 elif serialize_message:
106 value = serialize_message(msg)
107 elif isinstance(msg, PatternMessage) and all(
108 isinstance(p, str) for p in msg.pattern
109 ):
110 value = "".join(msg.pattern) # type: ignore[arg-type]
111 else:
112 raise ValueError(f"Unsupported message for {key}: {msg}")
113
114 value = (
115 control_chars.sub(encode_char, value)
116 if encoding in {"utf-8", "utf-16"}
117 else not_ascii_printable_chars.sub(encode_char, value)
118 )
119
120 if value[0:1].isspace():
121 value = "\\" + value
122 if value.endswith(" ") and not value.endswith("\\ "):
123 value = value[:-1] + "\\u0020"
124 yield f"{key} = {value}\n" if value else f"{key} =\n"
125 at_empty_line = False
126 else:
127 yield from comment(entry.comment, None, True)