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 Alias instance with validating JSON contents.""" 20 21import dataclasses 22 23from custom_json import _load_json_with_comment 24from validators import check_str 25from validators import check_weight_or_none 26 27 28@dataclasses.dataclass 29class Alias: 30 name: str 31 to: str 32 weight: int | None 33 34 35_ALIAS_KEYS = set(["name", "to", "weight"]) 36 37 38def parse_alias(obj) -> Alias: 39 """Convert given dict object to Alias instance.""" 40 unknown_keys = obj.keys() - _ALIAS_KEYS 41 assert not unknown_keys, "Unknown keys found: %s" % unknown_keys 42 alias = Alias( 43 name=check_str(obj, "name"), 44 to=check_str(obj, "to"), 45 weight=check_weight_or_none(obj, "weight"), 46 ) 47 48 assert alias.name != alias.to, "name and to must not be equal" 49 50 return alias 51 52 53def parse_alias_from_json(json_str) -> Alias: 54 """For testing purposes.""" 55 return parse_alias(_load_json_with_comment(json_str)) 56 57 58def parse_aliases(objs) -> [Alias]: 59 assert isinstance(objs, list), "aliases must be list" 60 return [parse_alias(obj) for obj in objs] 61 62 63def parse_aliases_from_json(json_str) -> [Alias]: 64 return parse_aliases(_load_json_with_comment(json_str)) 65