cli

package module
v0.0.5 Latest Latest
Warning

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

Go to latest
Published: Mar 8, 2025 License: BSD-3-Clause Imports: 11 Imported by: 0

README

cli

Module to implement command line interfaces with GNU options.

Documentation

Overview

Package cli supports the creation of command line applications with subcommands and help output.

A typical program will import this package, setup the root command and add a help command.

  package main

  import (
	"log"
	"os"

	"github.com/ulikunitz/cli"
  )

  func main() {
	log.SetFlags(0)

	root := &cli.Command{
		Name:        "foo",
		Info:        "program to run compression benchmarks",
		Subcommands: []*cli.Command{subcommand()},
	}

	cli.AddHelpCommand(root)

	var args []string
	if len(os.Args) == 1 {
		args = []string{"help"}
	} else {
		args = os.Args[1:]
	}

	if err := cli.Run(root, args); err != nil {
		log.Fatal(err)
	}
  }

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AddHelpCommand added in v0.0.2

func AddHelpCommand(root *Command) bool

AddHelpCommand adds a subcommand help to the root command if doesn't support a help command already.

func AddHelpOption added in v0.0.3

func AddHelpOption(cmd *Command) bool

AddHelpOption adds a help option for the command if it doesn't have an option -h already. Note the Exec function must already been set or the no help option is added

func AddHelpOptionToAll added in v0.0.3

func AddHelpOptionToAll(cmd *Command)

AddHelpOptionToAll adds a help option to all subcommands that don't have the name help.

func IsTerminal added in v0.0.4

func IsTerminal(fd uintptr) bool

IsTerminal returns true if the given file descriptor is a terminal.

func ParseOptions

func ParseOptions(options []*Option, args []string) (n int, err error)

ParseOptions parses the flags and stops at first non-flag or '--'. It returns the number of args parsed.

func ResetOptions

func ResetOptions(options []*Option) error

ResetOptions resets all options to the default. It may be useful before you are executing Parse a second time on an option set.

func Run

func Run(root *Command, args []string) error

Run parses the arguments and executes the exec command for the command identified. The call may return an error.

func UsageOptions

func UsageOptions(w io.Writer, opts []*Option, indent1, indent2 string) (n int, err error)

UsageOptions returns a textual list of all options sorted by alphabet. Usage information for an option will be preceded by indent1 and the description by indent1+indent2 formatted on 80 character lines.

Types

type Command

type Command struct {
	// Name of command usually short (e.g. "list")
	Name string
	// Short description of the command (e.g. "list all config parameters")
	Info string
	// The usage string may have multiple lines.
	Usage string
	// Longer description that will be formatted.
	Description string
	// Options list. Note these options must immediately follow the
	// command in the command line and any non-option will stop the
	// processing of the options for this command.
	Options []*Option
	// List of all subcommands for this command.
	Subcommands []*Command
	// Function that executes the command.
	Exec func(args []string) error
}

Command represents a command in the command tree. It may be the root of its own subcommand tree. The program itself will be represented by a root command with the name of the program.

Note that the lines of the Description field that have leading whitespace will be copied verbatim. So the typical use should look like this:

cmd := &Command{
    Name: "list",
    Description: `
The command list will list all configuration parameters. It supports multiple
options.`,
}

The Description field supports all features of the go doc comment formatter.

func Parse

func Parse(root *Command, args []string) (commands []*Command, n int, err error)

Parse parses the argument list and determines the sequence of subcommands. The root command itself is not parsed but its flags. Out is used for error messages during parsing. The return value n provides the number of commands parsed.

func (*Command) WriteDoc

func (cmd *Command) WriteDoc(w io.Writer) (n int, err error)

WriteDoc puts the documentation our on w. the style used is that of man files.

type CommandError

type CommandError struct {
	Name    string
	Message string
	Wrapped error
}

CommandError might be generated during Command parsing.

func (*CommandError) Error

func (err *CommandError) Error() string

Error prints the error message and appends the error string of the wrapped error.

func (*CommandError) Unwrap

func (err *CommandError) Unwrap() error

Unwrap returns the wrapped error.

type Option

type Option struct {
	// long name of the option; must be used with prefix '--'
	Name string
	// short option; must be in [A-Za-z0-9]
	Short rune
	// long names additional to name
	Names []string
	// short runes additional to Names
	Shorts []rune
	// Custom usage information about options
	UsageInfo string
	// description of the option
	Description string
	// HasParam defines whether the option has parameter
	HasParam bool
	// OptionalParam
	OptionalParam bool
	// ParamType describes the type of the parameter
	ParamType string
	// Default param value.
	Default string
	// SetValue set the value to the parameter string given and informs
	// whether there was a parameter or not.
	SetValue func(name string, param string, noParam bool) error
	// ResetValue can be used to reset the value. If it is nil then
	// opt.SetValue(opt.Default, false) will be called.
	ResetValue func()
}

Option represents a single option.

func BoolOption

func BoolOption(f *bool, name string, short rune, description string) *Option

BoolOption initializes a boolean flag. The argument f will be set to false.

func Float64Option added in v0.0.2

func Float64Option(f *float64, name string, short rune, description string) *Option

Float64Option creates a flag with a floating point value. The default value is the value of f when called. All forms of floating point numbers valid in the Go language are supported.

func IntOption added in v0.0.2

func IntOption(n *int, name string, short rune, description string) *Option

IntOption creates an integer flag. The default value is the value of n when this function is called. Integers in the form of 0b101, 0xf5 or 0234 are supported.

func StringOption

func StringOption(s *string, name string, short rune, description string) *Option

StringOption creates a string flag. The default value is the value that s has when Parse is called.

func (*Option) AllNames added in v0.0.4

func (opt *Option) AllNames() []string

AllNames returns all long option names in lexicographic order.

func (*Option) AllShorts added in v0.0.4

func (opt *Option) AllShorts() []rune

AllShorts returns all short option names in lexicographic order.

func (*Option) Reset

func (opt *Option) Reset() error

Reset calls ResetValue if defined or SetValue with with the default argument.

func (*Option) Usage

func (opt *Option) Usage() string

Usage returns the one-line string for the option.

type OptionError

type OptionError struct {
	Option  string
	Msg     string
	Wrapped error
}

OptionError provides information regarding an option error.

func (*OptionError) Error

func (err *OptionError) Error() string

func (*OptionError) Is

func (err *OptionError) Is(e error) bool

Is checks whether the error is actually one of the errors provided.

func (*OptionError) Unwrap

func (err *OptionError) Unwrap() error

Jump to

Keyboard shortcuts

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