Make negatable flag name customisable (#439)

* fix: Check if negatable duplicates another flag

Add a check for flags with the `negatable` option if the negative flag
conflicts with another tag, such as:

    Flag   bool `negatable:""`
    NoFlag bool

The flag `--no-flag` is ambiguous in this scenario.

* feat: Make negatable flag name customisable

Allow a value on the `negatable` tag to specify a flag name to use for
negation instead of using `--no-<flag-name>` as the flag.

e.g.

    Approve bool `default:"true",negatable:"deny"`

This example will allow `--deny` to set the `Approve` field to false.
This commit is contained in:
Cam Hutchison
2024-09-10 21:02:37 +10:00
committed by GitHub
parent 7d84b95294
commit 4ecb53599b
8 changed files with 128 additions and 49 deletions
+10 -5
View File
@@ -38,7 +38,7 @@ type Tag struct {
EnvPrefix string
Embed bool
Aliases []string
Negatable bool
Negatable string
Passthrough bool
// Storage for all tag keys for arbitrary lookups.
@@ -256,11 +256,16 @@ func hydrateTag(t *Tag, typ reflect.Type) error { //nolint: gocyclo
t.Prefix = t.Get("prefix")
t.EnvPrefix = t.Get("envprefix")
t.Embed = t.Has("embed")
negatable := t.Has("negatable")
if negatable && !isBool && !isBoolPtr {
return fmt.Errorf("negatable can only be set on booleans")
if t.Has("negatable") {
if !isBool && !isBoolPtr {
return fmt.Errorf("negatable can only be set on booleans")
}
negatable := t.Get("negatable")
if negatable == "" {
negatable = negatableDefault // placeholder for default negation of --no-<flag>
}
t.Negatable = negatable
}
t.Negatable = negatable
aliases := t.Get("aliases")
if len(aliases) > 0 {
t.Aliases = append(t.Aliases, strings.FieldsFunc(aliases, tagSplitFn)...)