-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinfo.go
93 lines (69 loc) · 1.88 KB
/
info.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
package tablex
import (
"errors"
"reflect"
"github.com/jedib0t/go-pretty/v6/table"
)
var ObjectIsNotStruct = errors.New("tablex_error: received object is not a structure")
type tablexInfo struct {
isCollection bool
reflType reflect.Type
emptyVal string
headers []interface{}
fields map[structFieldName]*fieldInfo
}
func newTablexInfo(obj interface{}, emptyVal string) (*tablexInfo, error) {
var isCollection bool
reflType := getReflectType(obj)
if reflType.Kind() == reflect.Slice || reflType.Kind() == reflect.Array {
isCollection = true
reflType = reflType.Elem()
}
if reflType.Kind() != reflect.Struct {
return nil, ObjectIsNotStruct
}
tInfo := &tablexInfo{
isCollection: isCollection,
reflType: reflType,
emptyVal: emptyVal,
}
tInfo.loadFields()
tInfo.loadHeaders()
return tInfo, nil
}
func (tx *tablexInfo) loadFields() {
tx.fields = make(map[structFieldName]*fieldInfo)
lastIdx := 0
for i := 0; i < tx.reflType.NumField(); i++ {
field := tx.reflType.Field(i)
lastIdx = tx.loadFieldInfo(field, lastIdx, nil)
}
}
func (tx *tablexInfo) loadHeaders() {
headers := make([]interface{}, len(tx.fields))
for _, fi := range tx.fields {
headers[fi.idxInTable] = fi.columnHeader
}
tx.headers = headers
}
func (tx *tablexInfo) rowsForObject(obj interface{}) []table.Row {
if !tx.isCollection {
row := tx.rowForObject(obj)
return []table.Row{row}
}
reflValue := reflect.ValueOf(obj)
rows := make([]table.Row, reflValue.Len())
for i := 0; i < reflValue.Len(); i++ {
collectionElem := reflValue.Index(i).Interface()
rows[i] = tx.rowForObject(collectionElem)
}
return rows
}
func (tx *tablexInfo) rowForObject(obj interface{}) table.Row {
reflValue := reflect.ValueOf(obj)
values := make([]interface{}, len(tx.headers))
for _, fi := range tx.fields {
values[fi.idxInTable] = fi.getFieldValue(reflValue, tx.emptyVal)
}
return values
}