Esempio n. 1
0
def start():
    opts = DEFAULT_OPTIONS

    # Remove default (None) values
    ops = {
        k: v
        for k, v in vars(parse_prelim_arguments()[0]).items() if v is not None
    }

    # Check if workdir is set, otherwise assume cwd
    if ops['workdir'] == "":
        ops['workdir'] = os.getcwd()
    else:
        ops['workdir'] = os.path.abspath(ops['workdir'])

    # Merge base config and file config (giving priority to file config)
    anyconfig.merge(opts,
                    parse_config_file_arguments(ops['workdir']),
                    ac_merge=anyconfig.MS_DICTS_AND_LISTS,
                    ac_parse_value=True)

    # Merge release into config to overwrite for release mode
    if ('release' in ops
            and ops['release']) or ('config' in opts
                                    and 'release' in opts['config']
                                    and opts['config']['release']):
        anyconfig.merge(opts['config'],
                        opts['release'],
                        ac_merge=anyconfig.MS_DICTS_AND_LISTS)

    # Merge CLI args
    anyconfig.merge(opts, {'config': ops},
                    ac_merge=anyconfig.MS_DICTS_AND_LISTS)

    opts = opts['config']

    opts = pythonify(opts)

    # Validate the config
    schema = anyconfig.load(
        __file__.replace("main.py", "") + "/concept/config_schema.json")
    anyconfig.validate(opts, schema, ac_schema_safe=False)

    # schema = anyconfig.gen_schema(opts, ac_schema_type="strict")
    # schema_s = anyconfig.dumps(schema, "json")
    #
    # with open(__file__.replace("main.py", "") + "/concept/config_schema.json", "w") as file:
    #     file.write(schema_s)

    if opts['print_options']:
        print(json.dumps(opts, sort_keys=True, indent=4))

    opts = munchify(opts)

    main(opts)
Esempio n. 2
0
    def _validate(self, config):
        try:
            anyconfig.validate(config, self.schema, ac_schema_safe=False)
        except jsonschema.exceptions.ValidationError as e:
            schema_error = "Failed validating '{validator}' in schema{schema}\n{message}".format(
                validator=e.validator,
                schema=format_as_index(list(e.relative_schema_path)[:-1]),
                message=e.message)
            raise ansibledoctor.exception.ConfigError("Configuration error",
                                                      schema_error)

        return True
Esempio n. 3
0
 def _validate(self, config):
     try:
         anyconfig.validate(config, self.schema, ac_schema_safe=False)
         return True
     except jsonschema.exceptions.ValidationError as e:
         schema_error = (
             "Error while loading configuration:\n"
             "Failed validating '{validator}' in schema{schema}").format(
                 validator=e.validator,
                 schema=format_as_index(list(e.relative_schema_path)[:-1]))
         utils.sysexit_with_message("{schema}: {msg}".format(
             schema=schema_error, msg=e.message))
Esempio n. 4
0
def load(path=None, with_defaults=False, validate=False):
    """
    Load the configuration.

    :param str path: configuration file path. If set to `None`, it makes the configuration file optional, meaning
        that either only the defaults will be loaded or that the configuration will be empty. Otherwise the
        loading will fail if the file is not found.
    :param bool with_defaults: if `True`, loads the default values when they are not specified in the configuration file
    :param bool validate: if `True`, validates the configuration. If an error is detected, a `SyntaxError`
        will be raised. The error message should indicate which part of the configuration file was invalid.
    :returns: (dict) A dictionary representing the configuration.
    """
    # Prepare the configuration dictionary, with the default values if requested.
    conf = CONFIGURATION_DEFAULTS if with_defaults else {}

    # Load the configuration file if specified.
    conf_from_file = {} if path is None else anyconfig.load(path)

    # Merge the configuration into the dictionary containing the defaults.
    # If `with_defaults` is False, this step simply loads the configuration file.
    anyconfig.merge(conf, conf_from_file)

    # Validate the configuration.
    if validate:
        (rc, err) = anyconfig.validate(conf, CONFIGURATION_SCHEMA)
        if not rc:
            raise SyntaxError(err)

    return conf
Esempio n. 5
0
    def read(self):
        """
        Parse the configs and validate it.

        It could be either local or from a local services
        (first local then packages by alphabetical order).
        """
        schema = anyconfig.multi_load(self.spec_files)
        config = anyconfig.multi_load(self.config_files)
        # Make sure the compiled configuration is valid
        try:
            anyconfig.validate(config, schema, safe=False)
        except _Error as error:
            self.error = '{} ({})'.format(error.message, ' -> '.join(map(str, error.path)))
            return False

        config['project_dir'] = path.realpath(path.dirname(self.config_file))
        if config['project_name'] == '':
            config['project_name'] = path.basename(config['project_dir'])

        return config
Esempio n. 6
0
    def __init__(self, file_path=FILENAME, spec_file_path=SPEC_FILENAME):
        self.config = DEFAULT_CONF
        conf_ = anyconfig.load(file_path)
        config_spec = anyconfig.load(spec_file_path)

        import re
        os_environ = environ.copy()
        re_exp = re.compile('radar_iot_.*')
        allowed_keys = filter(re_exp.match, os_environ.keys())
        environ_vars = {
            re.sub("radar_iot_", "", key, count=1): os_environ[key]
            for key in allowed_keys
        }

        anyconfig.merge(self.config, environ_vars)
        anyconfig.merge(self.config, conf_)
        (rc, err) = anyconfig.validate(self.config, config_spec)
        if rc is False or err != '':
            raise AttributeError('Invalid configuration', err)
        else:
            self.logger.info(
                f'Successfully loaded configuration from {self.FILENAME}')
Esempio n. 7
0
    def _validate(self) -> None:
        (rc, err) = anyconfig.validate(self.loaded_config, anyconfig.load(self.specs, ac_parser='yaml'))

        if err != '':
            raise ValueError('Your config is not valid: {}'.format(err))
Esempio n. 8
0
 def validate(self):
     # TODO: enumerate all errors by directly using `jsonschema`
     rc, err = anyconfig.validate(self._wrapped, self.schema)
     if err:
         raise ValueError(err)
Esempio n. 9
0
 def __validate_config(self, schema: str):
     """ Validates config using a json schema """
     schema = anyconfig.load(schema)
     anyconfig.validate(self.__config_dict, schema, ac_schema_safe=False)