added usage generation

This commit is contained in:
Alex Flint 2015-10-31 18:26:58 -07:00
parent 8397a40f4c
commit b9ad104f33
2 changed files with 132 additions and 123 deletions

131
parse.go
View File

@ -1,56 +1,16 @@
package arguments package arg
import ( import (
"fmt" "fmt"
"log"
"os" "os"
"reflect" "reflect"
"strconv" "strconv"
"strings" "strings"
) )
// MustParse processes command line arguments and exits upon failure. // spec represents a command line option
func MustParse(dest interface{}) {
err := Parse(dest)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
}
// Parse processes command line arguments and stores the result in args.
func Parse(dest interface{}) error {
return ParseFrom(dest, os.Args)
}
// ParseFrom processes command line arguments and stores the result in args.
func ParseFrom(dest interface{}, args []string) error {
v := reflect.ValueOf(dest)
if v.Kind() != reflect.Ptr {
panic(fmt.Sprintf("%s is not a pointer type", v.Type().Name()))
}
v = v.Elem()
// Parse the spec
spec, err := extractSpec(v.Type())
if err != nil {
return err
}
// Process args
err = processArgs(v, spec, args)
if err != nil {
return err
}
// Validate
return validate(spec)
}
// spec represents information about an argument extracted from struct tags
type spec struct { type spec struct {
field reflect.StructField dest reflect.Value
index int
long string long string
short string short string
multiple bool multiple bool
@ -60,13 +20,64 @@ type spec struct {
wasPresent bool wasPresent bool
} }
// extractSpec gets specifications for each argument from the tags in a struct // MustParse processes command line arguments and exits upon failure.
func extractSpec(t reflect.Type) ([]*spec, error) { func MustParse(dest ...interface{}) {
if t.Kind() != reflect.Struct { err := Parse(dest...)
panic(fmt.Sprintf("%s is not a struct pointer", t.Name())) if err != nil {
fmt.Println(err)
os.Exit(1)
}
}
// Parse processes command line arguments and stores the result in args.
func Parse(dest ...interface{}) error {
return ParseFrom(os.Args[1:], dest...)
}
// ParseFrom processes command line arguments and stores the result in args.
func ParseFrom(args []string, dest ...interface{}) error {
// Add the help option if one is not already defined
var internal struct {
Help bool `arg:"-h"`
} }
// Parse the spec
dest = append(dest, &internal)
spec, err := extractSpec(dest...)
if err != nil {
return err
}
// Process args
err = processArgs(spec, args)
if err != nil {
return err
}
// If -h or --help were specified then print help
if internal.Help {
writeUsage(os.Stdout, spec)
os.Exit(0)
}
// Validate
return validate(spec)
}
// extractSpec gets specifications for each argument from the tags in a struct
func extractSpec(dests ...interface{}) ([]*spec, error) {
var specs []*spec var specs []*spec
for _, dest := range dests {
v := reflect.ValueOf(dest)
if v.Kind() != reflect.Ptr {
panic(fmt.Sprintf("%s is not a pointer (did you forget an ampersand?)", v.Type()))
}
v = v.Elem()
if v.Kind() != reflect.Struct {
panic(fmt.Sprintf("%T is not a struct pointer", dest))
}
t := v.Type()
for i := 0; i < t.NumField(); i++ { for i := 0; i < t.NumField(); i++ {
// Check for the ignore switch in the tag // Check for the ignore switch in the tag
field := t.Field(i) field := t.Field(i)
@ -77,13 +88,11 @@ func extractSpec(t reflect.Type) ([]*spec, error) {
spec := spec{ spec := spec{
long: strings.ToLower(field.Name), long: strings.ToLower(field.Name),
field: field, dest: v.Field(i),
index: i,
} }
// Get the scalar type for this field // Get the scalar type for this field
scalarType := field.Type scalarType := field.Type
log.Println(field.Name, field.Type, field.Type.Kind())
if scalarType.Kind() == reflect.Slice { if scalarType.Kind() == reflect.Slice {
spec.multiple = true spec.multiple = true
scalarType = scalarType.Elem() scalarType = scalarType.Elem()
@ -130,11 +139,12 @@ func extractSpec(t reflect.Type) ([]*spec, error) {
} }
specs = append(specs, &spec) specs = append(specs, &spec)
} }
}
return specs, nil return specs, nil
} }
// processArgs processes arguments using a pre-constructed spec // processArgs processes arguments using a pre-constructed spec
func processArgs(dest reflect.Value, specs []*spec, args []string) error { func processArgs(specs []*spec, args []string) error {
// construct a map from --option to spec // construct a map from --option to spec
optionMap := make(map[string]*spec) optionMap := make(map[string]*spec)
for _, spec := range specs { for _, spec := range specs {
@ -192,7 +202,7 @@ func processArgs(dest reflect.Value, specs []*spec, args []string) error {
} else { } else {
values = append(values, value) values = append(values, value)
} }
err := setSlice(dest.Field(spec.index), values) err := setSlice(spec.dest, values)
if err != nil { if err != nil {
return fmt.Errorf("error processing %s: %v", arg, err) return fmt.Errorf("error processing %s: %v", arg, err)
} }
@ -200,7 +210,7 @@ func processArgs(dest reflect.Value, specs []*spec, args []string) error {
} }
// if it's a flag and it has no value then set the value to true // if it's a flag and it has no value then set the value to true
if spec.field.Type.Kind() == reflect.Bool && value == "" { if spec.dest.Kind() == reflect.Bool && value == "" {
value = "true" value = "true"
} }
@ -213,7 +223,7 @@ func processArgs(dest reflect.Value, specs []*spec, args []string) error {
i++ i++
} }
err := setScalar(dest.Field(spec.index), value) err := setScalar(spec.dest, value)
if err != nil { if err != nil {
return fmt.Errorf("error processing %s: %v", arg, err) return fmt.Errorf("error processing %s: %v", arg, err)
} }
@ -221,22 +231,21 @@ func processArgs(dest reflect.Value, specs []*spec, args []string) error {
// process positionals // process positionals
for _, spec := range specs { for _, spec := range specs {
label := strings.ToLower(spec.field.Name)
if spec.positional { if spec.positional {
if spec.multiple { if spec.multiple {
err := setSlice(dest.Field(spec.index), positionals) err := setSlice(spec.dest, positionals)
if err != nil { if err != nil {
return fmt.Errorf("error processing %s: %v", label, err) return fmt.Errorf("error processing %s: %v", spec.long, err)
} }
positionals = nil positionals = nil
} else if len(positionals) > 0 { } else if len(positionals) > 0 {
err := setScalar(dest.Field(spec.index), positionals[0]) err := setScalar(spec.dest, positionals[0])
if err != nil { if err != nil {
return fmt.Errorf("error processing %s: %v", label, err) return fmt.Errorf("error processing %s: %v", spec.long, err)
} }
positionals = positionals[1:] positionals = positionals[1:]
} else if spec.required { } else if spec.required {
return fmt.Errorf("%s is required", label) return fmt.Errorf("%s is required", spec.long)
} }
} }
} }
@ -250,7 +259,7 @@ func processArgs(dest reflect.Value, specs []*spec, args []string) error {
func validate(spec []*spec) error { func validate(spec []*spec) error {
for _, arg := range spec { for _, arg := range spec {
if !arg.positional && arg.required && !arg.wasPresent { if !arg.positional && arg.required && !arg.wasPresent {
return fmt.Errorf("--%s is required", strings.ToLower(arg.field.Name)) return fmt.Errorf("--%s is required", arg.long)
} }
} }
return nil return nil

View File

@ -1,4 +1,4 @@
package arguments package arg
import ( import (
"strings" "strings"
@ -16,7 +16,7 @@ func TestStringSingle(t *testing.T) {
var args struct { var args struct {
Foo string Foo string
} }
err := ParseFrom(&args, split("--foo bar")) err := ParseFrom(split("--foo bar"), &args)
require.NoError(t, err) require.NoError(t, err)
assert.Equal(t, "bar", args.Foo) assert.Equal(t, "bar", args.Foo)
} }
@ -30,7 +30,7 @@ func TestMixed(t *testing.T) {
Spam float32 Spam float32
} }
args.Bar = 3 args.Bar = 3
err := ParseFrom(&args, split("123 -spam=1.2 -ham -f xyz")) err := ParseFrom(split("123 -spam=1.2 -ham -f xyz"), &args)
require.NoError(t, err) require.NoError(t, err)
assert.Equal(t, "xyz", args.Foo) assert.Equal(t, "xyz", args.Foo)
assert.Equal(t, 3, args.Bar) assert.Equal(t, 3, args.Bar)
@ -43,7 +43,7 @@ func TestRequired(t *testing.T) {
var args struct { var args struct {
Foo string `arg:"required"` Foo string `arg:"required"`
} }
err := ParseFrom(&args, nil) err := ParseFrom(nil, &args)
require.Error(t, err, "--foo is required") require.Error(t, err, "--foo is required")
} }
@ -52,15 +52,15 @@ func TestShortFlag(t *testing.T) {
Foo string `arg:"-f"` Foo string `arg:"-f"`
} }
err := ParseFrom(&args, split("-f xyz")) err := ParseFrom(split("-f xyz"), &args)
require.NoError(t, err) require.NoError(t, err)
assert.Equal(t, "xyz", args.Foo) assert.Equal(t, "xyz", args.Foo)
err = ParseFrom(&args, split("-foo xyz")) err = ParseFrom(split("-foo xyz"), &args)
require.NoError(t, err) require.NoError(t, err)
assert.Equal(t, "xyz", args.Foo) assert.Equal(t, "xyz", args.Foo)
err = ParseFrom(&args, split("--foo xyz")) err = ParseFrom(split("--foo xyz"), &args)
require.NoError(t, err) require.NoError(t, err)
assert.Equal(t, "xyz", args.Foo) assert.Equal(t, "xyz", args.Foo)
} }
@ -71,7 +71,7 @@ func TestCaseSensitive(t *testing.T) {
Upper bool `arg:"-V"` Upper bool `arg:"-V"`
} }
err := ParseFrom(&args, split("-v")) err := ParseFrom(split("-v"), &args)
require.NoError(t, err) require.NoError(t, err)
assert.True(t, args.Lower) assert.True(t, args.Lower)
assert.False(t, args.Upper) assert.False(t, args.Upper)
@ -83,7 +83,7 @@ func TestCaseSensitive2(t *testing.T) {
Upper bool `arg:"-V"` Upper bool `arg:"-V"`
} }
err := ParseFrom(&args, split("-V")) err := ParseFrom(split("-V"), &args)
require.NoError(t, err) require.NoError(t, err)
assert.False(t, args.Lower) assert.False(t, args.Lower)
assert.True(t, args.Upper) assert.True(t, args.Upper)
@ -94,7 +94,7 @@ func TestPositional(t *testing.T) {
Input string `arg:"positional"` Input string `arg:"positional"`
Output string `arg:"positional"` Output string `arg:"positional"`
} }
err := ParseFrom(&args, split("foo")) err := ParseFrom(split("foo"), &args)
require.NoError(t, err) require.NoError(t, err)
assert.Equal(t, "foo", args.Input) assert.Equal(t, "foo", args.Input)
assert.Equal(t, "", args.Output) assert.Equal(t, "", args.Output)
@ -105,7 +105,7 @@ func TestRequiredPositional(t *testing.T) {
Input string `arg:"positional"` Input string `arg:"positional"`
Output string `arg:"positional,required"` Output string `arg:"positional,required"`
} }
err := ParseFrom(&args, split("foo")) err := ParseFrom(split("foo"), &args)
assert.Error(t, err) assert.Error(t, err)
} }
@ -114,7 +114,7 @@ func TestTooManyPositional(t *testing.T) {
Input string `arg:"positional"` Input string `arg:"positional"`
Output string `arg:"positional"` Output string `arg:"positional"`
} }
err := ParseFrom(&args, split("foo bar baz")) err := ParseFrom(split("foo bar baz"), &args)
assert.Error(t, err) assert.Error(t, err)
} }
@ -123,7 +123,7 @@ func TestMultiple(t *testing.T) {
Foo []int Foo []int
Bar []string Bar []string
} }
err := ParseFrom(&args, split("--foo 1 2 3 --bar x y z")) err := ParseFrom(split("--foo 1 2 3 --bar x y z"), &args)
require.NoError(t, err) require.NoError(t, err)
assert.Equal(t, []int{1, 2, 3}, args.Foo) assert.Equal(t, []int{1, 2, 3}, args.Foo)
assert.Equal(t, []string{"x", "y", "z"}, args.Bar) assert.Equal(t, []string{"x", "y", "z"}, args.Bar)