Skip to content

feat: make all cli flags available as env variables (opt-in) #3

Description

@mfridman

This might not be necessary since it's just a few helper functions most users can stub out in their code, e.g.,

func getFlagOrEnv(s *cli.State, name string, envPrefix string) (string, error) {
	envName := strings.ToUpper(name)
	val := cmp.Or(
		cli.GetFlag[string](s, name),
		os.Getenv(envPrefix+envName),
	)
	if val == "" {
		return "", fmt.Errorf("must provide --%s flag or set %s environment variable", name, envName)
	}
	return val, nil
}

We could optionally bake this logic into the cli library or add a cli.GetFlagOrEnv helper function.

Activity

  1. mfridman commented on Feb 16, 2026

    @mfridman
    CollaboratorAuthor

    Priority: CLI args > env vars > flag defaults

    Two opt-in mechanisms that work together:

    Per-flag via FlagMetadata.Env -- explicit, no magic. Useful when env var names don't follow a pattern (e.g., DATABASE_URL).

    FlagsMetadata: []cli.FlagMetadata{
        {Name: "db-url", Env: "DATABASE_URL", Required: true},
        {Name: "verbose", Env: "VERBOSE"},
    },

    Auto-mapping via FromEnv -- maps all flags automatically using a prefix. Unlike ff, the subcommand name is included, so myapp serve --port maps to MYAPP_SERVE_PORT instead of just MYAPP_PORT, avoiding collisions when subcommands share flag names.

    cli.Parse(root, os.Args[1:], cli.FromEnv("MYAPP"))

    If a flag has an explicit Env, it takes precedence over the auto-generated name.

  2. added theissue type on Feb 16, 2026
  3. added
    enhancement
    on Feb 16, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancement

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions