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

     1  package cmds
     2  
     3  import (
     4  	"flag"
     5  
     6  	"github.com/toolvox/utilgo/pkg/errs"
     7  )
     8  
     9  // GoFlag wraps a go [pkg/flag.Flag] making it compatible with this package.
    10  type GoFlag struct {
    11  	*flag.Flag
    12  }
    13  
    14  // Set implements [Flag] by calling Set on the [pkg/flag.Value] field of [pkg/flag.Flag].
    15  func (gf GoFlag) Set(value string) error {
    16  	if gf.Value == nil {
    17  		return errs.Newf("flag '%s' value was nil", gf.Name)
    18  	}
    19  	return gf.Value.Set(value)
    20  }
    21  
    22  // Get implements [Flag] by calling Get on the [pkg/flag.Value] field of [pkg/flag.Flag].
    23  func (gf GoFlag) Get() any {
    24  	if gf.Value == nil {
    25  		return errs.Newf("flag '%s' value was nil", gf.Name)
    26  	}
    27  
    28  	if gfGetter, ok := gf.Value.(flag.Getter); ok {
    29  		return gfGetter.Get()
    30  	}
    31  
    32  	return errs.Newf("flag '%s' value has no Get() any function", gf.Name)
    33  }
    34  
    35  // String implements [Flag] by returning the [pkg/flag.Flag]'s DefValue.
    36  func (gf GoFlag) String() string {
    37  	return gf.DefValue
    38  }
    39  
    40  // IsBoolFlag returns true of the wrapped flag is a bool flag.
    41  func (gf GoFlag) IsBoolFlag() bool {
    42  	bf, ok := gf.Value.(isBoolFlag)
    43  	return ok && bf.IsBoolFlag()
    44  }
    45  
    46  // FlagName returns the name of the [Flag].
    47  func (gf GoFlag) FlagName() string { return gf.Name }
    48  
    49  // FlagUsage returns the usage text of the [Flag].
    50  func (gf GoFlag) FlagUsage() string { return gf.Usage }
    51  
    52  // FromFlag creates a new [Flag] by wrapping a [pkg/flag.Flag].
    53  func FromFlag(goFlag *flag.Flag) Flag {
    54  
    55  	return GoFlag{goFlag}
    56  }