cli

package module
v1.3.2 Latest Latest
Warning

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

Go to latest
Published: Feb 28, 2024 License: MIT Imports: 8 Imported by: 1

README

License go.mod Go version GoDoc Latest tag Go Report

Command Line Interface made simpler

The main goal of this package is to avoid being too tightly coupled with existing CLI framework.

Motivation

As of today, there are some very nice frameworks to use to handle command line interface; one of them is spf13/cobra; but it is not super obvious how to create something decoupled from cobra.

Why would someone want to do that ?

  • i was using spf13/cobra and wanted to try urfave/cli and it implied quite a lot of changes to my application
  • i tried to avoid using a framework, but I was reinventing a lot of stuff
  • frameworks expose you to a lot of features, but it comes with a lot of concepts, and two different frameworks does not necessarily come with the same concepts nor the same implementation

I did not want to recreate yet a new CLI framework to solve my problem because existing ones already are complete, but I am not using a lot of features and I wanted to keep things simple to use, simple to test, and simple to extend.

Usage

The simplest command is defined by implementing the Command interface

type myCommand struct{}
func (myCommand) Execute(ctx context.Context, args []string, dashedArgs []string) error {
	return nil
}

func main() {
	cmd := cli.NewCommand(myCommand{})
	err := spf13cobra.Execute(context.Background(), os.Args, cmd)
	cli.Exit(err)
}

This will create a CLI with one root command. This CLI is then mapped to be executed by the spf13/cobra framework.

A more useful / complex example can be found in internal/example.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Exit

func Exit(ctx context.Context, err error, options ...ExitOption)

Exit exits the program and uses provided error to define program success or failure.

func GetInitializedFlagsFromContext added in v1.2.0

func GetInitializedFlagsFromContext(ctx context.Context) ([]Flag, []Flag)

GetInitializedFlagsFromContext returns initialized command flags.

func GetMetadataFromContext

func GetMetadataFromContext(ctx context.Context, key any) any

GetMetadataFromContext retrieves any value stores to the provided key, if any.

func NewCommandContext added in v1.2.0

func NewCommandContext(ctx context.Context) context.Context

NewCommandContext is called for each command to create a dedicated context.

func NewContextCancelableBySignal

func NewContextCancelableBySignal(sig os.Signal, sigs ...os.Signal) (context.Context, func())

NewContextCancelableBySignal creates a new context that cancels itself when provided signals are triggered.

func NewContextWithMetadata

func NewContextWithMetadata(ctx context.Context) context.Context

NewContextWithMetadata wraps the provided context to create a global metadata store to the CLI. It helps to pass dependencies across commands tree.

func NewErrorWithExitStatus

func NewErrorWithExitStatus(err error, status uint8) error

NewErrorWithExitStatus wraps the provided error and tells the CLI to exit with provided code.

func NewErrorWithHelp

func NewErrorWithHelp(err error) error

NewErrorWithHelp wraps provided error and tells the CLI to show usage help.

func SetExitLoggerInMetadata

func SetExitLoggerInMetadata(ctx context.Context, writer io.WriteCloser)

SetExitLoggerInMetadata sets the logger used by the CLI to write the exit message if any, inside the metadata. By default, the Exit func tries to find the logger in the metadata.

func SetInitializedFlagsInContext added in v1.2.0

func SetInitializedFlagsInContext(ctx context.Context, localFlags, persistentFlags []Flag)

SetInitializedFlagsInContext sets the provided initialized flags in the command context.

func SetMetadataInContext

func SetMetadataInContext(ctx context.Context, key, value any)

SetMetadataInContext associates a key to a value in the global CLI metadata store.

Types

type CLI

type CLI struct {
	Name        string
	Command     Command
	SubCommands []*CLI
}

CLI stores the settings associated to the CLI.

func New added in v1.3.0

func New(cmd Command) *CLI

New creates a new CLI.

func (*CLI) AddCommand

func (cli *CLI) AddCommand(name string, cmd Command) *CLI

AddCommand adds a new subcommand to the CLI.

func (*CLI) Mount added in v1.1.0

func (cli *CLI) Mount(name string, sub *CLI) *CLI

Mount adds a whole new CLI as a subcommand of the CLI. Provided name command of the cli is used as sub commands name.

type Command

type Command interface {
	Execute(ctx context.Context, args, dashedArgs []string) error
}

Command defines the minimal interface required to execute a CLI command.

type CommandContext

type CommandContext interface {
	Context(ctx context.Context) context.Context
}

CommandContext defines a way to propagate a custom context to child commands.

type CommandDescription

type CommandDescription interface{ Description() string }

CommandDescription defines a way to set a description on the command. A short description is created from the first description line.

type CommandExamples

type CommandExamples interface{ Examples() []string }

CommandExamples defines a way to set command examples.

type CommandFlags

type CommandFlags interface{ Flags() []Flag }

CommandFlags defines the flagValue of the command.

type CommandHook

type CommandHook interface{ Hook() *Hook }

CommandHook defines some callback called during command lifecycle.

type CommandPersistentFlags

type CommandPersistentFlags interface{ PersistentFlags() []Flag }

CommandPersistentFlags defines the persistent flags of the command.

type CommandPersistentHook

type CommandPersistentHook interface{ PersistentHook() *PersistentHook }

CommandPersistentHook defines some persistent callback called during command lifecycle. Differences between CommandHook and CommandPersistentHook is that executed command's hierarchy will also be called.

type CommandUsage

type CommandUsage interface{ Usage() string }

CommandUsage defines a way to set the way to use the command.

type ExitOption

type ExitOption func(*exitOptions)

ExitOption defines the function signature to configure things upon exit.

func WithExitFunc

func WithExitFunc(exitFunc func(status int)) ExitOption

WithExitFunc defines a custom function to exit.

func WithExitLoggerFunc

func WithExitLoggerFunc(getLoggerFunc func(context.Context) io.WriteCloser) ExitOption

WithExitLoggerFunc defines a way to customize logger used in messages.

type ExitStatusError

type ExitStatusError interface {
	error
	ExitStatus() uint8
}

ExitStatusError defines a new type of error that allow the customization of the CLI exit status.

type Flag

type Flag interface {
	// FlagValuer defines methods to get and set flag's value.
	FlagValuer

	// LongName if non-empty, defines the long name of the flag like --long.
	LongName() string
	// ShortName if non-empty, defines the short name of the flag like -s.
	ShortName() string
	// Description describes the flag display purpose.
	Description() string
}

Flag defines a flagValue.

func NewBuiltinFlag added in v1.2.0

func NewBuiltinFlag[T builtins](longName, shortName string, destination *T, description string) Flag

NewBuiltinFlag creates a new Flag which underlying type is any builtin type declared below.

longName is the long flagValue name, like --longname ; cannot be empty.
shortName is the short flagValue name ; usually 1 character, like -s ; can be empty.
destination is a pointer on the variable on which flagValue's value will be stored ; cannot be nil.
description is a short text explaining the flagValue ; can be empty.

func NewBuiltinPointerFlag added in v1.2.0

func NewBuiltinPointerFlag[T builtins](longName, shortName string, destination **T, description string) Flag

NewBuiltinPointerFlag creates a new Flag which underlying type is any pointer on builtin type declared below.

longName is the long flagValue name, like --longname ; cannot be empty.
shortName is the short flagValue name ; usually 1 character, like -s ; can be empty.
destination is a pointer on the variable on which flagValue's value will be stored ; cannot be nil.
description is a short text explaining the flagValue ; can be empty.

func NewBuiltinSliceFlag added in v1.2.0

func NewBuiltinSliceFlag[T builtins](longName, shortName string, destination *[]T, description string) Flag

NewBuiltinSliceFlag creates a new Flag which underlying type is any slice of builtin type declared below.

longName is the long flagValue name, like --longname ; cannot be empty.
shortName is the short flagValue name ; usually 1 character, like -s ; can be empty.
destination is a pointer on the variable on which flagValue's value will be stored ; cannot be nil.
description is a short text explaining the flagValue ; can be empty.

func NewFlag

func NewFlag(longName, shortName string, valuer FlagValuer, description string) Flag

NewFlag creates a Flag based on any underlying destination type.

longName is the long flag name, like --longname ; cannot be empty.
shortName is the short flag name ; usually 1 character, like -s ; can be empty.
valuer provide the way to set value to the destination.
description is a short text explaining the flag ; can be empty.

type FlagValuer

type FlagValuer interface {
	// Destination returns flag's value pointer.
	Destination() any
	// FromString parses and set the value.
	FromString(str string) error
	// IsSet returns whether the flag value has been set.
	IsSet() bool
	// String returns a representation of the value.
	String() string
	// TypeRepr returns a representation of the underlying type of the value. Example: 'int'.
	TypeRepr() string
}

FlagValuer defines how to set and get the value of a flag.

func NewFlagValuer added in v1.2.0

func NewFlagValuer[T any](destination *T, parse func(string) (T, error), toString func(T) string) FlagValuer

NewFlagValuer creates a flag valuer from a parse and toString functions. It panics if any parameters are nil.

func NewStringerFlagValuer added in v1.2.0

func NewStringerFlagValuer[T fmt.Stringer](destination *T, parse func(string) (T, error)) FlagValuer

NewStringerFlagValuer creates a flag valuer from a parse function returning something that implements stringer. See NewFlagValuer for more details.

type Hook

type Hook struct {
	BeforeCommandExecution HookFunc
	AfterCommandExecution  HookFunc
}

Hook defines callbacks to add custom behavior to the command lifecycle.

type HookFunc

type HookFunc func(ctx context.Context) error

HookFunc defines the hook signature.

type PersistentHook

type PersistentHook struct {
	BeforeFlagsDefinition  HookFunc
	BeforeCommandExecution HookFunc
	AfterCommandExecution  HookFunc
}

PersistentHook defines callbacks to add custom behavior to the command lifecycle.

type ShowHelpError

type ShowHelpError interface {
	error
	ShowHelp() bool
}

ShowHelpError defines a new type of error that defines whenever the error should display the command help before the error message.

Directories

Path Synopsis
cfg
internal
mapper

Jump to

Keyboard shortcuts

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