-
Notifications
You must be signed in to change notification settings - Fork 258
/
Copy pathmarshal.go
244 lines (227 loc) · 6.02 KB
/
marshal.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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright (c) 2023, daeuniverse Organization <[email protected]>
*/
package config
import (
"bytes"
"fmt"
"reflect"
"strconv"
"strings"
"github.com/daeuniverse/dae/common"
"github.com/daeuniverse/dae/pkg/config_parser"
)
// Marshal assume all tokens should be legal, and does not prevent injection attacks.
func (c *Config) Marshal(indentSpace int) (b []byte, err error) {
m := Marshaller{
IndentSpace: indentSpace,
}
// Root.
v := reflect.ValueOf(*c)
t := v.Type()
for i := 0; i < v.NumField(); i++ {
k, ok := t.Field(i).Tag.Lookup("mapstructure")
if !ok {
return nil, fmt.Errorf("section %v misses tag mapstructure", t.Field(i).Name)
}
if err = m.MarshalSection(k, v.Field(i), 0); err != nil {
return nil, err
}
}
return m.buf.Bytes(), nil
}
type Marshaller struct {
IndentSpace int
IgnoreZero bool
buf bytes.Buffer
}
func (m *Marshaller) Bytes() []byte {
return m.buf.Bytes()
}
func (m *Marshaller) writeLine(depth int, line string) {
if depth < 0 {
depth = 0
}
m.buf.Write(bytes.Repeat([]byte{' '}, depth*m.IndentSpace))
m.buf.WriteString(line)
m.buf.WriteString("\n")
}
func (m *Marshaller) marshalStringList(from reflect.Value, depth int, keyable bool) (err error) {
for i := 0; i < from.Len(); i++ {
str := from.Index(i)
if keyable {
tag, afterTag := common.GetTagFromLinkLikePlaintext(str.String())
if len(tag) > 0 {
m.writeLine(depth, tag+":"+strconv.Quote(afterTag))
continue
}
}
m.writeLine(depth, strconv.Quote(str.String()))
}
return nil
}
func (m *Marshaller) MarshalSection(name string, from reflect.Value, depth int) (err error) {
m.writeLine(depth, name+" {")
defer m.writeLine(depth, "}")
switch from.Kind() {
case reflect.Slice:
elemType := from.Type().Elem()
switch elemType.Kind() {
case reflect.String:
keyable := false
switch elemType {
case reflect.TypeOf(KeyableString("")):
keyable = true
default:
}
if err = m.marshalStringList(from, depth+1, keyable); err != nil {
return err
}
return nil
case reflect.Struct:
// "from" is a section list (sections in section).
/**
from {
field1 {
...
}
field2 {
...
}
}
should be parsed from:
from []struct {
Name string `mapstructure: "_"`
...
}
*/
// The struct should contain Name.
nameStructField, ok := elemType.FieldByName("Name")
if !ok || nameStructField.Type.Kind() != reflect.String || nameStructField.Tag.Get("mapstructure") != "_" {
return fmt.Errorf("a string field \"Name\" with mapstructure:\"_\" is required in struct %v from parse section", from.Type().Elem().String())
}
// Scan sections.
for i := 0; i < from.Len(); i++ {
item := from.Index(i)
nameField := item.FieldByName("Name")
if nameField.Kind() != reflect.String {
return fmt.Errorf("name field of section should be string type")
}
if err = m.MarshalSection(nameField.String(), item, depth+1); err != nil {
return err
}
}
return nil
default:
goto unsupported
}
case reflect.Struct:
// Section.
return m.marshalParam(from, depth+1)
default:
goto unsupported
}
panic("code should not reach here")
unsupported:
return fmt.Errorf("unsupported section type %v", from.Type())
}
func (m *Marshaller) marshalLeaf(key string, from reflect.Value, depth int) (err error) {
if m.IgnoreZero && from.IsZero() {
// Do not marshal zero value.
return nil
}
switch from.Kind() {
case reflect.Slice:
if from.Len() == 0 {
return nil
}
switch from.Index(0).Interface().(type) {
case fmt.Stringer, string,
uint8, uint16, uint32, uint64,
int8, int16, int32, int64,
float32, float64,
bool:
var vals []string
for i := 0; i < from.Len(); i++ {
vals = append(vals, fmt.Sprintf("%v", from.Index(i).Interface()))
}
m.writeLine(depth, key+":"+strconv.Quote(strings.Join(vals, ",")))
case *config_parser.Function:
var vals []string
for i := 0; i < from.Len(); i++ {
v := from.Index(i).Interface().(*config_parser.Function)
vals = append(vals, v.String(true, true, false))
}
m.writeLine(depth, key+":"+strings.Join(vals, "&&"))
case KeyableString:
m.writeLine(depth, key+" {")
if err = m.marshalStringList(from, depth+1, true); err != nil {
return err
}
m.writeLine(depth, "}")
default:
return fmt.Errorf("unknown leaf array type: %v", from.Type())
}
default:
switch val := from.Interface().(type) {
case fmt.Stringer, string,
uint8, uint16, uint32, uint64,
int8, int16, int32, int64,
float32, float64, int,
bool:
m.writeLine(depth, key+":"+strconv.Quote(fmt.Sprintf("%v", val)))
case *config_parser.Function:
m.writeLine(depth, key+":"+val.String(true, true, false))
default:
return fmt.Errorf("unknown leaf type: %T", val)
}
}
return nil
}
func (m *Marshaller) marshalParam(from reflect.Value, depth int) (err error) {
if from.Kind() != reflect.Struct {
return fmt.Errorf("marshalParam can only marshal struct")
}
// Marshal section.
typ := from.Type()
for i := 0; i < from.NumField(); i++ {
field := from.Field(i)
structField := typ.Field(i)
key, ok := structField.Tag.Lookup("mapstructure")
if !ok {
return fmt.Errorf("tag mapstructure is required")
}
// Reserved field.
if key == "_" {
switch structField.Name {
case "Name":
case "Rules":
// Expand.
rules, ok := field.Interface().([]*config_parser.RoutingRule)
if !ok {
return fmt.Errorf("unexpected Rules type: %v", field.Type())
}
for _, r := range rules {
m.writeLine(depth, r.String(false, true, true))
}
default:
return fmt.Errorf("unknown reserved field: %v", structField.Name)
}
continue
}
// Section(s) field.
if field.Kind() == reflect.Struct || (field.Kind() == reflect.Slice &&
field.Type().Elem().Kind() == reflect.Struct) {
if err = m.MarshalSection(key, field, depth); err != nil {
return err
}
continue
}
// Normal field.
if err = m.marshalLeaf(key, field, depth); err != nil {
return err
}
}
return nil
}