guinea

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Feb 8, 2023 License: MIT Imports: 5 Imported by: 23

README

guinea CI Go Reference

Guinea is a command line interface library.

Description

Programs very often organise the user interface in the form of subcommands. As an example the go command lets the user invoke multiple subcommands such as go build or go get. This library lets you nest any numbers of subcommands (which can be thought of as separate programs) in each other easily building complex user interfaces.

Example

This program implements a root command which displays the program version and two subcommands.

package main

import (
	"fmt"
	"github.com/boreq/guinea"
	"os"
)

var rootCommand = guinea.Command{
	Options: []guinea.Option{
		guinea.Option{
			Name:        "version",
			Type:        guinea.Bool,
			Description: "Display version",
		},
	},
	Run: func(c guinea.Context) error {
		if c.Options["version"].Bool() {
			fmt.Println("v0.0.0-dev")
			return nil
		}
		return guinea.ErrInvalidParms
	},
	Subcommands: map[string]*guinea.Command{
		"display_text": &commandDisplayText,
		"greet":        &commandGreet,
	},
	ShortDescription: "an example program using the guinea library",
	Description:      `This program demonstrates the use of a CLI library.`,
}

var commandDisplayText = guinea.Command{
	Run: func(c guinea.Context) error {
		fmt.Println("Hello world!")
		return nil
	},
	ShortDescription: "displays text on the screen",
	Description:      `This is a subcommand that displays "Hello world!" on the screen.`,
}

var commandGreet = guinea.Command{
	Arguments: []guinea.Argument{
		guinea.Argument{
			Name:        "person",
			Multiple:    false,
			Description: "a person to greet",
		},
	},
	Options: []guinea.Option{
		guinea.Option{
			Name:        "times",
			Type:        guinea.Int,
			Description: "Number of greetings",
			Default:     1,
		},
	},
	Run: func(c guinea.Context) error {
		for i := 0; i < c.Options["times"].Int(); i++ {
			fmt.Printf("Hello %s!\n", c.Arguments[0])
		}
		return nil
	},
	ShortDescription: "greets the specified person",
	Description:      `This is a subcommand that greets the specified person.`,
}

func main() {
	if err := guinea.Run(&rootCommand); err != nil {
		fmt.Fprintln(os.Stderr, err)
	}
}

And here are the example invocations of the program:

$ ./main --help
$ ./main --version
$ ./main display_text
$ ./main hello --help
$ ./main hello boreq
$ ./main hello --times 10 boreq

Documentation

Overview

Package guinea is a command line interface library.

Defining commands

This library operates on a tree-like structure of available commands. In the following example we define a root command with two subcommands. It will most likely be the best to define the commands as global variables in your package.

var rootCommand = guinea.Command{
	Run: func(c guinea.Context) error {
		fmt.Println("This is a root command.")
		return nil
	},
	Subcommands: map[string]*guinea.Command{
		"subcommandA": &subCommandA,
		"subcommandB": &subCommandB,
	},
}

var subCommandA = guinea.Command{
	Run: func(c guinea.Context) error {
		fmt.Println("This is the first subcommand.")
		return nil
	},
}

var subCommandB = guinea.Command{
	Run: func(c guinea.Context) error {
		fmt.Println("This is the second subcommand.")
		return nil
	},
}

Executing the commands

After defining the commands use the run function to execute them. The library will read os.Args to determine which command should be executed and to populate the context passed to it with options and arguments.

if err := guinea.Run(&rootCommand); err != nil {
	fmt.Fprintln(os.Stderr, err)
}

Using the program

The user can invoke a program in multiple ways.

$ ./example_program
$ ./example_program subcommandA
$ ./example_program subcommandB

Passing options and arguments

To let the user call a command with arguments or options populate the proper lists in the command struct.

var parametrizedCommand = guinea.Command{
	Run: func(c guinea.Context) error {
		fmt.Printf("Argument: %s\n", c.Arguments[0])
		fmt.Printf("Option: %d\n", c.Options["myopt"].Int())
		return nil
	},
	Arguments: []guinea.Argument{
		guinea.Argument{
			Name:        "myargument",
			Description: "An argument of a command.",
		},
	},
	Options: []guinea.Option{
		guinea.Option{
			Name:        "myopt",
			Type:        guinea.Int,
			Description: "An option which accepts an integer.",
			Default:     1,
		},
	},
}

If you wish to parse the arguments in a different way simply don't define any options or arguments in the command struct and pass the arguments from the context to your parsing function.

Index

Constants

This section is empty.

Variables

View Source
var ErrInvalidParms = errors.New("invalid parameters")

ErrInvalidParms can be returned by a CommandFunction to automatically display help text.

Functions

func Run

func Run(rootCommand *Command) error

Run is a high level function which adds special behaviour to the commands, namely displaying help to the user. If you wish to use the library without that feature use the FindCommand function directly.

Types

type Argument

type Argument struct {
	Name        string
	Multiple    bool
	Optional    bool
	Description string
}

Argument represents a required argument.

func (Argument) String

func (arg Argument) String() string

String places the argument name in angle brackets and appends three dots to it in order to indicate multiple arguments. It is used to generate help texts.

type Command

type Command struct {
	Run              CommandFunction
	Subcommands      map[string]*Command
	Options          []Option
	Arguments        []Argument
	ShortDescription string
	Description      string
}

Command represents a single command which can be executed by the program.

func FindCommand

func FindCommand(cmd *Command, args []string) (*Command, string, []string)

FindCommand attempts to recursively locate the command which should be executed. The provided command should be the root command of the program containing all other subcommands. The array containing the provided arguments will most likely be the os.Args array. The function returns the located subcommand, its name and the remaining unused arguments. Those values should be passed to the Command.Execute method.

func (Command) Execute

func (c Command) Execute(cmdName string, cmdArgs []string) error

Execute runs the command. Command name is used to generate the help texts and should usually be set to one of the return values of FindCommand. The array of the arguments provided for this subcommand is used to generate the context and should be set to one of the return values of FindCommand as well. The command will not be executed with an insufficient number of arguments so there is no need to check that in the run function.

func (Command) Help

func (c Command) Help(cmdName string) string

Help returns the full help text for this command The text contains the syntax of the command, a description, a list of accepted options and arguments and available subcommands. Command name should be set to one of the return values of FindCommand.

func (Command) PrintHelp

func (c Command) PrintHelp(cmdName string)

PrintHelp prints the return value of Help to the standard output.

func (Command) UsageString

func (c Command) UsageString(cmdName string) string

UsageString returns a short string containing the syntax of this command. Command name should be set to one of the return values of FindCommand.

type CommandFunction

type CommandFunction func(Context) error

type Context

type Context struct {
	Options   map[string]OptionValue
	Arguments []string
}

Context holds the options and arguments provided by the user.

type Option

type Option struct {
	Name        string
	Type        ValType
	Default     interface{}
	Description string
}

Option represents an optional flag.

func (Option) String

func (opt Option) String() string

String prepends the option name with one or two leading dashes and returns it. It is used to generate help texts.

type OptionValue

type OptionValue struct {
	Value interface{}
}

OptionValue stores the value of a parsed option as returned by the standard library flag package. The helper methods can be used to cast the value quickly but they will only succeed if the defined type of the option matches the called method.

func (OptionValue) Bool

func (v OptionValue) Bool() bool

Bool casts a value to a bool and panics on failure.

func (OptionValue) Int

func (v OptionValue) Int() int

Int casts a value to an int and panics on failure.

func (OptionValue) Str

func (v OptionValue) Str() string

Str casts a value to a string and panics on failure.

type ValType

type ValType int
const (
	String ValType = iota
	Bool
	Int
)

Jump to

Keyboard shortcuts

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