Skip to content

Commit 689a7a3

Browse files
committed
commands: flag - implement command.ValueNamer
This is specifically for `time.Duration` values, but generally applies to any value type that's missing a name in the `usage` string.
1 parent de511cb commit 689a7a3

File tree

1 file changed

+23
-1
lines changed

1 file changed

+23
-1
lines changed

internal/commands/flag.go

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import (
77
"io/fs"
88
"math"
99
"os"
10+
"reflect"
1011
"strconv"
1112
"strings"
1213
"time"
@@ -37,8 +38,25 @@ type (
3738
}
3839
sharedOption func(*sharedSettings) error
3940
sharedOptions []sharedOption
41+
42+
// standard [flag.funcValue] extended
43+
// for [command.ValueNamer].
44+
// (Because standard uses internal types
45+
// in a way we can't access;
46+
// see: [flag.UnquoteUsage]'s implementation.)
47+
genericFuncValue[T any] func(string) error
4048
)
4149

50+
func (gf genericFuncValue[T]) Set(s string) error { return gf(s) }
51+
func (gf genericFuncValue[T]) String() string { return "" }
52+
func (gf genericFuncValue[T]) Name() string {
53+
name := reflect.TypeOf((*T)(nil)).Elem().String()
54+
if index := strings.LastIndexByte(name, '.'); index != -1 {
55+
name = name[index+1:] // Remove [QualifiedIdent] prefix.
56+
}
57+
return strings.ToLower(name)
58+
}
59+
4260
const (
4361
permMaximum = 0o7777
4462
permReadAll = 0o444
@@ -515,11 +533,15 @@ func flagSetFunc[
515533
})
516534
return
517535
}
518-
flagSet.Func(name, usage, func(parameter string) error {
536+
funcFlag[VT](flagSet, name, usage, func(parameter string) error {
519537
return parseAndSet(parameter, options, setter)
520538
})
521539
}
522540

541+
func funcFlag[T any](flagSet *flag.FlagSet, name, usage string, fn func(string) error) {
542+
flagSet.Var(genericFuncValue[T](fn), name, usage)
543+
}
544+
523545
func parseAndSet[
524546
OSR optionsReference[OS, OT, ST],
525547
OS optionSlice[OT, ST],

0 commit comments

Comments
 (0)