args

package module
v0.10.0 Latest Latest
Warning

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

Go to latest
Published: Mar 3, 2023 License: MIT Imports: 1 Imported by: 2

README

Package args implements command-line arguments parsing.

Usage

Construct a new parser using args.NewParser().

This constructs a new Parser struct and returns a pointer to it:

import "github.com/amedmoore/go-args"
parser := args.NewParser()

You can pass the arguments slice to be parsed to this function.

parser := args.NewParser(os.Args[1:])

Or you can pass it later to the parser.Parse() function.

IMPORTANT NOTE is that you have to pass the args slice to one of these function, otherwise the parser will act as if you passed an empty slice.

After you construct the parser struct, call

parser.Parse()

to parse the arguments into three categories positional, options, and arguments.

Parsed arguments may then be accessed using one of the following accessors:

To access positional argument use

parser.At(index)

To ask if an option exists use

parser.HasOption("--my-option")

To access value of an argument use

parser.GetString("--my-arg")

if multiple values was passed with the same name, parser.GetString() will return the first value FROM THE RIGHT SIDE, meaning if your command was

$ myapp --my-arg val0 --my-arg val1 --my-arg val2

parser.GetString("--my-arg") will return "val2"

If your program allow passing multiple values to the same argument use

parser.Get("--my-arg")

this will return a slice that includes all values for the argument "--my-arg"

Command line arguments syntax

The following forms are permitted:

arg
-o
--option
-a val
--arg val

where arg represents a positional argument, -o, and --option represents options, and -a val, and --arg val represents arguments with value.

One or two minus signs (hyphens) may be used; they are equivalent.

Testing

  • On Windows:

    $ go test -bench .
    goos: windows
    goarch: amd64
    pkg: github.com/amedmoore/go-args
    cpu: Intel(R) Core(TM) i7-10870H CPU @ 2.20GHz
    Benchmark_Parser_Parse-16           1000000000
    PASS
    ok      github.com/amedmoore/go-args        0.025s
    
  • On Mac:

    $ go test -bench .
    goos: darwin
    goarch: arm64
    pkg: github.com/amedmoore/go-args
    Benchmark_Parser_Parse-8      1000000000      0.0000110 ns/op
    PASS
    ok      github.com/amedmoore/go-args        0.729s
    

TODO

  • Better error handling.
  • Support for the (--arg=val) syntax.
  • Support for the Windows (/opt, /arg val, and /arg=val) syntax.
  • Maybe add auto-cast for argument values? like GetString() string, GetInt() int, and GetBool() bool, etc...
  • Allow alternative names lookup in argument accessor functions (i.e. GetString("-h", "--help"))
  • Add type alias Parser for the struct ArgsParser.

License

This package is licensed under the MIT License feel free to use it as you want!

Documentation

Index

Constants

View Source
const FlagPrefix = '-'

FlagPrefix defines the special character used to indicate that this arg is a flag, we use this instead of a hard coded value to make it easier if we want to support platform-specific syntax in the future (i.e. the /arg syntax in Windows).

Variables

This section is empty.

Functions

This section is empty.

Types

type Parser

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

Parser is the main struct that does the parsing and hold the results.

func NewParser

func NewParser(args ...[]string) *Parser

NewParser constructs a new Parser struct and returns a pointer to it.

Optionally you can pass the arguments slice to be parsed to this function, example:

parser := args.NewParser(os.Args[1:])

Please note that you have to pass the arguments slice to either this or the `Parse()` function.

func (*Parser) Args

func (p *Parser) Args() []map[string]string

Args returns the parsed arguments (if has value) in the form of a slice of key-value pairs.

Make sure to call `Parse()` before using this function.

func (*Parser) At

func (p *Parser) At(index int) (string, bool)

At returns the positional argument in the specified index, and a bool value indicates weither the positional argument exists.

If the specified index was not found (out-of-index) the first return value will be an empty string.

Make sure to call `Parse()` before using this function.

func (*Parser) Get

func (p *Parser) Get(name string, alts ...string) []string

Get return all values provided with the given name. example:

$ myapp --name foo --name bar --name baz

names := parser.Get("--name")
for _, name := range names {
	print(name)
}

Get() allow alternative names lookup, example:

names := parser.Get("--name", "-n")

Make sure to call `Parse()` before using this function.

func (*Parser) GetInt

func (p *Parser) GetInt(name string, alts ...string) int64

GetInt returns the value of the given argument name.

If multiple values found with the same name, the first one from the right will be returned, example:

$ myapp --age 18 --age 21 --age 30

age := parser.GetInt("--age")
print(age) // 30

GetInt() allow alternative age lookup, example:

$ myapp --name foo -a 30

age := parser.LookupString("--age", "-a")
print(age) // 30

GetInt() returns -1 If argument was not found.

GetInt() panics if the argument was found but

was an invalid int value.

Make sure to call `Parse()` before using this function.

func (*Parser) GetString

func (p *Parser) GetString(name string, alts ...string) string

GetString returns the value of the given argument name.

If multiple values found with the same name, the first one from the right will be returned, example:

$ myapp --name foo --name bar --name baz

name := parser.GetString("--name")
print(name) // baz

GetString() allow alternative name lookup, example:

names := parser.GetString("--name", "-n")

Make sure to call `Parse()` before using this function.

func (*Parser) HasOption

func (p *Parser) HasOption(option string, alts ...string) bool

HasOption asks if a specific option was provided, example:

if parser.HasOption("-h") {
	// display help message!
}

HasOption also supports alias names lookup, example:

if parser.HasOption("--help", "-h") {
	// display help message!
}

Make sure to call `Parse()` before using this function.

func (*Parser) LookupInt

func (p *Parser) LookupInt(name string, alts ...string) (int64, bool)

LookupInt returns the value of the given argument name, and a bool value indicates weither the argument exists.

If multiple values found with the same name, the first one from the right will be returned, example:

$ myapp --age 18 --age 21 --age 30

age, exists := parser.GetInt("--age")
print(age)    // 30
print(exists) // true

LookupInt() allow alternative name lookup, example:

$ myapp --name foo -a 30

age, exists := parser.LookupInt("--age", "-a")
print(age)    // 30
print(exists) // true

LookupInt() returns -1 If argument was not found.

LookupInt() panics if the argument was found but

was an invalid int value.

Make sure to call `Parse()` before using this function.

func (*Parser) LookupString

func (p *Parser) LookupString(name string, alts ...string) (string, bool)

LookupString returns the value of the given argument name, and a bool value indicates weither the argument exists.

If multiple values found with the same name, the first one from the right will be returned, example:

$ myapp --name foo --name bar --name baz

name, exists := parser.LookupString("--name")
print(name)   // baz
print(exists) // true

LookupString() allow alternative name lookup, example:

$ myapp --age 30 -n bar

name, exists := parser.LookupString("--name", "-n")
print(name)   // bar
print(exists) // true

Make sure to call `Parse()` before using this function.

func (*Parser) Options

func (p *Parser) Options() []string

Options returns the parsed options in the form of string-slice.

Make sure to call `Parse()` before using this function.

func (*Parser) Parse

func (p *Parser) Parse(args ...[]string) error

Parse parses the command-line arguments and store, the result into the owner struct.

Optionally you can pass the arguments slice to be parsed to this function, example:

parser := args.NewParser()
parser.Parse(os.Args[1:])

Please note that arguments passed to this function will be ignored if you declared the parser struct with initial arguments, like:

parser := args.NewParser(os.Args[1:])

func (*Parser) Positional

func (p *Parser) Positional() []string

Positional returns the parsed positional arguments in the form of string-slice.

Make sure to call `Parse()` before using this function.

Directories

Path Synopsis
examples
simple Module

Jump to

Keyboard shortcuts

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