argp

package module
v0.0.0-...-ab3be54 Latest Latest
Warning

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

Go to latest
Published: Mar 25, 2025 License: MIT Imports: 19 Imported by: 17

README

GNU command line argument parser

Command line argument parser following the GNU standard.

./test -vo out.png --size 256 input.txt

with the following features:

  • build-in help (-h and --help) message
  • scan arguments into struct fields with configuration in tags
  • scan into composite field types (arrays, slices, structs)
  • allow for nested sub commands

GNU command line argument rules:

  • arguments are options when they begin with a hyphen -
  • multiple options can be combined: -abc is the same as -a -b -c
  • long options start with two hyphens: --abc is one option
  • option names are alphanumeric characters
  • options can have a value: -a 1 means that a has value 1
  • option values can be separated by a space, equal sign, or nothing: -a1 -a=1 -a 1 are all equal
  • options and non-options can be interleaved
  • options may appear in any order
  • the argument -- terminates all options so that all following arguments are treated as non-options
  • an argument value of - is allowed, usually used to mean standard in or out streams
  • options may be specified multiple times, only the last one determines its value

Additional features:

  • counting options: -vvv sets v = 3
  • appending options: -v 1 -v 2 sets v = []int{1, 2}
  • boolean options: --var enables and --no-var disables a boolean
  • options can be composite types, such as structs, slices, or maps:
    • -v 1,2,3 sets v = []int{1, 2, 3}
    • -v [1 2 3] sets v = []int{1, 2, 3}
    • -v {1:one 2:two} sets map[int]string{1:"one", 2:"two"}
    • -v {string 42 [0 1]} sets struct{S string, I int, B [2]bool}{"string", 42, false, true}
  • options can retrieve their list/dict values from a source (such as SQL):
    • -v file:email-addresses.txt sets v = []string{ /* lines in email-addresses.txt */ }
    • -v file:email-addresses.txt sets v = map[string]string{ /* key=value in email-addresses.txt lines */ }

See also github.com/tdewolff/prompt for a command line prompter.

Installation

Make sure you have Git and Go (1.22 or higher) installed, run

mkdir Project
cd Project
go mod init
go get -u github.com/tdewolff/argp

Then add the following import

import (
    "github.com/tdewolff/argp"
)

Examples

Default usage

A regular command with short and long options. See cmd/test/main.go.

package main

import "github.com/tdewolff/argp"

func main() {
    var verbose int
    var input string
    var output string
    var files []string
    size := 512 // default value

    cmd := argp.New("CLI tool description")
    cmd.AddOpt(argp.Count{&verbose}, "v", "verbose", "Increase verbosity, eg. -vvv")
    cmd.AddOpt(&output, "o", "output", "Output file name")
    cmd.AddOpt(&size, "", "size", "Image size")
    cmd.AddArg(&input, "input", "Input file name")
    cmd.AddRest(&files, "files", "Additional files")
    cmd.Parse()

    // ...
}

with help output

Usage: test [options] input files...

Options:
  -h, --help          Help
  -o, --output string Output file name
      --size=512 int  Image size
  -v, --verbose int   Increase verbosity, eg. -vvv

Arguments:
  input     Input file name
  files     Additional files
Sub commands

Example with sub commands using a main command for when no sub command is used, and a sub command named "cmd". For the main command we can also use New and AddOpt instead and process the command after argp.Parse().

package main

import "github.com/tdewolff/argp"

func main() {
    cmd := argp.NewCmd(&Main{}, "CLI tool description")
    cmd.AddCmd(&Command{}, "cmd", "Sub command")
    cmd.Parse()
}

type Main struct {
    Version bool `short:"v"`
}

func (cmd *Main) Run() error {
    // ...
}

type Command struct {
    Verbose bool `short:"v" name:""`
    Output string `short:"o" desc:"Output file name"`
    Size int `default:"512" desc:"Image size"`
}

func (cmd *Command) Run() error {
    // ...
}
Arguments
var input string
cmd.AddArg(&input, "input", "Input file name")

var files []string
cmd.AddRest(&files, "files", "Additional input files")
Options

Basic types

var v string = "default"
cmd.AddOpt(&v, "v", "var", "description")

var v bool = true
cmd.AddOpt(&v, "v", "var", "description")

var v int = 42 // also: int8, int16, int32, int64
cmd.AddOpt(&v, "v", "var", "description")

var v uint = 42 // also: uint8, uint16, uint32, uint64
cmd.AddOpt(&v, "v", "var", "description")

var v float64 = 4.2 // also: float32
cmd.AddOpt(&v, "v", "var", "description")

Composite types

v := [2]int{4, 2} // element can be any valid basic or composite type
cmd.AddOpt(&v, "v", "var", "description")
// --var [4 2]  =>  [2]int{4, 2}
// or: --var 4,2  =>  [2]int{4, 2}

v := []int{4, 2, 1} // element can be any valid basic or composite type
cmd.AddOpt(&v, "v", "var", "description")
// --var [4 2 1]  =>  []int{4, 2, 1}
// or: --var 4,2,1  =>  []int{4, 2, 1}

v := map[int]string{1:"one", 2:"two"} // key and value can be any valid basic or composite type
cmd.AddOpt(&v, "v", "var", "description")
// --var {1:one 2:two}  =>  map[int]string{1:"one", 2:"two"}

v := struct { // fields can be any valid basic or composite type
    S string
    I int
    B [2]bool
}{"string", 42, [2]bool{0, 1}}
cmd.AddOpt(&v, "v", "var", "description")
// --var {string 42 [0 1]}  =>  struct{S string, I int, B [2]bool}{"string", 42, false, true}
Count

Count the number of time a flag has been passed.

var c int
cmd.AddOpt(argp.Count{&c}, "c", "count", "Count")
// Count the number of times flag is present
// -c -c / -cc / --count --count  =>  2
// or: -c 5  =>  5
Append

Append each flag to a list.

var v []int
cmd.AddOpt(argp.Append{&v}, "v", "value", "Values")
// Append values for each flag
// -v 1 -v 2  =>  [1 2]
Config

Load all arguments from a configuration file. Currently only TOML is supported.

cmd.AddOpt(&argp.Config{cmd, "config.toml"}, "", "config", "Configuration file")
List

Use a list source specified as type:list. Default supported types are: inline.

  • Inline takes a []string, e.g. inline:[foo bar]
list := argp.NewList(il)
defer list.Close()

cmd.AddOpt(&list, "", "list", "List")

You can add a MySQL source:

type mysqlList struct {
	Hosts    string
	User     string
	Password string
	Dbname   string
	Query    string
}

func newMySQLList(s []string) (argp.ListSource, error) {
	if len(s) != 1 {
		return nil, fmt.Errorf("invalid path")
	}

	t := mysqlList{}
	if err := argp.LoadConfigFile(&t, s[0]); err != nil {
		return nil, err
	}

	uri := fmt.Sprintf("%s:%s@%s/%s", t.User, t.Password, t.Hosts, t.Dbname)
	db, err := sqlx.Open("mysql", uri)
	if err != nil {
		return nil, err
	}
	db.SetConnMaxLifetime(time.Minute)
	db.SetConnMaxIdleTime(time.Minute)
	db.SetMaxOpenConns(10)
	db.SetMaxIdleConns(10)
	return argp.NewSQLList(db, t.Query, "")
}

// ...
list.AddSource("mysql", newMySQLList)
// ...

Use as ./bin -list mysql:list-config.toml.

Dict

Use a dict source specified as type:dict. Default supported types are: static and inline.

  • Static takes a string and will return that as a value for all keys, e.g. static:foobar
  • Inline takes a map[string]string, e.g. inline:{foo:1 bar:2}
dict := argp.NewDict([]string{"static:value"})
defer dict.Close()

cmd.AddOpt(&dict, "", "dict", "Dict")

You can add custom sources must like the mysqlList example above.

Option tags

The following struct will accept the following options and arguments:

  • -v or --var with a default value of 42
  • The first argument called first with a default value of 4.2
  • The other arguments called rest
type Command struct {
    Var1 int `short:"v" name:"var" default:"42" desc:"Description"`
    Var2 float64 `name:"first" index:"0" default:"4.2"`
    Var3 []string `name:"rest" index:"*"`
}

func (cmd *Command) Run() error {
    // run command
    return nil
}

License

Released under the MIT license.

Documentation

Index

Examples

Constants

This section is empty.

Variables

View Source
var ShowUsage error = fmt.Errorf("bad command usage")

ShowUsage can be returned from a command to show the help message.

Functions

func LoadConfigFile

func LoadConfigFile(dst interface{}, filename string) error

LoadConfigFile loads .cf, .cfg, .toml, and .yaml files.

func TerminalSize

func TerminalSize() (int, int, error)

func TypeName

func TypeName(t reflect.Type) string

TypeName returns the type's name.

func UnmarshalConfig

func UnmarshalConfig(b []byte, dst interface{}) error

UnmarshalConfig parses simple .cf or .cfg files.

Types

type Append

type Append struct {
	I interface{}
}

Append is an option that appends to a slice, e.g. -a 5 -a 6 sets the value to [5 6]

func (Append) Help

func (appnd Append) Help() (string, string)

func (Append) Scan

func (appnd Append) Scan(name string, s []string) (int, error)

type Argp

type Argp struct {
	Cmd
	Description string

	Error *log.Logger
	// contains filtered or unexported fields
}

Argp is a (sub) command parser

func New

func New(description string) *Argp

New returns a new command parser that can set options and returns the remaining arguments from `Argp.Parse`.

func NewCmd

func NewCmd(cmd Cmd, description string) *Argp

NewCmd returns a new command parser that invokes the Run method of the passed command structure. The `Argp.Parse()` function will not return and will call os.Exit() with 0, 1 or 2 as the argument.

func (*Argp) AddArg

func (argp *Argp) AddArg(dst interface{}, name, description string)

AddArg adds an indexed value

func (*Argp) AddCmd

func (argp *Argp) AddCmd(cmd Cmd, name, description string) *Argp

AddCmd adds a sub command

func (*Argp) AddOpt

func (argp *Argp) AddOpt(dst interface{}, short, name string, description string)

AddOpt adds an option

func (*Argp) AddRest

func (argp *Argp) AddRest(dst interface{}, name, description string)

func (*Argp) IsSet

func (argp *Argp) IsSet(name string) bool

IsSet returns true if the option is set

func (*Argp) Parse

func (argp *Argp) Parse()

Parse parses the command line arguments. When the main command was instantiated with `NewCmd`, this command will exit.

func (*Argp) PrintHelp

func (argp *Argp) PrintHelp()

PrintHelp prints the help overview. This is automatically called when unknown or bad options are passed, but you can call this explicitly in other cases.

type Cmd

type Cmd interface {
	Run() error
}

Cmd is a command

type Config

type Config struct {
	Argp     *Argp
	Filename string
}

Config is an option that sets all options from a configuration file.

func (*Config) Help

func (config *Config) Help() (string, string)

func (*Config) Scan

func (config *Config) Scan(name string, s []string) (int, error)

type Count

type Count struct {
	I interface{}
}

Count is a counting option, e.g. -vvv sets count to 3, or -v=3 sets it directly

Example
var count int
argp := New("count variable")
argp.AddOpt(Count{&count}, "c", "count", "")

_, _, err := argp.parse([]string{"-ccc"})
if err != nil {
	panic(err)
}
fmt.Println(count)
Output:

3

func (Count) Help

func (count Count) Help() (string, string)

func (Count) Scan

func (count Count) Scan(name string, s []string) (int, error)

type Custom

type Custom interface {
	Help() (string, string)             // value and type representations for help
	Scan(string, []string) (int, error) // scan values from command line
}
Example
custom := CustomVar{}
argp := New("custom variable")
argp.AddOpt(&custom, "", "custom", "")

_, _, err := argp.parse([]string{"--custom", "1", "/", "2"})
if err != nil {
	panic(err)
}
fmt.Println(custom.Num, "/", custom.Div)
Output:

1 / 2

type Dict

type Dict struct {
	DictSource
	Sources map[string]DictSourceFunc
	Values  []string
}

Dict is an option that loads key-value map from a source (such as mysql).

func NewDict

func NewDict(values []string) *Dict

func (*Dict) AddSource

func (dict *Dict) AddSource(typ string, f DictSourceFunc)

func (*Dict) Close

func (dict *Dict) Close() error

func (*Dict) Help

func (dict *Dict) Help() (string, string)

func (*Dict) Scan

func (dict *Dict) Scan(name string, s []string) (int, error)

func (*Dict) Valid

func (dict *Dict) Valid() bool

type DictSource

type DictSource interface {
	Has(string) (bool, error)
	Get(string) (string, error)
	Close() error
}

func NewFileDict

func NewFileDict(s []string) (DictSource, error)

func NewInlineDict

func NewInlineDict(s []string) (DictSource, error)

func NewStaticDict

func NewStaticDict(s []string) (DictSource, error)

type DictSourceFunc

type DictSourceFunc func([]string) (DictSource, error)

type FileDict

type FileDict struct {
	InlineDict
}

type FileList

type FileList struct {
	InlineList
}

type InlineDict

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

func (*InlineDict) Close

func (t *InlineDict) Close() error

func (*InlineDict) Get

func (t *InlineDict) Get(key string) (string, error)

func (*InlineDict) Has

func (t *InlineDict) Has(key string) (bool, error)

type InlineList

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

func (*InlineList) Close

func (t *InlineList) Close() error

func (*InlineList) Has

func (t *InlineList) Has(val string) (bool, error)

func (*InlineList) List

func (t *InlineList) List() ([]string, error)

type List

type List struct {
	ListSource
	Sources map[string]ListSourceFunc
	Values  []string
}

List is an option that loads a list of values from a source (such as mysql).

func NewList

func NewList(values []string) *List

func (*List) AddSource

func (list *List) AddSource(typ string, f ListSourceFunc)

func (*List) Close

func (list *List) Close() error

func (*List) Help

func (list *List) Help() (string, string)

func (*List) Scan

func (list *List) Scan(name string, s []string) (int, error)

func (*List) Valid

func (list *List) Valid() bool

type ListSource

type ListSource interface {
	Has(string) (bool, error)
	List() ([]string, error)
	Close() error
}

func NewFileList

func NewFileList(s []string) (ListSource, error)

func NewInlineList

func NewInlineList(s []string) (ListSource, error)

type ListSourceFunc

type ListSourceFunc func([]string) (ListSource, error)

type SQLDict

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

func NewSQLDict

func NewSQLDict(db *sqlx.DB, query string) (*SQLDict, error)

func (*SQLDict) Close

func (t *SQLDict) Close() error

func (*SQLDict) Get

func (t *SQLDict) Get(key string) (string, error)

func (*SQLDict) Has

func (t *SQLDict) Has(key string) (bool, error)

type SQLList

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

func NewSQLList

func NewSQLList(db *sqlx.DB, query, queryHas string, cacheDur time.Duration) (*SQLList, error)

func (*SQLList) Close

func (t *SQLList) Close() error

func (*SQLList) Has

func (t *SQLList) Has(val string) (bool, error)

func (*SQLList) List

func (t *SQLList) List() ([]string, error)

type StaticDict

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

func (*StaticDict) Close

func (t *StaticDict) Close() error

func (*StaticDict) Get

func (t *StaticDict) Get(key string) (string, error)

func (*StaticDict) Has

func (t *StaticDict) Has(key string) (bool, error)

type Var

type Var struct {
	Value       reflect.Value
	Name        string
	Short       rune // 0 if not used
	Index       int  // -1 if not used
	Rest        bool
	Default     interface{} // nil is not used
	Description string
	// contains filtered or unexported fields
}

Var is a command option or argument

func (*Var) IsArgument

func (v *Var) IsArgument() bool

IsArgument returns true for an argument

func (*Var) IsOption

func (v *Var) IsOption() bool

IsOption returns true for an option

func (*Var) Set

func (v *Var) Set(i interface{}) bool

Set sets the variable's value

Directories

Path Synopsis
cmd

Jump to

Keyboard shortcuts

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