arcanis / clipanion

Type-safe CLI library / framework with no runtime dependencies
https://mael.dev/clipanion/
1.1k stars 61 forks source link

Adds .env option to Option.String #119

Closed arcanis closed 2 years ago

arcanis commented 2 years ago

I'm writing GitHub Actions powered by Clipanion, and some values (in particular GITHUB_TOKEN) are meant to be obtained from the environment. At the same time, it'd be beneficial to validate/coerce them like regular options and to allow options to override them. To this end, I added env into the context (which will be useful for griselbrand) and added an option to inject environment variables after default values, but before options.

swandir commented 2 years ago

Just needed this feature and found it freshly made, thanks :)

Suppose I have an option foo that is required for my command, but it can also come from env:

foo = Option.String("--foo", {
  env: "FOO",
  required: true,
});

In this case, if I run the CLI without options, I'd expect it first to try obtaining the value from env, and only if it's missing report a usage error. Currently it errors even if the value can be obtained from env.

arcanis commented 2 years ago

The required flag is a little special because it impacts the CLI routing. It literally says "this option must be set in the CLI for this command to be selected". For example you can have twice the same command as long as the second declares a required option that the first doesn't have (Clipanion is smart enough to disambiguate them). So env doesn't impact it (same as setting a default value doesn't change anything).

Perhaps the types should be updated to prevent using the two options together, but I'm worried it'd become quite a mess 🤔

swandir commented 2 years ago

However, it still seems useful to require an option to be provided, no matter through CLI or env.

Couldn't env be checked right after command line arguments during command routing?