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 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
|
# go-opt
[](https://builds.sr.ht/~rjarry/go-opt)
[go-opt](https://git.sr.ht/~rjarry/go-opt) is a library to parse command line
arguments based on tag annotations on struct fields. It came as a spin-off from
[aerc](https://git.sr.ht/~rjarry/aerc) to deal with its internal commands.
This project is a scaled down version of
[go-arg](https://github.com/alexflint/go-arg) with different usage patterns in
mind: command parsing and argument completion for internal application
commands.
## License
[MIT](https://git.sr.ht/~rjarry/go-opt/tree/main/item/LICENSE)
The `shlex.go` file has been inspired from the [github.com/google/shlex](
https://github.com/google/shlex/blob/master/shlex.go) package which is licensed
under the Apache 2.0 license.
## Contributing
Set patches via email to
[~rjarry/public-inbox@lists.sr.ht](mailto:~rjarry/aerc-devel@lists.sr.ht) or
alternatively to
[~rjarry/aerc-devel@lists.sr.ht](mailto:~rjarry/aerc-devel@lists.sr.ht) with
the `PATCH go-opt` subject prefix.
```sh
git config format.subjectPrefix "PATCH go-opt"
git config sendemail.to "~rjarry/public-inbox@lists.sr.ht"
```
## Usage
### Shell command line splitting
```go
package main
import (
"log"
"git.sr.ht/~rjarry/go-opt/v2"
)
func main() {
args, err := opt.LexArgs(`foo 'bar baz' -f\ boz -- " yolo "`)
if err != nil {
log.Fatalf("error: %s\n", err)
}
fmt.Printf("count: %d\n", args.Count())
fmt.Printf("args: %#v\n", args.Args())
fmt.Printf("raw: %q\n", args.String())
fmt.Println("shift 2")
args.Shift(2)
fmt.Printf("count: %d\n", args.Count())
fmt.Printf("args: %#v\n", args.Args())
fmt.Printf("raw: %q\n", args.String())
}
```
```console
$ go run main.go
count: 5
args: []string{"foo", "bar baz", "-f boz", "--", " yolo "}
raw: "foo 'bar baz' -f\\ boz -- \" yolo \""
shift 2
count: 3
args: []string{"-f boz", "--", " yolo "}
raw: "-f\\ boz -- \" yolo \""
```
### Argument parsing
```go
package main
import (
"fmt"
"log"
"git.sr.ht/~rjarry/go-opt/v2"
)
type Foo struct {
Delay time.Duration `opt:"-t,--delay" action:"ParseDelay" default:"1s"`
Force bool `opt:"--force"`
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 --force bar baz 'xy z'
main.Foo{Delay:1000000000, Force:true, Name:"bar", Cmd:[]string{"baz", "xy z"}}
$ foo -t
error: -t takes a value. Usage: foo [-t <delay>] [--force] [<name>] <cmd>...
```
### Argument completion
```go
package main
import (
"fmt"
"log"
"os"
"strings"
"git.sr.ht/~rjarry/go-opt/v2"
)
type CompleteStruct struct {
Name string `opt:"-n,--name" required:"true" complete:"CompleteName"`
Delay float64 `opt:"--delay"`
Zero bool `opt:"-z"`
Backoff bool `opt:"-B,--backoff"`
Tags []string `opt:"..." complete:"CompleteTag"`
}
func (c *CompleteStruct) CompleteName(arg string) []string {
return []string{"leonardo", "michelangelo", "rafaelo", "donatello"}
}
func (c *CompleteStruct) CompleteTag(arg string) []string {
var results []string
prefix := ""
if strings.HasPrefix(arg, "-") {
prefix = "-"
} else if strings.HasPrefix(arg, "+") {
prefix = "+"
}
tags := []string{"unread", "sent", "important", "inbox", "trash"}
for _, t := range tags {
t = prefix + t
if strings.HasPrefix(t, arg) {
results = append(results, t)
}
}
return results
}
func main() {
args, err := opt.QuoteArgs(os.Args...)
if err != nil {
log.Fatalf("error: %s\n", err)
}
var s CompleteStruct
completions, _ := opt.GetCompletions(args.String(), &s)
for _, c := range completions {
fmt.Println(c.Value)
}
}
```
```console
$ foo i
important
inbox
$ foo -
--backoff
--delay
--name
-B
-important
-inbox
-n
-sent
-trash
-unread
-z
$ foo +
+important
+inbox
+sent
+trash
+unread
```
## Supported tags
There is a set of tags that can be set on struct fields:
### `opt:"-f,--foo"`
Registers that this field is associated to the specified flag(s). 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.
### `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`
The special argument `--` forces an end to the flag parsing. The remaining
arguments are interpreted as positional arguments (see `getopt(3)`).
|