This repository has been archived by the owner on May 13, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathoutline.go
86 lines (68 loc) · 2.33 KB
/
outline.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
package bite
import (
"strings"
"reflect"
"github.com/spf13/cobra"
)
// like reflect.Indirect but reflect.Interface values too.
func indirectValue(val reflect.Value) reflect.Value {
if kind := val.Kind(); kind == reflect.Interface || kind == reflect.Ptr {
return val.Elem()
}
return val
}
// like reflect.Indirect but for types and reflect.Interface types too.
func indirectType(typ reflect.Type) reflect.Type {
if kind := typ.Kind(); kind == reflect.Interface || kind == reflect.Ptr {
return typ.Elem()
}
return typ
}
func makeDynamicSingleTableItem(header string, item interface{}) interface{} {
f := make([]reflect.StructField, 1)
f[0] = reflect.TypeOf(item).Field(0)
f[0].Tag = reflect.StructTag(`header:"` + header + `"`)
withHeaderTyp := reflect.StructOf(f)
tmp := indirectValue(reflect.ValueOf(item)).Convert(withHeaderTyp)
return tmp.Interface()
}
// OutlineStringResults accepts a key, i.e "name" and entries i.e ["schema1", "schema2", "schema3"]
// and will convert it to a slice of [{"name":"schema1"},"name":"schema2", "name":"schema3"}] to be able to be printed via `printJSON`.
func OutlineStringResults(cmd *cobra.Command, key string, entries []string) (items []interface{}) { // why not? (items []map[string]string) because jmespath can't work with it, only with []interface.
// key = strings.Title(key)
if strings.ToUpper(GetOutPutFlag(cmd)) == "JSON" {
// prepare as JSON.
for _, entry := range entries {
items = append(items, map[string]string{key: entry})
}
return
}
// prepare as Table.
for _, entry := range entries {
item := struct {
Value string
}{entry}
items = append(items, makeDynamicSingleTableItem(key, item))
}
return
}
// OutlineIntResults accepts a key, i.e "version" and entries i.e [1, 2, 3]
// and will convert it to a slice of [{"version":3},"version":1, "version":2}] to be able to be printed via `printJSON`.
func OutlineIntResults(cmd *cobra.Command, key string, entries []int) (items []interface{}) {
// key = strings.Title(key)
if strings.ToUpper(GetOutPutFlag(cmd)) == "JSON" {
// prepare as JSON.
for _, entry := range entries {
items = append(items, map[string]int{key: entry})
}
return
}
// prepare as Table.
for _, entry := range entries {
item := struct {
Value int
}{entry}
items = append(items, makeDynamicSingleTableItem(key, item))
}
return
}