Skip to content

Commit

Permalink
Add support for Var args and opts
Browse files Browse the repository at this point in the history
i.e. Make it possible for users to extend mow.cli with custom types for args and opts
  • Loading branch information
jawher committed Sep 16, 2016
1 parent 0de8a76 commit 6a576dc
Show file tree
Hide file tree
Showing 24 changed files with 1,489 additions and 374 deletions.
20 changes: 16 additions & 4 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -1,7 +1,19 @@
language: go
go:
- 1.4
- 1.5
- 1.6
- tip
- 1.6
- 1.7
- tip

sudo: false

install:
- go get github.com/gordonklaus/ineffassign
- go get github.com/golang/lint/golint
- go get -t ./...

script:
- "! gofmt -s -d . 2>&1 | read"
- go test -v ./...
- go vet
- ineffassign .
- golint .
91 changes: 91 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -282,6 +282,97 @@ mow.cli's API was specifically tailored to take a func parameter (called CmdInit

This way, the command specific variables scope is limited to this function.

## Custom types

Out of the box, mow.cli supports the following types for options and arguments:

* bool
* string
* int
* strings (slice of strings)
* ints (slice of ints)

You can however extend mow.cli to handle other types, e.g. `time.Duration`, `float64`, or even your own struct types for example.

To do so, you'll need to:

* implement the `flag.Value` interface for the custom type
* declare the option or the flag using `VarOpt`, `VarArg` for the short hands, and `Var` for the full form.

Here's an example:

```go
// Declare your type
type Duration time.Duration

// Make it implement flag.Value
func (d *Duration) Set(v string) error {
parsed, err := time.ParseDuration(v)
if err != nil {
return err
}
*d = Duration(parsed)
return nil
}

func (d *Duration) String() string {
duration := time.Duration(*d)
return duration.String()
}

func main() {
duration := Duration(0)

app := App("var", "")

app.VarArg("DURATION", &duration, "")

app.Run([]string{"cp", "1h31m42s"})
}
```

### Boolean custom types

To make your custom type behave as a boolean option, i.e. doesn't take a value, it has to implement a `IsBoolFlag` method that returns true:

```go
type BoolLike int


func (d *BoolLike) IsBoolFlag() bool {
return true
}
```

### Multi-valued custom type

To make your custom type behave as a multi-valued option or argument, i.e. takes multiple values,
it has to implement a `Clear` method which will be called whenever the value list needs to be cleared:

```go
type Durations []time.Duration

// Make it implement flag.Value
func (d *Durations) Set(v string) error {
parsed, err := time.ParseDuration(v)
if err != nil {
return err
}
*d = append(*d, Duration(parsed))
return nil
}

func (d *Durations) String() string {
return fmt.Sprintf("%v", *d)
}


// Make it multi-valued
func (d *Durations) Clear() {
*d = []Duration{}
}
```

## Interceptors

It is possible to define snippets of code to be executed before and after a command or any of its sub commands is executed.
Expand Down
146 changes: 101 additions & 45 deletions args.go
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@
package cli

import (
"flag"
"fmt"
"reflect"
)

// BoolArg describes a boolean argument
type BoolArg struct {
BoolParam

// The argument name as will be shown in help messages
Name string
// The argument description as will be shown in help messages
Expand All @@ -19,72 +17,117 @@ type BoolArg struct {
Value bool
// A boolean to display or not the current value of the argument in the help message
HideValue bool
// Set to true if this arg was set by the user (as opposed to being set from env or not set at all)
SetByUser *bool
}

func (a BoolArg) value() bool {
return a.Value
}

// StringArg describes a string argument
type StringArg struct {
StringParam

// The argument name as will be shown in help messages
Name string
// The argument description as will be shown in help messages
Desc string
// A space separated list of environment variables names to be used to initialize this argument
EnvVar string
// The argument's inital value
// The argument's initial value
Value string
// A boolean to display or not the current value of the argument in the help message
HideValue bool
// Set to true if this arg was set by the user (as opposed to being set from env or not set at all)
SetByUser *bool
}

func (a StringArg) value() string {
return a.Value
}

// IntArg describes an int argument
type IntArg struct {
IntParam

// The argument name as will be shown in help messages
Name string
// The argument description as will be shown in help messages
Desc string
// A space separated list of environment variables names to be used to initialize this argument
EnvVar string
// The argument's inital value
// The argument's initial value
Value int
// A boolean to display or not the current value of the argument in the help message
HideValue bool
// Set to true if this arg was set by the user (as opposed to being set from env or not set at all)
SetByUser *bool
}

func (a IntArg) value() int {
return a.Value
}

// StringsArg describes a string slice argument
type StringsArg struct {
StringsParam

// The argument name as will be shown in help messages
Name string
// The argument description as will be shown in help messages
Desc string
// A space separated list of environment variables names to be used to initialize this argument.
// The env variable should contain a comma separated list of values
EnvVar string
// The argument's inital value
// The argument's initial value
Value []string
// A boolean to display or not the current value of the argument in the help message
HideValue bool
// Set to true if this arg was set by the user (as opposed to being set from env or not set at all)
SetByUser *bool
}

func (a StringsArg) value() []string {
return a.Value
}

// IntsArg describes an int slice argument
type IntsArg struct {
IntsParam

// The argument name as will be shown in help messages
Name string
// The argument description as will be shown in help messages
Desc string
// A space separated list of environment variables names to be used to initialize this argument.
// The env variable should contain a comma separated list of values
EnvVar string
// The argument's inital value
// The argument's initial value
Value []int
// A boolean to display or not the current value of the argument in the help message
HideValue bool
// Set to true if this arg was set by the user (as opposed to being set from env or not set at all)
SetByUser *bool
}

func (a IntsArg) value() []int {
return a.Value
}

// VarArg describes an argument where the type and format of the value is controlled by the developer
type VarArg struct {
VarParam

// A space separated list of the option names *WITHOUT* the dashes, e.g. `f force` and *NOT* `-f --force`.
// The one letter names will then be called with a single dash (short option), the others with two (long options).
Name string
// The option description as will be shown in help messages
Desc string
// A space separated list of environment variables names to be used to initialize this option
EnvVar string
// A value implementing the flag.Value type (will hold the final value)
Value flag.Value
// A boolean to display or not the current value of the option in the help message
HideValue bool
// Set to true if this arg was set by the user (as opposed to being set from env or not set at all)
SetByUser *bool
}

func (a VarArg) value() flag.Value {
return a.Value
}

/*
Expand All @@ -93,7 +136,11 @@ BoolArg defines a boolean argument on the command c named `name`, with an initia
The result should be stored in a variable (a pointer to a bool) which will be populated when the app is run and the call arguments get parsed
*/
func (c *Cmd) BoolArg(name string, value bool, desc string) *bool {
return c.mkArg(arg{name: name, desc: desc}, value).(*bool)
return c.Bool(BoolArg{
Name: name,
Value: value,
Desc: desc,
})
}

/*
Expand All @@ -102,7 +149,11 @@ StringArg defines a string argument on the command c named `name`, with an initi
The result should be stored in a variable (a pointer to a string) which will be populated when the app is run and the call arguments get parsed
*/
func (c *Cmd) StringArg(name string, value string, desc string) *string {
return c.mkArg(arg{name: name, desc: desc}, value).(*string)
return c.String(StringArg{
Name: name,
Value: value,
Desc: desc,
})
}

/*
Expand All @@ -111,7 +162,11 @@ IntArg defines an int argument on the command c named `name`, with an initial va
The result should be stored in a variable (a pointer to an int) which will be populated when the app is run and the call arguments get parsed
*/
func (c *Cmd) IntArg(name string, value int, desc string) *int {
return c.mkArg(arg{name: name, desc: desc}, value).(*int)
return c.Int(IntArg{
Name: name,
Value: value,
Desc: desc,
})
}

/*
Expand All @@ -120,7 +175,11 @@ StringsArg defines a string slice argument on the command c named `name`, with a
The result should be stored in a variable (a pointer to a string slice) which will be populated when the app is run and the call arguments get parsed
*/
func (c *Cmd) StringsArg(name string, value []string, desc string) *[]string {
return c.mkArg(arg{name: name, desc: desc}, value).(*[]string)
return c.Strings(StringsArg{
Name: name,
Value: value,
Desc: desc,
})
}

/*
Expand All @@ -129,42 +188,39 @@ IntsArg defines an int slice argument on the command c named `name`, with an ini
The result should be stored in a variable (a pointer to an int slice) which will be populated when the app is run and the call arguments get parsed
*/
func (c *Cmd) IntsArg(name string, value []int, desc string) *[]int {
return c.mkArg(arg{name: name, desc: desc}, value).(*[]int)
return c.Ints(IntsArg{
Name: name,
Value: value,
Desc: desc,
})
}

type arg struct {
name string
desc string
envVar string
helpFormatter func(interface{}) string
value reflect.Value
hideValue bool
}
/*
VarArg defines an argument where the type and format is controlled by the developer on the command c named `name` and a description of `desc` which will be used in help messages.
func (a *arg) String() string {
return fmt.Sprintf("ARG(%s)", a.name)
The result will be stored in the value parameter (a value implementing the flag.Value interface) which will be populated when the app is run and the call arguments get parsed
*/
func (c *Cmd) VarArg(name string, value flag.Value, desc string) {
c.mkArg(arg{name: name, desc: desc, value: value})
}

func (a *arg) get() interface{} {
return a.value.Elem().Interface()
type arg struct {
name string
desc string
envVar string
hideValue bool
valueSetFromEnv bool
valueSetByUser *bool
value flag.Value
}

func (a *arg) set(s string) error {
return vset(a.value, s)
func (a *arg) String() string {
return fmt.Sprintf("ARG(%s)", a.name)
}

func (c *Cmd) mkArg(arg arg, defaultvalue interface{}) interface{} {
value := reflect.ValueOf(defaultvalue)
res := reflect.New(value.Type())

arg.helpFormatter = formatterFor(value.Type())

vinit(res, arg.envVar, defaultvalue)

arg.value = res
func (c *Cmd) mkArg(arg arg) {
arg.valueSetFromEnv = setFromEnv(arg.value, arg.envVar)

c.args = append(c.args, &arg)
c.argsIdx[arg.name] = &arg

return res.Interface()
}
1 change: 1 addition & 0 deletions args_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,7 @@ func TestStringsArg(t *testing.T) {

func TestIntsArg(t *testing.T) {
cmd := &Cmd{argsIdx: map[string]*arg{}}

vi := []int{42}
a := cmd.Ints(IntsArg{Name: "a", Value: vi, Desc: ""})
require.Equal(t, vi, *a)
Expand Down
Loading

0 comments on commit 6a576dc

Please sign in to comment.