opts

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: May 28, 2022 License: MIT Imports: 13 Imported by: 0

README

opts

Go Reference

Package opts makes it easy to create CLIs by defining options using struct tags.

Example

package main

import (
	"fmt"

	"github.com/isobit/opts"
)

type App struct {
	Excited  bool   `opts:"help='when true, use exclamation point'"`
	Greeting string `opts:"env=GREETING,help=the greeting to use"`
	Name     string `opts:"required,short=n,help=your name"`
}

func (app *App) Run() error {
	punctuation := "."
	if app.Excited {
		punctuation = "!"
	}
	fmt.Printf("%s, %s%s\n", app.Greeting, app.Name, punctuation)
	return nil
}

func main() {
	opts.New("greet", &App{Greeting: "Hey"}).
		Parse().
		RunFatal()
}
$ greet --help
USAGE:
    greet [OPTIONS]

OPTIONS:
    -h, --help                    show usage help
    --excited                     when true, use exclamation point
    --greeting <VALUE>  GREETING  the greeting to use  (default: Hey)
    -n, --name <VALUE>            your name  (required)

$ GREETING="Hello" greet -n world --excited
Hello, world!

Struct Tags

The parsing behavior for config fields can be controlled by adding a struct tag that opts understands. Opts struct tags look like opts:"key1,key2=value,key3='blah'"; for example:

struct Example {
	Foo string `opts:"required,placeholder=quux,short=f,env=FOO,help='hello, world'"`
}
Tag Value Description
- No Ignore field (similar to encoding/json)
required No Error if the field is not set at least once
help Yes Custom help text
placeholder Yes Custom help text
name Yes Explicit flag name (by default names are derived from the struct field name)
short Yes Single character short name alias
env Yes Environment variable to use as a default value
repeatable No Allow flag to be specified many times (value must be a slice type, each flag will be appended)

Tags are parsed according to this ABNF:

tags = "opts:" DQUOTE *(tag ",") tag DQUOTE
tag = key [ "=" value ]
key = *<anything except "=">
value = *<anything except ","> / "'" *<anything except "'"> "'"

Field Types and Flag Parsing

Primitive types (e.g. int and string), and pointers to primitive types (e.g. *int and *string) are handled natively by opts. In the case of pointers, if the default value is a nil pointer, and a value is passed, opts will construct a new value of the inner type and set the struct field to be a pointer to the newly constructed value.

There is no special parsing for string fields, they are set directly from input.

The following primitives are parsed by fmt.Sscanf using the %v directive:

  • bool
  • int, int8, int16, int32, int64
  • uint8, uint16, uint32, uint64
  • float32, float64

Additionally, time.Duration fields are automatically parsed using time.ParseDuration.

All other types are parsed using the first method below that is implemented with the type itself or a pointer to the type as the receiver:

  • Set(s string) error (similar to flag.Value)
  • UnmarshalText(text []byte) error (encoding.TextUnmarshaler)
  • UnmarshalBinary(data []byte) error (encoding.BinaryUnmarshaler)

Many standard library types already implement one of these methods. For example, time.Time implements encoding.TextUnmarshaler for parsing RFC 3339 timestamps.

Custom types can be used so long as they implement one of the above methods. Here is an example which parses a string slice from a comma-delimited flag value string:

type App struct {
	Foos Foos
}

type Foos []string

func (foos *Foos) UnmarshalText(text []byte) error {
	s := string(text)
	*foos = append(*foos, strings.Split(s, ",")...)
	return nil
}

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrHelp = fmt.Errorf("opts: help requested")

Functions

This section is empty.

Types

type Beforer

type Beforer interface {
	Before() error
}

type Opts

type Opts struct {
	Name      string
	ShortName string
	Help      string
	ShortHelp string
	// contains filtered or unexported fields
}

func Build

func Build(name string, config interface{}) (*Opts, error)

Build is like New, but it returns any errors instead of calling panic, at the expense of being harder to chain.

func New

func New(name string, config interface{}) *Opts

New creates a new Opts with the provided name and config. The config must be a pointer to a configuration struct. Default values can be specified by simply setting them on the config struct.

New returns an Opts pointer for further method chaining. If an error is encountered while building the options, such as a struct field having an unsupported type, New will panic. If you would like to have errors returned for handling, use Build instead.

func (*Opts) AddCommand

func (opts *Opts) AddCommand(cmdOpts *Opts) *Opts

AddCommand registers another Opts instance as a subcommand of this Opts instance.

func (*Opts) AddCommands

func (opts *Opts) AddCommands(cmds []*Opts) *Opts

AddCommands registers multiple Opts instances as subcommands of this Opts instance.

func (*Opts) HelpString

func (opts *Opts) HelpString() string

func (*Opts) Parse

func (opts *Opts) Parse() ParsedOpts

Parse is a convenience method for calling ParseArgs(os.Args)

func (*Opts) ParseArgs

func (opts *Opts) ParseArgs(args []string) ParsedOpts

ParseArgs parses using the passed-in args slice and OS-provided environment variables and returns a ParsedOpts instance which can be used for further method chaining.

If there are args remaining after parsing this Opts' fields, subcommands will be parsed recursively. The returned ParsedOpts.Runner represents the command which was specified (if it has a Run method). If a Before method is implemented on the Opts' config, this method will call it before recursing into any subcommand parsing.

func (*Opts) SetHelp

func (opts *Opts) SetHelp(help string) *Opts

SetHelp configures the command help string.

func (*Opts) SetShortHelp

func (opts *Opts) SetShortHelp(help string) *Opts

SetHelp configures the command short help string.

func (*Opts) SetShortName

func (opts *Opts) SetShortName(shortName string) *Opts

SetShortName configures a short alias for the command.

func (*Opts) WriteHelp

func (opts *Opts) WriteHelp(w io.Writer)

type ParsedOpts

type ParsedOpts struct {
	Err    error
	Opts   *Opts
	Runner Runner
}

func (ParsedOpts) Run

func (po ParsedOpts) Run() error

Run calls the Run method of the Opts config for the parsed command or, if an error occurred during parsing, prints the help text and returns that error instead. If help was requested, the error will flag.ErrHelp.

func (ParsedOpts) RunFatal

func (po ParsedOpts) RunFatal()

RunFatal is like Run, except it automatically handles printing out any errors returned by the Run method of the underlying Opts config, and exits with an appropriate status (1 if error, 0 otherwise).

type Runner

type Runner interface {
	Run() error
}

Jump to

Keyboard shortcuts

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