1#!/usr/bin/env python3 2# -*- coding: utf-8 -*- 3 4# Copyright (c) 2021-2023 Huawei Device Co., Ltd. 5# Licensed under the Apache License, Version 2.0 (the "License"); 6# you may not use this file except in compliance with the License. 7# You may obtain a copy of the License at 8# 9# http://www.apache.org/licenses/LICENSE-2.0 10# 11# Unless required by applicable law or agreed to in writing, software 12# distributed under the License is distributed on an "AS IS" BASIS, 13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14# See the License for the specific language governing permissions and 15# limitations under the License. 16# 17# This file does only contain a selection of the most common options. For a 18# full list see the documentation: 19# http://www.sphinx-doc.org/en/master/config 20 21import logging 22from typing import Dict, Optional, List, Union, Any 23 24import yaml 25 26from runner import utils 27from runner.logger import Log 28 29_LOGGER = logging.getLogger("runner.options.yaml_document") 30 31 32class YamlDocument: 33 _document: Optional[Dict[str, Any]] = None 34 35 @staticmethod 36 def document() -> Optional[Dict[str, Any]]: 37 return YamlDocument._document 38 39 @staticmethod 40 def load(config_path: Optional[str]) -> None: 41 YamlDocument._document = {} 42 if config_path is None: 43 return 44 45 with open(config_path, "r", encoding="utf-8") as stream: 46 try: 47 YamlDocument._document = yaml.safe_load(stream) 48 except yaml.YAMLError as exc: 49 Log.exception_and_raise(_LOGGER, str(exc), yaml.YAMLError) 50 51 @staticmethod 52 def save(config_path: str, data: Dict[str, Any]) -> None: 53 data_to_save = yaml.dump(data, indent=4) 54 utils.write_2_file(config_path, data_to_save) 55 56 @staticmethod 57 def get_value_by_path(yaml_path: str) -> Optional[Union[int, bool, str, List[str]]]: 58 yaml_parts = yaml_path.split(".") 59 current: Any = YamlDocument._document 60 for part in yaml_parts: 61 if current and isinstance(current, dict) and part in current.keys(): 62 current = current.get(part) 63 else: 64 return None 65 if current is None or isinstance(current, (bool, int, list, str)): 66 return current 67 68 Log.exception_and_raise(_LOGGER, f"Unsupported value type '{type(current)}' for '{yaml_path}'") 69