# go-opt

[![builds.sr.ht status](https://builds.sr.ht/~rjarry/go-opt.svg)](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:":blah:"`

The field is associated to a positional argument which maps to a nested
sub-command. The field must be an interface and must have a defined `action`
method (see below). The `action` must set the field value to the appropriate
structure pointer.

### `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.

### `minus:"true|false"`

By default, any argument starting with `-` or `--` will be interpreted as
a short or long flag, respectively. If no matching flag is found, an error will
be returned.

Setting `minus:"true"` allows changing that default behaviour. If no matching
flag is found, instead of throwing an error, the argument will be considered as
positional.

### `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.

By default, completion items will use the description of the field (if
`description` is defined). Each completion may contain an optional newline
character `\n` followed by its own description that will be used instead of the
default.

## 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)`).
