Compare commits
8 Commits
766786fcc2
...
argh-core
Author | SHA1 | Date | |
---|---|---|---|
06c70ea8eb
|
|||
689dfd65e8 | |||
a05e4d0982
|
|||
02bba4b62e | |||
12f4cba9a5 | |||
dbdd5cbc35 | |||
9361cba851
|
|||
5133e28f43
|
3
.github/workflows/cli.yml
vendored
3
.github/workflows/cli.yml
vendored
@@ -3,14 +3,11 @@ on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
- v3-dev-main
|
||||
tags:
|
||||
- v2.*
|
||||
- v3.*
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
- v3-dev-main
|
||||
permissions:
|
||||
contents: read
|
||||
jobs:
|
||||
|
@@ -1,6 +0,0 @@
|
||||
package altsrc
|
||||
|
||||
// defaultInputSource creates a default InputSourceContext.
|
||||
func defaultInputSource() (InputSourceContext, error) {
|
||||
return &MapInputSource{file: "", valueMap: map[interface{}]interface{}{}}, nil
|
||||
}
|
@@ -1,18 +0,0 @@
|
||||
# NOTE: this file is used by the tool defined in
|
||||
# ./cmd/urfave-cli-genflags/main.go which uses the
|
||||
# `Spec` type that maps to this file structure.
|
||||
flag_types:
|
||||
Bool:
|
||||
Duration:
|
||||
Float64:
|
||||
Generic:
|
||||
Int64:
|
||||
Int:
|
||||
IntSlice:
|
||||
Int64Slice:
|
||||
Float64Slice:
|
||||
String:
|
||||
Path:
|
||||
StringSlice:
|
||||
Uint64:
|
||||
Uint:
|
328
altsrc/flag.go
328
altsrc/flag.go
@@ -1,328 +0,0 @@
|
||||
package altsrc
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"syscall"
|
||||
|
||||
"github.com/urfave/cli/v3"
|
||||
)
|
||||
|
||||
// FlagInputSourceExtension is an extension interface of cli.Flag that
|
||||
// allows a value to be set on the existing parsed flags.
|
||||
type FlagInputSourceExtension interface {
|
||||
cli.Flag
|
||||
ApplyInputSourceValue(cCtx *cli.Context, isc InputSourceContext) error
|
||||
}
|
||||
|
||||
// ApplyInputSourceValues iterates over all provided flags and
|
||||
// executes ApplyInputSourceValue on flags implementing the
|
||||
// FlagInputSourceExtension interface to initialize these flags
|
||||
// to an alternate input source.
|
||||
func ApplyInputSourceValues(cCtx *cli.Context, inputSourceContext InputSourceContext, flags []cli.Flag) error {
|
||||
for _, f := range flags {
|
||||
inputSourceExtendedFlag, isType := f.(FlagInputSourceExtension)
|
||||
if isType {
|
||||
err := inputSourceExtendedFlag.ApplyInputSourceValue(cCtx, inputSourceContext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// InitInputSource is used to to setup an InputSourceContext on a cli.Command Before method. It will create a new
|
||||
// input source based on the func provided. If there is no error it will then apply the new input source to any flags
|
||||
// that are supported by the input source
|
||||
func InitInputSource(flags []cli.Flag, createInputSource func() (InputSourceContext, error)) cli.BeforeFunc {
|
||||
return func(cCtx *cli.Context) error {
|
||||
inputSource, err := createInputSource()
|
||||
if err != nil {
|
||||
return fmt.Errorf("Unable to create input source: inner error: \n'%v'", err.Error())
|
||||
}
|
||||
|
||||
return ApplyInputSourceValues(cCtx, inputSource, flags)
|
||||
}
|
||||
}
|
||||
|
||||
// InitInputSourceWithContext is used to to setup an InputSourceContext on a cli.Command Before method. It will create a new
|
||||
// input source based on the func provided with potentially using existing cli.Context values to initialize itself. If there is
|
||||
// no error it will then apply the new input source to any flags that are supported by the input source
|
||||
func InitInputSourceWithContext(flags []cli.Flag, createInputSource func(cCtx *cli.Context) (InputSourceContext, error)) cli.BeforeFunc {
|
||||
return func(cCtx *cli.Context) error {
|
||||
inputSource, err := createInputSource(cCtx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Unable to create input source with context: inner error: \n'%v'", err.Error())
|
||||
}
|
||||
|
||||
return ApplyInputSourceValues(cCtx, inputSource, flags)
|
||||
}
|
||||
}
|
||||
|
||||
// ApplyInputSourceValue applies a generic value to the flagSet if required
|
||||
func (f *GenericFlag) ApplyInputSourceValue(cCtx *cli.Context, isc InputSourceContext) error {
|
||||
if f.set == nil || cCtx.IsSet(f.Name) || isEnvVarSet(f.EnvVars) {
|
||||
return nil
|
||||
}
|
||||
for _, name := range f.GenericFlag.Names() {
|
||||
if !isc.isSet(name) {
|
||||
continue
|
||||
}
|
||||
value, err := isc.Generic(name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if value == nil {
|
||||
continue
|
||||
}
|
||||
for _, n := range f.Names() {
|
||||
_ = f.set.Set(n, value.String())
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// ApplyInputSourceValue applies a StringSlice value to the flagSet if required
|
||||
func (f *StringSliceFlag) ApplyInputSourceValue(cCtx *cli.Context, isc InputSourceContext) error {
|
||||
if f.set == nil || cCtx.IsSet(f.Name) || isEnvVarSet(f.EnvVars) {
|
||||
return nil
|
||||
}
|
||||
for _, name := range f.StringSliceFlag.Names() {
|
||||
if !isc.isSet(name) {
|
||||
continue
|
||||
}
|
||||
value, err := isc.StringSlice(name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if value == nil {
|
||||
continue
|
||||
}
|
||||
var sliceValue = *(cli.NewStringSlice(value...))
|
||||
for _, n := range f.Names() {
|
||||
underlyingFlag := f.set.Lookup(n)
|
||||
if underlyingFlag == nil {
|
||||
continue
|
||||
}
|
||||
underlyingFlag.Value = &sliceValue
|
||||
}
|
||||
if f.Destination != nil {
|
||||
f.Destination.Set(sliceValue.Serialize())
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ApplyInputSourceValue applies a IntSlice value if required
|
||||
func (f *IntSliceFlag) ApplyInputSourceValue(cCtx *cli.Context, isc InputSourceContext) error {
|
||||
if f.set == nil || cCtx.IsSet(f.Name) || isEnvVarSet(f.EnvVars) {
|
||||
return nil
|
||||
}
|
||||
for _, name := range f.IntSliceFlag.Names() {
|
||||
if !isc.isSet(name) {
|
||||
continue
|
||||
}
|
||||
value, err := isc.IntSlice(name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if value == nil {
|
||||
continue
|
||||
}
|
||||
var sliceValue = *(cli.NewIntSlice(value...))
|
||||
for _, n := range f.Names() {
|
||||
underlyingFlag := f.set.Lookup(n)
|
||||
if underlyingFlag == nil {
|
||||
continue
|
||||
}
|
||||
underlyingFlag.Value = &sliceValue
|
||||
}
|
||||
if f.Destination != nil {
|
||||
f.Destination.Set(sliceValue.Serialize())
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ApplyInputSourceValue applies a Int64Slice value if required
|
||||
func (f *Int64SliceFlag) ApplyInputSourceValue(cCtx *cli.Context, isc InputSourceContext) error {
|
||||
if f.set == nil || cCtx.IsSet(f.Name) || isEnvVarSet(f.EnvVars) {
|
||||
return nil
|
||||
}
|
||||
for _, name := range f.Int64SliceFlag.Names() {
|
||||
if !isc.isSet(name) {
|
||||
continue
|
||||
}
|
||||
value, err := isc.Int64Slice(name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if value == nil {
|
||||
continue
|
||||
}
|
||||
var sliceValue = *(cli.NewInt64Slice(value...))
|
||||
for _, n := range f.Names() {
|
||||
underlyingFlag := f.set.Lookup(n)
|
||||
if underlyingFlag == nil {
|
||||
continue
|
||||
}
|
||||
underlyingFlag.Value = &sliceValue
|
||||
}
|
||||
if f.Destination != nil {
|
||||
f.Destination.Set(sliceValue.Serialize())
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ApplyInputSourceValue applies a Bool value to the flagSet if required
|
||||
func (f *BoolFlag) ApplyInputSourceValue(cCtx *cli.Context, isc InputSourceContext) error {
|
||||
if f.set == nil || cCtx.IsSet(f.Name) || isEnvVarSet(f.EnvVars) {
|
||||
return nil
|
||||
}
|
||||
for _, name := range f.BoolFlag.Names() {
|
||||
if !isc.isSet(name) {
|
||||
continue
|
||||
}
|
||||
value, err := isc.Bool(name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, n := range f.Names() {
|
||||
_ = f.set.Set(n, strconv.FormatBool(value))
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ApplyInputSourceValue applies a String value to the flagSet if required
|
||||
func (f *StringFlag) ApplyInputSourceValue(cCtx *cli.Context, isc InputSourceContext) error {
|
||||
if f.set == nil || cCtx.IsSet(f.Name) || isEnvVarSet(f.EnvVars) {
|
||||
return nil
|
||||
}
|
||||
for _, name := range f.StringFlag.Names() {
|
||||
if !isc.isSet(name) {
|
||||
continue
|
||||
}
|
||||
value, err := isc.String(name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, n := range f.Names() {
|
||||
_ = f.set.Set(n, value)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ApplyInputSourceValue applies a Path value to the flagSet if required
|
||||
func (f *PathFlag) ApplyInputSourceValue(cCtx *cli.Context, isc InputSourceContext) error {
|
||||
if f.set == nil || cCtx.IsSet(f.Name) || isEnvVarSet(f.EnvVars) {
|
||||
return nil
|
||||
}
|
||||
for _, name := range f.PathFlag.Names() {
|
||||
if !isc.isSet(name) {
|
||||
continue
|
||||
}
|
||||
value, err := isc.String(name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if value == "" {
|
||||
continue
|
||||
}
|
||||
for _, n := range f.Names() {
|
||||
if !filepath.IsAbs(value) && isc.Source() != "" {
|
||||
basePathAbs, err := filepath.Abs(isc.Source())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
value = filepath.Join(filepath.Dir(basePathAbs), value)
|
||||
}
|
||||
_ = f.set.Set(n, value)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ApplyInputSourceValue applies a int value to the flagSet if required
|
||||
func (f *IntFlag) ApplyInputSourceValue(cCtx *cli.Context, isc InputSourceContext) error {
|
||||
if f.set == nil || cCtx.IsSet(f.Name) || isEnvVarSet(f.EnvVars) {
|
||||
return nil
|
||||
}
|
||||
for _, name := range f.IntFlag.Names() {
|
||||
if !isc.isSet(name) {
|
||||
continue
|
||||
}
|
||||
value, err := isc.Int(name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, n := range f.Names() {
|
||||
_ = f.set.Set(n, strconv.FormatInt(int64(value), 10))
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ApplyInputSourceValue applies a Duration value to the flagSet if required
|
||||
func (f *DurationFlag) ApplyInputSourceValue(cCtx *cli.Context, isc InputSourceContext) error {
|
||||
if f.set == nil || cCtx.IsSet(f.Name) || isEnvVarSet(f.EnvVars) {
|
||||
return nil
|
||||
}
|
||||
for _, name := range f.DurationFlag.Names() {
|
||||
if !isc.isSet(name) {
|
||||
continue
|
||||
}
|
||||
value, err := isc.Duration(name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, n := range f.Names() {
|
||||
_ = f.set.Set(n, value.String())
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ApplyInputSourceValue applies a Float64 value to the flagSet if required
|
||||
func (f *Float64Flag) ApplyInputSourceValue(cCtx *cli.Context, isc InputSourceContext) error {
|
||||
if f.set == nil || cCtx.IsSet(f.Name) || isEnvVarSet(f.EnvVars) {
|
||||
return nil
|
||||
}
|
||||
for _, name := range f.Float64Flag.Names() {
|
||||
if !isc.isSet(name) {
|
||||
continue
|
||||
}
|
||||
value, err := isc.Float64(name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
floatStr := float64ToString(value)
|
||||
for _, n := range f.Names() {
|
||||
_ = f.set.Set(n, floatStr)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func isEnvVarSet(envVars []string) bool {
|
||||
for _, envVar := range envVars {
|
||||
if _, ok := syscall.Getenv(envVar); ok {
|
||||
// TODO: Can't use this for bools as
|
||||
// set means that it was true or false based on
|
||||
// Bool flag type, should work for other types
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
func float64ToString(f float64) string {
|
||||
return fmt.Sprintf("%v", f)
|
||||
}
|
@@ -1,277 +0,0 @@
|
||||
// WARNING: this file is generated. DO NOT EDIT
|
||||
|
||||
package altsrc
|
||||
|
||||
import (
|
||||
"flag"
|
||||
|
||||
"github.com/urfave/cli/v3"
|
||||
)
|
||||
|
||||
// BoolFlag is the flag type that wraps cli.BoolFlag to allow
|
||||
// for other values to be specified
|
||||
type BoolFlag struct {
|
||||
*cli.BoolFlag
|
||||
set *flag.FlagSet
|
||||
}
|
||||
|
||||
// NewBoolFlag creates a new BoolFlag
|
||||
func NewBoolFlag(fl *cli.BoolFlag) *BoolFlag {
|
||||
return &BoolFlag{BoolFlag: fl, set: nil}
|
||||
}
|
||||
|
||||
// Apply saves the flagSet for later usage calls, then calls
|
||||
// the wrapped BoolFlag.Apply
|
||||
func (f *BoolFlag) Apply(set *flag.FlagSet) error {
|
||||
f.set = set
|
||||
return f.BoolFlag.Apply(set)
|
||||
}
|
||||
|
||||
// DurationFlag is the flag type that wraps cli.DurationFlag to allow
|
||||
// for other values to be specified
|
||||
type DurationFlag struct {
|
||||
*cli.DurationFlag
|
||||
set *flag.FlagSet
|
||||
}
|
||||
|
||||
// NewDurationFlag creates a new DurationFlag
|
||||
func NewDurationFlag(fl *cli.DurationFlag) *DurationFlag {
|
||||
return &DurationFlag{DurationFlag: fl, set: nil}
|
||||
}
|
||||
|
||||
// Apply saves the flagSet for later usage calls, then calls
|
||||
// the wrapped DurationFlag.Apply
|
||||
func (f *DurationFlag) Apply(set *flag.FlagSet) error {
|
||||
f.set = set
|
||||
return f.DurationFlag.Apply(set)
|
||||
}
|
||||
|
||||
// Float64Flag is the flag type that wraps cli.Float64Flag to allow
|
||||
// for other values to be specified
|
||||
type Float64Flag struct {
|
||||
*cli.Float64Flag
|
||||
set *flag.FlagSet
|
||||
}
|
||||
|
||||
// NewFloat64Flag creates a new Float64Flag
|
||||
func NewFloat64Flag(fl *cli.Float64Flag) *Float64Flag {
|
||||
return &Float64Flag{Float64Flag: fl, set: nil}
|
||||
}
|
||||
|
||||
// Apply saves the flagSet for later usage calls, then calls
|
||||
// the wrapped Float64Flag.Apply
|
||||
func (f *Float64Flag) Apply(set *flag.FlagSet) error {
|
||||
f.set = set
|
||||
return f.Float64Flag.Apply(set)
|
||||
}
|
||||
|
||||
// Float64SliceFlag is the flag type that wraps cli.Float64SliceFlag to allow
|
||||
// for other values to be specified
|
||||
type Float64SliceFlag struct {
|
||||
*cli.Float64SliceFlag
|
||||
set *flag.FlagSet
|
||||
}
|
||||
|
||||
// NewFloat64SliceFlag creates a new Float64SliceFlag
|
||||
func NewFloat64SliceFlag(fl *cli.Float64SliceFlag) *Float64SliceFlag {
|
||||
return &Float64SliceFlag{Float64SliceFlag: fl, set: nil}
|
||||
}
|
||||
|
||||
// Apply saves the flagSet for later usage calls, then calls
|
||||
// the wrapped Float64SliceFlag.Apply
|
||||
func (f *Float64SliceFlag) Apply(set *flag.FlagSet) error {
|
||||
f.set = set
|
||||
return f.Float64SliceFlag.Apply(set)
|
||||
}
|
||||
|
||||
// GenericFlag is the flag type that wraps cli.GenericFlag to allow
|
||||
// for other values to be specified
|
||||
type GenericFlag struct {
|
||||
*cli.GenericFlag
|
||||
set *flag.FlagSet
|
||||
}
|
||||
|
||||
// NewGenericFlag creates a new GenericFlag
|
||||
func NewGenericFlag(fl *cli.GenericFlag) *GenericFlag {
|
||||
return &GenericFlag{GenericFlag: fl, set: nil}
|
||||
}
|
||||
|
||||
// Apply saves the flagSet for later usage calls, then calls
|
||||
// the wrapped GenericFlag.Apply
|
||||
func (f *GenericFlag) Apply(set *flag.FlagSet) error {
|
||||
f.set = set
|
||||
return f.GenericFlag.Apply(set)
|
||||
}
|
||||
|
||||
// IntFlag is the flag type that wraps cli.IntFlag to allow
|
||||
// for other values to be specified
|
||||
type IntFlag struct {
|
||||
*cli.IntFlag
|
||||
set *flag.FlagSet
|
||||
}
|
||||
|
||||
// NewIntFlag creates a new IntFlag
|
||||
func NewIntFlag(fl *cli.IntFlag) *IntFlag {
|
||||
return &IntFlag{IntFlag: fl, set: nil}
|
||||
}
|
||||
|
||||
// Apply saves the flagSet for later usage calls, then calls
|
||||
// the wrapped IntFlag.Apply
|
||||
func (f *IntFlag) Apply(set *flag.FlagSet) error {
|
||||
f.set = set
|
||||
return f.IntFlag.Apply(set)
|
||||
}
|
||||
|
||||
// Int64Flag is the flag type that wraps cli.Int64Flag to allow
|
||||
// for other values to be specified
|
||||
type Int64Flag struct {
|
||||
*cli.Int64Flag
|
||||
set *flag.FlagSet
|
||||
}
|
||||
|
||||
// NewInt64Flag creates a new Int64Flag
|
||||
func NewInt64Flag(fl *cli.Int64Flag) *Int64Flag {
|
||||
return &Int64Flag{Int64Flag: fl, set: nil}
|
||||
}
|
||||
|
||||
// Apply saves the flagSet for later usage calls, then calls
|
||||
// the wrapped Int64Flag.Apply
|
||||
func (f *Int64Flag) Apply(set *flag.FlagSet) error {
|
||||
f.set = set
|
||||
return f.Int64Flag.Apply(set)
|
||||
}
|
||||
|
||||
// Int64SliceFlag is the flag type that wraps cli.Int64SliceFlag to allow
|
||||
// for other values to be specified
|
||||
type Int64SliceFlag struct {
|
||||
*cli.Int64SliceFlag
|
||||
set *flag.FlagSet
|
||||
}
|
||||
|
||||
// NewInt64SliceFlag creates a new Int64SliceFlag
|
||||
func NewInt64SliceFlag(fl *cli.Int64SliceFlag) *Int64SliceFlag {
|
||||
return &Int64SliceFlag{Int64SliceFlag: fl, set: nil}
|
||||
}
|
||||
|
||||
// Apply saves the flagSet for later usage calls, then calls
|
||||
// the wrapped Int64SliceFlag.Apply
|
||||
func (f *Int64SliceFlag) Apply(set *flag.FlagSet) error {
|
||||
f.set = set
|
||||
return f.Int64SliceFlag.Apply(set)
|
||||
}
|
||||
|
||||
// IntSliceFlag is the flag type that wraps cli.IntSliceFlag to allow
|
||||
// for other values to be specified
|
||||
type IntSliceFlag struct {
|
||||
*cli.IntSliceFlag
|
||||
set *flag.FlagSet
|
||||
}
|
||||
|
||||
// NewIntSliceFlag creates a new IntSliceFlag
|
||||
func NewIntSliceFlag(fl *cli.IntSliceFlag) *IntSliceFlag {
|
||||
return &IntSliceFlag{IntSliceFlag: fl, set: nil}
|
||||
}
|
||||
|
||||
// Apply saves the flagSet for later usage calls, then calls
|
||||
// the wrapped IntSliceFlag.Apply
|
||||
func (f *IntSliceFlag) Apply(set *flag.FlagSet) error {
|
||||
f.set = set
|
||||
return f.IntSliceFlag.Apply(set)
|
||||
}
|
||||
|
||||
// PathFlag is the flag type that wraps cli.PathFlag to allow
|
||||
// for other values to be specified
|
||||
type PathFlag struct {
|
||||
*cli.PathFlag
|
||||
set *flag.FlagSet
|
||||
}
|
||||
|
||||
// NewPathFlag creates a new PathFlag
|
||||
func NewPathFlag(fl *cli.PathFlag) *PathFlag {
|
||||
return &PathFlag{PathFlag: fl, set: nil}
|
||||
}
|
||||
|
||||
// Apply saves the flagSet for later usage calls, then calls
|
||||
// the wrapped PathFlag.Apply
|
||||
func (f *PathFlag) Apply(set *flag.FlagSet) error {
|
||||
f.set = set
|
||||
return f.PathFlag.Apply(set)
|
||||
}
|
||||
|
||||
// StringFlag is the flag type that wraps cli.StringFlag to allow
|
||||
// for other values to be specified
|
||||
type StringFlag struct {
|
||||
*cli.StringFlag
|
||||
set *flag.FlagSet
|
||||
}
|
||||
|
||||
// NewStringFlag creates a new StringFlag
|
||||
func NewStringFlag(fl *cli.StringFlag) *StringFlag {
|
||||
return &StringFlag{StringFlag: fl, set: nil}
|
||||
}
|
||||
|
||||
// Apply saves the flagSet for later usage calls, then calls
|
||||
// the wrapped StringFlag.Apply
|
||||
func (f *StringFlag) Apply(set *flag.FlagSet) error {
|
||||
f.set = set
|
||||
return f.StringFlag.Apply(set)
|
||||
}
|
||||
|
||||
// StringSliceFlag is the flag type that wraps cli.StringSliceFlag to allow
|
||||
// for other values to be specified
|
||||
type StringSliceFlag struct {
|
||||
*cli.StringSliceFlag
|
||||
set *flag.FlagSet
|
||||
}
|
||||
|
||||
// NewStringSliceFlag creates a new StringSliceFlag
|
||||
func NewStringSliceFlag(fl *cli.StringSliceFlag) *StringSliceFlag {
|
||||
return &StringSliceFlag{StringSliceFlag: fl, set: nil}
|
||||
}
|
||||
|
||||
// Apply saves the flagSet for later usage calls, then calls
|
||||
// the wrapped StringSliceFlag.Apply
|
||||
func (f *StringSliceFlag) Apply(set *flag.FlagSet) error {
|
||||
f.set = set
|
||||
return f.StringSliceFlag.Apply(set)
|
||||
}
|
||||
|
||||
// UintFlag is the flag type that wraps cli.UintFlag to allow
|
||||
// for other values to be specified
|
||||
type UintFlag struct {
|
||||
*cli.UintFlag
|
||||
set *flag.FlagSet
|
||||
}
|
||||
|
||||
// NewUintFlag creates a new UintFlag
|
||||
func NewUintFlag(fl *cli.UintFlag) *UintFlag {
|
||||
return &UintFlag{UintFlag: fl, set: nil}
|
||||
}
|
||||
|
||||
// Apply saves the flagSet for later usage calls, then calls
|
||||
// the wrapped UintFlag.Apply
|
||||
func (f *UintFlag) Apply(set *flag.FlagSet) error {
|
||||
f.set = set
|
||||
return f.UintFlag.Apply(set)
|
||||
}
|
||||
|
||||
// Uint64Flag is the flag type that wraps cli.Uint64Flag to allow
|
||||
// for other values to be specified
|
||||
type Uint64Flag struct {
|
||||
*cli.Uint64Flag
|
||||
set *flag.FlagSet
|
||||
}
|
||||
|
||||
// NewUint64Flag creates a new Uint64Flag
|
||||
func NewUint64Flag(fl *cli.Uint64Flag) *Uint64Flag {
|
||||
return &Uint64Flag{Uint64Flag: fl, set: nil}
|
||||
}
|
||||
|
||||
// Apply saves the flagSet for later usage calls, then calls
|
||||
// the wrapped Uint64Flag.Apply
|
||||
func (f *Uint64Flag) Apply(set *flag.FlagSet) error {
|
||||
f.set = set
|
||||
return f.Uint64Flag.Apply(set)
|
||||
}
|
||||
|
||||
// vim:ro
|
@@ -1,743 +0,0 @@
|
||||
package altsrc
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/urfave/cli/v3"
|
||||
)
|
||||
|
||||
type testApplyInputSource struct {
|
||||
Flag FlagInputSourceExtension
|
||||
FlagName string
|
||||
FlagSetName string
|
||||
Expected string
|
||||
ContextValueString string
|
||||
ContextValue flag.Value
|
||||
EnvVarValue string
|
||||
EnvVarName string
|
||||
SourcePath string
|
||||
MapValue interface{}
|
||||
}
|
||||
|
||||
type racyInputSource struct {
|
||||
*MapInputSource
|
||||
}
|
||||
|
||||
func (ris *racyInputSource) isSet(name string) bool {
|
||||
if _, ok := ris.MapInputSource.valueMap[name]; ok {
|
||||
ris.MapInputSource.valueMap[name] = bogus{0}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func TestGenericApplyInputSourceValue_Alias(t *testing.T) {
|
||||
v := &Parser{"abc", "def"}
|
||||
tis := testApplyInputSource{
|
||||
Flag: NewGenericFlag(&cli.GenericFlag{Name: "test", Aliases: []string{"test_alias"}, Value: &Parser{}}),
|
||||
FlagName: "test_alias",
|
||||
MapValue: v,
|
||||
}
|
||||
c := runTest(t, tis)
|
||||
expect(t, v, c.Generic("test_alias"))
|
||||
|
||||
c = runRacyTest(t, tis)
|
||||
refute(t, v, c.Generic("test_alias"))
|
||||
}
|
||||
|
||||
func TestGenericApplyInputSourceValue(t *testing.T) {
|
||||
v := &Parser{"abc", "def"}
|
||||
tis := testApplyInputSource{
|
||||
Flag: NewGenericFlag(&cli.GenericFlag{Name: "test", Value: &Parser{}}),
|
||||
FlagName: "test",
|
||||
MapValue: v,
|
||||
}
|
||||
c := runTest(t, tis)
|
||||
expect(t, v, c.Generic("test"))
|
||||
|
||||
c = runRacyTest(t, tis)
|
||||
refute(t, v, c.Generic("test"))
|
||||
}
|
||||
|
||||
func TestGenericApplyInputSourceMethodContextSet(t *testing.T) {
|
||||
p := &Parser{"abc", "def"}
|
||||
tis := testApplyInputSource{
|
||||
Flag: NewGenericFlag(&cli.GenericFlag{Name: "test", Value: &Parser{}}),
|
||||
FlagName: "test",
|
||||
MapValue: &Parser{"efg", "hig"},
|
||||
ContextValueString: p.String(),
|
||||
}
|
||||
c := runTest(t, tis)
|
||||
expect(t, p, c.Generic("test"))
|
||||
|
||||
c = runRacyTest(t, tis)
|
||||
refute(t, p, c.Generic("test"))
|
||||
}
|
||||
|
||||
func TestGenericApplyInputSourceMethodEnvVarSet(t *testing.T) {
|
||||
tis := testApplyInputSource{
|
||||
Flag: NewGenericFlag(&cli.GenericFlag{
|
||||
Name: "test",
|
||||
Value: &Parser{},
|
||||
EnvVars: []string{"TEST"},
|
||||
}),
|
||||
FlagName: "test",
|
||||
MapValue: &Parser{"efg", "hij"},
|
||||
EnvVarName: "TEST",
|
||||
EnvVarValue: "abc,def",
|
||||
}
|
||||
c := runTest(t, tis)
|
||||
expect(t, &Parser{"abc", "def"}, c.Generic("test"))
|
||||
|
||||
c = runRacyTest(t, tis)
|
||||
refute(t, &Parser{"abc", "def"}, c.Generic("test"))
|
||||
}
|
||||
|
||||
func TestStringSliceApplyInputSourceValue_Alias(t *testing.T) {
|
||||
dest := cli.NewStringSlice()
|
||||
tis := testApplyInputSource{
|
||||
Flag: NewStringSliceFlag(&cli.StringSliceFlag{Name: "test", Aliases: []string{"test_alias"}, Destination: dest}),
|
||||
FlagName: "test_alias",
|
||||
MapValue: []interface{}{"hello", "world"},
|
||||
}
|
||||
c := runTest(t, tis)
|
||||
expect(t, c.StringSlice("test_alias"), []string{"hello", "world"})
|
||||
expect(t, dest.Value(), []string{"hello", "world"})
|
||||
|
||||
// reset dest
|
||||
dest = cli.NewStringSlice()
|
||||
tis = testApplyInputSource{
|
||||
Flag: NewStringSliceFlag(&cli.StringSliceFlag{Name: "test", Aliases: []string{"test_alias"}, Destination: dest}),
|
||||
FlagName: "test_alias",
|
||||
MapValue: []interface{}{"hello", "world"},
|
||||
}
|
||||
c = runRacyTest(t, tis)
|
||||
refute(t, c.StringSlice("test_alias"), []string{"hello", "world"})
|
||||
refute(t, dest.Value(), []string{"hello", "world"})
|
||||
}
|
||||
|
||||
func TestStringSliceApplyInputSourceValue(t *testing.T) {
|
||||
dest := cli.NewStringSlice()
|
||||
tis := testApplyInputSource{
|
||||
Flag: NewStringSliceFlag(&cli.StringSliceFlag{Name: "test", Destination: dest}),
|
||||
FlagName: "test",
|
||||
MapValue: []interface{}{"hello", "world"},
|
||||
}
|
||||
c := runTest(t, tis)
|
||||
expect(t, c.StringSlice("test"), []string{"hello", "world"})
|
||||
expect(t, dest.Value(), []string{"hello", "world"})
|
||||
|
||||
// reset dest
|
||||
dest = cli.NewStringSlice()
|
||||
tis = testApplyInputSource{
|
||||
Flag: NewStringSliceFlag(&cli.StringSliceFlag{Name: "test", Destination: dest}),
|
||||
FlagName: "test",
|
||||
MapValue: []interface{}{"hello", "world"},
|
||||
}
|
||||
c = runRacyTest(t, tis)
|
||||
refute(t, c.StringSlice("test"), []string{"hello", "world"})
|
||||
refute(t, dest.Value(), []string{"hello", "world"})
|
||||
}
|
||||
|
||||
func TestStringSliceApplyInputSourceMethodContextSet(t *testing.T) {
|
||||
dest := cli.NewStringSlice()
|
||||
c := runTest(t, testApplyInputSource{
|
||||
Flag: NewStringSliceFlag(&cli.StringSliceFlag{Name: "test", Destination: dest}),
|
||||
FlagName: "test",
|
||||
MapValue: []interface{}{"hello", "world"},
|
||||
ContextValueString: "ohno",
|
||||
})
|
||||
expect(t, c.StringSlice("test"), []string{"ohno"})
|
||||
expect(t, dest.Value(), []string{"ohno"})
|
||||
}
|
||||
|
||||
func TestStringSliceApplyInputSourceMethodEnvVarSet(t *testing.T) {
|
||||
tis := testApplyInputSource{
|
||||
Flag: NewStringSliceFlag(&cli.StringSliceFlag{Name: "test", EnvVars: []string{"TEST"}}),
|
||||
FlagName: "test",
|
||||
MapValue: []interface{}{"hello", "world"},
|
||||
EnvVarName: "TEST",
|
||||
EnvVarValue: "oh,no",
|
||||
}
|
||||
c := runTest(t, tis)
|
||||
expect(t, c.StringSlice("test"), []string{"oh", "no"})
|
||||
|
||||
c = runRacyTest(t, tis)
|
||||
refute(t, c.StringSlice("test"), []string{"oh", "no"})
|
||||
}
|
||||
|
||||
func TestIntSliceApplyInputSourceValue_Alias(t *testing.T) {
|
||||
dest := cli.NewIntSlice()
|
||||
tis := testApplyInputSource{
|
||||
Flag: NewIntSliceFlag(&cli.IntSliceFlag{Name: "test", Aliases: []string{"test_alias"}, Destination: dest}),
|
||||
FlagName: "test_alias",
|
||||
MapValue: []interface{}{1, 2},
|
||||
}
|
||||
c := runTest(t, tis)
|
||||
expect(t, c.IntSlice("test_alias"), []int{1, 2})
|
||||
expect(t, dest.Value(), []int{1, 2})
|
||||
|
||||
dest = cli.NewIntSlice()
|
||||
tis = testApplyInputSource{
|
||||
Flag: NewIntSliceFlag(&cli.IntSliceFlag{Name: "test", Aliases: []string{"test_alias"}, Destination: dest}),
|
||||
FlagName: "test_alias",
|
||||
MapValue: []interface{}{1, 2},
|
||||
}
|
||||
c = runRacyTest(t, tis)
|
||||
refute(t, c.IntSlice("test_alias"), []int{1, 2})
|
||||
refute(t, dest.Value(), []int{1, 2})
|
||||
}
|
||||
|
||||
func TestIntSliceApplyInputSourceValue(t *testing.T) {
|
||||
dest := cli.NewIntSlice()
|
||||
tis := testApplyInputSource{
|
||||
Flag: NewIntSliceFlag(&cli.IntSliceFlag{Name: "test", Destination: dest}),
|
||||
FlagName: "test",
|
||||
MapValue: []interface{}{1, 2},
|
||||
}
|
||||
c := runTest(t, tis)
|
||||
expect(t, c.IntSlice("test"), []int{1, 2})
|
||||
expect(t, dest.Value(), []int{1, 2})
|
||||
|
||||
// reset dest
|
||||
dest = cli.NewIntSlice()
|
||||
tis = testApplyInputSource{
|
||||
Flag: NewIntSliceFlag(&cli.IntSliceFlag{Name: "test", Destination: dest}),
|
||||
FlagName: "test",
|
||||
MapValue: []interface{}{1, 2},
|
||||
}
|
||||
c = runRacyTest(t, tis)
|
||||
refute(t, c.IntSlice("test"), []int{1, 2})
|
||||
refute(t, dest.Value(), []int{1, 2})
|
||||
}
|
||||
|
||||
func TestIntSliceApplyInputSourceMethodContextSet(t *testing.T) {
|
||||
dest := cli.NewIntSlice()
|
||||
tis := testApplyInputSource{
|
||||
Flag: NewIntSliceFlag(&cli.IntSliceFlag{Name: "test", Destination: dest}),
|
||||
FlagName: "test",
|
||||
MapValue: []interface{}{1, 2},
|
||||
ContextValueString: "3",
|
||||
}
|
||||
c := runTest(t, tis)
|
||||
expect(t, c.IntSlice("test"), []int{3})
|
||||
expect(t, dest.Value(), []int{3})
|
||||
|
||||
// reset dest
|
||||
dest = cli.NewIntSlice()
|
||||
tis = testApplyInputSource{
|
||||
Flag: NewIntSliceFlag(&cli.IntSliceFlag{Name: "test", Destination: dest}),
|
||||
FlagName: "test",
|
||||
MapValue: []interface{}{1, 2},
|
||||
ContextValueString: "3",
|
||||
}
|
||||
c = runRacyTest(t, tis)
|
||||
refute(t, c.IntSlice("test"), []int{3})
|
||||
refute(t, dest.Value(), []int{3})
|
||||
}
|
||||
|
||||
func TestIntSliceApplyInputSourceMethodEnvVarSet(t *testing.T) {
|
||||
tis := testApplyInputSource{
|
||||
Flag: NewIntSliceFlag(&cli.IntSliceFlag{Name: "test", EnvVars: []string{"TEST"}}),
|
||||
FlagName: "test",
|
||||
MapValue: []interface{}{1, 2},
|
||||
EnvVarName: "TEST",
|
||||
EnvVarValue: "3,4",
|
||||
}
|
||||
c := runTest(t, tis)
|
||||
expect(t, c.IntSlice("test"), []int{3, 4})
|
||||
|
||||
c = runRacyTest(t, tis)
|
||||
refute(t, c.IntSlice("test"), []int{3, 4})
|
||||
}
|
||||
|
||||
func TestInt64SliceFlagApplyInputSourceValue(t *testing.T) {
|
||||
dest := cli.NewInt64Slice()
|
||||
tis := testApplyInputSource{
|
||||
Flag: NewInt64SliceFlag(&cli.Int64SliceFlag{Name: "test", Destination: dest}),
|
||||
FlagName: "test",
|
||||
MapValue: []interface{}{int64(1), int64(2)},
|
||||
}
|
||||
c := runTest(t, tis)
|
||||
expect(t, c.Int64Slice("test"), []int64{1, 2})
|
||||
expect(t, dest.Value(), []int64{1, 2})
|
||||
|
||||
// reset dest
|
||||
dest = cli.NewInt64Slice()
|
||||
tis = testApplyInputSource{
|
||||
Flag: NewInt64SliceFlag(&cli.Int64SliceFlag{Name: "test", Destination: dest}),
|
||||
FlagName: "test",
|
||||
MapValue: []interface{}{int64(1), int64(2)},
|
||||
}
|
||||
c = runRacyTest(t, tis)
|
||||
refute(t, c.IntSlice("test"), []int64{1, 2})
|
||||
refute(t, dest.Value(), []int64{1, 2})
|
||||
}
|
||||
|
||||
func TestBoolApplyInputSourceMethodSet(t *testing.T) {
|
||||
tis := testApplyInputSource{
|
||||
Flag: NewBoolFlag(&cli.BoolFlag{Name: "test"}),
|
||||
FlagName: "test",
|
||||
MapValue: true,
|
||||
}
|
||||
c := runTest(t, tis)
|
||||
expect(t, true, c.Bool("test"))
|
||||
|
||||
c = runRacyTest(t, tis)
|
||||
refute(t, true, c.Bool("test"))
|
||||
}
|
||||
|
||||
func TestBoolApplyInputSourceMethodSet_Alias(t *testing.T) {
|
||||
tis := testApplyInputSource{
|
||||
Flag: NewBoolFlag(&cli.BoolFlag{Name: "test", Aliases: []string{"test_alias"}}),
|
||||
FlagName: "test_alias",
|
||||
MapValue: true,
|
||||
}
|
||||
c := runTest(t, tis)
|
||||
expect(t, true, c.Bool("test_alias"))
|
||||
|
||||
c = runRacyTest(t, tis)
|
||||
refute(t, true, c.Bool("test_alias"))
|
||||
}
|
||||
|
||||
func TestBoolApplyInputSourceMethodContextSet(t *testing.T) {
|
||||
tis := testApplyInputSource{
|
||||
Flag: NewBoolFlag(&cli.BoolFlag{Name: "test"}),
|
||||
FlagName: "test",
|
||||
MapValue: false,
|
||||
ContextValueString: "true",
|
||||
}
|
||||
c := runTest(t, tis)
|
||||
expect(t, true, c.Bool("test"))
|
||||
|
||||
c = runRacyTest(t, tis)
|
||||
refute(t, true, c.Bool("test"))
|
||||
}
|
||||
|
||||
func TestBoolApplyInputSourceMethodEnvVarSet(t *testing.T) {
|
||||
tis := testApplyInputSource{
|
||||
Flag: NewBoolFlag(&cli.BoolFlag{Name: "test", EnvVars: []string{"TEST"}}),
|
||||
FlagName: "test",
|
||||
MapValue: false,
|
||||
EnvVarName: "TEST",
|
||||
EnvVarValue: "true",
|
||||
}
|
||||
c := runTest(t, tis)
|
||||
expect(t, true, c.Bool("test"))
|
||||
|
||||
c = runRacyTest(t, tis)
|
||||
refute(t, true, c.Bool("test"))
|
||||
}
|
||||
|
||||
func TestStringApplyInputSourceMethodSet_Alias(t *testing.T) {
|
||||
tis := testApplyInputSource{
|
||||
Flag: NewStringFlag(&cli.StringFlag{Name: "test", Aliases: []string{"test_alias"}}),
|
||||
FlagName: "test_alias",
|
||||
MapValue: "hello",
|
||||
}
|
||||
c := runTest(t, tis)
|
||||
expect(t, "hello", c.String("test_alias"))
|
||||
|
||||
c = runRacyTest(t, tis)
|
||||
refute(t, "hello", c.String("test_alias"))
|
||||
}
|
||||
|
||||
func TestStringApplyInputSourceMethodSet(t *testing.T) {
|
||||
tis := testApplyInputSource{
|
||||
Flag: NewStringFlag(&cli.StringFlag{Name: "test"}),
|
||||
FlagName: "test",
|
||||
MapValue: "hello",
|
||||
}
|
||||
c := runTest(t, tis)
|
||||
expect(t, "hello", c.String("test"))
|
||||
|
||||
c = runRacyTest(t, tis)
|
||||
refute(t, "hello", c.String("test"))
|
||||
}
|
||||
|
||||
func TestStringApplyInputSourceMethodContextSet(t *testing.T) {
|
||||
tis := testApplyInputSource{
|
||||
Flag: NewStringFlag(&cli.StringFlag{Name: "test"}),
|
||||
FlagName: "test",
|
||||
MapValue: "hello",
|
||||
ContextValueString: "goodbye",
|
||||
}
|
||||
c := runTest(t, tis)
|
||||
expect(t, "goodbye", c.String("test"))
|
||||
|
||||
c = runRacyTest(t, tis)
|
||||
refute(t, "goodbye", c.String("test"))
|
||||
}
|
||||
|
||||
func TestStringApplyInputSourceMethodEnvVarSet(t *testing.T) {
|
||||
tis := testApplyInputSource{
|
||||
Flag: NewStringFlag(&cli.StringFlag{Name: "test", EnvVars: []string{"TEST"}}),
|
||||
FlagName: "test",
|
||||
MapValue: "hello",
|
||||
EnvVarName: "TEST",
|
||||
EnvVarValue: "goodbye",
|
||||
}
|
||||
c := runTest(t, tis)
|
||||
expect(t, "goodbye", c.String("test"))
|
||||
|
||||
c = runRacyTest(t, tis)
|
||||
refute(t, "goodbye", c.String("test"))
|
||||
}
|
||||
|
||||
func TestPathApplyInputSourceMethodSet_Alias(t *testing.T) {
|
||||
tis := testApplyInputSource{
|
||||
Flag: NewPathFlag(&cli.PathFlag{Name: "test", Aliases: []string{"test_alias"}}),
|
||||
FlagName: "test_alias",
|
||||
MapValue: "hello",
|
||||
SourcePath: "/path/to/source/file",
|
||||
}
|
||||
c := runTest(t, tis)
|
||||
|
||||
expected := "/path/to/source/hello"
|
||||
if runtime.GOOS == "windows" {
|
||||
var err error
|
||||
// Prepend the corresponding drive letter (or UNC path?), and change
|
||||
// to windows-style path:
|
||||
expected, err = filepath.Abs(expected)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
expect(t, expected, c.String("test_alias"))
|
||||
|
||||
c = runRacyTest(t, tis)
|
||||
refute(t, expected, c.String("test_alias"))
|
||||
}
|
||||
|
||||
func TestPathApplyInputSourceMethodSet(t *testing.T) {
|
||||
tis := testApplyInputSource{
|
||||
Flag: NewPathFlag(&cli.PathFlag{Name: "test"}),
|
||||
FlagName: "test",
|
||||
MapValue: "hello",
|
||||
SourcePath: "/path/to/source/file",
|
||||
}
|
||||
c := runTest(t, tis)
|
||||
|
||||
expected := "/path/to/source/hello"
|
||||
if runtime.GOOS == "windows" {
|
||||
var err error
|
||||
// Prepend the corresponding drive letter (or UNC path?), and change
|
||||
// to windows-style path:
|
||||
expected, err = filepath.Abs(expected)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
expect(t, expected, c.String("test"))
|
||||
|
||||
c = runRacyTest(t, tis)
|
||||
refute(t, expected, c.String("test"))
|
||||
}
|
||||
|
||||
func TestPathApplyInputSourceMethodContextSet(t *testing.T) {
|
||||
tis := testApplyInputSource{
|
||||
Flag: NewPathFlag(&cli.PathFlag{Name: "test"}),
|
||||
FlagName: "test",
|
||||
MapValue: "hello",
|
||||
ContextValueString: "goodbye",
|
||||
SourcePath: "/path/to/source/file",
|
||||
}
|
||||
c := runTest(t, tis)
|
||||
expect(t, "goodbye", c.String("test"))
|
||||
|
||||
c = runRacyTest(t, tis)
|
||||
refute(t, "goodbye", c.String("test"))
|
||||
}
|
||||
|
||||
func TestPathApplyInputSourceMethodEnvVarSet(t *testing.T) {
|
||||
tis := testApplyInputSource{
|
||||
Flag: NewPathFlag(&cli.PathFlag{Name: "test", EnvVars: []string{"TEST"}}),
|
||||
FlagName: "test",
|
||||
MapValue: "hello",
|
||||
EnvVarName: "TEST",
|
||||
EnvVarValue: "goodbye",
|
||||
SourcePath: "/path/to/source/file",
|
||||
}
|
||||
c := runTest(t, tis)
|
||||
expect(t, "goodbye", c.String("test"))
|
||||
|
||||
c = runRacyTest(t, tis)
|
||||
refute(t, "goodbye", c.String("test"))
|
||||
}
|
||||
|
||||
func TestIntApplyInputSourceMethodSet_Alias(t *testing.T) {
|
||||
tis := testApplyInputSource{
|
||||
Flag: NewIntFlag(&cli.IntFlag{Name: "test", Aliases: []string{"test_alias"}}),
|
||||
FlagName: "test_alias",
|
||||
MapValue: 15,
|
||||
}
|
||||
c := runTest(t, tis)
|
||||
expect(t, 15, c.Int("test_alias"))
|
||||
|
||||
c = runRacyTest(t, tis)
|
||||
refute(t, 15, c.Int("test_alias"))
|
||||
}
|
||||
|
||||
func TestIntApplyInputSourceMethodSet(t *testing.T) {
|
||||
tis := testApplyInputSource{
|
||||
Flag: NewIntFlag(&cli.IntFlag{Name: "test"}),
|
||||
FlagName: "test",
|
||||
MapValue: 15,
|
||||
}
|
||||
c := runTest(t, tis)
|
||||
expect(t, 15, c.Int("test"))
|
||||
|
||||
c = runRacyTest(t, tis)
|
||||
refute(t, 15, c.Int("test"))
|
||||
}
|
||||
|
||||
func TestIntApplyInputSourceMethodSetNegativeValue(t *testing.T) {
|
||||
tis := testApplyInputSource{
|
||||
Flag: NewIntFlag(&cli.IntFlag{Name: "test"}),
|
||||
FlagName: "test",
|
||||
MapValue: -1,
|
||||
}
|
||||
c := runTest(t, tis)
|
||||
expect(t, -1, c.Int("test"))
|
||||
|
||||
c = runRacyTest(t, tis)
|
||||
refute(t, -1, c.Int("test"))
|
||||
}
|
||||
|
||||
func TestIntApplyInputSourceMethodContextSet(t *testing.T) {
|
||||
tis := testApplyInputSource{
|
||||
Flag: NewIntFlag(&cli.IntFlag{Name: "test"}),
|
||||
FlagName: "test",
|
||||
MapValue: 15,
|
||||
ContextValueString: "7",
|
||||
}
|
||||
c := runTest(t, tis)
|
||||
expect(t, 7, c.Int("test"))
|
||||
|
||||
c = runRacyTest(t, tis)
|
||||
refute(t, 7, c.Int("test"))
|
||||
}
|
||||
|
||||
func TestIntApplyInputSourceMethodEnvVarSet(t *testing.T) {
|
||||
tis := testApplyInputSource{
|
||||
Flag: NewIntFlag(&cli.IntFlag{Name: "test", EnvVars: []string{"TEST"}}),
|
||||
FlagName: "test",
|
||||
MapValue: 15,
|
||||
EnvVarName: "TEST",
|
||||
EnvVarValue: "12",
|
||||
}
|
||||
c := runTest(t, tis)
|
||||
expect(t, 12, c.Int("test"))
|
||||
|
||||
c = runRacyTest(t, tis)
|
||||
refute(t, 12, c.Int("test"))
|
||||
}
|
||||
|
||||
func TestDurationApplyInputSourceMethodSet_Alias(t *testing.T) {
|
||||
tis := testApplyInputSource{
|
||||
Flag: NewDurationFlag(&cli.DurationFlag{Name: "test", Aliases: []string{"test_alias"}}),
|
||||
FlagName: "test_alias",
|
||||
MapValue: 30 * time.Second,
|
||||
}
|
||||
c := runTest(t, tis)
|
||||
expect(t, 30*time.Second, c.Duration("test_alias"))
|
||||
|
||||
c = runRacyTest(t, tis)
|
||||
refute(t, 30*time.Second, c.Duration("test_alias"))
|
||||
}
|
||||
|
||||
func TestDurationApplyInputSourceMethodSet(t *testing.T) {
|
||||
tis := testApplyInputSource{
|
||||
Flag: NewDurationFlag(&cli.DurationFlag{Name: "test"}),
|
||||
FlagName: "test",
|
||||
MapValue: 30 * time.Second,
|
||||
}
|
||||
c := runTest(t, tis)
|
||||
expect(t, 30*time.Second, c.Duration("test"))
|
||||
|
||||
c = runRacyTest(t, tis)
|
||||
refute(t, 30*time.Second, c.Duration("test"))
|
||||
}
|
||||
|
||||
func TestDurationApplyInputSourceMethodSetNegativeValue(t *testing.T) {
|
||||
tis := testApplyInputSource{
|
||||
Flag: NewDurationFlag(&cli.DurationFlag{Name: "test"}),
|
||||
FlagName: "test",
|
||||
MapValue: -30 * time.Second,
|
||||
}
|
||||
c := runTest(t, tis)
|
||||
expect(t, -30*time.Second, c.Duration("test"))
|
||||
|
||||
c = runRacyTest(t, tis)
|
||||
refute(t, -30*time.Second, c.Duration("test"))
|
||||
}
|
||||
|
||||
func TestDurationApplyInputSourceMethodContextSet(t *testing.T) {
|
||||
tis := testApplyInputSource{
|
||||
Flag: NewDurationFlag(&cli.DurationFlag{Name: "test"}),
|
||||
FlagName: "test",
|
||||
MapValue: 30 * time.Second,
|
||||
ContextValueString: (15 * time.Second).String(),
|
||||
}
|
||||
c := runTest(t, tis)
|
||||
expect(t, 15*time.Second, c.Duration("test"))
|
||||
|
||||
c = runRacyTest(t, tis)
|
||||
refute(t, 15*time.Second, c.Duration("test"))
|
||||
}
|
||||
|
||||
func TestDurationApplyInputSourceMethodEnvVarSet(t *testing.T) {
|
||||
tis := testApplyInputSource{
|
||||
Flag: NewDurationFlag(&cli.DurationFlag{Name: "test", EnvVars: []string{"TEST"}}),
|
||||
FlagName: "test",
|
||||
MapValue: 30 * time.Second,
|
||||
EnvVarName: "TEST",
|
||||
EnvVarValue: (15 * time.Second).String(),
|
||||
}
|
||||
c := runTest(t, tis)
|
||||
expect(t, 15*time.Second, c.Duration("test"))
|
||||
|
||||
c = runRacyTest(t, tis)
|
||||
refute(t, 15*time.Second, c.Duration("test"))
|
||||
}
|
||||
|
||||
func TestFloat64ApplyInputSourceMethodSet(t *testing.T) {
|
||||
tis := testApplyInputSource{
|
||||
Flag: NewFloat64Flag(&cli.Float64Flag{Name: "test"}),
|
||||
FlagName: "test",
|
||||
MapValue: 1.3,
|
||||
}
|
||||
c := runTest(t, tis)
|
||||
expect(t, 1.3, c.Float64("test"))
|
||||
|
||||
c = runRacyTest(t, tis)
|
||||
refute(t, 1.3, c.Float64("test"))
|
||||
}
|
||||
|
||||
func TestFloat64ApplyInputSourceMethodSetNegativeValue_Alias(t *testing.T) {
|
||||
tis := testApplyInputSource{
|
||||
Flag: NewFloat64Flag(&cli.Float64Flag{Name: "test", Aliases: []string{"test_alias"}}),
|
||||
FlagName: "test_alias",
|
||||
MapValue: -1.3,
|
||||
}
|
||||
c := runTest(t, tis)
|
||||
expect(t, -1.3, c.Float64("test_alias"))
|
||||
|
||||
c = runRacyTest(t, tis)
|
||||
refute(t, -1.3, c.Float64("test_alias"))
|
||||
}
|
||||
|
||||
func TestFloat64ApplyInputSourceMethodSetNegativeValue(t *testing.T) {
|
||||
tis := testApplyInputSource{
|
||||
Flag: NewFloat64Flag(&cli.Float64Flag{Name: "test"}),
|
||||
FlagName: "test",
|
||||
MapValue: -1.3,
|
||||
}
|
||||
c := runTest(t, tis)
|
||||
expect(t, -1.3, c.Float64("test"))
|
||||
|
||||
c = runRacyTest(t, tis)
|
||||
refute(t, -1.3, c.Float64("test"))
|
||||
}
|
||||
|
||||
func TestFloat64ApplyInputSourceMethodSetNegativeValueNotSet(t *testing.T) {
|
||||
c := runTest(t, testApplyInputSource{
|
||||
Flag: NewFloat64Flag(&cli.Float64Flag{Name: "test1"}),
|
||||
FlagName: "test1",
|
||||
// dont set map value
|
||||
})
|
||||
expect(t, 0.0, c.Float64("test1"))
|
||||
}
|
||||
|
||||
func TestFloat64ApplyInputSourceMethodContextSet(t *testing.T) {
|
||||
tis := testApplyInputSource{
|
||||
Flag: NewFloat64Flag(&cli.Float64Flag{Name: "test"}),
|
||||
FlagName: "test",
|
||||
MapValue: 1.3,
|
||||
ContextValueString: fmt.Sprintf("%v", 1.4),
|
||||
}
|
||||
c := runTest(t, tis)
|
||||
expect(t, 1.4, c.Float64("test"))
|
||||
|
||||
c = runRacyTest(t, tis)
|
||||
refute(t, 1.4, c.Float64("test"))
|
||||
}
|
||||
|
||||
func TestFloat64ApplyInputSourceMethodEnvVarSet(t *testing.T) {
|
||||
tis := testApplyInputSource{
|
||||
Flag: NewFloat64Flag(&cli.Float64Flag{Name: "test", EnvVars: []string{"TEST"}}),
|
||||
FlagName: "test",
|
||||
MapValue: 1.3,
|
||||
EnvVarName: "TEST",
|
||||
EnvVarValue: fmt.Sprintf("%v", 1.4),
|
||||
}
|
||||
c := runTest(t, tis)
|
||||
expect(t, 1.4, c.Float64("test"))
|
||||
|
||||
c = runRacyTest(t, tis)
|
||||
refute(t, 1.4, c.Float64("test"))
|
||||
}
|
||||
|
||||
func runTest(t *testing.T, test testApplyInputSource) *cli.Context {
|
||||
inputSource := &MapInputSource{
|
||||
file: test.SourcePath,
|
||||
valueMap: map[interface{}]interface{}{test.FlagName: test.MapValue},
|
||||
}
|
||||
set := flag.NewFlagSet(test.FlagSetName, flag.ContinueOnError)
|
||||
c := cli.NewContext(nil, set, nil)
|
||||
if test.EnvVarName != "" && test.EnvVarValue != "" {
|
||||
_ = os.Setenv(test.EnvVarName, test.EnvVarValue)
|
||||
defer os.Setenv(test.EnvVarName, "")
|
||||
}
|
||||
|
||||
_ = test.Flag.Apply(set)
|
||||
if test.ContextValue != nil {
|
||||
f := set.Lookup(test.FlagName)
|
||||
f.Value = test.ContextValue
|
||||
}
|
||||
if test.ContextValueString != "" {
|
||||
_ = set.Set(test.FlagName, test.ContextValueString)
|
||||
}
|
||||
_ = test.Flag.ApplyInputSourceValue(c, inputSource)
|
||||
|
||||
return c
|
||||
}
|
||||
|
||||
func runRacyTest(t *testing.T, test testApplyInputSource) *cli.Context {
|
||||
set := flag.NewFlagSet(test.FlagSetName, flag.ContinueOnError)
|
||||
c := cli.NewContext(nil, set, nil)
|
||||
_ = test.Flag.ApplyInputSourceValue(c, &racyInputSource{
|
||||
MapInputSource: &MapInputSource{
|
||||
file: test.SourcePath,
|
||||
valueMap: map[interface{}]interface{}{test.FlagName: test.MapValue},
|
||||
},
|
||||
})
|
||||
|
||||
return c
|
||||
}
|
||||
|
||||
type Parser [2]string
|
||||
|
||||
func (p *Parser) Set(value string) error {
|
||||
parts := strings.Split(value, ",")
|
||||
if len(parts) != 2 {
|
||||
return fmt.Errorf("invalid format")
|
||||
}
|
||||
|
||||
(*p)[0] = parts[0]
|
||||
(*p)[1] = parts[1]
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *Parser) String() string {
|
||||
return fmt.Sprintf("%s,%s", p[0], p[1])
|
||||
}
|
||||
|
||||
type bogus [1]uint
|
@@ -1,31 +0,0 @@
|
||||
package altsrc
|
||||
|
||||
import (
|
||||
"os"
|
||||
"reflect"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
var (
|
||||
wd, _ = os.Getwd()
|
||||
)
|
||||
|
||||
func expect(t *testing.T, a interface{}, b interface{}) {
|
||||
_, fn, line, _ := runtime.Caller(1)
|
||||
fn = strings.Replace(fn, wd+"/", "", -1)
|
||||
|
||||
if !reflect.DeepEqual(a, b) {
|
||||
t.Errorf("(%s:%d) Expected %v (type %v) - Got %v (type %v)", fn, line, b, reflect.TypeOf(b), a, reflect.TypeOf(a))
|
||||
}
|
||||
}
|
||||
|
||||
func refute(t *testing.T, a interface{}, b interface{}) {
|
||||
_, fn, line, _ := runtime.Caller(1)
|
||||
fn = strings.Replace(fn, wd+"/", "", -1)
|
||||
|
||||
if reflect.DeepEqual(a, b) {
|
||||
t.Errorf("(%s:%d) Did not expect %v (type %v) - Got %v (type %v)", fn, line, b, reflect.TypeOf(b), a, reflect.TypeOf(a))
|
||||
}
|
||||
}
|
@@ -1,28 +0,0 @@
|
||||
package altsrc
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/urfave/cli/v3"
|
||||
)
|
||||
|
||||
// InputSourceContext is an interface used to allow
|
||||
// other input sources to be implemented as needed.
|
||||
//
|
||||
// Source returns an identifier for the input source. In case of file source
|
||||
// it should return path to the file.
|
||||
type InputSourceContext interface {
|
||||
Source() string
|
||||
|
||||
Int(name string) (int, error)
|
||||
Duration(name string) (time.Duration, error)
|
||||
Float64(name string) (float64, error)
|
||||
String(name string) (string, error)
|
||||
StringSlice(name string) ([]string, error)
|
||||
IntSlice(name string) ([]int, error)
|
||||
Int64Slice(name string) ([]int64, error)
|
||||
Generic(name string) (cli.Generic, error)
|
||||
Bool(name string) (bool, error)
|
||||
|
||||
isSet(name string) bool
|
||||
}
|
@@ -1,329 +0,0 @@
|
||||
package altsrc
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/urfave/cli/v3"
|
||||
)
|
||||
|
||||
const (
|
||||
fileName = "current.json"
|
||||
simpleJSON = `{"test": 15, "testb": false}`
|
||||
nestedJSON = `{"top": {"test": 15}}`
|
||||
)
|
||||
|
||||
func TestCommandJSONFileTest(t *testing.T) {
|
||||
cleanup := writeTempFile(t, fileName, simpleJSON)
|
||||
defer cleanup()
|
||||
|
||||
app := &cli.App{}
|
||||
set := flag.NewFlagSet("test", 0)
|
||||
test := []string{"test-cmd", "--load", fileName}
|
||||
_ = set.Parse(test)
|
||||
|
||||
c := cli.NewContext(app, set, nil)
|
||||
|
||||
command := &cli.Command{
|
||||
Name: "test-cmd",
|
||||
Aliases: []string{"tc"},
|
||||
Usage: "this is for testing",
|
||||
Description: "testing",
|
||||
Action: func(c *cli.Context) error {
|
||||
val := c.Int("test")
|
||||
expect(t, val, 15)
|
||||
|
||||
valb := c.Bool("testb")
|
||||
expect(t, valb, false)
|
||||
return nil
|
||||
},
|
||||
Flags: []cli.Flag{
|
||||
NewIntFlag(&cli.IntFlag{Name: "test"}),
|
||||
&cli.StringFlag{Name: "load"},
|
||||
NewBoolFlag(&cli.BoolFlag{Name: "testb", Value: true}),
|
||||
},
|
||||
}
|
||||
command.Before = InitInputSourceWithContext(command.Flags, NewJSONSourceFromFlagFunc("load"))
|
||||
err := command.Run(c, test...)
|
||||
|
||||
expect(t, err, nil)
|
||||
}
|
||||
|
||||
func TestCommandJSONFileTestGlobalEnvVarWins(t *testing.T) {
|
||||
cleanup := writeTempFile(t, fileName, simpleJSON)
|
||||
defer cleanup()
|
||||
|
||||
app := &cli.App{}
|
||||
set := flag.NewFlagSet("test", 0)
|
||||
_ = os.Setenv("THE_TEST", "10")
|
||||
defer os.Setenv("THE_TEST", "")
|
||||
|
||||
test := []string{"test-cmd", "--load", fileName}
|
||||
_ = set.Parse(test)
|
||||
|
||||
c := cli.NewContext(app, set, nil)
|
||||
|
||||
command := &cli.Command{
|
||||
Name: "test-cmd",
|
||||
Aliases: []string{"tc"},
|
||||
Usage: "this is for testing",
|
||||
Description: "testing",
|
||||
Action: func(c *cli.Context) error {
|
||||
val := c.Int("test")
|
||||
expect(t, val, 10)
|
||||
return nil
|
||||
},
|
||||
Flags: []cli.Flag{
|
||||
NewIntFlag(&cli.IntFlag{Name: "test", EnvVars: []string{"THE_TEST"}}),
|
||||
&cli.StringFlag{Name: "load"}},
|
||||
}
|
||||
command.Before = InitInputSourceWithContext(command.Flags, NewJSONSourceFromFlagFunc("load"))
|
||||
|
||||
err := command.Run(c, test...)
|
||||
|
||||
expect(t, err, nil)
|
||||
}
|
||||
|
||||
func TestCommandJSONFileTestGlobalEnvVarWinsNested(t *testing.T) {
|
||||
cleanup := writeTempFile(t, fileName, nestedJSON)
|
||||
defer cleanup()
|
||||
|
||||
app := &cli.App{}
|
||||
set := flag.NewFlagSet("test", 0)
|
||||
_ = os.Setenv("THE_TEST", "10")
|
||||
defer os.Setenv("THE_TEST", "")
|
||||
|
||||
test := []string{"test-cmd", "--load", fileName}
|
||||
_ = set.Parse(test)
|
||||
|
||||
c := cli.NewContext(app, set, nil)
|
||||
|
||||
command := &cli.Command{
|
||||
Name: "test-cmd",
|
||||
Aliases: []string{"tc"},
|
||||
Usage: "this is for testing",
|
||||
Description: "testing",
|
||||
Action: func(c *cli.Context) error {
|
||||
val := c.Int("top.test")
|
||||
expect(t, val, 10)
|
||||
return nil
|
||||
},
|
||||
Flags: []cli.Flag{
|
||||
NewIntFlag(&cli.IntFlag{Name: "top.test", EnvVars: []string{"THE_TEST"}}),
|
||||
&cli.StringFlag{Name: "load"}},
|
||||
}
|
||||
command.Before = InitInputSourceWithContext(command.Flags, NewJSONSourceFromFlagFunc("load"))
|
||||
|
||||
err := command.Run(c, test...)
|
||||
|
||||
expect(t, err, nil)
|
||||
}
|
||||
|
||||
func TestCommandJSONFileTestSpecifiedFlagWins(t *testing.T) {
|
||||
cleanup := writeTempFile(t, fileName, simpleJSON)
|
||||
defer cleanup()
|
||||
|
||||
app := &cli.App{}
|
||||
set := flag.NewFlagSet("test", 0)
|
||||
test := []string{"test-cmd", "--load", fileName, "--test", "7"}
|
||||
_ = set.Parse(test)
|
||||
|
||||
c := cli.NewContext(app, set, nil)
|
||||
|
||||
command := &cli.Command{
|
||||
Name: "test-cmd",
|
||||
Aliases: []string{"tc"},
|
||||
Usage: "this is for testing",
|
||||
Description: "testing",
|
||||
Action: func(c *cli.Context) error {
|
||||
val := c.Int("test")
|
||||
expect(t, val, 7)
|
||||
return nil
|
||||
},
|
||||
Flags: []cli.Flag{
|
||||
NewIntFlag(&cli.IntFlag{Name: "test"}),
|
||||
&cli.StringFlag{Name: "load"}},
|
||||
}
|
||||
command.Before = InitInputSourceWithContext(command.Flags, NewJSONSourceFromFlagFunc("load"))
|
||||
|
||||
err := command.Run(c, test...)
|
||||
|
||||
expect(t, err, nil)
|
||||
}
|
||||
|
||||
func TestCommandJSONFileTestSpecifiedFlagWinsNested(t *testing.T) {
|
||||
cleanup := writeTempFile(t, fileName, nestedJSON)
|
||||
defer cleanup()
|
||||
|
||||
app := &cli.App{}
|
||||
set := flag.NewFlagSet("test", 0)
|
||||
test := []string{"test-cmd", "--load", fileName, "--top.test", "7"}
|
||||
_ = set.Parse(test)
|
||||
|
||||
c := cli.NewContext(app, set, nil)
|
||||
|
||||
command := &cli.Command{
|
||||
Name: "test-cmd",
|
||||
Aliases: []string{"tc"},
|
||||
Usage: "this is for testing",
|
||||
Description: "testing",
|
||||
Action: func(c *cli.Context) error {
|
||||
val := c.Int("top.test")
|
||||
expect(t, val, 7)
|
||||
return nil
|
||||
},
|
||||
Flags: []cli.Flag{
|
||||
NewIntFlag(&cli.IntFlag{Name: "top.test"}),
|
||||
&cli.StringFlag{Name: "load"}},
|
||||
}
|
||||
command.Before = InitInputSourceWithContext(command.Flags, NewJSONSourceFromFlagFunc("load"))
|
||||
|
||||
err := command.Run(c, test...)
|
||||
|
||||
expect(t, err, nil)
|
||||
}
|
||||
|
||||
func TestCommandJSONFileTestDefaultValueFileWins(t *testing.T) {
|
||||
cleanup := writeTempFile(t, fileName, simpleJSON)
|
||||
defer cleanup()
|
||||
|
||||
app := &cli.App{}
|
||||
set := flag.NewFlagSet("test", 0)
|
||||
test := []string{"test-cmd", "--load", fileName}
|
||||
_ = set.Parse(test)
|
||||
|
||||
c := cli.NewContext(app, set, nil)
|
||||
|
||||
command := &cli.Command{
|
||||
Name: "test-cmd",
|
||||
Aliases: []string{"tc"},
|
||||
Usage: "this is for testing",
|
||||
Description: "testing",
|
||||
Action: func(c *cli.Context) error {
|
||||
val := c.Int("test")
|
||||
expect(t, val, 15)
|
||||
return nil
|
||||
},
|
||||
Flags: []cli.Flag{
|
||||
NewIntFlag(&cli.IntFlag{Name: "test", Value: 7}),
|
||||
&cli.StringFlag{Name: "load"}},
|
||||
}
|
||||
command.Before = InitInputSourceWithContext(command.Flags, NewJSONSourceFromFlagFunc("load"))
|
||||
|
||||
err := command.Run(c, test...)
|
||||
|
||||
expect(t, err, nil)
|
||||
}
|
||||
|
||||
func TestCommandJSONFileTestDefaultValueFileWinsNested(t *testing.T) {
|
||||
cleanup := writeTempFile(t, fileName, nestedJSON)
|
||||
defer cleanup()
|
||||
|
||||
app := &cli.App{}
|
||||
set := flag.NewFlagSet("test", 0)
|
||||
test := []string{"test-cmd", "--load", fileName}
|
||||
_ = set.Parse(test)
|
||||
|
||||
c := cli.NewContext(app, set, nil)
|
||||
|
||||
command := &cli.Command{
|
||||
Name: "test-cmd",
|
||||
Aliases: []string{"tc"},
|
||||
Usage: "this is for testing",
|
||||
Description: "testing",
|
||||
Action: func(c *cli.Context) error {
|
||||
val := c.Int("top.test")
|
||||
expect(t, val, 15)
|
||||
return nil
|
||||
},
|
||||
Flags: []cli.Flag{
|
||||
NewIntFlag(&cli.IntFlag{Name: "top.test", Value: 7}),
|
||||
&cli.StringFlag{Name: "load"}},
|
||||
}
|
||||
command.Before = InitInputSourceWithContext(command.Flags, NewJSONSourceFromFlagFunc("load"))
|
||||
|
||||
err := command.Run(c, test...)
|
||||
|
||||
expect(t, err, nil)
|
||||
}
|
||||
|
||||
func TestCommandJSONFileFlagHasDefaultGlobalEnvJSONSetGlobalEnvWins(t *testing.T) {
|
||||
cleanup := writeTempFile(t, fileName, simpleJSON)
|
||||
defer cleanup()
|
||||
|
||||
app := &cli.App{}
|
||||
set := flag.NewFlagSet("test", 0)
|
||||
_ = os.Setenv("THE_TEST", "11")
|
||||
defer os.Setenv("THE_TEST", "")
|
||||
|
||||
test := []string{"test-cmd", "--load", fileName}
|
||||
_ = set.Parse(test)
|
||||
|
||||
c := cli.NewContext(app, set, nil)
|
||||
|
||||
command := &cli.Command{
|
||||
Name: "test-cmd",
|
||||
Aliases: []string{"tc"},
|
||||
Usage: "this is for testing",
|
||||
Description: "testing",
|
||||
Action: func(c *cli.Context) error {
|
||||
val := c.Int("test")
|
||||
expect(t, val, 11)
|
||||
return nil
|
||||
},
|
||||
Flags: []cli.Flag{
|
||||
NewIntFlag(&cli.IntFlag{Name: "test", Value: 7, EnvVars: []string{"THE_TEST"}}),
|
||||
&cli.StringFlag{Name: "load"}},
|
||||
}
|
||||
command.Before = InitInputSourceWithContext(command.Flags, NewJSONSourceFromFlagFunc("load"))
|
||||
err := command.Run(c, test...)
|
||||
|
||||
expect(t, err, nil)
|
||||
}
|
||||
|
||||
func TestCommandJSONFileFlagHasDefaultGlobalEnvJSONSetGlobalEnvWinsNested(t *testing.T) {
|
||||
cleanup := writeTempFile(t, fileName, nestedJSON)
|
||||
defer cleanup()
|
||||
|
||||
app := &cli.App{}
|
||||
set := flag.NewFlagSet("test", 0)
|
||||
_ = os.Setenv("THE_TEST", "11")
|
||||
defer os.Setenv("THE_TEST", "")
|
||||
|
||||
test := []string{"test-cmd", "--load", fileName}
|
||||
_ = set.Parse(test)
|
||||
|
||||
c := cli.NewContext(app, set, nil)
|
||||
|
||||
command := &cli.Command{
|
||||
Name: "test-cmd",
|
||||
Aliases: []string{"tc"},
|
||||
Usage: "this is for testing",
|
||||
Description: "testing",
|
||||
Action: func(c *cli.Context) error {
|
||||
val := c.Int("top.test")
|
||||
expect(t, val, 11)
|
||||
return nil
|
||||
},
|
||||
Flags: []cli.Flag{
|
||||
NewIntFlag(&cli.IntFlag{Name: "top.test", Value: 7, EnvVars: []string{"THE_TEST"}}),
|
||||
&cli.StringFlag{Name: "load"}},
|
||||
}
|
||||
command.Before = InitInputSourceWithContext(command.Flags, NewJSONSourceFromFlagFunc("load"))
|
||||
err := command.Run(c, test...)
|
||||
|
||||
expect(t, err, nil)
|
||||
}
|
||||
|
||||
func writeTempFile(t *testing.T, name string, content string) func() {
|
||||
if err := ioutil.WriteFile(name, []byte(content), 0666); err != nil {
|
||||
t.Fatalf("cannot write %q: %v", name, err)
|
||||
}
|
||||
return func() {
|
||||
if err := os.Remove(name); err != nil {
|
||||
t.Errorf("cannot remove %q: %v", name, err)
|
||||
}
|
||||
}
|
||||
}
|
@@ -1,240 +0,0 @@
|
||||
package altsrc
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/urfave/cli/v3"
|
||||
)
|
||||
|
||||
// NewJSONSourceFromFlagFunc returns a func that takes a cli.Context
|
||||
// and returns an InputSourceContext suitable for retrieving config
|
||||
// variables from a file containing JSON data with the file name defined
|
||||
// by the given flag.
|
||||
func NewJSONSourceFromFlagFunc(flag string) func(c *cli.Context) (InputSourceContext, error) {
|
||||
return func(cCtx *cli.Context) (InputSourceContext, error) {
|
||||
if cCtx.IsSet(flag) {
|
||||
return NewJSONSourceFromFile(cCtx.String(flag))
|
||||
}
|
||||
|
||||
return defaultInputSource()
|
||||
}
|
||||
}
|
||||
|
||||
// NewJSONSourceFromFile returns an InputSourceContext suitable for
|
||||
// retrieving config variables from a file (or url) containing JSON
|
||||
// data.
|
||||
func NewJSONSourceFromFile(f string) (InputSourceContext, error) {
|
||||
data, err := loadDataFrom(f)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return NewJSONSource(data)
|
||||
}
|
||||
|
||||
// NewJSONSourceFromReader returns an InputSourceContext suitable for
|
||||
// retrieving config variables from an io.Reader that returns JSON data.
|
||||
func NewJSONSourceFromReader(r io.Reader) (InputSourceContext, error) {
|
||||
data, err := ioutil.ReadAll(r)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return NewJSONSource(data)
|
||||
}
|
||||
|
||||
// NewJSONSource returns an InputSourceContext suitable for retrieving
|
||||
// config variables from raw JSON data.
|
||||
func NewJSONSource(data []byte) (InputSourceContext, error) {
|
||||
var deserialized map[string]interface{}
|
||||
if err := json.Unmarshal(data, &deserialized); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &jsonSource{deserialized: deserialized}, nil
|
||||
}
|
||||
|
||||
func (x *jsonSource) Source() string {
|
||||
return x.file
|
||||
}
|
||||
|
||||
func (x *jsonSource) Int(name string) (int, error) {
|
||||
i, err := x.getValue(name)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
switch v := i.(type) {
|
||||
default:
|
||||
return 0, fmt.Errorf("unexpected type %T for %q", i, name)
|
||||
case int:
|
||||
return v, nil
|
||||
case float32:
|
||||
return int(v), nil
|
||||
case float64:
|
||||
return int(v), nil
|
||||
}
|
||||
}
|
||||
|
||||
func (x *jsonSource) Duration(name string) (time.Duration, error) {
|
||||
i, err := x.getValue(name)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
v, ok := i.(time.Duration)
|
||||
if !ok {
|
||||
return 0, fmt.Errorf("unexpected type %T for %q", i, name)
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
|
||||
func (x *jsonSource) Float64(name string) (float64, error) {
|
||||
i, err := x.getValue(name)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
v, ok := i.(float64)
|
||||
if !ok {
|
||||
return 0, fmt.Errorf("unexpected type %T for %q", i, name)
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
|
||||
func (x *jsonSource) String(name string) (string, error) {
|
||||
i, err := x.getValue(name)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
v, ok := i.(string)
|
||||
if !ok {
|
||||
return "", fmt.Errorf("unexpected type %T for %q", i, name)
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
|
||||
func (x *jsonSource) StringSlice(name string) ([]string, error) {
|
||||
i, err := x.getValue(name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
switch v := i.(type) {
|
||||
default:
|
||||
return nil, fmt.Errorf("unexpected type %T for %q", i, name)
|
||||
case []string:
|
||||
return v, nil
|
||||
case []interface{}:
|
||||
c := []string{}
|
||||
for _, s := range v {
|
||||
if str, ok := s.(string); ok {
|
||||
c = append(c, str)
|
||||
} else {
|
||||
return c, fmt.Errorf("unexpected item type %T in %T for %q", s, c, name)
|
||||
}
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
}
|
||||
|
||||
func (x *jsonSource) IntSlice(name string) ([]int, error) {
|
||||
i, err := x.getValue(name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
switch v := i.(type) {
|
||||
default:
|
||||
return nil, fmt.Errorf("unexpected type %T for %q", i, name)
|
||||
case []int:
|
||||
return v, nil
|
||||
case []interface{}:
|
||||
c := []int{}
|
||||
for _, s := range v {
|
||||
if i2, ok := s.(int); ok {
|
||||
c = append(c, i2)
|
||||
} else {
|
||||
return c, fmt.Errorf("unexpected item type %T in %T for %q", s, c, name)
|
||||
}
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
}
|
||||
|
||||
func (x *jsonSource) Int64Slice(name string) ([]int64, error) {
|
||||
i, err := x.getValue(name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
switch v := i.(type) {
|
||||
default:
|
||||
return nil, fmt.Errorf("unexpected type %T for %q", i, name)
|
||||
case []int64:
|
||||
return v, nil
|
||||
case []interface{}:
|
||||
c := []int64{}
|
||||
for _, s := range v {
|
||||
if i2, ok := s.(int64); ok {
|
||||
c = append(c, i2)
|
||||
} else {
|
||||
return c, fmt.Errorf("unexpected item type %T in %T for %q", s, c, name)
|
||||
}
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
}
|
||||
|
||||
func (x *jsonSource) Generic(name string) (cli.Generic, error) {
|
||||
i, err := x.getValue(name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
v, ok := i.(cli.Generic)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unexpected type %T for %q", i, name)
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
|
||||
func (x *jsonSource) Bool(name string) (bool, error) {
|
||||
i, err := x.getValue(name)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
v, ok := i.(bool)
|
||||
if !ok {
|
||||
return false, fmt.Errorf("unexpected type %T for %q", i, name)
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
|
||||
func (x *jsonSource) isSet(name string) bool {
|
||||
_, err := x.getValue(name)
|
||||
return err == nil
|
||||
}
|
||||
|
||||
func (x *jsonSource) getValue(key string) (interface{}, error) {
|
||||
return jsonGetValue(key, x.deserialized)
|
||||
}
|
||||
|
||||
func jsonGetValue(key string, m map[string]interface{}) (interface{}, error) {
|
||||
var ret interface{}
|
||||
var ok bool
|
||||
working := m
|
||||
keys := strings.Split(key, ".")
|
||||
for ix, k := range keys {
|
||||
if ret, ok = working[k]; !ok {
|
||||
return ret, fmt.Errorf("missing key %q", key)
|
||||
}
|
||||
if working, ok = ret.(map[string]interface{}); !ok {
|
||||
if ix < len(keys)-1 {
|
||||
return ret, fmt.Errorf("unexpected intermediate value at %q segment of %q: %T", k, key, ret)
|
||||
}
|
||||
}
|
||||
}
|
||||
return ret, nil
|
||||
}
|
||||
|
||||
type jsonSource struct {
|
||||
file string
|
||||
deserialized map[string]interface{}
|
||||
}
|
@@ -1,300 +0,0 @@
|
||||
package altsrc
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"reflect"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/urfave/cli/v3"
|
||||
)
|
||||
|
||||
// MapInputSource implements InputSourceContext to return
|
||||
// data from the map that is loaded.
|
||||
type MapInputSource struct {
|
||||
file string
|
||||
valueMap map[interface{}]interface{}
|
||||
}
|
||||
|
||||
// NewMapInputSource creates a new MapInputSource for implementing custom input sources.
|
||||
func NewMapInputSource(file string, valueMap map[interface{}]interface{}) *MapInputSource {
|
||||
return &MapInputSource{file: file, valueMap: valueMap}
|
||||
}
|
||||
|
||||
// nestedVal checks if the name has '.' delimiters.
|
||||
// If so, it tries to traverse the tree by the '.' delimited sections to find
|
||||
// a nested value for the key.
|
||||
func nestedVal(name string, tree map[interface{}]interface{}) (interface{}, bool) {
|
||||
if sections := strings.Split(name, "."); len(sections) > 1 {
|
||||
node := tree
|
||||
for _, section := range sections[:len(sections)-1] {
|
||||
child, ok := node[section]
|
||||
if !ok {
|
||||
return nil, false
|
||||
}
|
||||
|
||||
switch child := child.(type) {
|
||||
case map[string]interface{}:
|
||||
node = make(map[interface{}]interface{}, len(child))
|
||||
for k, v := range child {
|
||||
node[k] = v
|
||||
}
|
||||
case map[interface{}]interface{}:
|
||||
node = child
|
||||
default:
|
||||
return nil, false
|
||||
}
|
||||
}
|
||||
if val, ok := node[sections[len(sections)-1]]; ok {
|
||||
return val, true
|
||||
}
|
||||
}
|
||||
return nil, false
|
||||
}
|
||||
|
||||
// Source returns the path of the source file
|
||||
func (fsm *MapInputSource) Source() string {
|
||||
return fsm.file
|
||||
}
|
||||
|
||||
// Int returns an int from the map if it exists otherwise returns 0
|
||||
func (fsm *MapInputSource) Int(name string) (int, error) {
|
||||
otherGenericValue, exists := fsm.valueMap[name]
|
||||
if exists {
|
||||
otherValue, isType := otherGenericValue.(int)
|
||||
if !isType {
|
||||
return 0, incorrectTypeForFlagError(name, "int", otherGenericValue)
|
||||
}
|
||||
return otherValue, nil
|
||||
}
|
||||
nestedGenericValue, exists := nestedVal(name, fsm.valueMap)
|
||||
if exists {
|
||||
otherValue, isType := nestedGenericValue.(int)
|
||||
if !isType {
|
||||
return 0, incorrectTypeForFlagError(name, "int", nestedGenericValue)
|
||||
}
|
||||
return otherValue, nil
|
||||
}
|
||||
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
// Duration returns a duration from the map if it exists otherwise returns 0
|
||||
func (fsm *MapInputSource) Duration(name string) (time.Duration, error) {
|
||||
otherGenericValue, exists := fsm.valueMap[name]
|
||||
if exists {
|
||||
return castDuration(name, otherGenericValue)
|
||||
}
|
||||
nestedGenericValue, exists := nestedVal(name, fsm.valueMap)
|
||||
if exists {
|
||||
return castDuration(name, nestedGenericValue)
|
||||
}
|
||||
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
func castDuration(name string, value interface{}) (time.Duration, error) {
|
||||
if otherValue, isType := value.(time.Duration); isType {
|
||||
return otherValue, nil
|
||||
}
|
||||
otherStringValue, isType := value.(string)
|
||||
parsedValue, err := time.ParseDuration(otherStringValue)
|
||||
if !isType || err != nil {
|
||||
return 0, incorrectTypeForFlagError(name, "duration", value)
|
||||
}
|
||||
return parsedValue, nil
|
||||
}
|
||||
|
||||
// Float64 returns an float64 from the map if it exists otherwise returns 0
|
||||
func (fsm *MapInputSource) Float64(name string) (float64, error) {
|
||||
otherGenericValue, exists := fsm.valueMap[name]
|
||||
if exists {
|
||||
otherValue, isType := otherGenericValue.(float64)
|
||||
if !isType {
|
||||
return 0, incorrectTypeForFlagError(name, "float64", otherGenericValue)
|
||||
}
|
||||
return otherValue, nil
|
||||
}
|
||||
nestedGenericValue, exists := nestedVal(name, fsm.valueMap)
|
||||
if exists {
|
||||
otherValue, isType := nestedGenericValue.(float64)
|
||||
if !isType {
|
||||
return 0, incorrectTypeForFlagError(name, "float64", nestedGenericValue)
|
||||
}
|
||||
return otherValue, nil
|
||||
}
|
||||
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
// String returns a string from the map if it exists otherwise returns an empty string
|
||||
func (fsm *MapInputSource) String(name string) (string, error) {
|
||||
otherGenericValue, exists := fsm.valueMap[name]
|
||||
if exists {
|
||||
otherValue, isType := otherGenericValue.(string)
|
||||
if !isType {
|
||||
return "", incorrectTypeForFlagError(name, "string", otherGenericValue)
|
||||
}
|
||||
return otherValue, nil
|
||||
}
|
||||
nestedGenericValue, exists := nestedVal(name, fsm.valueMap)
|
||||
if exists {
|
||||
otherValue, isType := nestedGenericValue.(string)
|
||||
if !isType {
|
||||
return "", incorrectTypeForFlagError(name, "string", nestedGenericValue)
|
||||
}
|
||||
return otherValue, nil
|
||||
}
|
||||
|
||||
return "", nil
|
||||
}
|
||||
|
||||
// StringSlice returns an []string from the map if it exists otherwise returns nil
|
||||
func (fsm *MapInputSource) StringSlice(name string) ([]string, error) {
|
||||
otherGenericValue, exists := fsm.valueMap[name]
|
||||
if !exists {
|
||||
otherGenericValue, exists = nestedVal(name, fsm.valueMap)
|
||||
if !exists {
|
||||
return nil, nil
|
||||
}
|
||||
}
|
||||
|
||||
otherValue, isType := otherGenericValue.([]interface{})
|
||||
if !isType {
|
||||
return nil, incorrectTypeForFlagError(name, "[]interface{}", otherGenericValue)
|
||||
}
|
||||
|
||||
var stringSlice = make([]string, 0, len(otherValue))
|
||||
for i, v := range otherValue {
|
||||
stringValue, isType := v.(string)
|
||||
|
||||
if !isType {
|
||||
return nil, incorrectTypeForFlagError(fmt.Sprintf("%s[%d]", name, i), "string", v)
|
||||
}
|
||||
|
||||
stringSlice = append(stringSlice, stringValue)
|
||||
}
|
||||
|
||||
return stringSlice, nil
|
||||
}
|
||||
|
||||
// IntSlice returns an []int from the map if it exists otherwise returns nil
|
||||
func (fsm *MapInputSource) IntSlice(name string) ([]int, error) {
|
||||
otherGenericValue, exists := fsm.valueMap[name]
|
||||
if !exists {
|
||||
otherGenericValue, exists = nestedVal(name, fsm.valueMap)
|
||||
if !exists {
|
||||
return nil, nil
|
||||
}
|
||||
}
|
||||
|
||||
otherValue, isType := otherGenericValue.([]interface{})
|
||||
if !isType {
|
||||
return nil, incorrectTypeForFlagError(name, "[]interface{}", otherGenericValue)
|
||||
}
|
||||
|
||||
var intSlice = make([]int, 0, len(otherValue))
|
||||
for i, v := range otherValue {
|
||||
intValue, isType := v.(int)
|
||||
|
||||
if !isType {
|
||||
return nil, incorrectTypeForFlagError(fmt.Sprintf("%s[%d]", name, i), "int", v)
|
||||
}
|
||||
|
||||
intSlice = append(intSlice, intValue)
|
||||
}
|
||||
|
||||
return intSlice, nil
|
||||
}
|
||||
|
||||
// Int64Slice returns an []int64 from the map if it exists otherwise returns nil
|
||||
func (fsm *MapInputSource) Int64Slice(name string) ([]int64, error) {
|
||||
otherGenericValue, exists := fsm.valueMap[name]
|
||||
if !exists {
|
||||
otherGenericValue, exists = nestedVal(name, fsm.valueMap)
|
||||
if !exists {
|
||||
return nil, nil
|
||||
}
|
||||
}
|
||||
|
||||
otherValue, isType := otherGenericValue.([]interface{})
|
||||
if !isType {
|
||||
return nil, incorrectTypeForFlagError(name, "[]interface{}", otherGenericValue)
|
||||
}
|
||||
|
||||
var int64Slice = make([]int64, 0, len(otherValue))
|
||||
for i, v := range otherValue {
|
||||
int64Value, isType := v.(int64)
|
||||
|
||||
if !isType {
|
||||
return nil, incorrectTypeForFlagError(fmt.Sprintf("%s[%d]", name, i), "int", v)
|
||||
}
|
||||
|
||||
int64Slice = append(int64Slice, int64Value)
|
||||
}
|
||||
|
||||
return int64Slice, nil
|
||||
}
|
||||
|
||||
// Generic returns an cli.Generic from the map if it exists otherwise returns nil
|
||||
func (fsm *MapInputSource) Generic(name string) (cli.Generic, error) {
|
||||
otherGenericValue, exists := fsm.valueMap[name]
|
||||
if exists {
|
||||
otherValue, isType := otherGenericValue.(cli.Generic)
|
||||
if !isType {
|
||||
return nil, incorrectTypeForFlagError(name, "cli.Generic", otherGenericValue)
|
||||
}
|
||||
return otherValue, nil
|
||||
}
|
||||
nestedGenericValue, exists := nestedVal(name, fsm.valueMap)
|
||||
if exists {
|
||||
otherValue, isType := nestedGenericValue.(cli.Generic)
|
||||
if !isType {
|
||||
return nil, incorrectTypeForFlagError(name, "cli.Generic", nestedGenericValue)
|
||||
}
|
||||
return otherValue, nil
|
||||
}
|
||||
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// Bool returns an bool from the map otherwise returns false
|
||||
func (fsm *MapInputSource) Bool(name string) (bool, error) {
|
||||
otherGenericValue, exists := fsm.valueMap[name]
|
||||
if exists {
|
||||
otherValue, isType := otherGenericValue.(bool)
|
||||
if !isType {
|
||||
return false, incorrectTypeForFlagError(name, "bool", otherGenericValue)
|
||||
}
|
||||
return otherValue, nil
|
||||
}
|
||||
nestedGenericValue, exists := nestedVal(name, fsm.valueMap)
|
||||
if exists {
|
||||
otherValue, isType := nestedGenericValue.(bool)
|
||||
if !isType {
|
||||
return false, incorrectTypeForFlagError(name, "bool", nestedGenericValue)
|
||||
}
|
||||
return otherValue, nil
|
||||
}
|
||||
|
||||
return false, nil
|
||||
}
|
||||
|
||||
func (fsm *MapInputSource) isSet(name string) bool {
|
||||
if _, exists := fsm.valueMap[name]; exists {
|
||||
return exists
|
||||
}
|
||||
|
||||
_, exists := nestedVal(name, fsm.valueMap)
|
||||
return exists
|
||||
}
|
||||
|
||||
func incorrectTypeForFlagError(name, expectedTypeName string, value interface{}) error {
|
||||
valueType := reflect.TypeOf(value)
|
||||
valueTypeName := ""
|
||||
if valueType != nil {
|
||||
valueTypeName = valueType.Name()
|
||||
}
|
||||
|
||||
return fmt.Errorf("Mismatched type for flag '%s'. Expected '%s' but actual is '%s'", name, expectedTypeName, valueTypeName)
|
||||
}
|
@@ -1,35 +0,0 @@
|
||||
package altsrc
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestMapDuration(t *testing.T) {
|
||||
inputSource := NewMapInputSource(
|
||||
"test",
|
||||
map[interface{}]interface{}{
|
||||
"duration_of_duration_type": time.Minute,
|
||||
"duration_of_string_type": "1m",
|
||||
"duration_of_int_type": 1000,
|
||||
})
|
||||
d, err := inputSource.Duration("duration_of_duration_type")
|
||||
expect(t, time.Minute, d)
|
||||
expect(t, nil, err)
|
||||
d, err = inputSource.Duration("duration_of_string_type")
|
||||
expect(t, time.Minute, d)
|
||||
expect(t, nil, err)
|
||||
_, err = inputSource.Duration("duration_of_int_type")
|
||||
refute(t, nil, err)
|
||||
}
|
||||
|
||||
func TestMapInputSource_Int64Slice(t *testing.T) {
|
||||
inputSource := NewMapInputSource(
|
||||
"test",
|
||||
map[interface{}]interface{}{
|
||||
"test_num": []interface{}{int64(1), int64(2), int64(3)},
|
||||
})
|
||||
d, err := inputSource.Int64Slice("test_num")
|
||||
expect(t, []int64{1, 2, 3}, d)
|
||||
expect(t, nil, err)
|
||||
}
|
@@ -1,305 +0,0 @@
|
||||
package altsrc
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/urfave/cli/v3"
|
||||
)
|
||||
|
||||
func TestCommandTomFileTest(t *testing.T) {
|
||||
app := &cli.App{}
|
||||
set := flag.NewFlagSet("test", 0)
|
||||
_ = ioutil.WriteFile("current.toml", []byte("test = 15"), 0666)
|
||||
defer os.Remove("current.toml")
|
||||
test := []string{"test-cmd", "--load", "current.toml"}
|
||||
_ = set.Parse(test)
|
||||
|
||||
c := cli.NewContext(app, set, nil)
|
||||
|
||||
command := &cli.Command{
|
||||
Name: "test-cmd",
|
||||
Aliases: []string{"tc"},
|
||||
Usage: "this is for testing",
|
||||
Description: "testing",
|
||||
Action: func(c *cli.Context) error {
|
||||
val := c.Int("test")
|
||||
expect(t, val, 15)
|
||||
return nil
|
||||
},
|
||||
Flags: []cli.Flag{
|
||||
NewIntFlag(&cli.IntFlag{Name: "test"}),
|
||||
&cli.StringFlag{Name: "load"}},
|
||||
}
|
||||
command.Before = InitInputSourceWithContext(command.Flags, NewTomlSourceFromFlagFunc("load"))
|
||||
err := command.Run(c, test...)
|
||||
|
||||
expect(t, err, nil)
|
||||
}
|
||||
|
||||
func TestCommandTomlFileTestGlobalEnvVarWins(t *testing.T) {
|
||||
app := &cli.App{}
|
||||
set := flag.NewFlagSet("test", 0)
|
||||
_ = ioutil.WriteFile("current.toml", []byte("test = 15"), 0666)
|
||||
defer os.Remove("current.toml")
|
||||
|
||||
_ = os.Setenv("THE_TEST", "10")
|
||||
defer os.Setenv("THE_TEST", "")
|
||||
test := []string{"test-cmd", "--load", "current.toml"}
|
||||
_ = set.Parse(test)
|
||||
|
||||
c := cli.NewContext(app, set, nil)
|
||||
|
||||
command := &cli.Command{
|
||||
Name: "test-cmd",
|
||||
Aliases: []string{"tc"},
|
||||
Usage: "this is for testing",
|
||||
Description: "testing",
|
||||
Action: func(c *cli.Context) error {
|
||||
val := c.Int("test")
|
||||
expect(t, val, 10)
|
||||
return nil
|
||||
},
|
||||
Flags: []cli.Flag{
|
||||
NewIntFlag(&cli.IntFlag{Name: "test", EnvVars: []string{"THE_TEST"}}),
|
||||
&cli.StringFlag{Name: "load"}},
|
||||
}
|
||||
command.Before = InitInputSourceWithContext(command.Flags, NewTomlSourceFromFlagFunc("load"))
|
||||
|
||||
err := command.Run(c, test...)
|
||||
|
||||
expect(t, err, nil)
|
||||
}
|
||||
|
||||
func TestCommandTomlFileTestGlobalEnvVarWinsNested(t *testing.T) {
|
||||
app := &cli.App{}
|
||||
set := flag.NewFlagSet("test", 0)
|
||||
_ = ioutil.WriteFile("current.toml", []byte("[top]\ntest = 15"), 0666)
|
||||
defer os.Remove("current.toml")
|
||||
|
||||
_ = os.Setenv("THE_TEST", "10")
|
||||
defer os.Setenv("THE_TEST", "")
|
||||
test := []string{"test-cmd", "--load", "current.toml"}
|
||||
_ = set.Parse(test)
|
||||
|
||||
c := cli.NewContext(app, set, nil)
|
||||
|
||||
command := &cli.Command{
|
||||
Name: "test-cmd",
|
||||
Aliases: []string{"tc"},
|
||||
Usage: "this is for testing",
|
||||
Description: "testing",
|
||||
Action: func(c *cli.Context) error {
|
||||
val := c.Int("top.test")
|
||||
expect(t, val, 10)
|
||||
return nil
|
||||
},
|
||||
Flags: []cli.Flag{
|
||||
NewIntFlag(&cli.IntFlag{Name: "top.test", EnvVars: []string{"THE_TEST"}}),
|
||||
&cli.StringFlag{Name: "load"}},
|
||||
}
|
||||
command.Before = InitInputSourceWithContext(command.Flags, NewTomlSourceFromFlagFunc("load"))
|
||||
|
||||
err := command.Run(c, test...)
|
||||
|
||||
expect(t, err, nil)
|
||||
}
|
||||
|
||||
func TestCommandTomlFileTestSpecifiedFlagWins(t *testing.T) {
|
||||
app := &cli.App{}
|
||||
set := flag.NewFlagSet("test", 0)
|
||||
_ = ioutil.WriteFile("current.toml", []byte("test = 15"), 0666)
|
||||
defer os.Remove("current.toml")
|
||||
|
||||
test := []string{"test-cmd", "--load", "current.toml", "--test", "7"}
|
||||
_ = set.Parse(test)
|
||||
|
||||
c := cli.NewContext(app, set, nil)
|
||||
|
||||
command := &cli.Command{
|
||||
Name: "test-cmd",
|
||||
Aliases: []string{"tc"},
|
||||
Usage: "this is for testing",
|
||||
Description: "testing",
|
||||
Action: func(c *cli.Context) error {
|
||||
val := c.Int("test")
|
||||
expect(t, val, 7)
|
||||
return nil
|
||||
},
|
||||
Flags: []cli.Flag{
|
||||
NewIntFlag(&cli.IntFlag{Name: "test"}),
|
||||
&cli.StringFlag{Name: "load"}},
|
||||
}
|
||||
command.Before = InitInputSourceWithContext(command.Flags, NewTomlSourceFromFlagFunc("load"))
|
||||
|
||||
err := command.Run(c, test...)
|
||||
|
||||
expect(t, err, nil)
|
||||
}
|
||||
|
||||
func TestCommandTomlFileTestSpecifiedFlagWinsNested(t *testing.T) {
|
||||
app := &cli.App{}
|
||||
set := flag.NewFlagSet("test", 0)
|
||||
_ = ioutil.WriteFile("current.toml", []byte(`[top]
|
||||
test = 15`), 0666)
|
||||
defer os.Remove("current.toml")
|
||||
|
||||
test := []string{"test-cmd", "--load", "current.toml", "--top.test", "7"}
|
||||
_ = set.Parse(test)
|
||||
|
||||
c := cli.NewContext(app, set, nil)
|
||||
|
||||
command := &cli.Command{
|
||||
Name: "test-cmd",
|
||||
Aliases: []string{"tc"},
|
||||
Usage: "this is for testing",
|
||||
Description: "testing",
|
||||
Action: func(c *cli.Context) error {
|
||||
val := c.Int("top.test")
|
||||
expect(t, val, 7)
|
||||
return nil
|
||||
},
|
||||
Flags: []cli.Flag{
|
||||
NewIntFlag(&cli.IntFlag{Name: "top.test"}),
|
||||
&cli.StringFlag{Name: "load"}},
|
||||
}
|
||||
command.Before = InitInputSourceWithContext(command.Flags, NewTomlSourceFromFlagFunc("load"))
|
||||
|
||||
err := command.Run(c, test...)
|
||||
|
||||
expect(t, err, nil)
|
||||
}
|
||||
|
||||
func TestCommandTomlFileTestDefaultValueFileWins(t *testing.T) {
|
||||
app := &cli.App{}
|
||||
set := flag.NewFlagSet("test", 0)
|
||||
_ = ioutil.WriteFile("current.toml", []byte("test = 15"), 0666)
|
||||
defer os.Remove("current.toml")
|
||||
|
||||
test := []string{"test-cmd", "--load", "current.toml"}
|
||||
_ = set.Parse(test)
|
||||
|
||||
c := cli.NewContext(app, set, nil)
|
||||
|
||||
command := &cli.Command{
|
||||
Name: "test-cmd",
|
||||
Aliases: []string{"tc"},
|
||||
Usage: "this is for testing",
|
||||
Description: "testing",
|
||||
Action: func(c *cli.Context) error {
|
||||
val := c.Int("test")
|
||||
expect(t, val, 15)
|
||||
return nil
|
||||
},
|
||||
Flags: []cli.Flag{
|
||||
NewIntFlag(&cli.IntFlag{Name: "test", Value: 7}),
|
||||
&cli.StringFlag{Name: "load"}},
|
||||
}
|
||||
command.Before = InitInputSourceWithContext(command.Flags, NewTomlSourceFromFlagFunc("load"))
|
||||
|
||||
err := command.Run(c, test...)
|
||||
|
||||
expect(t, err, nil)
|
||||
}
|
||||
|
||||
func TestCommandTomlFileTestDefaultValueFileWinsNested(t *testing.T) {
|
||||
app := &cli.App{}
|
||||
set := flag.NewFlagSet("test", 0)
|
||||
_ = ioutil.WriteFile("current.toml", []byte("[top]\ntest = 15"), 0666)
|
||||
defer os.Remove("current.toml")
|
||||
|
||||
test := []string{"test-cmd", "--load", "current.toml"}
|
||||
_ = set.Parse(test)
|
||||
|
||||
c := cli.NewContext(app, set, nil)
|
||||
|
||||
command := &cli.Command{
|
||||
Name: "test-cmd",
|
||||
Aliases: []string{"tc"},
|
||||
Usage: "this is for testing",
|
||||
Description: "testing",
|
||||
Action: func(c *cli.Context) error {
|
||||
val := c.Int("top.test")
|
||||
expect(t, val, 15)
|
||||
return nil
|
||||
},
|
||||
Flags: []cli.Flag{
|
||||
NewIntFlag(&cli.IntFlag{Name: "top.test", Value: 7}),
|
||||
&cli.StringFlag{Name: "load"}},
|
||||
}
|
||||
command.Before = InitInputSourceWithContext(command.Flags, NewTomlSourceFromFlagFunc("load"))
|
||||
|
||||
err := command.Run(c, test...)
|
||||
|
||||
expect(t, err, nil)
|
||||
}
|
||||
|
||||
func TestCommandTomlFileFlagHasDefaultGlobalEnvTomlSetGlobalEnvWins(t *testing.T) {
|
||||
app := &cli.App{}
|
||||
set := flag.NewFlagSet("test", 0)
|
||||
_ = ioutil.WriteFile("current.toml", []byte("test = 15"), 0666)
|
||||
defer os.Remove("current.toml")
|
||||
|
||||
_ = os.Setenv("THE_TEST", "11")
|
||||
defer os.Setenv("THE_TEST", "")
|
||||
|
||||
test := []string{"test-cmd", "--load", "current.toml"}
|
||||
_ = set.Parse(test)
|
||||
|
||||
c := cli.NewContext(app, set, nil)
|
||||
|
||||
command := &cli.Command{
|
||||
Name: "test-cmd",
|
||||
Aliases: []string{"tc"},
|
||||
Usage: "this is for testing",
|
||||
Description: "testing",
|
||||
Action: func(c *cli.Context) error {
|
||||
val := c.Int("test")
|
||||
expect(t, val, 11)
|
||||
return nil
|
||||
},
|
||||
Flags: []cli.Flag{
|
||||
NewIntFlag(&cli.IntFlag{Name: "test", Value: 7, EnvVars: []string{"THE_TEST"}}),
|
||||
&cli.StringFlag{Name: "load"}},
|
||||
}
|
||||
command.Before = InitInputSourceWithContext(command.Flags, NewTomlSourceFromFlagFunc("load"))
|
||||
err := command.Run(c, test...)
|
||||
|
||||
expect(t, err, nil)
|
||||
}
|
||||
|
||||
func TestCommandTomlFileFlagHasDefaultGlobalEnvTomlSetGlobalEnvWinsNested(t *testing.T) {
|
||||
app := &cli.App{}
|
||||
set := flag.NewFlagSet("test", 0)
|
||||
_ = ioutil.WriteFile("current.toml", []byte("[top]\ntest = 15"), 0666)
|
||||
defer os.Remove("current.toml")
|
||||
|
||||
_ = os.Setenv("THE_TEST", "11")
|
||||
defer os.Setenv("THE_TEST", "")
|
||||
|
||||
test := []string{"test-cmd", "--load", "current.toml"}
|
||||
_ = set.Parse(test)
|
||||
|
||||
c := cli.NewContext(app, set, nil)
|
||||
|
||||
command := &cli.Command{
|
||||
Name: "test-cmd",
|
||||
Aliases: []string{"tc"},
|
||||
Usage: "this is for testing",
|
||||
Description: "testing",
|
||||
Action: func(c *cli.Context) error {
|
||||
val := c.Int("top.test")
|
||||
expect(t, val, 11)
|
||||
return nil
|
||||
},
|
||||
Flags: []cli.Flag{
|
||||
NewIntFlag(&cli.IntFlag{Name: "top.test", Value: 7, EnvVars: []string{"THE_TEST"}}),
|
||||
&cli.StringFlag{Name: "load"}},
|
||||
}
|
||||
command.Before = InitInputSourceWithContext(command.Flags, NewTomlSourceFromFlagFunc("load"))
|
||||
err := command.Run(c, test...)
|
||||
|
||||
expect(t, err, nil)
|
||||
}
|
@@ -1,112 +0,0 @@
|
||||
package altsrc
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"reflect"
|
||||
|
||||
"github.com/BurntSushi/toml"
|
||||
"github.com/urfave/cli/v3"
|
||||
)
|
||||
|
||||
type tomlMap struct {
|
||||
Map map[interface{}]interface{}
|
||||
}
|
||||
|
||||
func unmarshalMap(i interface{}) (ret map[interface{}]interface{}, err error) {
|
||||
ret = make(map[interface{}]interface{})
|
||||
m := i.(map[string]interface{})
|
||||
for key, val := range m {
|
||||
v := reflect.ValueOf(val)
|
||||
switch v.Kind() {
|
||||
case reflect.Bool:
|
||||
ret[key] = val.(bool)
|
||||
case reflect.String:
|
||||
ret[key] = val.(string)
|
||||
case reflect.Int:
|
||||
ret[key] = val.(int)
|
||||
case reflect.Int8:
|
||||
ret[key] = int(val.(int8))
|
||||
case reflect.Int16:
|
||||
ret[key] = int(val.(int16))
|
||||
case reflect.Int32:
|
||||
ret[key] = int(val.(int32))
|
||||
case reflect.Int64:
|
||||
ret[key] = int(val.(int64))
|
||||
case reflect.Uint:
|
||||
ret[key] = int(val.(uint))
|
||||
case reflect.Uint8:
|
||||
ret[key] = int(val.(uint8))
|
||||
case reflect.Uint16:
|
||||
ret[key] = int(val.(uint16))
|
||||
case reflect.Uint32:
|
||||
ret[key] = int(val.(uint32))
|
||||
case reflect.Uint64:
|
||||
ret[key] = int(val.(uint64))
|
||||
case reflect.Float32:
|
||||
ret[key] = float64(val.(float32))
|
||||
case reflect.Float64:
|
||||
ret[key] = val.(float64)
|
||||
case reflect.Map:
|
||||
if tmp, err := unmarshalMap(val); err == nil {
|
||||
ret[key] = tmp
|
||||
} else {
|
||||
return nil, err
|
||||
}
|
||||
case reflect.Array, reflect.Slice:
|
||||
ret[key] = val.([]interface{})
|
||||
default:
|
||||
return nil, fmt.Errorf("Unsupported: type = %#v", v.Kind())
|
||||
}
|
||||
}
|
||||
return ret, nil
|
||||
}
|
||||
|
||||
func (tm *tomlMap) UnmarshalTOML(i interface{}) error {
|
||||
if tmp, err := unmarshalMap(i); err == nil {
|
||||
tm.Map = tmp
|
||||
} else {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type tomlSourceContext struct {
|
||||
FilePath string
|
||||
}
|
||||
|
||||
// NewTomlSourceFromFile creates a new TOML InputSourceContext from a filepath.
|
||||
func NewTomlSourceFromFile(file string) (InputSourceContext, error) {
|
||||
tsc := &tomlSourceContext{FilePath: file}
|
||||
var results tomlMap = tomlMap{}
|
||||
if err := readCommandToml(tsc.FilePath, &results); err != nil {
|
||||
return nil, fmt.Errorf("Unable to load TOML file '%s': inner error: \n'%v'", tsc.FilePath, err.Error())
|
||||
}
|
||||
return &MapInputSource{file: file, valueMap: results.Map}, nil
|
||||
}
|
||||
|
||||
// NewTomlSourceFromFlagFunc creates a new TOML InputSourceContext from a provided flag name and source context.
|
||||
func NewTomlSourceFromFlagFunc(flagFileName string) func(cCtx *cli.Context) (InputSourceContext, error) {
|
||||
return func(cCtx *cli.Context) (InputSourceContext, error) {
|
||||
if cCtx.IsSet(flagFileName) {
|
||||
filePath := cCtx.String(flagFileName)
|
||||
return NewTomlSourceFromFile(filePath)
|
||||
}
|
||||
|
||||
return defaultInputSource()
|
||||
}
|
||||
}
|
||||
|
||||
func readCommandToml(filePath string, container interface{}) (err error) {
|
||||
b, err := loadDataFrom(filePath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = toml.Unmarshal(b, container)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = nil
|
||||
return
|
||||
}
|
@@ -1,308 +0,0 @@
|
||||
package altsrc
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/urfave/cli/v3"
|
||||
)
|
||||
|
||||
func TestCommandYamlFileTest(t *testing.T) {
|
||||
app := &cli.App{}
|
||||
set := flag.NewFlagSet("test", 0)
|
||||
_ = ioutil.WriteFile("current.yaml", []byte("test: 15"), 0666)
|
||||
defer os.Remove("current.yaml")
|
||||
test := []string{"test-cmd", "--load", "current.yaml"}
|
||||
_ = set.Parse(test)
|
||||
|
||||
c := cli.NewContext(app, set, nil)
|
||||
|
||||
command := &cli.Command{
|
||||
Name: "test-cmd",
|
||||
Aliases: []string{"tc"},
|
||||
Usage: "this is for testing",
|
||||
Description: "testing",
|
||||
Action: func(c *cli.Context) error {
|
||||
val := c.Int("test")
|
||||
expect(t, val, 15)
|
||||
return nil
|
||||
},
|
||||
Flags: []cli.Flag{
|
||||
NewIntFlag(&cli.IntFlag{Name: "test"}),
|
||||
&cli.StringFlag{Name: "load"}},
|
||||
}
|
||||
command.Before = InitInputSourceWithContext(command.Flags, NewYamlSourceFromFlagFunc("load"))
|
||||
err := command.Run(c, test...)
|
||||
|
||||
expect(t, err, nil)
|
||||
}
|
||||
|
||||
func TestCommandYamlFileTestGlobalEnvVarWins(t *testing.T) {
|
||||
app := &cli.App{}
|
||||
set := flag.NewFlagSet("test", 0)
|
||||
_ = ioutil.WriteFile("current.yaml", []byte("test: 15"), 0666)
|
||||
defer os.Remove("current.yaml")
|
||||
|
||||
_ = os.Setenv("THE_TEST", "10")
|
||||
defer os.Setenv("THE_TEST", "")
|
||||
test := []string{"test-cmd", "--load", "current.yaml"}
|
||||
_ = set.Parse(test)
|
||||
|
||||
c := cli.NewContext(app, set, nil)
|
||||
|
||||
command := &cli.Command{
|
||||
Name: "test-cmd",
|
||||
Aliases: []string{"tc"},
|
||||
Usage: "this is for testing",
|
||||
Description: "testing",
|
||||
Action: func(c *cli.Context) error {
|
||||
val := c.Int("test")
|
||||
expect(t, val, 10)
|
||||
return nil
|
||||
},
|
||||
Flags: []cli.Flag{
|
||||
NewIntFlag(&cli.IntFlag{Name: "test", EnvVars: []string{"THE_TEST"}}),
|
||||
&cli.StringFlag{Name: "load"}},
|
||||
}
|
||||
command.Before = InitInputSourceWithContext(command.Flags, NewYamlSourceFromFlagFunc("load"))
|
||||
|
||||
err := command.Run(c, test...)
|
||||
|
||||
expect(t, err, nil)
|
||||
}
|
||||
|
||||
func TestCommandYamlFileTestGlobalEnvVarWinsNested(t *testing.T) {
|
||||
app := &cli.App{}
|
||||
set := flag.NewFlagSet("test", 0)
|
||||
_ = ioutil.WriteFile("current.yaml", []byte(`top:
|
||||
test: 15`), 0666)
|
||||
defer os.Remove("current.yaml")
|
||||
|
||||
_ = os.Setenv("THE_TEST", "10")
|
||||
defer os.Setenv("THE_TEST", "")
|
||||
test := []string{"test-cmd", "--load", "current.yaml"}
|
||||
_ = set.Parse(test)
|
||||
|
||||
c := cli.NewContext(app, set, nil)
|
||||
|
||||
command := &cli.Command{
|
||||
Name: "test-cmd",
|
||||
Aliases: []string{"tc"},
|
||||
Usage: "this is for testing",
|
||||
Description: "testing",
|
||||
Action: func(c *cli.Context) error {
|
||||
val := c.Int("top.test")
|
||||
expect(t, val, 10)
|
||||
return nil
|
||||
},
|
||||
Flags: []cli.Flag{
|
||||
NewIntFlag(&cli.IntFlag{Name: "top.test", EnvVars: []string{"THE_TEST"}}),
|
||||
&cli.StringFlag{Name: "load"}},
|
||||
}
|
||||
command.Before = InitInputSourceWithContext(command.Flags, NewYamlSourceFromFlagFunc("load"))
|
||||
|
||||
err := command.Run(c, test...)
|
||||
|
||||
expect(t, err, nil)
|
||||
}
|
||||
|
||||
func TestCommandYamlFileTestSpecifiedFlagWins(t *testing.T) {
|
||||
app := &cli.App{}
|
||||
set := flag.NewFlagSet("test", 0)
|
||||
_ = ioutil.WriteFile("current.yaml", []byte("test: 15"), 0666)
|
||||
defer os.Remove("current.yaml")
|
||||
|
||||
test := []string{"test-cmd", "--load", "current.yaml", "--test", "7"}
|
||||
_ = set.Parse(test)
|
||||
|
||||
c := cli.NewContext(app, set, nil)
|
||||
|
||||
command := &cli.Command{
|
||||
Name: "test-cmd",
|
||||
Aliases: []string{"tc"},
|
||||
Usage: "this is for testing",
|
||||
Description: "testing",
|
||||
Action: func(c *cli.Context) error {
|
||||
val := c.Int("test")
|
||||
expect(t, val, 7)
|
||||
return nil
|
||||
},
|
||||
Flags: []cli.Flag{
|
||||
NewIntFlag(&cli.IntFlag{Name: "test"}),
|
||||
&cli.StringFlag{Name: "load"}},
|
||||
}
|
||||
command.Before = InitInputSourceWithContext(command.Flags, NewYamlSourceFromFlagFunc("load"))
|
||||
|
||||
err := command.Run(c, test...)
|
||||
|
||||
expect(t, err, nil)
|
||||
}
|
||||
|
||||
func TestCommandYamlFileTestSpecifiedFlagWinsNested(t *testing.T) {
|
||||
app := &cli.App{}
|
||||
set := flag.NewFlagSet("test", 0)
|
||||
_ = ioutil.WriteFile("current.yaml", []byte(`top:
|
||||
test: 15`), 0666)
|
||||
defer os.Remove("current.yaml")
|
||||
|
||||
test := []string{"test-cmd", "--load", "current.yaml", "--top.test", "7"}
|
||||
_ = set.Parse(test)
|
||||
|
||||
c := cli.NewContext(app, set, nil)
|
||||
|
||||
command := &cli.Command{
|
||||
Name: "test-cmd",
|
||||
Aliases: []string{"tc"},
|
||||
Usage: "this is for testing",
|
||||
Description: "testing",
|
||||
Action: func(c *cli.Context) error {
|
||||
val := c.Int("top.test")
|
||||
expect(t, val, 7)
|
||||
return nil
|
||||
},
|
||||
Flags: []cli.Flag{
|
||||
NewIntFlag(&cli.IntFlag{Name: "top.test"}),
|
||||
&cli.StringFlag{Name: "load"}},
|
||||
}
|
||||
command.Before = InitInputSourceWithContext(command.Flags, NewYamlSourceFromFlagFunc("load"))
|
||||
|
||||
err := command.Run(c, test...)
|
||||
|
||||
expect(t, err, nil)
|
||||
}
|
||||
|
||||
func TestCommandYamlFileTestDefaultValueFileWins(t *testing.T) {
|
||||
app := &cli.App{}
|
||||
set := flag.NewFlagSet("test", 0)
|
||||
_ = ioutil.WriteFile("current.yaml", []byte("test: 15"), 0666)
|
||||
defer os.Remove("current.yaml")
|
||||
|
||||
test := []string{"test-cmd", "--load", "current.yaml"}
|
||||
_ = set.Parse(test)
|
||||
|
||||
c := cli.NewContext(app, set, nil)
|
||||
|
||||
command := &cli.Command{
|
||||
Name: "test-cmd",
|
||||
Aliases: []string{"tc"},
|
||||
Usage: "this is for testing",
|
||||
Description: "testing",
|
||||
Action: func(c *cli.Context) error {
|
||||
val := c.Int("test")
|
||||
expect(t, val, 15)
|
||||
return nil
|
||||
},
|
||||
Flags: []cli.Flag{
|
||||
NewIntFlag(&cli.IntFlag{Name: "test", Value: 7}),
|
||||
&cli.StringFlag{Name: "load"}},
|
||||
}
|
||||
command.Before = InitInputSourceWithContext(command.Flags, NewYamlSourceFromFlagFunc("load"))
|
||||
|
||||
err := command.Run(c, test...)
|
||||
|
||||
expect(t, err, nil)
|
||||
}
|
||||
|
||||
func TestCommandYamlFileTestDefaultValueFileWinsNested(t *testing.T) {
|
||||
app := &cli.App{}
|
||||
set := flag.NewFlagSet("test", 0)
|
||||
_ = ioutil.WriteFile("current.yaml", []byte(`top:
|
||||
test: 15`), 0666)
|
||||
defer os.Remove("current.yaml")
|
||||
|
||||
test := []string{"test-cmd", "--load", "current.yaml"}
|
||||
_ = set.Parse(test)
|
||||
|
||||
c := cli.NewContext(app, set, nil)
|
||||
|
||||
command := &cli.Command{
|
||||
Name: "test-cmd",
|
||||
Aliases: []string{"tc"},
|
||||
Usage: "this is for testing",
|
||||
Description: "testing",
|
||||
Action: func(c *cli.Context) error {
|
||||
val := c.Int("top.test")
|
||||
expect(t, val, 15)
|
||||
return nil
|
||||
},
|
||||
Flags: []cli.Flag{
|
||||
NewIntFlag(&cli.IntFlag{Name: "top.test", Value: 7}),
|
||||
&cli.StringFlag{Name: "load"}},
|
||||
}
|
||||
command.Before = InitInputSourceWithContext(command.Flags, NewYamlSourceFromFlagFunc("load"))
|
||||
|
||||
err := command.Run(c, test...)
|
||||
|
||||
expect(t, err, nil)
|
||||
}
|
||||
|
||||
func TestCommandYamlFileFlagHasDefaultGlobalEnvYamlSetGlobalEnvWins(t *testing.T) {
|
||||
app := &cli.App{}
|
||||
set := flag.NewFlagSet("test", 0)
|
||||
_ = ioutil.WriteFile("current.yaml", []byte("test: 15"), 0666)
|
||||
defer os.Remove("current.yaml")
|
||||
|
||||
_ = os.Setenv("THE_TEST", "11")
|
||||
defer os.Setenv("THE_TEST", "")
|
||||
|
||||
test := []string{"test-cmd", "--load", "current.yaml"}
|
||||
_ = set.Parse(test)
|
||||
|
||||
c := cli.NewContext(app, set, nil)
|
||||
|
||||
command := &cli.Command{
|
||||
Name: "test-cmd",
|
||||
Aliases: []string{"tc"},
|
||||
Usage: "this is for testing",
|
||||
Description: "testing",
|
||||
Action: func(c *cli.Context) error {
|
||||
val := c.Int("test")
|
||||
expect(t, val, 11)
|
||||
return nil
|
||||
},
|
||||
Flags: []cli.Flag{
|
||||
NewIntFlag(&cli.IntFlag{Name: "test", Value: 7, EnvVars: []string{"THE_TEST"}}),
|
||||
&cli.StringFlag{Name: "load"}},
|
||||
}
|
||||
command.Before = InitInputSourceWithContext(command.Flags, NewYamlSourceFromFlagFunc("load"))
|
||||
err := command.Run(c, test...)
|
||||
|
||||
expect(t, err, nil)
|
||||
}
|
||||
|
||||
func TestCommandYamlFileFlagHasDefaultGlobalEnvYamlSetGlobalEnvWinsNested(t *testing.T) {
|
||||
app := &cli.App{}
|
||||
set := flag.NewFlagSet("test", 0)
|
||||
_ = ioutil.WriteFile("current.yaml", []byte(`top:
|
||||
test: 15`), 0666)
|
||||
defer os.Remove("current.yaml")
|
||||
|
||||
_ = os.Setenv("THE_TEST", "11")
|
||||
defer os.Setenv("THE_TEST", "")
|
||||
|
||||
test := []string{"test-cmd", "--load", "current.yaml"}
|
||||
_ = set.Parse(test)
|
||||
|
||||
c := cli.NewContext(app, set, nil)
|
||||
|
||||
command := &cli.Command{
|
||||
Name: "test-cmd",
|
||||
Aliases: []string{"tc"},
|
||||
Usage: "this is for testing",
|
||||
Description: "testing",
|
||||
Action: func(c *cli.Context) error {
|
||||
val := c.Int("top.test")
|
||||
expect(t, val, 11)
|
||||
return nil
|
||||
},
|
||||
Flags: []cli.Flag{
|
||||
NewIntFlag(&cli.IntFlag{Name: "top.test", Value: 7, EnvVars: []string{"THE_TEST"}}),
|
||||
&cli.StringFlag{Name: "load"}},
|
||||
}
|
||||
command.Before = InitInputSourceWithContext(command.Flags, NewYamlSourceFromFlagFunc("load"))
|
||||
err := command.Run(c, test...)
|
||||
|
||||
expect(t, err, nil)
|
||||
}
|
@@ -1,89 +0,0 @@
|
||||
package altsrc
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"runtime"
|
||||
"strings"
|
||||
|
||||
"github.com/urfave/cli/v3"
|
||||
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
type yamlSourceContext struct {
|
||||
FilePath string
|
||||
}
|
||||
|
||||
// NewYamlSourceFromFile creates a new Yaml InputSourceContext from a filepath.
|
||||
func NewYamlSourceFromFile(file string) (InputSourceContext, error) {
|
||||
ysc := &yamlSourceContext{FilePath: file}
|
||||
var results map[interface{}]interface{}
|
||||
err := readCommandYaml(ysc.FilePath, &results)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Unable to load Yaml file '%s': inner error: \n'%v'", ysc.FilePath, err.Error())
|
||||
}
|
||||
|
||||
return &MapInputSource{file: file, valueMap: results}, nil
|
||||
}
|
||||
|
||||
// NewYamlSourceFromFlagFunc creates a new Yaml InputSourceContext from a provided flag name and source context.
|
||||
func NewYamlSourceFromFlagFunc(flagFileName string) func(cCtx *cli.Context) (InputSourceContext, error) {
|
||||
return func(cCtx *cli.Context) (InputSourceContext, error) {
|
||||
if filePath := cCtx.String(flagFileName); filePath != "" {
|
||||
return NewYamlSourceFromFile(filePath)
|
||||
}
|
||||
return defaultInputSource()
|
||||
}
|
||||
}
|
||||
|
||||
func readCommandYaml(filePath string, container interface{}) (err error) {
|
||||
b, err := loadDataFrom(filePath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = yaml.Unmarshal(b, container)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = nil
|
||||
return
|
||||
}
|
||||
|
||||
func loadDataFrom(filePath string) ([]byte, error) {
|
||||
u, err := url.Parse(filePath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if u.Host != "" { // i have a host, now do i support the scheme?
|
||||
switch u.Scheme {
|
||||
case "http", "https":
|
||||
res, err := http.Get(filePath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ioutil.ReadAll(res.Body)
|
||||
default:
|
||||
return nil, fmt.Errorf("scheme of %s is unsupported", filePath)
|
||||
}
|
||||
} else if u.Path != "" { // i dont have a host, but I have a path. I am a local file.
|
||||
if _, notFoundFileErr := os.Stat(filePath); notFoundFileErr != nil {
|
||||
return nil, fmt.Errorf("Cannot read from file: '%s' because it does not exist.", filePath)
|
||||
}
|
||||
return ioutil.ReadFile(filePath)
|
||||
} else if runtime.GOOS == "windows" && strings.Contains(u.String(), "\\") {
|
||||
// on Windows systems u.Path is always empty, so we need to check the string directly.
|
||||
if _, notFoundFileErr := os.Stat(filePath); notFoundFileErr != nil {
|
||||
return nil, fmt.Errorf("Cannot read from file: '%s' because it does not exist.", filePath)
|
||||
}
|
||||
return ioutil.ReadFile(filePath)
|
||||
}
|
||||
|
||||
return nil, fmt.Errorf("unable to determine how to load from path %s", filePath)
|
||||
}
|
@@ -1,87 +0,0 @@
|
||||
package altsrc_test
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/urfave/cli/v3"
|
||||
"github.com/urfave/cli/v3/altsrc"
|
||||
)
|
||||
|
||||
func ExampleApp_Run_yamlFileLoaderDuration() {
|
||||
execServe := func(c *cli.Context) error {
|
||||
keepaliveInterval := c.Duration("keepalive-interval")
|
||||
fmt.Printf("keepalive %s\n", keepaliveInterval)
|
||||
return nil
|
||||
}
|
||||
|
||||
fileExists := func(filename string) bool {
|
||||
stat, _ := os.Stat(filename)
|
||||
return stat != nil
|
||||
}
|
||||
|
||||
// initConfigFileInputSource is like altsrc.InitInputSourceWithContext and altsrc.NewYamlSourceFromFlagFunc, but checks
|
||||
// if the config flag is exists and only loads it if it does. If the flag is set and the file exists, it fails.
|
||||
initConfigFileInputSource := func(configFlag string, flags []cli.Flag) cli.BeforeFunc {
|
||||
return func(context *cli.Context) error {
|
||||
configFile := context.String(configFlag)
|
||||
if context.IsSet(configFlag) && !fileExists(configFile) {
|
||||
return fmt.Errorf("config file %s does not exist", configFile)
|
||||
} else if !context.IsSet(configFlag) && !fileExists(configFile) {
|
||||
return nil
|
||||
}
|
||||
inputSource, err := altsrc.NewYamlSourceFromFile(configFile)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return altsrc.ApplyInputSourceValues(context, inputSource, flags)
|
||||
}
|
||||
}
|
||||
|
||||
flagsServe := []cli.Flag{
|
||||
&cli.StringFlag{
|
||||
Name: "config",
|
||||
Aliases: []string{"c"},
|
||||
EnvVars: []string{"CONFIG_FILE"},
|
||||
Value: "../testdata/empty.yml",
|
||||
DefaultText: "../testdata/empty.yml",
|
||||
Usage: "config file",
|
||||
},
|
||||
altsrc.NewDurationFlag(
|
||||
&cli.DurationFlag{
|
||||
Name: "keepalive-interval",
|
||||
Aliases: []string{"k"},
|
||||
EnvVars: []string{"KEEPALIVE_INTERVAL"},
|
||||
Value: 45 * time.Second,
|
||||
Usage: "interval of keepalive messages",
|
||||
},
|
||||
),
|
||||
}
|
||||
|
||||
cmdServe := &cli.Command{
|
||||
Name: "serve",
|
||||
Usage: "Run the server",
|
||||
UsageText: "serve [OPTIONS..]",
|
||||
Action: execServe,
|
||||
Flags: flagsServe,
|
||||
Before: initConfigFileInputSource("config", flagsServe),
|
||||
}
|
||||
|
||||
c := &cli.App{
|
||||
Name: "cmd",
|
||||
HideVersion: true,
|
||||
UseShortOptionHandling: true,
|
||||
Commands: []*cli.Command{
|
||||
cmdServe,
|
||||
},
|
||||
}
|
||||
|
||||
if err := c.Run([]string{"cmd", "serve", "--config", "../testdata/empty.yml"}); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
// Output:
|
||||
// keepalive 45s
|
||||
}
|
24
app.go
24
app.go
@@ -9,7 +9,6 @@ import (
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const suggestDidYouMeanTemplate = "Did you mean %q?"
|
||||
@@ -81,8 +80,6 @@ type App struct {
|
||||
OnUsageError OnUsageErrorFunc
|
||||
// Execute this function when an invalid flag is accessed from the context
|
||||
InvalidFlagAccessHandler InvalidFlagAccessFunc
|
||||
// Compilation date
|
||||
Compiled time.Time
|
||||
// List of all authors who contributed
|
||||
Authors []*Author
|
||||
// Copyright of the binary if any
|
||||
@@ -128,16 +125,6 @@ type SuggestFlagFunc func(flags []Flag, provided string, hideHelp bool) string
|
||||
|
||||
type SuggestCommandFunc func(commands []*Command, provided string) string
|
||||
|
||||
// Tries to find out when this binary was compiled.
|
||||
// Returns the current time if it fails to find it.
|
||||
func compileTime() time.Time {
|
||||
info, err := os.Stat(os.Args[0])
|
||||
if err != nil {
|
||||
return time.Now()
|
||||
}
|
||||
return info.ModTime()
|
||||
}
|
||||
|
||||
// NewApp creates a new cli Application with some reasonable defaults for Name,
|
||||
// Usage, Version and Action.
|
||||
func NewApp() *App {
|
||||
@@ -147,7 +134,6 @@ func NewApp() *App {
|
||||
UsageText: "",
|
||||
BashComplete: DefaultAppComplete,
|
||||
Action: helpCommand.Action,
|
||||
Compiled: compileTime(),
|
||||
Reader: os.Stdin,
|
||||
Writer: os.Stdout,
|
||||
ErrWriter: os.Stderr,
|
||||
@@ -188,10 +174,6 @@ func (a *App) Setup() {
|
||||
a.Action = helpCommand.Action
|
||||
}
|
||||
|
||||
if a.Compiled == (time.Time{}) {
|
||||
a.Compiled = compileTime()
|
||||
}
|
||||
|
||||
if a.Reader == nil {
|
||||
a.Reader = os.Stdin
|
||||
}
|
||||
@@ -209,7 +191,7 @@ func (a *App) Setup() {
|
||||
flag.VisitAll(func(f *flag.Flag) {
|
||||
// skip test flags
|
||||
if !strings.HasPrefix(f.Name, ignoreFlagPrefix) {
|
||||
a.Flags = append(a.Flags, &extFlag{f})
|
||||
a.Flags = append(a.Flags, &extFlag{f: f})
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -292,10 +274,6 @@ func (a *App) newRootCommand() *Command {
|
||||
}
|
||||
}
|
||||
|
||||
func (a *App) newFlagSet() (*flag.FlagSet, error) {
|
||||
return flagSet(a.Name, a.Flags)
|
||||
}
|
||||
|
||||
func (a *App) useShortOptionHandling() bool {
|
||||
return a.UseShortOptionHandling
|
||||
}
|
||||
|
@@ -26,4 +26,3 @@ show-cover:
|
||||
.PHONY: run
|
||||
run: build
|
||||
./urfave-cli-genflags
|
||||
./urfave-cli-genflags -f altsrc/flag-spec.yaml -o altsrc/flag_generated.go -p altsrc -a
|
||||
|
3
go.mod
3
go.mod
@@ -10,6 +10,9 @@ require (
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/davecgh/go-spew v1.1.1 // indirect
|
||||
github.com/pmezard/go-difflib v1.0.0 // indirect
|
||||
github.com/russross/blackfriday/v2 v2.1.0 // indirect
|
||||
github.com/stretchr/testify v1.8.1 // indirect
|
||||
golang.org/x/text v0.3.7 // indirect
|
||||
)
|
||||
|
13
go.sum
13
go.sum
@@ -2,13 +2,26 @@ github.com/BurntSushi/toml v1.1.0 h1:ksErzDEI1khOiGPgpwuI7x2ebx/uXQNw7xJpn9Eq1+I
|
||||
github.com/BurntSushi/toml v1.1.0/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ=
|
||||
github.com/cpuguy83/go-md2man/v2 v2.0.2 h1:p1EgwI/C7NhT0JmVkwCD2ZBK8j4aeHQX2pMHHBfMQ6w=
|
||||
github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk=
|
||||
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
||||
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
|
||||
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
||||
github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk=
|
||||
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
|
||||
github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673 h1:bAn7/zixMGCfxrRTfdpNzjtPYqr8smhKouy9mxVdGPU=
|
||||
github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673/go.mod h1:N3UwUGtsrSj3ccvlPHLoLsHnpR27oXr4ZE984MbSER8=
|
||||
golang.org/x/text v0.3.7 h1:olpwvP2KacW1ZWvsR7uQhoyTYvKAupfQrRGBFM352Gk=
|
||||
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
|
@@ -292,8 +292,6 @@ type App struct {
|
||||
OnUsageError OnUsageErrorFunc
|
||||
// Execute this function when an invalid flag is accessed from the context
|
||||
InvalidFlagAccessHandler InvalidFlagAccessFunc
|
||||
// Compilation date
|
||||
Compiled time.Time
|
||||
// List of all authors who contributed
|
||||
Authors []*Author
|
||||
// Copyright of the binary if any
|
||||
@@ -2313,358 +2311,3 @@ type VisibleFlagCategory interface {
|
||||
}
|
||||
VisibleFlagCategory is a category containing flags.
|
||||
|
||||
package altsrc // import "github.com/urfave/cli/v3/altsrc"
|
||||
|
||||
|
||||
FUNCTIONS
|
||||
|
||||
func ApplyInputSourceValues(cCtx *cli.Context, inputSourceContext InputSourceContext, flags []cli.Flag) error
|
||||
ApplyInputSourceValues iterates over all provided flags and executes
|
||||
ApplyInputSourceValue on flags implementing the FlagInputSourceExtension
|
||||
interface to initialize these flags to an alternate input source.
|
||||
|
||||
func InitInputSource(flags []cli.Flag, createInputSource func() (InputSourceContext, error)) cli.BeforeFunc
|
||||
InitInputSource is used to to setup an InputSourceContext on a cli.Command
|
||||
Before method. It will create a new input source based on the func provided.
|
||||
If there is no error it will then apply the new input source to any flags
|
||||
that are supported by the input source
|
||||
|
||||
func InitInputSourceWithContext(flags []cli.Flag, createInputSource func(cCtx *cli.Context) (InputSourceContext, error)) cli.BeforeFunc
|
||||
InitInputSourceWithContext is used to to setup an InputSourceContext on
|
||||
a cli.Command Before method. It will create a new input source based on
|
||||
the func provided with potentially using existing cli.Context values to
|
||||
initialize itself. If there is no error it will then apply the new input
|
||||
source to any flags that are supported by the input source
|
||||
|
||||
func NewJSONSourceFromFlagFunc(flag string) func(c *cli.Context) (InputSourceContext, error)
|
||||
NewJSONSourceFromFlagFunc returns a func that takes a cli.Context and
|
||||
returns an InputSourceContext suitable for retrieving config variables from
|
||||
a file containing JSON data with the file name defined by the given flag.
|
||||
|
||||
func NewTomlSourceFromFlagFunc(flagFileName string) func(cCtx *cli.Context) (InputSourceContext, error)
|
||||
NewTomlSourceFromFlagFunc creates a new TOML InputSourceContext from a
|
||||
provided flag name and source context.
|
||||
|
||||
func NewYamlSourceFromFlagFunc(flagFileName string) func(cCtx *cli.Context) (InputSourceContext, error)
|
||||
NewYamlSourceFromFlagFunc creates a new Yaml InputSourceContext from a
|
||||
provided flag name and source context.
|
||||
|
||||
|
||||
TYPES
|
||||
|
||||
type BoolFlag struct {
|
||||
*cli.BoolFlag
|
||||
// Has unexported fields.
|
||||
}
|
||||
BoolFlag is the flag type that wraps cli.BoolFlag to allow for other values
|
||||
to be specified
|
||||
|
||||
func NewBoolFlag(fl *cli.BoolFlag) *BoolFlag
|
||||
NewBoolFlag creates a new BoolFlag
|
||||
|
||||
func (f *BoolFlag) Apply(set *flag.FlagSet) error
|
||||
Apply saves the flagSet for later usage calls, then calls the wrapped
|
||||
BoolFlag.Apply
|
||||
|
||||
func (f *BoolFlag) ApplyInputSourceValue(cCtx *cli.Context, isc InputSourceContext) error
|
||||
ApplyInputSourceValue applies a Bool value to the flagSet if required
|
||||
|
||||
type DurationFlag struct {
|
||||
*cli.DurationFlag
|
||||
// Has unexported fields.
|
||||
}
|
||||
DurationFlag is the flag type that wraps cli.DurationFlag to allow for other
|
||||
values to be specified
|
||||
|
||||
func NewDurationFlag(fl *cli.DurationFlag) *DurationFlag
|
||||
NewDurationFlag creates a new DurationFlag
|
||||
|
||||
func (f *DurationFlag) Apply(set *flag.FlagSet) error
|
||||
Apply saves the flagSet for later usage calls, then calls the wrapped
|
||||
DurationFlag.Apply
|
||||
|
||||
func (f *DurationFlag) ApplyInputSourceValue(cCtx *cli.Context, isc InputSourceContext) error
|
||||
ApplyInputSourceValue applies a Duration value to the flagSet if required
|
||||
|
||||
type FlagInputSourceExtension interface {
|
||||
cli.Flag
|
||||
ApplyInputSourceValue(cCtx *cli.Context, isc InputSourceContext) error
|
||||
}
|
||||
FlagInputSourceExtension is an extension interface of cli.Flag that allows a
|
||||
value to be set on the existing parsed flags.
|
||||
|
||||
type Float64Flag struct {
|
||||
*cli.Float64Flag
|
||||
// Has unexported fields.
|
||||
}
|
||||
Float64Flag is the flag type that wraps cli.Float64Flag to allow for other
|
||||
values to be specified
|
||||
|
||||
func NewFloat64Flag(fl *cli.Float64Flag) *Float64Flag
|
||||
NewFloat64Flag creates a new Float64Flag
|
||||
|
||||
func (f *Float64Flag) Apply(set *flag.FlagSet) error
|
||||
Apply saves the flagSet for later usage calls, then calls the wrapped
|
||||
Float64Flag.Apply
|
||||
|
||||
func (f *Float64Flag) ApplyInputSourceValue(cCtx *cli.Context, isc InputSourceContext) error
|
||||
ApplyInputSourceValue applies a Float64 value to the flagSet if required
|
||||
|
||||
type Float64SliceFlag struct {
|
||||
*cli.Float64SliceFlag
|
||||
// Has unexported fields.
|
||||
}
|
||||
Float64SliceFlag is the flag type that wraps cli.Float64SliceFlag to allow
|
||||
for other values to be specified
|
||||
|
||||
func NewFloat64SliceFlag(fl *cli.Float64SliceFlag) *Float64SliceFlag
|
||||
NewFloat64SliceFlag creates a new Float64SliceFlag
|
||||
|
||||
func (f *Float64SliceFlag) Apply(set *flag.FlagSet) error
|
||||
Apply saves the flagSet for later usage calls, then calls the wrapped
|
||||
Float64SliceFlag.Apply
|
||||
|
||||
type GenericFlag struct {
|
||||
*cli.GenericFlag
|
||||
// Has unexported fields.
|
||||
}
|
||||
GenericFlag is the flag type that wraps cli.GenericFlag to allow for other
|
||||
values to be specified
|
||||
|
||||
func NewGenericFlag(fl *cli.GenericFlag) *GenericFlag
|
||||
NewGenericFlag creates a new GenericFlag
|
||||
|
||||
func (f *GenericFlag) Apply(set *flag.FlagSet) error
|
||||
Apply saves the flagSet for later usage calls, then calls the wrapped
|
||||
GenericFlag.Apply
|
||||
|
||||
func (f *GenericFlag) ApplyInputSourceValue(cCtx *cli.Context, isc InputSourceContext) error
|
||||
ApplyInputSourceValue applies a generic value to the flagSet if required
|
||||
|
||||
type InputSourceContext interface {
|
||||
Source() string
|
||||
|
||||
Int(name string) (int, error)
|
||||
Duration(name string) (time.Duration, error)
|
||||
Float64(name string) (float64, error)
|
||||
String(name string) (string, error)
|
||||
StringSlice(name string) ([]string, error)
|
||||
IntSlice(name string) ([]int, error)
|
||||
Int64Slice(name string) ([]int64, error)
|
||||
Generic(name string) (cli.Generic, error)
|
||||
Bool(name string) (bool, error)
|
||||
|
||||
// Has unexported methods.
|
||||
}
|
||||
InputSourceContext is an interface used to allow other input sources to be
|
||||
implemented as needed.
|
||||
|
||||
Source returns an identifier for the input source. In case of file source it
|
||||
should return path to the file.
|
||||
|
||||
func NewJSONSource(data []byte) (InputSourceContext, error)
|
||||
NewJSONSource returns an InputSourceContext suitable for retrieving config
|
||||
variables from raw JSON data.
|
||||
|
||||
func NewJSONSourceFromFile(f string) (InputSourceContext, error)
|
||||
NewJSONSourceFromFile returns an InputSourceContext suitable for retrieving
|
||||
config variables from a file (or url) containing JSON data.
|
||||
|
||||
func NewJSONSourceFromReader(r io.Reader) (InputSourceContext, error)
|
||||
NewJSONSourceFromReader returns an InputSourceContext suitable for
|
||||
retrieving config variables from an io.Reader that returns JSON data.
|
||||
|
||||
func NewTomlSourceFromFile(file string) (InputSourceContext, error)
|
||||
NewTomlSourceFromFile creates a new TOML InputSourceContext from a filepath.
|
||||
|
||||
func NewYamlSourceFromFile(file string) (InputSourceContext, error)
|
||||
NewYamlSourceFromFile creates a new Yaml InputSourceContext from a filepath.
|
||||
|
||||
type Int64Flag struct {
|
||||
*cli.Int64Flag
|
||||
// Has unexported fields.
|
||||
}
|
||||
Int64Flag is the flag type that wraps cli.Int64Flag to allow for other
|
||||
values to be specified
|
||||
|
||||
func NewInt64Flag(fl *cli.Int64Flag) *Int64Flag
|
||||
NewInt64Flag creates a new Int64Flag
|
||||
|
||||
func (f *Int64Flag) Apply(set *flag.FlagSet) error
|
||||
Apply saves the flagSet for later usage calls, then calls the wrapped
|
||||
Int64Flag.Apply
|
||||
|
||||
type Int64SliceFlag struct {
|
||||
*cli.Int64SliceFlag
|
||||
// Has unexported fields.
|
||||
}
|
||||
Int64SliceFlag is the flag type that wraps cli.Int64SliceFlag to allow for
|
||||
other values to be specified
|
||||
|
||||
func NewInt64SliceFlag(fl *cli.Int64SliceFlag) *Int64SliceFlag
|
||||
NewInt64SliceFlag creates a new Int64SliceFlag
|
||||
|
||||
func (f *Int64SliceFlag) Apply(set *flag.FlagSet) error
|
||||
Apply saves the flagSet for later usage calls, then calls the wrapped
|
||||
Int64SliceFlag.Apply
|
||||
|
||||
func (f *Int64SliceFlag) ApplyInputSourceValue(cCtx *cli.Context, isc InputSourceContext) error
|
||||
ApplyInputSourceValue applies a Int64Slice value if required
|
||||
|
||||
type IntFlag struct {
|
||||
*cli.IntFlag
|
||||
// Has unexported fields.
|
||||
}
|
||||
IntFlag is the flag type that wraps cli.IntFlag to allow for other values to
|
||||
be specified
|
||||
|
||||
func NewIntFlag(fl *cli.IntFlag) *IntFlag
|
||||
NewIntFlag creates a new IntFlag
|
||||
|
||||
func (f *IntFlag) Apply(set *flag.FlagSet) error
|
||||
Apply saves the flagSet for later usage calls, then calls the wrapped
|
||||
IntFlag.Apply
|
||||
|
||||
func (f *IntFlag) ApplyInputSourceValue(cCtx *cli.Context, isc InputSourceContext) error
|
||||
ApplyInputSourceValue applies a int value to the flagSet if required
|
||||
|
||||
type IntSliceFlag struct {
|
||||
*cli.IntSliceFlag
|
||||
// Has unexported fields.
|
||||
}
|
||||
IntSliceFlag is the flag type that wraps cli.IntSliceFlag to allow for other
|
||||
values to be specified
|
||||
|
||||
func NewIntSliceFlag(fl *cli.IntSliceFlag) *IntSliceFlag
|
||||
NewIntSliceFlag creates a new IntSliceFlag
|
||||
|
||||
func (f *IntSliceFlag) Apply(set *flag.FlagSet) error
|
||||
Apply saves the flagSet for later usage calls, then calls the wrapped
|
||||
IntSliceFlag.Apply
|
||||
|
||||
func (f *IntSliceFlag) ApplyInputSourceValue(cCtx *cli.Context, isc InputSourceContext) error
|
||||
ApplyInputSourceValue applies a IntSlice value if required
|
||||
|
||||
type MapInputSource struct {
|
||||
// Has unexported fields.
|
||||
}
|
||||
MapInputSource implements InputSourceContext to return data from the map
|
||||
that is loaded.
|
||||
|
||||
func NewMapInputSource(file string, valueMap map[interface{}]interface{}) *MapInputSource
|
||||
NewMapInputSource creates a new MapInputSource for implementing custom input
|
||||
sources.
|
||||
|
||||
func (fsm *MapInputSource) Bool(name string) (bool, error)
|
||||
Bool returns an bool from the map otherwise returns false
|
||||
|
||||
func (fsm *MapInputSource) Duration(name string) (time.Duration, error)
|
||||
Duration returns a duration from the map if it exists otherwise returns 0
|
||||
|
||||
func (fsm *MapInputSource) Float64(name string) (float64, error)
|
||||
Float64 returns an float64 from the map if it exists otherwise returns 0
|
||||
|
||||
func (fsm *MapInputSource) Generic(name string) (cli.Generic, error)
|
||||
Generic returns an cli.Generic from the map if it exists otherwise returns
|
||||
nil
|
||||
|
||||
func (fsm *MapInputSource) Int(name string) (int, error)
|
||||
Int returns an int from the map if it exists otherwise returns 0
|
||||
|
||||
func (fsm *MapInputSource) Int64Slice(name string) ([]int64, error)
|
||||
Int64Slice returns an []int64 from the map if it exists otherwise returns
|
||||
nil
|
||||
|
||||
func (fsm *MapInputSource) IntSlice(name string) ([]int, error)
|
||||
IntSlice returns an []int from the map if it exists otherwise returns nil
|
||||
|
||||
func (fsm *MapInputSource) Source() string
|
||||
Source returns the path of the source file
|
||||
|
||||
func (fsm *MapInputSource) String(name string) (string, error)
|
||||
String returns a string from the map if it exists otherwise returns an empty
|
||||
string
|
||||
|
||||
func (fsm *MapInputSource) StringSlice(name string) ([]string, error)
|
||||
StringSlice returns an []string from the map if it exists otherwise returns
|
||||
nil
|
||||
|
||||
type PathFlag struct {
|
||||
*cli.PathFlag
|
||||
// Has unexported fields.
|
||||
}
|
||||
PathFlag is the flag type that wraps cli.PathFlag to allow for other values
|
||||
to be specified
|
||||
|
||||
func NewPathFlag(fl *cli.PathFlag) *PathFlag
|
||||
NewPathFlag creates a new PathFlag
|
||||
|
||||
func (f *PathFlag) Apply(set *flag.FlagSet) error
|
||||
Apply saves the flagSet for later usage calls, then calls the wrapped
|
||||
PathFlag.Apply
|
||||
|
||||
func (f *PathFlag) ApplyInputSourceValue(cCtx *cli.Context, isc InputSourceContext) error
|
||||
ApplyInputSourceValue applies a Path value to the flagSet if required
|
||||
|
||||
type StringFlag struct {
|
||||
*cli.StringFlag
|
||||
// Has unexported fields.
|
||||
}
|
||||
StringFlag is the flag type that wraps cli.StringFlag to allow for other
|
||||
values to be specified
|
||||
|
||||
func NewStringFlag(fl *cli.StringFlag) *StringFlag
|
||||
NewStringFlag creates a new StringFlag
|
||||
|
||||
func (f *StringFlag) Apply(set *flag.FlagSet) error
|
||||
Apply saves the flagSet for later usage calls, then calls the wrapped
|
||||
StringFlag.Apply
|
||||
|
||||
func (f *StringFlag) ApplyInputSourceValue(cCtx *cli.Context, isc InputSourceContext) error
|
||||
ApplyInputSourceValue applies a String value to the flagSet if required
|
||||
|
||||
type StringSliceFlag struct {
|
||||
*cli.StringSliceFlag
|
||||
// Has unexported fields.
|
||||
}
|
||||
StringSliceFlag is the flag type that wraps cli.StringSliceFlag to allow for
|
||||
other values to be specified
|
||||
|
||||
func NewStringSliceFlag(fl *cli.StringSliceFlag) *StringSliceFlag
|
||||
NewStringSliceFlag creates a new StringSliceFlag
|
||||
|
||||
func (f *StringSliceFlag) Apply(set *flag.FlagSet) error
|
||||
Apply saves the flagSet for later usage calls, then calls the wrapped
|
||||
StringSliceFlag.Apply
|
||||
|
||||
func (f *StringSliceFlag) ApplyInputSourceValue(cCtx *cli.Context, isc InputSourceContext) error
|
||||
ApplyInputSourceValue applies a StringSlice value to the flagSet if required
|
||||
|
||||
type Uint64Flag struct {
|
||||
*cli.Uint64Flag
|
||||
// Has unexported fields.
|
||||
}
|
||||
Uint64Flag is the flag type that wraps cli.Uint64Flag to allow for other
|
||||
values to be specified
|
||||
|
||||
func NewUint64Flag(fl *cli.Uint64Flag) *Uint64Flag
|
||||
NewUint64Flag creates a new Uint64Flag
|
||||
|
||||
func (f *Uint64Flag) Apply(set *flag.FlagSet) error
|
||||
Apply saves the flagSet for later usage calls, then calls the wrapped
|
||||
Uint64Flag.Apply
|
||||
|
||||
type UintFlag struct {
|
||||
*cli.UintFlag
|
||||
// Has unexported fields.
|
||||
}
|
||||
UintFlag is the flag type that wraps cli.UintFlag to allow for other values
|
||||
to be specified
|
||||
|
||||
func NewUintFlag(fl *cli.UintFlag) *UintFlag
|
||||
NewUintFlag creates a new UintFlag
|
||||
|
||||
func (f *UintFlag) Apply(set *flag.FlagSet) error
|
||||
Apply saves the flagSet for later usage calls, then calls the wrapped
|
||||
UintFlag.Apply
|
||||
|
||||
|
37
internal/argh/argh.go
Normal file
37
internal/argh/argh.go
Normal file
@@ -0,0 +1,37 @@
|
||||
package argh
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
)
|
||||
|
||||
var (
|
||||
tracingEnabled = os.Getenv("ARGH_TRACING") == "enabled"
|
||||
traceLogger *log.Logger
|
||||
|
||||
Error = errors.New("argh error")
|
||||
)
|
||||
|
||||
func init() {
|
||||
if !tracingEnabled {
|
||||
return
|
||||
}
|
||||
|
||||
traceLogger = log.New(os.Stderr, "ARGH TRACING: ", 0)
|
||||
}
|
||||
|
||||
func tracef(format string, v ...any) {
|
||||
if !tracingEnabled {
|
||||
return
|
||||
}
|
||||
|
||||
if _, file, line, ok := runtime.Caller(1); ok {
|
||||
format = fmt.Sprintf("%v:%v ", filepath.Base(file), line) + format
|
||||
}
|
||||
|
||||
traceLogger.Printf(format, v...)
|
||||
}
|
181
internal/argh/argh_test.go
Normal file
181
internal/argh/argh_test.go
Normal file
@@ -0,0 +1,181 @@
|
||||
package argh_test
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/urfave/cli/v3/internal/argh"
|
||||
)
|
||||
|
||||
func ptrTo[T any](v T) *T {
|
||||
return &v
|
||||
}
|
||||
|
||||
func ptrFrom[T any](v *T) T {
|
||||
if v != nil {
|
||||
return *v
|
||||
}
|
||||
|
||||
var zero T
|
||||
return zero
|
||||
}
|
||||
|
||||
func BenchmarkStdlibFlag(b *testing.B) {
|
||||
for i := 0; i < b.N; i++ {
|
||||
func() {
|
||||
fl := flag.NewFlagSet("bench", flag.PanicOnError)
|
||||
okFlag := fl.Bool("ok", false, "")
|
||||
durFlag := fl.Duration("dur", time.Second, "")
|
||||
f64Flag := fl.Float64("f64", float64(42.0), "")
|
||||
iFlag := fl.Int("i", -11, "")
|
||||
i64Flag := fl.Int64("i64", -111111111111, "")
|
||||
sFlag := fl.String("s", "hello", "")
|
||||
uFlag := fl.Uint("u", 11, "")
|
||||
u64Flag := fl.Uint64("u64", 11111111111111111111, "")
|
||||
|
||||
_ = fl.Parse([]string{
|
||||
"-ok",
|
||||
"-dur", "42h42m10s",
|
||||
"-f64", "4242424242.42",
|
||||
"-i", "-42",
|
||||
"-i64", "-4242424242",
|
||||
"-s", "the answer",
|
||||
"-u", "42",
|
||||
"-u64", "4242424242",
|
||||
})
|
||||
_ = fmt.Sprint(
|
||||
"fl", fl,
|
||||
"okFlag", *okFlag,
|
||||
"durFlag", *durFlag,
|
||||
"f64Flag", *f64Flag,
|
||||
"iFlag", *iFlag,
|
||||
"i64Flag", *i64Flag,
|
||||
"sFlag", *sFlag,
|
||||
"uFlag", *uFlag,
|
||||
"u64Flag", *u64Flag,
|
||||
)
|
||||
}()
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkArgh(b *testing.B) {
|
||||
for i := 0; i < b.N; i++ {
|
||||
func() {
|
||||
var (
|
||||
okFlag *bool
|
||||
durFlag *time.Duration
|
||||
f64Flag *float64
|
||||
iFlag *int
|
||||
i64Flag *int64
|
||||
sFlag *string
|
||||
uFlag *uint
|
||||
u64Flag *uint64
|
||||
)
|
||||
|
||||
pCfg := argh.NewParserConfig()
|
||||
pCfg.Prog = &argh.CommandConfig{
|
||||
Flags: &argh.Flags{
|
||||
Map: map[string]argh.FlagConfig{
|
||||
"ok": {
|
||||
On: func(fl argh.CommandFlag) {
|
||||
okFlag = ptrTo(true)
|
||||
},
|
||||
},
|
||||
"dur": {
|
||||
NValue: 1,
|
||||
On: func(fl argh.CommandFlag) {
|
||||
if v, ok := fl.Values["0"]; ok {
|
||||
if pt, err := time.ParseDuration(v); err != nil {
|
||||
durFlag = ptrTo(pt)
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
"f64": {
|
||||
NValue: 1,
|
||||
On: func(fl argh.CommandFlag) {
|
||||
if v, ok := fl.Values["0"]; ok {
|
||||
if f, err := strconv.ParseFloat(v, 64); err == nil {
|
||||
f64Flag = ptrTo(f)
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
"i": {
|
||||
NValue: 1,
|
||||
On: func(fl argh.CommandFlag) {
|
||||
if v, ok := fl.Values["0"]; ok {
|
||||
if i, err := strconv.ParseInt(v, 10, 64); err == nil {
|
||||
iFlag = ptrTo(int(i))
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
"i64": {
|
||||
NValue: 1,
|
||||
On: func(fl argh.CommandFlag) {
|
||||
if v, ok := fl.Values["0"]; ok {
|
||||
if i, err := strconv.ParseInt(v, 10, 64); err == nil {
|
||||
i64Flag = ptrTo(i)
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
"s": {
|
||||
NValue: 1,
|
||||
On: func(fl argh.CommandFlag) {
|
||||
if v, ok := fl.Values["0"]; ok {
|
||||
sFlag = ptrTo(v)
|
||||
}
|
||||
},
|
||||
},
|
||||
"u": {
|
||||
NValue: 1,
|
||||
On: func(fl argh.CommandFlag) {
|
||||
if v, ok := fl.Values["0"]; ok {
|
||||
if u, err := strconv.ParseUint(v, 10, 64); err == nil {
|
||||
uFlag = ptrTo(uint(u))
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
"u64": {
|
||||
NValue: 1,
|
||||
On: func(fl argh.CommandFlag) {
|
||||
if v, ok := fl.Values["0"]; ok {
|
||||
if u, err := strconv.ParseUint(v, 10, 64); err == nil {
|
||||
u64Flag = ptrTo(u)
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
_, _ = argh.ParseArgs([]string{
|
||||
"--ok",
|
||||
"--dur", "42h42m10s",
|
||||
"--f64", "4242424242.42",
|
||||
"-i", "-42",
|
||||
"--i64", "-4242424242",
|
||||
"-s", "the answer",
|
||||
"-u", "42",
|
||||
"--u64", "4242424242",
|
||||
}, pCfg)
|
||||
_ = fmt.Sprint(
|
||||
"okFlag", ptrFrom(okFlag),
|
||||
"durFlag", ptrFrom(durFlag),
|
||||
"f64Flag", ptrFrom(f64Flag),
|
||||
"iFlag", ptrFrom(iFlag),
|
||||
"i64Flag", ptrFrom(i64Flag),
|
||||
"sFlag", ptrFrom(sFlag),
|
||||
"uFlag", ptrFrom(uFlag),
|
||||
"u64Flag", ptrFrom(u64Flag),
|
||||
)
|
||||
}()
|
||||
}
|
||||
}
|
50
internal/argh/ast.go
Normal file
50
internal/argh/ast.go
Normal file
@@ -0,0 +1,50 @@
|
||||
package argh
|
||||
|
||||
// ToAST accepts a slice of nodes as expected from ParseArgs and
|
||||
// returns an AST with parse-time artifacts dropped and reorganized
|
||||
// where applicable.
|
||||
func ToAST(parseTree []Node) []Node {
|
||||
ret := []Node{}
|
||||
|
||||
for i, node := range parseTree {
|
||||
tracef("ToAST i=%d node type=%T", i, node)
|
||||
|
||||
if _, ok := node.(*ArgDelimiter); ok {
|
||||
continue
|
||||
}
|
||||
|
||||
if _, ok := node.(*StopFlag); ok {
|
||||
continue
|
||||
}
|
||||
|
||||
if v, ok := node.(*CompoundShortFlag); ok {
|
||||
if v.Nodes != nil {
|
||||
ret = append(ret, ToAST(v.Nodes)...)
|
||||
}
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
if v, ok := node.(*CommandFlag); ok {
|
||||
astNodes := ToAST(v.Nodes)
|
||||
|
||||
if len(astNodes) == 0 {
|
||||
astNodes = nil
|
||||
}
|
||||
|
||||
ret = append(
|
||||
ret,
|
||||
&CommandFlag{
|
||||
Name: v.Name,
|
||||
Values: v.Values,
|
||||
Nodes: astNodes,
|
||||
})
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
ret = append(ret, node)
|
||||
}
|
||||
|
||||
return ret
|
||||
}
|
42
internal/argh/node.go
Normal file
42
internal/argh/node.go
Normal file
@@ -0,0 +1,42 @@
|
||||
package argh
|
||||
|
||||
type Node interface{}
|
||||
|
||||
type TypedNode struct {
|
||||
Type string
|
||||
Node Node
|
||||
}
|
||||
|
||||
type PassthroughArgs struct {
|
||||
Nodes []Node
|
||||
}
|
||||
|
||||
type CompoundShortFlag struct {
|
||||
Nodes []Node
|
||||
}
|
||||
|
||||
type Ident struct {
|
||||
Literal string
|
||||
}
|
||||
|
||||
type BadArg struct {
|
||||
Literal string
|
||||
From Pos
|
||||
To Pos
|
||||
}
|
||||
|
||||
// CommandFlag is a Node with a name, a slice of child Nodes, and
|
||||
// potentially a map of named values derived from the child Nodes
|
||||
type CommandFlag struct {
|
||||
Name string
|
||||
Values map[string]string
|
||||
Nodes []Node
|
||||
}
|
||||
|
||||
type StdinFlag struct{}
|
||||
|
||||
type StopFlag struct{}
|
||||
|
||||
type ArgDelimiter struct{}
|
||||
|
||||
type Assign struct{}
|
26
internal/argh/nvalue_string.go
Normal file
26
internal/argh/nvalue_string.go
Normal file
@@ -0,0 +1,26 @@
|
||||
// Code generated by "stringer -type NValue"; DO NOT EDIT.
|
||||
|
||||
package argh
|
||||
|
||||
import "strconv"
|
||||
|
||||
func _() {
|
||||
// An "invalid array index" compiler error signifies that the constant values have changed.
|
||||
// Re-run the stringer command to generate them again.
|
||||
var x [1]struct{}
|
||||
_ = x[OneOrMoreValue - -2]
|
||||
_ = x[ZeroOrMoreValue - -1]
|
||||
_ = x[ZeroValue-0]
|
||||
}
|
||||
|
||||
const _NValue_name = "OneOrMoreValueZeroOrMoreValueZeroValue"
|
||||
|
||||
var _NValue_index = [...]uint8{0, 14, 29, 38}
|
||||
|
||||
func (i NValue) String() string {
|
||||
i -= -2
|
||||
if i < 0 || i >= NValue(len(_NValue_index)-1) {
|
||||
return "NValue(" + strconv.FormatInt(int64(i+-2), 10) + ")"
|
||||
}
|
||||
return _NValue_name[_NValue_index[i]:_NValue_index[i+1]]
|
||||
}
|
392
internal/argh/parser.go
Normal file
392
internal/argh/parser.go
Normal file
@@ -0,0 +1,392 @@
|
||||
package argh
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type parser struct {
|
||||
s *Scanner
|
||||
|
||||
cfg *ParserConfig
|
||||
|
||||
errors ParserErrorList
|
||||
|
||||
tok Token
|
||||
lit string
|
||||
pos Pos
|
||||
|
||||
buffered bool
|
||||
}
|
||||
|
||||
type ParseTree struct {
|
||||
Nodes []Node `json:"nodes"`
|
||||
}
|
||||
|
||||
func ParseArgs(args []string, pCfg *ParserConfig) (*ParseTree, error) {
|
||||
p := &parser{}
|
||||
|
||||
if err := p.init(
|
||||
strings.NewReader(strings.Join(args, string(nul))),
|
||||
pCfg,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
tracef("ParseArgs(...) parser=%+#v", p)
|
||||
|
||||
return p.parseArgs()
|
||||
}
|
||||
|
||||
func (p *parser) addError(msg string) {
|
||||
p.errors.Add(Position{Column: int(p.pos)}, msg)
|
||||
}
|
||||
|
||||
func (p *parser) init(r io.Reader, pCfg *ParserConfig) error {
|
||||
p.errors = ParserErrorList{}
|
||||
|
||||
if pCfg == nil {
|
||||
return fmt.Errorf("nil parser config: %w", Error)
|
||||
}
|
||||
|
||||
p.cfg = pCfg
|
||||
|
||||
p.s = NewScanner(r, pCfg.ScannerConfig)
|
||||
|
||||
p.next()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *parser) parseArgs() (*ParseTree, error) {
|
||||
if p.errors.Len() != 0 {
|
||||
tracef("parseArgs() bailing due to initial error")
|
||||
return nil, p.errors.Err()
|
||||
}
|
||||
|
||||
tracef("parseArgs() parsing %q as program command; cfg=%+#v", p.lit, p.cfg.Prog)
|
||||
prog := p.parseCommand(p.cfg.Prog)
|
||||
|
||||
tracef("parseArgs() top level node is %T", prog)
|
||||
|
||||
nodes := []Node{prog}
|
||||
if v := p.parsePassthrough(); v != nil {
|
||||
tracef("parseArgs() appending passthrough argument %v", v)
|
||||
nodes = append(nodes, v)
|
||||
}
|
||||
|
||||
tracef("parseArgs() returning ParseTree")
|
||||
|
||||
return &ParseTree{Nodes: nodes}, p.errors.Err()
|
||||
}
|
||||
|
||||
func (p *parser) next() {
|
||||
tracef("next() before scan: %v %q %v", p.tok, p.lit, p.pos)
|
||||
|
||||
p.tok, p.lit, p.pos = p.s.Scan()
|
||||
|
||||
tracef("next() after scan: %v %q %v", p.tok, p.lit, p.pos)
|
||||
}
|
||||
|
||||
func (p *parser) parseCommand(cCfg *CommandConfig) Node {
|
||||
tracef("parseCommand(%+#v)", cCfg)
|
||||
|
||||
node := &CommandFlag{
|
||||
Name: p.lit,
|
||||
}
|
||||
values := map[string]string{}
|
||||
nodes := []Node{}
|
||||
|
||||
identIndex := 0
|
||||
|
||||
for i := 0; p.tok != EOL; i++ {
|
||||
if !p.buffered {
|
||||
tracef("parseCommand(...) buffered=false; scanning next")
|
||||
p.next()
|
||||
}
|
||||
|
||||
p.buffered = false
|
||||
|
||||
tracef("parseCommand(...) for=%d values=%+#v", i, values)
|
||||
tracef("parseCommand(...) for=%d nodes=%+#v", i, nodes)
|
||||
tracef("parseCommand(...) for=%d tok=%s lit=%q pos=%v", i, p.tok, p.lit, p.pos)
|
||||
|
||||
tracef("parseCommand(...) cCfg=%+#v", cCfg)
|
||||
|
||||
if subCfg, ok := cCfg.GetCommandConfig(p.lit); ok {
|
||||
subCommand := p.lit
|
||||
|
||||
nodes = append(nodes, p.parseCommand(&subCfg))
|
||||
|
||||
tracef("parseCommand(...) breaking after sub-command=%v", subCommand)
|
||||
break
|
||||
}
|
||||
|
||||
switch p.tok {
|
||||
case ARG_DELIMITER:
|
||||
tracef("parseCommand(...) handling %s", p.tok)
|
||||
|
||||
nodes = append(nodes, &ArgDelimiter{})
|
||||
|
||||
continue
|
||||
case IDENT, STDIN_FLAG:
|
||||
tracef("parseCommand(...) handling %s", p.tok)
|
||||
|
||||
if cCfg.NValue.Contains(identIndex) {
|
||||
name := fmt.Sprintf("%d", identIndex)
|
||||
|
||||
tracef("parseCommand(...) checking for name of identIndex=%d", identIndex)
|
||||
|
||||
if len(cCfg.ValueNames) > identIndex {
|
||||
name = cCfg.ValueNames[identIndex]
|
||||
tracef("parseCommand(...) setting name=%s from config value names", name)
|
||||
} else if len(cCfg.ValueNames) == 1 && (cCfg.NValue == OneOrMoreValue || cCfg.NValue == ZeroOrMoreValue) {
|
||||
name = fmt.Sprintf("%s.%d", cCfg.ValueNames[0], identIndex)
|
||||
tracef("parseCommand(...) setting name=%s from repeating value name", name)
|
||||
}
|
||||
|
||||
values[name] = p.lit
|
||||
}
|
||||
|
||||
if p.tok == STDIN_FLAG {
|
||||
nodes = append(nodes, &StdinFlag{})
|
||||
} else {
|
||||
nodes = append(nodes, &Ident{Literal: p.lit})
|
||||
}
|
||||
|
||||
identIndex++
|
||||
case LONG_FLAG, SHORT_FLAG, COMPOUND_SHORT_FLAG:
|
||||
tok := p.tok
|
||||
|
||||
flagNode := p.parseFlag(cCfg.Flags)
|
||||
|
||||
tracef("parseCommand(...) appending %s node=%+#v", tok, flagNode)
|
||||
|
||||
nodes = append(nodes, flagNode)
|
||||
case ASSIGN:
|
||||
tracef("parseCommand(...) error on bare %s", p.tok)
|
||||
|
||||
p.addError("invalid bare assignment")
|
||||
|
||||
break
|
||||
default:
|
||||
tracef("parseCommand(...) breaking on %s", p.tok)
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if len(nodes) > 0 {
|
||||
node.Nodes = nodes
|
||||
}
|
||||
|
||||
if len(values) > 0 {
|
||||
node.Values = values
|
||||
}
|
||||
|
||||
if cCfg.On != nil {
|
||||
tracef("parseCommand(...) calling command config handler for node=%+#v", node)
|
||||
cCfg.On(*node)
|
||||
} else {
|
||||
tracef("parseCommand(...) no command config handler for node=%+#v", node)
|
||||
}
|
||||
|
||||
tracef("parseCommand(...) returning node=%+#v", node)
|
||||
return node
|
||||
}
|
||||
|
||||
func (p *parser) parseIdent() Node {
|
||||
node := &Ident{Literal: p.lit}
|
||||
return node
|
||||
}
|
||||
|
||||
func (p *parser) parseFlag(flags *Flags) Node {
|
||||
switch p.tok {
|
||||
case SHORT_FLAG:
|
||||
tracef("parseFlag(...) parsing short flag with config=%+#v", flags)
|
||||
return p.parseShortFlag(flags)
|
||||
case LONG_FLAG:
|
||||
tracef("parseFlag(...) parsing long flag with config=%+#v", flags)
|
||||
return p.parseLongFlag(flags)
|
||||
case COMPOUND_SHORT_FLAG:
|
||||
tracef("parseFlag(...) parsing compound short flag with config=%+#v", flags)
|
||||
return p.parseCompoundShortFlag(flags)
|
||||
}
|
||||
|
||||
panic(fmt.Sprintf("token %v cannot be parsed as flag", p.tok))
|
||||
}
|
||||
|
||||
func (p *parser) parseShortFlag(flags *Flags) Node {
|
||||
node := &CommandFlag{Name: string(p.lit[1])}
|
||||
|
||||
flCfg, ok := flags.Get(node.Name)
|
||||
if !ok {
|
||||
p.addError(fmt.Sprintf("unknown flag %[1]q", node.Name))
|
||||
|
||||
return node
|
||||
}
|
||||
|
||||
return p.parseConfiguredFlag(node, flCfg, nil)
|
||||
}
|
||||
|
||||
func (p *parser) parseLongFlag(flags *Flags) Node {
|
||||
node := &CommandFlag{Name: string(p.lit[2:])}
|
||||
|
||||
flCfg, ok := flags.Get(node.Name)
|
||||
if !ok {
|
||||
p.addError(fmt.Sprintf("unknown flag %[1]q", node.Name))
|
||||
|
||||
return node
|
||||
}
|
||||
|
||||
return p.parseConfiguredFlag(node, flCfg, nil)
|
||||
}
|
||||
|
||||
func (p *parser) parseCompoundShortFlag(flags *Flags) Node {
|
||||
unparsedFlags := []*CommandFlag{}
|
||||
unparsedFlagConfigs := []FlagConfig{}
|
||||
|
||||
withoutFlagPrefix := p.lit[1:]
|
||||
|
||||
for _, r := range withoutFlagPrefix {
|
||||
node := &CommandFlag{Name: string(r)}
|
||||
|
||||
flCfg, ok := flags.Get(node.Name)
|
||||
if !ok {
|
||||
p.addError(fmt.Sprintf("unknown flag %[1]q", node.Name))
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
unparsedFlags = append(unparsedFlags, node)
|
||||
unparsedFlagConfigs = append(unparsedFlagConfigs, flCfg)
|
||||
}
|
||||
|
||||
flagNodes := []Node{}
|
||||
|
||||
for i, node := range unparsedFlags {
|
||||
flCfg := unparsedFlagConfigs[i]
|
||||
|
||||
if i != len(unparsedFlags)-1 {
|
||||
// NOTE: if a compound short flag is configured to accept
|
||||
// more than zero values but is not the last flag in the
|
||||
// group, it will be parsed with an override NValue of
|
||||
// ZeroValue so that it does not consume the next token.
|
||||
if flCfg.NValue.Required() {
|
||||
p.addError(
|
||||
fmt.Sprintf(
|
||||
"short flag %[1]q before end of compound group expects value",
|
||||
node.Name,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
flagNodes = append(
|
||||
flagNodes,
|
||||
p.parseConfiguredFlag(node, flCfg, zeroValuePtr),
|
||||
)
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
flagNodes = append(flagNodes, p.parseConfiguredFlag(node, flCfg, nil))
|
||||
}
|
||||
|
||||
return &CompoundShortFlag{Nodes: flagNodes}
|
||||
}
|
||||
|
||||
func (p *parser) parseConfiguredFlag(node *CommandFlag, flCfg FlagConfig, nValueOverride *NValue) Node {
|
||||
values := map[string]string{}
|
||||
nodes := []Node{}
|
||||
|
||||
atExit := func() *CommandFlag {
|
||||
if len(nodes) > 0 {
|
||||
node.Nodes = nodes
|
||||
}
|
||||
|
||||
if len(values) > 0 {
|
||||
node.Values = values
|
||||
}
|
||||
|
||||
if flCfg.On != nil {
|
||||
tracef("parseConfiguredFlag(...) calling flag config handler for node=%+#[1]v", node)
|
||||
flCfg.On(*node)
|
||||
} else {
|
||||
tracef("parseConfiguredFlag(...) no flag config handler for node=%+#[1]v", node)
|
||||
}
|
||||
|
||||
return node
|
||||
}
|
||||
|
||||
identIndex := 0
|
||||
|
||||
for i := 0; p.tok != EOL; i++ {
|
||||
if nValueOverride != nil && !(*nValueOverride).Contains(identIndex) {
|
||||
tracef("parseConfiguredFlag(...) identIndex=%d exceeds expected=%v; breaking", identIndex, *nValueOverride)
|
||||
break
|
||||
}
|
||||
|
||||
if !flCfg.NValue.Contains(identIndex) {
|
||||
tracef("parseConfiguredFlag(...) identIndex=%d exceeds expected=%v; breaking", identIndex, flCfg.NValue)
|
||||
break
|
||||
}
|
||||
|
||||
p.next()
|
||||
|
||||
switch p.tok {
|
||||
case ARG_DELIMITER:
|
||||
nodes = append(nodes, &ArgDelimiter{})
|
||||
|
||||
continue
|
||||
case ASSIGN:
|
||||
nodes = append(nodes, &Assign{})
|
||||
|
||||
continue
|
||||
case IDENT, STDIN_FLAG:
|
||||
name := fmt.Sprintf("%d", identIndex)
|
||||
|
||||
tracef("parseConfiguredFlag(...) checking for name of identIndex=%d", identIndex)
|
||||
|
||||
if len(flCfg.ValueNames) > identIndex {
|
||||
name = flCfg.ValueNames[identIndex]
|
||||
tracef("parseConfiguredFlag(...) setting name=%s from config value names", name)
|
||||
} else if len(flCfg.ValueNames) == 1 && (flCfg.NValue == OneOrMoreValue || flCfg.NValue == ZeroOrMoreValue) {
|
||||
name = fmt.Sprintf("%s.%d", flCfg.ValueNames[0], identIndex)
|
||||
tracef("parseConfiguredFlag(...) setting name=%s from repeating value name", name)
|
||||
} else {
|
||||
tracef("parseConfiguredFlag(...) setting name=%s", name)
|
||||
}
|
||||
|
||||
values[name] = p.lit
|
||||
|
||||
if p.tok == STDIN_FLAG {
|
||||
nodes = append(nodes, &StdinFlag{})
|
||||
} else {
|
||||
nodes = append(nodes, &Ident{Literal: p.lit})
|
||||
}
|
||||
|
||||
identIndex++
|
||||
default:
|
||||
tracef("parseConfiguredFlag(...) breaking on %s %q %v; setting buffered=true", p.tok, p.lit, p.pos)
|
||||
p.buffered = true
|
||||
|
||||
return atExit()
|
||||
}
|
||||
}
|
||||
|
||||
return atExit()
|
||||
}
|
||||
|
||||
func (p *parser) parsePassthrough() Node {
|
||||
nodes := []Node{}
|
||||
|
||||
for ; p.tok != EOL; p.next() {
|
||||
nodes = append(nodes, &Ident{Literal: p.lit})
|
||||
}
|
||||
|
||||
if len(nodes) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
return &PassthroughArgs{Nodes: nodes}
|
||||
}
|
214
internal/argh/parser_config.go
Normal file
214
internal/argh/parser_config.go
Normal file
@@ -0,0 +1,214 @@
|
||||
package argh
|
||||
|
||||
import "sync"
|
||||
|
||||
const (
|
||||
OneOrMoreValue NValue = -2
|
||||
ZeroOrMoreValue NValue = -1
|
||||
ZeroValue NValue = 0
|
||||
)
|
||||
|
||||
var (
|
||||
zeroValuePtr = func() *NValue {
|
||||
v := ZeroValue
|
||||
return &v
|
||||
}()
|
||||
)
|
||||
|
||||
type NValue int
|
||||
|
||||
func (nv NValue) Required() bool {
|
||||
if nv == OneOrMoreValue {
|
||||
return true
|
||||
}
|
||||
|
||||
return int(nv) >= 1
|
||||
}
|
||||
|
||||
func (nv NValue) Contains(i int) bool {
|
||||
tracef("NValue.Contains(%v)", i)
|
||||
|
||||
if i < int(ZeroValue) {
|
||||
return false
|
||||
}
|
||||
|
||||
if nv == OneOrMoreValue || nv == ZeroOrMoreValue {
|
||||
return true
|
||||
}
|
||||
|
||||
return int(nv) > i
|
||||
}
|
||||
|
||||
type ParserConfig struct {
|
||||
Prog *CommandConfig
|
||||
|
||||
ScannerConfig *ScannerConfig
|
||||
}
|
||||
|
||||
type ParserOption func(*ParserConfig)
|
||||
|
||||
func NewParserConfig(opts ...ParserOption) *ParserConfig {
|
||||
pCfg := &ParserConfig{}
|
||||
|
||||
for _, opt := range opts {
|
||||
if opt != nil {
|
||||
opt(pCfg)
|
||||
}
|
||||
}
|
||||
|
||||
if pCfg.Prog == nil {
|
||||
pCfg.Prog = &CommandConfig{}
|
||||
pCfg.Prog.init()
|
||||
}
|
||||
|
||||
if pCfg.ScannerConfig == nil {
|
||||
pCfg.ScannerConfig = POSIXyScannerConfig
|
||||
}
|
||||
|
||||
return pCfg
|
||||
}
|
||||
|
||||
type CommandConfig struct {
|
||||
NValue NValue
|
||||
ValueNames []string
|
||||
Flags *Flags
|
||||
Commands *Commands
|
||||
|
||||
On func(CommandFlag)
|
||||
}
|
||||
|
||||
func (cCfg *CommandConfig) init() {
|
||||
if cCfg.ValueNames == nil {
|
||||
cCfg.ValueNames = []string{}
|
||||
}
|
||||
|
||||
if cCfg.Flags == nil {
|
||||
cCfg.Flags = &Flags{}
|
||||
}
|
||||
|
||||
if cCfg.Commands == nil {
|
||||
cCfg.Commands = &Commands{}
|
||||
}
|
||||
}
|
||||
|
||||
func (cCfg *CommandConfig) GetCommandConfig(name string) (CommandConfig, bool) {
|
||||
tracef("CommandConfig.GetCommandConfig(%q)", name)
|
||||
|
||||
if cCfg.Commands == nil {
|
||||
cCfg.Commands = &Commands{Map: map[string]CommandConfig{}}
|
||||
}
|
||||
|
||||
return cCfg.Commands.Get(name)
|
||||
}
|
||||
|
||||
func (cCfg *CommandConfig) GetFlagConfig(name string) (FlagConfig, bool) {
|
||||
tracef("CommandConfig.GetFlagConfig(%q)", name)
|
||||
|
||||
if cCfg.Flags == nil {
|
||||
cCfg.Flags = &Flags{Map: map[string]FlagConfig{}}
|
||||
}
|
||||
|
||||
return cCfg.Flags.Get(name)
|
||||
}
|
||||
|
||||
func (cCfg *CommandConfig) SetFlagConfig(name string, flCfg FlagConfig) {
|
||||
tracef("CommandConfig.SetFlagConfig(%q, ...)", name)
|
||||
|
||||
if cCfg.Flags == nil {
|
||||
cCfg.Flags = &Flags{Map: map[string]FlagConfig{}}
|
||||
}
|
||||
|
||||
cCfg.Flags.Set(name, flCfg)
|
||||
}
|
||||
|
||||
func (cCfg *CommandConfig) SetDefaultFlagConfig(name string, flCfg FlagConfig) {
|
||||
tracef("CommandConfig.SetDefaultFlagConfig(%q, ...)", name)
|
||||
|
||||
if cCfg.Flags == nil {
|
||||
cCfg.Flags = &Flags{Map: map[string]FlagConfig{}}
|
||||
}
|
||||
|
||||
cCfg.Flags.SetDefault(name, flCfg)
|
||||
}
|
||||
|
||||
type FlagConfig struct {
|
||||
NValue NValue
|
||||
Persist bool
|
||||
ValueNames []string
|
||||
|
||||
On func(CommandFlag)
|
||||
}
|
||||
|
||||
type Flags struct {
|
||||
Parent *Flags
|
||||
Map map[string]FlagConfig
|
||||
|
||||
Automatic bool
|
||||
|
||||
m sync.Mutex
|
||||
}
|
||||
|
||||
func (fl *Flags) Get(name string) (FlagConfig, bool) {
|
||||
tracef("Flags.Get(%q)", name)
|
||||
|
||||
if fl.Map == nil {
|
||||
fl.Map = map[string]FlagConfig{}
|
||||
}
|
||||
|
||||
flCfg, ok := fl.Map[name]
|
||||
if !ok {
|
||||
if fl.Automatic {
|
||||
return FlagConfig{}, true
|
||||
}
|
||||
|
||||
if fl.Parent != nil {
|
||||
flCfg, ok = fl.Parent.Get(name)
|
||||
return flCfg, ok && flCfg.Persist
|
||||
}
|
||||
}
|
||||
|
||||
return flCfg, ok
|
||||
}
|
||||
|
||||
func (fl *Flags) Set(name string, flCfg FlagConfig) {
|
||||
tracef("Flags.Set(%q, ...)", name)
|
||||
|
||||
fl.m.Lock()
|
||||
defer fl.m.Unlock()
|
||||
|
||||
if fl.Map == nil {
|
||||
fl.Map = map[string]FlagConfig{}
|
||||
}
|
||||
|
||||
fl.Map[name] = flCfg
|
||||
}
|
||||
|
||||
func (fl *Flags) SetDefault(name string, flCfg FlagConfig) {
|
||||
tracef("Flags.SetDefault(%q, ...)", name)
|
||||
|
||||
fl.m.Lock()
|
||||
defer fl.m.Unlock()
|
||||
|
||||
if fl.Map == nil {
|
||||
fl.Map = map[string]FlagConfig{}
|
||||
}
|
||||
|
||||
if _, ok := fl.Map[name]; !ok {
|
||||
fl.Map[name] = flCfg
|
||||
}
|
||||
}
|
||||
|
||||
type Commands struct {
|
||||
Map map[string]CommandConfig
|
||||
}
|
||||
|
||||
func (cmd *Commands) Get(name string) (CommandConfig, bool) {
|
||||
tracef("Commands.Get(%q)", name)
|
||||
|
||||
if cmd.Map == nil {
|
||||
cmd.Map = map[string]CommandConfig{}
|
||||
}
|
||||
|
||||
cmdCfg, ok := cmd.Map[name]
|
||||
return cmdCfg, ok
|
||||
}
|
88
internal/argh/parser_error.go
Normal file
88
internal/argh/parser_error.go
Normal file
@@ -0,0 +1,88 @@
|
||||
package argh
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"sort"
|
||||
)
|
||||
|
||||
// ParserError is largely borrowed from go/scanner.Error
|
||||
type ParserError struct {
|
||||
Pos Position
|
||||
Msg string
|
||||
}
|
||||
|
||||
func (e ParserError) Error() string {
|
||||
if e.Pos.IsValid() {
|
||||
return e.Pos.String() + ":" + e.Msg
|
||||
}
|
||||
|
||||
return e.Msg
|
||||
}
|
||||
|
||||
// ParserErrorList is largely borrowed from go/scanner.ErrorList
|
||||
type ParserErrorList []*ParserError
|
||||
|
||||
func (el *ParserErrorList) Add(pos Position, msg string) {
|
||||
*el = append(*el, &ParserError{Pos: pos, Msg: msg})
|
||||
}
|
||||
|
||||
func (el *ParserErrorList) Reset() { *el = (*el)[0:0] }
|
||||
|
||||
func (el ParserErrorList) Len() int { return len(el) }
|
||||
|
||||
func (el ParserErrorList) Swap(i, j int) { el[i], el[j] = el[j], el[i] }
|
||||
|
||||
func (el ParserErrorList) Less(i, j int) bool {
|
||||
e := &el[i].Pos
|
||||
f := &el[j].Pos
|
||||
|
||||
if e.Column != f.Column {
|
||||
return e.Column < f.Column
|
||||
}
|
||||
|
||||
return el[i].Msg < el[j].Msg
|
||||
}
|
||||
|
||||
func (el ParserErrorList) Sort() {
|
||||
sort.Sort(el)
|
||||
}
|
||||
|
||||
func (el ParserErrorList) Error() string {
|
||||
switch len(el) {
|
||||
case 0:
|
||||
return "no errors"
|
||||
case 1:
|
||||
return el[0].Error()
|
||||
}
|
||||
return fmt.Sprintf("%s (and %d more errors)", el[0], len(el)-1)
|
||||
}
|
||||
|
||||
func (el ParserErrorList) Err() error {
|
||||
if len(el) == 0 {
|
||||
return nil
|
||||
}
|
||||
return el
|
||||
}
|
||||
|
||||
func (el ParserErrorList) Is(other error) bool {
|
||||
if _, ok := other.(ParserErrorList); ok {
|
||||
return el.Error() == other.Error()
|
||||
}
|
||||
|
||||
if v, ok := other.(*ParserErrorList); ok {
|
||||
return el.Error() == (*v).Error()
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
func PrintParserError(w io.Writer, err error) {
|
||||
if list, ok := err.(ParserErrorList); ok {
|
||||
for _, e := range list {
|
||||
fmt.Fprintf(w, "%s\n", e)
|
||||
}
|
||||
} else if err != nil {
|
||||
fmt.Fprintf(w, "%s\n", err)
|
||||
}
|
||||
}
|
1058
internal/argh/parser_test.go
Normal file
1058
internal/argh/parser_test.go
Normal file
File diff suppressed because it is too large
Load Diff
159
internal/argh/scanner.go
Normal file
159
internal/argh/scanner.go
Normal file
@@ -0,0 +1,159 @@
|
||||
package argh
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"errors"
|
||||
"io"
|
||||
"log"
|
||||
"unicode"
|
||||
)
|
||||
|
||||
type Scanner struct {
|
||||
r *bufio.Reader
|
||||
i int
|
||||
cfg *ScannerConfig
|
||||
}
|
||||
|
||||
func NewScanner(r io.Reader, cfg *ScannerConfig) *Scanner {
|
||||
if cfg == nil {
|
||||
cfg = POSIXyScannerConfig
|
||||
}
|
||||
|
||||
return &Scanner{
|
||||
r: bufio.NewReader(r),
|
||||
cfg: cfg,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Scanner) Scan() (Token, string, Pos) {
|
||||
ch, pos := s.read()
|
||||
|
||||
if s.cfg.IsBlankspace(ch) {
|
||||
_ = s.unread()
|
||||
return s.scanBlankspace()
|
||||
}
|
||||
|
||||
if s.cfg.IsAssignmentOperator(ch) {
|
||||
return ASSIGN, string(ch), pos
|
||||
}
|
||||
|
||||
if s.cfg.IsMultiValueDelim(ch) {
|
||||
return MULTI_VALUE_DELIMITER, string(ch), pos
|
||||
}
|
||||
|
||||
if ch == eol {
|
||||
return EOL, "", pos
|
||||
}
|
||||
|
||||
if ch == nul {
|
||||
return ARG_DELIMITER, string(ch), pos
|
||||
}
|
||||
|
||||
if unicode.IsGraphic(ch) {
|
||||
_ = s.unread()
|
||||
return s.scanArg()
|
||||
}
|
||||
|
||||
return ILLEGAL, string(ch), pos
|
||||
}
|
||||
|
||||
func (s *Scanner) read() (rune, Pos) {
|
||||
ch, _, err := s.r.ReadRune()
|
||||
s.i++
|
||||
|
||||
if errors.Is(err, io.EOF) {
|
||||
return eol, Pos(s.i)
|
||||
} else if err != nil {
|
||||
log.Printf("unknown scanner error=%+v", err)
|
||||
return eol, Pos(s.i)
|
||||
}
|
||||
|
||||
return ch, Pos(s.i)
|
||||
}
|
||||
|
||||
func (s *Scanner) unread() Pos {
|
||||
_ = s.r.UnreadRune()
|
||||
s.i--
|
||||
return Pos(s.i)
|
||||
}
|
||||
|
||||
func (s *Scanner) scanBlankspace() (Token, string, Pos) {
|
||||
buf := &bytes.Buffer{}
|
||||
ch, pos := s.read()
|
||||
buf.WriteRune(ch)
|
||||
|
||||
for {
|
||||
ch, pos = s.read()
|
||||
|
||||
if ch == eol {
|
||||
break
|
||||
} else if !s.cfg.IsBlankspace(ch) {
|
||||
pos = s.unread()
|
||||
break
|
||||
} else {
|
||||
_, _ = buf.WriteRune(ch)
|
||||
}
|
||||
}
|
||||
|
||||
return BS, buf.String(), pos
|
||||
}
|
||||
|
||||
func (s *Scanner) scanArg() (Token, string, Pos) {
|
||||
buf := &bytes.Buffer{}
|
||||
ch, pos := s.read()
|
||||
buf.WriteRune(ch)
|
||||
|
||||
for {
|
||||
ch, pos = s.read()
|
||||
|
||||
if ch == eol || ch == nul || s.cfg.IsAssignmentOperator(ch) || s.cfg.IsMultiValueDelim(ch) {
|
||||
pos = s.unread()
|
||||
break
|
||||
}
|
||||
|
||||
_, _ = buf.WriteRune(ch)
|
||||
}
|
||||
|
||||
str := buf.String()
|
||||
|
||||
if len(str) == 0 {
|
||||
return EMPTY, str, pos
|
||||
}
|
||||
|
||||
ch0 := rune(str[0])
|
||||
|
||||
if len(str) == 1 {
|
||||
if s.cfg.IsFlagPrefix(ch0) {
|
||||
return STDIN_FLAG, str, pos
|
||||
}
|
||||
|
||||
if s.cfg.IsAssignmentOperator(ch0) {
|
||||
return ASSIGN, str, pos
|
||||
}
|
||||
|
||||
return IDENT, str, pos
|
||||
}
|
||||
|
||||
ch1 := rune(str[1])
|
||||
|
||||
if len(str) == 2 {
|
||||
if s.cfg.IsFlagPrefix(ch0) && s.cfg.IsFlagPrefix(ch1) {
|
||||
return STOP_FLAG, str, pos
|
||||
}
|
||||
|
||||
if s.cfg.IsFlagPrefix(ch0) {
|
||||
return SHORT_FLAG, str, pos
|
||||
}
|
||||
}
|
||||
|
||||
if s.cfg.IsFlagPrefix(ch0) {
|
||||
if s.cfg.IsFlagPrefix(ch1) {
|
||||
return LONG_FLAG, str, pos
|
||||
}
|
||||
|
||||
return COMPOUND_SHORT_FLAG, str, pos
|
||||
}
|
||||
|
||||
return IDENT, str, pos
|
||||
}
|
39
internal/argh/scanner_config.go
Normal file
39
internal/argh/scanner_config.go
Normal file
@@ -0,0 +1,39 @@
|
||||
package argh
|
||||
|
||||
var (
|
||||
// POSIXyScannerConfig defines a scanner config that uses '-'
|
||||
// as the flag prefix, which also means that "--" is the "long
|
||||
// flag" prefix, a bare "--" is considered STOP_FLAG, and a
|
||||
// bare "-" is considered STDIN_FLAG.
|
||||
POSIXyScannerConfig = &ScannerConfig{
|
||||
AssignmentOperator: '=',
|
||||
FlagPrefix: '-',
|
||||
MultiValueDelim: ',',
|
||||
}
|
||||
)
|
||||
|
||||
type ScannerConfig struct {
|
||||
AssignmentOperator rune
|
||||
FlagPrefix rune
|
||||
MultiValueDelim rune
|
||||
}
|
||||
|
||||
func (cfg *ScannerConfig) IsFlagPrefix(ch rune) bool {
|
||||
return ch == cfg.FlagPrefix
|
||||
}
|
||||
|
||||
func (cfg *ScannerConfig) IsMultiValueDelim(ch rune) bool {
|
||||
return ch == cfg.MultiValueDelim
|
||||
}
|
||||
|
||||
func (cfg *ScannerConfig) IsAssignmentOperator(ch rune) bool {
|
||||
return ch == cfg.AssignmentOperator
|
||||
}
|
||||
|
||||
func (cfg *ScannerConfig) IsBlankspace(ch rune) bool {
|
||||
return ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r'
|
||||
}
|
||||
|
||||
func (cfg *ScannerConfig) IsUnderscore(ch rune) bool {
|
||||
return ch == '_'
|
||||
}
|
83
internal/argh/scanner_test.go
Normal file
83
internal/argh/scanner_test.go
Normal file
@@ -0,0 +1,83 @@
|
||||
package argh
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func BenchmarkScannerPOSIXyScannerScan(b *testing.B) {
|
||||
for i := 0; i < b.N; i++ {
|
||||
scanner := NewScanner(strings.NewReader(strings.Join([]string{
|
||||
"walrus",
|
||||
"-what",
|
||||
"--ball=awesome",
|
||||
"--elapsed",
|
||||
"carrot cake",
|
||||
}, string(nul))), nil)
|
||||
for {
|
||||
tok, _, _ := scanner.Scan()
|
||||
if tok == EOL {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestScannerPOSIXyScanner(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
argv []string
|
||||
expectedTokens []Token
|
||||
expectedLiterals []string
|
||||
expectedPositions []Pos
|
||||
}{
|
||||
{
|
||||
name: "simple",
|
||||
argv: []string{"walrus", "-cake", "--corn-dog", "awkward"},
|
||||
expectedTokens: []Token{
|
||||
IDENT,
|
||||
ARG_DELIMITER,
|
||||
COMPOUND_SHORT_FLAG,
|
||||
ARG_DELIMITER,
|
||||
LONG_FLAG,
|
||||
ARG_DELIMITER,
|
||||
IDENT,
|
||||
EOL,
|
||||
},
|
||||
expectedLiterals: []string{
|
||||
"walrus", string(nul), "-cake", string(nul), "--corn-dog", string(nul), "awkward", "",
|
||||
},
|
||||
expectedPositions: []Pos{
|
||||
6, 7, 12, 13, 23, 24, 31, 32,
|
||||
},
|
||||
},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
r := require.New(t)
|
||||
|
||||
scanner := NewScanner(strings.NewReader(strings.Join(tc.argv, string(nul))), nil)
|
||||
|
||||
actualTokens := []Token{}
|
||||
actualLiterals := []string{}
|
||||
actualPositions := []Pos{}
|
||||
|
||||
for {
|
||||
tok, lit, pos := scanner.Scan()
|
||||
|
||||
actualTokens = append(actualTokens, tok)
|
||||
actualLiterals = append(actualLiterals, lit)
|
||||
actualPositions = append(actualPositions, pos)
|
||||
|
||||
if tok == EOL {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
r.Equal(tc.expectedTokens, actualTokens)
|
||||
r.Equal(tc.expectedLiterals, actualLiterals)
|
||||
r.Equal(tc.expectedPositions, actualPositions)
|
||||
})
|
||||
}
|
||||
}
|
53
internal/argh/token.go
Normal file
53
internal/argh/token.go
Normal file
@@ -0,0 +1,53 @@
|
||||
//go:generate stringer -type Token
|
||||
|
||||
package argh
|
||||
|
||||
import "fmt"
|
||||
|
||||
const (
|
||||
ILLEGAL Token = iota
|
||||
EOL
|
||||
EMPTY // ''
|
||||
BS // ' ' '\t' '\n'
|
||||
IDENT // char group without flag prefix: 'some' 'words'
|
||||
ARG_DELIMITER // rune(0)
|
||||
ASSIGN // '='
|
||||
MULTI_VALUE_DELIMITER // ','
|
||||
LONG_FLAG // char group with double flag prefix: '--flag'
|
||||
SHORT_FLAG // single char with single flag prefix: '-f'
|
||||
COMPOUND_SHORT_FLAG // char group with single flag prefix: '-flag'
|
||||
STDIN_FLAG // '-'
|
||||
STOP_FLAG // '--'
|
||||
|
||||
nul = rune(0)
|
||||
eol = rune(-1)
|
||||
)
|
||||
|
||||
type Token int
|
||||
|
||||
// Position is adapted from go/token.Position
|
||||
type Position struct {
|
||||
Column int
|
||||
}
|
||||
|
||||
func (p *Position) IsValid() bool { return p.Column > 0 }
|
||||
|
||||
func (p Position) String() string {
|
||||
s := ""
|
||||
if p.IsValid() {
|
||||
s = fmt.Sprintf("%d", p.Column)
|
||||
}
|
||||
if s == "" {
|
||||
s = "-"
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// Pos is borrowed from go/token.Pos
|
||||
type Pos int
|
||||
|
||||
const NoPos Pos = 0
|
||||
|
||||
func (p Pos) IsValid() bool {
|
||||
return p != NoPos
|
||||
}
|
35
internal/argh/token_string.go
Normal file
35
internal/argh/token_string.go
Normal file
@@ -0,0 +1,35 @@
|
||||
// Code generated by "stringer -type Token"; DO NOT EDIT.
|
||||
|
||||
package argh
|
||||
|
||||
import "strconv"
|
||||
|
||||
func _() {
|
||||
// An "invalid array index" compiler error signifies that the constant values have changed.
|
||||
// Re-run the stringer command to generate them again.
|
||||
var x [1]struct{}
|
||||
_ = x[ILLEGAL-0]
|
||||
_ = x[EOL-1]
|
||||
_ = x[EMPTY-2]
|
||||
_ = x[BS-3]
|
||||
_ = x[IDENT-4]
|
||||
_ = x[ARG_DELIMITER-5]
|
||||
_ = x[ASSIGN-6]
|
||||
_ = x[MULTI_VALUE_DELIMITER-7]
|
||||
_ = x[LONG_FLAG-8]
|
||||
_ = x[SHORT_FLAG-9]
|
||||
_ = x[COMPOUND_SHORT_FLAG-10]
|
||||
_ = x[STDIN_FLAG-11]
|
||||
_ = x[STOP_FLAG-12]
|
||||
}
|
||||
|
||||
const _Token_name = "ILLEGALEOLEMPTYBSIDENTARG_DELIMITERASSIGNMULTI_VALUE_DELIMITERLONG_FLAGSHORT_FLAGCOMPOUND_SHORT_FLAGSTDIN_FLAGSTOP_FLAG"
|
||||
|
||||
var _Token_index = [...]uint8{0, 7, 10, 15, 17, 22, 35, 41, 62, 71, 81, 100, 110, 119}
|
||||
|
||||
func (i Token) String() string {
|
||||
if i < 0 || i >= Token(len(_Token_index)-1) {
|
||||
return "Token(" + strconv.FormatInt(int64(i), 10) + ")"
|
||||
}
|
||||
return _Token_name[_Token_index[i]:_Token_index[i+1]]
|
||||
}
|
@@ -155,7 +155,7 @@ func main() {
|
||||
},
|
||||
&cli.StringSliceFlag{
|
||||
Name: "packages",
|
||||
Value: cli.NewStringSlice("cli", "altsrc", "internal/build"),
|
||||
Value: cli.NewStringSlice("cli", "internal/build", "internal/argh"),
|
||||
},
|
||||
},
|
||||
}
|
||||
@@ -500,14 +500,9 @@ func GenerateActionFunc(cCtx *cli.Context) error {
|
||||
return err
|
||||
}
|
||||
|
||||
altsrcDocs, err := sh("go", "doc", "-all", filepath.Join(top, "altsrc"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := os.WriteFile(
|
||||
filepath.Join(top, "godoc-current.txt"),
|
||||
[]byte(cliDocs+altsrcDocs),
|
||||
[]byte(cliDocs),
|
||||
0644,
|
||||
); err != nil {
|
||||
return err
|
||||
|
357
testdata/godoc-v3.x.txt
vendored
357
testdata/godoc-v3.x.txt
vendored
@@ -292,8 +292,6 @@ type App struct {
|
||||
OnUsageError OnUsageErrorFunc
|
||||
// Execute this function when an invalid flag is accessed from the context
|
||||
InvalidFlagAccessHandler InvalidFlagAccessFunc
|
||||
// Compilation date
|
||||
Compiled time.Time
|
||||
// List of all authors who contributed
|
||||
Authors []*Author
|
||||
// Copyright of the binary if any
|
||||
@@ -2313,358 +2311,3 @@ type VisibleFlagCategory interface {
|
||||
}
|
||||
VisibleFlagCategory is a category containing flags.
|
||||
|
||||
package altsrc // import "github.com/urfave/cli/v3/altsrc"
|
||||
|
||||
|
||||
FUNCTIONS
|
||||
|
||||
func ApplyInputSourceValues(cCtx *cli.Context, inputSourceContext InputSourceContext, flags []cli.Flag) error
|
||||
ApplyInputSourceValues iterates over all provided flags and executes
|
||||
ApplyInputSourceValue on flags implementing the FlagInputSourceExtension
|
||||
interface to initialize these flags to an alternate input source.
|
||||
|
||||
func InitInputSource(flags []cli.Flag, createInputSource func() (InputSourceContext, error)) cli.BeforeFunc
|
||||
InitInputSource is used to to setup an InputSourceContext on a cli.Command
|
||||
Before method. It will create a new input source based on the func provided.
|
||||
If there is no error it will then apply the new input source to any flags
|
||||
that are supported by the input source
|
||||
|
||||
func InitInputSourceWithContext(flags []cli.Flag, createInputSource func(cCtx *cli.Context) (InputSourceContext, error)) cli.BeforeFunc
|
||||
InitInputSourceWithContext is used to to setup an InputSourceContext on
|
||||
a cli.Command Before method. It will create a new input source based on
|
||||
the func provided with potentially using existing cli.Context values to
|
||||
initialize itself. If there is no error it will then apply the new input
|
||||
source to any flags that are supported by the input source
|
||||
|
||||
func NewJSONSourceFromFlagFunc(flag string) func(c *cli.Context) (InputSourceContext, error)
|
||||
NewJSONSourceFromFlagFunc returns a func that takes a cli.Context and
|
||||
returns an InputSourceContext suitable for retrieving config variables from
|
||||
a file containing JSON data with the file name defined by the given flag.
|
||||
|
||||
func NewTomlSourceFromFlagFunc(flagFileName string) func(cCtx *cli.Context) (InputSourceContext, error)
|
||||
NewTomlSourceFromFlagFunc creates a new TOML InputSourceContext from a
|
||||
provided flag name and source context.
|
||||
|
||||
func NewYamlSourceFromFlagFunc(flagFileName string) func(cCtx *cli.Context) (InputSourceContext, error)
|
||||
NewYamlSourceFromFlagFunc creates a new Yaml InputSourceContext from a
|
||||
provided flag name and source context.
|
||||
|
||||
|
||||
TYPES
|
||||
|
||||
type BoolFlag struct {
|
||||
*cli.BoolFlag
|
||||
// Has unexported fields.
|
||||
}
|
||||
BoolFlag is the flag type that wraps cli.BoolFlag to allow for other values
|
||||
to be specified
|
||||
|
||||
func NewBoolFlag(fl *cli.BoolFlag) *BoolFlag
|
||||
NewBoolFlag creates a new BoolFlag
|
||||
|
||||
func (f *BoolFlag) Apply(set *flag.FlagSet) error
|
||||
Apply saves the flagSet for later usage calls, then calls the wrapped
|
||||
BoolFlag.Apply
|
||||
|
||||
func (f *BoolFlag) ApplyInputSourceValue(cCtx *cli.Context, isc InputSourceContext) error
|
||||
ApplyInputSourceValue applies a Bool value to the flagSet if required
|
||||
|
||||
type DurationFlag struct {
|
||||
*cli.DurationFlag
|
||||
// Has unexported fields.
|
||||
}
|
||||
DurationFlag is the flag type that wraps cli.DurationFlag to allow for other
|
||||
values to be specified
|
||||
|
||||
func NewDurationFlag(fl *cli.DurationFlag) *DurationFlag
|
||||
NewDurationFlag creates a new DurationFlag
|
||||
|
||||
func (f *DurationFlag) Apply(set *flag.FlagSet) error
|
||||
Apply saves the flagSet for later usage calls, then calls the wrapped
|
||||
DurationFlag.Apply
|
||||
|
||||
func (f *DurationFlag) ApplyInputSourceValue(cCtx *cli.Context, isc InputSourceContext) error
|
||||
ApplyInputSourceValue applies a Duration value to the flagSet if required
|
||||
|
||||
type FlagInputSourceExtension interface {
|
||||
cli.Flag
|
||||
ApplyInputSourceValue(cCtx *cli.Context, isc InputSourceContext) error
|
||||
}
|
||||
FlagInputSourceExtension is an extension interface of cli.Flag that allows a
|
||||
value to be set on the existing parsed flags.
|
||||
|
||||
type Float64Flag struct {
|
||||
*cli.Float64Flag
|
||||
// Has unexported fields.
|
||||
}
|
||||
Float64Flag is the flag type that wraps cli.Float64Flag to allow for other
|
||||
values to be specified
|
||||
|
||||
func NewFloat64Flag(fl *cli.Float64Flag) *Float64Flag
|
||||
NewFloat64Flag creates a new Float64Flag
|
||||
|
||||
func (f *Float64Flag) Apply(set *flag.FlagSet) error
|
||||
Apply saves the flagSet for later usage calls, then calls the wrapped
|
||||
Float64Flag.Apply
|
||||
|
||||
func (f *Float64Flag) ApplyInputSourceValue(cCtx *cli.Context, isc InputSourceContext) error
|
||||
ApplyInputSourceValue applies a Float64 value to the flagSet if required
|
||||
|
||||
type Float64SliceFlag struct {
|
||||
*cli.Float64SliceFlag
|
||||
// Has unexported fields.
|
||||
}
|
||||
Float64SliceFlag is the flag type that wraps cli.Float64SliceFlag to allow
|
||||
for other values to be specified
|
||||
|
||||
func NewFloat64SliceFlag(fl *cli.Float64SliceFlag) *Float64SliceFlag
|
||||
NewFloat64SliceFlag creates a new Float64SliceFlag
|
||||
|
||||
func (f *Float64SliceFlag) Apply(set *flag.FlagSet) error
|
||||
Apply saves the flagSet for later usage calls, then calls the wrapped
|
||||
Float64SliceFlag.Apply
|
||||
|
||||
type GenericFlag struct {
|
||||
*cli.GenericFlag
|
||||
// Has unexported fields.
|
||||
}
|
||||
GenericFlag is the flag type that wraps cli.GenericFlag to allow for other
|
||||
values to be specified
|
||||
|
||||
func NewGenericFlag(fl *cli.GenericFlag) *GenericFlag
|
||||
NewGenericFlag creates a new GenericFlag
|
||||
|
||||
func (f *GenericFlag) Apply(set *flag.FlagSet) error
|
||||
Apply saves the flagSet for later usage calls, then calls the wrapped
|
||||
GenericFlag.Apply
|
||||
|
||||
func (f *GenericFlag) ApplyInputSourceValue(cCtx *cli.Context, isc InputSourceContext) error
|
||||
ApplyInputSourceValue applies a generic value to the flagSet if required
|
||||
|
||||
type InputSourceContext interface {
|
||||
Source() string
|
||||
|
||||
Int(name string) (int, error)
|
||||
Duration(name string) (time.Duration, error)
|
||||
Float64(name string) (float64, error)
|
||||
String(name string) (string, error)
|
||||
StringSlice(name string) ([]string, error)
|
||||
IntSlice(name string) ([]int, error)
|
||||
Int64Slice(name string) ([]int64, error)
|
||||
Generic(name string) (cli.Generic, error)
|
||||
Bool(name string) (bool, error)
|
||||
|
||||
// Has unexported methods.
|
||||
}
|
||||
InputSourceContext is an interface used to allow other input sources to be
|
||||
implemented as needed.
|
||||
|
||||
Source returns an identifier for the input source. In case of file source it
|
||||
should return path to the file.
|
||||
|
||||
func NewJSONSource(data []byte) (InputSourceContext, error)
|
||||
NewJSONSource returns an InputSourceContext suitable for retrieving config
|
||||
variables from raw JSON data.
|
||||
|
||||
func NewJSONSourceFromFile(f string) (InputSourceContext, error)
|
||||
NewJSONSourceFromFile returns an InputSourceContext suitable for retrieving
|
||||
config variables from a file (or url) containing JSON data.
|
||||
|
||||
func NewJSONSourceFromReader(r io.Reader) (InputSourceContext, error)
|
||||
NewJSONSourceFromReader returns an InputSourceContext suitable for
|
||||
retrieving config variables from an io.Reader that returns JSON data.
|
||||
|
||||
func NewTomlSourceFromFile(file string) (InputSourceContext, error)
|
||||
NewTomlSourceFromFile creates a new TOML InputSourceContext from a filepath.
|
||||
|
||||
func NewYamlSourceFromFile(file string) (InputSourceContext, error)
|
||||
NewYamlSourceFromFile creates a new Yaml InputSourceContext from a filepath.
|
||||
|
||||
type Int64Flag struct {
|
||||
*cli.Int64Flag
|
||||
// Has unexported fields.
|
||||
}
|
||||
Int64Flag is the flag type that wraps cli.Int64Flag to allow for other
|
||||
values to be specified
|
||||
|
||||
func NewInt64Flag(fl *cli.Int64Flag) *Int64Flag
|
||||
NewInt64Flag creates a new Int64Flag
|
||||
|
||||
func (f *Int64Flag) Apply(set *flag.FlagSet) error
|
||||
Apply saves the flagSet for later usage calls, then calls the wrapped
|
||||
Int64Flag.Apply
|
||||
|
||||
type Int64SliceFlag struct {
|
||||
*cli.Int64SliceFlag
|
||||
// Has unexported fields.
|
||||
}
|
||||
Int64SliceFlag is the flag type that wraps cli.Int64SliceFlag to allow for
|
||||
other values to be specified
|
||||
|
||||
func NewInt64SliceFlag(fl *cli.Int64SliceFlag) *Int64SliceFlag
|
||||
NewInt64SliceFlag creates a new Int64SliceFlag
|
||||
|
||||
func (f *Int64SliceFlag) Apply(set *flag.FlagSet) error
|
||||
Apply saves the flagSet for later usage calls, then calls the wrapped
|
||||
Int64SliceFlag.Apply
|
||||
|
||||
func (f *Int64SliceFlag) ApplyInputSourceValue(cCtx *cli.Context, isc InputSourceContext) error
|
||||
ApplyInputSourceValue applies a Int64Slice value if required
|
||||
|
||||
type IntFlag struct {
|
||||
*cli.IntFlag
|
||||
// Has unexported fields.
|
||||
}
|
||||
IntFlag is the flag type that wraps cli.IntFlag to allow for other values to
|
||||
be specified
|
||||
|
||||
func NewIntFlag(fl *cli.IntFlag) *IntFlag
|
||||
NewIntFlag creates a new IntFlag
|
||||
|
||||
func (f *IntFlag) Apply(set *flag.FlagSet) error
|
||||
Apply saves the flagSet for later usage calls, then calls the wrapped
|
||||
IntFlag.Apply
|
||||
|
||||
func (f *IntFlag) ApplyInputSourceValue(cCtx *cli.Context, isc InputSourceContext) error
|
||||
ApplyInputSourceValue applies a int value to the flagSet if required
|
||||
|
||||
type IntSliceFlag struct {
|
||||
*cli.IntSliceFlag
|
||||
// Has unexported fields.
|
||||
}
|
||||
IntSliceFlag is the flag type that wraps cli.IntSliceFlag to allow for other
|
||||
values to be specified
|
||||
|
||||
func NewIntSliceFlag(fl *cli.IntSliceFlag) *IntSliceFlag
|
||||
NewIntSliceFlag creates a new IntSliceFlag
|
||||
|
||||
func (f *IntSliceFlag) Apply(set *flag.FlagSet) error
|
||||
Apply saves the flagSet for later usage calls, then calls the wrapped
|
||||
IntSliceFlag.Apply
|
||||
|
||||
func (f *IntSliceFlag) ApplyInputSourceValue(cCtx *cli.Context, isc InputSourceContext) error
|
||||
ApplyInputSourceValue applies a IntSlice value if required
|
||||
|
||||
type MapInputSource struct {
|
||||
// Has unexported fields.
|
||||
}
|
||||
MapInputSource implements InputSourceContext to return data from the map
|
||||
that is loaded.
|
||||
|
||||
func NewMapInputSource(file string, valueMap map[interface{}]interface{}) *MapInputSource
|
||||
NewMapInputSource creates a new MapInputSource for implementing custom input
|
||||
sources.
|
||||
|
||||
func (fsm *MapInputSource) Bool(name string) (bool, error)
|
||||
Bool returns an bool from the map otherwise returns false
|
||||
|
||||
func (fsm *MapInputSource) Duration(name string) (time.Duration, error)
|
||||
Duration returns a duration from the map if it exists otherwise returns 0
|
||||
|
||||
func (fsm *MapInputSource) Float64(name string) (float64, error)
|
||||
Float64 returns an float64 from the map if it exists otherwise returns 0
|
||||
|
||||
func (fsm *MapInputSource) Generic(name string) (cli.Generic, error)
|
||||
Generic returns an cli.Generic from the map if it exists otherwise returns
|
||||
nil
|
||||
|
||||
func (fsm *MapInputSource) Int(name string) (int, error)
|
||||
Int returns an int from the map if it exists otherwise returns 0
|
||||
|
||||
func (fsm *MapInputSource) Int64Slice(name string) ([]int64, error)
|
||||
Int64Slice returns an []int64 from the map if it exists otherwise returns
|
||||
nil
|
||||
|
||||
func (fsm *MapInputSource) IntSlice(name string) ([]int, error)
|
||||
IntSlice returns an []int from the map if it exists otherwise returns nil
|
||||
|
||||
func (fsm *MapInputSource) Source() string
|
||||
Source returns the path of the source file
|
||||
|
||||
func (fsm *MapInputSource) String(name string) (string, error)
|
||||
String returns a string from the map if it exists otherwise returns an empty
|
||||
string
|
||||
|
||||
func (fsm *MapInputSource) StringSlice(name string) ([]string, error)
|
||||
StringSlice returns an []string from the map if it exists otherwise returns
|
||||
nil
|
||||
|
||||
type PathFlag struct {
|
||||
*cli.PathFlag
|
||||
// Has unexported fields.
|
||||
}
|
||||
PathFlag is the flag type that wraps cli.PathFlag to allow for other values
|
||||
to be specified
|
||||
|
||||
func NewPathFlag(fl *cli.PathFlag) *PathFlag
|
||||
NewPathFlag creates a new PathFlag
|
||||
|
||||
func (f *PathFlag) Apply(set *flag.FlagSet) error
|
||||
Apply saves the flagSet for later usage calls, then calls the wrapped
|
||||
PathFlag.Apply
|
||||
|
||||
func (f *PathFlag) ApplyInputSourceValue(cCtx *cli.Context, isc InputSourceContext) error
|
||||
ApplyInputSourceValue applies a Path value to the flagSet if required
|
||||
|
||||
type StringFlag struct {
|
||||
*cli.StringFlag
|
||||
// Has unexported fields.
|
||||
}
|
||||
StringFlag is the flag type that wraps cli.StringFlag to allow for other
|
||||
values to be specified
|
||||
|
||||
func NewStringFlag(fl *cli.StringFlag) *StringFlag
|
||||
NewStringFlag creates a new StringFlag
|
||||
|
||||
func (f *StringFlag) Apply(set *flag.FlagSet) error
|
||||
Apply saves the flagSet for later usage calls, then calls the wrapped
|
||||
StringFlag.Apply
|
||||
|
||||
func (f *StringFlag) ApplyInputSourceValue(cCtx *cli.Context, isc InputSourceContext) error
|
||||
ApplyInputSourceValue applies a String value to the flagSet if required
|
||||
|
||||
type StringSliceFlag struct {
|
||||
*cli.StringSliceFlag
|
||||
// Has unexported fields.
|
||||
}
|
||||
StringSliceFlag is the flag type that wraps cli.StringSliceFlag to allow for
|
||||
other values to be specified
|
||||
|
||||
func NewStringSliceFlag(fl *cli.StringSliceFlag) *StringSliceFlag
|
||||
NewStringSliceFlag creates a new StringSliceFlag
|
||||
|
||||
func (f *StringSliceFlag) Apply(set *flag.FlagSet) error
|
||||
Apply saves the flagSet for later usage calls, then calls the wrapped
|
||||
StringSliceFlag.Apply
|
||||
|
||||
func (f *StringSliceFlag) ApplyInputSourceValue(cCtx *cli.Context, isc InputSourceContext) error
|
||||
ApplyInputSourceValue applies a StringSlice value to the flagSet if required
|
||||
|
||||
type Uint64Flag struct {
|
||||
*cli.Uint64Flag
|
||||
// Has unexported fields.
|
||||
}
|
||||
Uint64Flag is the flag type that wraps cli.Uint64Flag to allow for other
|
||||
values to be specified
|
||||
|
||||
func NewUint64Flag(fl *cli.Uint64Flag) *Uint64Flag
|
||||
NewUint64Flag creates a new Uint64Flag
|
||||
|
||||
func (f *Uint64Flag) Apply(set *flag.FlagSet) error
|
||||
Apply saves the flagSet for later usage calls, then calls the wrapped
|
||||
Uint64Flag.Apply
|
||||
|
||||
type UintFlag struct {
|
||||
*cli.UintFlag
|
||||
// Has unexported fields.
|
||||
}
|
||||
UintFlag is the flag type that wraps cli.UintFlag to allow for other values
|
||||
to be specified
|
||||
|
||||
func NewUintFlag(fl *cli.UintFlag) *UintFlag
|
||||
NewUintFlag creates a new UintFlag
|
||||
|
||||
func (f *UintFlag) Apply(set *flag.FlagSet) error
|
||||
Apply saves the flagSet for later usage calls, then calls the wrapped
|
||||
UintFlag.Apply
|
||||
|
||||
|
Reference in New Issue
Block a user