def from_config_parser(cls, name: str, config_section: configparser.SectionProxy): """Parse a configuration from a configparser section""" # Default use_auth to True use_auth = DEFAULT_USE_AUTH try: use_auth = config_section.getboolean(CONFIG_USE_AUTH) except ValueError: pass # Get all secrets secrets = {} for config_key, config_val in config_section.items(): if config_key.startswith(CREDENTIALS_SECRET_PREFIX): # Of form "secret_GRAPHNAME" - parse GRAPHNAME graph_name = config_key.replace(CREDENTIALS_SECRET_PREFIX, "", 1) secrets[graph_name] = config_val return cls( name=name, server=config_section.get(CONFIG_SERVER_KEY, ""), client_version=config_section.get(CONFIG_CLIENT_VERSION_KEY, ""), restpp_port=config_section.get(CONFIG_RESTPP_PORT, DEFAULT_RESTPP_PORT).__str__(), gs_port=config_section.get(CONFIG_GS_PORT, DEFAULT_GS_PORT).__str__(), use_auth=use_auth, username=config_section.get(CREDENTIALS_USERNAME_KEY, ""), password=config_section.get(CREDENTIALS_PASSWORD_KEY, ""), secrets=secrets)
def from_config(cls, section: configparser.SectionProxy, option_handler_id: str = None) -> OptionHandler: """ Create a handler of this class based on the configuration in the config section. :param section: The configuration section :param option_handler_id: Optional extra identifier :return: A handler object :rtype: OptionHandler """ sub_options = [] for name, value in section.items(): # Strip numbers from the end, this can be used to supply the same option multiple times name = name.rstrip('0123456789-') if '-' in name or '_' in name: suboption_name = name.replace('_', '-').lower() else: suboption_name = camelcase_to_dash(name) suboption = name_registry.get(suboption_name) if not suboption: raise configparser.ParsingError("Unknown suboption: {}".format(suboption_name)) for suboption_value in re.split('[,\t ]+', value): if not suboption_value: raise configparser.ParsingError("{} option has no value".format(name)) sub_options.append(suboption.from_string(suboption_value)) return cls(sub_options)
def _parse_section(self, template: LinterOptions, section: SectionProxy) -> ConfigFileSection: parsed_section: ConfigFileSection = {} for option_key, option_value in section.items(): processed_value = self._parse_option(option_key, option_value, template, section) if processed_value: parsed_section[option_key] = processed_value return parsed_section
def from_config(cls, section: configparser.SectionProxy, option_handler_id: str = None) -> OptionHandler: """ Create a handler of this class based on the configuration in the config section. :param section: The configuration section :param option_handler_id: Optional extra identifier :return: A handler object :rtype: OptionHandler """ domain_names = [] for name, value in section.items(): # Strip numbers from the end, this can be used to supply the same option multiple times name = name.rstrip("0123456789-") if name != "domain-name": continue domain_names.append(value) return cls(domain_names)
def _parse_smart_section(section: configparser.SectionProxy): """ Convert a ConfigParser section into a python dictionary. Values within the section are converted dictionary keys. The section name is ignored. To ignore unrelated values any key starting with "env_" is ignored. Two types of keys are supported: simple keys [source] url=https://example.org => {'url': 'https://example.org'} subdict keys [source] filter.tenant=u6 filter.status=1 => {'filter': {'tenant': 'u6', 'status': '1'}} """ data: typing.Dict[str, typing.Union[str, typing.Dict[str, str]]] = {} for k, v in section.items(): if k.startswith('env_'): continue if '.' in k: # parse subdict value: filter.tenant=u6 k, _, kk = k.partition('.') if k not in data: data[k] = {} data[k][kk] = v else: # parse simple value: url=https://example.org data[k] = v return data
def clean_section(d: SectionProxy, **kwargs) -> Dict[Text, Any]: """ Helper to clean a ConfigParser's section and return as dictionary convert boolean values to bools, integer values to ints, float values to floats @param d: @param kwargs: @return: """ def get(option, chain: Iterator): try: return next(chain)(option) except (AttributeError, TypeError, ValueError): return get(option, chain) return { o: kwargs[o] if o in kwargs else get( o, iter((d.getint, d.getfloat, d.getboolean, d.get))) for o, v in { **dict(d.items()), **kwargs }.items() }
def convert_config_stanza(config: SectionProxy) -> t.Dict: return {k: v for k, v in config.items()}
def regexes(config_section: configparser.SectionProxy): return { category: re.compile(regex, re.IGNORECASE) for category, regex in config_section.items() }
def config_section_string(section: configparser.SectionProxy) -> str: data = { k: v if k != "password" else "<redacted>" for k, v in section.items() } return f"{data}"
def _parse_json(json: configparser.SectionProxy) -> JSON: return { key: IniReader.parse_value(value) for key, value in json.items() }
def parse_tags(tag_config: configparser.SectionProxy) -> List[Tag]: return [Tag(key, value) for key, value in tag_config.items()]