maxb2 / typer-config

Utilities for working with configuration files in typer CLIs.
https://maxb2.github.io/typer-config/
MIT License
24 stars 1 forks source link

Config sections for subcommands? #283

Closed ncoghlan closed 3 days ago

ncoghlan commented 5 days ago

I'm not sure if this is a docs question or an enhancement request (or both). typer-config looks really interesting, but my app has multiple subcommands.

Does typer-config support subcommand-specific setting overrides, or would that need to be added via a custom loader callback that requests access to the command context?

maxb2 commented 4 days ago

All you have to do is define a custom loader like in the Pyproject TOML Example. In essence, the loader takes in the file and selects a particular section and passes it on. The only drawback is that you would need to define a custom loader for each command. However, the loader_transformer combinator makes this pretty easy. In principal, one could make a decorator to capture the name of the function as the subcommand and subset the config automatically. Let me know if you do want this feature!

maxb2 commented 3 days ago

Actually the use_*_config() decorators let you set the subsection easily. For example:

import typer
from typer_config.decorators import use_yaml_config

app = typer.Typer()

@app.command()
@use_yaml_config(["cmd1"])
def cmd1(...):
     ...

@app.command()
@use_yaml_config(["cmd2"])
def cmd2(...):
     ...

if __name__ == "__main__":
    app()

with

# config.yml
cmd1:
    arg1: stuff
cmd2:
    arg1: things
    arg2: other