1from configparser import ConfigParser 2import os 3import sys 4from collections import OrderedDict 5from typing import Any, Dict 6 7here = os.path.dirname(__file__) 8 9class ConfigDict(Dict[str, Any]): 10 def __init__(self, base_path, *args, **kwargs): 11 self.base_path = base_path 12 dict.__init__(self, *args, **kwargs) 13 14 def get_path(self, key, default=None): 15 if key not in self: 16 return default 17 path = self[key] 18 os.path.expanduser(path) 19 return os.path.abspath(os.path.join(self.base_path, path)) 20 21def read(config_path): 22 config_path = os.path.abspath(config_path) 23 config_root = os.path.dirname(config_path) 24 parser = ConfigParser() 25 success = parser.read(config_path) 26 assert config_path in success, success 27 28 subns = {"pwd": os.path.abspath(os.path.curdir)} 29 30 rv = OrderedDict() 31 for section in parser.sections(): 32 rv[section] = ConfigDict(config_root) 33 for key in parser.options(section): 34 rv[section][key] = parser.get(section, key, raw=False, vars=subns) 35 36 return rv 37 38def path(argv=None): 39 if argv is None: 40 argv = [] 41 path = None 42 43 for i, arg in enumerate(argv): 44 if arg == "--config": 45 if i + 1 < len(argv): 46 path = argv[i + 1] 47 elif arg.startswith("--config="): 48 path = arg.split("=", 1)[1] 49 if path is not None: 50 break 51 52 if path is None: 53 if os.path.exists("wptrunner.ini"): 54 path = os.path.abspath("wptrunner.ini") 55 else: 56 path = os.path.join(here, "..", "wptrunner.default.ini") 57 58 return os.path.abspath(path) 59 60def load(): 61 return read(path(sys.argv)) 62