| 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 |
// pointuh is a trivial gengo/v2 program which consider its inputs, and emits |
| 18 |
// to new packages the same types, except for structs, where all fields are |
| 19 |
// pointers. |
| 20 |
package main |
| 21 |
|
| 22 |
import ( |
| 23 |
"flag" |
| 24 |
"fmt" |
| 25 |
"io" |
| 26 |
"os" |
| 27 |
"path/filepath" |
| 28 |
|
| 29 |
"github.com/spf13/pflag" |
| 30 |
"k8s.io/gengo/v2" |
| 31 |
"k8s.io/gengo/v2/generator" |
| 32 |
"k8s.io/gengo/v2/namer" |
| 33 |
"k8s.io/gengo/v2/types" |
| 34 |
"k8s.io/klog/v2" |
| 35 |
) |
| 36 |
|
| 37 |
func main() { |
| 38 |
klog.InitFlags(nil) |
| 39 |
args := &Args{} |
| 40 |
|
| 41 |
// Collect and parse flags. |
| 42 |
args.AddFlags(pflag.CommandLine) |
| 43 |
flag.Set("logtostderr", "true") |
| 44 |
pflag.CommandLine.AddGoFlagSet(flag.CommandLine) |
| 45 |
pflag.Parse() |
| 46 |
|
| 47 |
if err := args.Validate(); err != nil { |
| 48 |
klog.ErrorS(err, "fatal error") |
| 49 |
os.Exit(1) |
| 50 |
} |
| 51 |
|
| 52 |
myTargets := func(context *generator.Context) []generator.Target { |
| 53 |
return getTargets(context, args) |
| 54 |
} |
| 55 |
|
| 56 |
// Run the tool. |
| 57 |
if err := gengo.Execute( |
| 58 |
getNameSystems(), |
| 59 |
getDefaultNameSystem(), |
| 60 |
myTargets, |
| 61 |
gengo.StdBuildTag, |
| 62 |
pflag.Args(), |
| 63 |
); err != nil { |
| 64 |
klog.ErrorS(err, "fatal error") |
| 65 |
os.Exit(1) |
| 66 |
} |
| 67 |
klog.V(2).InfoS("Completed successfully.") |
| 68 |
} |
| 69 |
|
| 70 |
type Args struct { |
| 71 |
outputDir string // must be a directory path |
| 72 |
outputPkg string // must be a Go import-path |
| 73 |
outputFile string |
| 74 |
goHeaderFile string |
| 75 |
} |
| 76 |
|
| 77 |
// AddFlags adds this tool's flags to the flagset. |
| 78 |
func (args *Args) AddFlags(fs *pflag.FlagSet) { |
| 79 |
fs.StringVar(&args.outputDir, "output-dir", "", |
| 80 |
"the base directory under which to generate results") |
| 81 |
fs.StringVar(&args.outputPkg, "output-pkg", "", |
| 82 |
"the base Go import-path under which to generate results") |
| 83 |
fs.StringVar(&args.outputFile, "output-file", "generated.pointuh.go", |
| 84 |
"the name of the file to be generated") |
| 85 |
fs.StringVar(&args.goHeaderFile, "go-header-file", "", |
| 86 |
"the path to a file containing boilerplate header text; the string \"YEAR\" will be replaced with the current 4-digit year") |
| 87 |
} |
| 88 |
|
| 89 |
// Validate checks the arguments. |
| 90 |
func (args *Args) Validate() error { |
| 91 |
if len(args.outputDir) == 0 { |
| 92 |
return fmt.Errorf("--output-dir must be specified") |
| 93 |
} |
| 94 |
if len(args.outputPkg) == 0 { |
| 95 |
return fmt.Errorf("--output-pkg must be specified") |
| 96 |
} |
| 97 |
if len(args.outputFile) == 0 { |
| 98 |
return fmt.Errorf("--output-file must be specified") |
| 99 |
} |
| 100 |
|
| 101 |
return nil |
| 102 |
} |
| 103 |
|
| 104 |
// getNameSystems returns the name system used by the generators in this package. |
| 105 |
func getNameSystems() namer.NameSystems { |
| 106 |
return namer.NameSystems{ |
| 107 |
"raw": namer.NewRawNamer("", nil), |
| 108 |
} |
| 109 |
} |
| 110 |
|
| 111 |
// getDefaultNameSystem returns the default name system for ordering the types to be |
| 112 |
// processed by the generators in this package. |
| 113 |
func getDefaultNameSystem() string { |
| 114 |
return "raw" |
| 115 |
} |
| 116 |
|
| 117 |
// getTargets is called after the inputs have been loaded. It is expected to |
| 118 |
// examine the provided context and return a list of Packages which will be |
| 119 |
// executed further. |
| 120 |
func getTargets(c *generator.Context, args *Args) []generator.Target { |
| 121 |
boilerplate, err := gengo.GoBoilerplate(args.goHeaderFile, gengo.StdBuildTag, gengo.StdGeneratedBy) |
| 122 |
if err != nil { |
| 123 |
klog.Fatalf("failed loading boilerplate: %v", err) |
| 124 |
} |
| 125 |
|
| 126 |
var targets []generator.Target |
| 127 |
for _, input := range c.Inputs { |
| 128 |
klog.V(2).InfoS("processing", "pkg", input) |
| 129 |
|
| 130 |
pkg := c.Universe[input] |
| 131 |
|
| 132 |
targets = append(targets, &generator.SimpleTarget{ |
| 133 |
PkgName: pkg.Name, |
| 134 |
PkgPath: filepath.Join(args.outputPkg, pkg.Name), |
| 135 |
PkgDir: filepath.Join(args.outputDir, filepath.Base(pkg.Path)), |
| 136 |
|
| 137 |
HeaderComment: boilerplate, |
| 138 |
|
| 139 |
// FilterFunc returns true if this Package cares about this type. |
| 140 |
// Each Generator has its own Filter method which will be checked |
| 141 |
// subsequently. This will be called for every type in every |
| 142 |
// loaded package, not just things in our inputs. |
| 143 |
FilterFunc: func(c *generator.Context, t *types.Type) bool { |
| 144 |
// Only consider types in our inputs |
| 145 |
return t.Name.Package == pkg.Path |
| 146 |
}, |
| 147 |
|
| 148 |
// GeneratorsFunc returns a list of Generators, each of which is |
| 149 |
// responsible for a single output file (though multiple generators |
| 150 |
// may write to the same one). |
| 151 |
GeneratorsFunc: func(c *generator.Context) (generators []generator.Generator) { |
| 152 |
return []generator.Generator{ |
| 153 |
newPointuhGenerator(args.outputFile, pkg), |
| 154 |
} |
| 155 |
}, |
| 156 |
}) |
| 157 |
} |
| 158 |
|
| 159 |
return targets |
| 160 |
} |
| 161 |
|
| 162 |
// pointuhGenerator produces a file with autogenerated functions. |
| 163 |
type pointuhGenerator struct { |
| 164 |
generator.GoGenerator |
| 165 |
myPackage *types.Package |
| 166 |
} |
| 167 |
|
| 168 |
func newPointuhGenerator(outputFilename string, pkg *types.Package) generator.Generator { |
| 169 |
return &pointuhGenerator{ |
| 170 |
GoGenerator: generator.GoGenerator{ |
| 171 |
OutputFilename: outputFilename, |
| 172 |
}, |
| 173 |
myPackage: pkg, |
| 174 |
} |
| 175 |
} |
| 176 |
|
| 177 |
// Namers returns a set of NameSystems which will be merged with the namers |
| 178 |
// provided when executing this package. In case of a name collision, the |
| 179 |
// values produced here will win. |
| 180 |
func (g *pointuhGenerator) Namers(*generator.Context) namer.NameSystems { |
| 181 |
return namer.NameSystems{ |
| 182 |
// This elides package names when the name is in "this" package. |
| 183 |
"localraw": namer.NewRawNamer(g.myPackage.Path, nil), |
| 184 |
} |
| 185 |
} |
| 186 |
|
| 187 |
// GenerateType should emit code for the specified type. This will be called |
| 188 |
// for every type which made it through this Generator's Filter method. |
| 189 |
func (g *pointuhGenerator) GenerateType(c *generator.Context, t *types.Type, w io.Writer) error { |
| 190 |
if namer.IsPrivateGoName(t.Name.Name) { |
| 191 |
return nil |
| 192 |
} |
| 193 |
|
| 194 |
klog.V(2).InfoS("generating pointerful type", "type", t.String()) |
| 195 |
|
| 196 |
sw := generator.NewSnippetWriter(w, c, "$", "$") |
| 197 |
// Only modify structs. |
| 198 |
if t.Kind == types.Struct { |
| 199 |
emitModifiedStruct(t, sw) |
| 200 |
} else { |
| 201 |
emitUnmodifiedType(t, sw) |
| 202 |
} |
| 203 |
return sw.Error() |
| 204 |
} |
| 205 |
|
| 206 |
func emitUnmodifiedType(t *types.Type, sw *generator.SnippetWriter) { |
| 207 |
if t.Kind == types.DeclarationOf || t.Kind == types.Interface { |
| 208 |
return |
| 209 |
} |
| 210 |
|
| 211 |
args := argsFromType(t) |
| 212 |
sw.Do("// $.type|localraw$ is an autogenerated clone of $.type|raw$\n", args) |
| 213 |
sw.Do("type $.type|localraw$ ", args) |
| 214 |
for { |
| 215 |
if t.Kind != types.Pointer { |
| 216 |
break |
| 217 |
} |
| 218 |
sw.Do("*", nil) |
| 219 |
t = t.Elem |
| 220 |
} |
| 221 |
switch t.Kind { |
| 222 |
case types.Builtin: |
| 223 |
sw.Do("$.type.Name.Name$\n", args) |
| 224 |
case types.Map: |
| 225 |
sw.Do("map[$.type.Key$]$.type.Elem$\n", args) |
| 226 |
case types.Slice: |
| 227 |
sw.Do("[]$.type.Elem$\n", args) |
| 228 |
case types.Array: |
| 229 |
sw.Do("[$.type.Len$]$.type.Elem$\n", args) |
| 230 |
case types.Alias: |
| 231 |
sw.Do("$.type.Underlying|localraw$\n", args) |
| 232 |
case types.Struct: |
| 233 |
// must be non-exported |
| 234 |
sw.Do("struct {\n", args) |
| 235 |
sw.Do("}\n", nil) |
| 236 |
default: |
| 237 |
sw.Do("ERROR_Unhandled_input_type // $.type|raw$ ($.type.Kind$)\n", args) |
| 238 |
} |
| 239 |
sw.Do("\n", nil) |
| 240 |
} |
| 241 |
|
| 242 |
func emitModifiedStruct(t *types.Type, sw *generator.SnippetWriter) { |
| 243 |
args := argsFromType(t) |
| 244 |
sw.Do("// $.type|localraw$ is an autogenerated type.\n", args) |
| 245 |
sw.Do("type $.type|localraw$ struct {\n", args) |
| 246 |
for _, field := range t.Members { |
| 247 |
args := argsFromType(field.Type) |
| 248 |
if field.Type.Kind == types.Pointer { |
| 249 |
sw.Do(fmt.Sprintf("%s $.type|raw$\n", field.Name), args) |
| 250 |
} else { |
| 251 |
sw.Do(fmt.Sprintf("%s *$.type|raw$\n", field.Name), args) |
| 252 |
} |
| 253 |
} |
| 254 |
sw.Do("}\n", args) |
| 255 |
} |
| 256 |
|
| 257 |
func argsFromType(ts ...*types.Type) generator.Args { |
| 258 |
a := generator.Args{ |
| 259 |
"type": ts[0], |
| 260 |
} |
| 261 |
for i, t := range ts { |
| 262 |
a[fmt.Sprintf("type%d", i+1)] = t |
| 263 |
} |
| 264 |
return a |
| 265 |
} |