1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
|
package opt
/*
Example use:
```go
package main
import (
"fmt"
"log"
"git.sr.ht/~rjarry/go-opt/v2"
)
type Foo struct {
Delay time.Duration `opt:"-t" action:"ParseDelay" default:"1s"`
Force bool `opt:"-f"`
Name string `opt:"name" required:"false" metavar:"FOO"`
Cmd []string `opt:"..."`
}
func (f *Foo) ParseDelay(arg string) error {
d, err := time.ParseDuration(arg)
if err != nil {
return err
}
f.Delay = d
return nil
}
func main() {
var foo Foo
err := opt.CmdlineToStruct("foo -f bar baz 'xy z' ", &foo)
if err != nil {
log.Fatalf("error: %s\n", err)
}
fmt.Printf("%#v\n", foo)
}
```
```console
$ foo -f bar baz 'xy z'
Foo{Delay: 1000000000, Force: true, Name: "bar", Cmd: []string{"baz", "xy z"}}
$ foo -t
error: -t takes a value. Usage: foo [-t <delay>] [-f] [<name>] <cmd>...
```
## Supported tags
There is a set of tags that can be set on struct fields:
### `opt:"-f"`
Registers that this field is associated to the specified flag. Unless a custom
`action` method is specified, the flag value will be automatically converted
from string to the field type (only basic scalar types are supported: all
integers (both signed and unsigned), all floats and strings. If the field type
is `bool`, the flag will take no value. Only supports short flags for now.
### `opt:"blah"`
Field is associated to a positional argument.
### `opt:"..."`
Field will be mapped to all remaining arguments. If the field is `string`, the
raw command line will be stored preserving any shell quoting, otherwise the
field needs to be `[]string` and will receive the remaining arguments after
interpreting shell quotes.
### `opt:"-"`
Special value to indicate that this command will accept any argument without
any check nor parsing. The field on which it is set will not be updated and
should be called `Unused struct{}` as a convention. The field name must start
with an upper case to avoid linter warnings because of unused fields.
### `action:"ParseFoo"`
Custom method to be used instead of the default automatic conversion. Needs to
be a method with a pointer receiver to the struct itself, takes a single
`string` argument and may return an `error` to abort parsing. The `action`
method is responsible of updating the struct.
### `description:"foobaz"` or `desc:"foobaz"`
A description that is returned alongside arguments during autocompletion.
### `default:"foobaz"`
Default `string` value if not specified by the user. Will be processed by the
same conversion/parsing as any other argument.
### `metavar:"foo|bar|baz"`
Displayed name for argument values in the generated usage help.
### `required:"true|false"`
By default, flag arguments are optional and positional arguments are required.
Using this tag allows changing that default behaviour. If an argument is not
required, it will be surrounded by square brackets in the generated usage help.
### `aliases:"cmd1,cmd2"`
By default, arguments are interpreted for all command aliases. If this is
specified, this field/option will only be applicable to the specified command
aliases.
### `complete:"CompleteFoo"`
Custom method to return the valid completions for the annotated option
/ argument. Needs to be a method with a pointer receiver to the struct itself,
takes a single `string` argument and must return a `[]string` slice containing
the valid completions.
## Caveats
Depending on field types, the argument string values are parsed using the
appropriate conversion function.
If no `opt` tag is set on a field, it will be excluded from automated argument
parsing. It can still be updated indirectly via a custom `action` method.
Short flags can be combined like with `getopt(3)`:
* Flags with no value: `-abc` is equivalent to `-a -b -c`
* Flags with a value (options): `-j9` is equivalent to `-j 9`
*/
import (
"errors"
"fmt"
)
func CmdlineToStruct(cmdline string, v any) error {
args := LexArgs(cmdline)
return ArgsToStruct(args, v)
}
func ArgsToStruct(args *Args, v any) error {
if args.Count() == 0 {
return errors.New("empty command")
}
cmd := NewCmdSpec(args.Arg(0), v)
if err := cmd.ParseArgs(args); err != nil {
return fmt.Errorf("%w. Usage: %s", err, cmd.Usage())
}
return nil
}
func GetCompletions(cmdline string, v any) (completions []Completion, prefix string) {
args := LexArgs(cmdline)
if args.Count() == 0 {
return nil, ""
}
spec := NewCmdSpec(args.Arg(0), v)
return spec.GetCompletions(args)
}
|