Skip to content

Commit de511cb

Browse files
committed
command: add ValueNamer interface for flags
If a value's type name isn't provided in the usage string, `flag.UnquoteUsage` provides a default name for specific types; these types are unexported and local to the `flag` package. Since external `flag.Value` implementations won't be matched by those type checks, we can add a way to override the default name of "value".
1 parent e6e6920 commit de511cb

File tree

1 file changed

+17
-1
lines changed

1 file changed

+17
-1
lines changed

internal/command/command.go

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,12 @@ type (
5050
FlagBinder interface {
5151
BindFlags(*flag.FlagSet)
5252
}
53+
// ValueNamer may be implemented by a [flag.Value]
54+
// to specify the name of its parameter type, but
55+
// is only used if the name is absent in the usage string.
56+
ValueNamer interface {
57+
Name() string
58+
}
5359
// Option is a functional option.
5460
// One can be returned by the various constructors
5561
// before being passed to [MakeCommand].
@@ -347,7 +353,7 @@ func printFlags(
347353
flagName = render(bold(flagName))
348354
}
349355
writeFn(" " + flagName)
350-
valueType, usage := flag.UnquoteUsage(flg)
356+
valueType, usage := unquoteUsage(flg)
351357
if len(valueType) > 0 {
352358
if styled {
353359
valueType = italicUnderline(valueType)
@@ -414,6 +420,16 @@ func newItalicUnderlineRenderer(renderer *glamour.TermRenderer) stringModiferFun
414420
}
415421
}
416422

423+
func unquoteUsage(flg *flag.Flag) (name, usage string) {
424+
name, usage = flag.UnquoteUsage(flg)
425+
if name == "value" {
426+
if namer, ok := flg.Value.(ValueNamer); ok {
427+
name = namer.Name()
428+
}
429+
}
430+
return name, usage
431+
}
432+
417433
// isZeroValue determines whether the string represents the zero
418434
// value for a flag.
419435
// *Borrowed from standard library.

0 commit comments

Comments
 (0)