opt

package module
v1.4.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 4, 2024 License: MIT Imports: 6 Imported by: 10

README

go-opt

builds.sr.ht status

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 to deal with its internal commands.

This project is a scaled down version of go-arg with different usage patterns in mind: command parsing and argument completion for internal application commands.

License

MIT

The shlex.go file has been inspired from the github.com/google/shlex package which is licensed under the Apache 2.0 license.

Contributing

Set patches via email to ~rjarry/public-inbox@lists.sr.ht or alternatively to ~rjarry/aerc-devel@lists.sr.ht with the PATCH go-opt subject prefix.

git config format.subjectPrefix "PATCH go-opt"
git config sendemail.to "~rjarry/public-inbox@lists.sr.ht"

Usage

Shell command line splitting
package main

import (
	"log"

	"git.sr.ht/~rjarry/go-opt"
)

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())
}
$ 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
package main

import (
	"fmt"
	"log"

	"git.sr.ht/~rjarry/go-opt"
)

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)
}
$ 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
package main

import (
	"fmt"
	"log"
	"os"
	"strings"

	"git.sr.ht/~rjarry/go-opt"
)

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)
	fmt.Println(strings.Join(completions, "\n"))
}
$ 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.

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

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrArgIndex = errors.New("argument index out of bounds")

Functions

func ArgsToStruct

func ArgsToStruct(args *Args, v any) error

func CmdlineToStruct

func CmdlineToStruct(cmdline string, v any) error

func GetCompletions

func GetCompletions(cmdline string, v any) (completions []string, prefix string)

func QuoteArg

func QuoteArg(arg string) string

Wrap a single argument with appropriate quoting so that it can be used in a shell command.

func SplitArgs

func SplitArgs(cmd string) []string

Shortcut for LexArgs(cmd).Args()

Types

type ArgError

type ArgError struct {
	// contains filtered or unexported fields
}

func (*ArgError) Error

func (e *ArgError) Error() string

type Args

type Args struct {
	// contains filtered or unexported fields
}

Shell command line with interpreted arguments. Allows access to individual arguments and to preserve shell quoting.

func LexArgs

func LexArgs(cmd string) *Args

Interpret a shell command line into multiple arguments.

func QuoteArgs

func QuoteArgs(args ...string) *Args

Build a shell command from multiple arguments.

func (*Args) Arg

func (a *Args) Arg(n int) string

Get the nth argument after interpreting shell quotes. Will panic if the argument index does not exist.

func (*Args) ArgSafe

func (a *Args) ArgSafe(n int) (string, error)

Get the nth argument after interpreting shell quotes.

func (*Args) Args

func (a *Args) Args() []string

Get all arguments after interpreting shell quotes.

func (*Args) Clone

func (a *Args) Clone() *Args

Make a deep copy of an Args object.

func (*Args) Count

func (a *Args) Count() int

Get the number of arguments after interpreting shell quotes.

func (*Args) Cut

func (a *Args) Cut(n int) []string

Same as CutSafe but cannot fail.

func (*Args) CutSafe

func (a *Args) CutSafe(n int) ([]string, error)

Remove n arguments from the end of the command line. Will fail if cutting an invalid number of arguments.

func (*Args) Extend

func (a *Args) Extend(cmd string)

Extend the command line with more arguments.

func (*Args) LeadingSpace added in v1.2.0

func (a *Args) LeadingSpace() string

func (*Args) Prepend

func (a *Args) Prepend(cmd string)

Insert the specified prefix at the beginning of the command line.

func (*Args) Shift

func (a *Args) Shift(n int) []string

Same as ShiftSafe but cannot fail.

func (*Args) ShiftSafe

func (a *Args) ShiftSafe(n int) ([]string, error)

Remove n arguments from the beginning of the command line. Same semantics as the `shift` built-in shell command. Will fail if shifting an invalid number of arguments.

func (*Args) String

func (a *Args) String() string

Get the raw command line, with uninterpreted shell quotes.

func (*Args) TrailingSpace added in v1.2.0

func (a *Args) TrailingSpace() string

type CmdSpec

type CmdSpec struct {
	// contains filtered or unexported fields
}

Command line options specifier

func NewCmdSpec

func NewCmdSpec(name string, v any) *CmdSpec

Interpret all struct fields to a list of option specs

func (*CmdSpec) GetCompletions

func (c *CmdSpec) GetCompletions(args *Args) ([]string, string)

func (*CmdSpec) ParseArgs

func (c *CmdSpec) ParseArgs(args *Args) error

func (*CmdSpec) Usage

func (c *CmdSpec) Usage() string

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL