1#!/usr/bin/env python3 2# 3# Copyright 2018 - The Android Open Source Project 4# 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. 16from acts import utils 17 18 19class ConfigFileParser(object): 20 """A strategy base class for parsing config files.""" 21 22 def parse(self, file_path): 23 """Parses the file at the given path.""" 24 raise NotImplementedError 25 26 27class JsonFileParser(ConfigFileParser): 28 """A strategy class for parsing JSON files.""" 29 30 def parse(self, file_path): 31 """Parses a JSON file into a config dict.""" 32 # Suppress any error log message, but still raise an error upon failure. 33 return utils.load_config(file_path, log_errors=False) 34 35 36class ConfigFileLoader(object): 37 """A class that loads a config file, agnostic of config file type.""" 38 _file_parsers = [ 39 JsonFileParser() 40 ] 41 42 @classmethod 43 def load_config_from_file(cls, file_path): 44 exception_list = [] 45 for file_parser in cls._file_parsers: 46 try: 47 return file_parser.parse(file_path) 48 except Exception as e: 49 exception_list.append(e) 50 raise ValueError( 51 'Unable to find a suitable file parser for %s. Each file parser ' 52 'failed with the below errors:\n %s' % 53 (file_path, 54 ''.join(['%s: %s\n' % (type(cls._file_parsers[i]), 55 exception_list[i]) 56 for i in range(len(exception_list))]))) 57