gocmd

package module
v3.1.0+incompatible Latest Latest
Warning

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

Go to latest
Published: Sep 5, 2018 License: MIT Imports: 9 Imported by: 11

README

gocmd

Release Build Status Coverage Report GoDoc

A Go library for building command line applications.

Features

  • Advanced command line arguments handling
    • Subcommand handling
    • Short and long command line arguments
    • Multiple arguments (repeated or delimited)
    • Support for environment variables
    • Well formatted usage printing
    • Auto usage and version printing
    • Unknown argument handling
  • Output tables in the terminal
  • Template support for config files
  • No external dependency

Installation

go get github.com/devfacet/gocmd

Usage

A basic app

See basic for full code.

func main() {
	flags := struct {
		Help      bool `short:"h" long:"help" description:"Display usage" global:"true"`
		Version   bool `short:"v" long:"version" description:"Display version"`
		VersionEx bool `long:"vv" description:"Display version (extended)"`
		Echo      struct {
			Settings bool `settings:"true" allow-unknown-arg:"true"`
		} `command:"echo" description:"Print arguments"`
		Math struct {
			Sqrt struct {
				Number float64 `short:"n" long:"number" required:"true" description:"Number"`
			} `command:"sqrt" description:"Calculate square root"`
			Pow struct {
				Base     float64 `short:"b" long:"base" required:"true" description:"Base"`
				Exponent float64 `short:"e" long:"exponent" required:"true" description:"Exponent"`
			} `command:"pow" description:"Calculate base exponential"`
		} `command:"math" description:"Math functions" nonempty:"true"`
	}{}

	// Echo command
	gocmd.HandleFlag("Echo", func(cmd *gocmd.Cmd, args []string) error {
		fmt.Printf("%s\n", strings.Join(cmd.FlagArgs("Echo")[1:], " "))
		return nil
	})

	// Math commands
	gocmd.HandleFlag("Math.Sqrt", func(cmd *gocmd.Cmd, args []string) error {
		fmt.Println(math.Sqrt(flags.Math.Sqrt.Number))
		return nil
	})
	gocmd.HandleFlag("Math.Pow", func(cmd *gocmd.Cmd, args []string) error {
		fmt.Println(math.Pow(flags.Math.Pow.Base, flags.Math.Pow.Exponent))
		return nil
	})

	// Init the app
	gocmd.New(gocmd.Options{
		Name:        "basic",
		Version:     "1.0.0",
		Description: "A basic app",
		Flags:       &flags,
		ConfigType:  gocmd.ConfigTypeAuto,
	})
}
cd examples/basic/
go build .
$ ./basic
Usage: basic [options...] COMMAND [options...]

A basic app

Options:
  -h, --help         	Display usage
  -v, --version      	Display version
      --vv           	Display version (extended)

Commands:
  echo               	Print arguments
  math               	Math functions
    sqrt             	Calculate square root
      -n, --number   	Number
    pow              	Calculate base exponential
      -b, --base     	Base
      -e, --exponent 	Exponent

Build

go build .

Test

./test.sh

Release

git add CHANGELOG.md # update CHANGELOG.md
./release.sh v1.0.0  # replace "v1.0.0" with new version

git ls-remote --tags # check the new tag

Contributing

  • Code contributions must be through pull requests
  • Run tests, linting and formatting before a pull request
  • Pull requests can not be merged without being reviewed
  • Use "Issues" for bug reports, feature requests and discussions
  • Do not refactor existing code without a discussion
  • Do not add a new third party dependency without a discussion
  • Use semantic versioning and git tags for versioning

License

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

Documentation

Overview

Package gocmd is a library for building command line applications

Index

Examples

Constants

View Source
const (
	// ConfigTypeAuto is a configuration type that enables automatic functionalities
	// such as usage and version printing, exit on error, etc.
	// It sets AnyError, AutoHelp, AutoVersion, ExitOnError = true
	ConfigTypeAuto = iota + 1
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Cmd

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

Cmd represents a command

func New

func New(o Options) (*Cmd, error)

New returns a command by the given options

Example (Command)
os.Args = []string{"gocmd.test", "math", "sqrt", "-n=9"}

flags := struct {
	Help      bool `short:"h" long:"help" description:"Display usage" global:"true"`
	Version   bool `short:"v" long:"version" description:"Display version"`
	VersionEx bool `long:"vv" description:"Display version (extended)"`
	Echo      struct {
		Settings bool `settings:"true" allow-unknown-arg:"true"`
	} `command:"echo" description:"Print arguments"`
	Math struct {
		Sqrt struct {
			Number float64 `short:"n" long:"number" required:"true" description:"Number"`
		} `command:"sqrt" description:"Calculate square root"`
		Pow struct {
			Base     float64 `short:"b" long:"base" required:"true" description:"Base"`
			Exponent float64 `short:"e" long:"exponent" required:"true" description:"Exponent"`
		} `command:"pow" description:"Calculate base exponential"`
	} `command:"math" description:"Math functions" nonempty:"true"`
}{}

// Echo command
gocmd.HandleFlag("Echo", func(cmd *gocmd.Cmd, args []string) error {
	fmt.Printf("%s\n", strings.Join(cmd.FlagArgs("Echo")[1:], " "))
	return nil
})

// Math commands
gocmd.HandleFlag("Math.Sqrt", func(cmd *gocmd.Cmd, args []string) error {
	fmt.Println(math.Sqrt(flags.Math.Sqrt.Number))
	return nil
})
gocmd.HandleFlag("Math.Pow", func(cmd *gocmd.Cmd, args []string) error {
	fmt.Println(math.Pow(flags.Math.Pow.Base, flags.Math.Pow.Exponent))
	return nil
})

// Init the app
gocmd.New(gocmd.Options{
	Name:        "basic",
	Version:     "1.0.0",
	Description: "A basic app",
	Flags:       &flags,
	ConfigType:  gocmd.ConfigTypeAuto,
})
Output:

3
Example (Usage)
os.Args = []string{"gocmd.test"}

_, err := gocmd.New(gocmd.Options{
	Name:        "basic",
	Version:     "1.0.0",
	Description: "A basic app",
	Flags: &struct {
		Help      bool `short:"h" long:"help" description:"Display usage" global:"true"`
		Version   bool `short:"v" long:"version" description:"Display version"`
		VersionEx bool `long:"vv" description:"Display version (extended)"`
		Echo      struct {
			Settings bool `settings:"true" allow-unknown-arg:"true"`
		} `command:"echo" description:"Print arguments"`
		Math struct {
			Sqrt struct {
				Number float64 `short:"n" long:"number" required:"true" description:"Number"`
			} `command:"sqrt" description:"Calculate square root"`
			Pow struct {
				Base     float64 `short:"b" long:"base" required:"true" description:"Base"`
				Exponent float64 `short:"e" long:"exponent" required:"true" description:"Exponent"`
			} `command:"pow" description:"Calculate base exponential"`
		} `command:"math" description:"Math functions"`
	}{},
	AutoHelp:    true,
	AutoVersion: true,
	AnyError:    true,
})
if err != nil {
	log.Fatal(err)
}
Output:

Usage: basic [options...] COMMAND [options...]

A basic app

Options:
  -h, --help         	Display usage
  -v, --version      	Display version
      --vv           	Display version (extended)

Commands:
  echo               	Print arguments
  math               	Math functions
    sqrt             	Calculate square root
      -n, --number   	Number
    pow              	Calculate base exponential
      -b, --base     	Base
      -e, --exponent 	Exponent
Example (Usage_h)
os.Args = []string{"gocmd.test", "-h"}

_, err := gocmd.New(gocmd.Options{
	Name:        "basic",
	Version:     "1.0.0",
	Description: "A basic app",
	Flags: &struct {
		Help bool `short:"h" long:"help" description:"Display usage" global:"true"`
	}{},
	AutoHelp: true,
	AnyError: true,
})
if err != nil {
	log.Fatal(err)
}
Output:

Usage: basic [options...]

A basic app

Options:
  -h, --help 	Display usage
Example (Usage_help)
os.Args = []string{"gocmd.test", "--help"}

_, err := gocmd.New(gocmd.Options{
	Name:        "basic",
	Version:     "1.0.0",
	Description: "A basic app",
	Flags: &struct {
		Help bool `long:"help" description:"Display usage" global:"true"`
	}{},
	AutoHelp: true,
	AnyError: true,
})
if err != nil {
	log.Fatal(err)
}
Output:

Usage: basic [options...]

A basic app

Options:
      --help 	Display usage
Example (Version)
os.Args = []string{"gocmd.test", "-vv"}

_, err := gocmd.New(gocmd.Options{
	Name:        "basic",
	Version:     "1.0.0",
	Description: "A basic app",
	Flags: &struct {
		Version   bool `short:"v" long:"version" description:"Display version"`
		VersionEx bool `long:"vv" description:"Display version (extended)"`
	}{},
	AutoVersion: true,
})
if err != nil {
	log.Fatal(err)
}
Output:

App name    : basic
App version : 1.0.0
Go version  : vTest
Example (Version_v)
os.Args = []string{"gocmd.test", "-v"}

_, err := gocmd.New(gocmd.Options{
	Name:        "basic",
	Version:     "1.0.0",
	Description: "A basic app",
	Flags: &struct {
		Version bool `short:"v" long:"version" description:"Display version"`
	}{},
	AutoVersion: true,
})
if err != nil {
	log.Fatal(err)
}
Output:

1.0.0
Example (Version_version)
os.Args = []string{"gocmd.test", "--version"}

_, err := gocmd.New(gocmd.Options{
	Name:        "basic",
	Version:     "1.0.0",
	Description: "A basic app",
	Flags: &struct {
		Version bool `long:"version" description:"Display version"`
	}{},
	AutoVersion: true,
})
if err != nil {
	log.Fatal(err)
}
Output:

1.0.0

func (*Cmd) Description

func (cmd *Cmd) Description() string

Description returns the description of the command

func (*Cmd) FlagArgs

func (cmd *Cmd) FlagArgs(name string) []string

FlagArgs returns the flag arguments by the given flag name Nested flags are separated by dot (i.e. Foo.Bar)

func (*Cmd) FlagErrors

func (cmd *Cmd) FlagErrors() []error

FlagErrors returns the list of the flag errors

func (*Cmd) FlagValue

func (cmd *Cmd) FlagValue(name string) interface{}

FlagValue returns the flag value by the given flag name Nested flags are separated by dot (i.e. Foo.Bar)

func (*Cmd) LookupFlag

func (cmd *Cmd) LookupFlag(name string) ([]string, bool)

LookupFlag returns the flag arguments by the given flag name Nested flags are separated by dot (i.e. Foo.Bar)

func (*Cmd) Name

func (cmd *Cmd) Name() string

Name returns the name of the command

func (*Cmd) PrintUsage

func (cmd *Cmd) PrintUsage()

PrintUsage prints usage

func (*Cmd) PrintVersion

func (cmd *Cmd) PrintVersion(extra bool)

PrintVersion prints version information

Example
cmd, err := gocmd.New(gocmd.Options{
	Version: "1.0.0",
})
if err == nil {
	cmd.PrintVersion(false)
}
Output:

1.0.0

func (*Cmd) Version

func (cmd *Cmd) Version() string

Version returns the version of the command

type ConfigType

type ConfigType int

ConfigType represents a configuration type

type FlagHandler

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

FlagHandler represents a flag handler

func HandleFlag

func HandleFlag(name string, handler func(cmd *Cmd, args []string) error) (*FlagHandler, error)

HandleFlag registers the flag handle for the given flag name

func (*FlagHandler) SetExitOnError

func (fh *FlagHandler) SetExitOnError(v bool)

SetExitOnError sets the value of the exitOnError

func (*FlagHandler) SetPriority

func (fh *FlagHandler) SetPriority(v int)

SetPriority sets the value of the priority

type Logger

type Logger interface {
	Fatalf(format string, v ...interface{})
	Printf(format string, v ...interface{})
}

Logger is the interface that must be implemented by loggers

type Options

type Options struct {
	// Name is the command name
	Name string
	// Version is the command version
	Version string
	// Description is the command description
	Description string
	// Flags hold user defined command line arguments and commands
	Flags interface{}
	// Logger represents the logger that is being used for printing errors
	Logger Logger
	// ConfigType is the configuration type
	ConfigType ConfigType
	// AnyError checks all the errors and returns the first one if any
	AnyError bool
	// AutoHelp prints the usage content when the help flags are detected
	AutoHelp bool
	// AutoVersion prints the version content when the version flags are detected
	AutoVersion bool
	// ExitOnError prints the error and exits the program when there is an error
	ExitOnError bool
}

Options represents the options that can be set when creating a new command

Directories

Path Synopsis
examples
Package flagset provides functions for handling command line arguments
Package flagset provides functions for handling command line arguments
Package table provides functions for handling tables in terminal
Package table provides functions for handling tables in terminal
Package template provides functions for handling templates
Package template provides functions for handling templates

Jump to

Keyboard shortcuts

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