Skip to content

First-class support for using env variables as flag defaults #62

@molisani

Description

@molisani

Today, when you're configuring a flag you can specify a default value. This default value is a string1 that is used directly as the input if one is not provided by the user at runtime. In many cases, applications consume environment variables in a similar way to how they consume flags so it can be useful to set the default value for a flag from an environment variable. This can be done already, like so (for a --logLevel flag):

logLevel: {
    brief: "Log level"
    kind: "parsed",
    parse: String,
    default: process.env["LOG_LEVEL"],
}

However, with this approach there is no way for the help text to explain where it got this default. The user may change their environment variable and the default will change, but this would have to be manually documented. It would be useful if this pattern of setting the default to an environment variable was supported as a first-class feature and reflected as such in the help text.

Describe the solution you'd like
Given that most defaults are written as string literals, it shouldn't be too much more complicated than that. We do not want to reduce the value-space of all strings, so I think any option that "prefixes" strings should be ignored (i.e. no default: "$VAR_NAME" to mean VAR_NAME).

The current proposal would be to allow default to be an object with a single property env indicating the name of the environment variable to inspect for the default value.

logLevel: {
    brief: "Log level"
    kind: "parsed",
    parse: String,
    default: { env: "LOG_LEVEL" },
}

The help text should reflect both what the default value would be and also the name of the environment variable it was sourced from. Something like the following:

FLAGS
     [--log-level]    Log level     [default = INFO, from LOG_LEVEL]

Footnotes

  1. It can also be a boolean or an enum of a string, but for simplicity's sake I'm just referring to the "parsed" use case here.

Metadata

Metadata

Assignees

Labels

core ⚙Relates to the @stricli/core packageenhancement ✨New feature or request

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions