-
-
Notifications
You must be signed in to change notification settings - Fork 17
/
app.go
356 lines (310 loc) · 10.3 KB
/
app.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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
package main
import (
"bytes"
"errors"
"fmt"
"net/http"
"net/url"
"sort"
"strconv"
"strings"
"github.com/Skarlso/crd-to-sample-yaml/pkg/fetcher"
"github.com/maxence-charriere/go-app/v10/pkg/app"
"k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1"
"k8s.io/apimachinery/pkg/util/yaml"
"github.com/Skarlso/crd-to-sample-yaml/pkg"
)
// crdView is the main component to display a rendered CRD.
type crdView struct {
app.Compo
preRenderErr error
content []byte
comment bool
}
// Version wraps a top level version resource which contains the underlying openAPIV3Schema.
type Version struct {
Version string
Kind string
Group string
Properties []*Property
Description string
YAML string
}
// Property builds up a Tree structure of embedded things.
type Property struct {
Name string
Description string
Type string
Nullable bool
Patterns string
Format string
Indent int
Version string
Default string
Required bool
Properties []*Property
}
func (h *crdView) buildError(err error) app.UI {
return app.Div().Class("alert alert-danger").Role("alert").Body(
app.Span().Class("closebtn").Body(app.Text("×")),
app.H4().Class("alert-heading").Text("Oops!"),
app.Text(err.Error()))
}
func (h *crdView) OnNav(ctx app.Context) {
if !strings.Contains(ctx.Page().URL().String(), "share") {
return
}
u := ctx.Page().URL().Query().Get("url")
if u == "" {
h.preRenderErr = errors.New(
"url parameter has to be define in the following format: " +
"/share?url=https://example.com/crd.yaml")
return
}
if _, err := url.Parse(u); err != nil {
h.preRenderErr = fmt.Errorf("invald url provided in query: %w", err)
return
}
f := fetcher.NewFetcher(http.DefaultClient)
content, err := f.Fetch(u)
if err != nil {
h.preRenderErr = err
return
}
h.content = content
}
// The Render method is where the component appearance is defined. Here, a
// "Hello World!" is displayed as a heading.
func (h *crdView) Render() app.UI {
if h.preRenderErr != nil {
return h.buildError(h.preRenderErr)
}
crd := &v1beta1.CustomResourceDefinition{}
if err := yaml.Unmarshal(h.content, crd); err != nil {
return h.buildError(err)
}
versions := make([]Version, 0)
parser := pkg.NewParser(crd.Spec.Group, crd.Spec.Names.Kind, h.comment, false)
for _, version := range crd.Spec.Versions {
out, err := parseCRD(version.Schema.OpenAPIV3Schema.Properties, version.Name, pkg.RootRequiredFields)
if err != nil {
return h.buildError(err)
}
var buffer []byte
buf := bytes.NewBuffer(buffer)
if err := parser.ParseProperties(version.Name, buf, version.Schema.OpenAPIV3Schema.Properties, pkg.RootRequiredFields); err != nil {
return h.buildError(err)
}
versions = append(versions, Version{
Version: version.Name,
Properties: out,
Kind: crd.Spec.Names.Kind,
Group: crd.Spec.Group,
Description: version.Schema.OpenAPIV3Schema.Description,
YAML: buf.String(),
})
}
wrapper := app.Div().Class("content-wrapper")
container := app.Div().Class("container")
container.Body(app.Range(versions).Slice(func(i int) app.UI {
div := app.Div().Class("versions")
version := versions[i]
yamlContent := app.Div().Class("accordion").ID("yaml-accordion-" + version.Version).Body(
app.Div().Class("accordion-item").Body(
app.H2().Class("accordion-header").Body(
app.Div().Class("container").Body(app.Div().Class("row").Body(
app.Div().Class("col").Body(
app.Button().Class("accordion-button").Type("button").DataSets(
map[string]any{
"bs-toggle": "collapse",
"bs-target": "#yaml-accordion-collapse-" + version.Version,
}).
Aria("expanded", "false").
Aria("controls", "yaml-accordion-collapse-"+version.Version).
Body(app.Text("Details")),
),
app.Div().Class("col").Body(
app.Button().Class("clippy-"+strconv.Itoa(i)).DataSet("clipboard-target", "#yaml-sample-"+version.Version).Body(
app.Script().Text(fmt.Sprintf("new ClipboardJS('.clippy-%d');", i)),
app.I().Class("fa fa-clipboard"),
),
),
)),
),
app.Div().Class("accordion-collapse collapse").ID("yaml-accordion-collapse-"+version.Version).DataSet("bs-parent", "#yaml-accordion-"+version.Version).Body(
app.Div().Class("accordion-body").Body(
app.Pre().Body(
app.Code().Class("language-yaml").ID("yaml-sample-"+version.Version).Body(
app.Text(version.YAML),
)),
),
),
),
)
div.Body(
app.H1().Body(
app.P().Body(app.Text(fmt.Sprintf(
`Version: %s/%s`,
version.Group,
version.Version,
))),
app.P().Body(app.Text("Kind: "+version.Kind))),
app.P().Body(app.Text(version.Description)),
app.P().Body(app.Text("Generated YAML sample:")),
yamlContent,
app.H1().Text(version.Version),
app.Div().Class("accordion").ID("version-accordion-"+version.Version).Body(
render(app.Div().Class("accordion-item"), version.Properties, "version-accordion-"+version.Version, 0),
),
)
return div
}))
return wrapper.Body(
app.Script().Src("https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-core.min.js"),
app.Script().Src("https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/plugins/autoloader/prism-autoloader.min.js"),
container,
)
}
var borderOpacity = map[int]string{
0: "border border-secondary-subtle",
1: "border border-secondary-subtle border-opacity-75",
2: "border border-secondary-subtle border-opacity-50",
3: "border border-secondary-subtle border-opacity-25",
4: "border border-secondary-subtle border-opacity-10",
}
func render(d app.UI, p []*Property, accordionID string, depth int) app.UI {
borderOpacity, ok := borderOpacity[depth]
if !ok {
borderOpacity = ""
}
elements := make([]app.UI, 0, len(p))
for _, prop := range p {
// add the parent first
headerElements := []app.UI{
app.Div().Class("col").Body(app.Text(prop.Name)),
app.Div().Class("text-muted col").Text(prop.Type),
}
if prop.Required {
headerElements = append(headerElements, app.Div().Class("text-bg-primary").Class("col").Text("required"))
}
if prop.Format != "" {
headerElements = append(headerElements, app.Div().Class("col").Text(prop.Format))
}
if prop.Default != "" {
headerElements = append(headerElements, app.Div().Class("col").Text(prop.Default))
}
if prop.Patterns != "" {
headerElements = append(headerElements, app.Div().Class("col").Class("fst-italic").Text(prop.Patterns))
}
headerContainer := app.Div().Class("container").Body(
// Both rows are important here to produce the desired outcome.
app.Div().Class("row").Body(
app.P().Class("fw-bold").Class("row").Body(
headerElements...,
),
app.Div().Class("row").Class("text-break").Body(app.Text(prop.Description)),
),
)
targetID := "accordion-collapse-for-" + prop.Name + accordionID
button := app.Button().ID("accordion-button-id-"+prop.Name+accordionID).Class("accordion-button").Type("button").DataSets(
map[string]any{
"bs-toggle": "collapse",
"bs-target": "#" + targetID, // the # is important
}).
Aria("expanded", "false").
Aria("controls", targetID).
Body(
headerContainer,
)
if len(prop.Properties) != 0 {
button.Class("bg-success-subtle")
}
header := app.H2().Class("accordion-header").Class(borderOpacity).Body(button)
elements = append(elements, header)
// The next section can be skipped if there are no child properties.
if len(prop.Properties) == 0 {
continue
}
accordionDiv := app.Div().Class("accordion-collapse collapse").ID(targetID).DataSet("bs-parent", "#"+accordionID)
accordionBody := app.Div().Class("accordion-body")
var bodyElements []app.UI
// add any children that the parent has
if len(prop.Properties) > 0 {
element := render(app.Div().ID(prop.Name).Class("accordion-item"), prop.Properties, targetID, depth+1)
bodyElements = append(bodyElements, element)
}
accordionBody.Body(bodyElements...)
accordionDiv.Body(accordionBody)
elements = append(elements, accordionDiv)
}
// add all the elements and return the div
//nolint: gocritic // type switch
switch t := d.(type) {
case app.HTMLDiv:
t.Body(elements...)
d = t
}
return d
}
// parseCRD takes the properties and constructs a linked list out of the embedded properties that the recursive
// template can call and construct linked divs.
func parseCRD(properties map[string]v1beta1.JSONSchemaProps, version string, requiredList []string) ([]*Property, error) {
sortedKeys := make([]string, 0, len(properties))
output := make([]*Property, 0, len(properties))
for k := range properties {
sortedKeys = append(sortedKeys, k)
}
sort.Strings(sortedKeys)
for _, k := range sortedKeys {
// Create the Property with the values necessary.
// Check if there are properties for it in Properties or in Array -> Properties.
// If yes, call parseCRD and add the result to the created properties Properties list.
// If not, or if we are done, add this new property to the list of properties and return it.
v := properties[k]
required := false
for _, item := range requiredList {
if item == k {
required = true
break
}
}
p := &Property{
Name: k,
Type: v.Type,
Description: v.Description,
Patterns: v.Pattern,
Format: v.Format,
Nullable: v.Nullable,
Version: version,
Required: required,
}
if v.Default != nil {
p.Default = string(v.Default.Raw)
}
switch {
case len(properties[k].Properties) > 0 && properties[k].AdditionalProperties == nil:
requiredList = v.Required
out, err := parseCRD(properties[k].Properties, version, requiredList)
if err != nil {
return nil, err
}
p.Properties = out
case properties[k].Type == "array" && properties[k].Items.Schema != nil && len(properties[k].Items.Schema.Properties) > 0:
requiredList = v.Required
out, err := parseCRD(properties[k].Items.Schema.Properties, version, requiredList)
if err != nil {
return nil, err
}
p.Properties = out
case properties[k].AdditionalProperties != nil:
requiredList = v.Required
out, err := parseCRD(properties[k].AdditionalProperties.Schema.Properties, version, requiredList)
if err != nil {
return nil, err
}
p.Properties = out
}
output = append(output, p)
}
return output, nil
}