forked from wtfutil/wtf
/
help_parser.go
82 lines (64 loc) · 1.55 KB
/
help_parser.go
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
package utils
import (
"reflect"
"regexp"
"strconv"
"unicode"
"unicode/utf8"
"github.com/wtfutil/wtf/cfg"
)
/* -------------------- Exported Functions -------------------- */
func HelpFromInterface(item interface{}) string {
result := ""
t := reflect.TypeOf(item)
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
kind := field.Type.Kind()
if field.Type.Kind() == reflect.Ptr {
kind = field.Type.Elem().Kind()
}
if field.Name == "common" {
result += HelpFromInterface(cfg.Common{})
}
switch kind {
case reflect.Interface:
result += HelpFromInterface(field.Type.Elem())
default:
result += helpFromValue(field)
}
}
return result
}
// StripColorTags removes tcell color tags from a given string
func StripColorTags(input string) string {
openColorRegex := regexp.MustCompile(`\[.*?\]`)
return openColorRegex.ReplaceAllString(input, "")
}
/* -------------------- Unexported Functions -------------------- */
func helpFromValue(field reflect.StructField) string {
result := ""
optional, err := strconv.ParseBool(field.Tag.Get("optional"))
if err != nil {
optional = false
}
help := field.Tag.Get("help")
if optional {
help = "Optional " + help
}
values := field.Tag.Get("values")
if help != "" {
result += "\n\n " + lowercaseTitle(field.Name)
result += "\n " + help
if values != "" {
result += "\n Values: " + values
}
}
return result
}
func lowercaseTitle(title string) string {
if title == "" {
return ""
}
r, n := utf8.DecodeRuneInString(title)
return string(unicode.ToLower(r)) + title[n:]
}