TUN-3964: Revert "TUN-3922: Repoint urfave/cli/v2 library at patched branch at github.com/ipostelnik/cli/v2@fixed which correctly handles reading flags declared at multiple levels of subcommands."

This reverts commit 1670ee87fb.
This commit is contained in:
cthuang 2021-02-23 12:23:57 +00:00 committed by Chung Ting Huang
parent e9c2afec56
commit 9d5bd256be
37 changed files with 274 additions and 307 deletions

2
go.mod
View File

@ -2,8 +2,6 @@ module github.com/cloudflare/cloudflared
go 1.15
replace github.com/urfave/cli/v2 => github.com/ipostelnik/cli/v2 v2.3.1-0.20210212191405-2b6ed1f5ef69
require (
github.com/certifi/gocertifi v0.0.0-20200211180108-c7c1fbc02894 // indirect
github.com/cloudflare/brotli-go v0.0.0-20191101163834-d34379f7ff93

3
go.sum
View File

@ -350,8 +350,6 @@ github.com/imdario/mergo v0.3.9/go.mod h1:2EnlNZ0deacrJVfApfmtdGgDfMuh/nq6Ok1EcJ
github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8=
github.com/influxdata/influxdb1-client v0.0.0-20191209144304-8bf82d3c094d/go.mod h1:qj24IKcXYK6Iy9ceXlo3Tc+vtHo9lIhSX5JddghvEPo=
github.com/infobloxopen/go-trees v0.0.0-20190313150506-2af4e13f9062/go.mod h1:PcNJqIlcX/dj3DTG/+QQnRvSgTMG6CLpRMjWcv4+J6w=
github.com/ipostelnik/cli/v2 v2.3.1-0.20210212191405-2b6ed1f5ef69 h1:TuZfNu8oRuQr6Y8UIvQlpXq+G+SzytMUGx8NrBt+2jg=
github.com/ipostelnik/cli/v2 v2.3.1-0.20210212191405-2b6ed1f5ef69/go.mod h1:LJmUH05zAU44vOAcrfzZQKsZbVcdbOG8rtL3/XcUArI=
github.com/jimstudt/http-authentication v0.0.0-20140401203705-3eca13d6893a/go.mod h1:wK6yTYYcgjHE1Z1QtXACPDjcFJyBskHEdagmnq3vsP8=
github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af/go.mod h1:Nht3zPeWKUH0NzdCt2Blrr5ys8VGpn0CEB0cQHVjt7k=
github.com/jmespath/go-jmespath v0.3.0 h1:OS12ieG61fsCg5+qLJ+SsW9NicxNkg3b25OyT2yCeUc=
@ -980,7 +978,6 @@ gopkg.in/warnings.v0 v0.1.2/go.mod h1:jksf8JmL6Qr/oQM2OXTHunEvvTAsrWBLb6OOjuVWRN
gopkg.in/yaml.v2 v2.0.0-20170812160011-eb3733d160e7/go.mod h1:JAlM8MvJe8wmxCU4Bli9HhUf9+ttbYbLASfIpnQbh74=
gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.3/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.5/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.7/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=

View File

@ -1,7 +1,7 @@
cli
===
[![GoDoc](https://godoc.org/github.com/urfave/cli?status.svg)](https://pkg.go.dev/github.com/urfave/cli/v2)
[![GoDoc](https://godoc.org/github.com/urfave/cli?status.svg)](https://godoc.org/github.com/urfave/cli)
[![codebeat](https://codebeat.co/badges/0a8f30aa-f975-404b-b878-5fab3ae1cc5f)](https://codebeat.co/projects/github-com-urfave-cli)
[![Go Report Card](https://goreportcard.com/badge/urfave/cli)](https://goreportcard.com/report/urfave/cli)
[![codecov](https://codecov.io/gh/urfave/cli/branch/master/graph/badge.svg)](https://codecov.io/gh/urfave/cli)
@ -17,15 +17,11 @@ Usage documentation exists for each major version. Don't know what version you'r
- `v2` - [./docs/v2/manual.md](./docs/v2/manual.md)
- `v1` - [./docs/v1/manual.md](./docs/v1/manual.md)
Guides for migrating to newer versions:
- `v1-to-v2` - [./docs/migrate-v1-to-v2.md](./docs/migrate-v1-to-v2.md)
## Installation
Using this package requires a working Go environment. [See the install instructions for Go](http://golang.org/doc/install.html).
Make sure you have a working Go environment. Go version 1.11+ is supported. [See the install instructions for Go](http://golang.org/doc/install.html).
Go Modules are required when using this package. [See the go blog guide on using Go Modules](https://blog.golang.org/using-go-modules).
Go Modules are strongly recommended when using this package. [See the go blog guide on using Go Modules](https://blog.golang.org/using-go-modules).
### Using `v2` releases
@ -67,4 +63,4 @@ export PATH=$PATH:$GOPATH/bin
cli is tested against multiple versions of Go on Linux, and against the latest
released version of Go on OS X and Windows. This project uses Github Actions for
builds. To see our currently supported go versions and platforms, look at the [./.github/workflows/cli.yml](https://github.com/urfave/cli/blob/master/.github/workflows/cli.yml).
builds. For more build info, please look at the [./.github/workflows/cli.yml](https://github.com/urfave/cli/blob/master/.github/workflows/cli.yml).

View File

@ -1,6 +0,0 @@
package altsrc
// defaultInputSource creates a default InputSourceContext.
func defaultInputSource() (InputSourceContext, error) {
return &MapInputSource{file: "", valueMap: map[interface{}]interface{}{}}, nil
}

View File

@ -1,45 +0,0 @@
# Only types that provide implementation of FlagInputSourceExtension can be listed here
# please keep list sorted alphabetically
flag_types = [
"Bool",
"Duration",
"Float64",
"Generic",
"Int",
"IntSlice",
"Path",
"String",
"StringSlice",
]
print('''// Code generated by fg.py; DO NOT EDIT.
package altsrc
import (
"flag"
"github.com/urfave/cli/v2"
)''')
for t in flag_types:
print(f'''
// {t}Flag is the flag type that wraps cli.{t}Flag to allow
// for other values to be specified
type {t}Flag struct {{
*cli.{t}Flag
set *flag.FlagSet
}}
var _ FlagInputSourceExtension = (*{t}Flag)(nil)
// New{t}Flag creates a new {t}Flag
func New{t}Flag(fl *cli.{t}Flag) *{t}Flag {{
return &{t}Flag{{{t}Flag: fl, set: nil}}
}}
// Apply saves the flagSet for later usage calls, then calls
// the wrapped {t}Flag.Apply
func (f *{t}Flag) Apply(set *flag.FlagSet) error {{
f.set = set
return f.{t}Flag.Apply(set)
}}''')

View File

@ -1,4 +1,4 @@
// Code generated by fg.py; DO NOT EDIT.
// Code generated by fg; DO NOT EDIT.
package altsrc
@ -14,7 +14,6 @@ type BoolFlag struct {
*cli.BoolFlag
set *flag.FlagSet
}
var _ FlagInputSourceExtension = (*BoolFlag)(nil)
// NewBoolFlag creates a new BoolFlag
func NewBoolFlag(fl *cli.BoolFlag) *BoolFlag {
@ -34,7 +33,6 @@ type DurationFlag struct {
*cli.DurationFlag
set *flag.FlagSet
}
var _ FlagInputSourceExtension = (*DurationFlag)(nil)
// NewDurationFlag creates a new DurationFlag
func NewDurationFlag(fl *cli.DurationFlag) *DurationFlag {
@ -54,7 +52,6 @@ type Float64Flag struct {
*cli.Float64Flag
set *flag.FlagSet
}
var _ FlagInputSourceExtension = (*Float64Flag)(nil)
// NewFloat64Flag creates a new Float64Flag
func NewFloat64Flag(fl *cli.Float64Flag) *Float64Flag {
@ -74,7 +71,6 @@ type GenericFlag struct {
*cli.GenericFlag
set *flag.FlagSet
}
var _ FlagInputSourceExtension = (*GenericFlag)(nil)
// NewGenericFlag creates a new GenericFlag
func NewGenericFlag(fl *cli.GenericFlag) *GenericFlag {
@ -88,13 +84,31 @@ func (f *GenericFlag) Apply(set *flag.FlagSet) error {
return f.GenericFlag.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)
}
// 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
}
var _ FlagInputSourceExtension = (*IntFlag)(nil)
// NewIntFlag creates a new IntFlag
func NewIntFlag(fl *cli.IntFlag) *IntFlag {
@ -114,7 +128,6 @@ type IntSliceFlag struct {
*cli.IntSliceFlag
set *flag.FlagSet
}
var _ FlagInputSourceExtension = (*IntSliceFlag)(nil)
// NewIntSliceFlag creates a new IntSliceFlag
func NewIntSliceFlag(fl *cli.IntSliceFlag) *IntSliceFlag {
@ -128,24 +141,42 @@ func (f *IntSliceFlag) Apply(set *flag.FlagSet) error {
return f.IntSliceFlag.Apply(set)
}
// PathFlag is the flag type that wraps cli.PathFlag to allow
// Int64SliceFlag is the flag type that wraps cli.Int64SliceFlag to allow
// for other values to be specified
type PathFlag struct {
*cli.PathFlag
type Int64SliceFlag struct {
*cli.Int64SliceFlag
set *flag.FlagSet
}
var _ FlagInputSourceExtension = (*PathFlag)(nil)
// NewPathFlag creates a new PathFlag
func NewPathFlag(fl *cli.PathFlag) *PathFlag {
return &PathFlag{PathFlag: fl, set: nil}
// 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 PathFlag.Apply
func (f *PathFlag) Apply(set *flag.FlagSet) error {
// the wrapped Int64SliceFlag.Apply
func (f *Int64SliceFlag) Apply(set *flag.FlagSet) error {
f.set = set
return f.PathFlag.Apply(set)
return f.Int64SliceFlag.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)
}
// StringFlag is the flag type that wraps cli.StringFlag to allow
@ -154,7 +185,6 @@ type StringFlag struct {
*cli.StringFlag
set *flag.FlagSet
}
var _ FlagInputSourceExtension = (*StringFlag)(nil)
// NewStringFlag creates a new StringFlag
func NewStringFlag(fl *cli.StringFlag) *StringFlag {
@ -168,13 +198,31 @@ func (f *StringFlag) Apply(set *flag.FlagSet) error {
return f.StringFlag.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)
}
// 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
}
var _ FlagInputSourceExtension = (*StringSliceFlag)(nil)
// NewStringSliceFlag creates a new StringSliceFlag
func NewStringSliceFlag(fl *cli.StringSliceFlag) *StringSliceFlag {
@ -187,3 +235,41 @@ func (f *StringSliceFlag) Apply(set *flag.FlagSet) error {
f.set = set
return f.StringSliceFlag.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)
}
// 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)
}

View File

@ -17,12 +17,8 @@ import (
// by the given flag.
func NewJSONSourceFromFlagFunc(flag string) func(c *cli.Context) (InputSourceContext, error) {
return func(context *cli.Context) (InputSourceContext, error) {
if context.IsSet(flag) {
return NewJSONSourceFromFile(context.String(flag))
}
return defaultInputSource()
}
}
// NewJSONSourceFromFile returns an InputSourceContext suitable for

View File

@ -16,11 +16,6 @@ type MapInputSource struct {
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.

View File

@ -87,13 +87,9 @@ func NewTomlSourceFromFile(file string) (InputSourceContext, error) {
// NewTomlSourceFromFlagFunc creates a new TOML InputSourceContext from a provided flag name and source context.
func NewTomlSourceFromFlagFunc(flagFileName string) func(context *cli.Context) (InputSourceContext, error) {
return func(context *cli.Context) (InputSourceContext, error) {
if context.IsSet(flagFileName) {
filePath := context.String(flagFileName)
return NewTomlSourceFromFile(filePath)
}
return defaultInputSource()
}
}
func readCommandToml(filePath string, container interface{}) (err error) {

View File

@ -33,13 +33,9 @@ func NewYamlSourceFromFile(file string) (InputSourceContext, error) {
// NewYamlSourceFromFlagFunc creates a new Yaml InputSourceContext from a provided flag name and source context.
func NewYamlSourceFromFlagFunc(flagFileName string) func(context *cli.Context) (InputSourceContext, error) {
return func(context *cli.Context) (InputSourceContext, error) {
if context.IsSet(flagFileName) {
filePath := context.String(flagFileName)
return NewYamlSourceFromFile(filePath)
}
return defaultInputSource()
}
}
func readCommandYaml(filePath string, container interface{}) (err error) {

View File

@ -64,7 +64,7 @@ type App struct {
Action ActionFunc
// Execute this function if the proper command cannot be found
CommandNotFound CommandNotFoundFunc
// Execute this function if a usage error occurs
// Execute this function if an usage error occurs
OnUsageError OnUsageErrorFunc
// Compilation date
Compiled time.Time
@ -72,15 +72,12 @@ type App struct {
Authors []*Author
// Copyright of the binary if any
Copyright string
// Reader reader to write input to (useful for tests)
Reader io.Reader
// Writer writer to write output to
Writer io.Writer
// ErrWriter writes error output
ErrWriter io.Writer
// ExitErrHandler processes any error encountered while running an App before
// it is returned to the caller. If no function is provided, HandleExitCoder
// is used as the default behavior.
// Execute this function to handle ExitErrors. If not provided, HandleExitCoder is provided to
// function as a default, so this is optional.
ExitErrHandler ExitErrHandlerFunc
// Other custom info
Metadata map[string]interface{}
@ -119,9 +116,7 @@ func NewApp() *App {
BashComplete: DefaultAppComplete,
Action: helpCommand.Action,
Compiled: compileTime(),
Reader: os.Stdin,
Writer: os.Stdout,
ErrWriter: os.Stderr,
}
}
@ -140,7 +135,7 @@ func (a *App) Setup() {
}
if a.HelpName == "" {
a.HelpName = a.Name
a.HelpName = filepath.Base(os.Args[0])
}
if a.Usage == "" {
@ -163,18 +158,10 @@ func (a *App) Setup() {
a.Compiled = compileTime()
}
if a.Reader == nil {
a.Reader = os.Stdin
}
if a.Writer == nil {
a.Writer = os.Stdout
}
if a.ErrWriter == nil {
a.ErrWriter = os.Stderr
}
var newCommands []*Command
for _, c := range a.Commands {
@ -208,6 +195,10 @@ func (a *App) Setup() {
if a.Metadata == nil {
a.Metadata = make(map[string]interface{})
}
if a.Writer == nil {
a.Writer = os.Stdout
}
}
func (a *App) newFlagSet() (*flag.FlagSet, error) {
@ -299,6 +290,8 @@ func (a *App) RunContext(ctx context.Context, arguments []string) (err error) {
if a.Before != nil {
beforeErr := a.Before(context)
if beforeErr != nil {
_, _ = fmt.Fprintf(a.Writer, "%v\n\n", beforeErr)
_ = ShowAppHelp(context)
a.handleExitCoder(context, beforeErr)
err = beforeErr
return err
@ -328,11 +321,11 @@ func (a *App) RunContext(ctx context.Context, arguments []string) (err error) {
// RunAndExitOnError calls .Run() and exits non-zero if an error was returned
//
// Deprecated: instead you should return an error that fulfills cli.ExitCoder
// to cli.App.Run. This will cause the application to exit with the given error
// to cli.App.Run. This will cause the application to exit with the given eror
// code in the cli.ExitCoder
func (a *App) RunAndExitOnError() {
if err := a.Run(os.Args); err != nil {
_, _ = fmt.Fprintln(a.ErrWriter, err)
_, _ = fmt.Fprintln(a.errWriter(), err)
OsExiter(1)
}
}
@ -486,6 +479,15 @@ func (a *App) VisibleFlags() []Flag {
return visibleFlags(a.Flags)
}
func (a *App) errWriter() io.Writer {
// When the app ErrWriter is nil use the package level one.
if a.ErrWriter == nil {
return ErrWriter
}
return a.ErrWriter
}
func (a *App) appendFlag(fl Flag) {
if !hasFlag(a.Flags, fl) {
a.Flags = append(a.Flags, fl)

View File

@ -150,6 +150,7 @@ func (c *Command) Run(ctx *Context) (err error) {
if c.Before != nil {
err = c.Before(context)
if err != nil {
_ = ShowCommandHelp(context, c.Name)
context.App.handleExitCoder(context, err)
return err
}
@ -241,9 +242,8 @@ func (c *Command) startApp(ctx *Context) error {
app.HideHelpCommand = c.HideHelpCommand
app.Version = ctx.App.Version
app.HideVersion = true
app.HideVersion = ctx.App.HideVersion
app.Compiled = ctx.App.Compiled
app.Reader = ctx.App.Reader
app.Writer = ctx.App.Writer
app.ErrWriter = ctx.App.ErrWriter
app.ExitErrHandler = ctx.App.ExitErrHandler

View File

@ -18,7 +18,6 @@ type Context struct {
Command *Command
shellComplete bool
flagSet *flag.FlagSet
fromFlagSet map[string]bool
parentContext *Context
}
@ -33,14 +32,6 @@ func NewContext(app *App, set *flag.FlagSet, parentCtx *Context) *Context {
}
}
// pre-compute flag seen on the command line at this context
c.fromFlagSet = make(map[string]bool)
if set != nil {
set.Visit(func(f *flag.Flag) {
c.fromFlagSet[f.Name] = true
})
}
c.Command = &Command{}
if c.Context == nil {
@ -57,47 +48,33 @@ func (c *Context) NumFlags() int {
// Set sets a context flag to a value.
func (c *Context) Set(name, value string) error {
err := c.flagSet.Set(name, value)
if err == nil {
c.fromFlagSet[name] = true
}
return err
return c.flagSet.Set(name, value)
}
// IsSet determines if the flag was actually set
func (c *Context) IsSet(name string) bool {
for ctx := c; ctx != nil; ctx = ctx.parentContext {
// try flags parsed from command line first
if ctx.flagSet.Lookup(name) == nil {
// flag not defined in this context
continue
if fs := lookupFlagSet(name, c); fs != nil {
if fs := lookupFlagSet(name, c); fs != nil {
isSet := false
fs.Visit(func(f *flag.Flag) {
if f.Name == name {
isSet = true
}
if ctx.flagOnCommandLine(name) {
return true
}
// now see if value was set externally via environment
definedFlags := ctx.Command.Flags
if ctx.Command.Name == "" && ctx.App != nil {
definedFlags = ctx.App.Flags
}
for _, ff := range definedFlags {
for _, fn := range ff.Names() {
if fn == name {
if ff.IsSet() {
})
if isSet {
return true
}
}
}
}
}
f := lookupFlag(name, c)
if f == nil {
return false
}
func (c *Context) flagOnCommandLine(name string) bool {
return c.fromFlagSet[name]
return f.IsSet()
}
return false
}
// LocalFlagNames returns a slice of flag names used in this context.
@ -131,10 +108,7 @@ func (c *Context) Lineage() []*Context {
// Value returns the value of the flag corresponding to `name`
func (c *Context) Value(name string) interface{} {
if fs := lookupFlagSet(name, c); fs != nil {
return fs.Lookup(name).Value.(flag.Getter).Get()
}
return nil
return c.flagSet.Lookup(name).Value.(flag.Getter).Get()
}
// Args returns the command line arguments associated with the context.
@ -176,25 +150,6 @@ func lookupFlag(name string, ctx *Context) Flag {
return nil
}
func (c *Context) resolveFlagDeep(name string) *flag.Flag {
var src *flag.Flag
for cur := c; cur != nil; cur = cur.parentContext {
if f := cur.flagSet.Lookup(name); f != nil {
if cur.flagOnCommandLine(name) {
// we've found most specific instance on command line, use it
src = f
break
}
if src == nil {
// flag was defined, but value is not present among flags of the current context
// remember the most specific instance of the flag not from command line as fallback
src = f
}
}
}
return src
}
func lookupFlagSet(name string, ctx *Context) *flag.FlagSet {
for _, c := range ctx.Lineage() {
if f := c.flagSet.Lookup(name); f != nil {

View File

@ -15,39 +15,31 @@ import (
// The function errors if either parsing or writing of the string fails.
func (a *App) ToMarkdown() (string, error) {
var w bytes.Buffer
if err := a.writeDocTemplate(&w, 8); err != nil {
if err := a.writeDocTemplate(&w); err != nil {
return "", err
}
return w.String(), nil
}
// ToMan creates a man page string with section number for the `*App`
// ToMan creates a man page string for the `*App`
// The function errors if either parsing or writing of the string fails.
func (a *App) ToManWithSection(sectionNumber int) (string, error) {
func (a *App) ToMan() (string, error) {
var w bytes.Buffer
if err := a.writeDocTemplate(&w, sectionNumber); err != nil {
if err := a.writeDocTemplate(&w); err != nil {
return "", err
}
man := md2man.Render(w.Bytes())
return string(man), nil
}
// ToMan creates a man page string for the `*App`
// The function errors if either parsing or writing of the string fails.
func (a *App) ToMan() (string, error) {
man, err := a.ToManWithSection(8)
return man, err
}
type cliTemplate struct {
App *App
SectionNum int
Commands []string
GlobalArgs []string
SynopsisArgs []string
}
func (a *App) writeDocTemplate(w io.Writer, sectionNum int) error {
func (a *App) writeDocTemplate(w io.Writer) error {
const name = "cli"
t, err := template.New(name).Parse(MarkdownDocTemplate)
if err != nil {
@ -55,7 +47,6 @@ func (a *App) writeDocTemplate(w io.Writer, sectionNum int) error {
}
return t.ExecuteTemplate(w, name, &cliTemplate{
App: a,
SectionNum: sectionNum,
Commands: prepareCommands(a.Commands, 0),
GlobalArgs: prepareArgsWithValues(a.VisibleFlags()),
SynopsisArgs: prepareArgsSynopsis(a.VisibleFlags()),

View File

@ -17,10 +17,11 @@ var ErrWriter io.Writer = os.Stderr
// MultiError is an error that wraps multiple errors.
type MultiError interface {
error
// Errors returns a copy of the errors slice
Errors() []error
}
// newMultiError creates a new MultiError. Pass in one or more errors.
// NewMultiError creates a new MultiError. Pass in one or more errors.
func newMultiError(err ...error) MultiError {
ret := multiError(err)
return &ret
@ -64,20 +65,13 @@ type exitError struct {
message interface{}
}
// NewExitError calls Exit to create a new ExitCoder.
//
// Deprecated: This function is a duplicate of Exit and will eventually be removed.
// NewExitError makes a new *exitError
func NewExitError(message interface{}, exitCode int) ExitCoder {
return Exit(message, exitCode)
}
// Exit wraps a message and exit code into an error, which by default is
// handled with a call to os.Exit during default error handling.
//
// This is the simplest way to trigger a non-zero exit code for an App without
// having to call os.Exit manually. During testing, this behavior can be avoided
// by overiding the ExitErrHandler function on an App or the package-global
// OsExiter function.
// Exit wraps a message and exit code into an ExitCoder suitable for handling by
// HandleExitCoder
func Exit(message interface{}, exitCode int) ExitCoder {
return &exitError{
message: message,
@ -93,14 +87,10 @@ func (ee *exitError) ExitCode() int {
return ee.exitCode
}
// HandleExitCoder handles errors implementing ExitCoder by printing their
// message and calling OsExiter with the given exit code.
//
// If the given error instead implements MultiError, each error will be checked
// for the ExitCoder interface, and OsExiter will be called with the last exit
// code found, or exit code 1 if no ExitCoder is found.
//
// This function is the default error-handling behavior for an App.
// HandleExitCoder checks if the error fulfills the ExitCoder interface, and if
// so prints the error to stderr (if it is non-empty) and calls OsExiter with the
// given exit code. If the given error is a MultiError, then this func is
// called on all members of the Errors slice and calls OsExiter with the last exit code.
func HandleExitCoder(err error) {
if err == nil {
return

View File

@ -171,10 +171,6 @@ func fishAddFileFlag(flag Flag, completion *strings.Builder) {
if f.TakesFile {
return
}
case *PathFlag:
if f.TakesFile {
return
}
}
completion.WriteString(" -f")
}

View File

@ -359,11 +359,7 @@ func stringifySliceFlag(usage string, names, defaultVals []string) string {
}
usageWithDefault := strings.TrimSpace(fmt.Sprintf("%s%s", usage, defaultVal))
multiInputString := "(accepts multiple inputs)"
if usageWithDefault != "" {
multiInputString = "\t" + multiInputString
}
return fmt.Sprintf("%s\t%s%s", prefixedNames(names, placeholder), usageWithDefault, multiInputString)
return fmt.Sprintf("%s\t%s", prefixedNames(names, placeholder), usageWithDefault)
}
func hasFlag(flags []Flag, fl Flag) bool {

View File

@ -87,10 +87,14 @@ func (f *BoolFlag) Apply(set *flag.FlagSet) error {
// Bool looks up the value of a local BoolFlag, returns
// false if not found
func (c *Context) Bool(name string) bool {
return lookupBool(c.resolveFlagDeep(name))
if fs := lookupFlagSet(name, c); fs != nil {
return lookupBool(name, fs)
}
return false
}
func lookupBool(f *flag.Flag) bool {
func lookupBool(name string, set *flag.FlagSet) bool {
f := set.Lookup(name)
if f != nil {
parsed, err := strconv.ParseBool(f.Value.String())
if err != nil {

View File

@ -86,10 +86,14 @@ func (f *DurationFlag) Apply(set *flag.FlagSet) error {
// Duration looks up the value of a local DurationFlag, returns
// 0 if not found
func (c *Context) Duration(name string) time.Duration {
return lookupDuration(c.resolveFlagDeep(name))
if fs := lookupFlagSet(name, c); fs != nil {
return lookupDuration(name, fs)
}
return 0
}
func lookupDuration(f *flag.Flag) time.Duration {
func lookupDuration(name string, set *flag.FlagSet) time.Duration {
f := set.Lookup(name)
if f != nil {
parsed, err := time.ParseDuration(f.Value.String())
if err != nil {

View File

@ -87,10 +87,14 @@ func (f *Float64Flag) Apply(set *flag.FlagSet) error {
// Float64 looks up the value of a local Float64Flag, returns
// 0 if not found
func (c *Context) Float64(name string) float64 {
return lookupFloat64(c.resolveFlagDeep(name))
if fs := lookupFlagSet(name, c); fs != nil {
return lookupFloat64(name, fs)
}
return 0
}
func lookupFloat64(f *flag.Flag) float64 {
func lookupFloat64(name string, set *flag.FlagSet) float64 {
f := set.Lookup(name)
if f != nil {
parsed, err := strconv.ParseFloat(f.Value.String(), 64)
if err != nil {

View File

@ -146,10 +146,14 @@ func (f *Float64SliceFlag) Apply(set *flag.FlagSet) error {
// Float64Slice looks up the value of a local Float64SliceFlag, returns
// nil if not found
func (c *Context) Float64Slice(name string) []float64 {
return lookupFloat64Slice(c.resolveFlagDeep(name))
if fs := lookupFlagSet(name, c); fs != nil {
return lookupFloat64Slice(name, fs)
}
return nil
}
func lookupFloat64Slice(f *flag.Flag) []float64 {
func lookupFloat64Slice(name string, set *flag.FlagSet) []float64 {
f := set.Lookup(name)
if f != nil {
if slice, ok := f.Value.(*Float64Slice); ok {
return slice.Value()

View File

@ -89,10 +89,14 @@ func (f GenericFlag) Apply(set *flag.FlagSet) error {
// Generic looks up the value of a local GenericFlag, returns
// nil if not found
func (c *Context) Generic(name string) interface{} {
return lookupGeneric(c.resolveFlagDeep(name))
if fs := lookupFlagSet(name, c); fs != nil {
return lookupGeneric(name, fs)
}
return nil
}
func lookupGeneric(f *flag.Flag) interface{} {
func lookupGeneric(name string, set *flag.FlagSet) interface{} {
f := set.Lookup(name)
if f != nil {
parsed, err := f.Value, error(nil)
if err != nil {

View File

@ -87,10 +87,14 @@ func (f *IntFlag) Apply(set *flag.FlagSet) error {
// Int looks up the value of a local IntFlag, returns
// 0 if not found
func (c *Context) Int(name string) int {
return lookupInt(c.resolveFlagDeep(name))
if fs := lookupFlagSet(name, c); fs != nil {
return lookupInt(name, fs)
}
return 0
}
func lookupInt(f *flag.Flag) int {
func lookupInt(name string, set *flag.FlagSet) int {
f := set.Lookup(name)
if f != nil {
parsed, err := strconv.ParseInt(f.Value.String(), 0, 64)
if err != nil {

View File

@ -86,10 +86,14 @@ func (f *Int64Flag) Apply(set *flag.FlagSet) error {
// Int64 looks up the value of a local Int64Flag, returns
// 0 if not found
func (c *Context) Int64(name string) int64 {
return lookupInt64(c.resolveFlagDeep(name))
if fs := lookupFlagSet(name, c); fs != nil {
return lookupInt64(name, fs)
}
return 0
}
func lookupInt64(f *flag.Flag) int64 {
func lookupInt64(name string, set *flag.FlagSet) int64 {
f := set.Lookup(name)
if f != nil {
parsed, err := strconv.ParseInt(f.Value.String(), 0, 64)
if err != nil {

View File

@ -145,10 +145,11 @@ func (f *Int64SliceFlag) Apply(set *flag.FlagSet) error {
// Int64Slice looks up the value of a local Int64SliceFlag, returns
// nil if not found
func (c *Context) Int64Slice(name string) []int64 {
return lookupInt64Slice(c.resolveFlagDeep(name))
return lookupInt64Slice(name, c.flagSet)
}
func lookupInt64Slice(f *flag.Flag) []int64 {
func lookupInt64Slice(name string, set *flag.FlagSet) []int64 {
f := set.Lookup(name)
if f != nil {
if slice, ok := f.Value.(*Int64Slice); ok {
return slice.Value()

View File

@ -156,10 +156,14 @@ func (f *IntSliceFlag) Apply(set *flag.FlagSet) error {
// IntSlice looks up the value of a local IntSliceFlag, returns
// nil if not found
func (c *Context) IntSlice(name string) []int {
return lookupIntSlice(c.resolveFlagDeep(name))
if fs := lookupFlagSet(name, c); fs != nil {
return lookupIntSlice(name, c.flagSet)
}
return nil
}
func lookupIntSlice(f *flag.Flag) []int {
func lookupIntSlice(name string, set *flag.FlagSet) []int {
f := set.Lookup(name)
if f != nil {
if slice, ok := f.Value.(*IntSlice); ok {
return slice.Value()

View File

@ -75,10 +75,15 @@ func (f *PathFlag) Apply(set *flag.FlagSet) error {
// Path looks up the value of a local PathFlag, returns
// "" if not found
func (c *Context) Path(name string) string {
return lookupPath(c.resolveFlagDeep(name))
if fs := lookupFlagSet(name, c); fs != nil {
return lookupPath(name, fs)
}
func lookupPath(f *flag.Flag) string {
return ""
}
func lookupPath(name string, set *flag.FlagSet) string {
f := set.Lookup(name)
if f != nil {
parsed, err := f.Value.String(), error(nil)
if err != nil {

View File

@ -76,10 +76,14 @@ func (f *StringFlag) Apply(set *flag.FlagSet) error {
// String looks up the value of a local StringFlag, returns
// "" if not found
func (c *Context) String(name string) string {
return lookupString(c.resolveFlagDeep(name))
if fs := lookupFlagSet(name, c); fs != nil {
return lookupString(name, fs)
}
return ""
}
func lookupString(f *flag.Flag) string {
func lookupString(name string, set *flag.FlagSet) string {
f := set.Lookup(name)
if f != nil {
parsed, err := f.Value.String(), error(nil)
if err != nil {

View File

@ -116,17 +116,8 @@ func (f *StringSliceFlag) GetValue() string {
// Apply populates the flag given the flag set and environment
func (f *StringSliceFlag) Apply(set *flag.FlagSet) error {
if f.Destination != nil && f.Value != nil {
f.Destination.slice = make([]string, len(f.Value.slice))
copy(f.Destination.slice, f.Value.slice)
}
if val, ok := flagFromEnvOrFile(f.EnvVars, f.FilePath); ok {
if f.Value == nil {
f.Value = &StringSlice{}
}
destination := f.Value
if f.Destination != nil {
destination = f.Destination
@ -163,10 +154,14 @@ func (f *StringSliceFlag) Apply(set *flag.FlagSet) error {
// StringSlice looks up the value of a local StringSliceFlag, returns
// nil if not found
func (c *Context) StringSlice(name string) []string {
return lookupStringSlice(c.resolveFlagDeep(name))
if fs := lookupFlagSet(name, c); fs != nil {
return lookupStringSlice(name, fs)
}
return nil
}
func lookupStringSlice(f *flag.Flag) []string {
func lookupStringSlice(name string, set *flag.FlagSet) []string {
f := set.Lookup(name)
if f != nil {
if slice, ok := f.Value.(*StringSlice); ok {
return slice.Value()

View File

@ -118,9 +118,7 @@ func (f *TimestampFlag) Apply(set *flag.FlagSet) error {
if f.Layout == "" {
return fmt.Errorf("timestamp Layout is required")
}
if f.Value == nil {
f.Value = &Timestamp{}
}
f.Value.SetLayout(f.Layout)
if val, ok := flagFromEnvOrFile(f.EnvVars, f.FilePath); ok {
@ -138,11 +136,15 @@ func (f *TimestampFlag) Apply(set *flag.FlagSet) error {
// Timestamp gets the timestamp from a flag name
func (c *Context) Timestamp(name string) *time.Time {
return lookupTimestamp(c.resolveFlagDeep(name))
if fs := lookupFlagSet(name, c); fs != nil {
return lookupTimestamp(name, fs)
}
return nil
}
// Fetches the timestamp value from the local timestampWrap
func lookupTimestamp(f *flag.Flag) *time.Time {
func lookupTimestamp(name string, set *flag.FlagSet) *time.Time {
f := set.Lookup(name)
if f != nil {
return (f.Value.(*Timestamp)).Value()
}

View File

@ -86,10 +86,14 @@ func (f *UintFlag) GetValue() string {
// Uint looks up the value of a local UintFlag, returns
// 0 if not found
func (c *Context) Uint(name string) uint {
return lookupUint(c.resolveFlagDeep(name))
if fs := lookupFlagSet(name, c); fs != nil {
return lookupUint(name, fs)
}
return 0
}
func lookupUint(f *flag.Flag) uint {
func lookupUint(name string, set *flag.FlagSet) uint {
f := set.Lookup(name)
if f != nil {
parsed, err := strconv.ParseUint(f.Value.String(), 0, 64)
if err != nil {

View File

@ -86,10 +86,14 @@ func (f *Uint64Flag) GetValue() string {
// Uint64 looks up the value of a local Uint64Flag, returns
// 0 if not found
func (c *Context) Uint64(name string) uint64 {
return lookupUint64(c.resolveFlagDeep(name))
if fs := lookupFlagSet(name, c); fs != nil {
return lookupUint64(name, fs)
}
return 0
}
func lookupUint64(f *flag.Flag) uint64 {
func lookupUint64(name string, set *flag.FlagSet) uint64 {
f := set.Lookup(name)
if f != nil {
parsed, err := strconv.ParseUint(f.Value.String(), 0, 64)
if err != nil {

View File

@ -5,5 +5,5 @@ go 1.11
require (
github.com/BurntSushi/toml v0.3.1
github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d
gopkg.in/yaml.v2 v2.2.3
gopkg.in/yaml.v2 v2.2.2
)

View File

@ -10,5 +10,5 @@ github.com/shurcooL/sanitized_anchor_name v1.0.0 h1:PdmoCO6wvbs+7yrJyMORt4/BmY5I
github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc=
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.v2 v2.2.3 h1:fvjTMHxHEw/mxHbtzPi3JCcKXQRAnQTBRo6YCJSVHKI=
gopkg.in/yaml.v2 v2.2.3/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=

View File

@ -72,13 +72,13 @@ func ShowAppHelpAndExit(c *Context, exitCode int) {
// ShowAppHelp is an action that displays the help.
func ShowAppHelp(c *Context) error {
tpl := c.App.CustomAppHelpTemplate
if tpl == "" {
tpl = AppHelpTemplate
template := c.App.CustomAppHelpTemplate
if template == "" {
template = AppHelpTemplate
}
if c.App.ExtraInfo == nil {
HelpPrinter(c.App.Writer, tpl, c.App)
HelpPrinter(c.App.Writer, template, c.App)
return nil
}
@ -87,7 +87,7 @@ func ShowAppHelp(c *Context) error {
"ExtraInfo": c.App.ExtraInfo,
}
}
HelpPrinterCustom(c.App.Writer, tpl, c.App, customAppData())
HelpPrinterCustom(c.App.Writer, template, c.App, customAppData())
return nil
}
@ -214,12 +214,6 @@ func ShowCommandHelp(ctx *Context, command string) error {
return nil
}
// ShowSubcommandHelpAndExit - Prints help for the given subcommand and exits with exit code.
func ShowSubcommandHelpAndExit(c *Context, exitCode int) {
_ = ShowSubcommandHelp(c)
os.Exit(exitCode)
}
// ShowSubcommandHelp prints help for the given subcommand
func ShowSubcommandHelp(c *Context) error {
if c == nil {
@ -270,9 +264,6 @@ func ShowCommandCompletions(ctx *Context, command string) {
func printHelpCustom(out io.Writer, templ string, data interface{}, customFuncs map[string]interface{}) {
funcMap := template.FuncMap{
"join": strings.Join,
"indent": indent,
"nindent": nindent,
"trim": strings.TrimSpace,
}
for key, value := range customFuncs {
funcMap[key] = value
@ -375,12 +366,3 @@ func checkCommandCompletions(c *Context, name string) bool {
ShowCommandCompletions(c, name)
return true
}
func indent(spaces int, v string) string {
pad := strings.Repeat(" ", spaces)
return pad + strings.Replace(v, "\n", "\n"+pad, -1)
}
func nindent(spaces int, v string) string {
return "\n" + indent(spaces, v)
}

View File

@ -13,7 +13,7 @@ VERSION:
{{.Version}}{{end}}{{end}}{{if .Description}}
DESCRIPTION:
{{.Description | nindent 3 | trim}}{{end}}{{if len .Authors}}
{{.Description}}{{end}}{{if len .Authors}}
AUTHOR{{with $length := len .Authors}}{{if ne 1 $length}}S{{end}}{{end}}:
{{range $index, $author := .Authors}}{{if $index}}
@ -45,7 +45,7 @@ CATEGORY:
{{.Category}}{{end}}{{if .Description}}
DESCRIPTION:
{{.Description | nindent 3 | trim}}{{end}}{{if .VisibleFlags}}
{{.Description}}{{end}}{{if .VisibleFlags}}
OPTIONS:
{{range .VisibleFlags}}{{.}}
@ -62,7 +62,7 @@ USAGE:
{{if .UsageText}}{{.UsageText}}{{else}}{{.HelpName}} command{{if .VisibleFlags}} [command options]{{end}} {{if .ArgsUsage}}{{.ArgsUsage}}{{else}}[arguments...]{{end}}{{end}}{{if .Description}}
DESCRIPTION:
{{.Description | nindent 3 | trim}}{{end}}
{{.Description}}{{end}}
COMMANDS:{{range .VisibleCategories}}{{if .Name}}
{{.Name}}:{{range .VisibleCommands}}
@ -74,7 +74,7 @@ OPTIONS:
{{end}}{{end}}
`
var MarkdownDocTemplate = `% {{ .App.Name }} {{ .SectionNum }}
var MarkdownDocTemplate = `% {{ .App.Name }} 8
# NAME

3
vendor/modules.txt vendored
View File

@ -246,7 +246,7 @@ github.com/shurcooL/sanitized_anchor_name
## explicit
github.com/stretchr/testify/assert
github.com/stretchr/testify/require
# github.com/urfave/cli/v2 v2.2.0 => github.com/ipostelnik/cli/v2 v2.3.1-0.20210212191405-2b6ed1f5ef69
# github.com/urfave/cli/v2 v2.2.0
## explicit
github.com/urfave/cli/v2
github.com/urfave/cli/v2/altsrc
@ -431,4 +431,3 @@ zombiezen.com/go/capnproto2/rpc/internal/refcount
zombiezen.com/go/capnproto2/schemas
zombiezen.com/go/capnproto2/server
zombiezen.com/go/capnproto2/std/capnp/rpc
# github.com/urfave/cli/v2 => github.com/ipostelnik/cli/v2 v2.3.1-0.20210212191405-2b6ed1f5ef69