Debian Codegraph @

third_party/python/moz.l10n/moz/l10n/resource/plain_json/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 import defaultdict
18 from collections.abc import Iterator
19 from json import dumps
20 from typing import Any
21
22 from moz.l10n.message import Message, PatternMessage
23
24 from ..data import Entry, Resource
25
26
27 def plain_json_serialize(
28 resource: Resource[str, Any] | Resource[Message, Any],
29 trim_comments: bool = False,
30 ) -> Iterator[str]:
31 """
32 Serialize a resource as a nested JSON object.
33
34 Comments and metadata are not supported.
35
36 Yields the entire JSON result as a single string.
37 """
38
39 def check(comment: str | None, meta: Any) -> None:
40 if trim_comments:
41 return
42 if comment:
43 raise ValueError("Resource and section comments are not supported")
44 if meta:
45 raise ValueError("Metadata is not supported")
46
47 def ddict() -> dict[str, Any]:
48 return defaultdict(ddict)
49
50 check(resource.comment, resource.meta)
51 root = ddict()
52 for section in resource.sections:
53 check(section.comment, section.meta)
54 section_parent = root
55 for part in section.id:
56 section_parent = section_parent[part]
57 for entry in section.entries:
58 if isinstance(entry, Entry):
59 check(entry.comment, entry.meta)
60 if not entry.id:
61 raise ValueError(f"Unsupported empty identifier in {section.id}")
62 msg = entry.value
63 if isinstance(msg, str):
64 value = msg
65 elif isinstance(msg, PatternMessage) and all(
66 isinstance(p, str) for p in msg.pattern
67 ):
68 value = "".join(msg.pattern) # type: ignore[arg-type]
69 else:
70 raise ValueError(
71 f"Unsupported message for {section.id + entry.id}: {msg}"
72 )
73 parent = section_parent
74 for part in entry.id[:-1]:
75 parent = parent[part]
76 parent[entry.id[-1]] = value
77 else:
78 check(entry.comment, None)
79 yield dumps(root, indent=2)
80 yield "\n"