Documentation ¶
Overview ¶
Package bite is a toolbox for CLI cobra-based applications.
Example code:
package main var app = &bite.Application{ Name: "my-app", Version: "0.0.1", HelpTemplate: bite.HelpTemplate{ BuildTime: "Fr May 01 03:48:42 UTC 2018", BuildRevision: "a0d0c263ec4858fe3e527625b0236584c9f11479", ShowGoRuntimeVersion: true, // Template: customize template using any custom `fmt.Stringer`, }, Setup: func(cmd *cobra.Command, args []string) error { // setup here. return nil }, Shutdown: nil, } func init() { // app.AddCommand(aCobraCommand()) } func main() { if err := app.Run(os.Stdout, os.Args[1:]); err != nil { fmt.Fprintln(os.Stderr, err.Error()) os.Exit(1) } }
Github: https://github.com/lensesio/bite
Index ¶
- Variables
- func AllowEmptyFlag(err error) error
- func Apply(cmd *cobra.Command, runners ...CobraRunner)
- func Build(app *Application) *cobra.Command
- func CanBeSilent(cmd *cobra.Command) *cobra.Command
- func CanPrintJSON(cmd *cobra.Command)
- func CheckRequiredFlags(cmd *cobra.Command, nameValuePairs FlagPair) (err error)
- func CountRegisteredFlags(set *pflag.FlagSet) (n int)
- func ElseBind(fn func() error) func(*FileLoader)
- func ExecuteWithSpinner(cmd *cobra.Command) error
- func ExpectsFeedback(cmd *cobra.Command) bool
- func FindCommand(applicationName string, args []string) (*cobra.Command, []string)
- func FriendlyError(cmd *cobra.Command, code int, format string, args ...interface{})
- func GetCommand(applicationName string, commandName string) *cobra.Command
- func GetJSONPrettyFlag(cmd *cobra.Command) bool
- func GetJSONQueryFlag(cmd *cobra.Command) string
- func GetOutPutFlag(cmd *cobra.Command) string
- func GetOutPutFlagFrom(set *pflag.FlagSet) string
- func GetOutPutFlagKey() string
- func GetSilentFlag(cmd *cobra.Command) bool
- func HasFlag(cmd *cobra.Command, flagName string) (found bool)
- func HasSilentFlag(cmd *cobra.Command) bool
- func LoadFile(cmd *cobra.Command, path string, outPtr interface{}) error
- func MarshalJSON(v interface{}, pretty bool, transformers ...Transformer) ([]byte, error)
- func NewFlagSet(name string, register func(flags *pflag.FlagSet)) *pflag.FlagSet
- func OutlineIntResults(cmd *cobra.Command, key string, entries []int) (items []interface{})
- func OutlineStringResults(cmd *cobra.Command, key string, entries []string) (items []interface{})
- func Prepend(cmd *cobra.Command, runners ...CobraRunner)
- func PrintInfo(cmd *cobra.Command, format string, a ...interface{}) error
- func PrintJSON(cmd *cobra.Command, v interface{}) error
- func PrintObject(cmd *cobra.Command, v interface{}, tableOnlyFilters ...interface{}) error
- func ReadInPipe() (bool, []byte, error)
- func RegisterOutPutFlag(cmd *cobra.Command, ptr *string)
- func RegisterOutPutFlagTo(set *pflag.FlagSet, ptr *string)
- func TryReadFile(flagValue string, outPtr interface{}) (err error)
- func TryReadFileContents(flagValue string) ([]byte, error)
- func WriteJSON(w io.Writer, v interface{}, pretty bool, jmespathQuery string) error
- func WriteYAML(w io.Writer, v interface{}) error
- type Application
- func (app *Application) AddCommand(cmd *cobra.Command)
- func (app *Application) ClearPrintCache()
- func (app *Application) FindCommand(args []string) (*cobra.Command, []string)
- func (app *Application) GetCommand(commandName string) *cobra.Command
- func (app *Application) Print(format string, args ...interface{}) error
- func (app *Application) PrintInfo(format string, args ...interface{}) error
- func (app *Application) PrintObject(v interface{}) error
- func (app *Application) Run(output io.Writer, args []string) error
- func (app *Application) Write(b []byte) (int, error)
- type ApplicationBuilder
- func (b *ApplicationBuilder) Description(description string) *ApplicationBuilder
- func (b *ApplicationBuilder) Flags(fn func(*Flags)) *ApplicationBuilder
- func (b *ApplicationBuilder) Get() *Application
- func (b *ApplicationBuilder) GetFlags() *Flags
- func (b *ApplicationBuilder) Parse(args ...string) error
- func (b *ApplicationBuilder) Run(w io.Writer, args []string) error
- func (b *ApplicationBuilder) Setup(setupFunc CobraRunner) *ApplicationBuilder
- func (b *ApplicationBuilder) Version(version string) *ApplicationBuilder
- type CobraRunner
- type Error
- type FileLoader
- type FlagPair
- type FlagVar
- type Flags
- type FriendlyErrors
- type HelpTemplate
- type Memory
- func (m *Memory) Clear() int
- func (m *Memory) Get(key uint8) (value interface{}, found bool)
- func (m *Memory) GetAll() map[uint8]interface{}
- func (m *Memory) Has(key uint8) bool
- func (m *Memory) MustGet(key uint8) interface{}
- func (m *Memory) Set(key uint8, value interface{}) (replacement bool)
- func (m *Memory) SetOnce(key uint8, value interface{}) bool
- func (m *Memory) SetOnceFunc(key uint8, receiverFunc interface{}) error
- func (m *Memory) Unset(key uint8) (removed bool)
- func (m *Memory) Visit(key uint8, visitorFunc interface{}) bool
- type PathResolver
- type Transformer
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var JSONFlagSet = NewFlagSet("flagset.json", func(flags *pflag.FlagSet) { flags.Bool(jsonPrettyFlagKey, false, "Enable the pretty format for JSON output of commands (default false).") flags.StringP(jsonQueryFlagKey, string(jsonQueryFlagKey[0]), "", "Jmespath query expression. This allows for querying the JSON output of commands") })
Functions ¶
func AllowEmptyFlag ¶
func Apply ¶
func Apply(cmd *cobra.Command, runners ...CobraRunner)
func Build ¶
func Build(app *Application) *cobra.Command
func CanBeSilent ¶
CanBeSilent registeres the `--silent` flag to the "cmd" command.
func CanPrintJSON ¶
func CheckRequiredFlags ¶
CheckRequiredFlags function can be used to manually check for required flags, when the command does not specify a required flag (mostly because of file loading feature).
func CountRegisteredFlags ¶
CountRegisteredFlags returns the length of the registered flags (except help), some of them may not be used "now" at all.
func ElseBind ¶
func ElseBind(fn func() error) func(*FileLoader)
func ExecuteWithSpinner ¶
ExecuteWithSpinner will make the spinner visible until first output from a command.
func ExpectsFeedback ¶
ExpectsFeedback returns true if the "cmd" command's `--silent` flag is registered and it's true, or the `--output` is table.
func FindCommand ¶
func FriendlyError ¶
func GetJSONPrettyFlag ¶
func GetJSONQueryFlag ¶
func GetOutPutFlag ¶
func GetOutPutFlagFrom ¶
func GetOutPutFlagKey ¶
func GetOutPutFlagKey() string
func GetSilentFlag ¶
GetSilentFlag returns the value(true/false) of the `--silent` flag, however if not found it returns false too.
func HasFlag ¶
HasFlag returns true if "flagName" can be found in the "cmd" cobra or its parents, otherwise false.
func HasSilentFlag ¶
HasSilentFlag returns true if the "cmd" command has registered the `--silent` flag.
func LoadFile ¶
LoadFile same as `tryReadFile` but it should be used for operations that we read the whole object from file, not just a sub property of it like `--config ./configs.json`.
It just prints a message to the user that we load from file, so we ignore the flags.
func MarshalJSON ¶
func MarshalJSON(v interface{}, pretty bool, transformers ...Transformer) ([]byte, error)
func OutlineIntResults ¶
OutlineIntResults accepts a key, i.e "version" and entries i.e [1, 2, 3] and will convert it to a slice of [{"version":3},"version":1, "version":2}] to be able to be printed via `printJSON`.
func OutlineStringResults ¶
OutlineStringResults accepts a key, i.e "name" and entries i.e ["schema1", "schema2", "schema3"] and will convert it to a slice of [{"name":"schema1"},"name":"schema2", "name":"schema3"}] to be able to be printed via `printJSON`.
func Prepend ¶
func Prepend(cmd *cobra.Command, runners ...CobraRunner)
func PrintInfo ¶
PrintInfo prints an info message to the command's standard output. If the `--silent“ flag is a REGISTERED flag for that command, then it will check if it's false or not set in order to print, otherwise it will check the `--machine-friendly` flag, if true not print.
Useful when you want to have --machine-friendly on but want to print an important info message to the user as well but user can also disable that message via a second flag, the --silent one.
func PrintObject ¶
func ReadInPipe ¶
ReadInPipe reads from the input pipe.
First argument returns true if in pipe has any data to read from, if false then the caller can continue by requiring a flag. Second argument returns the data of the io pipe, and third one is the error cames from .Stat() or from the ReadAll() of the in pipe.
func RegisterOutPutFlag ¶
func RegisterOutPutFlagTo ¶
func TryReadFile ¶
TryReadFile will try to check if a flag value begins with 'flagFilePrefix' if so, then it will json parse its contents, decode them and set to the `outPtr`, otherwise it will decode the flagvalue using json unmarshaler and send the result to the `outPtr`.
func TryReadFileContents ¶
TryReadFileContents will try to check if a flag value begins with 'flagFilePrefix' if so then it returns the contents of the filename given from the flagValue after the 'flagFilePrefix' character. Otherwise returns the flagValue as raw slice of bytes.
Types ¶
type Application ¶
type Application struct { Name string Version string Description string Long string HelpTemplate fmt.Stringer // ShowSpinner if true(default is false) then // it waits via "visual" spinning before each command's job done. ShowSpinner bool DisableOutputFormatController bool OutPut *string PersistentFlags func(*pflag.FlagSet) Setup CobraRunner Shutdown CobraRunner FriendlyErrors FriendlyErrors Memory *Memory TableHeaderBgColor, TableHeaderFgColor string // see `whichColor(string, int) int` CobraCommand *cobra.Command // the root command, after "Build" state. // contains filtered or unexported fields }
func Get ¶
func Get(cmd *cobra.Command) *Application
func GetByName ¶
func GetByName(applicationName string) *Application
func (*Application) AddCommand ¶
func (app *Application) AddCommand(cmd *cobra.Command)
func (*Application) ClearPrintCache ¶
func (app *Application) ClearPrintCache()
func (*Application) FindCommand ¶
func (app *Application) FindCommand(args []string) (*cobra.Command, []string)
func (*Application) GetCommand ¶
func (app *Application) GetCommand(commandName string) *cobra.Command
func (*Application) Print ¶
func (app *Application) Print(format string, args ...interface{}) error
func (*Application) PrintInfo ¶
func (app *Application) PrintInfo(format string, args ...interface{}) error
func (*Application) PrintObject ¶
func (app *Application) PrintObject(v interface{}) error
type ApplicationBuilder ¶
type ApplicationBuilder struct {
// contains filtered or unexported fields
}
Example ¶
package main import ( "fmt" "os" "github.com/lensesio/bite" ) func main() { var name string program := bite. Name("bite-simple-example"). Flags(func(flags *bite.Flags) { // Register a flag. flags.Bool("silent", false, "--silent") // Register and bind a flag to a local variable. flags.StringVar(&name, "name", "", "--name=") }) // Parse using custom arguments or system's, i.e `os.Args[1:]...`. if err := program.Parse("--silent=false", "--name=Joe"); err != nil { fmt.Fprintln(os.Stderr, err.Error()) os.Exit(-1) } // Get a flag's value manually. silent, _ := program.GetFlags().GetBool("silent") if !silent { // Use the binded local variable "name". fmt.Printf("Hello %s", name) } }
Output: Hello Joe
func Name ¶
func Name(name string) *ApplicationBuilder
func (*ApplicationBuilder) Description ¶
func (b *ApplicationBuilder) Description(description string) *ApplicationBuilder
func (*ApplicationBuilder) Flags ¶
func (b *ApplicationBuilder) Flags(fn func(*Flags)) *ApplicationBuilder
func (*ApplicationBuilder) Get ¶
func (b *ApplicationBuilder) Get() *Application
func (*ApplicationBuilder) GetFlags ¶
func (b *ApplicationBuilder) GetFlags() *Flags
func (*ApplicationBuilder) Parse ¶
func (b *ApplicationBuilder) Parse(args ...string) error
func (*ApplicationBuilder) Setup ¶
func (b *ApplicationBuilder) Setup(setupFunc CobraRunner) *ApplicationBuilder
func (*ApplicationBuilder) Version ¶
func (b *ApplicationBuilder) Version(version string) *ApplicationBuilder
type CobraRunner ¶
func ArgsRange ¶
func ArgsRange(min int, max int) CobraRunner
func FileBind ¶
func FileBind(outPtr interface{}, customizers ...func(*FileLoader)) CobraRunner
func If ¶
func If(condStatic bool, runners ...CobraRunner) CobraRunner
func Join ¶
func Join(runners ...CobraRunner) CobraRunner
func RequireFlags ¶
func RequireFlags(nameValuePairsFunc func() FlagPair) CobraRunner
type FileLoader ¶
type FileLoader struct {
// contains filtered or unexported fields
}
func ShouldTryLoadFile ¶
func ShouldTryLoadFile(cmd *cobra.Command, outPtr interface{}) *FileLoader
func (*FileLoader) Else ¶
func (fl *FileLoader) Else(fn func() error) *FileLoader
func (*FileLoader) WithPathResolve ¶
func (fl *FileLoader) WithPathResolve(fn PathResolver) *FileLoader
type FlagPair ¶
type FlagPair map[string]interface{}
FlagPair is just a map[string]interface{}, see `CheckRequiredFlags` for more.
type FlagVar ¶
type FlagVar struct {
// contains filtered or unexported fields
}
Supported custom types underline are: strings, ints and booleans only.
func NewFlagVar ¶
func NewFlagVar(v interface{}) *FlagVar
type FriendlyErrors ¶
type HelpTemplate ¶
type HelpTemplate struct { Name string BuildTime string BuildRevision string BuildVersion string ShowGoRuntimeVersion bool Template fmt.Stringer }
func (HelpTemplate) String ¶
func (h HelpTemplate) String() string
type Memory ¶
type Memory struct {
// contains filtered or unexported fields
}
Memory describes a temporary storage for each application, useful to store different kind of custom values.
func (*Memory) Clear ¶
Clear removes all the stored elements and returns the total length of the elements removed, safe for concurrent access.
func (*Memory) GetAll ¶
GetAll returns a clone of all the stored values, safe for concurrent access.
func (*Memory) SetOnce ¶
SetOnce will store a value based on its key if it's not there already, do not confuse its action with immutability.
func (*Memory) SetOnceFunc ¶
func (*Memory) Visit ¶
m.Visit(MyKey, func(value MyValue) { do something with the value if found }) == visitor function was compatible and executed successfully. Note that it doesn't lock until the function ends, this is because the function may access other memory's function which locks and that will result on a deadlock.