-
Notifications
You must be signed in to change notification settings - Fork 5.4k
/
main.go
90 lines (78 loc) · 2.25 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
package main
import (
"errors"
"fmt"
"go/importer"
"go/types"
"os"
"strings"
"github.com/spf13/cobra"
)
func main() {
if err := newCommand().Execute(); err != nil {
os.Exit(1)
}
}
const (
packagePrefix = "k8s.io/api/"
)
func newCommand() *cobra.Command {
var (
docsOutputPath string = ""
)
var command = &cobra.Command{
Use: "go run github.com/argoproj/argo-cd/hack/known_types ALIAS PACKAGE_PATH OUTPUT_PATH",
Example: "go run github.com/argoproj/argo-cd/hack/known_types corev1 k8s.io/api/core/v1 corev1_known_types.go",
RunE: func(c *cobra.Command, args []string) error {
if len(args) < 3 {
return errors.New("alias and package are not specified")
}
alias := args[0]
packagePath := args[1]
outputPath := args[2]
// nolint:staticcheck
imprt := importer.For("source", nil)
pkg, err := imprt.Import(packagePath)
if err != nil {
return err
}
if !strings.HasPrefix(packagePath, packagePrefix) {
return fmt.Errorf("package must be under %s", packagePrefix)
}
shortPackagePath := strings.TrimPrefix(packagePath, packagePrefix)
var mapItems []string
var docs []string
names := pkg.Scope().Names()
for i := range names {
obj := pkg.Scope().Lookup(names[i])
typeName, ok := obj.(*types.TypeName)
if !ok || !typeName.Exported() {
continue
}
_, isStruct := typeName.Type().Underlying().(*types.Struct)
_, isMap := typeName.Type().Underlying().(*types.Map)
if !isStruct && !isMap {
continue
}
docs = append(docs, fmt.Sprintf("%s/%s", shortPackagePath, typeName.Name()))
mapItems = append(mapItems, fmt.Sprintf(`
knownTypes["%s/%s"] = func() interface{} {
return &%s.%s{}
}`, shortPackagePath, typeName.Name(), alias, typeName.Name()))
}
res := fmt.Sprintf(`// Code generated by github.com/argoproj/argo-cd/hack/known_types. DO NOT EDIT.
package normalizers
import corev1 "k8s.io/api/core/v1"
func init() {%s
}`, strings.Join(mapItems, ""))
if docsOutputPath != "" {
if err = os.WriteFile(docsOutputPath, []byte(strings.Join(docs, "\n")), 0644); err != nil {
return err
}
}
return os.WriteFile(outputPath, []byte(res), 0644)
},
}
command.Flags().StringVar(&docsOutputPath, "docs", "", "Docs output file path")
return command
}