| 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 json import loads |
| 19 |
from typing import Any |
| 20 |
|
| 21 |
from moz.l10n.message import Message, PatternMessage |
| 22 |
|
| 23 |
from ..data import Entry, Resource, Section |
| 24 |
from ..format import Format |
| 25 |
|
| 26 |
|
| 27 |
def plain_json_parse(source: str | bytes) -> Resource[Message, Any]: |
| 28 |
""" |
| 29 |
Parse a JSON file into a message resource. |
| 30 |
|
| 31 |
The input is expected to be a nested object with string values at leaf nodes. |
| 32 |
|
| 33 |
The parsed resource will not include any metadata. |
| 34 |
""" |
| 35 |
json: dict[str, dict[str, Any]] = loads(source) |
| 36 |
if not isinstance(json, dict): |
| 37 |
raise ValueError(f"Unexpected root value: {json}") |
| 38 |
return Resource( |
| 39 |
Format.plain_json, [Section((), [e for e in plain_object([], json)])] |
| 40 |
) |
| 41 |
|
| 42 |
|
| 43 |
def plain_object(path: list[str], obj: dict[str, Any]) -> Iterator[Entry[Message, Any]]: |
| 44 |
for k, value in obj.items(): |
| 45 |
key = [*path, k] |
| 46 |
if isinstance(value, str): |
| 47 |
yield Entry(tuple(key), PatternMessage([value])) |
| 48 |
elif isinstance(value, dict): |
| 49 |
yield from plain_object(key, value) |
| 50 |
else: |
| 51 |
raise ValueError(f"Unexpected value at {key}: {value}") |