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%
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
Provenance
- Commit
4d2c4af- Tree
3f8c390- Author
Albert Nigmatzianov <albertnigma@gmail.com>- Committer
Albert Nigmatzianov <albertnigma@gmail.com>- Parent
d83a1d7
2 files changed+31 added−94 removed
modified:cobra.go+5 added-67 removed
17 unmodified lines18 19 import (20 "fmt"21 "io"22- "reflect"23- "strconv"22 "strings"23 "text/template"24 "unicode"25 )26 27 var 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 }31 32 var initializers []func()33 24 unmodified lines58 func OnInitialize(y ...func()) {59 initializers = append(initializers, y...)60 }61 68-// 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.71-func Gt(a interface{}, b interface{}) bool {72- var left, right int6473- av := reflect.ValueOf(a)74-75- 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- }83-84- bv := reflect.ValueOf(b)85-86- 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- }94-95- return left > right96-}97-98-// Eq takes two types and checks whether they are equal. Supported types are int and string. Unsupported types will panic.99-func Eq(a interface{}, b interface{}) bool {100- av := reflect.ValueOf(a)101- bv := reflect.ValueOf(b)102-103- 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-}113-114-func trimRightSpace(s string) string {62+func trimTrailingWhitespaces(s string) string {63 return strings.TrimRightFunc(s, unicode.IsSpace)64 }65 118-// appendIfNotPresent will append stringToAppend to the end of s, but only if it's not yet present in s.119-func appendIfNotPresent(s, stringToAppend string) string {120- if strings.Contains(s, stringToAppend) {121- return s122- }123- return s + " " + stringToAppend124-}125-66 // rpad adds padding to the right of a string.67 func rpad(s string, padding int) string {68 template := fmt.Sprintf("%%-%ds", padding)69 return fmt.Sprintf(template, s)70 }71 72 // tmpl executes the given template text on data, writing the result to w.73 func 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 }77 78 // ld compares two strings and returns the levenshtein distance between them.79 func ld(s, t string, ignoreCase bool) int {33 unmodified linesmodified:command.go+26 added-27 removed
328 unmodified lines329 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}}335 336 Aliases:337 {{.NameAndAliases}}{{end}}{{if .HasExample}}338 339 Examples:340-{{ .Example }}{{end}}{{if .HasAvailableSubCommands}}340+{{.Example}}{{end}}{{if .HasAvailableSubCommands}}341 342 Available Commands:{{range .Commands}}{{if (or .IsAvailableCommand (eq .Name "help"))}}343 {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableLocalFlags}}344 345 Flags:346-{{.LocalFlags.FlagUsages | trimRightSpace}}{{end}}{{if .HasAvailableInheritedFlags}}346+{{.LocalFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasAvailableInheritedFlags}}347 348 Global Flags:349-{{.InheritedFlags.FlagUsages | trimRightSpace}}{{end}}{{if .HasHelpSubCommands}}349+{{.InheritedFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasHelpSubCommands}}350 351 Additional help topics:{{range .Commands}}{{if .IsAdditionalHelpTopicCommand}}352 {{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableSubCommands}}353 9 unmodified lines363 364 if c.HasParent() {365 return c.parent.HelpTemplate()366 }367- return `{{with or .Long .Short }}{{. | trim}}367+ return `{{with (or .Long .Short)}}{{. | trimTrailingWhitespaces}}368 369 {{end}}{{if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}}`370 }371 490 unmodified lines862 }863 864 // Println is a convenience method to Println to the defined output, fallback to Stderr if not set.865 func (c *Command) Println(i ...interface{}) {866- str := fmt.Sprintln(i...)867- c.Print(str)866+ c.Print(fmt.Sprintln(i...))867 }868 869 // Printf is a convenience method to Printf to the defined output, fallback to Stderr if not set.870 func (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 }873 874 // CommandPath returns the full path to this command.875 func (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 }881 882 // UseLine puts out the full usage for a given command (including parents).883 func (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 }895 896 // DebugFlags used to determine which flags have been assigned to which commands897 // and which persist.37 unmodified lines935 }936 937 // Name returns the command's name: the first word in the use line.938 func (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 }949 950 // HasAlias determines if a given string is an alias of the command.314 unmodified lines