xref: /aosp_15_r20/frameworks/base/data/fonts/script/fallback_builder.py (revision d57664e9bc4670b3ecf6748a746a57c557b6bc9e)
1#!/usr/bin/env python
2
3#
4# Copyright (C) 2024 The Android Open Source Project
5#
6# Licensed under the Apache License, Version 2.0 (the "License");
7# you may not use this file except in compliance with the License.
8# You may obtain a copy of the License at
9#
10#      http://www.apache.org/licenses/LICENSE-2.0
11#
12# Unless required by applicable law or agreed to in writing, software
13# distributed under the License is distributed on an "AS IS" BASIS,
14# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15# See the License for the specific language governing permissions and
16# limitations under the License.
17#
18
19"""Build Fallback instance with validating JSON contents."""
20
21import dataclasses
22
23from custom_json import _load_json_with_comment
24from validators import check_str_or_none
25
26
27@dataclasses.dataclass
28class FallbackEntry:
29  lang: str | None
30  id: str | None
31
32
33_FALLBACK_KEYS = set(["lang", "id"])
34
35
36def _parse_entry(obj) -> FallbackEntry:
37  """Convert given dict object to FallbackEntry instance."""
38  unknown_keys = obj.keys() - _FALLBACK_KEYS
39  assert not unknown_keys, "Unknown keys found: %s" % unknown_keys
40  entry = FallbackEntry(
41      lang=check_str_or_none(obj, "lang"),
42      id=check_str_or_none(obj, "id"),
43  )
44
45  assert entry.lang or entry.id, "lang or id must be specified."
46  assert (
47      not entry.lang or not entry.id
48  ), "lang and id must not be specified at the same time"
49
50  return entry
51
52
53def parse_fallback(objs) -> [FallbackEntry]:
54  assert isinstance(objs, list), "fallback must be list"
55  assert objs, "at least one etnry must be specified"
56  return [_parse_entry(obj) for obj in objs]
57
58
59def parse_fallback_from_json(json_str) -> [FallbackEntry]:
60  """For testing purposes."""
61  return parse_fallback(_load_json_with_comment(json_str))
62