File size: 5,672 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
package main

import (
	"flag"
	"fmt"
	"os"
	"reflect"
	"strconv"
	"strings"
	"text/template"

	"github.com/target/goalert/config"
)

func hasType(typeName string, fields []field) bool {
	for _, f := range fields {
		if f.Type == typeName {
			return true
		}
	}
	return false
}

var tmpl = template.Must(
	template.
		New("mapconfig.go").
		Funcs(template.FuncMap{
			"quote":      strconv.Quote,
			"hasBool":    func(fields []field) bool { return hasType("ConfigTypeBoolean", fields) },
			"hasStrList": func(fields []field) bool { return hasType("ConfigTypeStringList", fields) },
			"hasInt":     func(fields []field) bool { return hasType("ConfigTypeInteger", fields) },
		}).
		Parse(`
import (
	"github.com/target/goalert/config"
	"github.com/target/goalert/validation"
)

func MapConfigHints(cfg config.Hints) []ConfigHint {
	return []ConfigHint{
		{{- range .HintFields }}
		{ID: {{quote .ID}}, Value: {{.Value}}},
		{{- end}}
	}
}

// MapConfigValues will map a Config struct into a flat list of ConfigValue structs.
func MapConfigValues(cfg config.Config) []ConfigValue {
	return []ConfigValue{
		{{- range .ConfigFields }}
		{ID: {{quote .ID}}, Type: {{.Type}}, Description: {{quote .Desc}}, Value: {{.Value}}{{if .Password}}, Password: true{{end}}{{if .Dep}}, Deprecated: {{quote .Dep}}{{end}}},
		{{- end}}
	}
}

// MapPublicConfigValues will map a Config struct into a flat list of ConfigValue structs.
func MapPublicConfigValues(cfg config.Config) []ConfigValue {
	return []ConfigValue{
		{{- range .ConfigFields }}
		{{- if .Public}}
		{ID: {{quote .ID}}, Type: {{.Type}}, Description: {{quote .Desc}}, Value: {{.Value}}{{if .Password}}, Password: true{{end}}{{if .Dep}}, Deprecated: {{quote .Dep}}{{end}}},
		{{- end}}
		{{- end}}
	}
}

// ApplyConfigValues will apply a list of ConfigValues to a Config struct.
func ApplyConfigValues(cfg config.Config, vals []ConfigValueInput) (config.Config, error) {
	{{- if hasStrList .ConfigFields}}
	parseStringList := func(v string) []string {
		if v == "" {
			return nil
		}
		return strings.Split(v, "\n")
	}
	{{- end}}
	{{- if hasInt .ConfigFields}}
	parseInt := func(id, v string) (int, error) {
		if v == "" {
			return 0, nil
		}
		val, err := strconv.ParseInt(v, 10, 32)
		if err != nil {
			return 0, validation.NewFieldError("\""+id+"\".Value", "integer value invalid: " + err.Error())
		}
		return int(val), nil
	}
	{{- end}}
	{{- if hasBool .ConfigFields}}
	parseBool := func(id, v string) (bool, error) {
		switch v {
		case "true":
			return true, nil
		case "false":
			return false, nil
		default:
			return false, validation.NewFieldError("\""+id+"\".Value", "boolean value invalid: expected 'true' or 'false'")
		}
	}
	{{- end}}
	for _, v := range vals {
		switch v.ID {
		{{- range .ConfigFields}}
		case {{quote .ID}}:
			{{- if eq .Type "ConfigTypeString"}}
			cfg.{{.ID}} = v.Value
			{{- else if eq .Type "ConfigTypeStringList"}}
			cfg.{{.ID}} = parseStringList(v.Value)
			{{- else if eq .Type "ConfigTypeInteger"}}
			val, err := parseInt(v.ID, v.Value)
			if err != nil {
				return cfg, err
			}
			cfg.{{.ID}} = val
			{{- else if eq .Type "ConfigTypeBoolean"}}
			val, err := parseBool(v.ID, v.Value)
			if err != nil {
				return cfg, err
			}
			cfg.{{.ID}} = val
			{{- end}}
		{{- end}}
		default:
			return cfg, validation.NewFieldError("ID", fmt.Sprintf("unknown config ID '%s'", v.ID))
		}
	}
	return cfg, nil
}
`))

type field struct {
	ID, Type, Desc, Value, Dep string
	Public, Password           bool
}

func main() {
	out := flag.String("out", "", "Output file.")
	flag.Parse()

	w := os.Stdout
	if *out != "" {
		fd, err := os.Create(*out)
		if err != nil {
			panic(err)
		}
		defer fd.Close()
		w = fd
	}

	_, err := fmt.Fprintln(w, `// Code generated by devtools/configparams DO NOT EDIT.

package graphql2`)
	if err != nil {
		panic(err)
	}

	var input struct {
		ConfigFields []field
		HintFields   []field
	}
	input.ConfigFields = printType("", reflect.TypeOf(config.Config{}), "", "", false, false)
	input.HintFields = printType("", reflect.TypeOf(config.Hints{}), "", "", false, false)

	err = tmpl.Execute(w, input)
	if err != nil {
		panic(err)
	}
}

func printField(prefix string, f reflect.StructField) []field {
	fPrefix := prefix + f.Name + "."
	if f.Type.Kind() == reflect.Slice && f.Type.Elem().Kind() == reflect.Struct {
		fPrefix = prefix + f.Name + "[]."
	}
	return printType(fPrefix, f.Type, f.Tag.Get("info"), f.Tag.Get("deprecated"), f.Tag.Get("public") == "true", f.Tag.Get("password") == "true")
}

func printType(prefix string, v reflect.Type, details, dep string, public, pass bool) []field {
	var f []field
	key := strings.TrimSuffix(prefix, ".")

	var typ, value string
	switch v.Kind() {
	case reflect.Struct:
		for i := 0; i < v.NumField(); i++ {
			if v.Field(i).PkgPath != "" {
				// skip unexported fields
				continue
			}
			f = append(f, printField(prefix, v.Field(i))...)
		}
		return f
	case reflect.Bool:
		typ = "ConfigTypeBoolean"
		value = fmt.Sprintf(`fmt.Sprintf("%%t", cfg.%s)`, key)
	case reflect.String:
		typ = "ConfigTypeString"
		value = fmt.Sprintf(`cfg.%s`, key)
	case reflect.Int:
		typ = "ConfigTypeInteger"
		value = fmt.Sprintf(`fmt.Sprintf("%%d", cfg.%s)`, key)
	case reflect.Slice:
		switch v.Elem().Kind() {
		case reflect.String:
			typ = "ConfigTypeStringList"
			value = fmt.Sprintf(`strings.Join(cfg.%s, "\n")`, key)
		default:
			panic(fmt.Sprintf("not implemented for type []%v", v.Elem().Kind()))
		}
	default:
		panic(fmt.Sprintf("not implemented for type %T", v.Kind()))
	}

	f = append(f, field{ID: key, Type: typ, Desc: details, Dep: dep, Value: value, Public: public, Password: pass})
	return f
}