forked from kubernetes/autoscaler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvpa-generate-flags.go
282 lines (241 loc) · 7.32 KB
/
vpa-generate-flags.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
/*
Copyright 2024 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
"bytes"
"fmt"
"go/ast"
"go/parser"
"go/token"
"io"
"log"
"os"
"path/filepath"
"sort"
"strings"
"text/template"
"time"
)
type flagInfo struct {
Name string
DefaultValue string
Type string
Description string
SourceFile string
}
type templateData struct {
Flags []flagInfo
Timestamp string
}
var componentTemplates = map[string]string{
"recommender": `# What are the parameters to VPA recommender?
This document is auto-generated from the flag definitions in the VPA recommender code.
Last updated: {{ .Timestamp }}
| Flag | Type | Default | Description |
|------|------|---------|-------------|
{{- range .Flags }}
| --{{ .Name }} | {{ .Type }} | {{ .DefaultValue }} | {{ .Description }} |
{{- end }}
`,
"updater": `# What are the parameters to VPA updater?
This document is auto-generated from the flag definitions in the VPA updater code.
Last updated: {{ .Timestamp }}
| Flag | Type | Default | Description |
|------|------|---------|-------------|
{{- range .Flags }}
| --{{ .Name }} | {{ .Type }} | {{ .DefaultValue }} | {{ .Description }} |
{{- end }}
`,
"admission": `# What are the parameters to VPA admission controller?
This document is auto-generated from the flag definitions in the VPA admission controller code.
Last updated: {{ .Timestamp }}
| Flag | Type | Default | Description |
|------|------|---------|-------------|
{{- range .Flags }}
| --{{ .Name }} | {{ .Type }} | {{ .DefaultValue }} | {{ .Description }} |
{{- end }}
`,
}
func main() {
if len(os.Args) != 3 {
fmt.Println("Generates markdown documentation for VPA recommender flags.")
fmt.Println("usage: vpa-recommender-generate-flags <source-dir> <output-file>")
fmt.Println(" <source-dir> - Path to the directory containing the Go source files")
fmt.Println(" <output-file> - Path to the output markdown file")
os.Exit(1)
}
sourceDir := os.Args[1]
outputFile := os.Args[2]
flags, err := collectFlags(sourceDir)
if err != nil {
log.Fatalf("Error collecting flags: %v", err)
}
sort.Slice(flags, func(i, j int) bool {
return flags[i].Name < flags[j].Name
})
err = generateDocs(flags, outputFile)
if err != nil {
log.Fatalf("Error generating documentation: %v", err)
}
fmt.Println("Successfully generated documentation in", outputFile)
}
func extractFlagFromCall(call *ast.CallExpr, sourcePath string) *flagInfo {
if len(call.Args) < 3 {
return nil
}
// Extract flag name
nameArg, ok := call.Args[0].(*ast.BasicLit)
if !ok {
return nil
}
name := strings.Trim(nameArg.Value, "\"")
// Extract default value
var defaultValue string
switch v := call.Args[1].(type) {
case *ast.BasicLit:
defaultValue = strings.Trim(v.Value, "\"")
case *ast.BinaryExpr:
// Handle Duration expressions like "1*time.Minute"
if lit, ok := v.X.(*ast.BasicLit); ok {
if sel, ok := v.Y.(*ast.SelectorExpr); ok {
if ident, ok := sel.X.(*ast.Ident); ok && ident.Name == "time" {
number := strings.Trim(lit.Value, "\"")
unit := sel.Sel.Name
defaultValue = fmt.Sprintf("%s%s", number, unit)
}
}
}
case *ast.UnaryExpr:
// Handle negative numbers
if lit, ok := v.X.(*ast.BasicLit); ok {
defaultValue = fmt.Sprintf("%s%s", v.Op.String(), lit.Value)
}
case *ast.Ident:
defaultValue = v.Name
case *ast.SelectorExpr:
// Handle references to constants like "model.DefaultMemoryAggregationInterval"
if x, ok := v.X.(*ast.Ident); ok {
defaultValue = fmt.Sprintf("%s.%s", x.Name, v.Sel.Name)
}
default:
// Instead of defaulting to "0", make it clear this is a reference
defaultValue = fmt.Sprintf("${%T}", v)
}
// Extract description
descArg, ok := call.Args[2].(*ast.BasicLit)
if !ok {
return nil
}
description := strings.Trim(descArg.Value, "\"")
description = strings.ReplaceAll(description, "\n\t\t", " ")
description = strings.ReplaceAll(description, "\n", " ")
description = strings.TrimSpace(description)
return &flagInfo{
Name: name,
DefaultValue: defaultValue,
Type: call.Fun.(*ast.SelectorExpr).Sel.Name,
Description: description,
SourceFile: sourcePath,
}
}
func collectFlags(sourceDir string) ([]flagInfo, error) {
var flags []flagInfo
err := filepath.Walk(sourceDir, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
// Skip non-Go files
if !strings.HasSuffix(path, ".go") || info.IsDir() {
return nil
}
fset := token.NewFileSet()
file, err := parser.ParseFile(fset, path, nil, parser.ParseComments)
if err != nil {
return fmt.Errorf("error parsing file %s: %v", path, err)
}
fileFlags := extractFlags(file, getRelativePath(sourceDir, path))
flags = append(flags, fileFlags...)
return nil
})
return flags, err
}
func extractFlags(file *ast.File, sourcePath string) []flagInfo {
var flags []flagInfo
ast.Inspect(file, func(n ast.Node) bool {
// Look for flag.String(), flag.Bool(), flag.Float64(), etc.
if call, ok := n.(*ast.CallExpr); ok {
if sel, ok := call.Fun.(*ast.SelectorExpr); ok {
if ident, ok := sel.X.(*ast.Ident); ok {
if ident.Name == "flag" {
if flag := extractFlagFromCall(call, sourcePath); flag != nil {
flags = append(flags, *flag)
}
}
}
}
}
return true
})
return flags
}
func generateDocs(flags []flagInfo, outputFile string) error {
component := determineComponent(outputFile)
markdownTemplate, ok := componentTemplates[component]
if !ok {
return fmt.Errorf("couldn't find template for %s ", component)
}
tmpl, err := template.New("flags").Parse(markdownTemplate)
if err != nil {
return fmt.Errorf("error parsing template: %v", err)
}
data := templateData{
Flags: flags,
Timestamp: time.Now().UTC().Format("2006-01-02 15:04:05 UTC"),
}
var buf bytes.Buffer
if err := tmpl.Execute(&buf, data); err != nil {
return fmt.Errorf("error executing template: %v", err)
}
f, err := os.Create(outputFile)
if err != nil {
return fmt.Errorf("error creating output file: %v", err)
}
defer f.Close()
_, err = io.Copy(f, &buf)
return err
}
func getRelativePath(baseDir, fullPath string) string {
rel, err := filepath.Rel(baseDir, fullPath)
if err != nil {
return fullPath
}
return rel
}
// We determine the component by the path of the output file.
// if the path contains "recommender", we generate recommender flags.
// if the path contains "updater", we generate updater flags.
// if the path contains "admission", we generate admission flags.
// Otherwise, we generate recommender flags.
func determineComponent(outputPath string) string {
if strings.Contains(outputPath, "updater") {
return "updater"
}
if strings.Contains(outputPath, "admission") {
return "admission"
}
if strings.Contains(outputPath, "recommender") {
return "recommender"
}
fmt.Println("Couldn't find component. default is recommender")
return "recommender"
}