forked from micromdm/mdm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenerate_marshaler_code.go
117 lines (101 loc) · 2.25 KB
/
generate_marshaler_code.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
// +build ignore
package main
import (
"bytes"
"flag"
"html/template"
"io/ioutil"
"log"
"reflect"
"golang.org/x/tools/imports"
"github.com/micromdm/mdm"
)
func main() {
out := flag.String("out", "marshaler.go", "path to output file")
flag.Parse()
pbytes := generateMarshalPlist()
jbytes := generateUnmarshalJSON()
var buf bytes.Buffer
buf.Write(pbytes)
buf.Write([]byte("\n"))
buf.Write(jbytes)
pretty, err := imports.Process("", buf.Bytes(), nil)
if err != nil {
log.Fatal(err)
}
ioutil.WriteFile(*out, pretty, 0644)
}
const plistStub = `
// generated by go:generate, DO NOT EDIT
package mdm
func (c *Command) MarshalPlist() (interface{}, error) {
switch c.RequestType {
case "ProfileList",
"ProvisioningProfileList",
"CertificateList",
"SecurityInfo",
"StopMirroring",
"ClearRestrictionsPassword",
"UserList",
"LogOutUser",
"DisableLostMode",
"DeviceLocation",
"ManagedMediaList",
"OSUpdateStatus",
"DeviceConfigured",
"AvailableOSUpdates",
"Restrictions",
"ShutDownDevice",
"RestartDevice":
return &struct {
RequestType string
}{
RequestType: c.RequestType,
}, nil
{{ range .}}
case "{{.Case}}":
return &struct {
RequestType string
{{.Case}}
}{
RequestType: c.RequestType,
{{.Case}}: c.{{.Case}},
}, nil
{{end}}
default:
return nil, fmt.Errorf("unknown request type: %s", c.RequestType)
}
}
`
func generateMarshalPlist() []byte {
type param struct {
Case string
}
var params []param
val := reflect.ValueOf(mdm.Command{})
for i := 1; i < val.NumField(); i++ {
name := val.Field(i).Type().Name()
params = append(params, param{Case: name})
}
var tmpl = template.Must(template.New("test").Parse(plistStub))
var buf bytes.Buffer
tmpl.Execute(&buf, params)
return buf.Bytes()
}
func generateUnmarshalJSON() []byte {
type param struct {
Case string
}
var params []param
val := reflect.ValueOf(mdm.Command{})
for i := 1; i < val.NumField(); i++ {
name := val.Field(i).Type().Name()
params = append(params, param{Case: name})
}
var tmpl = template.Must(template.New("").ParseFiles("marshal_json.template"))
var buf bytes.Buffer
if err := tmpl.ExecuteTemplate(&buf, "marshal_json.template", params); err != nil {
log.Fatal(err)
}
return buf.Bytes()
}