Documentation ¶
Overview ¶
Console Line Input Framework for rapid development of small or large scale CLI applications.
See the Github page for a full documentation with examples and patterns (https://github.com/ukautz/clif).
clif's design was influenced by Symfony Console (http://symfony.com/doc/current/components/console/introduction.html).
Determine terminal width which can come in handy for rendering tables and somesuch.
DISCLAIMER: The code contents of all term*.go files is PROUDLY STOLEN FROM https://github.com/cheggaaa/pb which sadly does not export this nicely written functions and to whom all credits should go. Only slight modifications.
Index ¶
- Constants
- Variables
- func InputAny(s string) error
- func InputEmptyOk(s string) error
- func IsCallError(err error) bool
- func IsControlCharStart(c byte) bool
- func IsFloat(name, value string) (string, error)
- func IsInt(name, value string) (string, error)
- func RenderFixedSizeDuration(dur time.Duration) string
- func SplitFormattedString(str string) []string
- func StringLength(str string) int
- func TermWidth() (int, error)
- func Wrap(s string, limit uint) string
- type Argument
- func (this *Argument) Assign(val string) error
- func (this *Argument) Bool() bool
- func (this *Argument) Bools() []bool
- func (this *Argument) Count() int
- func (this *Argument) Float() float64
- func (this *Argument) Floats() []float64
- func (this *Argument) Int() int
- func (this *Argument) Ints() []int
- func (this *Argument) Json() (map[string]interface{}, error)
- func (this *Argument) Jsons() ([]map[string]interface{}, error)
- func (this *Argument) Provided() bool
- func (this *Argument) SetDefault(v string) *Argument
- func (this *Argument) SetDescription(v string) *Argument
- func (this *Argument) SetEnv(v string) *Argument
- func (this *Argument) SetParse(v ParseMethod) *Argument
- func (this *Argument) SetRegex(r *regexp.Regexp) *Argument
- func (this *Argument) SetUsage(v string) *Argument
- func (this *Argument) String() string
- func (this *Argument) Strings() []string
- func (this *Argument) Time(format ...string) (*time.Time, error)
- func (this *Argument) Times(format ...string) ([]time.Time, error)
- type CallError
- type CallMethod
- type Cli
- func (this *Cli) Add(cmd ...*Command) *Cli
- func (this *Cli) AddDefaultOptions(opts ...*Option) *Cli
- func (this *Cli) Call(c *Command) ([]reflect.Value, error)
- func (this *Cli) Herald(cmd ...HeraldCallback) *Cli
- func (this *Cli) Named(n string) interface{}
- func (this *Cli) New(name, usage string, call CallMethod) *Cli
- func (this *Cli) NewDefaultOption(name, alias, usage, _default string, required, multiple bool) *Cli
- func (this *Cli) Output() Output
- func (this *Cli) Register(v interface{}) *Cli
- func (this *Cli) RegisterAs(n string, v interface{}) *Cli
- func (this *Cli) RegisterNamed(n string, v interface{}) *Cli
- func (this *Cli) Run()
- func (this *Cli) RunWith(args []string)
- func (this *Cli) SeparateArgs(args []string) (string, []string)
- func (this *Cli) SetDefaultCommand(v string) *Cli
- func (this *Cli) SetDescription(v string) *Cli
- func (this *Cli) SetInput(in Input) *Cli
- func (this *Cli) SetOnInterrupt(cb func() error) *Cli
- func (this *Cli) SetOutput(out Output) *Cli
- func (this *Cli) SetPreCall(cb func(c *Command) error) *Cli
- type Command
- func (this *Command) AddArgument(v *Argument) *Command
- func (this *Command) AddOption(v *Option) *Command
- func (this *Command) Argument(name string) *Argument
- func (this *Command) Input() map[string][]string
- func (this *Command) NewArgument(name, usage, _default string, required, multiple bool) *Command
- func (this *Command) NewFlag(name, alias, usage string, multiple bool) *Command
- func (this *Command) NewOption(name, alias, usage, _default string, required, multiple bool) *Command
- func (this *Command) Option(name string) *Option
- func (this *Command) Parse(args []string) error
- func (this *Command) SetCli(c *Cli) *Command
- func (this *Command) SetDescription(desc string) *Command
- func (this *Command) SetPostCall(call CallMethod) *Command
- func (this *Command) SetPreCall(call CallMethod) *Command
- type CommandsSort
- type DefaultFormatter
- type DefaultInput
- type DefaultOutput
- func (this *DefaultOutput) Escape(msg string) string
- func (this *DefaultOutput) Printf(msg string, args ...interface{})
- func (this *DefaultOutput) ProgressBars() ProgressBarPool
- func (this *DefaultOutput) SetFormatter(f Formatter) Output
- func (this *DefaultOutput) Sprintf(msg string, args ...interface{}) string
- func (this *DefaultOutput) Table(headers []string, style ...*TableStyle) *Table
- func (this *DefaultOutput) Writer() io.Writer
- type Formatter
- type HeraldCallback
- type Input
- type NamedParameters
- type Option
- func (this *Option) Assign(val string) error
- func (this *Option) Bool() bool
- func (this *Option) Bools() []bool
- func (this *Option) Count() int
- func (this *Option) Float() float64
- func (this *Option) Floats() []float64
- func (this *Option) Int() int
- func (this *Option) Ints() []int
- func (this *Option) IsFlag() *Option
- func (this *Option) Json() (map[string]interface{}, error)
- func (this *Option) Jsons() ([]map[string]interface{}, error)
- func (this *Option) Provided() bool
- func (this *Option) SetDefault(v string) *Option
- func (this *Option) SetDescription(v string) *Option
- func (this *Option) SetEnv(v string) *Option
- func (this *Option) SetParse(v ParseMethod) *Option
- func (this *Option) SetRegex(r *regexp.Regexp) *Option
- func (this *Option) SetUsage(v string) *Option
- func (this *Option) String() string
- func (this *Option) Strings() []string
- func (this *Option) Time(format ...string) (*time.Time, error)
- func (this *Option) Times(format ...string) ([]time.Time, error)
- type Output
- type ParseMethod
- type ProgressBar
- type ProgressBarPool
- type ProgressBarSimple
- func (this *ProgressBarSimple) Done() bool
- func (this *ProgressBarSimple) Finish()
- func (this *ProgressBarSimple) Increase(amount int) error
- func (this *ProgressBarSimple) Increment() error
- func (this *ProgressBarSimple) Position() int
- func (this *ProgressBarSimple) Render() string
- func (this *ProgressBarSimple) RenderWidth() int
- func (this *ProgressBarSimple) Reset()
- func (this *ProgressBarSimple) Set(position int) error
- func (this *ProgressBarSimple) SetRenderWidth(v int) ProgressBar
- func (this *ProgressBarSimple) SetSize(v int) ProgressBar
- func (this *ProgressBarSimple) SetStyle(v *ProgressBarStyle) ProgressBar
- func (this *ProgressBarSimple) Style() *ProgressBarStyle
- type ProgressBarStyle
- type ReduceMethod
- type Registry
- func (this *Registry) Alias(alias string, v interface{})
- func (this *Registry) Get(s string) reflect.Value
- func (this *Registry) Has(s string) bool
- func (this *Registry) Names() []string
- func (this *Registry) Reduce(cb ReduceMethod) []interface{}
- func (this *Registry) ReduceAsync(cb ReduceMethod) chan interface{}
- func (this *Registry) Register(v interface{})
- type Table
- func (this *Table) AddRow(cols []string) error
- func (this *Table) AddRows(rows [][]string) error
- func (this *Table) Render(maxWidth ...int) string
- func (this *Table) Reset()
- func (this *Table) SetColumn(rowIdx, colIdx int, content string) error
- func (this *Table) SetHeaders(headers []string) error
- func (this *Table) SetRow(idx int, cols []string) error
- func (this *Table) SetStyle(style *TableStyle)
- type TableCol
- func (this *TableCol) Content(maxWidth ...int) string
- func (this *TableCol) ContentPrefixed(prefix string, maxWidth ...int) string
- func (this *TableCol) LineCount(maxWidth ...int) int
- func (this *TableCol) Render(maxWidth int) (content string, width, lineCount int)
- func (this *TableCol) SetContent(content string) *TableCol
- func (this *TableCol) SetRenderer(renderer func(string) string) *TableCol
- func (this *TableCol) SetRow(row *TableRow) *TableCol
- func (this *TableCol) Width(maxWidth ...int) int
- type TableRow
- func (this *TableRow) CalculateWidths(totalWidth int) (colSize []int)
- func (this *TableRow) Render(totalWidth int) (rendered []string, maxLineCount int)
- func (this *TableRow) RenderWithWidths(colWidths []int) (rendered []string, maxLineCount int)
- func (this *TableRow) SetCol(idx int, col *TableCol) error
- func (this *TableRow) SetRenderer(renderer func(string) string) *TableRow
- func (this *TableRow) SetTable(table *Table) *TableRow
- func (this *TableRow) Width(maxWidth ...int) int
- type TableStyle
- type WrapTrimMode
- type WrapWhitespaceMode
- type Wrapper
Constants ¶
const ( PROGRESS_BAR_ADDON_OFF progressBarAddon = iota PROGRESS_BAR_ADDON_PREPEND PROGRESS_BAR_ADDON_APPEND )
const ( TERM_TIOCGWINSZ = 0x5413 TERM_TIOCGWINSZ_OSX = 1074295912 TERM_DEFAULT_WIDTH = 78 )
const (
LINE_BREAK = "\n"
)
const (
PROGRESS_BAR_DEFAULT_REFRESH = time.Millisecond * 50
)
Variables ¶
var ( RenderAskQuestion = func(question string) string { return "<query>" + strings.TrimRight(question, " ") + "<reset> " } RenderInputRequiredError = fmt.Errorf("Input required") )
var ( DefaultOutputTableHeaderRenderer = func(out Output) func(string) string { return func(content string) string { return strings.Join(SplitFormattedString(out.Sprintf("<headline>%s<reset>", content)), "\n") } } DefaultOutputTableContentRenderer = func(out Output) func(string) string { return func(content string) string { from := strings.Replace(content, "\n", "<BR>", -1) from = rxControlCharacters.ReplaceAllString(from, "<CTRL>") return strings.Join(SplitFormattedString(out.Sprintf(content)), "\n") } } )
var ( // ProgressBarDefaultRenderElapsed ProgressBarDefaultRenderCount = func(pos, max int, bar ProgressBar) string { l := len(fmt.Sprintf("%d", max)) return fmt.Sprintf("%"+fmt.Sprintf("%d", l)+"d/%d", pos, max) } ProgressBarDefaultRenderElapsed = func(elapsed time.Duration, bar ProgressBar) string { return fmt.Sprintf("@%s", RenderFixedSizeDuration(elapsed)) } ProgressBarDefaultRenderEstimated = func(forecast time.Duration, bar ProgressBar) string { return fmt.Sprintf("~%s", RenderFixedSizeDuration(forecast)) } ProgressBarDefaultRenderPercentage = func(percent float32, bar ProgressBar) string { if percent > 99.99 { return " 100%" } else { return fmt.Sprintf("%4.1f%%", percent) } } ProgressBarDefaultRenderPrefix = func(count, elapsed, estimate, percentage string) string { out := []string{} for _, s := range []string{count, elapsed, estimate, percentage} { if s != "" { out = append(out, s) } } if len(out) == 0 { return "" } return strings.Join(out, " / ") + " " } ProgressBarDefaultRenderSuffix = func(count, elapsed, estimate, percentage string) string { out := []string{} for _, s := range []string{count, elapsed, estimate, percentage} { if s != "" { out = append(out, s) } } if len(out) == 0 { return "" } return " " + strings.Join(out, " / ") } // ProgressBarStyleAscii is an ASCII encoding based style for rendering the progress bar ProgressBarStyleAscii = &ProgressBarStyle{ Empty: '-', Progress: '=', Rightmost: '>', None: '-', LeftBorder: '[', RightBorder: ']', Percentage: PROGRESS_BAR_ADDON_APPEND, Elapsed: PROGRESS_BAR_ADDON_PREPEND, } // ProgressBarStyleUtf8 is an UTF-8 encoding based style for rendering the progress bar ProgressBarStyleUtf8 = &ProgressBarStyle{ Empty: ' ', Progress: '█', Rightmost: '▓', None: '░', LeftBorder: '▕', RightBorder: '▏', Percentage: PROGRESS_BAR_ADDON_APPEND, Elapsed: PROGRESS_BAR_ADDON_PREPEND, } )
var ( ClosedTableStyle = &TableStyle{ Bottom: "─", ContentRenderer: func(content string) string { return content }, CrossBottom: "┴", CrossInner: "┼", CrossLeft: "├", CrossRight: "┤", CrossTop: "┬", HeaderRenderer: func(content string) string { return fmt.Sprintf("\033[1;4m%s\033[0m", content) }, InnerHorizontal: "─", InnerVertical: "│", Left: "│", LeftBottom: "└", LeftTop: "┌", Prefix: " ", Right: "│", RightBottom: "┘", RightTop: "┐", Suffix: " ", Top: "─", } ClosedTableStyleLight = &TableStyle{ Bottom: "\033[38;5;234m─\033[0m", ContentRenderer: func(content string) string { return content }, CrossBottom: "\033[38;5;234m┴\033[0m", CrossInner: "\033[38;5;234m┼\033[0m", CrossLeft: "\033[38;5;234m├\033[0m", CrossRight: "\033[38;5;234m┤\033[0m", CrossTop: "\033[38;5;234m┬\033[0m", HeaderRenderer: func(content string) string { return fmt.Sprintf("\033[1;4m%s\033[0m", content) }, InnerHorizontal: "\033[38;5;234m─\033[0m", InnerVertical: "\033[38;5;234m│\033[0m", Left: "\033[38;5;234m│\033[0m", LeftBottom: "\033[38;5;234m└\033[0m", LeftTop: "\033[38;5;234m┌\033[0m", Prefix: " ", Right: "\033[38;5;234m│\033[0m", RightBottom: "\033[38;5;234m┘\033[0m", RightTop: "\033[38;5;234m┐\033[0m", Suffix: " ", Top: "\033[38;5;234m─\033[0m", } OpenTableStyle = &TableStyle{ Bottom: "", ContentRenderer: func(content string) string { return content }, CrossBottom: "┴", CrossInner: "┼", CrossLeft: "", CrossRight: "", CrossTop: "┬", HeaderRenderer: func(content string) string { return fmt.Sprintf("\033[1m%s\033[0m", content) }, InnerHorizontal: "─", InnerVertical: "│", Left: "", LeftBottom: "", LeftTop: "", Prefix: " ", Right: "", RightBottom: "", RightTop: "", Suffix: " ", Top: "", } OpenTableStyleLight = &TableStyle{ Bottom: "", ContentRenderer: func(content string) string { return content }, CrossBottom: "\033[38;5;234m┴\033[0m", CrossInner: "\033[38;5;234m┼\033[0m", CrossLeft: "", CrossRight: "", CrossTop: "\033[38;5;234m┬\033[0m", HeaderRenderer: func(content string) string { return fmt.Sprintf("\033[1m%s\033[0m", content) }, InnerHorizontal: "\033[38;5;234m─\033[0m", InnerVertical: "\033[38;5;234m│\033[0m", Left: "", LeftBottom: "", LeftTop: "", Prefix: " ", Right: "", RightBottom: "", RightTop: "", Suffix: " ", Top: "", } DefaultTableStyle *TableStyle )
var ( // TermWidthCall is the callback returning the terminal width TermWidthCall func() (int, error) // TermWidthCurrent contains the current terminal width from the last // call of `TerminalWidth()` (which is called in `init()`) TermWidthCurrent = TERM_DEFAULT_WIDTH )
var ConfirmNoRegex = regexp.MustCompile(`^(?i)no?$`)
ConfirmNoRegex is the regular expression used to check if the user replied negative
var ConfirmRejection = "<warn>Please respond with \"yes\" or \"no\"<reset>\n\n"
ConfirmRejection is the message replied to the user if she does not answer with "yes", "y", "no" or "n" (case insensitive)
var ConfirmYesRegex = regexp.MustCompile(`^(?i)y(es)?$`)
ConfirmYesRegex is the regular expression used to check if the user replied positive
var Dbg = func(msg string, args ...interface{}) { if v := os.Getenv("DEBUG_CLIF"); v != "1" { return } if dbgFh == nil { dbgFh, _ = os.OpenFile(filepath.Join(os.TempDir(), "debug.clif"), os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644) } dbgFh.Write([]byte(fmt.Sprintf("[%s] %s\n", time.Now(), fmt.Sprintf(msg, args...)))) }
var DebugStyles = map[string]string{
"error": "E:",
"warn": "W:",
"info": "I:",
"success": "S:",
"debug": "D:",
"headline": "H:",
"subline": "U:",
"important": "P:",
"query": "Q:",
"reset": "R:",
}
var DefaultFormatterEscape = func(msg string) string { return DefaultFormatterTokenRegex.ReplaceAllStringFunc(msg, func(token string) string { return `\` + token }) }
DefaultFormatterEscape is a callback to replace all tokens with escaped versions
var DefaultFormatterPost = func(msg string) string { return strings.Replace(msg, "~~~~#~~~~", "<", -1) }
DefaultFormatterPost is a post-callback, after DefaultFormatterTokenRegex is used
var DefaultFormatterPre = func(msg string) string { return strings.Replace(msg, `\<`, "~~~~#~~~~", -1) }
DefaultFormatterPre is a pre-callback, before DefaultFormatterTokenRegex is used
var DefaultFormatterTokenRegex = regexp.MustCompile(`(<[^>]+>)`)
DefaultFormatterTokenRegex is a regex to find all tokens, used by the DefaultFormatter
var DefaultHelpOption = &Option{ parameter: parameter{ Name: "help", Usage: "Display this help message", Description: "Display this help message", }, Alias: "h", Flag: true, }
DefaultHelpOption is the "--help" option, which is (per default) added to any command.
var DefaultOptions = []*Option{DefaultHelpOption}
DefaultOptions are prepended to any newly created command. Will be added immediately in the `NewCommand` call. See also `cli.NewDefaultOption()` and `cli.AddDefaultOptions()`.
var DefaultStyles = map[string]string{
"error": "\033[31;1m",
"warn": "\033[33m",
"info": "\033[34m",
"success": "\033[32m",
"debug": "\033[30;1m",
"headline": "\033[4;1m",
"subline": "\033[4m",
"important": "\033[47;30;1m",
"query": "\033[36m",
"reset": "\033[0m",
}
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" }
DescribeCli command implements the string rendering of a cli which help uses. Can be overwritten at users discretion.
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 usgInfo := []string{} if p.Multiple { short = short + " ..." usgInfo = append(usgInfo, `<debug>mult<reset>`) } if p.Required { usgInfo = append(usgInfo, `<important>req<reset>`) } else { short = fmt.Sprintf("[%s]", short) } if p.Env != "" { usgInfo = append(usgInfo, fmt.Sprintf(`env: <debug>%s<reset>`, p.Env)) } if p.Default != "" { usgInfo = append(usgInfo, fmt.Sprintf(`default: <debug>"%s"<reset>`, p.Default)) } if l := len(p.Name); l > argMax { argMax = l } usage = append(usage, short) if len(usgInfo) > 0 { usg += " (" + strings.Join(usgInfo, ", ") + ")" } 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 usgInfo := []string{} if p.Multiple { short = short + " ..." usgInfo = append(usgInfo, `<debug>mult<reset>`) } if !p.Required { short = "[" + short + "]" } else { usgInfo = append(usgInfo, `<important>req<reset>`) } if p.Env != "" { usgInfo = append(usgInfo, fmt.Sprintf(`env: <debug>%s<reset>`, p.Env)) } if p.Default != "" { usgInfo = append(usgInfo, fmt.Sprintf(`default: <debug>"%s"<reset>`, p.Default)) } if l := len(long); l > optMax { optMax = l } usage = append(usage, short) if len(usgInfo) > 0 { usg += " (" + strings.Join(usgInfo, ", ") + ")" } 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" }
DescribeCommand implements the string rendering of a command which help uses. Can be overwritten at users discretion.
var Die = func(msg string, args ...interface{}) { NewColorOutput(os.Stderr).Printf("<error>"+msg+"<reset>\n", args...) Exit(1) }
Die is the default function executed on die. It can be used as a shorthand via `clif.Die("foo %s", "bar")` and can be overwritten to change the failure exit handling CLI-wide.
var (
ErrHeadersNotSetYet = fmt.Errorf("Cannot add/set data when headers are not set")
)
var Exit = func(s int) { os.Exit(s) }
Exit is wrapper for os.Exit, so it can be overwritten for tests or edge use cases
var ( // PbOutOfBoundError is returned when increasing, adding or setting the position // with a value which is below 0 or beyond size of the progress bar PbOutOfBoundError = fmt.Errorf("Position is out of bounds") )
var RenderChooseOption = func(key, value string, size int) string { return fmt.Sprintf(" <query>%-"+fmt.Sprintf("%d", size+1)+"s<reset> %s\n", key+")", value) }
RenderChooseOption is the method used by default input `Choose()` method to to render a singular choice into a string. Can be overwritten at users discretion.
var RenderChooseQuery = func() string {
return "Choose: "
}
RenderChooseQuery is the method used by default input `Choose()` method to to render the query prompt choice (after the choices) into a string. Can be overwritten at users discretion.
var RenderChooseQuestion = func(question string) string {
return question + "\n"
}
RenderChooseQuestion is the method used by default input `Choose()` method to to render the question (displayed before listing the choices) into a string. Can be overwritten at users discretion.
var SunburnStyles = map[string]string{
"error": "\033[97;48;5;196;1m",
"warn": "\033[30;48;5;208;2m",
"info": "\033[38;5;142;2m",
"success": "\033[38;5;2;2m",
"debug": "\033[38;5;242;2m",
"headline": "\033[38;5;226;1m",
"subline": "\033[38;5;228;1m",
"important": "\033[38;5;15;2;4m",
"query": "\033[38;5;77m",
"reset": "\033[0m",
}
http://misc.flogisoft.com/bash/tip_colors_and_formatting#colors1
var ( TableColWrapper = func(limit int) *Wrapper { wrapper := NewWrapper(uint(limit)) wrapper.WhitespaceMode = WRAP_WHITESPACE_CONTRACT wrapper.TrimMode = WRAP_TRIM_RIGHT wrapper.BreakWords = true return wrapper } )
var WinterStyles = map[string]string{
"error": "\033[97;48;5;89;1m",
"warn": "\033[30;48;5;97;2m",
"info": "\033[38;5;69;2m",
"success": "\033[38;5;45;1m",
"debug": "\033[38;5;239;2m",
"headline": "\033[38;5;21;1m",
"subline": "\033[38;5;27;1m",
"important": "\033[38;5;15;2;4m",
"query": "\033[38;5;111m",
"reset": "\033[0m",
}
http://misc.flogisoft.com/bash/tip_colors_and_formatting#colors1
Functions ¶
func InputEmptyOk ¶
func IsCallError ¶
func IsControlCharStart ¶
IsControlCharStart returns bool whether character is "\033" aka "\e"
func RenderFixedSizeDuration ¶
func SplitFormattedString ¶
SplitFormattedString splits formatted string into multiple lines while making sure that control characters end at line end and possibly re-start at next line
func StringLength ¶
StringLength returns the length of an UTF8 string without any control characters
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 ordered after required arguments. Only one argument is allowed to contain multiple values and it needs to be the last one.
func NewArgument ¶
NewArgument constructs a new argument
func (*Argument) Assign ¶
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
Bool representation of the value (will be false, if not given or not parsable)
func (*Argument) Bools ¶
func (this *Argument) Bools() []bool
Bools returns values as bool array (values will be false, if not parsable to float64)
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.0, if not given or not parsable)
func (*Argument) Floats ¶
func (this *Argument) Floats() []float64
Floats returns values as float64 array (values will be 0.0, if not parsable to float64)
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 returns values as int array (values will be 0, if not parsable to int)
func (*Argument) Json ¶
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).
Helpful to allow complex inputs: `my-app do --foo '{"bar": "baz"}'`
func (*Argument) Provided ¶
func (this *Argument) Provided() bool
Provided returns bool whether argument was provided
func (*Argument) SetDefault ¶
SetDefault is a builder method to set default value. Default value is used if the argument is not provided (after environment variable).
func (*Argument) SetDescription ¶
SetDescription is a builder method to sets argument description. Description is an elaborate explanation which is used in help generation.
func (*Argument) SetEnv ¶
SetEnv is a builder method to set environment variable name, from which to take the value, if not provided (before default).
func (*Argument) SetParse ¶
func (this *Argument) SetParse(v ParseMethod) *Argument
SetParse is a builder method to set setup call on value. The setup call must return a replace value (can be unchanged) or an error, which stops evaluation and returns error to user.
func (*Argument) SetRegex ¶
SetRegex is a builder method to set regular expression which is used to check the the argument input (in case of multiple: each will be checked)
func (*Argument) SetUsage ¶
SetUsage is builder method to set the usage description. Usage is a short account of what the argument is used for, for help generaiton.
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 returns values as array of strings
type CallError ¶
type CallError struct {
// contains filtered or unexported fields
}
func NewCallError ¶
type CallMethod ¶
type CallMethod interface{}
CallMethod is the interface for functions used as command callbacks. `interface{}` is used so that those functions can have arbitrary input and output signatures. However, they still must be functions.
type Cli ¶
type Cli struct { // Name is the name of the console application used in the generated help Name string // Version is used in the generated help Version string // Description is used in the generated help Description string // Commands contain all registered commands and can be manipulated directly Commands map[string]*Command // Heralds contain list of command-create-callbacks which will be executed on `Run()` Heralds []HeraldCallback // Registry is a container holding objects for injection Registry *Registry // DefaultOptions contains options which are added to all commands early in the `Run()` call. DefaultOptions []*Option // DefaultCommand contains name of the command which is executed if non is given. Defaults to "list" DefaultCommand string // PreCall is executed before the chosen command is called, if defined PreCall func(c *Command) error // contains filtered or unexported fields }
Cli is a command line interface object
func (*Cli) AddDefaultOptions ¶
AddDefaultOptions adds a list of options to default options.
func (*Cli) Call ¶
Call executes command by building all input parameters based on objects registered in the container and running the callback.
func (*Cli) Herald ¶
func (this *Cli) Herald(cmd ...HeraldCallback) *Cli
Herald registers command constructors, which will be executed in `Run()`.
func (*Cli) New ¶
func (this *Cli) New(name, usage string, call CallMethod) *Cli
New creates and adds a new command
func (*Cli) NewDefaultOption ¶
func (this *Cli) NewDefaultOption(name, alias, usage, _default string, required, multiple bool) *Cli
NewDefaultOption creates and adds a new option to default list.
func (*Cli) RegisterAs ¶
RegisterAs is builder method and registers object under alias in registry
func (*Cli) RegisterNamed ¶
RegisterNamed registers a parameter for injecting in a named map[string]inteface{}
func (*Cli) SeparateArgs ¶
SeparateArgs takes (command line) args and tries to separate command name and the actual args & options
func (*Cli) SetDefaultCommand ¶
SetDefaultCommand is builder method and overwrites the default command ("list") with something else
func (*Cli) SetDescription ¶
SetDescription is builder method and sets description
func (*Cli) SetOnInterrupt ¶
SetOnInterrupt sets callback for interrupt signal (ctrl+c)
type Command ¶
type Command struct { // Cli back-references the Cli in which the command is registered Cli *Cli // Name is the unique (within Cli scope) call-name of the command Name string // Usage is a shorthand description of what the command does. Used in help output. Usage string // Description is a long elaboration on what the command does. Used in help output. Description string // Options contain all the registered options of the command. Options []*Option // Arguments contain all the registered arguments of the command. Arguments []*Argument // Call holds reflections of the callback. Call reflect.Value // contains filtered or unexported fields }
Command represents a named callback with a set of arguments and options
func NewCommand ¶
func NewCommand(name, usage string, call CallMethod) *Command
NewCommand constructs a new command
func NewHelpCommand ¶
func NewHelpCommand() *Command
NewHelpCommand returns the default help command
func NewListCommand ¶
func NewListCommand() *Command
NewListCommand returns the default help command
func (*Command) AddArgument ¶
AddArgument is builder method to add a new argument
func (*Command) Input ¶
Input returns map containing whole input values (of all options, all arguments)
func (*Command) NewArgument ¶
NewArgument is builder method to construct and add a new argument
func (*Command) NewOption ¶
func (this *Command) NewOption(name, alias, usage, _default string, required, multiple bool) *Command
NewOption is builder method to construct and add a new option
func (*Command) SetDescription ¶
SetDescription is builder method setting description
func (*Command) SetPostCall ¶
func (this *Command) SetPostCall(call CallMethod) *Command
func (*Command) SetPreCall ¶
func (this *Command) SetPreCall(call CallMethod) *Command
type CommandsSort ¶
type CommandsSort []*Command
CommandSort implements the `sort.Sortable` interface for commands, based on the command `Name` attribute
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
NewDefaultFormatter constructs a new constructor with the given styles
func (*DefaultFormatter) Escape ¶
func (this *DefaultFormatter) Escape(msg string) string
func (*DefaultFormatter) Format ¶
func (this *DefaultFormatter) Format(msg string) string
type DefaultInput ¶
type DefaultInput struct {
// contains filtered or unexported fields
}
DefaultInput is the default used input implementation
func NewDefaultInput ¶
func NewDefaultInput(in io.Reader, out Output) *DefaultInput
NewDefaultInput constructs a new default input implementation on given io reader (if nil, fall back to `os.Stdin`). Requires Output for issuing questions to user.
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
func (*DefaultInput) Confirm ¶
func (this *DefaultInput) Confirm(question string) bool
type DefaultOutput ¶
type DefaultOutput struct {
// contains filtered or unexported fields
}
DefaultOutput is the default used output type
func NewColorOutput ¶
func NewColorOutput(io io.Writer) *DefaultOutput
NewColoredOutput returns default output (on `os.Stdout`, if io is nil) using a formatter which applies the default color styles to style tokens on output.
func NewDebugOutput ¶
func NewDebugOutput(io io.Writer) *DefaultOutput
NewDebugOutput is used for debugging the color formatter
func NewMonochromeOutput ¶
func NewMonochromeOutput(io io.Writer) *DefaultOutput
NewMonochromeOutput returns default output (on `os.Stdout`, if io is nil) using a formatter which strips all style tokens (hence rendering non-colored, plain strings)
func NewOutput ¶
func NewOutput(io io.Writer, f Formatter) *DefaultOutput
NewOutput generates a new (default) output with provided io writer (if nil then `os.Stdout` is used) and a formatter
func (*DefaultOutput) Escape ¶
func (this *DefaultOutput) Escape(msg string) string
func (*DefaultOutput) Printf ¶
func (this *DefaultOutput) Printf(msg string, args ...interface{})
func (*DefaultOutput) ProgressBars ¶
func (this *DefaultOutput) ProgressBars() ProgressBarPool
func (*DefaultOutput) SetFormatter ¶
func (this *DefaultOutput) SetFormatter(f Formatter) Output
func (*DefaultOutput) Sprintf ¶
func (this *DefaultOutput) Sprintf(msg string, args ...interface{}) string
func (*DefaultOutput) Table ¶
func (this *DefaultOutput) Table(headers []string, style ...*TableStyle) *Table
func (*DefaultOutput) Writer ¶
func (this *DefaultOutput) Writer() io.Writer
type Formatter ¶
type Formatter interface { // Escape escapes a string, so that no formatter tokens will be interpolated (eg `<foo>` -> `\<foo>`) Escape(msg string) string // Format renders message for output by applying <style> tokens Format(msg string) string }
Formatter is used by Output for rendering. It supports style directives in the form <info> or <end> or suchlike
type HeraldCallback ¶
HeraldCallback is type for creator method, which can be registered with the `Herald()` method.
type Input ¶
type Input interface { // Ask prints question to user and then 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 prints question to user and then 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 // Confirm prints question to user until she replies with "yes", "y", "no" or "n" Confirm(question string) bool }
Input is an interface for input helping. It provides shorthand methods for often used CLI interactions.
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 a user input which is initialized with a single or double dash (eg "--foo" or "-f"). It may not be followed by a value, in which case it is considered a flag (see `IsFlag`). Options can be multiple inputs (no restrictions as there are for Arguments). An option can be required or optional. Options do not need to have any particular order.
func (*Option) Assign ¶
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
Bool representation of the value (will be false, if not given or not parsable)
func (*Option) Bools ¶
func (this *Option) Bools() []bool
Bools returns values as bool array (values will be false, if not parsable to float64)
func (*Option) Float ¶
func (this *Option) Float() float64
Float representation of the value (will be 0.0, if not given or not parsable)
func (*Option) Floats ¶
func (this *Option) Floats() []float64
Floats returns values as float64 array (values will be 0.0, if not parsable to float64)
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 returns values as int array (values will be 0, if not parsable to int)
func (*Option) IsFlag ¶
IsFlag marks an option as a flag. A Flag does not have any values. If it exists (eg "--verbose"), then it is automatically initialized with the string "true", which then can be checked with the `Bool()` method for actual `bool`
func (*Option) Json ¶
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).
Helpful to allow complex inputs: `my-app do --foo '{"bar": "baz"}'`
func (*Option) Provided ¶
func (this *Option) Provided() bool
Provided returns bool whether argument was provided
func (*Option) SetDefault ¶
SetDefault is a builder method to set default value. Default value is used if the option is not provided (after environment variable).
func (*Option) SetDescription ¶
SetDescription is a builder method to sets option description. Description is an elaborate explanation which is used in help generation.
func (*Option) SetEnv ¶
SetEnv is a builder method to set environment variable name, from which to take the value, if not provided (before default).
func (*Option) SetParse ¶
func (this *Option) SetParse(v ParseMethod) *Option
SetParse is a builder method to set setup call on value. The setup call must return a replace value (can be unchanged) or an error, which stops evaluation and returns error to user.
func (*Option) SetRegex ¶
SetRegex is a builder method to set regular expression which is used to check the the option input (in case of multiple: each will be checked)
func (*Option) SetUsage ¶
SetUsage is builder method to set the usage description. Usage is a short account of what the option is used for, for help generaiton.
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 returns values as array of strings
type Output ¶
type Output interface { // Escape escapes a string, so that no formatter tokens will be interpolated (eg `<foo>` -> `\<foo>`) Escape(s string) string // Printf applies format (renders styles) and writes to output Printf(msg string, args ...interface{}) // ProgressBars returns the pool of progress bars ProgressBars() ProgressBarPool // Sprintf applies format (renders styles) and returns as string Sprintf(msg string, args ...interface{}) string // SetFormatter is builder method and replaces current formatter SetFormatter(f Formatter) Output // Table creates a table object Table(header []string, style ...*TableStyle) *Table // Writer returns the `io.Writer` used by this output Writer() io.Writer }
Output is interface for
type ParseMethod ¶
SetupMethod is type for callback on Setup of Argument or Option. The return string replaces the original input. Called on each value (in case of multiple).
func IsAll ¶
func IsAll(v ...ParseMethod) ParseMethod
IsAll joins a set of validators methods and returns true if ALL of them match
func IsAny ¶
func IsAny(v ...ParseMethod) ParseMethod
IsAny joins a set of validator methods and returns true if ANY of them matches
type ProgressBar ¶
type ProgressBar interface { // Done returns whether progress bar is done (position == size) Done() bool // Finish sets progress to max and Finish() // Increase adds given amount to progress Increase(amount int) error // Increment increases progress by one Increment() error // Position returns the progress position Position() int // Render returns the rendered progress bar in it's current position Render() string // RenderWidth returns the width of the rendered output (amount of chars (rune)) RenderWidth() int // Reset sets position to zero and unsets all timers Reset() // Set moves the progress to given position Set(position int) error // SetRenderWidth sets total width of rendered output to given amount of characters (runes) SetRenderWidth(v int) ProgressBar // SetSize sets the total size of the progress bar SetSize(v int) ProgressBar // SetStyle sets the style of the progress bar SetStyle(style *ProgressBarStyle) ProgressBar // Style sets the Style() *ProgressBarStyle }
type ProgressBarPool ¶
type ProgressBarPool interface { // Finish sets all progress to max and stops Finish() chan bool // Has return whether a bar with name exists or not Has(bar string) bool // Init adds and initializes a new, named progress bar of given size and returns it Init(name string, size int) (ProgressBar, error) // Start initializes rendering of all registered bars Start() // Style sets style of registered progress bars Style(style *ProgressBarStyle) error // With set's output width of registered progress bars Width(width int) error }
func NewProgressBarPool ¶
func NewProgressBarPool(style ...*ProgressBarStyle) ProgressBarPool
type ProgressBarSimple ¶
type ProgressBarSimple struct {
// contains filtered or unexported fields
}
func NewProgressBar ¶
func NewProgressBar(size int) *ProgressBarSimple
func (*ProgressBarSimple) Done ¶
func (this *ProgressBarSimple) Done() bool
Done returns bool whether progress bar is done (at 100%)
func (*ProgressBarSimple) Finish ¶
func (this *ProgressBarSimple) Finish()
Finish ends progress by skipping to the end
func (*ProgressBarSimple) Increase ¶
func (this *ProgressBarSimple) Increase(amount int) error
Add increases progress by given amount
func (*ProgressBarSimple) Increment ¶
func (this *ProgressBarSimple) Increment() error
Increase adds a one to progress
func (*ProgressBarSimple) Position ¶
func (this *ProgressBarSimple) Position() int
Position returns the current position
func (*ProgressBarSimple) Render ¶
func (this *ProgressBarSimple) Render() string
Render returns rendered progress bar in current progress position
func (*ProgressBarSimple) RenderWidth ¶
func (this *ProgressBarSimple) RenderWidth() int
Render returns rendered progress bar in current progress position
func (*ProgressBarSimple) Reset ¶
func (this *ProgressBarSimple) Reset()
func (*ProgressBarSimple) Set ¶
func (this *ProgressBarSimple) Set(position int) error
Set moves progress to given position (must be between 0 and size)
func (*ProgressBarSimple) SetRenderWidth ¶
func (this *ProgressBarSimple) SetRenderWidth(v int) ProgressBar
SetRenderWidth is builder method to set render width (defaults to PB_DEFAULT_RENDER_WIDTH)
func (*ProgressBarSimple) SetSize ¶
func (this *ProgressBarSimple) SetSize(v int) ProgressBar
SetSize is builder method to set size (i.e. max length) of progress
func (*ProgressBarSimple) SetStyle ¶
func (this *ProgressBarSimple) SetStyle(v *ProgressBarStyle) ProgressBar
SetStyle sets the rendering (output) style (i.e. the characters used to print the progress bar)
func (*ProgressBarSimple) Style ¶
func (this *ProgressBarSimple) Style() *ProgressBarStyle
Style returns the currently used style
type ProgressBarStyle ¶
type ProgressBarStyle struct { Empty rune Progress rune Rightmost rune None rune LeftBorder rune RightBorder rune Count progressBarAddon Elapsed progressBarAddon Estimate progressBarAddon Percentage progressBarAddon RenderCount func(pos, max int, bar ProgressBar) string RenderElapsed func(elapsed time.Duration, bar ProgressBar) string RenderEstimate func(forecast time.Duration, bar ProgressBar) string RenderPercentage func(percent float32, bar ProgressBar) string RenderPrefix func(count, elapsed, estimate, percentage string) string RenderSuffix func(count, elapsed, estimate, percentage string) string }
ProgressBarStyle
func CloneProgressBarStyle ¶
func CloneProgressBarStyle(from *ProgressBarStyle) *ProgressBarStyle
type ReduceMethod ¶
ReduceMethod is type of the callback of the `Reduce` and `ReduceAsync` methods
type Registry ¶
Registry is a small container holding objects which are injected into command calls.
func (*Registry) Get ¶
Get returns registered object by their type name (`reflect.TypeOf(..).String()`)
func (*Registry) Reduce ¶
func (this *Registry) Reduce(cb ReduceMethod) []interface{}
Reduce calls a bool-returning function on all registered objects in alphanumerical order and returns all selected as a slice
func (*Registry) ReduceAsync ¶
func (this *Registry) ReduceAsync(cb ReduceMethod) chan interface{}
ReduceAsync calls a bool-returning function on all registered objects concurrently and writes all selected objects in a return channel
type Table ¶
type Table struct { // AllowEmptyFill decides whether SetRow() and SetColumn() with row indices // bigger than the amount of rows creates additional, empty rows in between. // USE WITH CAUTION! AllowEmptyFill bool // set of output headers Headers *TableRow // set of row, col, lines Rows []*TableRow // contains filtered or unexported fields }
func NewTable ¶
func NewTable(headers []string, style ...*TableStyle) *Table
NewTable constructs new Table with optional list of headers
func (*Table) SetColumn ¶
SetColumn sets the contents of a specific column in a specific row. See `SetRow` for limitations on the row index. The column index must be within the bounds of the column amount.
func (*Table) SetHeaders ¶
SetHeaders sets the headers of the table. Can only be called before any data has been added.
func (*Table) SetRow ¶
SetRow sets columns in a specific row.
If `AllowEmptyFill` is true, then the row index can be arbitrary and empty columns will be automatically created, if needed. Otherwise the row index must be within the bounds of existing data or an error is returned.
func (*Table) SetStyle ¶
func (this *Table) SetStyle(style *TableStyle)
SetStyle changes the table style
type TableCol ¶
type TableCol struct {
// contains filtered or unexported fields
}
func NewTableCol ¶
NewTableCol creates a new table column object from given content
func (*TableCol) Content ¶
Content returns the string content of the column. If maxWidth is not given or 0 then the original content is returned. Otherwise the returned content is wrapped to the maxWidth limitation. Words will be split if they exceed the maxWidth value.
func (*TableCol) ContentPrefixed ¶
ContentPrefixed
func (*TableCol) LineCount ¶
LineCount returns the amount of lines of the content. If a `maxWidth` value is provided then the returned line count is calculated based on the existing content.
Example 1:
maxWidth not given content = "foo bar baz" line count = 1
Example 2:
maxWidth = 3 content = "foo bar baz" line count = 3
func (*TableCol) Render ¶
Render returns wrapped content, max content line width and content line count. See `LineCount()`, `Width()` and `Content()` for more informations.
func (*TableCol) SetContent ¶
func (*TableCol) SetRenderer ¶
type TableRow ¶
type TableRow struct { // MaxLineCount is the maximum amount of MaxLineCount int ColAmount int Cols []*TableCol // contains filtered or unexported fields }
func NewTableRow ¶
func (*TableRow) CalculateWidths ¶
func (*TableRow) RenderWithWidths ¶
func (*TableRow) SetRenderer ¶
type TableStyle ¶
type TableStyle struct { LeftTop string Left string LeftBottom string Right string RightTop string RightBottom string CrossInner string CrossTop string CrossBottom string CrossLeft string CrossRight string InnerHorizontal string InnerVertical string Top string Bottom string Prefix string Suffix string HeaderRenderer func(content string) string ContentRenderer func(content string) string }
func CopyTableStyle ¶
func CopyTableStyle(from *TableStyle) *TableStyle
func NewDefaultTableStyle ¶
func NewDefaultTableStyle() *TableStyle
func (*TableStyle) CalculateColWidths ¶
func (this *TableStyle) CalculateColWidths(table *Table, totalTableWidth int) []int
CalculateColWidths returns the widths of the cols of the table, for given max width
func (*TableStyle) Render ¶
func (this *TableStyle) Render(table *Table, mw ...int) string
Render renders given table with a given max width. Max width can not be lower than waste per row (see `Waste()`) and at least one character per column.
func (*TableStyle) Waste ¶
func (this *TableStyle) Waste(colCount int) int
Waste returns the amount of "wasted" characters (table render characters + prefix and suffix whitespaces) for given amount of columns
type WrapTrimMode ¶
type WrapTrimMode int
WrapTrimMode defines whether and how wrapped lines are trimmed. See WRAP_TRIM_*
const ( // WRAP_TRIM_NONE keeps " foo bar baz " as is WRAP_TRIM_NONE WrapTrimMode = iota // WRAP_TRIM_RIGHT transforms " foo bar baz " to "foo bar baz " WRAP_TRIM_RIGHT // WRAP_TRIM_LEFT transforms " foo bar baz " to " foo bar baz" WRAP_TRIM_LEFT // WRAP_TRIM_BOTH transforms " foo bar baz " to "foo bar baz" WRAP_TRIM_BOTH )
type WrapWhitespaceMode ¶
type WrapWhitespaceMode int
WrapWhitespaceMode defines whether in-sentence whitespaces are reduced contracted or not. See WRAP_WHITESPACE_*
const ( // WRAP_WHITESPACE_CONTRACT contracts "foo bar baz" to "foo bar baz" WRAP_WHITESPACE_CONTRACT WrapWhitespaceMode = iota // WRAP_WHITESPACE_KEEP keeps "foo bar baz" as is WRAP_WHITESPACE_KEEP )
type Wrapper ¶
type Wrapper struct { // BreakWords controls whether over-length words can be broken or not. // Example: Wrapping "foo barrr" with limit of 3 and NO wrapping will // return "foo\nbarrr" and with wrapping will return "foo\nbar\nrr" BreakWords bool // KeepEmptyLines controls whether empty lines are removed or not. Defaults // to false. If set to true then "foo\n\nbar" stays "foo\n\n"bar". Otherwise // it becomes "foo\nbar" KeepEmptyLines bool // Limit is the max length per wrapped line Limit uint // TrimMode defines whether/how wrapped lines are trimmed or not TrimMode WrapTrimMode // WhitespaceMode defines whether in-sentence whitespaces are reduced // or not. Eg with disabled contracting WhitespaceMode WrapWhitespaceMode }
Wrapper transforms multi- or single-line strings into multi-line strings of maximum line length.
func NewWrapper ¶
Source Files ¶
- cli.go
- clif.go
- command.go
- common.go
- default_commands.go
- describer.go
- formatter.go
- input.go
- output.go
- parameter.go
- parameter_argument.go
- parameter_option.go
- progress.go
- progress_bar.go
- progress_style.go
- registry.go
- table.go
- table_col.go
- table_row.go
- table_style.go
- term.go
- term_nix.go
- term_x.go
- validators.go
- wrap.go