Debian Codegraph @

third_party/python/moz.l10n/moz/l10n/resource/inc/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 re import compile
18 from typing import Any
19
20 from moz.l10n.message import Message, PatternMessage
21
22 from ..data import Comment, Entry, Resource, Section
23 from ..format import Format
24
25 re_define = compile(r"#define[ \t]+(\w+)(?:[ \t](.*))?")
26
27
28 def inc_parse(source: str | bytes) -> Resource[Message, Any]:
29 """
30 Parse a .inc file into a message resource.
31
32 Directives such as `#filter` and `#unfilter` will be stored as standalone comments.
33
34 The parsed resource will not include any metadata.
35 """
36 entries: list[Entry[Message, Any] | Comment] = []
37 comment: str = ""
38 if not isinstance(source, str):
39 source = source.decode()
40 for line in source.splitlines():
41 if not line or line.isspace():
42 if comment:
43 entries.append(Comment(comment))
44 comment = ""
45 elif line.startswith("# "):
46 nc = line[2:].lstrip()
47 if nc.startswith("#"):
48 nc = line
49 comment = f"{comment}\n{nc}" if comment else nc
50 else:
51 match = re_define.fullmatch(line)
52 if match:
53 name, value = match.groups()
54 entries.append(Entry((name,), PatternMessage([value]), comment))
55 comment = ""
56 elif line.startswith("#"):
57 if comment:
58 entries.append(Comment(comment))
59 comment = ""
60 entries.append(Comment(line))
61 else:
62 raise ValueError(f"Unsupported content: {line}")
63 if comment:
64 entries.append(Comment(comment))
65 return Resource(Format.inc, [Section((), entries)])