bite

package module
v0.0.0-...-f88b399 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2020 License: Apache-2.0 Imports: 22 Imported by: 0

README

Bite

A toolbox for cobra-based command line applications.

build status report card

Installation

The only requirement is the Go Programming Language, at least version 1.10.

$ go get -u github.com/lensesio/bite

Table of Contents

Work in progress...

Versioning

Current: v0.0.1

Read more about Semantic Versioning 2.0.0

License

Distributed under Apache Version 2.0 License, click here for more details.

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

Examples

Constants

This section is empty.

Variables

View Source
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 AllowEmptyFlag(err error) error

func Apply

func Apply(cmd *cobra.Command, runners ...CobraRunner)

func Build

func Build(app *Application) *cobra.Command

func CanBeSilent

func CanBeSilent(cmd *cobra.Command) *cobra.Command

CanBeSilent registeres the `--silent` flag to the "cmd" command.

func CanPrintJSON

func CanPrintJSON(cmd *cobra.Command)

func CheckRequiredFlags

func CheckRequiredFlags(cmd *cobra.Command, nameValuePairs FlagPair) (err error)

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

func CountRegisteredFlags(set *pflag.FlagSet) (n int)

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

func ExecuteWithSpinner(cmd *cobra.Command) error

ExecuteWithSpinner will make the spinner visible until first output from a command.

func ExpectsFeedback

func ExpectsFeedback(cmd *cobra.Command) bool

ExpectsFeedback returns true if the "cmd" command's `--silent` flag is registered and it's true, or the `--output` is table.

func FindCommand

func FindCommand(applicationName string, args []string) (*cobra.Command, []string)

func FriendlyError

func FriendlyError(cmd *cobra.Command, code int, format string, args ...interface{})

func GetCommand

func GetCommand(applicationName string, commandName string) *cobra.Command

func GetJSONPrettyFlag

func GetJSONPrettyFlag(cmd *cobra.Command) bool

func GetJSONQueryFlag

func GetJSONQueryFlag(cmd *cobra.Command) string

func GetOutPutFlag

func GetOutPutFlag(cmd *cobra.Command) string

func GetOutPutFlagFrom

func GetOutPutFlagFrom(set *pflag.FlagSet) string

func GetOutPutFlagKey

func GetOutPutFlagKey() string

func GetSilentFlag

func GetSilentFlag(cmd *cobra.Command) bool

GetSilentFlag returns the value(true/false) of the `--silent` flag, however if not found it returns false too.

func HasFlag

func HasFlag(cmd *cobra.Command, flagName string) (found bool)

HasFlag returns true if "flagName" can be found in the "cmd" cobra or its parents, otherwise false.

func HasSilentFlag

func HasSilentFlag(cmd *cobra.Command) bool

HasSilentFlag returns true if the "cmd" command has registered the `--silent` flag.

func LoadFile

func LoadFile(cmd *cobra.Command, path string, outPtr interface{}) error

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 NewFlagSet

func NewFlagSet(name string, register func(flags *pflag.FlagSet)) *pflag.FlagSet

func OutlineIntResults

func OutlineIntResults(cmd *cobra.Command, key string, entries []int) (items []interface{})

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

func OutlineStringResults(cmd *cobra.Command, key string, entries []string) (items []interface{})

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

func PrintInfo(cmd *cobra.Command, format string, a ...interface{}) error

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 PrintJSON

func PrintJSON(cmd *cobra.Command, v interface{}) error

func PrintObject

func PrintObject(cmd *cobra.Command, v interface{}, tableOnlyFilters ...interface{}) error

func ReadInPipe

func ReadInPipe() (bool, []byte, error)

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 RegisterOutPutFlag(cmd *cobra.Command, ptr *string)

func RegisterOutPutFlagTo

func RegisterOutPutFlagTo(set *pflag.FlagSet, ptr *string)

func TryReadFile

func TryReadFile(flagValue string, outPtr interface{}) (err error)

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

func TryReadFileContents(flagValue string) ([]byte, error)

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.

func WriteJSON

func WriteJSON(w io.Writer, v interface{}, pretty bool, jmespathQuery string) error

func WriteYAML

func WriteYAML(w io.Writer, v interface{}) error

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

func (*Application) Run

func (app *Application) Run(output io.Writer, args []string) error

func (*Application) Write

func (app *Application) Write(b []byte) (int, 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) Run

func (b *ApplicationBuilder) Run(w io.Writer, 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

type CobraRunner func(*cobra.Command, []string) error

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 Error

type Error interface {
	Code() int
}

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

func (FlagVar) Set

func (f FlagVar) Set(v string) error

func (FlagVar) String

func (f FlagVar) String() string

func (FlagVar) Type

func (f FlagVar) Type() string

type Flags

type Flags = pflag.FlagSet

type FriendlyErrors

type FriendlyErrors map[int]string

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 GetMemory

func GetMemory(cmd *cobra.Command) *Memory

func (*Memory) Clear

func (m *Memory) Clear() int

Clear removes all the stored elements and returns the total length of the elements removed, safe for concurrent access.

func (*Memory) Get

func (m *Memory) Get(key uint8) (value interface{}, found bool)

value, found := m.Get(MyKey), safe for concurrent access.

func (*Memory) GetAll

func (m *Memory) GetAll() map[uint8]interface{}

GetAll returns a clone of all the stored values, safe for concurrent access.

func (*Memory) Has

func (m *Memory) Has(key uint8) bool

m.Has(MyKey) == exists, safe for concurrent access.

func (*Memory) MustGet

func (m *Memory) MustGet(key uint8) interface{}

func (*Memory) Set

func (m *Memory) Set(key uint8, value interface{}) (replacement bool)

m.Set(MyKey, MyValue{}) == existed and replaced, safe for concurrent access.

func (*Memory) SetOnce

func (m *Memory) SetOnce(key uint8, value interface{}) bool

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 (m *Memory) SetOnceFunc(key uint8, receiverFunc interface{}) error

func (*Memory) Unset

func (m *Memory) Unset(key uint8) (removed bool)

m.Unset(MyKey) == removed, safe for concurrent access.

func (*Memory) Visit

func (m *Memory) Visit(key uint8, visitorFunc interface{}) bool

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.

type PathResolver

type PathResolver func(cmd *cobra.Command, args []string) string

type Transformer

type Transformer func([]byte, bool) ([]byte, error)

Jump to

Keyboard shortcuts

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