feat: flag action

This commit is contained in:
Wendell Sun
2022-02-15 23:49:41 +08:00
parent 880a802dc8
commit 14366f7030
19 changed files with 257 additions and 0 deletions

26
app.go
View File

@@ -342,6 +342,10 @@ func (a *App) RunContext(ctx context.Context, arguments []string) (err error) {
}
}
if err = runFlagActions(cCtx, a.Flags); err != nil {
return err
}
var c *Command
args := cCtx.Args()
if args.Present() {
@@ -523,6 +527,10 @@ func (a *App) RunAsSubcommand(ctx *Context) (err error) {
}
}
if err = runFlagActions(cCtx, a.Flags); err != nil {
return err
}
args := cCtx.Args()
if args.Present() {
name := args.First()
@@ -646,6 +654,24 @@ func (a *App) argsWithDefaultCommand(oldArgs Args) Args {
return oldArgs
}
func runFlagActions(c *Context, fs []Flag) error {
for _, f := range fs {
isSet := false
for _, name := range f.Names() {
if c.IsSet(name) {
isSet = true
break
}
}
if isSet {
if err := f.RunAction(c); err != nil {
return err
}
}
}
return nil
}
// Author represents someone who has contributed to a cli project.
type Author struct {
Name string // The Authors name