-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
319 lines (282 loc) · 8.46 KB
/
main.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
/*
Copyright 2024 Nokia.
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 // nolint:revive
import (
"fmt"
"log"
"os"
"os/exec"
"path"
"path/filepath"
"regexp"
"strings"
"github.com/spf13/cobra"
"golang.org/x/mod/modfile"
)
var bin, output string
var cmd = cobra.Command{
Use: "apiserver-runtime-gen",
Short: "run code generators",
PreRunE: preRunE,
RunE: runE,
}
func preRunE(cmd *cobra.Command, args []string) error {
if module == "" {
return fmt.Errorf("must specify module")
}
if len(versions) == 0 {
return fmt.Errorf("must specify versions")
}
return nil
}
func runE(cmd *cobra.Command, args []string) error {
var err error
// get the location the generators are installed
bin = os.Getenv("GOBIN")
if bin == "" {
bin = filepath.Join(os.Getenv("HOME"), "go", "bin")
}
// install the generators
if install {
for _, gen := range generators {
// nolint:gosec
err := run(exec.Command("go", "install", path.Join("k8s.io/code-generator/cmd", gen)))
if err != nil {
return err
}
if gen == "go-to-protobuf" {
err := run(exec.Command("go", "mod", "vendor"))
if err != nil {
return err
}
err = run(exec.Command("go", "mod", "tidy"))
if err != nil {
return err
}
}
}
}
// setup the directory to generate the code to.
// code generators don't work with go modules, and try the full path of the module
output, err = os.MkdirTemp("", "gen")
if err != nil {
return err
}
if clean {
// nolint:errcheck
defer os.RemoveAll(output)
}
d, l := path.Split(module) // split the directory from the link we will create
p := filepath.Join(strings.Split(d, "/")...) // convert module path to os filepath
p = filepath.Join(output, p) // create the directory which will contain the link
err = os.MkdirAll(p, 0700)
if err != nil {
return err
}
// link the tmp location to this one so the code generator writes to the correct path
wd, err := os.Getwd()
if err != nil {
return err
}
err = os.Symlink(wd, filepath.Join(p, l))
if err != nil {
return err
}
return doGen()
}
func doGen() error {
inputs := strings.Join(versions, ",")
//protoInput := versions[0]
clientVersions := versions[:2]
clientgenInput := strings.Join(clientVersions, ",")
gen := map[string]bool{}
for _, g := range generators {
gen[g] = true
}
if gen["deepcopy-gen"] {
err := run(getCmd("deepcopy-gen",
"--input-dirs", inputs,
"-O", "zz_generated.deepcopy",
"--bounding-dirs", path.Join(module, "apis")))
if err != nil {
return err
}
}
if gen["openapi-gen"] {
err := run(getCmd("openapi-gen",
"--input-dirs", "k8s.io/apimachinery/pkg/api/resource,"+
"k8s.io/apimachinery/pkg/apis/meta/v1,"+
"k8s.io/apimachinery/pkg/runtime,"+
"k8s.io/apimachinery/pkg/version,"+
inputs,
"-O", "zz_generated.openapi",
"--output-package", path.Join(module, "apis/generated/openapi")))
if err != nil {
return err
}
}
if gen["client-gen"] {
inputBase := ""
versionsInputs := clientgenInput
// e.g. base = "example.io/foo/api", strippedVersions = "v1,v1beta1"
// e.g. base = "example.io/foo/pkg/apis", strippedVersions = "test/v1,test/v1beta1"
if base, strippedVersions, ok := findInputBase(module, clientVersions); ok {
inputBase = base
versionsInputs = strings.Join(strippedVersions, ",")
}
fmt.Println("inputBase", inputBase)
fmt.Println("clientgenInput", clientgenInput)
fmt.Println("versionsInputs", versionsInputs)
err := run(getCmd("client-gen",
"--clientset-name", "versioned", "--input-base", "",
"--input", versionsInputs, "--output-package", path.Join(module, "apis/generated/clientset")))
if err != nil {
return err
}
}
if gen["lister-gen"] {
err := run(getCmd("lister-gen",
"--input-dirs", clientgenInput, "--output-package", path.Join(module, "apis/generated/listers")))
if err != nil {
return err
}
}
if gen["informer-gen"] {
err := run(getCmd("informer-gen",
"--input-dirs", clientgenInput,
"--versioned-clientset-package", path.Join(module, "apis/generated/clientset/versioned"),
"--listers-package", path.Join(module, "apis/generated/listers"),
"--output-package", path.Join(module, "apis/generated/informers")))
if err != nil {
return err
}
}
if gen["go-to-protobuf"] {
err := run(getCmd("go-to-protobuf",
"--packages", inputs,
"--apimachinery-packages", "-k8s.io/apimachinery/pkg/api/resource,-k8s.io/apimachinery/pkg/runtime/schema,-k8s.io/apimachinery/pkg/runtime,-k8s.io/apimachinery/pkg/apis/meta/v1,-k8s.io/api/core/v1",
"--proto-import", "./vendor",
))
if err != nil {
return err
}
}
return nil
}
var (
generators []string
header string
module string
versions []string
clean, install bool
)
func main() {
cmd.Flags().BoolVar(&clean, "clean", true, "Delete temporary directory for code generation.")
options := []string{"client-gen", "deepcopy-gen", "informer-gen", "lister-gen", "openapi-gen", "go-to-protobuf"}
defaultGen := []string{"deepcopy-gen", "openapi-gen"}
cmd.Flags().StringSliceVarP(&generators, "generator", "g",
defaultGen, fmt.Sprintf("Code generator to install and run. Options: %v.", options))
defaultBoilerplate := filepath.Join("hack", "boilerplate.go.txt")
cmd.Flags().StringVar(&header, "go-header-file", defaultBoilerplate,
"File containing boilerplate header text. The string YEAR will be replaced with the current 4-digit year.")
cmd.Flags().BoolVar(&install, "install-generators", true, "Go get the generators")
var defaultModule string
cwd, _ := os.Getwd()
if modRoot := findModuleRoot(cwd); modRoot != "" {
if b, err := os.ReadFile(filepath.Clean(path.Join(modRoot, "go.mod"))); err == nil {
defaultModule = modfile.ModulePath(b)
}
}
cmd.Flags().StringVar(&module, "module", defaultModule, "Go module of the apiserver.")
// calculate the versions
var defaultVersions []string
if files, err := os.ReadDir(filepath.Join("apis")); err == nil {
for _, f := range files {
if f.IsDir() {
versionFiles, err := os.ReadDir(filepath.Join("apis", f.Name()))
if err != nil {
log.Fatal(err)
}
for _, v := range versionFiles {
if v.IsDir() {
match := versionRegexp.MatchString(v.Name())
if !match {
continue
}
defaultVersions = append(defaultVersions, path.Join(module, "apis", f.Name(), v.Name()))
}
}
}
}
} else {
fmt.Fprintf(os.Stderr, "cannot parse api versions: %v\n", err)
}
cmd.Flags().StringSliceVar(
&versions, "versions", defaultVersions, "Go packages of API versions to generate code for.")
if err := cmd.Execute(); err != nil {
log.Fatal(err)
}
}
var versionRegexp = regexp.MustCompile("^v[0-9]+((alpha|beta)?[0-9]+)?$")
func run(cmd *exec.Cmd) error {
fmt.Println(strings.Join(cmd.Args, " "))
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Stdin = os.Stdin
return cmd.Run()
}
func getCmd(cmd string, args ...string) *exec.Cmd {
// nolint:gosec
e := exec.Command(filepath.Join(bin, cmd), "--output-base", output, "--go-header-file", header)
e.Args = append(e.Args, args...)
return e
}
func findModuleRoot(dir string) string {
for {
if _, err := os.Stat(filepath.Join(dir, "go.mod")); err == nil {
return dir
}
parentDIR := path.Dir(dir)
if parentDIR == dir {
break
}
dir = parentDIR
}
return ""
}
func findInputBase(module string, versions []string) (string, []string, bool) {
if allHasPrefix(filepath.Join(module, "api"), versions) {
base := filepath.Join(module, "api")
return base, allTrimPrefix(base+"/", versions), true
}
if allHasPrefix(filepath.Join(module, "apis"), versions) {
base := filepath.Join(module, "apis")
return base, allTrimPrefix(base+"/", versions), true
}
return "", nil, false
}
func allHasPrefix(prefix string, paths []string) bool {
for _, p := range paths {
if !strings.HasPrefix(p, prefix) {
return false
}
}
return true
}
func allTrimPrefix(prefix string, versions []string) []string {
vs := make([]string, 0)
for _, v := range versions {
vs = append(vs, strings.TrimPrefix(v, prefix))
}
return vs
}