Debian Codegraph @

third_party/python/moz.l10n/moz/l10n/resource/properties/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 enum import Enum
18 from re import Match, compile
19 from typing import Any, Callable
20
21 from moz.l10n.message import Message, PatternMessage
22
23 from ..data import Comment, Entry, LinePos, Resource, Section
24 from ..format import Format
25
26
27 class LineKind(Enum):
28 EMPTY = 0
29 COMMENT = 1
30 KEY = 2
31 VALUE = 3
32
33
34 esc_re = compile("\\\\(u[0-9A-Fa-f]{1,4}|.)")
35
36
37 def esc_parse(match: Match[str]) -> str:
38 esc = match.group(1)
39 if len(esc) > 1 and esc[0] == "u":
40 n = int(esc[1:], 16)
41 return chr(n)
42 elif esc == "t":
43 return "\t"
44 elif esc == "n":
45 return "\n"
46 elif esc == "f":
47 return "\f"
48 elif esc == "r":
49 return "\r"
50 else:
51 return esc
52
53
54 def properties_parse(
55 source: bytes | str,
56 encoding: str = "utf-8",
57 parse_message: Callable[[str], Message] | None = None,
58 ) -> Resource[Message, Any]:
59 """
60 Parse a .properties file into a message resource.
61
62 By default, all messages are parsed as PatternMessage([str]).
63 To customize that, define an appropriate `parse_message(str) -> Message`.
64
65 The parsed resource will not include any metadata.
66 """
67 if not isinstance(source, str):
68 source = source.decode(encoding)
69 parser = PropertiesParser(source)
70 entries: list[Entry[Message, Any] | Comment] = []
71 resource = Resource(Format.properties, [Section((), entries)])
72
73 start_line = 0
74 comment = ""
75 prev_linepos: LinePos | None = None
76 entry: Entry[Message, Any] | None = None
77 for kind, line, value in parser:
78 if kind == LineKind.VALUE:
79 assert entry
80 if parse_message:
81 entry.value = parse_message(value)
82 else:
83 assert isinstance(entry.value, PatternMessage)
84 entry.value.pattern.append(value)
85 if entry.linepos and line > entry.linepos.key:
86 entry.linepos.value = line
87 entry.linepos.end = line + 1
88 entry = None
89 else:
90 if prev_linepos:
91 prev_linepos.end = max(prev_linepos.end, line)
92 prev_linepos = None
93 entry = None
94 if kind == LineKind.KEY:
95 entry = Entry(
96 id=(value,),
97 value=PatternMessage([]),
98 comment=comment,
99 linepos=LinePos(start_line or line, line, line, line + 1),
100 )
101 prev_linepos = entry.linepos
102 entries.append(entry)
103 comment = ""
104 start_line = 0
105 elif kind == LineKind.COMMENT:
106 if comment:
107 comment += "\n" + value
108 else:
109 comment = value
110 start_line = line
111 elif comment:
112 # empty line or EOF after a comment
113 if entries or resource.comment:
114 entries.append(Comment(comment))
115 else:
116 resource.comment = comment
117 comment = ""
118 start_line = 0
119 return resource
120
121
122 class PropertiesParser:
123 def __init__(self, source: str) -> None:
124 self.source = source
125 self.pos = 0
126 self.line_pos = 1
127 self.at_value = False
128 self.done = False
129
130 def __iter__(self) -> PropertiesParser:
131 return self
132
133 def __next__(self) -> tuple[LineKind, int, str]:
134 if self.done:
135 raise StopIteration
136
137 lp = self.line_pos
138 self.ws()
139 if self.pos == len(self.source):
140 self.done = True
141 return LineKind.EMPTY, lp, ""
142
143 if self.nl():
144 self.at_value = False
145 return LineKind.EMPTY, lp, ""
146
147 if self.at_value:
148 # value
149 self.at_value = False
150 line_start = start = self.pos
151 at_escape = False
152 at_cr = False
153 idx = -1
154 lines: list[str] = []
155 for idx, ch in enumerate(self.source[start:]):
156 if ch == "\n" or ch == "\r":
157 if at_escape:
158 at_escape = False
159 self.line_pos += 1
160 end = start + idx - 1
161 lines.append(self.source[line_start:end])
162 at_cr = ch == "\r"
163 line_start = start + idx + 1
164 elif ch == "\n" and at_cr:
165 at_cr = False
166 line_start = start + idx + 1
167 else:
168 idx -= 1
169 break
170 else:
171 if at_cr:
172 at_cr = False
173 if at_escape:
174 at_escape = False
175 elif ch == "\\":
176 at_escape = True
177 self.pos = end = start + idx + 1
178 lines.append(self.source[line_start:end])
179 self.nl()
180 value = "".join(
181 esc_re.sub(esc_parse, line.lstrip("\f\t ")) for line in lines
182 )
183 return LineKind.VALUE, lp, value
184
185 if self.source.startswith(("#", "!"), self.pos):
186 # comment
187 self.pos += 1
188 if self.source.startswith(" ", self.pos):
189 # Ignore one space after #, if present.
190 self.pos += 1
191 start = self.pos
192 idx = -1
193 for idx, ch in enumerate(self.source[start:]):
194 if ch == "\n" or ch == "\r":
195 idx -= 1
196 break
197 end = self.pos = start + idx + 1
198 self.nl()
199 return LineKind.COMMENT, lp, self.source[start:end]
200
201 # key
202 start = self.pos
203 at_escape = False
204 idx = -1
205 for idx, ch in enumerate(self.source[start:]):
206 if at_escape:
207 at_escape = False
208 elif ch == "\\":
209 at_escape = True
210 elif ch in {"\n", "\r", "\t", "\f", " ", "=", ":"}:
211 idx -= 1
212 break
213 end = self.pos = start + idx + 1
214 self.ws()
215 if self.source.startswith(("=", ":"), self.pos):
216 self.pos += 1
217 self.at_value = True
218 return LineKind.KEY, lp, esc_re.sub(esc_parse, self.source[start:end])
219
220 def nl(self) -> bool:
221 if self.source.startswith("\n", self.pos):
222 self.pos += 1
223 self.line_pos += 1
224 return True
225 elif self.source.startswith("\r", self.pos):
226 self.pos += 1
227 self.line_pos += 1
228 if self.source.startswith("\n", self.pos):
229 self.pos += 1
230 return True
231 return False
232
233 def ws(self) -> None:
234 for ch in self.source[self.pos :]:
235 if ch in {" ", "\t", "\f"}:
236 self.pos += 1
237 else:
238 break