Skip to content

Commit

Permalink
Add Get{Flag,Arg,Command}.
Browse files Browse the repository at this point in the history
  • Loading branch information
alecthomas committed Dec 19, 2015
1 parent ad87b9d commit 292d4f2
Show file tree
Hide file tree
Showing 4 changed files with 41 additions and 0 deletions.
13 changes: 13 additions & 0 deletions args.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,19 @@ func (a *argGroup) have() bool {
return len(a.args) > 0
}

// GetArg gets an argument definition.
//
// This allows existing arguments to be modified after definition but before parsing. Useful for
// modular applications.
func (a *argGroup) GetArg(name string) *ArgClause {
for _, arg := range a.args {
if arg.name == name {
return arg
}
}
return nil
}

func (a *argGroup) Arg(name, help string) *ArgClause {
arg := newArg(name, help)
a.args = append(a.args, arg)
Expand Down
8 changes: 8 additions & 0 deletions cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,14 @@ func (c *cmdGroup) defaultSubcommand() *CmdClause {
return nil
}

// GetArg gets a command definition.
//
// This allows existing commands to be modified after definition but before parsing. Useful for
// modular applications.
func (c *cmdGroup) GetCommand(name string) *CmdClause {
return c.commands[name]
}

func newCmdGroup(app *Application) *cmdGroup {
return &cmdGroup{
app: app,
Expand Down
8 changes: 8 additions & 0 deletions flags.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,14 @@ func newFlagGroup() *flagGroup {
}
}

// GetFlag a flag definition.
//
// This allows existing flags to be modified after definition but before parsing. Useful for
// modular applications.
func (f *flagGroup) GetFlag(name string) *FlagClause {
return f.long[name]
}

// Flag defines a new flag with the given long name and help.
func (f *flagGroup) Flag(name, help string) *FlagClause {
flag := newFlag(name, help)
Expand Down
12 changes: 12 additions & 0 deletions flags_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -144,3 +144,15 @@ func TestDuplicateLongFlag(t *testing.T) {
_, err := app.Parse([]string{})
assert.Error(t, err)
}

func TestGetFlagAndOverrideDefault(t *testing.T) {
app := newTestApp()
a := app.Flag("a", "").Default("default").String()
_, err := app.Parse([]string{})
assert.NoError(t, err)
assert.Equal(t, "default", *a)
app.GetFlag("a").Default("new")
_, err = app.Parse([]string{})
assert.NoError(t, err)
assert.Equal(t, "new", *a)
}

0 comments on commit 292d4f2

Please sign in to comment.