github.com/toolvox/utilgo@v0.0.5/pkg/cli/cmds/flag.go (about)

     1  // Package cmds defines interfaces and types for flags and commands.
     2  //
     3  // cmds is somewhat compatible with go's [pkg/flag] package.
     4  package cmds
     5  
     6  // FlagValue is an interface to a value that can be set via flags.
     7  // Compatible with go's [pkg/flag.Value] and [pkg/flag.Getter] interfaces.
     8  //
     9  // The result of calling String before Set is used to represent the default value.
    10  //
    11  // Boolean flags (which don't require an explicit value) must be marked by implementing:
    12  //
    13  //	func (*) IsBoolFlag() bool { return true }
    14  //
    15  // Definition:
    16  type FlagValue interface {
    17  	Set(string) error
    18  	Get() any
    19  	String() string
    20  }
    21  
    22  // isBoolFlag is the implicit interface that implements IsBoolFlag() bool.
    23  type isBoolFlag interface {
    24  	IsBoolFlag() bool
    25  }
    26  
    27  // Flag is an interface to flag with a name, a value, and optional usage text.
    28  //
    29  // Go's [pkg/flag.Flag] struct can be used by wrapping with [FromFlag].
    30  type Flag interface {
    31  	FlagValue
    32  
    33  	FlagName() string
    34  	FlagUsage() string
    35  }
    36  
    37  // CmdFlag implements [Flag] wrapping [FlagValue] with a name and usage text.
    38  type CmdFlag struct {
    39  	FlagValue
    40  
    41  	Name  string
    42  	Usage string
    43  }
    44  
    45  // FlagName returns the flag's name.
    46  func (vf CmdFlag) FlagName() string { return vf.Name }
    47  
    48  // FlagUsage returns the flag's usage text.
    49  func (vf CmdFlag) FlagUsage() string { return vf.Usage }
    50  
    51  // NewFlag creates a new [Flag] from a [FlagValue], a name, and usage text.
    52  func NewFlag(value FlagValue, name string, usage string) Flag {
    53  	return &CmdFlag{
    54  		FlagValue: value,
    55  		Name:      name,
    56  		Usage:     usage,
    57  	}
    58  }