Skip to content

Add TextFlag for encoding.TextMarshaler/TextUnmarshaler values - #2415

Open
ChrisJr404 wants to merge 2 commits into
urfave:mainfrom
ChrisJr404:add-text-flag
Open

Add TextFlag for encoding.TextMarshaler/TextUnmarshaler values#2415
ChrisJr404 wants to merge 2 commits into
urfave:mainfrom
ChrisJr404:add-text-flag

Conversation

@ChrisJr404

Copy link
Copy Markdown

What type of PR is this?

  • feature

What this does

Adds TextFlag, the cli equivalent of the standard library's flag.TextVar (added in Go 1.19). It lets any value implementing both encoding.TextMarshaler and encoding.TextUnmarshaler be populated directly from a flag.

The motivating case from #2051 is log-level configuration: *slog.LevelVar satisfies both interfaces, so you can wire the level straight into a flag and have the logger ready (with a sensible default) before parsing even finishes:

lv := &slog.LevelVar{} // defaults to INFO
cmd := &cli.Command{
    Flags: []cli.Flag{
        &cli.TextFlag{Name: "log-level", Value: lv},
    },
}
// --log-level WARN  ->  lv.Level() == slog.LevelWarn

Other stdlib types such as *netip.Addr and *time.Time work the same way, as do third-party types like zap's atomic level.

Implementation notes

  • Follows the existing FlagBase[T, C, VC] value pattern, mirroring GenericFlag/StringFlag.
  • Reuses StringConfig so TrimSpace is available.
  • Adds a Command.Text(name) lookup, consistent with the other typed getters.
  • Create only overwrites the target when a non-nil default Value is provided, so a Destination pointing at an existing target isn't clobbered by the nil interface default.

Testing

New flag_text_test.go covers set-from-arg, default value, Destination, TrimSpace, env source, invalid-value error propagation, and Command.Text. godoc-current.txt / testdata/godoc-v3.x.txt regenerated.

Closes #2051

Adds TextFlag, mirroring the standard library's flag.TextVar, so any type
implementing encoding.TextMarshaler and encoding.TextUnmarshaler (such as
*slog.LevelVar) can be set from a flag. Follows the existing FlagBase value
pattern and reuses StringConfig for TrimSpace. Adds Command.Text lookup.

Closes urfave#2051
@ChrisJr404
ChrisJr404 requested a review from a team as a code owner August 18, 2026 17:25
Exercise the previously-uncovered branches in flag_text.go: the
MarshalText error paths in ToString and String, String's nil and
successful cases, Set with a nil destination, and Command.Text when
the named flag is absent or not a TextMarshalUnmarshaler.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Text flags

1 participant