/
outfmt.go
72 lines (60 loc) · 1.3 KB
/
outfmt.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
package outfmt
import (
"encoding/json"
"reflect"
"github.com/NorskHelsenett/outfmt/internal/cache"
"github.com/NorskHelsenett/outfmt/internal/table"
"gopkg.in/yaml.v2"
)
type SpecField struct {
Key string
Field string
}
type Spec map[string][]SpecField
type OutputFormat int64
const (
OutputFormatJSON OutputFormat = iota
OutputFormatYAML
OutputFormatTable
OutputFormatField
OutputFormatCondition
)
type Config struct {
Format OutputFormat
/// only used for OutputFormatField
AdditionalField string
}
func Format(data any, config *Config) ([]byte, error) {
switch config.Format {
case OutputFormatJSON:
return json.Marshal(data)
case OutputFormatYAML:
return yaml.Marshal(data)
case OutputFormatTable:
t := table.New()
t.For(data, "default")
return t.Flush()
case OutputFormatCondition:
t := table.New()
t.For(data, config.AdditionalField)
return t.Flush()
case OutputFormatField:
t := table.New()
t.Field(data, config.AdditionalField)
return t.Flush()
}
return nil, nil
}
func Register(of any, spec *Spec) {
fields := make(cache.Fields)
for c, condition := range *spec {
fields[c] = []cache.Entry{}
for _, e := range condition {
fields[c] = append(fields[c], cache.Entry{
Key: e.Key,
Field: e.Field,
})
}
}
cache.Set(reflect.TypeOf(of), fields)
}