argparse

package module
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Mar 5, 2023 License: MIT Imports: 8 Imported by: 0

README

argparse

Project Status

⚠️ No Longer Supported ⚠️

There are a variety of Golang command-line libraries currently available. Right now development on argparse has stagnated. I am planning on revamp the library to attempt to bring it back to its roots, as well as improve the underlying code.

Try one of the libraries here, instead: https://github.com/avelino/awesome-go#command-line




CircleCI GoDoc Go Report Card

Contents

Description

clagraff/argparse is a golang library for command-line argument parsing. It is heavily influenced by the functionallity found in Python3's argparse package.

clagraff/argparse places a focus on method-chaining for setting up options, flags, and parsers, and supports a variety of features.

Install

Stable V1.x.x version

go get gopkg.in/clagraff/argparse.v1

Development version

$ go get github.com/clagraff/argparse

Boom! All set! Feel free to read on for examples on getting started and using this package.

The Basics

Create a parser

Here we have a basic program which greets a user by a provided name, optionally in uppercase. We need create a parser, include our option and flag, and then parse our programs arguments. It could look something like:

package main

import (
	"fmt"
	"os"
	"strings"

	"github.com/clagraff/argparse"
)

func callback(p *argparse.Parser, ns *argparse.Namespace, leftovers []string, err error) {
	if err != nil {
		switch err.(type) {
		case argparse.ShowHelpErr, argparse.ShowVersionErr:
			// For either ShowHelpErr or ShowVersionErr, the parser has already
			// displayed the necessary text to the user. So we end the program
			// by returning.
			return
		default:
			fmt.Println(err, "\n")
			p.ShowHelp()
		}

		return // Exit program
	}

	name := ns.Get("name").(string)
	upper := ns.Get("upper").(string) == "true"

	if upper == true {
		name = strings.ToUpper(name)
	}

	fmt.Printf("Hello, %s!\n", name)
	if len(leftovers) > 0 {
		fmt.Println("\nUnused args:", leftovers)
	}
}

func main() {
	p := argparse.NewParser("Output a friendly greeting", callback).Version("1.3.0a")
	p.AddHelp().AddVersion() // Enable help and version flags

	upperFlag := argparse.NewFlag("u", "upper", "Use uppercase text").Default("false")
	nameOption := argparse.NewArg("n name", "name", "Name of person to greet").Default("John").Required()

	p.AddOptions(upperFlag, nameOption)

	// Parse all available program arguments (except for the program path).
	p.Parse(os.Args[1:]...)
}

You could then run it and receive the following output:

> go run main.go Luke
Hello, Luke!

> go run main.go Vader -u
Hello, VADER!

> go run main.go
n, name: too few arguments

usage: main [-h] [-v] [-u] n NAME

Output a friendly greeting

positional arguments:
  n NAME       Name of person to greet

optional arguments:
  -h, --help     Show program help
  -v, --version  Show program version
  -u, --upper    Use uppercase text

Arguments

Arguments are command-line values passed to the program when its execution starts. When these values are expected by the program, we use a convention of classifying these arguments into two types: Flags and Options.

Types
Flags

Flags represent non-positional, boolean arguments. These arguments are "false" by default, will utilize the argparse.StoreTrue action. They do not consume any additional arguments other than themselves. You can create a new flag using:

// Create a short and long flag for "use-default", -d --default, with a description.
use_default := argparse.NewFlag("d default", "use-default", "Enable the default mode")

argparse.Option is the struct used for creating parseable options.

Options

Options are arguments which store/represent one or more values. While options can represent a variety of input types, they are always serialized to a string. Options may be required or not, may be positional or not, can have a variable number of parameters, and can operate in a variety of manners.

Here is an example of an option foo, which has a default value of bar, is required, and expects 1 additional argument which will be stored as foo's value

// Create a required Option -foo, with a default value of "bar", that expects and stores 1 argument.
f := argparse.NewOption("-f --foo", "foo", "A foo option").Default("bar").Nargs("1").Required().Action(argparse.Store)
Methods

Options can be configured in a variety of ways. Therefore, method-chaining is heavily used to quickly create and setup an option. Consider the following example:

// Create a required Option -foo, with a default value of "bar", that expects and stores 1 argument.
f := argparse.NewOption("-f --foo", "foo", "A foo option").Default("bar").Nargs("1").Required().Action(argparse.Store)

Options can have the following attributes:

  • Is required or not required
  • Is positional or not positional
  • Has a default value
  • Has a constant value
  • Expects a specified number of arguments (or no arguments)
  • Is identified by one or more public qualifiers (e.g.: -f or --foo)
  • Can require arguments to match specified choices
Nargs

Nargs, a shortening of "numer of arguments", represents the number of arguments a flag expects after its presence in a programs complete list of parameters. This could be an actual number, such as 0 or 5, or it could be any of the following characters: *+?.

The * character represents "any and all arguments" following the flag.

The + character represents "one or more arguments" following the flag.

The ? character represents "no arguments or only one argument" following the flag.

The r or R characters represent "all remaining arguments" that were not consumed during parsing. These narg choices do not consume the parse arguments they are applicable to.

Actions

A flag's action defines what should occur when a flag is parsed. All flags must have an action. By default, a flag will store true in the parser when present, and false when not. The following are the currently available actions:

  • argparse.StoreTrue will store true in the parser when the flag is present.
  • argparse.StoreFalse will store false in the parser when the flag is present.
  • argparse.StoreConst will store the flag's constant value into the parser when the flag is present.
  • argparse.Store will store the appropriate number of arguments into the parser when the flag & arguments are present.
  • argparse.AppendConst will append the flag's constant to the flag's slice within the parser.
  • argparse.Append will append the appropriate number of arguments into the flag's slice within the parser.
  • argparse.ShowHelp will print the parser's generate help text to stdout.

Documentation

Overview

Package argparse is a Golang command line argument parsing library, taking heavy influance from Python's argparse module.

Using argparse, it is possible to easily create command-line interfaces, such as:

> exc --help

usage: main [-h] [-v] [-e] [-x  ...] [-n] [-f] [-k] [p PATTERN] [s SPLIT] [c CHAR]

Construct and execute arguments from Stdin

positional arguments:
  [p PATTERN]         Stdin regex grouping pattern
  [s SPLIT]           Delimiting regex for Stdin
  [c CHAR]            Replacement string for argument parsing

optional arguments:
  -h, --help          Show program help
  -v, --version       Show program version
  -e, --empty         Allow empty text
  -x, --exec          Pasrable command string
  -n, --dry-run       Output commands instead of executing
  -f, --force         Force continue command execution upon errored commands
  -k, --keep-newline  Allow trailing newline from Stdin

Much of the heavy lifting for creating a cmd-line interface is managed by argparse, so you can focus on getting your program created and running.

For example, the code required to create the above interface is as follows:

import (
	"github.com/clagraff/argparse"
)

func main() {
	p := argparse.NewParser("Construct and execute arguments from Stdin").Version("0.0.0")
	p.AddHelp().AddVersion() // Enable `--help` & `-h` to display usage text to the user.

	pattern := argparse.NewArg("p pattern", "pattern", "Stdin regex grouping pattern").Default(".*")
	split := argparse.NewArg("s split", "split", "Delimiting regex for Stdin").Default("\n")
	nonEmpty := argparse.NewOption("e empty", "empty", "Allow empty text")
	keepNewline := argparse.NewFlag("k keep-newline", "keep-newline", "Allow trailing newline from Stdin").Default("false")
	command := argparse.NewOption("x exec", "exec", "Pasrable command string").Nargs("r").Action(argparse.Store)
	replacementChar := argparse.NewArg("c char", "char", "Replacement string for argument parsing").Default("%")
	dryRun := argparse.NewFlag("n dry-run", "dry", "Output commands instead of executing")
	ignoreErrors := argparse.NewFlag("f force", "force", "Force continue command execution upon errored commands")

	p.AddOptions(pattern, split, nonEmpty, command, replacementChar, dryRun, ignoreErrors, keepNewline)

	ns, _, err := p.Parse(os.Args[1:]...)
	switch err.(type) {
	case argparse.ShowHelpErr:
		return
	case error:
		fmt.Println(err, "\n")
		p.ShowHelp()
		return
	}

To get started, all you need is a Parser and a few Options!

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Append

func Append(p *Parser, f *Option, args ...string) ([]string, error)

Append retrives the appropriate number of argumnents for the current option, (if any), and appends them individually into the parser. Remaining arguments and errors are returned.

func AppendConst

func AppendConst(p *Parser, f *Option, args ...string) ([]string, error)

AppendConst appends the option's constant value into the parser. Provided arguments remain unmodified.

func ShowHelp

func ShowHelp(p *Parser, f *Option, args ...string) ([]string, error)

ShowHelp calls the parser's ShowHelp function to output parser usage information and help information for each option to stdout. Provided arguments remain unchanged. It returns a ShowHelpErr error instance, used to prevent further parsing.

func ShowVersion

func ShowVersion(p *Parser, f *Option, args ...string) ([]string, error)

ShowVersion calls the parser's ShowVersion function to output parser/program version information. Provided arguments remain unchanged. It returns a ShowVersionErr instance, used to prevent further parsing.

func Store

func Store(p *Parser, f *Option, args ...string) ([]string, error)

Store will attempt to store the appropriate number of arguments for the option, (if any), into the parser. Remaining arguments & any errors are returned.

func StoreConst

func StoreConst(p *Parser, f *Option, args ...string) ([]string, error)

StoreConst stores the option's constant value into the parser. Provided arguments remain unmodified.

func StoreFalse

func StoreFalse(p *Parser, f *Option, args ...string) ([]string, error)

StoreFalse stores a boolean `false` into the parser. Provided arguments remain unmodified.

func StoreTrue

func StoreTrue(p *Parser, f *Option, args ...string) ([]string, error)

StoreTrue stores a boolean `true` into the parser. Provided arguments remain unmodified.

func ValidateChoice

func ValidateChoice(f Option, arg string) error

ValidateChoice returns an error if the provided interface value does not exists as valid choice for the provided flag.

func ValidateType

func ValidateType(f Option, arg string) error

ValidateType attempt to type-convert the string argument to the flag's desired type. It will return an error if the provided interface value does not satisfy the Option's expected Reflect.Kind type.

Types

type Action

type Action func(*Parser, *Option, ...string) ([]string, error)

Action is type to represent a callable function which will operate on a parser, a option, and an array of argument strings.

type InvalidChoiceErr

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

InvalidChoiceErr indicates that an argument is not among the valid choices for the option.

func (InvalidChoiceErr) Error

func (err InvalidChoiceErr) Error() string

Error will return a string error message for the InvalidChoiceErr

type InvalidFlagNameErr

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

InvalidFlagNameErr indicates that an argument with the provided public name not exist.

func (InvalidFlagNameErr) Error

func (err InvalidFlagNameErr) Error() string

Error will return a string error message for the InvalidFlagNameErr

type InvalidOptionErr

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

InvalidOptionErr indicates that an option is invalid.

func (InvalidOptionErr) Error

func (err InvalidOptionErr) Error() string

Error will return a string error message for the InvalidFlagNameErr

type InvalidParserNameErr

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

InvalidParserNameErr indicates that a Command name has already been assigned and cannot be re-assigned.

func (InvalidParserNameErr) Error

func (err InvalidParserNameErr) Error() string

Error will return a string error message for the InvalidParserNameErr

type InvalidTypeErr

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

InvalidTypeErr indicates that an argument cannot be casted the the option's expected type.

func (InvalidTypeErr) Error

func (err InvalidTypeErr) Error() string

Error will return a string error message for the InvalidTypeErr

type MissingEnvVarErr added in v1.0.2

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

MissingEnvVarErr indicates that an environmental variable could not be found with the provided variable name.

func (MissingEnvVarErr) Error added in v1.0.2

func (err MissingEnvVarErr) Error() string

Error will return a string error message for the MissingEnvVarErr.

type MissingOneOrMoreArgsErr

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

MissingOneOrMoreArgsErr indicated that not enough arguments were provided, when one or more arguments were expected, for the option.

func (MissingOneOrMoreArgsErr) Error

func (err MissingOneOrMoreArgsErr) Error() string

Error will return a string error message for the TooFewArgsErr

type MissingOptionErr

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

MissingOptionErr indicated that an option was required but is missing.

func (MissingOptionErr) Error

func (err MissingOptionErr) Error() string

Error will return a string error message for the MissingOptionErr

type MissingParserErr

type MissingParserErr struct {
	Parsers []SubParser
}

MissingParserErr indicated that commands were available, but none were used.

func (MissingParserErr) Error

func (err MissingParserErr) Error() string

Error will return a string error message for the MissingParserErr

type Namespace

type Namespace map[string]interface{}

Namespace is a map of key-value pairs, used for storing pairings between options' destinations and their associated values. It will contain only `string` and `[]string` values.

func NewNamespace

func NewNamespace() *Namespace

NewNamespace will return a pointer to a new Namespace instance.

func (Namespace) Get

func (n Namespace) Get(key string) interface{}

Get will retrieve either a string or a []string if the specified key exists in the mapping. Otherwise, an empty string is returned

func (Namespace) KeyExists

func (n Namespace) KeyExists(key string) bool

KeyExists returns a bool indicating true if the key does exist in the mapping, or otherwise false.

func (Namespace) Require

func (n Namespace) Require(keys ...string) error

Require will assert that all the specified keys exist in the namespace.

func (*Namespace) Set

func (n *Namespace) Set(key string, value interface{}) *Namespace

Set will set the mapping's value at the desired key to the value provided.

func (Namespace) Slice

func (n Namespace) Slice(key string) []string

Slice will retrieve either a string or a []string if the specified key exists in the mapping. Otherwise, an empty string is returned

func (Namespace) String

func (n Namespace) String(key string) string

String will retrieve either a string or a []string if the specified key exists in the mapping. Otherwise, an empty string is returned

func (Namespace) Try

func (n Namespace) Try(key string) (interface{}, error)

Try will retrieve either a string or a []string if the specified key exists in the mapping. Otherwise, an error is returned.

type Option

type Option struct {
	ArgNum        string       // Any digit, "+", "?", "*", or "r" and "R" to represent how many arguments an option can expect.
	ConstVal      string       // A constant value to represent when used with the actions.StoreConst action.
	DefaultVal    string       // A value to represent the Option by default.
	DesiredAction Action       // A callback function which will parse an option and its arguments.
	DestName      string       // A unique identifier to store an option's value within a namespace.
	ExpectedType  reflect.Kind // The variable-type that an Option's arguments are to be interpretted as.
	HelpText      string       // Text describing the usage/meaning of the Option.
	IsRequired    bool         // Indicate if an Option must be present when parsing.
	IsPositional  bool         // Indicate that an Option is identified by its position when parsing.
	MetaVarText   []string     // Text used when representing an Option and its arguments.
	PublicNames   []string     // Qualifiers for identifying the option during parsing.
	ValidChoices  []string     // A slice of valid choices for arguments of the Option.
}

Option contains the necessary attributes for representing a parsable option. You can create a vanilla Option by using the NewOption function, or you can create Flag-type or Argument-type Option using the NewFlag and NewArg functions, respectively.

An example of using these functions can be seen below:

o := argparse.NewOption("-o", "output", "Enable output")
o.Positional().Required().Nargs("0").Action(StoreTrue).Default("false")

f := argparse.NewFlag("-n --dry", "dryRun", "Enable dry-run mode")
a := argparse.NewArg("--in", "inputPath", "Path to specified input file")

func NewArg

func NewArg(names, dest, help string) *Option

NewArg initializes a new Option pointer, and sets its Nargs to 1, its action to Store, and makes it a positional option.

func NewFlag

func NewFlag(names, dest, help string) *Option

NewFlag initializes a new Option pointer, sets its Nargs to 0, its action to StoreTrue, and its default value to false.

func NewOption

func NewOption(names, dest, help string) *Option

NewOption instantiates a new Option pointer, initializing it as a boolean flag. Multiple names should be delimited by a space; names should not contain the prefix character.

func (*Option) Action

func (f *Option) Action(action Action) *Option

Action sets the option's action to the provided action function.

func (*Option) Choices

func (f *Option) Choices(choices ...string) *Option

Choices appends the provided slice as acceptable arguments for the option.

func (*Option) Const

func (f *Option) Const(value string) *Option

Const sets the option's constant value to the provided interface. A option's constant value is only used for certain actions. By default, the constant value is `nil`.

func (*Option) Default

func (f *Option) Default(value string) *Option

Default sets the option's default value. A option's default value is only used for certain actions. By default, the default value is `nil`.

func (*Option) Dest

func (f *Option) Dest(name string) *Option

Dest sets a option's destination name. This is used as the key for storing the option's values within the parser.

func (*Option) DisplayName

func (f *Option) DisplayName() string

DisplayName returns the option's public name, prefixed with the appropriate number of hyphen-minus characters.

func (*Option) GetChoices

func (f *Option) GetChoices() string

GetChoices returns a string-representation of the valid choices for the current Option.

func (*Option) GetUsage

func (f *Option) GetUsage() string

GetUsage returns the usage text for the option. This includes proper formatting of the option's display name & parameters. For parameters: by default, parameters will be the option's public name. This can be overridden by modifying the MetaVars slice for the option.

func (*Option) Help

func (f *Option) Help(text string) *Option

Help sets the option's help/usage text.

func (*Option) IsPublicName

func (f *Option) IsPublicName(name string) bool

IsPublicName will check the provided string against current option's public names to determine if there is a match.

func (*Option) MetaVar

func (f *Option) MetaVar(meta string, metaSlice ...string) *Option

MetaVar sets the option's metavar text to the provided string. Additional metavar strings can be provided, and will be used for options with more than expected argument.

func (*Option) Nargs

func (f *Option) Nargs(nargs interface{}) *Option

Nargs sets the option's number of expected arguments. Integers represent the absolute number of arguments to be expected. The `?` character represents an expectation of zero or one arguments. The `*` character represents an expectation of any number or arguments. The `+` character represents an expectation of one or more arguments. The `r` and `R` characters represent using all arguments not used after the initial parsing of options.

func (*Option) NotPositional

func (f *Option) NotPositional() *Option

NotPositional disables a option from being positionally interpretted.

func (*Option) NotRequired

func (f *Option) NotRequired() *Option

NotRequired prevents the option from being required to be present when parsing arguments.

func (*Option) Positional

func (f *Option) Positional() *Option

Positional enables a option to be positionally interpretted.

func (*Option) Required

func (f *Option) Required() *Option

Required enables the option to required to be present when parsing arguments.

func (*Option) String

func (f *Option) String() string

String outputs a string-serialized version of the Option.

func (*Option) Type

func (f *Option) Type(kind reflect.Kind) *Option

Type sets the expected reflect.Kind type an option will accept.

type Parser

type Parser struct {
	AllowAbbrev bool
	Callback    func(*Parser, *Namespace, []string, error)
	EpilogText  string
	Namespace   *Namespace
	Options     []*Option
	Parsers     []SubParser
	ProgramName string
	UsageText   string
	VersionDesc string
}

Parser contains program-level settings and information, stores options, and values collected upon parsing.

func NewParser

func NewParser(desc string, callback func(*Parser, *Namespace, []string, error)) *Parser

NewParser returns an instantiated pointer to a new parser instance, with a description matching the provided string.

func (*Parser) AddHelp

func (p *Parser) AddHelp() *Parser

AddHelp adds a new option to output usage information for the current parser and each of its options.

func (*Parser) AddOption

func (p *Parser) AddOption(f *Option) *Parser

AddOption appends the provided option to the current parser.

func (*Parser) AddOptions

func (p *Parser) AddOptions(opts ...*Option) *Parser

AddOptions appends the provided options to the current parser.

func (*Parser) AddParser

func (p *Parser) AddParser(name string, parser *Parser) *Parser

AddParser appends the provided parse to the current parser as an available command.

func (*Parser) AddVersion

func (p *Parser) AddVersion() *Parser

AddVersion adds a new option to the program version.

func (*Parser) Epilog added in v1.0.2

func (p *Parser) Epilog(text string) *Parser

Epilog sets the provide string as the epilog text for the parser. This text is displayed during the help text, after all available text is outputted.

func (*Parser) GetHelp

func (p *Parser) GetHelp() string

GetHelp returns a string containing the parser's description text, and the usage information for each option currently incorporated within the parser.

func (*Parser) GetOption

func (p *Parser) GetOption(name string) (*Option, error)

GetOption retrieves the first option with a public name matching the specified name, or will otherwise return an error.

func (Parser) GetParser

func (p Parser) GetParser(name string) (*Parser, error)

GetParser retrieves the desired sub-parser from the current parser, or returns an error if the desired parser does not exist.

func (*Parser) GetVersion

func (p *Parser) GetVersion() string

GetVersion will return the version text for the current parser.

func (*Parser) Parse

func (p *Parser) Parse(allArgs ...string)

Parse accepts a slice of strings as options and arguments to be parsed. The parser will call each encountered option's action. Unexpected options will cause an error. All errors are returned.

func (*Parser) Path

func (p *Parser) Path(progPath string) *Parser

Path will set the parser's program name to the program name specified by the provided path.

func (*Parser) Prog

func (p *Parser) Prog(name string) *Parser

Prog sets the name of the parser directly.

func (*Parser) ShowHelp

func (p *Parser) ShowHelp() *Parser

ShowHelp outputs to stdout the parser's generated help text.

func (*Parser) ShowVersion

func (p *Parser) ShowVersion() *Parser

ShowVersion outputs to stdout the parser's generated versioning text.

func (*Parser) Usage

func (p *Parser) Usage(usage string) *Parser

Usage sets the provide string as the usage/description text for the parser.

func (*Parser) Version

func (p *Parser) Version(version string) *Parser

Version sets the provide string as the version text for the parser.

type ShowHelpErr

type ShowHelpErr struct{}

ShowHelpErr indicates that the program was instructed to show it's help text.

func (ShowHelpErr) Error

func (err ShowHelpErr) Error() string

type ShowVersionErr

type ShowVersionErr struct{}

ShowVersionErr indicates that the program was instructed to show it's versioning text.

func (ShowVersionErr) Error

func (err ShowVersionErr) Error() string

type SubParser

type SubParser struct {
	Parser *Parser
	Name   string
}

SubParser contains a Parser pointer and the public name for the sub command.

type TooFewArgsErr

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

TooFewArgsErr indicated that not enough arguments were provided for the option.

func (TooFewArgsErr) Error

func (err TooFewArgsErr) Error() string

Error will return a string error message for the TooFewArgsErr

Jump to

Keyboard shortcuts

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