-
Notifications
You must be signed in to change notification settings - Fork 20
/
listhelp.go
111 lines (93 loc) · 2.58 KB
/
listhelp.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
package listformat
import (
"fmt"
"slices"
"sort"
"strings"
"github.com/open-component-model/ocm/pkg/utils"
)
type StringElementDescriptionList []string
func (l StringElementDescriptionList) Size() int { return len(l) / 2 }
func (l StringElementDescriptionList) Key(i int) string { return l[2*i] }
func (l StringElementDescriptionList) Description(i int) string { return l[2*i+1] }
type StringElementList []string
func (l StringElementList) Size() int { return len(l) }
func (l StringElementList) Key(i int) string { return l[i] }
func (l StringElementList) Description(i int) string { return "" }
func FormatList(def string, elems ...string) string {
return FormatListElements(def, StringElementList(elems))
}
type maplist[K ~string, E any] struct {
desc func(E) string
keys []K
m map[K]E
}
func (l *maplist[K, E]) Size() int { return len(l.keys) }
func (l *maplist[K, E]) Key(i int) string { return string(l.keys[i]) }
func (l *maplist[K, E]) Description(i int) string { return l.desc(l.m[l.keys[i]]) }
func FormatMapElements[K ~string, E any](def string, m map[K]E, desc ...func(E) string) string {
if len(desc) == 0 || desc[0] == nil {
desc = []func(E) string{StringDescription[E]}
}
keys := utils.StringMapKeys(m)
return FormatListElements(def, &maplist[K, E]{
desc: desc[0],
keys: keys,
m: m,
})
}
type DescriptionSource interface {
GetDescription() string
}
type DirectDescriptionSource interface {
Description() string
}
func StringDescription[E any](e E) string {
if d, ok := any(e).(DescriptionSource); ok {
return d.GetDescription()
}
if d, ok := any(e).(DirectDescriptionSource); ok {
return d.Description()
}
return fmt.Sprintf("%s", any(e))
}
type ListElements interface {
Size() int
Key(i int) string
Description(i int) string
}
func FormatListElements(def string, elems ListElements) string {
names := ""
size := elems.Size()
for i := 0; i < size; i++ {
key := elems.Key(i)
names = fmt.Sprintf("%s - <code>%s</code>", names, key)
if key == def {
names += " (default)"
}
desc := elems.Description(i)
if desc != "" {
names += ": " + utils.IndentLines(desc, " ", true)
if strings.Contains(desc, "\n") {
names += "\n"
}
}
names += "\n"
}
return names
}
func FormatDescriptionList(def string, elems ...string) string {
list := slices.Clone(elems)
sort.Strings(list)
out := ""
for _, l := range list {
if l != "" {
out += " - " + utils.IndentLines(l, " ", true)
if strings.Contains(l, "\n") {
out += "\n"
}
}
out += "\n"
}
return out
}