Skip to content
Myr

Improve template mechanisms

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* Delete Eq, Gt, appendIfNotPresent and trim functions * Add "[flags]" in UseLine * Simplify other functions * Simplify templates Minor performance improvement. Benchmark for command with 4 flags and one child command: benchmark old ns/op new ns/op delta BenchmarkCmdUsageFunc-4 335860 319290 -4.93% benchmark old allocs new allocs delta BenchmarkCmdUsageFunc-4 562 543 -3.38% benchmark old bytes new bytes delta BenchmarkCmdUsageFunc-4 21623 21037 -2.71%

authored by Albert Nigmatzianov · committed by Albert Nigmatzianov · parent d83a1d7 · Browse files · 2 files+31 added−94 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

2 files+31 added−94 removed

  • other:+31 added−94 removed

2 files+31 added−94 removed

modified:cobra.go+5 added-67 removed
17 unmodified lines
1819import (20 "fmt"21 "io"22 "reflect"23 "strconv"22 "strings"23 "text/template"24 "unicode"25)2627var templateFuncs = template.FuncMap{30 "trim": strings.TrimSpace,31 "trimRightSpace": trimRightSpace,32 "appendIfNotPresent": appendIfNotPresent,33 "rpad": rpad,34 "gt": Gt,35 "eq": Eq,28 "trimTrailingWhitespaces": trimTrailingWhitespaces,29 "rpad": rpad,30}3132var initializers []func()33
24 unmodified lines
58func OnInitialize(y ...func()) {59 initializers = append(initializers, y...)60}6168// Gt takes two types and checks whether the first type is greater than the second. In case of types Arrays, Chans,69// Maps and Slices, Gt will compare their lengths. Ints are compared directly while strings are first parsed as70// ints and then compared.71func Gt(a interface{}, b interface{}) bool {72 var left, right int6473 av := reflect.ValueOf(a)7475 switch av.Kind() {76 case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice:77 left = int64(av.Len())78 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:79 left = av.Int()80 case reflect.String:81 left, _ = strconv.ParseInt(av.String(), 10, 64)82 }8384 bv := reflect.ValueOf(b)8586 switch bv.Kind() {87 case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice:88 right = int64(bv.Len())89 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:90 right = bv.Int()91 case reflect.String:92 right, _ = strconv.ParseInt(bv.String(), 10, 64)93 }9495 return left > right96}9798// Eq takes two types and checks whether they are equal. Supported types are int and string. Unsupported types will panic.99func Eq(a interface{}, b interface{}) bool {100 av := reflect.ValueOf(a)101 bv := reflect.ValueOf(b)102103 switch av.Kind() {104 case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice:105 panic("Eq called on unsupported type")106 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:107 return av.Int() == bv.Int()108 case reflect.String:109 return av.String() == bv.String()110 }111 return false112}113114func trimRightSpace(s string) string {62func trimTrailingWhitespaces(s string) string {63 return strings.TrimRightFunc(s, unicode.IsSpace)64}65118// appendIfNotPresent will append stringToAppend to the end of s, but only if it's not yet present in s.119func appendIfNotPresent(s, stringToAppend string) string {120 if strings.Contains(s, stringToAppend) {121 return s122 }123 return s + " " + stringToAppend124}12566// rpad adds padding to the right of a string.67func rpad(s string, padding int) string {68 template := fmt.Sprintf("%%-%ds", padding)69 return fmt.Sprintf(template, s)70}7172// tmpl executes the given template text on data, writing the result to w.73func tmpl(w io.Writer, text string, data interface{}) error {134 t := template.New("top")135 t.Funcs(templateFuncs)136 template.Must(t.Parse(text))137 return t.Execute(w, data)74 t := template.New("top").Funcs(templateFuncs)75 return template.Must(t.Parse(text)).Execute(w, data)76}7778// ld compares two strings and returns the levenshtein distance between them.79func ld(s, t string, ignoreCase bool) int {
33 unmodified lines
modified:command.go+26 added-27 removed
328 unmodified lines
329 if c.HasParent() {330 return c.parent.UsageTemplate()331 }332 return `Usage:{{if .Runnable}}333 {{if .HasAvailableFlags}}{{appendIfNotPresent .UseLine "[flags]"}}{{else}}{{.UseLine}}{{end}}{{end}}{{if .HasAvailableSubCommands}}334 {{ .CommandPath}} [command]{{end}}{{if gt .Aliases 0}}333 {{.UseLine}}{{end}}{{if .HasAvailableSubCommands}}334 {{.CommandPath}} [command]{{end}}{{if gt (len .Aliases) 0}}335336Aliases:337 {{.NameAndAliases}}{{end}}{{if .HasExample}}338339Examples:340{{ .Example }}{{end}}{{if .HasAvailableSubCommands}}340{{.Example}}{{end}}{{if .HasAvailableSubCommands}}341342Available Commands:{{range .Commands}}{{if (or .IsAvailableCommand (eq .Name "help"))}}343 {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableLocalFlags}}344345Flags:346{{.LocalFlags.FlagUsages | trimRightSpace}}{{end}}{{if .HasAvailableInheritedFlags}}346{{.LocalFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasAvailableInheritedFlags}}347348Global Flags:349{{.InheritedFlags.FlagUsages | trimRightSpace}}{{end}}{{if .HasHelpSubCommands}}349{{.InheritedFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasHelpSubCommands}}350351Additional help topics:{{range .Commands}}{{if .IsAdditionalHelpTopicCommand}}352 {{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableSubCommands}}353
9 unmodified lines
363364 if c.HasParent() {365 return c.parent.HelpTemplate()366 }367 return `{{with or .Long .Short }}{{. | trim}}367 return `{{with (or .Long .Short)}}{{. | trimTrailingWhitespaces}}368369{{end}}{{if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}}`370}371
490 unmodified lines
862}863864// Println is a convenience method to Println to the defined output, fallback to Stderr if not set.865func (c *Command) Println(i ...interface{}) {866 str := fmt.Sprintln(i...)867 c.Print(str)866 c.Print(fmt.Sprintln(i...))867}868869// Printf is a convenience method to Printf to the defined output, fallback to Stderr if not set.870func (c *Command) Printf(format string, i ...interface{}) {872 str := fmt.Sprintf(format, i...)873 c.Print(str)871 c.Print(fmt.Sprintf(format, i...))872}873874// CommandPath returns the full path to this command.875func (c *Command) CommandPath() string {878 str := c.Name()879 x := c880 for x.HasParent() {881 str = x.parent.Name() + " " + str882 x = x.parent876 if c.HasParent() {877 return c.Parent().CommandPath() + " " + c.Name()878 }884 return str879 return c.Name()880}881882// UseLine puts out the full usage for a given command (including parents).883func (c *Command) UseLine() string {889 str := ""884 var useline string885 if c.HasParent() {891 str = c.parent.CommandPath() + " "886 useline = c.parent.CommandPath() + " " + c.Use887 } else {888 useline = c.Use889 }893 return str + c.Use890 if c.HasAvailableFlags() && !strings.Contains(useline, "[flags]") {891 useline += " [flags]"892 }893 return useline894}895896// DebugFlags used to determine which flags have been assigned to which commands897// and which persist.
37 unmodified lines
935}936937// Name returns the command's name: the first word in the use line.938func (c *Command) Name() string {939 if c.name != "" {940 return c.name939 if c.name == "" {940 name := c.Use941 i := strings.Index(name, " ")942 if i >= 0 {943 name = name[:i]944 }945 c.name = name946 }942 name := c.Use943 i := strings.Index(name, " ")944 if i >= 0 {945 name = name[:i]946 }947 c.name = name947 return c.name948}949950// HasAlias determines if a given string is an alias of the command.
314 unmodified lines