예제 #1
0
def load_config(config_file: Path) -> ConfigModel:
    if not config_file.is_file():
        logger.error('%s does not exist', config_file)
        raise SasstasticError('config files does not exist')
    try:
        with config_file.open('r') as f:
            data = yaml.load(f, Loader=Loader)
    except yaml.YAMLError as e:
        logger.error('invalid YAML file %s:\n%s', config_file, e)
        raise SasstasticError('invalid YAML file')
    try:
        config = ConfigModel.parse_obj(data)
    except ValidationError as exc:
        logger.error('Error parsing %s:\n%s', config_file,
                     display_errors(exc.errors()))
        raise SasstasticError('error parsing config file')
    config_dir = config_file.parent

    if not config.download.dir.is_absolute():
        config.download.dir = config_dir / config.download.dir

    if not config.build_dir.is_absolute():
        config.build_dir = config_dir / config.build_dir

    if not config.output_dir.is_absolute():
        config.output_dir = config_dir / config.output_dir
    return config
예제 #2
0
def load_config(config_file: Path) -> ConfigModel:
    if not config_file.is_file():
        logger.error('%s does not exist', config_file)
        raise SasstasticError('config files does not exist')
    try:
        with config_file.open('r') as f:
            data = yaml.load(f, Loader=Loader)
    except yaml.YAMLError as e:
        logger.error('invalid YAML file %s:\n%s', config_file, e)
        raise SasstasticError('invalid YAML file')

    try:
        return ConfigModel.parse_obj(config_file, data)
    except ValidationError as exc:
        logger.error('Error parsing %s:\n%s', config_file,
                     display_errors(exc.errors()))
        raise SasstasticError('error parsing config file')
예제 #3
0
def create_app_environment(event: Mapping[str, object]) -> Dict[str, object]:
    parsed_event = EventModelBodyParameters.parse_obj(event)
    if "appName" not in parsed_event.pathParameters:
        raise Exception(f"There is not a appName field")

    appName = parsed_event.pathParameters["appName"].lower()
    user_email = parsed_event.requestContext.authorizer.user_email
    print(f"appName: {appName} and user_email: {user_email}")

    body_string = "{}" if parsed_event.body is None or parsed_event.body == "" else parsed_event.body
    try:
        body = json.loads(body_string)
        validate_input_data = PostAppEventBody.parse_obj(body)
        app_environment_name = validate_input_data.environment
        print(f"App Environment Name: {app_environment_name}")
    except ValidationError as e:
        msg = display_errors(e.errors())
        return {"statusCode": 400, "body": json.dumps({"msg": msg})}
예제 #4
0
def config_file_settings_source(
    settings: EventedConfigFileSettings,
) -> Dict[str, Any]:
    """Read config files during init of an EventedConfigFileSettings obj.

    The two important values are the `settings._config_path`
    attribute, which is the main config file (if present), and
    `settings.__config__.source`, which is an optional list of additional files
    to read. (files later in the list take precedence and `_config_path` takes
    precedence over all)

    Parameters
    ----------
    settings : EventedConfigFileSettings
        The new model instance (not fully instantiated)

    Returns
    -------
    dict
        *validated* values for the model.
    """
    # _config_path is the primary config file on the model (the one to save to)
    config_path = getattr(settings, '_config_path', None)

    default_cfg = type(settings).__private_attributes__.get('_config_path')
    default_cfg = getattr(default_cfg, 'default', None)

    # if the config has a `sources` list, read those too and merge.
    sources = list(getattr(settings.__config__, 'sources', []))
    if config_path:
        sources.append(config_path)
    if not sources:
        return {}

    data: dict = {}
    for path in sources:
        if not path:
            continue  # pragma: no cover
        _path = Path(path).expanduser().resolve()

        # if the requested config path does not exist, move on to the next
        if not _path.is_file():
            # if it wasn't the `_config_path` stated in the BaseModel itself,
            # we warn, since this would have been user provided.
            if _path != default_cfg:
                _logger.warning(
                    trans._(
                        "Requested config path is not a file: {path}",
                        path=_path,
                    )
                )
            continue

        # get loader for yaml/json
        if str(path).endswith(('.yaml', '.yml')):
            load = __import__('yaml').safe_load
        elif str(path).endswith(".json"):
            load = __import__('json').load
        else:
            warn(
                trans._(
                    "Unrecognized file extension for config_path: {path}",
                    path=path,
                )
            )
            continue

        try:
            # try to parse the config file into a dict
            new_data = load(_path.read_text()) or {}
        except Exception as err:
            _logger.warning(
                trans._(
                    "The content of the napari settings file could not be read\n\nThe default settings will be used and the content of the file will be replaced the next time settings are changed.\n\nError:\n{err}",
                    deferred=True,
                    err=err,
                )
            )
            continue
        assert isinstance(new_data, dict), _path.read_text()
        deep_update(data, new_data, copy=False)

    try:
        # validate the data, passing config_path=None so we dont recurse
        # back to this point again.
        type(settings)(config_path=None, **data)
    except ValidationError as err:
        if getattr(settings.__config__, 'strict_config_check', False):
            raise

        # if errors occur, we still want to boot, so we just remove bad keys
        errors = err.errors()
        msg = trans._(
            "Validation errors in config file(s).\nThe following fields have been reset to the default value:\n\n{errors}\n",
            deferred=True,
            errors=display_errors(errors),
        )
        try:
            # we're about to nuke some settings, so just in case... try backup
            backup_path = _path.parent / f'{_path.stem}.BAK{_path.suffix}'
            backup_path.write_text(_path.read_text())
        except Exception:
            pass

        _logger.warning(msg)
        try:
            _remove_bad_keys(data, [e.get('loc', ()) for e in errors])
        except KeyError:  # pragma: no cover
            _logger.warning(
                trans._(
                    'Failed to remove validation errors from config file. Using defaults.'
                )
            )
            data = {}
    # store data at this state for potential later recovery
    settings._config_file_settings = data
    return data