forked from fybrik/crdoc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
builder.go
311 lines (265 loc) · 8.04 KB
/
builder.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
// Copyright 2021 IBM Corp.
// SPDX-License-Identifier: Apache-2.0
package builder
import (
"crypto/sha1"
"embed"
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
"strings"
"text/template"
"github.com/Masterminds/sprig/v3"
log "github.com/sirupsen/logrus"
"golang.org/x/exp/slices"
"k8s.io/apiextensions-apiserver/pkg/apis/apiextensions"
"github.com/travelping/crdoc/pkg/functions"
)
// ModelBuilder is the entry point for docs generation
type ModelBuilder struct {
Model *Model
Strict bool
TemplatesDirOrFile string
OutputFilepath string
keys map[string]int
builtinTemplates fs.FS
}
func NewModelBuilder(model *Model, strict bool, templatesDirOrFile string, outputFilepath string, builtinTemplates embed.FS) *ModelBuilder {
builder := &ModelBuilder{
Model: model,
Strict: strict,
TemplatesDirOrFile: templatesDirOrFile,
OutputFilepath: outputFilepath,
builtinTemplates: builtinTemplates,
}
builder.keys = make(map[string]int)
return builder
}
// Add adds a CustomResourceDefinition to the model
func (b *ModelBuilder) Add(crd *apiextensions.CustomResourceDefinition) error {
// Add chapter for each version
for _, version := range crd.Spec.Versions {
group := crd.Spec.Group
gv := fmt.Sprintf("%s/%s", group, version.Name)
kind := crd.Spec.Names.Kind
// Find matching group/version
groupModel := b.Model.findGroupModel(group, version.Name)
if groupModel == nil {
if b.Strict {
log.Warn(fmt.Sprintf("group/version not found in TOC: %s", gv))
continue
}
groupModel = &GroupModel{
Group: group,
Version: version.Name,
}
b.Model.Groups = append(b.Model.Groups, groupModel)
}
// Find matching kind
kindModel := groupModel.findKindModel(kind)
if kindModel == nil {
if b.Strict {
log.Warn(fmt.Sprintf("group/version/kind not found in TOC: %s/%s", gv, kind))
continue
}
kindModel = &KindModel{
Name: kind,
}
groupModel.Kinds = append(groupModel.Kinds, kindModel)
}
// Find schema
validation := version.Schema
if validation == nil {
// Fallback to resource level schema
validation = crd.Spec.Validation
}
if validation == nil {
return errors.New("missing validation field in input CRD")
}
schema := validation.OpenAPIV3Schema
// Recusively add type models
_, _ = b.addTypeModels(groupModel, kindModel, kind, schema, true)
}
return nil
}
type mapKey struct {
Name string
DescHash string
}
// First 7 chars of a hash of s.
func hash(s string) string {
return fmt.Sprintf("%x", sha1.Sum([]byte(s)))[:7]
}
func (b *ModelBuilder) deduplicateTypeModels() {
for _, group := range b.Model.Groups {
group := group
for _, kinds := range group.Kinds {
kinds := kinds
modelsMap := make(map[mapKey]*TypeModel)
for idxTypes, typeModel := range kinds.Types {
typeModel := typeModel
curKey := mapKey{Name: typeModel.Name, DescHash: hash(typeModel.Description)}
if _, ok := modelsMap[curKey]; ok {
// Model already exists. Add the parent if not already added and continue.
for _, key := range typeModel.Parents {
if !slices.Contains(modelsMap[curKey].Parents, key) {
modelsMap[curKey].Parents = append(modelsMap[curKey].Parents, Parent{Key: key.Key, Name: key.Name})
}
}
continue
}
// Model didn't yet exist in our unique Models map, add it now.
typeModel.Order = idxTypes
modelsMap[curKey] = typeModel
}
// Remove old Models with duplicates
kinds.Types = nil
// Re-add the unique ones
for idx := range modelsMap {
kinds.Types = append(kinds.Types, modelsMap[idx])
}
slices.SortFunc(kinds.Types, func(a, b *TypeModel) bool {
return a.Order < b.Order
})
}
}
}
// Output writes markdown to the output direcory
func (b *ModelBuilder) Output() error {
b.deduplicateTypeModels()
outputFilepath := filepath.Clean(b.OutputFilepath)
// create dirs if needed
err := os.MkdirAll(filepath.Dir(outputFilepath), os.ModePerm)
if err != nil {
return err
}
// create the file
f, err := os.Create(outputFilepath)
if err != nil {
return err
}
defer func() {
if err := f.Close(); err != nil {
log.Errorf("Error closing file: %s\n", err)
}
}()
// Values for embedded templates
templatesFs := b.builtinTemplates
pattern := "templates/**.tmpl"
dir, file := filepath.Split(b.TemplatesDirOrFile)
if dir != "" {
// Override to take extenal template
templatesFs = os.DirFS(dir)
pattern = "**.tmpl"
}
return template.Must(template.New(file).
Funcs(sprig.TxtFuncMap()).
Funcs(functions.ExportedMap).
ParseFS(templatesFs, pattern)).
Execute(f, *b.Model)
}
// Adjust the names in form of `parent.other.parent.type` to only `type`
// and remove the array indicator from the name.
func concise(name string) string {
idx := strings.LastIndex(name, ".")
if idx >= 0 {
name = name[idx+1:]
}
name = strings.TrimSuffix(name, "[]")
return name
}
// Return the number of markdown headings (#) by counting the dots from the full name.
func headings(name string) string {
count := strings.Count(name, ".")
return strings.Repeat("#", count)
}
func (b *ModelBuilder) addTypeModels(groupModel *GroupModel, kindModel *KindModel, name string, schema *apiextensions.JSONSchemaProps, isTopLevel bool) (string, *TypeModel) {
typeName := getTypeName(schema)
if typeName == "object" && schema.Properties != nil {
// Create an object type model
typeModel := &TypeModel{
Name: concise(name),
Key: concise(name) + "-" + hash(schema.Description),
Description: schema.Description,
IsTopLevel: isTopLevel,
Headings: headings(name),
}
kindModel.Types = append(kindModel.Types, typeModel)
// For each field
for _, fieldName := range orderedPropertyKeys(schema.Required, schema.Properties, isTopLevel) {
property := getEnrichedProperty(schema, fieldName)
fieldFullname := strings.Join([]string{name, fieldName}, ".")
fieldTypename, fieldTypeModel := b.addTypeModels(groupModel, kindModel, fieldFullname, &property, false)
var fieldTypeKey *string = nil
if fieldTypeModel != nil {
fieldTypeKey = &fieldTypeModel.Key
fieldTypeModel.Parents = append(fieldTypeModel.Parents, Parent{Name: typeModel.Name, Key: typeModel.Key})
}
fieldDescription := property.Description
// Create field model
fieldModel := &FieldModel{
Name: fieldName,
Type: fieldTypename,
TypeKey: fieldTypeKey,
Description: fieldDescription,
Required: containsString(fieldName, schema.Required),
Schema: property,
}
typeModel.Fields = append(typeModel.Fields, fieldModel)
}
return typeName, typeModel
} else if typeName == "[]" {
childTypeName, childTypeModel := b.addTypeModels(groupModel, kindModel,
fmt.Sprintf("%s[]", name), schema.Items.Schema, false)
return "[]" + childTypeName, childTypeModel
} else if typeName == "map[string]" {
childTypeName, childTypeModel := b.addTypeModels(groupModel, kindModel,
fmt.Sprintf("%s[key]", name), schema.AdditionalProperties.Schema, false)
return "map[string]" + childTypeName, childTypeModel
}
return typeName, nil
}
func (b *ModelBuilder) createKey(name string) string {
key := functions.Anchorize(name)
if value, exists := b.keys[key]; exists {
value++
key = fmt.Sprintf("%s-%d", key, value)
} else {
b.keys[key] = 0
}
return key
}
func getTypeName(props *apiextensions.JSONSchemaProps) string {
if props.XIntOrString {
return "int or string"
}
if props.XEmbeddedResource {
return "RawExtension"
}
if props.Type == "" && props.XPreserveUnknownFields != nil {
return "JSON"
}
if props.Type == "string" && props.Enum != nil && len(props.Enum) > 0 {
return "enum"
}
if props.Format != "" && props.Type == "byte" {
return "[]byte"
}
// map
if props.Type == "object" && props.AdditionalProperties != nil {
if props.AdditionalProperties.Schema == nil && props.AdditionalProperties.Allows {
return "map[string]string"
}
return "map[string]"
}
// array
if props.Type == "array" {
if props.Items == nil {
return "[]object"
}
return "[]"
}
return props.Type
}