Debian Codegraph @

v2/examples/kilroy/main.go

raw
1 /*
2 Copyright 2023 The Kubernetes Authors.
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15 */
16
17 // kilroy is a trivial gengo/v2 program which adds a tag-method to types.
18 package main
19
20 import (
21 "flag"
22 "fmt"
23 "io"
24 "os"
25
26 "github.com/spf13/pflag"
27 "k8s.io/gengo/v2"
28 "k8s.io/gengo/v2/generator"
29 "k8s.io/gengo/v2/namer"
30 "k8s.io/gengo/v2/types"
31 "k8s.io/klog/v2"
32 )
33
34 func main() {
35 klog.InitFlags(nil)
36 args := &Args{}
37
38 // Collect and parse flags.
39 args.AddFlags(pflag.CommandLine)
40 flag.Set("logtostderr", "true")
41 pflag.CommandLine.AddGoFlagSet(flag.CommandLine)
42 pflag.Parse()
43
44 if err := args.Validate(); err != nil {
45 klog.ErrorS(err, "fatal error")
46 os.Exit(1)
47 }
48
49 myTargets := func(context *generator.Context) []generator.Target {
50 return getTargets(context, args)
51 }
52
53 // Run the tool.
54 if err := gengo.Execute(
55 getNameSystems(),
56 getDefaultNameSystem(),
57 myTargets,
58 gengo.StdBuildTag,
59 pflag.Args(),
60 ); err != nil {
61 klog.ErrorS(err, "fatal error")
62 os.Exit(1)
63 }
64 klog.V(2).InfoS("completed successfully")
65 }
66
67 type Args struct {
68 outputFile string
69 methodName string
70 goHeaderFile string
71 }
72
73 // AddFlags adds this tool's flags to the flagset.
74 func (args *Args) AddFlags(fs *pflag.FlagSet) {
75 fs.StringVar(&args.outputFile, "output-file", "generated.kilroy.go",
76 "the name of the file to be generated")
77 fs.StringVar(&args.methodName, "method-name", "KilroyWasHere",
78 "the name of the method to add")
79 fs.StringVar(&args.goHeaderFile, "go-header-file", "",
80 "the path to a file containing boilerplate header text; the string \"YEAR\" will be replaced with the current 4-digit year")
81 }
82
83 // Validate checks the arguments.
84 func (args *Args) Validate() error {
85 if args.outputFile == "" {
86 return fmt.Errorf("--output-file must be specified")
87 }
88 if args.methodName == "" {
89 return fmt.Errorf("--method-name must be specified")
90 }
91
92 return nil
93 }
94
95 // getNameSystems returns the name system used by the generators in this package.
96 func getNameSystems() namer.NameSystems {
97 return namer.NameSystems{
98 "raw": namer.NewRawNamer("", nil),
99 }
100 }
101
102 // getDefaultNameSystem returns the default name system for ordering the types to be
103 // processed by the generators in this package.
104 func getDefaultNameSystem() string {
105 return "raw"
106 }
107
108 // getTargets is called after the inputs have been loaded. It is expected to
109 // examine the provided context and return a list of Packages which will be
110 // executed further.
111 func getTargets(c *generator.Context, args *Args) []generator.Target {
112 boilerplate, err := gengo.GoBoilerplate(args.goHeaderFile, gengo.StdBuildTag, gengo.StdGeneratedBy)
113 if err != nil {
114 klog.Fatalf("failed loading boilerplate: %v", err)
115 }
116
117 targets := []generator.Target{}
118 for _, input := range c.Inputs {
119 klog.V(2).InfoS("processing", "pkg", input)
120
121 pkg := c.Universe[input]
122
123 targets = append(targets, &generator.SimpleTarget{
124 PkgName: pkg.Name,
125 PkgPath: pkg.Path, // output pkg is the same as the input
126 PkgDir: pkg.Dir, // output pkg is the same as the input
127 HeaderComment: boilerplate,
128
129 // FilterFunc returns true if this Package cares about this type.
130 // Each Generator has its own Filter method which will be checked
131 // subsequently. This will be called for every type in every
132 // loaded package, not just things in our inputs.
133 FilterFunc: func(c *generator.Context, t *types.Type) bool {
134 return t.Name.Package == pkg.Path
135 },
136
137 // GeneratorsFunc returns a list of Generators, each of which is
138 // responsible for a single output file (though multiple generators
139 // may write to the same one).
140 GeneratorsFunc: func(c *generator.Context) (generators []generator.Generator) {
141 return []generator.Generator{
142 newKilroyGenerator(args.outputFile, pkg, args.methodName),
143 }
144 },
145 })
146 }
147
148 return targets
149 }
150
151 // kilroyGenerator produces a file with autogenerated functions.
152 type kilroyGenerator struct {
153 generator.GoGenerator
154 myPackage *types.Package
155 methodName string
156 }
157
158 func newKilroyGenerator(outputFilename string, pkg *types.Package, methodName string) generator.Generator {
159 return &kilroyGenerator{
160 GoGenerator: generator.GoGenerator{
161 OutputFilename: outputFilename,
162 },
163 myPackage: pkg,
164 methodName: methodName,
165 }
166 }
167
168 // Filter returns true if this Generator cares about this type.
169 // This will be called for every type which made it through this Package's
170 // Filter method.
171 func (g *kilroyGenerator) Filter(c *generator.Context, t *types.Type) bool {
172 // We only handle exported structs.
173 return t.Kind == types.Struct && !namer.IsPrivateGoName(t.Name.Name)
174 }
175
176 // Namers returns a set of NameSystems which will be merged with the namers
177 // provided when executing this package. In case of a name collision, the
178 // values produced here will win.
179 func (g *kilroyGenerator) Namers(*generator.Context) namer.NameSystems {
180 return namer.NameSystems{
181 // This elides package names when the name is in "this" package.
182 "raw": namer.NewRawNamer(g.myPackage.Path, nil),
183 }
184 }
185
186 // GenerateType should emit code for the specified type. This will be called
187 // for every type which made it through this Generator's Filter method.
188 func (g *kilroyGenerator) GenerateType(c *generator.Context, t *types.Type, w io.Writer) error {
189 klog.V(2).InfoS("generating kilroy method", "type", t.String(), "method", g.methodName)
190
191 sw := generator.NewSnippetWriter(w, c, "$", "$")
192 args := argsFromType(t)
193 args["methodName"] = g.methodName
194
195 sw.Do("// $.methodName$ is an autogenerated method.\n", args)
196 sw.Do("func ($.type|raw$) $.methodName$() {}\n", args)
197
198 return sw.Error()
199 }
200
201 func argsFromType(ts ...*types.Type) generator.Args {
202 a := generator.Args{
203 "type": ts[0],
204 }
205 for i, t := range ts {
206 a[fmt.Sprintf("type%d", i+1)] = t
207 }
208 return a
209 }