Debian Codegraph @

third_party/python/moz.l10n/moz/l10n/resource/inc/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 typing import Any
19
20 from moz.l10n.message import Message, PatternMessage
21
22 from ..data import Entry, Resource
23
24
25 def inc_serialize(
26 resource: Resource[str, Any] | Resource[Message, Any],
27 trim_comments: bool = False,
28 ) -> Iterator[str]:
29 """
30 Serialize a resource as the contents of a .inc file.
31
32 Section identifiers and multi-part identifiers are not supported.
33
34 Non-string message values and metadata is not supported.
35
36 Comment lines not starting with `#` will be prefixed with `# `.
37
38 Yields each line separately.
39 """
40
41 def comment(comment: str, meta: Any, standalone: bool) -> Iterator[str]:
42 if meta:
43 raise ValueError("Metadata is not supported")
44 if comment:
45 for line in comment.strip("\n").split("\n"):
46 if line.startswith("#"):
47 if not trim_comments or not line.startswith("# "):
48 yield f"{line}\n"
49 elif not trim_comments:
50 line = line.strip()
51 yield f"# {line}\n" if line else "#\n"
52 if standalone:
53 yield "\n"
54
55 yield from comment(resource.comment, resource.meta, True)
56 for section in resource.sections:
57 yield from comment(section.comment, section.meta, True)
58 if section.id:
59 raise ValueError(f"Section identifiers not supported: {section.id}")
60 for entry in section.entries:
61 if isinstance(entry, Entry):
62 yield from comment(entry.comment, entry.meta, False)
63 if len(entry.id) != 1:
64 raise ValueError(f"Unsupported identifier: {entry.id}")
65 msg = entry.value
66 if isinstance(msg, str):
67 value = msg
68 elif isinstance(msg, PatternMessage) and all(
69 isinstance(p, str) for p in msg.pattern
70 ):
71 value = "".join(msg.pattern) # type: ignore[arg-type]
72 else:
73 raise ValueError(f"Unsupported message for {entry.id[0]}: {msg}")
74 value = value.replace("\n", " ")
75 yield f"#define {entry.id[0]} {value}\n"
76 yield "\n"
77 else:
78 yield from comment(entry.comment, None, True)