clif

package module
v0.0.0-...-54e9ad4 Latest Latest
Warning

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

Go to latest
Published: Jun 17, 2015 License: MIT Imports: 12 Imported by: 0

README

status

CLIF - Command line interface framework

Go framework for rapid command line application development.

Example

extended

package main

import "gopkg.in/ukautz/clif.v0"

func main() {
	c := cli.New("My App", "1.0.0", "An example application").
		New("hello", "The obligatory hello world", func(out cli.Output) {
			out.Printf("Hello World\n")
		})
	c.Run()
}


Install

$ go get gopkg.in/ukautz/clif.v0

Getting started

One the one side, CLIF's builder-like API can be easily used for rapid development of small, single purpose tools. On the other side, CLIF is designed with complex console applications in mind.

clif.New("My App", "1.0.0", "An example application").
	New("ls", "", func() { fmt.Printf("Foo\n") }).
	New("bar", "", func() { fmt.Printf("Bar\n") }).
	Run()

Commands

Commands must have a unique name and can have additional arguments and options.

cmd1 := cli.NewCommand("name", "A description", callBackFunction)
cmd2 := cli.NewCommand("other", "Another description", callBackFunction2)

The name is used from the command line to call the command:

$ ./app name
$ ./app other
Callback functions

Callback functions can have arbitrary parameters. CLIF uses a small, built-in dependency injection container which allows you to register any kind of object (struct or interface) beforehand.

CLIF pre-populates the dependency container with a couple of built-in objects:

  • The Output (formatted output helper, see below)
  • The Input (input helper, see below)
  • The *Cli instance itself
  • The current *Command instance
package main

import "gopkg.in/ukautz/clif.v0"

type MyFoo struct {}

// ... MyFoo implementation

func callMe(out clif.Output, foo *MyFoo) {
	out.Printf("Foo: %s\n", foo)
}

func main() {
	cli := clif.New("my-app", "My kewl App", "0.8.5").
		New("call", "Call me", callMe).
		Register(new(MyFoo))
	cli.Run()
}

If you want to register an interface, you need to use the Go'ish way:

package main

import "gopkg.in/ukautz/clif.v0"

// the interface
type MyFoo interface {
	Bar() string
}

// the struct implementing the interface
type MyBar struct {}

// ... MyBar implementation

func callMe(out clif.Output, foo MyFoo) {
	out.Printf("Foo: %s\n", foo)
}

func main() {
	t := reflect.TypeOf((*MyFoo)(nil)).Elem()
	cli := clif.New("my-app", "My kewl App", "0.8.5").
		New("call", "Call me", callMe).
		RegisterAs(t.String(), new(MyBar))
	cli.Run()
}
Arguments and Options

CLIF can deal with arguments and options. The difference being:

  • Arguments come after the command name. They are identified by their position.
  • Options have no fixed position. They are identified by their --opt-name (or alias, eg -O)

Of course you can use arguments and options at the same time..

Arguments

Arguments are additional command line parameters which come after the command name itself.

cmd := cli.NewCommand("hello", "A description", callBackFunction)
	.NewArgument("name", "Name for greeting", "", true, false)

arg := clif.NewAgument("other", "Something ..", "default", false, true)
cmd.AddArgument(arg)

Arguments consist of a name, a description, an optional default value a required flag and a multiple flag.

$ ./my-app hello the-name other1 other2 other3
#            ^      ^       ^       ^     ^
#            |      |       |       |     |
#            |      |       |       | third "other" arg
#            |      |       |  second "other" arg
#            |      |  first "other" arg
#            |  the "name" arg
#        command name

Position of arguments matters. Make sure you add them in the right order. And: required arguments must come before optional arguments (makes sense, right?). There can be only one multiple argument at all.

You can access the arguments by injecting the command instance into the callback and calling the Argument() method. You can choose to interpret the argument as String(), Int(), Float(), Bool(), Time() or Json(). Multiple arguments can be accessed with Strings(), Ints() .. and so on. Count() gives the amount of (provided) multiple arguments and Provided() returns bool for optional arguments. Pleas see parameter.go for more.

func callbackFunctionI(c *clif.Command) {
	name := c.Argument("name").String()
	others := c.Argument("other").Strings()
	// .. do something ..
}
Options

Options have no fixed position. They are referenced by their name (eg --name) or alias (eg -n).

cmd := cli.NewCommand("hello", "A description", callBackFunction)
	.NewOption("name", "n", "Name for greeting", "", true, false)

arg := clif.NewOption("other", "O", "Something ..", "default", false, true)
cmd.AddOption(arg)

Now:

$ ./my-app hello --other bar -n Me -O foo
#                       ^       ^    ^
#                       |       |    |
#                       |       |  second other opt
#                       |   name opt
#                  first other opt

You can access options the same way as arguments, just use Option() instead.

func callbackFunctionI(c *clif.Command) {
	name := c.Option("name").String()
	others := c.Option("other").Strings()
	// .. do something ..
}
Flags

There is a special kind of option, which does not expect a parameter: the flag.

flag := clif.NewOption("my-flag", "f", "Something ..", "", false, false).IsFlag()
cmd := cli.NewCommand("hello", "A description", callBackFunction).AddOption(flag)

Usually, you want to use Bool() on flags:

func callbackFunctionI(c *clif.Command) {
	if c.Option("my-flag").Bool() {
		// ..
	}
}
Validation

You can provide argument or option validators, which are executed on parsing the command line input, before it is delegated to your callback.

arg := clif.NewArgument("my-int", "An integer", "", true, false)
arg.SetValidator(func(name, value string) error {
	if _, err := strconv.Atoi(value); err != nil {
		return fmt.Errorf("Oops: %s is not an integer: %s", name, err)
	} else {
		return nil
	}
})

There are a couple of built-in validators you can use out of the box:

  • clif.IsInt - Checks for integer
  • clif.IsFloat - Checks for float

See validators.go.

Input & Output

Of course, you can just use fmt and os.Stdin, but for convenience (and fancy output) there are clif.Output and clif.Input.

func callbackFunctionI(in clif.Input, out clif.Output) {
	name := in.Ask("Who are you? ", func(v string) error {
		if len(v) > 0 {
			return nil
		} else {
			return fmt.Errorf("Didn't catch that")
		}
	})
	father := in.Choose("Who is your father?", map[string]string{
		"yoda":  "The small, green guy",
		"darth": "NOOOOOOOO!",
		"obi":   "The old man with the light thingy",
	})

	out.Printf("Well, %s, ", name)
	if father != "darth" {
		out.Printf("<success>may the force be with you!<reset>\n")
	} else {
		out.Printf("<error>u bad!<reset>\n")
	}
}

input

Customizing Input

There is not much. Check out RenderChooseQuestion, RenderChooseOption and RenderChooseQuery in input.go.

Extending Output

Output comes with a set of tokens, such as <success> or <error>, which inject ASCII color codes into the output stream. If you don't want fancy colors, you can just:

cli := clif.New("my-app", "0.1.0", "Boring output")
cli.SetOutput(clif.NewPlainOutput())

To extend or change the fancy style, please modify clif.DefaultStyles in formatter.go.

See also

There are a lot of other approaches you should have a look at.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var DefaultHelpOption = &Option{
	parameter: parameter{
		Name:        "help",
		Usage:       "Display this help message",
		Description: "Display this help message",
	},
	Alias: "h",
	Flag:  true,
}

DefaultOptions are prepended to any newly created command

View Source
var DefaultOptions = []*Option{DefaultHelpOption}

DefaultOptions are prepended to any newly created command

View Source
var DefaultStyles = map[string]string{
	"error":     "\033[31;1m",
	"warn":      "\033[33m",
	"info":      "\033[36m",
	"success":   "\033[32m",
	"debug":     "\033[30;1m",
	"headline":  "\033[4;1m",
	"subline":   "\033[4m",
	"important": "\033[47;30;1m",
	"query":     "\033[34m",
	"reset":     "\033[0m",
}
View Source
var DescribeCli = func(c *Cli) string {

	line := "<headline>" + c.Name + "<reset>"
	if c.Version != "" {
		line += " <debug>(" + c.Version + ")<reset>"
	}
	lines := []string{line}

	if c.Description != "" {
		lines = append(lines, "<info>"+c.Description+"<reset>\n")
	}

	prog := filepath.Base(os.Args[0])
	lines = append(lines, fmt.Sprintf("<subline>Usage:<reset>\n  %s command [arg ..] [--opt val ..]\n", prog))

	lines = append(lines, "<subline>Available commands:<reset>")
	max := 0
	ordered := make(map[string][]*Command)
	prefices := make([]string, 0)
	for _, cmd := range c.Commands {
		if l := len(cmd.Name); l > max {
			max = l
		}
		prefix := ""
		if i := strings.Index(cmd.Name, ":"); i > -1 {
			prefix = cmd.Name[0:i]
		}
		if ordered[prefix] == nil {
			prefices = append(prefices, prefix)
			ordered[prefix] = make([]*Command, 0)
		}
		ordered[prefix] = append(ordered[prefix], cmd)
	}
	sort.Strings(prefices)
	for _, prefix := range prefices {
		if prefix != "" {
			lines = append(lines, fmt.Sprintf(" <subline>%s<reset>", prefix))
		}
		sort.Sort(CommandsSort(ordered[prefix]))
		for _, cmd := range ordered[prefix] {
			lines = append(lines, fmt.Sprintf("  <info>%-"+fmt.Sprintf("%d", max)+"s<reset>  %s", cmd.Name, cmd.Usage))
		}
	}

	return strings.Join(lines, "\n") + "\n"
}
View Source
var DescribeCommand = func(c *Command) string {
	lines := []string{"Command: <headline>" + c.Name + "<reset>"}

	if c.Description != "" {
		lines = append(lines, []string{"<info>" + c.Description + "<reset>", ""}...)
	} else if c.Usage != "" {
		lines = append(lines, []string{"<info>" + c.Usage + "<reset>", ""}...)
	}

	lines = append(lines, "<subline>Usage:<reset>")
	usage := []string{c.Name}
	args := make([][]string, 0)
	argMax := 0
	opts := make([][]string, 0)
	optMax := 0
	for _, p := range c.Arguments {
		var short string
		usg := p.Usage
		short = p.Name
		if p.Multiple {
			short = short + " ..."
			usg += " (mult)"
		}
		if p.Required {
			usg += " (req)"
		} else {
			short = fmt.Sprintf("[%s]", short)
		}
		if p.Default != "" {
			usg += fmt.Sprintf(" (default: \"%s\")", p.Default)
		}
		if l := len(p.Name); l > argMax {
			argMax = l
		}
		usage = append(usage, short)
		args = append(args, []string{p.Name, usg})
	}

	for _, p := range c.Options {
		short := fmt.Sprintf("--%s", p.Name)
		if p.Alias != "" {
			short += "|-" + p.Alias
		}
		if !p.Flag {
			short += " val"
		}
		long := short
		usg := p.Usage
		if !p.Required {
			short = "[" + short + "]"
		} else {
			usg += " (req)"
		}
		if p.Multiple {
			short = short + " ..."
			usg += " (mult)"
		}
		if p.Default != "" {
			usg += fmt.Sprintf(" (default: \"%s\")", p.Default)
		}
		if l := len(long); l > optMax {
			optMax = l
		}
		usage = append(usage, short)
		opts = append(opts, []string{long, usg})
	}
	lines = append(lines, "  "+strings.Join(usage, " "))
	lines = append(lines, "")

	if len(args) > 0 {
		lines = append(lines, "<subline>Arguments:<reset>")
		for _, l := range args {
			lines = append(lines, fmt.Sprintf("  <info>%-"+fmt.Sprintf("%d", argMax)+"s<reset>  %s", l[0], l[1]))
		}
		lines = append(lines, "")
	}

	if len(opts) > 0 {
		lines = append(lines, "<subline>Options:<reset>")
		for _, l := range opts {
			lines = append(lines, fmt.Sprintf("  <info>%-"+fmt.Sprintf("%d", optMax)+"s<reset>  %s", l[0], l[1]))
		}
		lines = append(lines, "")
	}

	return strings.Join(lines, "\n") + "\n"
}
View Source
var Die = func(msg string, args ...interface{}) {
	fmt.Printf(msg+"\n", args...)
	os.Exit(1)
}
View Source
var RenderChooseOption = func(key, value string, size int) string {
	return fmt.Sprintf("  <query>%-"+fmt.Sprintf("%d", size+1)+"s<reset> %s\n", key+")", value)
}
View Source
var RenderChooseQuery = func() string {
	return "Choose: "
}
View Source
var RenderChooseQuestion = func(question string) string {
	return question + "\n"
}

Functions

func IsFloat

func IsFloat(name, value string) error

IsInt checks if value is float

func IsInt

func IsInt(name, value string) error

IsInt checks if value is an integer

Types

type Argument

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

Arguments must be provided immediately after the command in the order they were added. Non required arguments must be orderd after required arguments. Only one argument is allowed to contain multiple values and it needs to be the last one.

func NewArgument

func NewArgument(name, usage, _default string, required, multiple bool) *Argument

func (*Argument) Assign

func (this *Argument) Assign(val string) error

Assign tries to add value to parameter and returns error if it fails due to invalid format or invalid amount (single vs multiple parameters)

func (*Argument) Bool

func (this *Argument) Bool() bool

Float representation of the value (will be false, if not given or not parsable)

func (*Argument) Bools

func (this *Argument) Bools() []bool

Ints representation of the value (can be nil, if non given or slice of 0-values for)

func (*Argument) Count

func (this *Argument) Count() int

Provided returns amount of values provided

func (*Argument) Float

func (this *Argument) Float() float64

Float representation of the value (will be 0, if not given or not parsable)

func (*Argument) Floats

func (this *Argument) Floats() []float64

Ints representation of the value (can be nil, if non given or slice of 0-values for)

func (*Argument) Int

func (this *Argument) Int() int

Int representation of the value (will be 0, if not given or not parsable)

func (*Argument) Ints

func (this *Argument) Ints() []int

Ints representation of the value (can be nil, if non given or slice of 0-values for)

func (*Argument) Json

func (this *Argument) Json() (map[string]interface{}, error)

Json assumes the input is a JSON string and parses into a standard map[string]interface{} Returns error, if not parsable (or eg array JSON)

func (*Argument) Jsons

func (this *Argument) Jsons() ([]map[string]interface{}, error)

func (*Argument) Provided

func (this *Argument) Provided() bool

Provided returns bool whether argument was provided

func (*Argument) SetDefault

func (this *Argument) SetDefault(v string) *parameter

SetDefault is a builder method to set default value

func (*Argument) SetDescription

func (this *Argument) SetDescription(v string) *parameter

SetDescription is a builder method to set description

func (*Argument) SetParser

func (this *Argument) SetParser(v ParserMethod) *parameter

SetDefault is a builder method to set default value

func (*Argument) SetRegex

func (this *Argument) SetRegex(r *regexp.Regexp) *parameter

SetDefault is a builder method to set default value

func (*Argument) SetUsage

func (this *Argument) SetUsage(v string) *parameter

SetUsage is a builder method to set usage

func (*Argument) SetValidator

func (this *Argument) SetValidator(v ValidatorMethod) *parameter

SetDefault is a builder method to set default value

func (*Argument) String

func (this *Argument) String() string

String representation of the value (can be empty string)

func (*Argument) Strings

func (this *Argument) Strings() []string

Strings representation of the value (can be nil)

func (*Argument) Time

func (this *Argument) Time(format ...string) (*time.Time, error)

Date is a date time representation of the value If no format is provided, then `2006-01-02 15:04:05` will be used

func (*Argument) Times

func (this *Argument) Times(format ...string) ([]time.Time, error)

type CallMethod

type CallMethod interface{}

type Cli

type Cli struct {
	Name        string
	Version     string
	Description string
	Commands    map[string]*Command
	Registry    *Registry
}

Cli is a command line interface object

func New

func New(name, version, desc string) *Cli

func (*Cli) Add

func (this *Cli) Add(cmd ...*Command) *Cli

Add is a builder method for adding a new command

func (*Cli) New

func (this *Cli) New(name, usage string, call CallMethod) *Cli

New creates and adds a new command

func (*Cli) Output

func (this *Cli) Output() Output

Output is shorthand for currently registered output

func (*Cli) Register

func (this *Cli) Register(v interface{}) *Cli

RegisterAs is builder method and registers object in registry

func (*Cli) RegisterAs

func (this *Cli) RegisterAs(n string, v interface{}) *Cli

RegisterAs is builder method and registers object under alias in registry

func (*Cli) Run

func (this *Cli) Run()

Run with arguments

func (*Cli) RunWith

func (this *Cli) RunWith(args []string)

Run the cli and be happy

func (*Cli) SetInput

func (this *Cli) SetInput(in Input) *Cli

SetOutput is builder method and replaces current input

func (*Cli) SetOutput

func (this *Cli) SetOutput(out Output) *Cli

SetOutput is builder method and replaces current output

type Command

type Command struct {
	Cli         *Cli
	Name        string
	Usage       string
	Description string
	Options     []*Option
	Arguments   []*Argument
	Call        reflect.Value
}

Command ..

func NewCommand

func NewCommand(name, usage string, call CallMethod) *Command

NewCommand constructs new command

func NewHelpCommand

func NewHelpCommand() *Command

func (*Command) AddArgument

func (this *Command) AddArgument(v *Argument) *Command

AddArgument is builder method to add a new argument

func (*Command) AddOption

func (this *Command) AddOption(v *Option) *Command

AddOption is builder method to add a new option

func (*Command) Argument

func (this *Command) Argument(name string) *Argument

func (*Command) Input

func (this *Command) Input() map[string][]string

func (*Command) NewArgument

func (this *Command) NewArgument(name, usage, _default string, required, multiple bool) *Command

AddArgument is builder method to add a new argument

func (*Command) NewOption

func (this *Command) NewOption(name, alias, usage, _default string, required, multiple bool) *Command

AddOption is builder method to add a new option

func (*Command) Option

func (this *Command) Option(name string) *Option

func (*Command) Parse

func (this *Command) Parse(args []string) error

Parse command line args to argument

func (*Command) SetCli

func (this *Command) SetCli(c *Cli) *Command

SetDescription is builder method setting desciption

func (*Command) SetDescription

func (this *Command) SetDescription(desc string) *Command

SetDescription is builder method setting desciption

type CommandsSort

type CommandsSort []*Command

func (CommandsSort) Len

func (this CommandsSort) Len() int

func (CommandsSort) Less

func (this CommandsSort) Less(i, j int) bool

func (CommandsSort) Swap

func (this CommandsSort) Swap(i, j int)

type DefaultFormatter

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

DefaultFormatter strips all formatting from the output message

func NewDefaultFormatter

func NewDefaultFormatter(styles map[string]string) *DefaultFormatter

func (*DefaultFormatter) Format

func (this *DefaultFormatter) Format(msg string) string

type DefaultInput

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

func NewDefaultInput

func NewDefaultInput(in io.Reader, out Output) *DefaultInput

func (*DefaultInput) Ask

func (this *DefaultInput) Ask(question string, check func(string) error) string

func (*DefaultInput) AskRegex

func (this *DefaultInput) AskRegex(question string, rx *regexp.Regexp) string

func (*DefaultInput) Choose

func (this *DefaultInput) Choose(question string, choices map[string]string) string

type DefaultOutput

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

func NewFancyOutput

func NewFancyOutput(io io.Writer) *DefaultOutput

func NewOutput

func NewOutput(io io.Writer, f Formatter) *DefaultOutput

func NewPlainOutput

func NewPlainOutput(io io.Writer) *DefaultOutput

func (*DefaultOutput) Printf

func (this *DefaultOutput) Printf(msg string, args ...interface{})

func (*DefaultOutput) SetFormatter

func (this *DefaultOutput) SetFormatter(f Formatter) Output

type Formatter

type Formatter interface {

	// Format renders message with args for output
	Format(msg string) string
}

Formatter is used by Output for rendering. It supports style directives in the form <info> or <end> or suchlike

type Input

type Input interface {
	// Ask reads user input and returns as soon as it's non empty or queries again until it is
	Ask(question string, check func(string) error) string

	// AskRegex reads user input, compares it against regex and return if matching or queries again until it does
	AskRegex(question string, rx *regexp.Regexp) string

	// Choose renders choices for user and returns what was choosen
	Choose(question string, choices map[string]string) string
}

type Option

type Option struct {

	// Alias can be a shorter name
	Alias string

	// If is a flag, then no value can be assigned (if present, then bool true)
	Flag bool
	// contains filtered or unexported fields
}

Option is like an argument, but with a single or double dash in front

func NewOption

func NewOption(name, alias, usage, _default string, required, multiple bool) *Option

func (*Option) Assign

func (this *Option) Assign(val string) error

Assign tries to add value to parameter and returns error if it fails due to invalid format or invalid amount (single vs multiple parameters)

func (*Option) Bool

func (this *Option) Bool() bool

Float representation of the value (will be false, if not given or not parsable)

func (*Option) Bools

func (this *Option) Bools() []bool

Ints representation of the value (can be nil, if non given or slice of 0-values for)

func (*Option) Count

func (this *Option) Count() int

Provided returns amount of values provided

func (*Option) Float

func (this *Option) Float() float64

Float representation of the value (will be 0, if not given or not parsable)

func (*Option) Floats

func (this *Option) Floats() []float64

Ints representation of the value (can be nil, if non given or slice of 0-values for)

func (*Option) Int

func (this *Option) Int() int

Int representation of the value (will be 0, if not given or not parsable)

func (*Option) Ints

func (this *Option) Ints() []int

Ints representation of the value (can be nil, if non given or slice of 0-values for)

func (*Option) IsFlag

func (this *Option) IsFlag() *Option

func (*Option) Json

func (this *Option) Json() (map[string]interface{}, error)

Json assumes the input is a JSON string and parses into a standard map[string]interface{} Returns error, if not parsable (or eg array JSON)

func (*Option) Jsons

func (this *Option) Jsons() ([]map[string]interface{}, error)

func (*Option) Provided

func (this *Option) Provided() bool

Provided returns bool whether argument was provided

func (*Option) SetDefault

func (this *Option) SetDefault(v string) *parameter

SetDefault is a builder method to set default value

func (*Option) SetDescription

func (this *Option) SetDescription(v string) *parameter

SetDescription is a builder method to set description

func (*Option) SetParser

func (this *Option) SetParser(v ParserMethod) *parameter

SetDefault is a builder method to set default value

func (*Option) SetRegex

func (this *Option) SetRegex(r *regexp.Regexp) *parameter

SetDefault is a builder method to set default value

func (*Option) SetUsage

func (this *Option) SetUsage(v string) *parameter

SetUsage is a builder method to set usage

func (*Option) SetValidator

func (this *Option) SetValidator(v ValidatorMethod) *parameter

SetDefault is a builder method to set default value

func (*Option) String

func (this *Option) String() string

String representation of the value (can be empty string)

func (*Option) Strings

func (this *Option) Strings() []string

Strings representation of the value (can be nil)

func (*Option) Time

func (this *Option) Time(format ...string) (*time.Time, error)

Date is a date time representation of the value If no format is provided, then `2006-01-02 15:04:05` will be used

func (*Option) Times

func (this *Option) Times(format ...string) ([]time.Time, error)

type Output

type Output interface {
	// Printf writes to output
	Printf(msg string, args ...interface{})

	// SetFormatter is builder method and replaces current formatter
	SetFormatter(f Formatter) Output
}

Output is interface for outputter classes

type ParserMethod

type ParserMethod func(name, value string) (string, error)

type Registry

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

func NewRegistry

func NewRegistry() *Registry

func (*Registry) Alias

func (this *Registry) Alias(alias string, v interface{})

func (*Registry) Get

func (this *Registry) Get(s string) reflect.Value

func (*Registry) Has

func (this *Registry) Has(s string) bool

func (*Registry) Register

func (this *Registry) Register(v interface{})

type ValidatorMethod

type ValidatorMethod func(name, value string) error

func IsAll

func IsAll(v ...ValidatorMethod) ValidatorMethod

IsAll joins a set of validators methods and returns true if ALL of them match

func IsAny

func IsAny(v ...ValidatorMethod) ValidatorMethod

IsAny joins a set of validator methods and returns true if ANY of them matches

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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