How to set a default value for a flag in cobra

71 Views Asked by At

Is there a way to define a default value for a flag (VarP) in the cobra?

func (f *FlagSet) VarPF(value Value, name, shorthand, usage string) *Flag {
    // Remember the default value as a string; it won't change.
    flag := &Flag{
        Name:      name,
        Shorthand: shorthand,
        Usage:     usage,
        Value:     value,
        DefValue:  value.String(),
    }
    f.AddFlag(flag)
    return flag
}

I could not find a default value in the function definition.

1

There are 1 best solutions below

0
coxley On

There are several ways — it's unclear what's been tried from the question.

  • The easiest way is to use one of the dozens of type-specific FlagSet helper methods. For example, FlagSet.StringVarP
  • If you're using custom logic to load flags that don't work well with that, there is FlagSet.AddFlag which takes a Flag. This type has a field for default value.
  • Then there's what you mentioned in your question, using FlagSet.Var and related methods, by implementing a custom type with that interface. If you go this route, you're responsible for defining what a "default value" is. The Value interface provides a method to Set a value and output what the current value is. If you want a default value, return it when nothing has been set in your custom type.