Skip to content

yieldbot/gocli

Repository files navigation

gocli

Build Status Coverage GoDoc Release

A Go CLI library that provides subcommand handling, tidy usage and version printing.

Installation

go get github.com/yieldbot/gocli

Usage

A simple CLI app

See simple.go for full code.

func init() {
  // Init flags
  flag.BoolVar(&usageFlag, "h", false, "Display usage")
  flag.BoolVar(&usageFlag, "help", false, "Display usage")
  flag.BoolVar(&versionFlag, "version", false, "Display version information")
  flag.BoolVar(&versionFlag, "v", false, "Display version information")
}

func main() {

  // Init cli
  cli = gocli.Cli{
    Name:        "simple",
    Version:     "1.0.0",
    Description: "A simple app",
    Commands: map[string]string{
      "echo": "Print the given arguments",
    },
  }
  cli.Init()

  // Run commands
  if cli.SubCommand == "echo" {
    // Echo command
    fmt.Println(strings.Join(cli.SubCommandArgs, " "))
  } else if versionFlag {
    // Version
    cli.PrintVersion(true)
  } else {
    // Default
    cli.PrintUsage()
  }
}
$ go run examples/simple.go
Usage: simple [OPTIONS] COMMAND [arg...]

A simple app

Options:
  -h, --help    : Display usage
  -v, --version : Display version information

Commands:
  echo          : Print the given arguments
$ go run examples/simple.go -v
Bin version : 1.0.0
Go version  : go1.6
$ go run examples/simple.go echo hello world
hello world

License

Licensed under The MIT License (MIT)
For the full copyright and license information, please view the LICENSE.txt file.