flip

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Apr 8, 2019 License: MIT Imports: 12 Imported by: 19

README

flip

A flag line processor for the Go programming language

Example

Examples speak a lot, so jump into some code.

main.go:

    ```
    package main

    import (
        "context"
        "log"
        "os"
        "path"

        "github.com/Laughs-In-Flowers/flip"
    )

    var (
        F              flip.Flipper
        value          string = ""
        versionPackage string = path.Base(os.Args[0])
        versionTag     string = "Example"
        versionHash    string = "Ex#1"
        versionDate    string = "Today"
        output         int    = 0
    )

    func TopCommand() flip.Command {
        var val string
        fs := flip.NewFlagSet("t", flip.ContinueOnError)
        fs.StringVar(&val, "value", val, "A flag string value")

        return flip.NewCommand(
            "",
            "./example",
            "Top level options use.",
            1,
            false,
            func(c context.Context, a []string) (context.Context, flip.ExitStatus) {
                value = value + " " + val
                return c, flip.ExitNo
            },
            fs,
        )
    }

    func RunCommand1() flip.Command {
        var val string
        fs := flip.NewFlagSet("r1", flip.ContinueOnError)
        fs.StringVar(&val, "value", val, "A flag string value")

        return flip.NewCommand(
            "",
            "run1",
            "run1 command",
            1,
            false,
            func(c context.Context, a []string) (context.Context, flip.ExitStatus) {
                value = value + " " + val
                log.Printf("%v", value)
                return c, flip.ExitSuccess
            },
            fs,
        )
    }

    func RunCommand2() flip.Command {
        var val string
        fs := flip.NewFlagSet("r2", flip.ContinueOnError)
        fs.StringVar(&val, "value", val, "A flag string value")

        return flip.NewCommand(
            "",
            "run2",
            "run2 command",
            2,
            false,
            func(c context.Context, a []string) (context.Context, flip.ExitStatus) {
                value = value + " " + val
                log.Printf("%v", value)
                return c, flip.ExitSuccess
            },
            fs,
        )
    }

    func RunCommand3() flip.Command {
        var val string
        fs := flip.NewFlagSet("r3", flip.ContinueOnError)
        fs.StringVar(&val, "value", val, "A flag string value")

        return flip.NewCommand(
            "",
            "run3",
            "run3 command",
            2,
            false,
            func(c context.Context, a []string) (context.Context, flip.ExitStatus) {
                value = value + " " + val
                return c, flip.ExitNo
            },
            fs,
        )
    }

    func init() {
        F = flip.New("example")
        F.AddBuiltIn("version", versionPackage, versionTag, versionHash, versionDate).
            AddBuiltIn("help").
            SetGroup("gtop", -1, TopCommand()).
            SetGroup("grun", 1, RunCommand1(), RunCommand2(), RunCommand3())
    }

    func main() {
        os.Exit(F.Execute(context.Background(), os.Args))
    }               
    ```

compile & run commands:

1. ./example --value "Y" run1 -value "Z"

2. ./example -value "X" run3 -value "Y" run2 -value "Z"

2. ./example version

3. ./example version -tag
    
4. ./example help

5. ./example help grun

6. ./example help run2

Documentation

Index

Constants

This section is empty.

Variables

View Source
var NoColor = !IsTerminal(os.Stdout.Fd())

Functions

func Color

func Color(value ...Attribute) func(io.Writer, ...interface{})

Should work in most terminals. See github.com/mattn/go-colorable for tweaking tips by os.

func IsTerminal

func IsTerminal(fd uintptr) bool

IsTerminal return true if the file descriptor is terminal. see github.com/mattn/go-isatty You WILL want to change this if you are using an os other than a Linux variant.

func UnquoteMessage

func UnquoteMessage(flag *Flag) (name string, usage string)

Types

type Adder

type Adder interface {
	AddBuiltIn(string, ...string) Flipper
}

An interface that handles adding(package builtin commands) by string parameters.

type Attribute

type Attribute int
const (
	Reset Attribute = iota
	Bold
	Faint
	Italic
	Underline
	BlinkSlow
	BlinkRapid
	ReverseVideo
	Concealed
	CrossedOut
)
const (
	FgBlack Attribute = iota + 30
	FgRed
	FgGreen
	FgYellow
	FgBlue
	FgMagenta
	FgCyan
	FgWhite
)
const (
	FgHiBlack Attribute = iota + 90
	FgHiRed
	FgHiGreen
	FgHiYellow
	FgHiBlue
	FgHiMagenta
	FgHiCyan
	FgHiWhite
)
const (
	BgBlack Attribute = iota + 40
	BgRed
	BgGreen
	BgYellow
	BgBlue
	BgMagenta
	BgCyan
	BgWhite
)
const (
	BgHiBlack Attribute = iota + 100
	BgHiRed
	BgHiGreen
	BgHiYellow
	BgHiBlue
	BgHiMagenta
	BgHiCyan
	BgHiWhite
)

type BoolContain

type BoolContain interface {
	SetBool(string, bool)
	ToBool(string) bool
}

type Cleaner

type Cleaner interface {
	SetCleanup(ExitStatus, ...Cleanup)
	RunCleanup(ExitStatus, context.Context) int
}

An interface for post-command actions.

type Cleanup

type Cleanup func(context.Context)

A cleanup function taking a context.Context only.

type Command

type Command interface {
	Group() string
	SetGroup(string)
	Tag() string
	Priority() int
	Escapes() bool
	Use(io.Writer)
	Execute(context.Context, []string) (context.Context, ExitStatus)
	Flagger
}

An interface for encapsulating a command.

func NewCommand

func NewCommand(group, tag, use string,
	priority int,
	escapes bool,
	cfn CommandFunc,
	fs *FlagSet) Command

Returns a new Command provided group, tag, use strings, priority integer a boolean indicating escape (stop processing command for other commands after this command is found, passing the params to the current command instead of going to another command), A CommandFunc to process the command, and a corresponding FlagSet for the Command).

type CommandFunc

type CommandFunc func(context.Context, []string) (context.Context, ExitStatus)

A function taking context.Context, and a string slice, returns context.Context and an ExitStatus.

type Commander

type Commander interface {
	Grouper
	GetCommand(...string) []Command
	SetCommand(...Command) Flipper
}

An interface for grouping nad managing commands for a Flip instance.

type ErrorHandling

type ErrorHandling int

An integer type representing method for handling errors.

const (
	ContinueOnError ErrorHandling = iota // continue on error
	ExitOnError                          // exit on error
	PanicOnError                         // panic on error
)

type Executer

type Executer interface {
	Execute(context.Context, []string) int
}

An interface for command execution.

type ExitStatus

type ExitStatus int

An integer type useful for marking results of commands.

const (
	ExitNo         ExitStatus = 999  // continue processing commands
	ExitSuccess    ExitStatus = 0    // return 0
	ExitFailure    ExitStatus = -1   // return -1
	ExitUsageError ExitStatus = -2   // return -2
	ExitAny        ExitStatus = -666 // status for cleaning function setup, never return
)

type Flag

type Flag struct {
	Name     string // name as it appears on command line
	Message  string // help message
	Value    Value  // value as set
	DefValue string // default value (as text); for usage message
}

A type representing one command line flag

type FlagSet

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

A type for handling any number of flags and fulfilling the Flagger interface.

func NewFlagSet

func NewFlagSet(name string, errorHandling ErrorHandling) *FlagSet

Creates a new *FlagSet with the string name and the provided error handling.

func (*FlagSet) Arg

func (f *FlagSet) Arg(i int) string

func (*FlagSet) Args

func (f *FlagSet) Args() []string

func (*FlagSet) Bool

func (f *FlagSet) Bool(name string, value bool, usage string) *bool

func (*FlagSet) BoolContain

func (f *FlagSet) BoolContain(d BoolContain, name, key, usage string) BoolContain

func (*FlagSet) BoolContainVar

func (f *FlagSet) BoolContainVar(d BoolContain, name, key string, value bool, usage string)

func (*FlagSet) BoolVar

func (f *FlagSet) BoolVar(p *bool, name string, value bool, usage string)

func (*FlagSet) Duration

func (f *FlagSet) Duration(name string, value time.Duration, usage string) *time.Duration

func (*FlagSet) DurationContain

func (f *FlagSet) DurationContain(d StringContain, name, key, usage string) StringContain

func (*FlagSet) DurationContainVar

func (f *FlagSet) DurationContainVar(d StringContain, name, key, value, usage string)

func (*FlagSet) DurationVar

func (f *FlagSet) DurationVar(p *time.Duration, name string, value time.Duration, usage string)

func (*FlagSet) Float64

func (f *FlagSet) Float64(name string, value float64, usage string) *float64

func (*FlagSet) Float64Contain

func (f *FlagSet) Float64Contain(d Float64Contain, name, key, usage string) Float64Contain

func (*FlagSet) Float64ContainVar

func (f *FlagSet) Float64ContainVar(d Float64Contain, name, key string, value float64, usage string)

func (*FlagSet) Float64Var

func (f *FlagSet) Float64Var(p *float64, name string, value float64, usage string)

func (*FlagSet) Int

func (f *FlagSet) Int(name string, value int, usage string) *int

func (*FlagSet) Int64

func (f *FlagSet) Int64(name string, value int64, usage string) *int64

func (*FlagSet) Int64Contain

func (f *FlagSet) Int64Contain(d Int64Contain, name, key, usage string) Int64Contain

func (*FlagSet) Int64ContainVar

func (f *FlagSet) Int64ContainVar(d Int64Contain, name, key string, value int64, usage string)

func (*FlagSet) Int64Var

func (f *FlagSet) Int64Var(p *int64, name string, value int64, usage string)

func (*FlagSet) IntContain

func (f *FlagSet) IntContain(d IntContain, name, key, usage string) IntContain

func (*FlagSet) IntContainVar

func (f *FlagSet) IntContainVar(d IntContain, name, key string, value int, usage string)

func (*FlagSet) IntVar

func (f *FlagSet) IntVar(p *int, name string, value int, usage string)

func (*FlagSet) Lookup

func (f *FlagSet) Lookup(name string) *Flag

Return a *Flag by the provided name, or nil if nothing is found.

func (*FlagSet) NArg

func (f *FlagSet) NArg() int

func (*FlagSet) NFlag

func (f *FlagSet) NFlag() int

func (*FlagSet) Out

func (f *FlagSet) Out() io.Writer

Returns an io.Writer from the *FlagSet.

func (*FlagSet) Parse

func (f *FlagSet) Parse(arguments []string) error

*FlagSet function satisfying the Parser interface Parse function.

func (*FlagSet) Parsed

func (f *FlagSet) Parsed() bool

*FlagSet function satisfying the Parser interface Parsed function.

func (*FlagSet) RegexContainVar

func (f *FlagSet) RegexContainVar(d StringContain, name, key, usage string, xfn RgxContainBridgeFunc, rawRegexps ...string) StringContain

A contain backed flag processing a regular expression

func (*FlagSet) RegexVar

func (f *FlagSet) RegexVar(name, usage string, xfn RgxBridgeFunc, rawRegexps ...string)

A flag processing a regular expression

func (*FlagSet) Set

func (f *FlagSet) Set(name, value string) error

Sets a flag by string name and value, returning an error.

func (*FlagSet) SetOut

func (f *FlagSet) SetOut(output io.Writer)

Sets the provided io.Writer to the *FlagSet.

func (*FlagSet) String

func (f *FlagSet) String(name string, value string, usage string) *string

func (*FlagSet) StringContain

func (f *FlagSet) StringContain(d StringContain, name, key, usage string) StringContain

func (*FlagSet) StringContainVar

func (f *FlagSet) StringContainVar(d StringContain, name, key, value, usage string)

func (*FlagSet) StringVar

func (f *FlagSet) StringVar(p *string, name string, value string, usage string)

func (*FlagSet) Uint

func (f *FlagSet) Uint(name string, value uint, usage string) *uint

func (*FlagSet) Uint64

func (f *FlagSet) Uint64(name string, value uint64, usage string) *uint64

func (*FlagSet) Uint64Contain

func (f *FlagSet) Uint64Contain(d Uint64Contain, name, key, usage string) Uint64Contain

func (*FlagSet) Uint64ContainVar

func (f *FlagSet) Uint64ContainVar(d Uint64Contain, name, key string, value uint64, usage string)

func (*FlagSet) Uint64Var

func (f *FlagSet) Uint64Var(p *uint64, name string, value uint64, usage string)

func (*FlagSet) UintContain

func (f *FlagSet) UintContain(d UintContain, name, key, usage string) UintContain

func (*FlagSet) UintContainVar

func (f *FlagSet) UintContainVar(d UintContain, name, key string, value uint, usage string)

func (*FlagSet) UintVar

func (f *FlagSet) UintVar(p *uint, name string, value uint, usage string)

func (*FlagSet) Usage

func (f *FlagSet) Usage(o io.Writer)

func (*FlagSet) Var

func (f *FlagSet) Var(value Value, name string, usage string)

Sets a Value, name string & usage string as a *Flag to be used by the *FlagSet This will panic for duplicate and/or previously defined Flags.

func (*FlagSet) Visit

func (f *FlagSet) Visit(fn func(*Flag))

A *FlagSet Visit function satisfying the Visiter interface.

func (*FlagSet) VisitAll

func (f *FlagSet) VisitAll(fn func(*Flag))

A *FlagSet VisitAll function satisfying the Visiter interface.

type Flagger

type Flagger interface {
	GetterSetter
	Parser
	Stater
	Visiter
	Writer
	Wuser
}

An interface encapsulating behavior for sets of flags.

type Flip

type Flip struct {
	Commander
	Instructer
	Executer
	Cleaner
}

A struct as the package default flag line processor, implementing Flipper.

func New

func New(name string) *Flip

Return a new package default Flip corresponding to the provided string name.

func NewFlip

func NewFlip(fns ...FlipConfig) *Flip

func (*Flip) AddBuiltIn

func (f *Flip) AddBuiltIn(nc string, args ...string) Flipper

Adds a builtin command by string name and string argument. Currently, commands added by this method are: - help (takes no other arguments) - version (followed by package, tag, version, and hash information strings, in that order)

type FlipConfig

type FlipConfig func(*Flip)

type Flipper

type Flipper interface {
	Adder
	Commander
	Instructer
	Executer
	Cleaner
}

Flipper is the flag line processor interface.

type Float64Contain

type Float64Contain interface {
	SetFloat64(string, float64)
	ToFloat64(string) float64
}

type GetterSetter

type GetterSetter interface {
	Lookup(string) *Flag
	Set(string, string) error
	Var(Value, string, string)
}

An interface for gettign & setting flags.

type Group

type Group struct {
	Name     string
	Priority int

	Commands []Command
	// contains filtered or unexported fields
}

func NewGroup

func NewGroup(name string, priority int, cs ...Command) *Group

Returns a new group provided the string name, priority integer, and any number of Command.

func (Group) Len

func (g Group) Len() int

group Len function for sort.Sort

func (Group) Less

func (g Group) Less(i, j int) bool

group Less function for sort.Sort

func (*Group) SortBy

func (g *Group) SortBy(s string)

Set the groups sorting parameter. "alpha" indicating alphabetic sorting is the only currently available outside of the default sort by priority.

func (Group) Swap

func (g Group) Swap(i, j int)

group Swap function for sort.Sort

func (*Group) Use

func (g *Group) Use(o io.Writer)

Writes the entire group usage to the provided io.Writer.

type Grouper

type Grouper interface {
	Groups() *Groups
	GetGroup(string) *Group
	SetGroup(string, int, ...Command) Flipper
}

An interface for grouping commands.

type Groups

type Groups struct {
	SortBy string
	Has    []*Group
}

func (Groups) Len

func (g Groups) Len() int

groups Len function for sort.Sort

func (Groups) Less

func (g Groups) Less(i, j int) bool

groups Less function for sort.Sort

func (Groups) Swap

func (g Groups) Swap(i, j int)

groups Swap function for sort.Sort

type Instructer

type Instructer interface {
	SwapInstructer(Instructer)
	Instruction(context.Context)
	SubsetInstruction(c ...Command) func(context.Context)
	Writer
}

An interface for providing instruction i.e. writes usage strings.

type Int64Contain

type Int64Contain interface {
	SetInt64(string, int64)
	ToInt64(string) int64
}

type IntContain

type IntContain interface {
	SetInt(string, int)
	ToInt(string) int
}

type Parser

type Parser interface {
	Parse([]string) error
	Parsed() bool
}

An interface handling flag parsing from a string slice, and returning details of parsing status.

type RgxBridgeFunc

type RgxBridgeFunc func(string, ...*regexp.Regexp) error

type RgxContainBridgeFunc

type RgxContainBridgeFunc func(string, StringContain, ...*regexp.Regexp) error

type Stater

type Stater interface {
	NFlag() int
	NArg() int
	Arg(int) string
	Args() []string
}

type StringContain

type StringContain interface {
	SetString(string, string)
	ToString(string) string
}

type Uint64Contain

type Uint64Contain interface {
	SetUint64(string, uint64)
	ToUint64(string) uint64
}

type UintContain

type UintContain interface {
	SetUint(string, uint)
	ToUint(string) uint
}

type Value

type Value interface {
	String() string
	Set(string) error
	Get() interface{}
}

A package level interface for abstracting flag values

type Visiter

type Visiter interface {
	Visit(func(*Flag))
	VisitAll(func(*Flag))
}

An interface to manage sending a function to all flags.

type Writer

type Writer interface {
	Out() io.Writer
	SetOut(io.Writer)
}

A package level writer interface.

type Wuser

type Wuser interface {
	Usage(io.Writer)
}

An interface calling usage strings of a flagset.

Jump to

Keyboard shortcuts

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