spf13 / pflag

Drop-in replacement for Go's flag package, implementing POSIX/GNU-style --flags.
BSD 3-Clause "New" or "Revised" License
2.43k stars 348 forks source link

normalizing a flag side-effects #366

Closed nicolasparada closed 1 year ago

nicolasparada commented 1 year ago

I want to rename a flag. Mark the old one as deprecated but allow it to keep working. Basically add an alias.

I tried normalizing it to add the alias.

fs.SetNormalizeFunc(normalizeOldToNew)
func normalizeOldToNew(_ *pflag.FlagSet, name string) pflag.NormalizedName {
    if name == "old" {
        name = "new"
    }
    return pflag.NormalizedName(name)
}

But now if I deprecate the old flag, it also deprecates the new one. Like if they were connected.

fs.MarkDeprecated("old", "use --new instead")
$ ./myprogram --new
Flag --new has been deprecated, use --new instead 

Btw, marking it as hidden, also hides both.

I tried changing the order of stuff but didn't work. For now I removed the normalize function and got a similar result to what I want. But this behavior is a little unexpected.

memreflect commented 1 year ago

If you're merely renaming the flag, you can share the Value between two different flags:

fs.Bool("new", false, "new flag usage")
newFlag := fs.Lookup("new")

// deprecated --old alias for --new
oldFlag := fs.VarPF(newFlag.Value, "old", "", "old flag usage")
oldFlag.Deprecated = "use --new"
oldFlag.Hidden = true
// only necessary when newFlag.NoOptDefVal != "", like if --new is a bool flag
oldFlag.NoOptDefVal = newFlag.NoOptDefVal

Playground demo

nicolasparada commented 1 year ago

That's what I did at the end.

Maybe the docs are a little bit confusing in the readme.