Skip to content

typerdrive Settings modules

typerdrive.settings.attach

Provide a decorator that attaches the typerdrive settings to a typer command function.

Attributes

Classes

Functions:

attach_settings

attach_settings(
    settings_model: type[BaseModel],
    *,
    validation: Validation = Validation.BEFORE,
    persist: bool = False,
    show: bool = False,
) -> Callable[
    [ContextFunction[P, T]], ContextFunction[P, T]
]

Attach the typerdrive settings to the decorated typer command function.

Parameters:

Name Type Description Default
validation Validation

Indicates when validation should happen in the decorator:

    - If `BEFORE`, validate before calling the function
    - If `AFTER`, validate after calling the function
    - If `BOTH`, validate before and after calling the function
    - If `NEVER`, don't validate
BEFORE
persist bool

If set, the settings values will be stored in the settings file

False
show bool

If set, show the current settings after running the function

False
Source code in src/typerdrive/settings/attach.py
def attach_settings(
    settings_model: type[BaseModel],
    *,
    validation: Validation = Validation.BEFORE,
    persist: bool = False,
    show: bool = False,
) -> Callable[[ContextFunction[P, T]], ContextFunction[P, T]]:
    """
    Attach the `typerdrive` settings to the decorated `typer` command function.

    Parameters:
        validation: Indicates when validation should happen in the decorator:

                    - If `BEFORE`, validate before calling the function
                    - If `AFTER`, validate after calling the function
                    - If `BOTH`, validate before and after calling the function
                    - If `NEVER`, don't validate

        persist:    If set, the settings values will be stored in the settings file
        show:       If set, show the current settings after running the function
    """

    def _decorate(func: ContextFunction[P, T]) -> ContextFunction[P, T]:
        manager_param_key: str | None = None
        settings_param_key: str | None = None
        rewriter = SignatureRewriter(func)
        for key, hint in rewriter.hints.items():
            if hint is settings_model:
                rewriter.cloak(key, Annotated[settings_model | None, CloakingDevice])  # type: ignore[invalid-type-form]
                settings_param_key = key
            elif hint is SettingsManager:
                rewriter.cloak(key, Annotated[SettingsManager | None, CloakingDevice])
                manager_param_key = key

        def wrapper(ctx: typer.Context, *args: P.args, **kwargs: P.kwargs) -> T:
            manager: SettingsManager = SettingsManager(settings_model)

            if validation & Validation.BEFORE:
                SettingsError.require_condition(
                    len(manager.invalid_warnings) == 0,
                    f"Initial settings are invalid: {manager.invalid_warnings}",
                )
            to_context(ctx, "settings_manager", manager)

            kwargs_dict = cast(dict[str, Any], kwargs)
            if settings_param_key:
                kwargs_dict[settings_param_key] = manager.settings_instance

            if manager_param_key:
                kwargs_dict[manager_param_key] = manager

            ret_val = func(ctx, *args, **kwargs)

            if validation & Validation.AFTER:
                with SettingsError.handle_errors("Final settings are invalid"):
                    manager.validate()

            if persist:
                manager.save()
            if show:
                terminal_message(
                    manager.pretty(),
                    subject="Current settings",
                    footer=f"saved to {manager.settings_path}" if persist else None,
                )

            return ret_val

        rewriter.apply(wrapper)
        return wrapper

    return _decorate

get_settings

get_settings(ctx: Context, type_hint: type[ST]) -> ST

Get the settings instance from the TyperdriveContext.

Source code in src/typerdrive/settings/attach.py
def get_settings[ST: BaseModel](
    ctx: typer.Context,
    type_hint: type[ST],
) -> ST:
    """
    Get the settings instance from the `TyperdriveContext`.
    """
    return SettingsError.ensure_type(
        get_settings_manager(ctx).settings_instance,
        type_hint,
        f"Settings instance doesn't match expected {type_hint=}",
    )

get_settings_manager

get_settings_manager(ctx: Context) -> SettingsManager

Retrieve the SettingsManager from the TyperdriveContext.

Source code in src/typerdrive/settings/attach.py
def get_settings_manager(ctx: typer.Context) -> SettingsManager:
    """
    Retrieve the `SettingsManager` from the `TyperdriveContext`.
    """
    with SettingsError.handle_errors("Settings are not bound to the context. Use the @attach_settings() decorator"):
        mgr: Any = from_context(ctx, "settings_manager")
    return SettingsError.ensure_type(
        mgr,
        SettingsManager,
        "Item in user context at `settings_manager` was not a SettingsManager",
    )

get_settings_value

get_settings_value(ctx: Context, settings_key: str) -> Any

Get a particular settings value from the TyperdriveContext.

Source code in src/typerdrive/settings/attach.py
def get_settings_value(ctx: typer.Context, settings_key: str) -> Any:
    """
    Get a particular settings value from the `TyperdriveContext`.
    """
    instance: BaseModel = get_settings_manager(ctx).settings_instance
    ret = getattr(instance, settings_key, Sentinel.MISSING)
    SettingsError.require_condition(
        ret is not Sentinel.MISSING,
        f"Settings instance doesn't have field {settings_key}",
    )
    return ret

typerdrive.settings.commands

Provide commands that can be added to a typer app to manage settings.

Classes

Functions:

add_bind

add_bind(cli: Typer, settings_model: type[BaseModel])

Add the bind command to the given typer app.

Source code in src/typerdrive/settings/commands.py
def add_bind(cli: typer.Typer, settings_model: type[BaseModel]):
    """
    Add the `bind` command to the given `typer` app.
    """
    opt_defs: list[OptDef] = []
    for name, field_info in settings_model.model_fields.items():
        default = field_info.default if field_info.default is not PydanticUndefined else Sentinel.NOT_GIVEN
        annotation: Any = SettingsError.enforce_defined(field_info.annotation, "Option type may not be `None`")

        secret_cli_type = _secret_cli_type(annotation)
        is_secret = secret_cli_type is not None
        is_collection = is_model_collection(annotation)
        is_nested_model = is_model_type(annotation)

        opt_kwargs: dict[str, Any] = {
            "name": name,
            "param_type": secret_cli_type if is_secret else str if is_collection else annotation,
            "default": default.get_secret_value() if isinstance(default, SecretStr) else default,
            "help": field_info.description,
            "show_default": not is_secret,
            "hide_input": is_secret,
        }
        if not is_secret and (is_nested_model or is_collection):
            opt_kwargs["parser"] = make_parser(annotation)
            opt_kwargs["metavar"] = pretty_model(annotation) if is_nested_model else pretty_annotation(annotation)

        opt_defs.append(OptDef(**opt_kwargs))
    build_command(
        cli,
        bind,
        *opt_defs,
        decorators=[
            DecDef(
                dec_func=handle_errors,
                dec_args=["Failed to bind settings"],
                dec_kwargs={
                    "handle_exc_class": SettingsError,
                    "unwrap_message": False,
                    "debug": True,
                },
                is_simple=False,
            ),
            DecDef(
                dec_func=attach_settings,
                dec_args=[settings_model],
                dec_kwargs={"validation": Validation.AFTER, "persist": True, "show": True},
                is_simple=False,
            ),
        ],
        include_context=True,
    )

add_encryption_reset

add_encryption_reset(
    cli: Typer, settings_model: type[BaseModel]
)

Add the reset command to the given encryption subcommand app.

Source code in src/typerdrive/settings/commands.py
def add_encryption_reset(cli: typer.Typer, settings_model: type[BaseModel]):
    """
    Add the `reset` command to the given `encryption` subcommand app.
    """

    def encryption_reset() -> None:
        """Remove the secret encryption identity and reset all encrypted settings values to their defaults."""
        SecretEncryption, secret_encryption_error = _require_encryption()
        with _encryption_errors(secret_encryption_error):
            config = get_typerdrive_config()
            encryption = SecretEncryption(config)
            if not encryption.material_path.exists():
                typer.echo("There is no secret encryption identity to reset.", err=True)
                raise typer.Exit(1)
            typer.confirm(
                "This permanently removes the encryption identity and resets all encrypted settings values to their"
                " defaults. Continue?",
                abort=True,
            )
            try:
                settings = json.loads(config.settings_path.read_text(encoding="utf-8"))
            except FileNotFoundError:
                settings = None
            except (ValueError, UnicodeError, RecursionError):
                typer.echo("Cannot read the settings file; restore or repair it before resetting.", err=True)
                raise typer.Exit(1) from None
            if settings is not None:
                content = json.dumps(reset_encrypted_fields(settings_model, settings), indent=2)
                atomic_write(config.settings_path, content.encode("utf-8"))
            encryption.reset()
            typer.echo(
                "Secret encryption identity removed and encrypted settings reset. Run `encryption setup` to start over."
            )

    cli.command("reset")(encryption_reset)

add_reset

add_reset(cli: Typer, settings_model: type[BaseModel])

Add the reset command to the given typer app.

Source code in src/typerdrive/settings/commands.py
def add_reset(cli: typer.Typer, settings_model: type[BaseModel]):
    """
    Add the `reset` command to the given `typer` app.
    """
    build_command(
        cli,
        reset,
        decorators=[
            DecDef(
                dec_func=handle_errors,
                dec_args=["Failed to reset settings"],
                dec_kwargs={
                    "handle_exc_class": SettingsError,
                    "unwrap_message": False,
                    "debug": True,
                },
                is_simple=False,
            ),
            DecDef(
                dec_func=attach_settings,
                dec_args=[settings_model],
                dec_kwargs={"validation": Validation.NEVER, "persist": True, "show": True},
                is_simple=False,
            ),
        ],
        include_context=True,
    )

add_settings_subcommand

add_settings_subcommand(
    cli: Typer, settings_model: type[BaseModel]
)

Add all settings commands to the given app.

Source code in src/typerdrive/settings/commands.py
def add_settings_subcommand(cli: typer.Typer, settings_model: type[BaseModel]):
    """
    Add all `settings` commands to the given app.
    """
    settings_cli = typer.Typer(help="Manage settings for the app", invoke_without_command=True, no_args_is_help=True)

    for cmd in [add_bind, add_update, add_unset, add_reset, add_show]:
        cmd(settings_cli, settings_model)

    encryption_cli = typer.Typer(
        help="Manage encryption of secret settings values", invoke_without_command=True, no_args_is_help=True
    )
    for name, command in [
        ("setup", encryption_setup),
        ("change-passphrase", encryption_change_passphrase),
        ("lock", encryption_lock),
        ("unlock", encryption_unlock),
    ]:
        encryption_cli.command(name)(command)
    add_encryption_reset(encryption_cli, settings_model)
    settings_cli.add_typer(encryption_cli, name="encryption")

    cli.add_typer(settings_cli, name="settings")

add_show

add_show(cli: Typer, settings_model: type[BaseModel])

Add the show command to the given typer app.

Source code in src/typerdrive/settings/commands.py
def add_show(cli: typer.Typer, settings_model: type[BaseModel]):
    """
    Add the `show` command to the given `typer` app.
    """
    build_command(
        cli,
        show,
        decorators=[
            DecDef(
                dec_func=handle_errors,
                dec_args=["Failed to show settings"],
                dec_kwargs={
                    "handle_exc_class": SettingsError,
                    "unwrap_message": False,
                    "debug": True,
                },
                is_simple=False,
            ),
            DecDef(
                dec_func=attach_settings,
                dec_args=[settings_model],
                dec_kwargs={"validation": Validation.NEVER, "persist": False, "show": True},
                is_simple=False,
            ),
        ],
        include_context=True,
    )

add_unset

add_unset(cli: Typer, settings_model: type[BaseModel])

Add the unset command to the given typer app.

Source code in src/typerdrive/settings/commands.py
def add_unset(cli: typer.Typer, settings_model: type[BaseModel]):
    """
    Add the `unset` command to the given `typer` app.
    """
    opt_defs: list[OptDef] = []
    for name, field_info in settings_model.model_fields.items():
        opt_defs.append(
            OptDef(
                name=name,
                param_type=bool,
                default=False,
                help=field_info.description,
                show_default=True,
                override_name=name,
            )
        )
    build_command(
        cli,
        unset,
        *opt_defs,
        decorators=[
            DecDef(
                dec_func=handle_errors,
                dec_args=["Failed to unset settings"],
                dec_kwargs={
                    "handle_exc_class": SettingsError,
                    "unwrap_message": False,
                    "debug": True,
                },
                is_simple=False,
            ),
            DecDef(
                dec_func=attach_settings,
                dec_args=[settings_model],
                dec_kwargs={"validation": Validation.NEVER, "persist": True, "show": True},
                is_simple=False,
            ),
        ],
        include_context=True,
    )

add_update

add_update(cli: Typer, settings_model: type[BaseModel])

Add the update command to the given typer app.

Source code in src/typerdrive/settings/commands.py
def add_update(cli: typer.Typer, settings_model: type[BaseModel]):
    """
    Add the `update` command to the given `typer` app.
    """
    opt_defs: list[OptDef] = []
    for name, field_info in settings_model.model_fields.items():
        annotation: Any = SettingsError.enforce_defined(field_info.annotation, "Option type may not be `None`")
        default: None | bool = None
        is_secret = _secret_cli_type(annotation) is not None
        is_collection = is_model_collection(annotation)
        is_nested_model = is_model_type(annotation)
        cli_type = str if is_secret or is_collection else annotation
        opt_kwargs: dict[str, Any] = {
            "name": name,
            "param_type": cli_type | None,
            "default": default,
            "help": field_info.description,
            "show_default": not is_secret,
            "hide_input": is_secret,
        }
        if not is_secret and (is_nested_model or is_collection):
            opt_kwargs["parser"] = make_parser(annotation)
            opt_kwargs["metavar"] = pretty_model(annotation) if is_nested_model else pretty_annotation(annotation)

        opt_defs.append(OptDef(**opt_kwargs))
    build_command(
        cli,
        update,
        *opt_defs,
        decorators=[
            DecDef(
                dec_func=handle_errors,
                dec_args=["Failed to update settings"],
                dec_kwargs={
                    "handle_exc_class": SettingsError,
                    "unwrap_message": False,
                    "debug": True,
                },
                is_simple=False,
            ),
            DecDef(
                dec_func=attach_settings,
                dec_args=[settings_model],
                dec_kwargs={"validation": Validation.NEVER, "persist": True, "show": True},
                is_simple=False,
            ),
        ],
        include_context=True,
    )

bind

bind(ctx: Context)

Bind all settings for the app.

Source code in src/typerdrive/settings/commands.py
def bind(ctx: typer.Context):
    """
    Bind all settings for the app.
    """
    __manager: SettingsManager = get_settings_manager(ctx)
    excluded_locals = ["__manager", "ctx"]
    settings_values = {k: v for (k, v) in locals().items() if k not in excluded_locals}
    __manager.update(**settings_values)

encryption_change_passphrase

encryption_change_passphrase() -> None

Change the secret encryption passphrase.

Source code in src/typerdrive/settings/commands.py
def encryption_change_passphrase() -> None:
    """Change the secret encryption passphrase."""
    SecretEncryption, secret_encryption_error = _require_encryption()
    with _encryption_errors(secret_encryption_error):
        encryption = SecretEncryption(get_typerdrive_config())
        if _is_unprotected(encryption):
            typer.echo("Cannot change the passphrase of an unprotected key; migration is not supported.", err=True)
            raise typer.Exit(1)
        old = _passphrase("Current passphrase")
        new = _passphrase("New passphrase", confirm=True)
        encryption.change_passphrase(old, new)
        typer.echo("Secret encryption passphrase changed.")

encryption_lock

encryption_lock() -> None

Remove the cached secret encryption identity.

Source code in src/typerdrive/settings/commands.py
def encryption_lock() -> None:
    """Remove the cached secret encryption identity."""
    SecretEncryption, secret_encryption_error = _require_encryption()
    with _encryption_errors(secret_encryption_error):
        SecretEncryption(get_typerdrive_config()).lock()
        typer.echo("Cached identity removed; an unprotected key remains usable without a passphrase.")

encryption_setup

encryption_setup(
    no_passphrase: Annotated[
        bool,
        Option(
            --no - passphrase,
            help="Store the identity without passphrase protection.",
        ),
    ] = False,
) -> None

Create secret encryption key material.

Source code in src/typerdrive/settings/commands.py
def encryption_setup(
    no_passphrase: Annotated[
        bool, typer.Option("--no-passphrase", help="Store the identity without passphrase protection.")
    ] = False,
) -> None:
    """Create secret encryption key material."""
    SecretEncryption, secret_encryption_error = _require_encryption()
    with _encryption_errors(secret_encryption_error):
        config = get_typerdrive_config()
        encryption = SecretEncryption(config)
        if encryption.material_path.exists():
            typer.echo("Secret encryption key material already exists; it will not be replaced.", err=True)
            raise typer.Exit(1)
        try:
            settings = json.loads(config.settings_path.read_text(encoding="utf-8"))
        except FileNotFoundError:
            settings = None
        except (ValueError, UnicodeError, RecursionError):
            typer.echo("Cannot inspect settings for encrypted secrets; restore or repair the settings file.", err=True)
            raise typer.Exit(1) from None
        if _contains_age_marker(settings):
            typer.echo("Encrypted settings found without key material; restore the original key material.", err=True)
            raise typer.Exit(1)
        encryption.setup(None if no_passphrase else _passphrase("New passphrase", confirm=True))
        if no_passphrase:
            typer.echo("Secret encryption set up; the identity is stored without passphrase protection.")
        else:
            typer.echo("Secret encryption set up.")

encryption_unlock

encryption_unlock() -> None

Unlock the secret encryption identity.

Source code in src/typerdrive/settings/commands.py
def encryption_unlock() -> None:
    """Unlock the secret encryption identity."""
    SecretEncryption, secret_encryption_error = _require_encryption()
    with _encryption_errors(secret_encryption_error):
        config = get_typerdrive_config()
        encryption = SecretEncryption(config)
        if _is_unprotected(encryption):
            typer.echo("Cannot unlock an unprotected key; it is already usable without a passphrase.", err=True)
            raise typer.Exit(1)
        encryption.unlock(_passphrase("Secret encryption passphrase"))
        if config.encryption_cache_ttl == 0:
            typer.echo("Passphrase verified; identity caching is disabled.")
        else:
            typer.echo("Secret encryption unlocked.")

reset

reset(ctx: Context)

Remove all settings from the app.

Source code in src/typerdrive/settings/commands.py
def reset(ctx: typer.Context):
    """
    Remove all settings from the app.
    """
    typer.confirm("Are you sure you want to reset your settings?", abort=True)
    __manager: SettingsManager = get_settings_manager(ctx)
    __manager.reset()
    try:
        import_module("pyrage")
    except ModuleNotFoundError:
        return
    SecretEncryption, _ = _require_encryption()
    SecretEncryption(get_typerdrive_config()).reset()

show

show(ctx: Context)

Show the current app's settings.

Source code in src/typerdrive/settings/commands.py
def show(ctx: typer.Context):
    """
    Show the current app's settings.
    """

unset

unset(ctx: Context)

Remove some settings from the app.

Source code in src/typerdrive/settings/commands.py
def unset(ctx: typer.Context):
    """
    Remove some settings from the app.
    """
    __manager: SettingsManager = get_settings_manager(ctx)
    excluded_locals = ["__manager", "ctx"]
    settings_values = {k: v for (k, v) in locals().items() if k not in excluded_locals and v}
    __manager.unset(*settings_values.keys())

update

update(ctx: Context)

Update some settings for the app.

Source code in src/typerdrive/settings/commands.py
def update(ctx: typer.Context):
    """
    Update some settings for the app.
    """
    __manager: SettingsManager = get_settings_manager(ctx)
    excluded_locals = ["__manager", "ctx"]
    settings_values = {k: v for (k, v) in locals().items() if k not in excluded_locals and v is not None}
    __manager.update(**settings_values)

typerdrive.settings.exceptions

Provide exceptions specific to the settings feature of typerdrive.

Classes

SecretEncryptionError

Bases: SettingsError

Indicates invalid or unavailable encryption material.

Source code in src/typerdrive/settings/exceptions.py
class SecretEncryptionError(SettingsError):
    """
    Indicates invalid or unavailable encryption material.
    """

SecretValueError

Bases: SettingsError, ValueError

Indicates an input value that cannot be an encrypted secret.

Subclasses ValueError so that pydantic reports it as a validation failure.

Source code in src/typerdrive/settings/exceptions.py
class SecretValueError(SettingsError, ValueError):
    """
    Indicates an input value that cannot be an encrypted secret.

    Subclasses `ValueError` so that pydantic reports it as a validation failure.
    """

SettingsDisplayError

Bases: SettingsError

Indicates that there was a problem showing the settings.

Source code in src/typerdrive/settings/exceptions.py
class SettingsDisplayError(SettingsError):
    """
    Indicates that there was a problem showing the settings.
    """

SettingsError

Bases: TyperdriveError

The base exception for settings errors.

Source code in src/typerdrive/settings/exceptions.py
class SettingsError(TyperdriveError):
    """
    The base exception for settings errors.
    """

    exit_code: ExitCode = ExitCode.GENERAL_ERROR
Attributes
exit_code class-attribute instance-attribute
exit_code: ExitCode = ExitCode.GENERAL_ERROR

SettingsInitError

Bases: SettingsError

Indicates that there was a problem initializing the settings.

Source code in src/typerdrive/settings/exceptions.py
class SettingsInitError(SettingsError):
    """
    Indicates that there was a problem initializing the settings.
    """

SettingsResetError

Bases: SettingsError

Indicates that there was a problem resetting a settings value.

Source code in src/typerdrive/settings/exceptions.py
class SettingsResetError(SettingsError):
    """
    Indicates that there was a problem resetting a settings value.
    """

SettingsSaveError

Bases: SettingsError

Indicates that there was a problem saving the settings to disk.

Source code in src/typerdrive/settings/exceptions.py
class SettingsSaveError(SettingsError):
    """
    Indicates that there was a problem saving the settings to disk.
    """

SettingsUnsetError

Bases: SettingsError

Indicates that there was a problem unsetting a settings value.

Source code in src/typerdrive/settings/exceptions.py
class SettingsUnsetError(SettingsError):
    """
    Indicates that there was a problem unsetting a settings value.
    """

SettingsUpdateError

Bases: SettingsError

Indicates that there was a problem updating a settings value.

Source code in src/typerdrive/settings/exceptions.py
class SettingsUpdateError(SettingsError):
    """
    Indicates that there was a problem updating a settings value.
    """

typerdrive.settings.manager

Provide a class for managing the typerdrive settings feature.

Attributes

Classes

SettingsManager

Manage settings for the typerdrive app.

Source code in src/typerdrive/settings/manager.py
class SettingsManager:
    """
    Manage settings for the `typerdrive` app.
    """

    settings_model: type[BaseModel]
    """ A `pydantic` model _type_ that defines the app's settings """

    settings_path: Path
    """ The path to the file where settings are persisted """

    invalid_warnings: dict[str, str]
    """ Tracks which fields of the settings instance are invalid """

    settings_instance: BaseModel
    """ An instance of the `settings_model` that holds the app's current settings """

    def __init__(self, settings_model: type[BaseModel]):
        config: TyperdriveConfig = get_typerdrive_config()

        self.settings_model = settings_model
        self.settings_path = config.settings_path
        self.invalid_warnings = {}

        with SettingsInitError.handle_errors("Failed to initialize settings"):
            settings_values: dict[str, Any] = {}
            loading = self.settings_path.exists()
            if loading:
                settings_values = json.loads(self.settings_path.read_text())
            self._construct_instance(settings_values, loading=loading)

    def construct_instance(self, **settings_values: Any):
        self._construct_instance(settings_values)

    def _construct_instance(self, settings_values: dict[str, Any], loading: bool = False):
        context: dict[str, Any] = {LOADING_CONTEXT_KEY: loading}
        error = None
        try:
            instance = self.settings_model.model_validate(settings_values, context=context)
        except ValidationError as err:
            instance = construct_permissive(self.settings_model, context, **settings_values)
            error = err
        self.settings_instance = instance
        if error is None:
            self.invalid_warnings = {}
        else:
            self.set_warnings(error)

    def set_warnings(self, err: ValidationError):
        """Extract field names and messages from a validation error."""
        self.invalid_warnings = {}
        for data in err.errors():
            key: str = cast(str, data["loc"][0])
            message = data["msg"]
            self.invalid_warnings[key] = message

    def dump(self) -> dict[str, Any]:
        """Dump settings as plain JSON-compatible data, with all secrets unwrapped."""
        return self.settings_instance.model_dump(mode="json", context={DUMP_CONTEXT_KEY: DumpMode.PLAINTEXT})

    def _snapshot(self) -> dict[str, Any]:
        """Dump settings for re-validation. Secrets stay wrapped, so encrypted secrets remain lazy."""
        instance = self.settings_instance
        return {name: getattr(instance, name) for name in type(instance).model_fields if hasattr(instance, name)}

    def to_dict(self) -> dict[str, Any]:
        """Return settings values as plain data."""
        return self.dump()

    def update(self, **settings_values: Any):
        """Update settings and retain warnings for invalid values."""
        logger.debug("Updating settings")
        with SettingsUpdateError.handle_errors("Failed to update settings"):
            combined_settings = {**self._snapshot(), **settings_values}
            self.construct_instance(**combined_settings)

    def unset(self, *unset_keys: str):
        """Remove the settings corresponding to the provided keys."""
        logger.debug(f"Unsetting keys {unset_keys}")
        with SettingsUnsetError.handle_errors("Failed to remove keys"):
            settings_values = {key: value for key, value in self._snapshot().items() if key not in unset_keys}
            self.construct_instance(**settings_values)

    def reset(self):
        """Reset the settings back to defaults."""
        logger.debug("Resetting all settings")

        with SettingsResetError.handle_errors("Failed to reset settings"):
            self.construct_instance()

    def validate(self):
        """
        Validate the current settings values.

        If invalid, `ValidationError` exceptions will be raised
        """
        self.settings_model.model_validate(self._snapshot())

    def pretty(self, with_style: bool = True) -> RenderableType:
        """Return a pretty representation of the settings."""
        (bold_, _bold) = ("[bold]", "[/bold]") if with_style else ("", "")
        (italic_, _italic) = ("[italic]", "[/italic]") if with_style else ("", "")
        (underline_, _underline) = ("[underline]", "[/underline]") if with_style else ("", "")
        (red_, _red) = ("[red]", "[/red]") if with_style else ("", "")
        (blue_, _blue) = ("[blue]", "[/blue]") if with_style else ("", "")

        nested: list[str] = []
        items: list[RenderableType] = []
        values_table: Table = Table(
            title="Settings Values",
            title_style="bold underline",
            title_justify="left",
            box=None,
        )
        values_table.add_column(justify="right", style="bold", no_wrap=True)
        values_table.add_column(justify="left", style="italic", no_wrap=True)
        values_table.add_column(justify="center")
        values_table.add_column(justify="left", no_wrap=True)

        for field_name, field_info in self.settings_instance.__class__.model_fields.items():
            if field_name == "invalid_warning":
                continue
            try:
                val = getattr(self.settings_instance, field_name)
                field_string = str(val)
            except AttributeError:
                field_string = "<UNSET>"
            if field_name in self.invalid_warnings:
                field_string = f"{red_}{field_string}{_red}"
            annotation = SettingsDisplayError.enforce_defined(
                field_info.annotation, f"The field info annotation for {field_info} was not defined!"
            )
            field_type: str = f"{italic_}{pretty_annotation(annotation)}{_italic}"
            if is_model_type(annotation) or is_model_collection(annotation):
                field_type = f"{blue_}{field_type}*{_blue}"
                nested.append(pretty_field_info(field_info))
            values_table.add_row(dasherize(field_name), field_type, "->", field_string)

        items.append(values_table)

        if self.invalid_warnings:
            items.extend(["", ""])
            invalid_table: Table = Table(
                title="Invalid Values",
                title_style="bold underline",
                title_justify="left",
                box=None,
            )
            invalid_table.add_column(justify="right", style="bold", no_wrap=True)
            invalid_table.add_column(justify="center")
            invalid_table.add_column(justify="left", no_wrap=True)
            for field_name, invalid_warning in self.invalid_warnings.items():
                invalid_table.add_row(dasherize(field_name), "->", invalid_warning)
            items.append(invalid_table)

        if nested:
            items.extend(["", "", f"{blue_}{bold_}{underline_}{_underline}{_bold}{_blue}"])
            nested_table: Table = Table(
                title="*Nested Model Types",
                title_style="blue bold underline",
                title_justify="left",
                box=None,
            )
            nested_table.add_column(style="bold")
            for model in nested:
                nested_table.add_row(model)
            items.append(nested_table)

        return Group(*items)

    def save(self):
        """Write the current settings to disk."""
        logger.debug(f"Saving settings to {self.settings_path}")

        with SettingsSaveError.handle_errors(f"Failed to save settings to {self.settings_path}"):
            data = self.settings_instance.model_dump(
                mode="json",
                include=set(type(self.settings_instance).model_fields),
                context={DUMP_CONTEXT_KEY: DumpMode.PERSIST},
            )
            content = json.dumps(data, indent=2)
            self.settings_path.parent.mkdir(parents=True, exist_ok=True)
            atomic_write(self.settings_path, content.encode("utf-8"))
Attributes
invalid_warnings instance-attribute
invalid_warnings: dict[str, str] = {}

Tracks which fields of the settings instance are invalid

settings_instance instance-attribute
settings_instance: BaseModel

An instance of the settings_model that holds the app's current settings

settings_model instance-attribute
settings_model: type[BaseModel] = settings_model

A pydantic model type that defines the app's settings

settings_path instance-attribute
settings_path: Path = config.settings_path

The path to the file where settings are persisted

Methods:
__init__
__init__(settings_model: type[BaseModel])
Source code in src/typerdrive/settings/manager.py
def __init__(self, settings_model: type[BaseModel]):
    config: TyperdriveConfig = get_typerdrive_config()

    self.settings_model = settings_model
    self.settings_path = config.settings_path
    self.invalid_warnings = {}

    with SettingsInitError.handle_errors("Failed to initialize settings"):
        settings_values: dict[str, Any] = {}
        loading = self.settings_path.exists()
        if loading:
            settings_values = json.loads(self.settings_path.read_text())
        self._construct_instance(settings_values, loading=loading)
construct_instance
construct_instance(**settings_values: Any)
Source code in src/typerdrive/settings/manager.py
def construct_instance(self, **settings_values: Any):
    self._construct_instance(settings_values)
dump
dump() -> dict[str, Any]

Dump settings as plain JSON-compatible data, with all secrets unwrapped.

Source code in src/typerdrive/settings/manager.py
def dump(self) -> dict[str, Any]:
    """Dump settings as plain JSON-compatible data, with all secrets unwrapped."""
    return self.settings_instance.model_dump(mode="json", context={DUMP_CONTEXT_KEY: DumpMode.PLAINTEXT})
pretty
pretty(with_style: bool = True) -> RenderableType

Return a pretty representation of the settings.

Source code in src/typerdrive/settings/manager.py
def pretty(self, with_style: bool = True) -> RenderableType:
    """Return a pretty representation of the settings."""
    (bold_, _bold) = ("[bold]", "[/bold]") if with_style else ("", "")
    (italic_, _italic) = ("[italic]", "[/italic]") if with_style else ("", "")
    (underline_, _underline) = ("[underline]", "[/underline]") if with_style else ("", "")
    (red_, _red) = ("[red]", "[/red]") if with_style else ("", "")
    (blue_, _blue) = ("[blue]", "[/blue]") if with_style else ("", "")

    nested: list[str] = []
    items: list[RenderableType] = []
    values_table: Table = Table(
        title="Settings Values",
        title_style="bold underline",
        title_justify="left",
        box=None,
    )
    values_table.add_column(justify="right", style="bold", no_wrap=True)
    values_table.add_column(justify="left", style="italic", no_wrap=True)
    values_table.add_column(justify="center")
    values_table.add_column(justify="left", no_wrap=True)

    for field_name, field_info in self.settings_instance.__class__.model_fields.items():
        if field_name == "invalid_warning":
            continue
        try:
            val = getattr(self.settings_instance, field_name)
            field_string = str(val)
        except AttributeError:
            field_string = "<UNSET>"
        if field_name in self.invalid_warnings:
            field_string = f"{red_}{field_string}{_red}"
        annotation = SettingsDisplayError.enforce_defined(
            field_info.annotation, f"The field info annotation for {field_info} was not defined!"
        )
        field_type: str = f"{italic_}{pretty_annotation(annotation)}{_italic}"
        if is_model_type(annotation) or is_model_collection(annotation):
            field_type = f"{blue_}{field_type}*{_blue}"
            nested.append(pretty_field_info(field_info))
        values_table.add_row(dasherize(field_name), field_type, "->", field_string)

    items.append(values_table)

    if self.invalid_warnings:
        items.extend(["", ""])
        invalid_table: Table = Table(
            title="Invalid Values",
            title_style="bold underline",
            title_justify="left",
            box=None,
        )
        invalid_table.add_column(justify="right", style="bold", no_wrap=True)
        invalid_table.add_column(justify="center")
        invalid_table.add_column(justify="left", no_wrap=True)
        for field_name, invalid_warning in self.invalid_warnings.items():
            invalid_table.add_row(dasherize(field_name), "->", invalid_warning)
        items.append(invalid_table)

    if nested:
        items.extend(["", "", f"{blue_}{bold_}{underline_}{_underline}{_bold}{_blue}"])
        nested_table: Table = Table(
            title="*Nested Model Types",
            title_style="blue bold underline",
            title_justify="left",
            box=None,
        )
        nested_table.add_column(style="bold")
        for model in nested:
            nested_table.add_row(model)
        items.append(nested_table)

    return Group(*items)
reset
reset()

Reset the settings back to defaults.

Source code in src/typerdrive/settings/manager.py
def reset(self):
    """Reset the settings back to defaults."""
    logger.debug("Resetting all settings")

    with SettingsResetError.handle_errors("Failed to reset settings"):
        self.construct_instance()
save
save()

Write the current settings to disk.

Source code in src/typerdrive/settings/manager.py
def save(self):
    """Write the current settings to disk."""
    logger.debug(f"Saving settings to {self.settings_path}")

    with SettingsSaveError.handle_errors(f"Failed to save settings to {self.settings_path}"):
        data = self.settings_instance.model_dump(
            mode="json",
            include=set(type(self.settings_instance).model_fields),
            context={DUMP_CONTEXT_KEY: DumpMode.PERSIST},
        )
        content = json.dumps(data, indent=2)
        self.settings_path.parent.mkdir(parents=True, exist_ok=True)
        atomic_write(self.settings_path, content.encode("utf-8"))
set_warnings
set_warnings(err: ValidationError)

Extract field names and messages from a validation error.

Source code in src/typerdrive/settings/manager.py
def set_warnings(self, err: ValidationError):
    """Extract field names and messages from a validation error."""
    self.invalid_warnings = {}
    for data in err.errors():
        key: str = cast(str, data["loc"][0])
        message = data["msg"]
        self.invalid_warnings[key] = message
to_dict
to_dict() -> dict[str, Any]

Return settings values as plain data.

Source code in src/typerdrive/settings/manager.py
def to_dict(self) -> dict[str, Any]:
    """Return settings values as plain data."""
    return self.dump()
unset
unset(*unset_keys: str)

Remove the settings corresponding to the provided keys.

Source code in src/typerdrive/settings/manager.py
def unset(self, *unset_keys: str):
    """Remove the settings corresponding to the provided keys."""
    logger.debug(f"Unsetting keys {unset_keys}")
    with SettingsUnsetError.handle_errors("Failed to remove keys"):
        settings_values = {key: value for key, value in self._snapshot().items() if key not in unset_keys}
        self.construct_instance(**settings_values)
update
update(**settings_values: Any)

Update settings and retain warnings for invalid values.

Source code in src/typerdrive/settings/manager.py
def update(self, **settings_values: Any):
    """Update settings and retain warnings for invalid values."""
    logger.debug("Updating settings")
    with SettingsUpdateError.handle_errors("Failed to update settings"):
        combined_settings = {**self._snapshot(), **settings_values}
        self.construct_instance(**combined_settings)
validate
validate()

Validate the current settings values.

If invalid, ValidationError exceptions will be raised

Source code in src/typerdrive/settings/manager.py
def validate(self):
    """
    Validate the current settings values.

    If invalid, `ValidationError` exceptions will be raised
    """
    self.settings_model.model_validate(self._snapshot())

Functions:

typerdrive.settings.secrets.models

Provide the secret string types for settings models.

PlaintextSecretStr is persisted as plaintext, and EncryptedSecretStr is persisted as age ciphertext. Both mask themselves in str() and repr(). Pydantic's own SecretStr is not supported in settings models because it serializes to a mask.

Attributes

Classes

EncryptedSecretStr

Bases: SecretStr

A secret string that is plaintext in memory and age-encrypted on disk.

The value is encrypted only when settings are saved, and decrypted only when settings are loaded from disk. Like SecretStr, it masks its value in str() and repr().

Source code in src/typerdrive/settings/secrets/models.py
class EncryptedSecretStr(SecretStr):
    """
    A secret string that is plaintext in memory and age-encrypted on disk.

    The value is encrypted only when settings are saved, and decrypted only when settings are loaded from disk. Like
    `SecretStr`, it masks its value in `str()` and `repr()`.
    """

    typerdrive_encrypted = True
    """Marks this type as encrypted for settings utilities that must not import this optional module."""

    @classmethod
    def __get_pydantic_core_schema__(cls, source: type[Any], handler: Any) -> core_schema.CoreSchema:
        return core_schema.with_info_plain_validator_function(
            cls.validate_value,
            json_schema_input_schema=core_schema.str_schema(),
            serialization=core_schema.plain_serializer_function_ser_schema(
                cls.serialize_value,
                info_arg=True,
                when_used="always",
            ),
        )

    @classmethod
    def validate_value(cls, value: Any, info: core_schema.ValidationInfo) -> Self:
        """Wrap a string as a secret, decrypting it first when it is being loaded from disk."""
        if isinstance(value, cls):
            return value
        if isinstance(value, SecretStr):
            value = value.get_secret_value()
        value = SecretValueError.ensure_type(value, str, "EncryptedSecretStr requires a string or SecretStr")
        context = info.context if isinstance(info.context, dict) else {}
        if context.get(LOADING_CONTEXT_KEY) and value.startswith("age:"):
            return cls.from_ciphertext(value)
        return cls(value)

    @classmethod
    def from_ciphertext(cls, ciphertext: str) -> Self:
        """Hold ciphertext without decrypting it. It is decrypted on first access to the value."""
        secret = cls("")
        secret._ciphertext = ciphertext
        return secret

    _ciphertext: str | None = None
    _decrypted: bool = False

    def _display(self) -> str:
        return "**********" if self._ciphertext is not None else super()._display()

    def get_secret_value(self) -> str:
        if self._ciphertext is not None and not self._decrypted:
            self._secret_value = _get_secret_encryption().decrypt(self._ciphertext)
            self._decrypted = True
        return super().get_secret_value()

    @classmethod
    def serialize_value(cls, value: Any, info: core_schema.SerializationInfo) -> str:
        """Serialize as ciphertext or plaintext when the dump context asks for it. Otherwise, mask the value."""
        context = info.context if isinstance(info.context, dict) else {}
        mode = context.get(DUMP_CONTEXT_KEY)
        if not isinstance(value, SecretStr):
            return value
        if info.mode != "json" and mode is None:
            return value
        if mode == DumpMode.PERSIST:
            return value.encrypt()
        if mode == DumpMode.PLAINTEXT:
            return value.get_secret_value()
        return "**********"

    def encrypt(self) -> str:
        """Return the age ciphertext of this secret for the configured recipient."""
        if self._ciphertext is not None:
            return self._ciphertext
        return _get_secret_encryption().encrypt(self.get_secret_value())
Attributes
typerdrive_encrypted class-attribute instance-attribute
typerdrive_encrypted = True

Marks this type as encrypted for settings utilities that must not import this optional module.

Methods:
__get_pydantic_core_schema__ classmethod
__get_pydantic_core_schema__(
    source: type[Any], handler: Any
) -> core_schema.CoreSchema
Source code in src/typerdrive/settings/secrets/models.py
@classmethod
def __get_pydantic_core_schema__(cls, source: type[Any], handler: Any) -> core_schema.CoreSchema:
    return core_schema.with_info_plain_validator_function(
        cls.validate_value,
        json_schema_input_schema=core_schema.str_schema(),
        serialization=core_schema.plain_serializer_function_ser_schema(
            cls.serialize_value,
            info_arg=True,
            when_used="always",
        ),
    )
encrypt
encrypt() -> str

Return the age ciphertext of this secret for the configured recipient.

Source code in src/typerdrive/settings/secrets/models.py
def encrypt(self) -> str:
    """Return the age ciphertext of this secret for the configured recipient."""
    if self._ciphertext is not None:
        return self._ciphertext
    return _get_secret_encryption().encrypt(self.get_secret_value())
from_ciphertext classmethod
from_ciphertext(ciphertext: str) -> Self

Hold ciphertext without decrypting it. It is decrypted on first access to the value.

Source code in src/typerdrive/settings/secrets/models.py
@classmethod
def from_ciphertext(cls, ciphertext: str) -> Self:
    """Hold ciphertext without decrypting it. It is decrypted on first access to the value."""
    secret = cls("")
    secret._ciphertext = ciphertext
    return secret
get_secret_value
get_secret_value() -> str
Source code in src/typerdrive/settings/secrets/models.py
def get_secret_value(self) -> str:
    if self._ciphertext is not None and not self._decrypted:
        self._secret_value = _get_secret_encryption().decrypt(self._ciphertext)
        self._decrypted = True
    return super().get_secret_value()
serialize_value classmethod
serialize_value(value: Any, info: SerializationInfo) -> str

Serialize as ciphertext or plaintext when the dump context asks for it. Otherwise, mask the value.

Source code in src/typerdrive/settings/secrets/models.py
@classmethod
def serialize_value(cls, value: Any, info: core_schema.SerializationInfo) -> str:
    """Serialize as ciphertext or plaintext when the dump context asks for it. Otherwise, mask the value."""
    context = info.context if isinstance(info.context, dict) else {}
    mode = context.get(DUMP_CONTEXT_KEY)
    if not isinstance(value, SecretStr):
        return value
    if info.mode != "json" and mode is None:
        return value
    if mode == DumpMode.PERSIST:
        return value.encrypt()
    if mode == DumpMode.PLAINTEXT:
        return value.get_secret_value()
    return "**********"
validate_value classmethod
validate_value(value: Any, info: ValidationInfo) -> Self

Wrap a string as a secret, decrypting it first when it is being loaded from disk.

Source code in src/typerdrive/settings/secrets/models.py
@classmethod
def validate_value(cls, value: Any, info: core_schema.ValidationInfo) -> Self:
    """Wrap a string as a secret, decrypting it first when it is being loaded from disk."""
    if isinstance(value, cls):
        return value
    if isinstance(value, SecretStr):
        value = value.get_secret_value()
    value = SecretValueError.ensure_type(value, str, "EncryptedSecretStr requires a string or SecretStr")
    context = info.context if isinstance(info.context, dict) else {}
    if context.get(LOADING_CONTEXT_KEY) and value.startswith("age:"):
        return cls.from_ciphertext(value)
    return cls(value)

PlaintextSecretStr

Bases: SecretStr

A SecretStr that is masked for display, but is written as plaintext when serialized to JSON.

Pydantic's SecretStr serializes to a mask (**********) in JSON mode, which would corrupt a settings file if it were persisted. This type behaves exactly like SecretStr (including masking in str() and repr()), except that its JSON serialization is the real value. This allows settings to be persisted with the normal pydantic serializers instead of walking the model by hand.

Use this type (or EncryptedSecretStr) for secrets in a settings model, instead of SecretStr.

Note

Because the plaintext is written to the settings file, protect that file with appropriate filesystem permissions or use EncryptedSecretStr.

Source code in src/typerdrive/settings/secrets/models.py
class PlaintextSecretStr(SecretStr):
    """
    A `SecretStr` that is masked for display, but is written as plaintext when serialized to JSON.

    Pydantic's `SecretStr` serializes to a mask (`**********`) in JSON mode, which would corrupt a settings file if it
    were persisted. This type behaves exactly like `SecretStr` (including masking in `str()` and `repr()`), except
    that its JSON serialization is the real value. This allows settings to be persisted with the normal pydantic
    serializers instead of walking the model by hand.

    Use this type (or `EncryptedSecretStr`) for secrets in a settings model, instead of `SecretStr`.

    Note:
        Because the plaintext is written to the settings file, protect that file with appropriate filesystem
        permissions or use `EncryptedSecretStr`.
    """

    @classmethod
    def __get_pydantic_core_schema__(cls, source: type[Any], handler: Any) -> core_schema.CoreSchema:
        return core_schema.with_info_plain_validator_function(
            cls.validate_value,
            json_schema_input_schema=core_schema.str_schema(),
            serialization=core_schema.plain_serializer_function_ser_schema(
                cls.serialize_value,
                info_arg=True,
                when_used="always",
            ),
        )

    @classmethod
    def validate_value(cls, value: Any, info: core_schema.ValidationInfo) -> Self:
        """Wrap a `str` or any `SecretStr` as this type."""
        if isinstance(value, cls):
            return value
        if isinstance(value, SecretStr):
            value = value.get_secret_value()
        if not isinstance(value, str):
            raise ValueError(f"{cls.__name__} requires a string or SecretStr")
        return cls(value)

    @classmethod
    def serialize_value(cls, value: Any, info: core_schema.SerializationInfo) -> Any:
        """Return the value itself in python mode, and the plaintext in JSON mode."""
        if info.mode != "json" or not isinstance(value, SecretStr):
            return value
        return value.get_secret_value()
Methods:
__get_pydantic_core_schema__ classmethod
__get_pydantic_core_schema__(
    source: type[Any], handler: Any
) -> core_schema.CoreSchema
Source code in src/typerdrive/settings/secrets/models.py
@classmethod
def __get_pydantic_core_schema__(cls, source: type[Any], handler: Any) -> core_schema.CoreSchema:
    return core_schema.with_info_plain_validator_function(
        cls.validate_value,
        json_schema_input_schema=core_schema.str_schema(),
        serialization=core_schema.plain_serializer_function_ser_schema(
            cls.serialize_value,
            info_arg=True,
            when_used="always",
        ),
    )
serialize_value classmethod
serialize_value(value: Any, info: SerializationInfo) -> Any

Return the value itself in python mode, and the plaintext in JSON mode.

Source code in src/typerdrive/settings/secrets/models.py
@classmethod
def serialize_value(cls, value: Any, info: core_schema.SerializationInfo) -> Any:
    """Return the value itself in python mode, and the plaintext in JSON mode."""
    if info.mode != "json" or not isinstance(value, SecretStr):
        return value
    return value.get_secret_value()
validate_value classmethod
validate_value(value: Any, info: ValidationInfo) -> Self

Wrap a str or any SecretStr as this type.

Source code in src/typerdrive/settings/secrets/models.py
@classmethod
def validate_value(cls, value: Any, info: core_schema.ValidationInfo) -> Self:
    """Wrap a `str` or any `SecretStr` as this type."""
    if isinstance(value, cls):
        return value
    if isinstance(value, SecretStr):
        value = value.get_secret_value()
    if not isinstance(value, str):
        raise ValueError(f"{cls.__name__} requires a string or SecretStr")
    return cls(value)