-
Notifications
You must be signed in to change notification settings - Fork 7
/
codec.go
180 lines (170 loc) · 5.78 KB
/
codec.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
package jennies
import (
"bytes"
"encoding/json"
"fmt"
"go/format"
"slices"
"strings"
"time"
"cuelang.org/go/cue"
"github.com/grafana/codejen"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
"github.com/grafana/grafana-app-sdk/codegen"
"github.com/grafana/grafana-app-sdk/codegen/jennies"
"github.com/grafana/grafana-app-sdk/codegen/templates"
)
// slightly janky dynamic way of getting the JSON keys of all CommonMetadata fields,
// so they don't need to be hard-coded in the Jenny, and can sync with kindsys
var (
tmnow = metav1.NewTime(time.Now())
i64 = int64(1)
commonMetadataBytes, _ = json.Marshal(metav1.ObjectMeta{
Name: "foo",
GenerateName: "bar",
Namespace: "foo",
SelfLink: "bar",
UID: types.UID("foo"),
ResourceVersion: "bar",
Generation: i64,
CreationTimestamp: tmnow,
DeletionTimestamp: &tmnow,
DeletionGracePeriodSeconds: &i64,
Labels: map[string]string{"foo": "bar"},
Annotations: map[string]string{"foo": "bar"},
OwnerReferences: []metav1.OwnerReference{{}},
Finalizers: []string{"foo"},
ManagedFields: []metav1.ManagedFieldsEntry{{}},
})
commonMetadataFieldMap = map[string]any{
"extraFields": struct{}{}, // This needs to be ignored but is currently joined in in kindsys
}
_ = json.Unmarshal(commonMetadataBytes, &commonMetadataFieldMap)
)
type CodecGenerator struct {
// This flag exists for compatibility with thema codegen, which only generates code for the current/latest version of the kind
OnlyUseCurrentVersion bool
}
func (*CodecGenerator) JennyName() string {
return "ThemaCodecGenerator"
}
func (r *CodecGenerator) Generate(kind codegen.Kind) (codejen.Files, error) {
files := make(codejen.Files, 0)
if r.OnlyUseCurrentVersion {
ver := kind.Version(kind.Properties().Current)
if ver == nil {
return nil, fmt.Errorf("no version for %s", kind.Properties().Current)
}
b, err := r.generateObjectFile(kind, ver, strings.ToLower(kind.Properties().MachineName))
if err != nil {
return nil, err
}
files = append(files, codejen.File{
RelativePath: fmt.Sprintf("%s/%s_codec_gen.go", kind.Properties().MachineName, kind.Properties().MachineName),
Data: b,
From: []codejen.NamedJenny{r},
})
} else {
allVersions := kind.Versions()
for i := 0; i < len(allVersions); i++ {
ver := allVersions[i]
b, err := r.generateObjectFile(kind, &ver, jennies.ToPackageName(ver.Version))
if err != nil {
return nil, err
}
files = append(files, codejen.File{
RelativePath: fmt.Sprintf("%s/%s/%s_codec_gen.go", kind.Properties().MachineName, jennies.ToPackageName(ver.Version), kind.Properties().MachineName),
Data: b,
From: []codejen.NamedJenny{r},
})
}
}
return files, nil
}
func (*CodecGenerator) generateObjectFile(kind codegen.Kind, version *codegen.KindVersion, pkg string) ([]byte, error) {
customMetadataFields := make([]templates.ObjectMetadataField, 0)
mdv := version.Schema.LookupPath(cue.MakePath(cue.Str("metadata")))
if mdv.Exists() {
mit, err := mdv.Fields()
if err != nil {
return nil, err
}
for mit.Next() {
lbl := mit.Selector().String()
// Skip the common metadata fields
if _, ok := commonMetadataFieldMap[lbl]; ok {
continue
}
fieldName := ""
// The go field name is the CUE label with the first letter capitalized (to make it exported)
// We have to track the actual field names of all custom metadata fields for the template
if len(lbl) > 1 {
fieldName = strings.ToUpper(lbl[0:1]) + lbl[1:]
} else {
fieldName = strings.ToUpper(lbl)
}
customMetadataFields = append(customMetadataFields, templates.ObjectMetadataField{
JSONName: lbl,
FieldName: fieldName,
GoType: goTypeFromCUEValue(mit.Value()),
})
}
}
// Sort extra fields so that codegen is deterministic for ordering
slices.SortFunc(customMetadataFields, func(a, b templates.ObjectMetadataField) int {
return strings.Compare(a.FieldName, b.FieldName)
})
meta := kind.Properties()
md := templates.ResourceObjectTemplateMetadata{
Package: pkg,
TypeName: meta.Kind,
SpecTypeName: "Spec",
ObjectTypeName: meta.Kind,
ObjectShortName: "o",
Subresources: make([]templates.SubresourceMetadata, 0),
CustomMetadataFields: customMetadataFields,
}
it, err := version.Schema.Fields()
if err != nil {
return nil, err
}
for it.Next() {
if it.Label() == "spec" || it.Label() == "metadata" {
continue
}
md.Subresources = append(md.Subresources, templates.SubresourceMetadata{
TypeName: exportField(it.Label()),
JSONName: it.Label(),
})
}
b := bytes.Buffer{}
err = templates.WriteThemaCodec(md, &b)
if err != nil {
return nil, err
}
formatted, err := format.Source(b.Bytes())
if err != nil {
return nil, err
}
return formatted, nil
}
// nolint:gocritic
func goTypeFromCUEValue(value cue.Value) templates.CustomMetadataFieldGoType {
// Super janky for now--there's _got_ to be a better way of determining the type for a definition field
// Maybe we take it from openapi instead?
st := cueFmtState{}
value.Format(&st, 'v')
typeString := st.String()
if strings.Contains(typeString, "time.Time") {
return templates.GoTypeTime
} else if strings.Contains(typeString, "int") {
return templates.GoTypeInt
} else if strings.Contains(typeString, "struct") {
// TODO--once we allow non-string types, we need to be able to reference them here
return templates.GoTypeString
} else if strings.Contains(typeString, "string") {
return templates.GoTypeString
}
return templates.CustomMetadataFieldGoType{}
}