Top Related Projects
Quick Overview
go-flags is a Go library for parsing command line arguments and flags. It provides a flexible and feature-rich way to define and handle command line options, supporting both short and long flag names, as well as nested command structures.
Pros
- Supports a wide range of flag types, including built-in Go types and custom types
- Allows for nested command structures, making it suitable for complex CLI applications
- Provides automatic generation of help text and man pages
- Offers both POSIX-style short flags and GNU-style long flags
Cons
- Learning curve might be steeper compared to simpler flag parsing libraries
- Some users report issues with error handling and custom types in edge cases
- Documentation could be more comprehensive, especially for advanced use cases
- May be overkill for very simple command line applications
Code Examples
- Basic flag parsing:
type Options struct {
Verbose bool `short:"v" long:"verbose" description:"Show verbose debug information"`
Name string `short:"n" long:"name" description:"A name" required:"true"`
}
var opts Options
_, err := flags.Parse(&opts)
if err != nil {
log.Fatal(err)
}
- Nested commands:
type CommonOptions struct {
Verbose bool `short:"v" long:"verbose" description:"Show verbose debug information"`
}
type AddCommand struct {
CommonOptions
Name string `short:"n" long:"name" description:"Name to add" required:"true"`
}
type DeleteCommand struct {
CommonOptions
ID int `short:"i" long:"id" description:"ID to delete" required:"true"`
}
var parser = flags.NewParser(nil, flags.Default)
parser.AddCommand("add", "Add a new item", "Add a new item to the database", &AddCommand{})
parser.AddCommand("delete", "Delete an item", "Delete an item from the database", &DeleteCommand{})
_, err := parser.Parse()
if err != nil {
log.Fatal(err)
}
- Custom value parser:
type Point struct {
X, Y int
}
func (p *Point) UnmarshalFlag(value string) error {
parts := strings.Split(value, ",")
if len(parts) != 2 {
return fmt.Errorf("invalid point format")
}
x, err := strconv.Atoi(parts[0])
if err != nil {
return err
}
y, err := strconv.Atoi(parts[1])
if err != nil {
return err
}
p.X, p.Y = x, y
return nil
}
type Options struct {
Point Point `short:"p" long:"point" description:"A point in 2D space"`
}
var opts Options
_, err := flags.Parse(&opts)
if err != nil {
log.Fatal(err)
}
Getting Started
To use go-flags in your Go project, first install it:
go get github.com/jessevdk/go-flags
Then, import it in your Go code:
import "github.com/jessevdk/go-flags"
Define a struct to hold your command line options, add tags to specify flag names and descriptions, and use flags.Parse()
to parse the command line arguments:
type Options struct {
Verbose bool `short:"v" long:"verbose" description:"Show verbose debug information"`
OutputFile string `short:"o" long:"output" description:"Output file" default:"output.txt"`
}
var opts Options
_, err := flags.Parse(&opts)
if err != nil {
log.Fatal(err)
}
// Use opts.Verbose and opts.OutputFile in your program
Competitor Comparisons
A Commander for modern Go CLI interactions
Pros of Cobra
- More comprehensive CLI framework with built-in support for subcommands and nested subcommands
- Includes a generator for quickly scaffolding new CLI applications
- Offers better integration with other popular Go libraries like viper for configuration management
Cons of Cobra
- Steeper learning curve due to its more complex structure and features
- May be overkill for simple CLI applications with few commands
- Requires more boilerplate code for basic functionality
Code Comparison
Cobra:
var rootCmd = &cobra.Command{
Use: "app",
Short: "A brief description of your application",
Run: func(cmd *cobra.Command, args []string) {
// Your code here
},
}
go-flags:
type Options struct {
Verbose bool `short:"v" long:"verbose" description:"Show verbose debug information"`
}
var options Options
_, err := flags.Parse(&options)
Cobra provides a more structured approach to defining commands and subcommands, while go-flags focuses on parsing command-line flags with a simpler API. Cobra is better suited for complex CLI applications with multiple commands, whereas go-flags is more lightweight and easier to use for simpler applications that primarily need flag parsing.
A Go library for implementing command-line interfaces.
Pros of cli
- Provides a more comprehensive CLI framework with support for subcommands and nested command structures
- Includes built-in help generation and version command functionality
- Offers a simpler API for creating complex command-line interfaces
Cons of cli
- Less flexible in terms of flag parsing options compared to go-flags
- May be overkill for simpler CLI applications that don't require nested commands
- Lacks some advanced features like argument completion and custom tag support
Code Comparison
cli:
c := cli.NewCLI("app", "1.0.0")
c.Args = os.Args[1:]
c.Commands = map[string]cli.CommandFactory{
"foo": fooCommandFactory,
}
go-flags:
var opts struct {
Verbose []bool `short:"v" long:"verbose" description:"Show verbose debug information"`
}
_, err := flags.Parse(&opts)
Summary
cli is better suited for complex CLI applications with nested command structures, while go-flags excels in flexible flag parsing and simpler command-line tools. The choice between the two depends on the specific requirements of your project and the level of complexity needed in your CLI interface.
CONTRIBUTIONS ONLY: A Go (golang) command line and flag parser
Pros of kingpin
- More extensive and flexible command-line structure support
- Built-in support for generating man pages and bash/zsh completions
- Cleaner API with method chaining for defining flags and arguments
Cons of kingpin
- Slightly more verbose syntax for simple use cases
- Less actively maintained (last commit in 2019 vs. go-flags in 2023)
- Steeper learning curve for advanced features
Code Comparison
go-flags:
type Options struct {
Verbose []bool `short:"v" long:"verbose" description:"Show verbose debug information"`
Name string `short:"n" long:"name" description:"A name" required:"true"`
}
var opts Options
_, err := flags.Parse(&opts)
kingpin:
var (
verbose = kingpin.Flag("verbose", "Verbose mode.").Short('v').Bool()
name = kingpin.Flag("name", "Name of user.").Short('n').Required().String()
)
kingpin.Parse()
Both libraries offer similar functionality for basic command-line parsing. go-flags uses struct tags to define flags, while kingpin uses a more fluent API. kingpin's approach is more verbose for simple cases but offers more flexibility for complex command structures. go-flags may be preferable for straightforward applications, while kingpin shines in more complex scenarios with nested commands and advanced features.
Struct-based argument parsing in Go
Pros of go-arg
- Simpler API with less boilerplate code
- Uses struct tags for configuration, making it more idiomatic Go
- Better support for nested structs and custom types
Cons of go-arg
- Less feature-rich compared to go-flags
- Limited support for command-line flags without corresponding struct fields
- Fewer options for customizing help output
Code Comparison
go-arg:
type Args struct {
Foo string `arg:"required,-f" help:"foo is a required flag"`
Bar int
}
func main() {
var args Args
arg.MustParse(&args)
}
go-flags:
type Options struct {
Foo string `short:"f" long:"foo" required:"true" description:"foo is a required flag"`
Bar int `long:"bar"`
}
func main() {
var opts Options
_, err := flags.Parse(&opts)
if err != nil {
log.Fatal(err)
}
}
Both libraries offer command-line argument parsing for Go applications, but they differ in their approach and feature set. go-arg focuses on simplicity and idiomatic Go code, while go-flags provides more extensive customization options and a wider range of features. The choice between the two depends on the specific requirements of your project and personal preferences regarding API design.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
go-flags: a go library for parsing command line arguments
This library provides similar functionality to the builtin flag library of go, but provides much more functionality and nicer formatting. From the documentation:
Package flags provides an extensive command line option parser. The flags package is similar in functionality to the go builtin flag package but provides more options and uses reflection to provide a convenient and succinct way of specifying command line options.
Supported features:
- Options with short names (-v)
- Options with long names (--verbose)
- Options with and without arguments (bool v.s. other type)
- Options with optional arguments and default values
- Multiple option groups each containing a set of options
- Generate and print well-formatted help message
- Passing remaining command line arguments after -- (optional)
- Ignoring unknown command line options (optional)
- Supports -I/usr/include -I=/usr/include -I /usr/include option argument specification
- Supports multiple short options -aux
- Supports all primitive go types (string, int{8..64}, uint{8..64}, float)
- Supports same option multiple times (can store in slice or last option counts)
- Supports maps
- Supports function callbacks
- Supports namespaces for (nested) option groups
The flags package uses structs, reflection and struct field tags to allow users to specify command line options. This results in very simple and concise specification of your application options. For example:
type Options struct {
Verbose []bool `short:"v" long:"verbose" description:"Show verbose debug information"`
}
This specifies one option with a short name -v and a long name --verbose. When either -v or --verbose is found on the command line, a 'true' value will be appended to the Verbose field. e.g. when specifying -vvv, the resulting value of Verbose will be {[true, true, true]}.
Example:
var opts struct {
// Slice of bool will append 'true' each time the option
// is encountered (can be set multiple times, like -vvv)
Verbose []bool `short:"v" long:"verbose" description:"Show verbose debug information"`
// Example of automatic marshalling to desired type (uint)
Offset uint `long:"offset" description:"Offset"`
// Example of a callback, called each time the option is found.
Call func(string) `short:"c" description:"Call phone number"`
// Example of a required flag
Name string `short:"n" long:"name" description:"A name" required:"true"`
// Example of a flag restricted to a pre-defined set of strings
Animal string `long:"animal" choice:"cat" choice:"dog"`
// Example of a value name
File string `short:"f" long:"file" description:"A file" value-name:"FILE"`
// Example of a pointer
Ptr *int `short:"p" description:"A pointer to an integer"`
// Example of a slice of strings
StringSlice []string `short:"s" description:"A slice of strings"`
// Example of a slice of pointers
PtrSlice []*string `long:"ptrslice" description:"A slice of pointers to string"`
// Example of a map
IntMap map[string]int `long:"intmap" description:"A map from string to int"`
// Example of env variable
Thresholds []int `long:"thresholds" default:"1" default:"2" env:"THRESHOLD_VALUES" env-delim:","`
}
// Callback which will invoke callto:<argument> to call a number.
// Note that this works just on OS X (and probably only with
// Skype) but it shows the idea.
opts.Call = func(num string) {
cmd := exec.Command("open", "callto:"+num)
cmd.Start()
cmd.Process.Release()
}
// Make some fake arguments to parse.
args := []string{
"-vv",
"--offset=5",
"-n", "Me",
"--animal", "dog", // anything other than "cat" or "dog" will raise an error
"-p", "3",
"-s", "hello",
"-s", "world",
"--ptrslice", "hello",
"--ptrslice", "world",
"--intmap", "a:1",
"--intmap", "b:5",
"arg1",
"arg2",
"arg3",
}
// Parse flags from `args'. Note that here we use flags.ParseArgs for
// the sake of making a working example. Normally, you would simply use
// flags.Parse(&opts) which uses os.Args
args, err := flags.ParseArgs(&opts, args)
if err != nil {
panic(err)
}
fmt.Printf("Verbosity: %v\n", opts.Verbose)
fmt.Printf("Offset: %d\n", opts.Offset)
fmt.Printf("Name: %s\n", opts.Name)
fmt.Printf("Animal: %s\n", opts.Animal)
fmt.Printf("Ptr: %d\n", *opts.Ptr)
fmt.Printf("StringSlice: %v\n", opts.StringSlice)
fmt.Printf("PtrSlice: [%v %v]\n", *opts.PtrSlice[0], *opts.PtrSlice[1])
fmt.Printf("IntMap: [a:%v b:%v]\n", opts.IntMap["a"], opts.IntMap["b"])
fmt.Printf("Remaining args: %s\n", strings.Join(args, " "))
// Output: Verbosity: [true true]
// Offset: 5
// Name: Me
// Ptr: 3
// StringSlice: [hello world]
// PtrSlice: [hello world]
// IntMap: [a:1 b:5]
// Remaining args: arg1 arg2 arg3
More information can be found in the godocs: http://godoc.org/github.com/jessevdk/go-flags
Top Related Projects
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot