cli

package module
v0.0.5 Latest Latest
Warning

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

Go to latest
Published: Oct 20, 2021 License: BSD-3-Clause Imports: 16 Imported by: 0

README

= CLI

Struct-based CLI library for Go

== Status

This project is alpha. It lacks in documentation, testing and featres. It's out for feedback and bug reports. Expect bugs and breaking changes.

== Example

[source,go]
----
package main

import (
	"context"
	"fmt"
	"log"

	"github.com/thegrumpylion/cli"
)

type rootCmd struct {
	Host string
	Port int
}

func (c *rootCmd) Run(ctx context.Context) error {
	fmt.Println(c.Host, c.Port)
	return nil
}

func main() {
	c := &rootCmd{}

	if err := cli.ParseCommandAndExecute(context.Background(), c); err != nil {
		log.Fatalln("error:", err)
	}
}
----

[source,sh]
----
./cmd --host localhost --port 8080
----

----
localhost 8080
----

Or

[source,sh]
----
./cmd --host=localhost --port=8080
----

----
localhost 8080
----

=== Help

[source,sh]
----
./cmd --help
----

----
Usage:
  cmd [--host HOST] [--port PORT]

Flags:
      --host             
      --port
----

=== Completion

[source,sh]
----
complete -o nospace -C ./cmd ./cmd
----

----
$ ./cmd <TAB>
$ ./cmd --<TAB><TAB>
--host   --port
$ ./cmd --
----

Documentation

Index

Constants

View Source
const (
	// SplicerNone no splicer
	SplicerNone = iota
	// SplicerDot . splicer
	SplicerDot
	// SplicerDash - splicer
	SplicerDash
	// SplicerUnderscore _ splicer
	SplicerUnderscore
)

Variables

View Source
var ErrInvalidFlag = func(flg string) error { return fmt.Errorf("invalid flag: %s", flg) }
View Source
var ErrInvalidValue = func(val, flg string) error { return fmt.Errorf("invalid value: %s for flag: %s", val, flg) }

Functions

func LastErrorFromContext

func LastErrorFromContext(ctx context.Context) error

LastErrorFromContext get the last error in case the execution continues on errors

func NewCommand

func NewCommand(name string, cmd interface{})

NewCommand add new root command to defaultCLI

func Parse

func Parse(args []string) error

Parse marshal string args to struct using the defaultCLI

func ParseCommand

func ParseCommand(cmd interface{}) error

ParseCommand creates a new root command from 1st OS arg and cmd and parses os.Args as input on default CLI

func ParseCommandAndRun

func ParseCommandAndRun(ctx context.Context, cmd interface{}) error

ParseCommandAndRun combines ParseCommand & Run

func RegisterEnum

func RegisterEnum(enumMap interface{})

RegisterEnum resgister an enum map to the default CLI

func RegisterNamedCompleter

func RegisterNamedCompleter(name string, comp Completer)

RegisterNamedCompleter adds named completers to be accessed by struct tag `complete:""`

func Run

func Run(ctx context.Context) error

Run the chain of commands in default parser

Types

type CLI

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

CLI holds the cli state and configration

func NewCLI

func NewCLI(options ...Option) *CLI

NewCLI create new CLI

func (*CLI) NewCommand

func (cli *CLI) NewCommand(name string, cmd interface{})

NewCommand add new root command to this CLI

func (*CLI) Parse

func (cli *CLI) Parse(args []string) (err error)

Parse marshal string args to struct

func (*CLI) ParseCommand

func (cli *CLI) ParseCommand(cmd interface{}) error

ParseCommand creates a new root command from 1st OS arg and cmd and parses os.Args as input

func (*CLI) ParseCommandAndRun

func (cli *CLI) ParseCommandAndRun(ctx context.Context, cmd interface{}) error

ParseCommandAndRun combines ParseCommand & Run

func (*CLI) RegisterEnum

func (cli *CLI) RegisterEnum(enumMap interface{})

RegisterEnum resgister an enum map. map must have string key and int/uint value. The value must also be a custom type e.g. type MyEnum uint32

func (*CLI) Run

func (cli *CLI) Run(ctx context.Context) error

Execute the chain of commands

type Case

type Case uint32

Case string case

const (
	// CaseNone string as is
	CaseNone Case = iota
	// CaseLower caselower
	CaseLower
	// CaseUpper CASEUPPER
	CaseUpper
	// CaseCamel CaseCamel
	CaseCamel
	// CaseCamelLower caseCamelLower
	CaseCamelLower
	// CaseSnake case_snake
	CaseSnake
	// CaseSnakeUpper CASE_SNAKE_UPPER
	CaseSnakeUpper
	// CaseKebab case-kebab
	CaseKebab
	// CaseKebabUpper CASE-KEBAB-UPPER
	CaseKebabUpper
)

func (Case) Parse

func (c Case) Parse(s string) string

Parse resturns s in case c

type Completer

type Completer interface {
	// Complete returns suggestions filtered by val
	Complete(val string) []string
}

Completer interface

type Descriptioner

type Descriptioner interface {
	Description() string
}

type ErrCommandNotFound

type ErrCommandNotFound struct {
	Command string
}

func (ErrCommandNotFound) Error

func (e ErrCommandNotFound) Error() string

type ErrNoSuchFlag

type ErrNoSuchFlag struct {
	Flag string
}

func (ErrNoSuchFlag) Error

func (e ErrNoSuchFlag) Error() string

type FuncCompleter

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

FuncCompleter creates a Completer from a func of the same signature

func NewFuncCmpleter

func NewFuncCmpleter(f func(val string) []string) *FuncCompleter

NewFuncCmpleter instantiates a new FuncCompleter from f

func (*FuncCompleter) Complete

func (fc *FuncCompleter) Complete(val string) []string

type Helper

type Helper interface {
	Help() string
}

type OnErrorStrategy

type OnErrorStrategy uint

OnErrorStrategy defines how errors are handled on execution

const (
	// OnErrorBreak halt execution and return the error immediately
	OnErrorBreak OnErrorStrategy = iota
	// OnErrorPostRunners execute post runners in stack but break if post runner returns error.
	// LastErrorFromContext can be used to retrieve the error
	OnErrorPostRunners
	// OnErrorPostRunnersContinue execute post runners in stack ignoring errors. LastErrorFromContext
	// can be used to retrieve any error
	OnErrorPostRunnersContinue
	// OnErrorContinue ignore errors. LastErrorFromContext can be used to retrieve any error.
	OnErrorContinue
)

type Option

type Option func(o *cliOptions)

Option option type for Parser

func WithArgCase

func WithArgCase(c Case) Option

WithArgCase set the arg case. default is CaseCamelLower

func WithArgSplicer

func WithArgSplicer(s Splicer) Option

WithArgSplicer set the arg splicer

func WithCmdCase

func WithCmdCase(c Case) Option

WithCmdCase set the cmd case. default is CaseLower

func WithCmdColumnSize

func WithCmdColumnSize(s uint) Option

WithCmdColumnSize sets the command description column size in help

func WithEnvCase

func WithEnvCase(c Case) Option

WithEnvCase set the env case. default is CaseSnakeUpper

func WithEnvSplicer

func WithEnvSplicer(s Splicer) Option

WithEnvSplicer set the env splicer

func WithFlagColumnSize

func WithFlagColumnSize(s uint) Option

WithFlagColumnSize sets the flag description column size in help

func WithGlobalArgsEnabled

func WithGlobalArgsEnabled() Option

WithGlobalArgsEnabled enable global argumets

func WithHelpFlags

func WithHelpFlags(long, short string) Option

WithHelpFlags sets the help flags. Default --help,-h

func WithIdentSize

func WithIdentSize(s uint) Option

WithIdentSize sets the ident size for command, flags & arguments displayed in help

func WithOnErrorStrategy

func WithOnErrorStrategy(str OnErrorStrategy) Option

WithOnErrorStrategy sets the execution strategy for handling errors

func WithSeparator

func WithSeparator(sep Separator) Option

WithSeparator sets the flag separator charachter for help and completion

func WithStructTags

func WithStructTags(tags StructTags) Option

WithStructTags sets the struct tags to be used by this parser

func WithVersionFlags

func WithVersionFlags(long, short string) Option

WithVersionFlags sets the version flags. Default --version

type PersistentPostRunner

type PersistentPostRunner interface {
	PersistentPostRun(ctx context.Context) error
}

PersistentPostRunner interface

type PersistentPreRunner

type PersistentPreRunner interface {
	PersistentPreRun(ctx context.Context) error
}

PersistentPreRunner interface

type PostRunner

type PostRunner interface {
	PostRun(ctx context.Context) error
}

PostRunner interface

type PreRunner

type PreRunner interface {
	PreRun(ctx context.Context) error
}

PreRunner interface

type Runner

type Runner interface {
	Run(ctx context.Context) error
}

Runner interface

type Separator

type Separator byte
const (
	SeparatorSpace  Separator = ' '
	SeparatorEquals Separator = '='
)

type Splicer

type Splicer uint32

Splicer neated arg/env string splicer

func (Splicer) Splice

func (s Splicer) Splice(a, b string) string

Splice concatenates a and b separated by char s

type StateFunc

type StateFunc func(s string, t parserToken) (StateFunc, error)

type StructTags

type StructTags struct {
	Cli      string
	Cmd      string
	Long     string
	Short    string
	Env      string
	Default  string
	Usage    string
	Complete string
}

StructTags struct tags values

type Versioner

type Versioner interface {
	Version() string
}

Jump to

Keyboard shortcuts

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