forked from vmware-archive/jhanda
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathusage.go
More file actions
101 lines (82 loc) · 1.86 KB
/
Copy pathusage.go
File metadata and controls
101 lines (82 loc) · 1.86 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package jhanda
import (
"fmt"
"reflect"
"sort"
"strings"
)
type Usage struct {
Description string
ShortDescription string
Flags interface{}
}
func PrintUsage(receiver interface{}) (string, error) {
v := reflect.ValueOf(receiver)
t := v.Type()
if t.Kind() != reflect.Struct {
return "", fmt.Errorf("unexpected pointer to non-struct type %s", t.Kind())
}
var fields []reflect.StructField
for i := 0; i < t.NumField(); i++ {
fields = append(fields, t.Field(i))
}
var usage []string
var length int
for _, field := range fields {
var longShort string
long, ok := field.Tag.Lookup("long")
if ok {
longShort += fmt.Sprintf("--%s", long)
}
short, ok := field.Tag.Lookup("short")
if ok {
if longShort != "" {
longShort += ", "
}
longShort += fmt.Sprintf("-%s", short)
}
if len(longShort) > length {
length = len(longShort)
}
usage = append(usage, longShort)
}
for i, line := range usage {
usage[i] = pad(line, " ", length)
}
for i, field := range fields {
kind := field.Type.Kind().String()
if kind == reflect.Slice.String() {
kind = fmt.Sprintf("%s (variadic)", field.Type.Elem().Kind().String())
}
line := fmt.Sprintf("%s %s", usage[i], kind)
if len(line) > length {
length = len(line)
}
usage[i] = line
}
for i, line := range usage {
usage[i] = pad(line, " ", length)
}
for i, field := range fields {
description, ok := field.Tag.Lookup("description")
if ok {
usage[i] = fmt.Sprintf("%s %s", usage[i], description)
}
}
for i, field := range fields {
defaultValue, ok := field.Tag.Lookup("default")
if ok {
usage[i] = fmt.Sprintf("%s (default: %s)", usage[i], defaultValue)
}
}
sort.Strings(usage)
return strings.Join(usage, "\n"), nil
}
func pad(str, pad string, length int) string {
for {
str += pad
if len(str) > length {
return str[0:length]
}
}
}