cmdline

package module
v0.15.3 Latest Latest
Warning

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

Go to latest
Published: Oct 29, 2023 License: MIT Imports: 10 Imported by: 28

README

Go Code coverage Maintainability

Package cmdline provides a parser for command line arguments. This package is different from the builtin package flag.

  • Options are used when parsing arguments
  • Flag is a boolean option
  • Self documenting options are preferred
  • Multiname options, e.g. -n, --dry-run map to same option
  • Easy way to default to environment variables
  • There are no pointer variations
  • Parsing non option arguments
  • Usage output with optional examples and preface

Example

func ExampleNewBasicParser() {
	os.Setenv("VERBOSE", "yes")
	var (
		cli		= NewBasicParser()
		uid		= cli.Option("--uid", "Generated if not given").Int(0)
		password	= cli.Option("-p, --password, $PASSWORD").String("")
		verbose		= cli.Flag("-V, --verbose, $VERBOSE")
		role		= cli.Option("-r, --role").Enum("guest",
			"guest", "admin", "nobody",
		)
		url	= cli.Option("--test-host").Url("tcp://example.com:123")
		dur	= cli.Option("--pause").Duration("200ms")

		// parse and name non options
		username	= cli.NamedArg("USERNAME").String("")
		note		= cli.NamedArg("NOTE").String("")
	)
	cli.Parse()

	if !verbose {
		log.SetOutput(ioutil.Discard)
	}
	fmt.Fprintln(os.Stdout, uid, username, password, note, role, url, dur)
}

Documentation

Overview

Package cmdline provides a way to parse command line arguments.

Example (EnvOption)
os.Setenv("PASSWORD", "secret")
os.Setenv("VERBOSE", "true")
var (
	cli     = NewParser()
	pass    = cli.Option("-p, --password, $PASSWORD").String("")
	verbose = cli.Flag("-V, --verbose, $VERBOSE")
)
fmt.Println(pass, verbose)
Output:

secret true

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func ParseBool added in v0.11.0

func ParseBool(v string) (bool, error)

ParseBool returns true if the string evaluates to a true expression. See example for possible values.

Example
in := []string{
	"1", "y", "yes", "Yes", "YES", "true", "True", "TRUE",
	"0", "n", "no", "No", "NO", "false", "False", "FALSE", "",
}
for _, v := range in {
	got, _ := ParseBool(v)
	fmt.Printf("%-5s %v\n", v, got)
}
_, err := ParseBool("other")
fmt.Println(err)
Output:

1     true
y     true
yes   true
Yes   true
YES   true
true  true
True  true
TRUE  true
0     false
n     false
no    false
No    false
NO    false
false false
False false
FALSE false
      false
parse bool "other"

Types

type Basic added in v0.6.0

type Basic struct {
	*Parser
	// contains filtered or unexported fields
}

func NewBasicParser added in v0.6.0

func NewBasicParser() *Basic

NewBasicParser returns a parser including help options -h, --help.

Example
os.Setenv("VERBOSE", "yes")
var (
	cli      = NewBasicParser()
	uid      = cli.Option("--uid", "Generated if not given").Int(0)
	password = cli.Option("-p, --password, $PASSWORD").String("")
	verbose  = cli.Flag("-V, --verbose, $VERBOSE")
	role     = cli.Option("-r, --role").Enum("guest",
		"guest", "admin", "nobody",
	)
	url = cli.Option("--test-host").Url("tcp://example.com:123")
	dur = cli.Option("--pause").Duration("200ms")

	// parse and name non options
	username = cli.NamedArg("USERNAME").String("")
	note     = cli.NamedArg("NOTE").String("")
)
cli.Parse()

// use options ...
if !verbose {
	log.SetOutput(ioutil.Discard)
}
fmt.Fprintln(os.Stdout, uid, username, password, note, role, url, dur)
Output:

func (*Basic) Parse added in v0.6.0

func (me *Basic) Parse()

Parse checks for errors or if the help flag is given writes usage to os.Stdout

func (*Basic) Usage added in v0.7.0

func (me *Basic) Usage() *Usage

Usage returns the usage for further documentation. If Parse method has not been called, it adds the help flag.

type Group

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

func (*Group) Items

func (me *Group) Items() []*Item

func (*Group) New

func (me *Group) New(name string, any interface{}) *Item

func (*Group) Selected

func (me *Group) Selected() interface{}

Selected returns the matching item. Defaults to the first in the group.

func (*Group) Title

func (me *Group) Title() string

type Item

type Item struct {
	Name   string
	Loader interface{}
}

func (*Item) Load

func (me *Item) Load(p *Parser) interface{}

Load returns the item with extra options if it implements WithExtraOptions interface.

type NamedArg added in v0.9.0

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

func (*NamedArg) String added in v0.9.0

func (me *NamedArg) String(def string) string

String returns the value of this NamedArg or the given default

func (*NamedArg) Strings added in v0.9.0

func (me *NamedArg) Strings(def ...string) []string

Strings returns the values of this argument. If no default is given this NamedArg is considered required.

type Option

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

Option defines a command line option, ie. --username

func NewOption

func NewOption(names string, args ...string) *Option

NewOption returns an option defined by a comma separated list of names and arguments to match against. Usually you would call Parser.Option(names) over this.

func (*Option) Bool

func (opt *Option) Bool(def bool) bool

Bool returns bool value from the arguments or the given default value.

func (*Option) BoolOpt

func (opt *Option) BoolOpt() (bool, *Option)

BoolOpt returns bool value from the arguments. The Option is returned for more configuration.

func (*Option) Doc

func (opt *Option) Doc(lines ...string)

Doc sets the documentation lines for this option.

func (*Option) Duration added in v0.12.0

func (opt *Option) Duration(def string) time.Duration
Example
var (
	cli = NewParser()
	u   = cli.Option("-d, --duration").Duration("199µs")
)
fmt.Println(u.Microseconds())
Output:

199

func (*Option) DurationOpt added in v0.12.0

func (opt *Option) DurationOpt(def string) (time.Duration, *Option)

func (*Option) Enum added in v0.10.0

func (opt *Option) Enum(def string, possible ...string) string

Enum same as EnumOpt but does not return the Option

Example
os.Args = []string{"mycmd"} // just for this test
cli := NewParser()
cli.Option("-a, --animal").Enum("snake", "snake", "bear", "goat")

cli.Usage().WriteTo(os.Stdout)
Output:


Usage: mycmd [OPTIONS]

Options
    -a, --animal : "snake" [snake bear goat]

func (*Option) EnumOpt added in v0.10.0

func (opt *Option) EnumOpt(def string, possible ...string) (string, *Option)

Enum returns an enumerated string. It's ok to only have one.

func (*Option) Float64

func (opt *Option) Float64(def float64) float64

Float64 returns float64 value from the arguments or the given default value.

func (*Option) Float64Opt

func (opt *Option) Float64Opt(def float64) (float64, *Option)

Float64Opt returns float64 value from the arguments or the given default value.

func (*Option) Int

func (opt *Option) Int(def int) int

Int same as IntOpt but does not return the Option.

func (*Option) IntOpt

func (opt *Option) IntOpt(def int) (int, *Option)

IntOpt returns int value from the arguments or the given default value.

func (*Option) String

func (opt *Option) String(def string) string

String same as StringOpt but does not return the Option.

func (*Option) StringOpt

func (opt *Option) StringOpt(def string) (string, *Option)

StringOpt returns string value from the arguments or the given default value.

func (*Option) Uint

func (opt *Option) Uint(def uint64) uint64

Uint same as UintOpt but does not return the Option

func (*Option) Uint16

func (opt *Option) Uint16(def uint16) uint16

Uint16 same as uint16(Uint(...))

func (*Option) Uint32

func (opt *Option) Uint32(def uint32) uint32

Uint32 same as uint32(Uint(...))

func (*Option) Uint8

func (opt *Option) Uint8(def uint8) uint8

Uint8 same as uint8(Uint(...))

func (*Option) UintOpt

func (opt *Option) UintOpt(def uint64) (uint64, *Option)

UintOpt returns an unsigned int option

func (*Option) Url added in v0.12.0

func (opt *Option) Url(def string) *url.URL
Example
var (
	cli = NewParser()
	u   = cli.Option("-s, --server").Url("tcp://127.0.0.1:2345")
)
fmt.Println(u.Scheme, u.Hostname(), u.Port())
Output:

tcp 127.0.0.1 2345

func (*Option) UrlOpt added in v0.12.0

func (opt *Option) UrlOpt(def string) (*url.URL, *Option)

type Parser

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

Parser groups arguments for option parsing and usage.

Example (UsageHiddenPassword)
cli := NewParser()
cli.args = []string{"adduser"}
_, opt := cli.Option("--uid").IntOpt(0)
opt.Doc("If not given, one is generated")
cli.Option("-p, --password",
	"minimum 8 chars",
	"hidden",
).String("secret")

cli.Usage().WriteTo(os.Stdout)
Output:

Usage: adduser [OPTIONS]

Options
    --uid : 0
        If not given, one is generated

    -p, --password : "********"
        minimum 8 chars

func NewParser

func NewParser() *Parser

NewParser returns a parser using the DefaultShell

Example
var (
	cli      = NewParser()
	uid      = cli.Option("--uid", "Generated if not given").Int(0)
	password = cli.Option("-p, --password, $PASSWORD").String("")
	help     = cli.Flag("-h, --help")

	// parse and name non options
	username = cli.NamedArg("USERNAME").String("")
	note     = cli.NamedArg("NOTE").String("")
)

switch {
case help:
	cli.Usage().WriteTo(os.Stdout)
	os.Exit(0)

case !cli.Ok():
	fmt.Fprintln(os.Stderr, cli.Error())
	fmt.Fprintln(os.Stderr, "Try --help for more information")
	os.Exit(1)
}

// use options ...
fmt.Fprintln(os.Stdout, uid, username, password, note)
Output:

func (*Parser) Argn

func (me *Parser) Argn(n int) string

Argn returns the n:th of remaining arguments starting at 0.

func (*Parser) Args

func (me *Parser) Args() []string

Args returns arguments not matched by any of the options

func (*Parser) Error

func (me *Parser) Error() error

Error returns first error of the given options.

func (*Parser) Flag

func (me *Parser) Flag(name string) bool

Flag is short for Option(name).Bool()

func (*Parser) Group

func (me *Parser) Group(title, name string) *Group

func (*Parser) NamedArg added in v0.9.0

func (me *Parser) NamedArg(name string) *NamedArg

NamedArg returns an named argument

func (*Parser) Ok

func (me *Parser) Ok() bool

Ok returns true if no parsing error occured

func (*Parser) Option

func (me *Parser) Option(names string, doclines ...string) *Option

Option returns a new option with the given names. Names should be a comma separated string, e.g.

-n, --dry-run

You can also include an environment variable to use as default value in the names, e.g.

-t, --token, $COGNITO_TOKEN

func (*Parser) Parse added in v0.6.0

func (me *Parser) Parse()

Parse checks parsing errors and exits on errors

func (*Parser) Preface added in v0.7.0

func (me *Parser) Preface(lines ...string)

Preface is the same as Usage().Preface

func (*Parser) SetShell added in v0.8.0

func (me *Parser) SetShell(sh Shell)

func (*Parser) String

func (me *Parser) String() string

func (*Parser) Usage added in v0.7.0

func (me *Parser) Usage() *Usage

Usage returns the currently documented options for further documentation.

Example (OptionalNamedArguments)
os.Args = []string{"mycmd"} // just for this test
cli := NewBasicParser()
cli.NamedArg("FILES...").Strings("file1", "file2")
cli.Usage().WriteTo(os.Stdout)
Output:


Usage: mycmd [OPTIONS] [FILES...]

Options
    -h, --help
Example (RequiredNamedArguments)
os.Args = []string{"mycmd", "-h"} // just for this test
cli := NewBasicParser()
cli.NamedArg("FILES...").Strings()
cli.Usage().WriteTo(os.Stdout)
Output:


Usage: mycmd [OPTIONS] FILES...

Options
    -h, --help

type Shell added in v0.8.0

type Shell interface {
	Getenv(string) string
	Args() []string
	Getwd() (string, error)
	Stdin() io.Reader
	Stdout() io.Writer
	Stderr() io.Writer
	Exit(code int)
	Fatal(v ...interface{})
}

Shell defines a command line execution context.

var DefaultShell Shell = NewShellOS()

DefaultShell is used by all new parsers.

type ShellOS added in v0.8.0

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

ShellOS uses package os

func NewShellOS added in v0.8.0

func NewShellOS() *ShellOS

NewShellOS returns a shell from the os values.

func (*ShellOS) Args added in v0.8.0

func (me *ShellOS) Args() []string

Args returns os.Args

func (*ShellOS) Exit added in v0.8.0

func (me *ShellOS) Exit(code int)

Exit returns the given exit code

func (*ShellOS) Fatal added in v0.8.0

func (me *ShellOS) Fatal(v ...interface{})

func (*ShellOS) Getenv added in v0.8.0

func (me *ShellOS) Getenv(key string) string

Getenv returns os.Getenv

func (*ShellOS) Getwd added in v0.8.0

func (me *ShellOS) Getwd() (string, error)

Getwd returns os.Getwd

func (*ShellOS) Stderr added in v0.8.0

func (me *ShellOS) Stderr() io.Writer

Stderr returns os.Stderr

func (*ShellOS) Stdin added in v0.8.0

func (me *ShellOS) Stdin() io.Reader

Stdin returns os.Stdin

func (*ShellOS) Stdout added in v0.8.0

func (me *ShellOS) Stdout() io.Writer

Stdout returns os.Stdout

type Usage added in v0.7.0

type Usage struct {
	*Parser
	// contains filtered or unexported fields
}

type Usage is for documenting the configured parser

func (*Usage) Example added in v0.7.0

func (me *Usage) Example(lines ...string)

Example adds an examples section. The examples are placed last after options and named arguments. Examples are plain text and not evaluated in any way.

func (*Usage) Preface added in v0.7.0

func (me *Usage) Preface(lines ...string)

Preface adds lines just before the options section

func (*Usage) WriteOptionsTo added in v0.7.0

func (me *Usage) WriteOptionsTo(w io.Writer)

WriteOptionsTo writes the Options section to the given writer.

func (*Usage) WriteTo added in v0.7.0

func (me *Usage) WriteTo(w io.Writer) (int64, error)

WriteUsageTo writes names, defaults and documentation to the given writer with the first line being

Usage: COMMAND [OPTIONS] ARGUMENTS...

type WithExtraOptions

type WithExtraOptions interface {
	// ExtraOptions is used to parse extra options for a grouped item
	ExtraOptions(*Parser)
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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