commands/cli: Sort options by length when generating options helptext
Matt Bell committed
Nov 12, 2014 at 18:32 UTC
3e7592f2ccda96182df7ff4abb308b62009ebd5a
1 file changed
+27
-3
commands/cli/helptext.go
+27
-3
@@ -3,6 +3,7 @@ package cli
3
import (
4
"fmt"
5
"io"
6
+ "sort"
7
"strings"
8
"text/template"
9
@@ -270,10 +271,12 @@ func optionText(cmd ...*cmds.Command) []string {
271
if len(lines) < i+1 {
272
lines = append(lines, "")
273
}
273
- if len(opt.Names) >= j+1 {
274
- lines[i] += fmt.Sprintf(optionFlag, opt.Names[j])
274
+
275
+ names := sortByLength(opt.Names)
276
+ if len(names) >= j+1 {
277
+ lines[i] += fmt.Sprintf(optionFlag, names[j])
278
}
276
- if len(opt.Names) > j+1 {
279
+ if len(names) > j+1 {
280
lines[i] += ", "
281
done = false
282
}
@@ -385,3 +388,24 @@ func indent(lines []string, prefix string) []string {
388
func indentString(line string, prefix string) string {
389
return prefix + strings.Replace(line, "\n", "\n"+prefix, -1)
390
}
391
+
392
+type lengthSlice []string
393
+
394
+func (ls lengthSlice) Len() int {
395
+ return len(ls)
396
+}
397
+func (ls lengthSlice) Swap(a, b int) {
398
+ ls[a], ls[b] = ls[b], ls[a]
399
+}
400
+func (ls lengthSlice) Less(a, b int) bool {
401
+ return len(ls[a]) < len(ls[b])
402
+}
403
+
404
+func sortByLength(slice []string) []string {
405
+ output := make(lengthSlice, len(slice))
406
+ for i, val := range slice {
407
+ output[i] = val
408
+ }
409
+ sort.Sort(output)
410
+ return []string(output)
411
+}