1
0
mirror of https://github.com/kubernetes-sigs/descheduler.git synced 2026-01-28 14:41:10 +01:00

bump to kubernetes v0.32.0-rc.2

Signed-off-by: Amir Alavi <amiralavi7@gmail.com>
This commit is contained in:
Amir Alavi
2024-12-06 10:36:06 -05:00
parent 2c11481856
commit f4c3fdf418
1822 changed files with 68460 additions and 50001 deletions

View File

@@ -19,6 +19,7 @@ package generators
import (
"io"
"path"
"slices"
"strings"
"k8s.io/gengo/v2/generator"
@@ -114,7 +115,7 @@ func (g *applyConfigurationGenerator) GenerateType(c *generator.Context, t *type
sw.Do(constructor, typeParams)
}
}
g.generateWithFuncs(t, typeParams, sw, nil)
g.generateWithFuncs(t, typeParams, sw, nil, &[]string{})
g.generateGetters(t, typeParams, sw, nil)
return sw.Error()
}
@@ -176,7 +177,8 @@ func (g *applyConfigurationGenerator) generateGetters(t *types.Type, typeParams
}
}
func (g *applyConfigurationGenerator) generateWithFuncs(t *types.Type, typeParams TypeParams, sw *generator.SnippetWriter, embed *memberParams) {
func (g *applyConfigurationGenerator) generateWithFuncs(t *types.Type, typeParams TypeParams, sw *generator.SnippetWriter, embed *memberParams,
generated *[]string) {
for _, member := range t.Members {
if blocklisted(t, member) {
continue
@@ -186,6 +188,11 @@ func (g *applyConfigurationGenerator) generateWithFuncs(t *types.Type, typeParam
memberType = &types.Type{Kind: types.Pointer, Elem: memberType}
}
if jsonTags, ok := lookupJSONTags(member); ok {
if slices.Contains(*generated, member.Name) {
klog.V(5).Infof("With%s already generated on %s, skipping\n", member.Name, t.Name)
continue
}
*generated = append(*generated, member.Name)
memberParams := memberParams{
TypeParams: typeParams,
Member: member,
@@ -194,7 +201,7 @@ func (g *applyConfigurationGenerator) generateWithFuncs(t *types.Type, typeParam
EmbeddedIn: embed,
}
if memberParams.Member.Embedded {
g.generateWithFuncs(member.Type, typeParams, sw, &memberParams)
g.generateWithFuncs(member.Type, typeParams, sw, &memberParams, generated)
if !jsonTags.inline {
// non-inlined embeds are nillable and need a "ensure exists" utility function
sw.Do(ensureEmbedExists, memberParams)
@@ -281,9 +288,9 @@ func (g *applyConfigurationGenerator) generateMemberWith(sw *generator.SnippetWr
sw.Do("func (b *$.ApplyConfig.ApplyConfiguration|public$) With$.Member.Name$(value $.MemberType|raw$) *$.ApplyConfig.ApplyConfiguration|public$ {\n", memberParams)
g.ensureEmbedExistsIfApplicable(sw, memberParams)
if g.refGraph.isApplyConfig(memberParams.Member.Type) || isNillable(memberParams.Member.Type) {
sw.Do("b.$.Member.Name$ = value\n", memberParams)
sw.Do("b$if ne .EmbeddedIn nil$.$.EmbeddedIn.MemberType.Elem.Name.Name$$end$.$.Member.Name$ = value\n", memberParams)
} else {
sw.Do("b.$.Member.Name$ = &value\n", memberParams)
sw.Do("b$if ne .EmbeddedIn nil$.$.EmbeddedIn.MemberType.Elem.Name.Name$$end$.$.Member.Name$ = &value\n", memberParams)
}
sw.Do(" return b\n", memberParams)
sw.Do("}\n", memberParams)
@@ -297,7 +304,7 @@ func (g *applyConfigurationGenerator) generateMemberGetter(sw *generator.Snippet
sw.Do("func (b *$.ApplyConfig.ApplyConfiguration|public$) Get$.Member.Name$() *$.MemberType|raw$ {\n", memberParams)
}
g.ensureEmbedExistsIfApplicable(sw, memberParams)
sw.Do(" return b.$.Member.Name$\n", memberParams)
sw.Do(" return b$if ne .EmbeddedIn nil$.$.EmbeddedIn.MemberType.Elem.Name.Name$$end$.$.Member.Name$\n", memberParams)
sw.Do("}\n", memberParams)
}
@@ -324,15 +331,15 @@ func (g *applyConfigurationGenerator) generateMemberWithForSlice(sw *generator.S
sw.Do("}\n", memberParams)
if memberIsPointerToSlice {
sw.Do("*b.$.Member.Name$ = append(*b.$.Member.Name$, *values[i])\n", memberParams)
sw.Do("*b$if ne .EmbeddedIn nil$.$.EmbeddedIn.MemberType.Elem.Name.Name$$end$.$.Member.Name$ = append(*b$if ne .EmbeddedIn nil$.$.EmbeddedIn.MemberType.Elem.Name.Name$$end$.$.Member.Name$, *values[i])\n", memberParams)
} else {
sw.Do("b.$.Member.Name$ = append(b.$.Member.Name$, *values[i])\n", memberParams)
sw.Do("b$if ne .EmbeddedIn nil$.$.EmbeddedIn.MemberType.Elem.Name.Name$$end$.$.Member.Name$ = append(b$if ne .EmbeddedIn nil$.$.EmbeddedIn.MemberType.Elem.Name.Name$$end$.$.Member.Name$, *values[i])\n", memberParams)
}
} else {
if memberIsPointerToSlice {
sw.Do("*b.$.Member.Name$ = append(*b.$.Member.Name$, values[i])\n", memberParams)
sw.Do("*b$if ne .EmbeddedIn nil$.$.EmbeddedIn.MemberType.Elem.Name.Name$$end$.$.Member.Name$ = append(*b$if ne .EmbeddedIn nil$.$.EmbeddedIn.MemberType.Elem.Name.Name$$end$.$.Member.Name$, values[i])\n", memberParams)
} else {
sw.Do("b.$.Member.Name$ = append(b.$.Member.Name$, values[i])\n", memberParams)
sw.Do("b$if ne .EmbeddedIn nil$.$.EmbeddedIn.MemberType.Elem.Name.Name$$end$.$.Member.Name$ = append(b$if ne .EmbeddedIn nil$.$.EmbeddedIn.MemberType.Elem.Name.Name$$end$.$.Member.Name$, values[i])\n", memberParams)
}
}
sw.Do(" }\n", memberParams)
@@ -347,11 +354,11 @@ func (g *applyConfigurationGenerator) generateMemberWithForMap(sw *generator.Sni
sw.Do("// overwriting an existing map entries in $.Member.Name$ field with the same key.\n", memberParams)
sw.Do("func (b *$.ApplyConfig.ApplyConfiguration|public$) With$.Member.Name$(entries $.MemberType|raw$) *$.ApplyConfig.ApplyConfiguration|public$ {\n", memberParams)
g.ensureEmbedExistsIfApplicable(sw, memberParams)
sw.Do(" if b.$.Member.Name$ == nil && len(entries) > 0 {\n", memberParams)
sw.Do(" b.$.Member.Name$ = make($.MemberType|raw$, len(entries))\n", memberParams)
sw.Do(" if b$if ne .EmbeddedIn nil$.$.EmbeddedIn.MemberType.Elem.Name.Name$$end$.$.Member.Name$ == nil && len(entries) > 0 {\n", memberParams)
sw.Do(" b$if ne .EmbeddedIn nil$.$.EmbeddedIn.MemberType.Elem.Name.Name$$end$.$.Member.Name$ = make($.MemberType|raw$, len(entries))\n", memberParams)
sw.Do(" }\n", memberParams)
sw.Do(" for k, v := range entries {\n", memberParams)
sw.Do(" b.$.Member.Name$[k] = v\n", memberParams)
sw.Do(" b$if ne .EmbeddedIn nil$.$.EmbeddedIn.MemberType.Elem.Name.Name$$end$.$.Member.Name$[k] = v\n", memberParams)
sw.Do(" }\n", memberParams)
sw.Do(" return b\n", memberParams)
sw.Do("}\n", memberParams)

View File

@@ -19,13 +19,11 @@ package generators
import (
"io"
"gopkg.in/yaml.v2"
"k8s.io/kube-openapi/pkg/schemaconv"
"k8s.io/gengo/v2/generator"
"k8s.io/gengo/v2/namer"
"k8s.io/gengo/v2/types"
"k8s.io/kube-openapi/pkg/schemaconv"
yaml "sigs.k8s.io/yaml/goyaml.v2"
)
// utilGenerator generates the ForKind() utility function.
@@ -71,11 +69,12 @@ func (g *internalGenerator) GenerateType(c *generator.Context, _ *types.Type, w
return err
}
sw.Do(schemaBlock, map[string]interface{}{
"schemaYAML": string(schemaYAML),
"smdParser": smdParser,
"smdNewParser": smdNewParser,
"yamlObject": yamlObject,
"yamlUnmarshal": yamlUnmarshal,
"schemaYAML": string(schemaYAML),
"smdParser": smdParser,
"smdNewParser": smdNewParser,
"fmtSprintf": fmtSprintf,
"syncOnce": syncOnce,
"yamlObject": yamlObject,
})
return sw.Error()
@@ -87,13 +86,13 @@ func Parser() *{{.smdParser|raw}} {
var err error
parser, err = {{.smdNewParser|raw}}(schemaYAML)
if err != nil {
panic(fmt.Sprintf("Failed to parse schema: %v", err))
panic({{.fmtSprintf|raw}}("Failed to parse schema: %v", err))
}
})
return parser
}
var parserOnce sync.Once
var parserOnce {{.syncOnce|raw}}
var parser *{{.smdParser|raw}}
var schemaYAML = {{.yamlObject|raw}}(` + "`{{.schemaYAML}}`" + `)
`

View File

@@ -188,7 +188,7 @@ func targetForApplyConfigurationsPackage(outputDirBase, outputPkgBase, pkgSubdir
localPkg: outputPkg,
groupVersion: gv,
applyConfig: toGenerate,
imports: generator.NewImportTracker(),
imports: generator.NewImportTrackerForPackage(outputPkg),
refGraph: refs,
openAPIType: openAPIType,
})
@@ -211,7 +211,7 @@ func targetForUtils(outputDirBase, outputPkgBase string, boilerplate []byte, gro
OutputFilename: "utils.go",
},
outputPackage: outputPkgBase,
imports: generator.NewImportTracker(),
imports: generator.NewImportTrackerForPackage(outputPkgBase),
groupVersions: groupVersions,
typesForGroupVersion: applyConfigsForGroupVersion,
groupGoNames: groupGoNames,
@@ -236,7 +236,7 @@ func targetForInternal(outputDirBase, outputPkgBase string, boilerplate []byte,
OutputFilename: "internal.go",
},
outputPackage: outputPkgBase,
imports: generator.NewImportTracker(),
imports: generator.NewImportTrackerForPackage(outputPkg),
typeModels: models,
})
return generators

View File

@@ -19,6 +19,8 @@ package generators
import "k8s.io/gengo/v2/types"
var (
fmtSprintf = types.Ref("fmt", "Sprintf")
syncOnce = types.Ref("sync", "Once")
applyConfiguration = types.Ref("k8s.io/apimachinery/pkg/runtime", "ApplyConfiguration")
groupVersionKind = types.Ref("k8s.io/apimachinery/pkg/runtime/schema", "GroupVersionKind")
typeMeta = types.Ref("k8s.io/apimachinery/pkg/apis/meta/v1", "TypeMeta")
@@ -31,5 +33,4 @@ var (
smdParser = types.Ref("sigs.k8s.io/structured-merge-diff/v4/typed", "Parser")
testingTypeConverter = types.Ref("k8s.io/client-go/testing", "TypeConverter")
yamlObject = types.Ref("sigs.k8s.io/structured-merge-diff/v4/typed", "YAMLObject")
yamlUnmarshal = types.Ref("gopkg.in/yaml.v2", "Unmarshal")
)

View File

@@ -61,6 +61,9 @@ type Args struct {
// If non-empty, Apply functions are generated for each type and reference the apply builders.
// If empty (""), Apply functions are not generated.
ApplyConfigurationPackage string
// PrefersProtobuf determines if the generated clientset uses protobuf for API requests.
PrefersProtobuf bool
}
func New() *Args {
@@ -99,6 +102,8 @@ func (args *Args) AddFlags(fs *pflag.FlagSet, inputBase string) {
"list of comma separated plural exception definitions in Type:PluralizedType form")
fs.StringVar(&args.ApplyConfigurationPackage, "apply-configuration-package", args.ApplyConfigurationPackage,
"optional package of apply configurations, generated by applyconfiguration-gen, that are required to generate Apply functions for each type in the clientset. By default Apply functions are not generated.")
fs.BoolVar(&args.PrefersProtobuf, "prefers-protobuf", args.PrefersProtobuf,
"when set, client-gen will generate a clientset that uses protobuf for API requests")
// support old flags
fs.SetNormalizeFunc(mapFlagName("clientset-path", "output-pkg", fs.GetNormalizeFunc()))

View File

@@ -128,7 +128,7 @@ func DefaultNameSystem() string {
return "public"
}
func targetForGroup(gv clientgentypes.GroupVersion, typeList []*types.Type, clientsetDir, clientsetPkg string, groupPkgName string, groupGoName string, apiPath string, inputPkg string, applyBuilderPkg string, boilerplate []byte) generator.Target {
func targetForGroup(gv clientgentypes.GroupVersion, typeList []*types.Type, clientsetDir, clientsetPkg string, groupPkgName string, groupGoName string, apiPath string, inputPkg string, applyBuilderPkg string, boilerplate []byte, prefersProtobuf bool) generator.Target {
subdir := []string{"typed", strings.ToLower(groupPkgName), strings.ToLower(gv.Version.NonEmpty())}
gvDir := filepath.Join(clientsetDir, filepath.Join(subdir...))
gvPkg := path.Join(clientsetPkg, path.Join(subdir...))
@@ -160,8 +160,9 @@ func targetForGroup(gv clientgentypes.GroupVersion, typeList []*types.Type, clie
group: gv.Group.NonEmpty(),
version: gv.Version.String(),
groupGoName: groupGoName,
prefersProtobuf: prefersProtobuf,
typeToMatch: t,
imports: generator.NewImportTracker(),
imports: generator.NewImportTrackerForPackage(gvPkg),
})
}
@@ -177,7 +178,7 @@ func targetForGroup(gv clientgentypes.GroupVersion, typeList []*types.Type, clie
groupGoName: groupGoName,
apiPath: apiPath,
types: typeList,
imports: generator.NewImportTracker(),
imports: generator.NewImportTrackerForPackage(gvPkg),
})
expansionFileName := "generated_expansion.go"
@@ -214,7 +215,7 @@ func targetForClientset(args *args.Args, clientsetDir, clientsetPkg string, grou
groups: args.Groups,
groupGoNames: groupGoNames,
clientsetPackage: clientsetPkg,
imports: generator.NewImportTracker(),
imports: generator.NewImportTrackerForPackage(clientsetPkg),
},
}
return generators
@@ -260,7 +261,7 @@ NextGroup:
OutputPath: schemeDir,
Groups: args.Groups,
GroupGoNames: groupGoNames,
ImportTracker: generator.NewImportTracker(),
ImportTracker: generator.NewImportTrackerForPackage(schemePkg),
CreateRegistry: internalClient,
},
}
@@ -424,7 +425,7 @@ func GetTargets(context *generator.Context, args *args.Args) []generator.Target
targetForGroup(
gv, orderer.OrderTypes(types), clientsetDir, clientsetPkg,
group.PackageName, groupGoNames[gv], args.ClientsetAPIPath,
inputPath, args.ApplyConfigurationPackage, boilerplate))
inputPath, args.ApplyConfigurationPackage, boilerplate, args.PrefersProtobuf))
if args.FakeClient {
targetList = append(targetList,
fake.TargetForGroup(gv, orderer.OrderTypes(types), clientsetDir, clientsetPkg, group.PackageName, groupGoNames[gv], inputPath, args.ApplyConfigurationPackage, boilerplate))

View File

@@ -58,12 +58,12 @@ func TargetForGroup(gv clientgentypes.GroupVersion, typeList []*types.Type, clie
OutputFilename: "fake_" + strings.ToLower(c.Namers["private"].Name(t)) + ".go",
},
outputPackage: outputPkg,
realClientPackage: realClientPkg,
inputPackage: inputPkg,
group: gv.Group.NonEmpty(),
version: gv.Version.String(),
groupGoName: groupGoName,
typeToMatch: t,
imports: generator.NewImportTracker(),
imports: generator.NewImportTrackerForPackage(outputPkg),
applyConfigurationPackage: applyBuilderPackage,
})
}
@@ -74,11 +74,10 @@ func TargetForGroup(gv clientgentypes.GroupVersion, typeList []*types.Type, clie
},
outputPackage: outputPkg,
realClientPackage: realClientPkg,
group: gv.Group.NonEmpty(),
version: gv.Version.String(),
groupGoName: groupGoName,
types: typeList,
imports: generator.NewImportTracker(),
imports: generator.NewImportTrackerForPackage(outputPkg),
})
return generators
},
@@ -111,7 +110,7 @@ func TargetForClientset(args *args.Args, clientsetDir, clientsetPkg string, appl
groups: args.Groups,
groupGoNames: groupGoNames,
fakeClientsetPackage: clientsetPkg,
imports: generator.NewImportTracker(),
imports: generator.NewImportTrackerForPackage(clientsetPkg),
realClientsetPackage: clientsetPkg,
applyConfigurationPackage: applyConfigurationPkg,
},
@@ -123,7 +122,7 @@ func TargetForClientset(args *args.Args, clientsetDir, clientsetPkg string, appl
OutputPkg: clientsetPkg,
Groups: args.Groups,
GroupGoNames: groupGoNames,
ImportTracker: generator.NewImportTracker(),
ImportTracker: generator.NewImportTrackerForPackage(clientsetPkg),
PrivateScheme: true,
},
}

View File

@@ -77,7 +77,6 @@ func (g *genClientset) Imports(c *generator.Context) (imports []string) {
"fakediscovery \"k8s.io/client-go/discovery/fake\"",
"k8s.io/apimachinery/pkg/runtime",
"k8s.io/apimachinery/pkg/watch",
"k8s.io/apimachinery/pkg/api/meta/testrestmapper",
)
return

View File

@@ -34,7 +34,6 @@ type genFakeForGroup struct {
generator.GoGenerator
outputPackage string // must be a Go import-path
realClientPackage string // must be a Go import-path
group string
version string
groupGoName string
// types in this group
@@ -78,6 +77,8 @@ func (g *genFakeForGroup) GenerateType(c *generator.Context, t *types.Type, w io
"Fake": c.Universe.Type(types.Name{Package: "k8s.io/client-go/testing", Name: "Fake"}),
"RESTClientInterface": c.Universe.Type(types.Name{Package: "k8s.io/client-go/rest", Name: "Interface"}),
"RESTClient": c.Universe.Type(types.Name{Package: "k8s.io/client-go/rest", Name: "RESTClient"}),
"FakeClient": c.Universe.Type(types.Name{Package: "k8s.io/client-go/gentype", Name: "FakeClient"}),
"NewFakeClient": c.Universe.Function(types.Name{Package: "k8s.io/client-go/gentype", Name: "NewFakeClient"}),
}
sw.Do(groupClientTemplate, m)
@@ -110,13 +111,13 @@ type Fake$.GroupGoName$$.Version$ struct {
var getterImplNamespaced = `
func (c *Fake$.GroupGoName$$.Version$) $.type|publicPlural$(namespace string) $.realClientPackage$.$.type|public$Interface {
return &Fake$.type|publicPlural${c, namespace}
return newFake$.type|publicPlural$(c, namespace)
}
`
var getterImplNonNamespaced = `
func (c *Fake$.GroupGoName$$.Version$) $.type|publicPlural$() $.realClientPackage$.$.type|public$Interface {
return &Fake$.type|publicPlural${c}
return newFake$.type|publicPlural$(c)
}
`

View File

@@ -35,7 +35,7 @@ import (
type genFakeForType struct {
generator.GoGenerator
outputPackage string // Must be a Go import-path
group string
realClientPackage string // Must be a Go import-path
version string
groupGoName string
inputPackage string
@@ -61,37 +61,9 @@ func (g *genFakeForType) Imports(c *generator.Context) (imports []string) {
return g.imports.ImportLines()
}
// Ideally, we'd like genStatus to return true if there is a subresource path
// registered for "status" in the API server, but we do not have that
// information, so genStatus returns true if the type has a status field.
func genStatus(t *types.Type) bool {
// Default to true if we have a Status member
hasStatus := false
for _, m := range t.Members {
if m.Name == "Status" {
hasStatus = true
break
}
}
tags := util.MustParseClientGenTags(append(t.SecondClosestCommentLines, t.CommentLines...))
return hasStatus && !tags.NoStatus
}
// hasObjectMeta returns true if the type has a ObjectMeta field.
func hasObjectMeta(t *types.Type) bool {
for _, m := range t.Members {
if m.Embedded && m.Name == "ObjectMeta" {
return true
}
}
return false
}
// GenerateType makes the body of a file implementing the individual typed client for type t.
func (g *genFakeForType) GenerateType(c *generator.Context, t *types.Type, w io.Writer) error {
sw := generator.NewSnippetWriter(w, c, "$", "$")
pkg := path.Base(t.Name.Package)
tags, err := util.ParseClientGenTags(append(t.SecondClosestCommentLines, t.CommentLines...))
if err != nil {
return err
@@ -99,30 +71,28 @@ func (g *genFakeForType) GenerateType(c *generator.Context, t *types.Type, w io.
const pkgClientGoTesting = "k8s.io/client-go/testing"
m := map[string]interface{}{
"type": t,
"inputType": t,
"resultType": t,
"subresourcePath": "",
"package": pkg,
"Package": namer.IC(pkg),
"namespaced": !tags.NonNamespaced,
"Group": namer.IC(g.group),
"GroupGoName": g.groupGoName,
"Version": namer.IC(g.version),
"version": g.version,
"SchemeGroupVersion": c.Universe.Type(types.Name{Package: t.Name.Package, Name: "SchemeGroupVersion"}),
"CreateOptions": c.Universe.Type(types.Name{Package: "k8s.io/apimachinery/pkg/apis/meta/v1", Name: "CreateOptions"}),
"DeleteOptions": c.Universe.Type(types.Name{Package: "k8s.io/apimachinery/pkg/apis/meta/v1", Name: "DeleteOptions"}),
"GetOptions": c.Universe.Type(types.Name{Package: "k8s.io/apimachinery/pkg/apis/meta/v1", Name: "GetOptions"}),
"ListOptions": c.Universe.Type(types.Name{Package: "k8s.io/apimachinery/pkg/apis/meta/v1", Name: "ListOptions"}),
"PatchOptions": c.Universe.Type(types.Name{Package: "k8s.io/apimachinery/pkg/apis/meta/v1", Name: "PatchOptions"}),
"ApplyOptions": c.Universe.Type(types.Name{Package: "k8s.io/apimachinery/pkg/apis/meta/v1", Name: "ApplyOptions"}),
"UpdateOptions": c.Universe.Type(types.Name{Package: "k8s.io/apimachinery/pkg/apis/meta/v1", Name: "UpdateOptions"}),
"Everything": c.Universe.Function(types.Name{Package: "k8s.io/apimachinery/pkg/labels", Name: "Everything"}),
"PatchType": c.Universe.Type(types.Name{Package: "k8s.io/apimachinery/pkg/types", Name: "PatchType"}),
"ApplyPatchType": c.Universe.Type(types.Name{Package: "k8s.io/apimachinery/pkg/types", Name: "ApplyPatchType"}),
"watchInterface": c.Universe.Type(types.Name{Package: "k8s.io/apimachinery/pkg/watch", Name: "Interface"}),
"jsonMarshal": c.Universe.Type(types.Name{Package: "encoding/json", Name: "Marshal"}),
"type": t,
"inputType": t,
"resultType": t,
"subresourcePath": "",
"namespaced": !tags.NonNamespaced,
"GroupGoName": g.groupGoName,
"Version": namer.IC(g.version),
"realClientInterface": c.Universe.Type(types.Name{Package: g.realClientPackage, Name: t.Name.Name + "Interface"}),
"SchemeGroupVersion": c.Universe.Type(types.Name{Package: t.Name.Package, Name: "SchemeGroupVersion"}),
"CreateOptions": c.Universe.Type(types.Name{Package: "k8s.io/apimachinery/pkg/apis/meta/v1", Name: "CreateOptions"}),
"DeleteOptions": c.Universe.Type(types.Name{Package: "k8s.io/apimachinery/pkg/apis/meta/v1", Name: "DeleteOptions"}),
"GetOptions": c.Universe.Type(types.Name{Package: "k8s.io/apimachinery/pkg/apis/meta/v1", Name: "GetOptions"}),
"ListOptions": c.Universe.Type(types.Name{Package: "k8s.io/apimachinery/pkg/apis/meta/v1", Name: "ListOptions"}),
"PatchOptions": c.Universe.Type(types.Name{Package: "k8s.io/apimachinery/pkg/apis/meta/v1", Name: "PatchOptions"}),
"ApplyOptions": c.Universe.Type(types.Name{Package: "k8s.io/apimachinery/pkg/apis/meta/v1", Name: "ApplyOptions"}),
"UpdateOptions": c.Universe.Type(types.Name{Package: "k8s.io/apimachinery/pkg/apis/meta/v1", Name: "UpdateOptions"}),
"PatchType": c.Universe.Type(types.Name{Package: "k8s.io/apimachinery/pkg/types", Name: "PatchType"}),
"ApplyPatchType": c.Universe.Type(types.Name{Package: "k8s.io/apimachinery/pkg/types", Name: "ApplyPatchType"}),
"watchInterface": c.Universe.Type(types.Name{Package: "k8s.io/apimachinery/pkg/watch", Name: "Interface"}),
"jsonMarshal": c.Universe.Type(types.Name{Package: "encoding/json", Name: "Marshal"}),
"fmtErrorf": c.Universe.Type(types.Name{Package: "fmt", Name: "Errorf"}),
"contextContext": c.Universe.Type(types.Name{Package: "context", Name: "Context"}),
"NewRootListActionWithOptions": c.Universe.Function(types.Name{Package: pkgClientGoTesting, Name: "NewRootListActionWithOptions"}),
"NewListActionWithOptions": c.Universe.Function(types.Name{Package: pkgClientGoTesting, Name: "NewListActionWithOptions"}),
@@ -130,8 +100,6 @@ func (g *genFakeForType) GenerateType(c *generator.Context, t *types.Type, w io.
"NewGetActionWithOptions": c.Universe.Function(types.Name{Package: pkgClientGoTesting, Name: "NewGetActionWithOptions"}),
"NewRootDeleteActionWithOptions": c.Universe.Function(types.Name{Package: pkgClientGoTesting, Name: "NewRootDeleteActionWithOptions"}),
"NewDeleteActionWithOptions": c.Universe.Function(types.Name{Package: pkgClientGoTesting, Name: "NewDeleteActionWithOptions"}),
"NewRootDeleteCollectionActionWithOptions": c.Universe.Function(types.Name{Package: pkgClientGoTesting, Name: "NewRootDeleteCollectionActionWithOptions"}),
"NewDeleteCollectionActionWithOptions": c.Universe.Function(types.Name{Package: pkgClientGoTesting, Name: "NewDeleteCollectionActionWithOptions"}),
"NewRootUpdateActionWithOptions": c.Universe.Function(types.Name{Package: pkgClientGoTesting, Name: "NewRootUpdateActionWithOptions"}),
"NewUpdateActionWithOptions": c.Universe.Function(types.Name{Package: pkgClientGoTesting, Name: "NewUpdateActionWithOptions"}),
"NewRootCreateActionWithOptions": c.Universe.Function(types.Name{Package: pkgClientGoTesting, Name: "NewRootCreateActionWithOptions"}),
@@ -144,11 +112,16 @@ func (g *genFakeForType) GenerateType(c *generator.Context, t *types.Type, w io.
"NewGetSubresourceActionWithOptions": c.Universe.Function(types.Name{Package: pkgClientGoTesting, Name: "NewGetSubresourceActionWithOptions"}),
"NewRootGetSubresourceActionWithOptions": c.Universe.Function(types.Name{Package: pkgClientGoTesting, Name: "NewRootGetSubresourceActionWithOptions"}),
"NewRootUpdateSubresourceActionWithOptions": c.Universe.Function(types.Name{Package: pkgClientGoTesting, Name: "NewRootUpdateSubresourceActionWithOptions"}),
"NewRootPatchActionWithOptions": c.Universe.Function(types.Name{Package: pkgClientGoTesting, Name: "NewRootPatchActionWithOptions"}),
"NewPatchActionWithOptions": c.Universe.Function(types.Name{Package: pkgClientGoTesting, Name: "NewPatchActionWithOptions"}),
"NewRootPatchSubresourceActionWithOptions": c.Universe.Function(types.Name{Package: pkgClientGoTesting, Name: "NewRootPatchSubresourceActionWithOptions"}),
"NewPatchSubresourceActionWithOptions": c.Universe.Function(types.Name{Package: pkgClientGoTesting, Name: "NewPatchSubresourceActionWithOptions"}),
"ExtractFromListOptions": c.Universe.Function(types.Name{Package: pkgClientGoTesting, Name: "ExtractFromListOptions"}),
"FakeClient": c.Universe.Type(types.Name{Package: "k8s.io/client-go/gentype", Name: "FakeClient"}),
"NewFakeClient": c.Universe.Function(types.Name{Package: "k8s.io/client-go/gentype", Name: "NewFakeClient"}),
"FakeClientWithApply": c.Universe.Type(types.Name{Package: "k8s.io/client-go/gentype", Name: "FakeClientWithApply"}),
"NewFakeClientWithApply": c.Universe.Function(types.Name{Package: "k8s.io/client-go/gentype", Name: "NewFakeClientWithApply"}),
"FakeClientWithList": c.Universe.Type(types.Name{Package: "k8s.io/client-go/gentype", Name: "FakeClientWithList"}),
"NewFakeClientWithList": c.Universe.Function(types.Name{Package: "k8s.io/client-go/gentype", Name: "NewFakeClientWithList"}),
"FakeClientWithListAndApply": c.Universe.Type(types.Name{Package: "k8s.io/client-go/gentype", Name: "FakeClientWithListAndApply"}),
"NewFakeClientWithListAndApply": c.Universe.Function(types.Name{Package: "k8s.io/client-go/gentype", Name: "NewFakeClientWithListAndApply"}),
}
generateApply := len(g.applyConfigurationPackage) > 0
@@ -158,56 +131,23 @@ func (g *genFakeForType) GenerateType(c *generator.Context, t *types.Type, w io.
m["inputApplyConfig"] = types.Ref(path.Join(g.applyConfigurationPackage, gvString), t.Name.Name+"ApplyConfiguration")
}
if tags.NonNamespaced {
sw.Do(structNonNamespaced, m)
} else {
sw.Do(structNamespaced, m)
listableOrAppliable := noList | noApply
if !tags.NoVerbs && tags.HasVerb("list") {
listableOrAppliable |= withList
}
if !tags.NoVerbs && tags.HasVerb("apply") && generateApply {
listableOrAppliable |= withApply
}
sw.Do(structType[listableOrAppliable], m)
sw.Do(newStruct[listableOrAppliable], m)
if tags.NoVerbs {
return sw.Error()
}
sw.Do(resource, m)
sw.Do(kind, m)
if tags.HasVerb("get") {
sw.Do(getTemplate, m)
}
if tags.HasVerb("list") {
if hasObjectMeta(t) {
sw.Do(listUsingOptionsTemplate, m)
} else {
sw.Do(listTemplate, m)
}
}
if tags.HasVerb("watch") {
sw.Do(watchTemplate, m)
}
if tags.HasVerb("create") {
sw.Do(createTemplate, m)
}
if tags.HasVerb("update") {
sw.Do(updateTemplate, m)
}
if tags.HasVerb("updateStatus") && genStatus(t) {
sw.Do(updateStatusTemplate, m)
}
if tags.HasVerb("delete") {
sw.Do(deleteTemplate, m)
}
if tags.HasVerb("deleteCollection") {
sw.Do(deleteCollectionTemplate, m)
}
if tags.HasVerb("patch") {
sw.Do(patchTemplate, m)
}
if tags.HasVerb("apply") && generateApply {
sw.Do(applyTemplate, m)
}
if tags.HasVerb("applyStatus") && generateApply && genStatus(t) {
sw.Do(applyStatusTemplate, m)
}
_, typeGVString := util.ParsePathGroupVersion(g.inputPackage)
// generate extended client methods
@@ -251,7 +191,6 @@ func (g *genFakeForType) GenerateType(c *generator.Context, t *types.Type, w io.
}
if e.HasVerb("list") {
sw.Do(adjustTemplate(e.VerbName, e.VerbType, listTemplate), m)
}
@@ -305,38 +244,133 @@ func adjustTemplate(name, verbType, template string) string {
return strings.ReplaceAll(template, " "+titler.String(verbType), " "+name)
}
// template for the struct that implements the type's interface
var structNamespaced = `
// Fake$.type|publicPlural$ implements $.type|public$Interface
type Fake$.type|publicPlural$ struct {
Fake *Fake$.GroupGoName$$.Version$
ns string
// struct and constructor variants
const (
// The following values are bits in a bitmask.
// The values which can be set indicate list support and apply support;
// to make the declarations easier to read (like a truth table), corresponding zero-values
// are also declared.
noList = 0
noApply = 0
withList = 1 << iota
withApply
)
// The following string slices are similar to maps, but with combinable keys used as indices.
// Each entry defines whether it supports lists and/or apply; each bit is then toggled:
// * noList, noApply: index 0;
// * withList, noApply: index 1;
// * noList, withApply: index 2;
// * withList, withApply: index 3.
// Go enforces index unicity in these kinds of declarations.
// struct declarations
var structType = []string{
noList | noApply: `
// fake$.type|publicPlural$ implements $.type|public$Interface
type fake$.type|publicPlural$ struct {
*$.FakeClient|raw$[*$.type|raw$]
Fake *Fake$.GroupGoName$$.Version$
}
`,
withList | noApply: `
// fake$.type|publicPlural$ implements $.type|public$Interface
type fake$.type|publicPlural$ struct {
*$.FakeClientWithList|raw$[*$.type|raw$, *$.type|raw$List]
Fake *Fake$.GroupGoName$$.Version$
}
`,
noList | withApply: `
// fake$.type|publicPlural$ implements $.type|public$Interface
type fake$.type|publicPlural$ struct {
*$.FakeClientWithApply|raw$[*$.type|raw$, *$.inputApplyConfig|raw$]
Fake *Fake$.GroupGoName$$.Version$
}
`,
withList | withApply: `
// fake$.type|publicPlural$ implements $.type|public$Interface
type fake$.type|publicPlural$ struct {
*$.FakeClientWithListAndApply|raw$[*$.type|raw$, *$.type|raw$List, *$.inputApplyConfig|raw$]
Fake *Fake$.GroupGoName$$.Version$
}
`,
}
`
// template for the struct that implements the type's interface
var structNonNamespaced = `
// Fake$.type|publicPlural$ implements $.type|public$Interface
type Fake$.type|publicPlural$ struct {
Fake *Fake$.GroupGoName$$.Version$
// Constructors for the struct, in all variants
var newStruct = []string{
noList | noApply: `
func newFake$.type|publicPlural$(fake *Fake$.GroupGoName$$.Version$$if .namespaced$, namespace string$end$) $.realClientInterface|raw$ {
return &fake$.type|publicPlural${
$.NewFakeClient|raw$[*$.type|raw$](
fake.Fake,
$if .namespaced$namespace$else$""$end$,
$.SchemeGroupVersion|raw$.WithResource("$.type|resource$"),
$.SchemeGroupVersion|raw$.WithKind("$.type|singularKind$"),
func() *$.type|raw$ {return &$.type|raw${}},
),
fake,
}
}
`,
noList | withApply: `
func newFake$.type|publicPlural$(fake *Fake$.GroupGoName$$.Version$$if .namespaced$, namespace string$end$) $.realClientInterface|raw$ {
return &fake$.type|publicPlural${
$.NewFakeClientWithApply|raw$[*$.type|raw$, *$.inputApplyConfig|raw$](
fake.Fake,
$if .namespaced$namespace$else$""$end$,
$.SchemeGroupVersion|raw$.WithResource("$.type|resource$"),
$.SchemeGroupVersion|raw$.WithKind("$.type|singularKind$"),
func() *$.type|raw$ {return &$.type|raw${}},
),
fake,
}
}
`,
withList | noApply: `
func newFake$.type|publicPlural$(fake *Fake$.GroupGoName$$.Version$$if .namespaced$, namespace string$end$) $.realClientInterface|raw$ {
return &fake$.type|publicPlural${
$.NewFakeClientWithList|raw$[*$.type|raw$, *$.type|raw$List](
fake.Fake,
$if .namespaced$namespace$else$""$end$,
$.SchemeGroupVersion|raw$.WithResource("$.type|resource$"),
$.SchemeGroupVersion|raw$.WithKind("$.type|singularKind$"),
func() *$.type|raw$ {return &$.type|raw${}},
func() *$.type|raw$List {return &$.type|raw$List{}},
func(dst, src *$.type|raw$List) {dst.ListMeta = src.ListMeta},
func(list *$.type|raw$List) []*$.type|raw$ {return gentype.ToPointerSlice(list.Items)},
func(list *$.type|raw$List, items []*$.type|raw$) {list.Items = gentype.FromPointerSlice(items)},
),
fake,
}
}
`,
withList | withApply: `
func newFake$.type|publicPlural$(fake *Fake$.GroupGoName$$.Version$$if .namespaced$, namespace string$end$) $.realClientInterface|raw$ {
return &fake$.type|publicPlural${
$.NewFakeClientWithListAndApply|raw$[*$.type|raw$, *$.type|raw$List, *$.inputApplyConfig|raw$](
fake.Fake,
$if .namespaced$namespace$else$""$end$,
$.SchemeGroupVersion|raw$.WithResource("$.type|resource$"),
$.SchemeGroupVersion|raw$.WithKind("$.type|singularKind$"),
func() *$.type|raw$ {return &$.type|raw${}},
func() *$.type|raw$List {return &$.type|raw$List{}},
func(dst, src *$.type|raw$List) {dst.ListMeta = src.ListMeta},
func(list *$.type|raw$List) []*$.type|raw$ {return gentype.ToPointerSlice(list.Items)},
func(list *$.type|raw$List, items []*$.type|raw$) {list.Items = gentype.FromPointerSlice(items)},
),
fake,
}
}
`,
}
`
var resource = `
var $.type|allLowercasePlural$Resource = $.SchemeGroupVersion|raw$.WithResource("$.type|resource$")
`
var kind = `
var $.type|allLowercasePlural$Kind = $.SchemeGroupVersion|raw$.WithKind("$.type|singularKind$")
`
var listTemplate = `
// List takes label and field selectors, and returns the list of $.type|publicPlural$ that match those selectors.
func (c *Fake$.type|publicPlural$) List(ctx context.Context, opts $.ListOptions|raw$) (result *$.type|raw$List, err error) {
func (c *fake$.type|publicPlural$) List(ctx $.contextContext|raw$, opts $.ListOptions|raw$) (result *$.type|raw$List, err error) {
emptyResult := &$.type|raw$List{}
obj, err := c.Fake.
$if .namespaced$Invokes($.NewListActionWithOptions|raw$($.type|allLowercasePlural$Resource, $.type|allLowercasePlural$Kind, c.ns, opts), emptyResult)
$else$Invokes($.NewRootListActionWithOptions|raw$($.type|allLowercasePlural$Resource, $.type|allLowercasePlural$Kind, opts), emptyResult)$end$
$if .namespaced$Invokes($.NewListActionWithOptions|raw$(c.Resource(), c.Kind(), c.Namespace(), opts), emptyResult)
$else$Invokes($.NewRootListActionWithOptions|raw$(c.Resource(), c.Kind(), opts), emptyResult)$end$
if obj == nil {
return emptyResult, err
}
@@ -344,38 +378,13 @@ func (c *Fake$.type|publicPlural$) List(ctx context.Context, opts $.ListOptions|
}
`
var listUsingOptionsTemplate = `
// List takes label and field selectors, and returns the list of $.type|publicPlural$ that match those selectors.
func (c *Fake$.type|publicPlural$) List(ctx context.Context, opts $.ListOptions|raw$) (result *$.type|raw$List, err error) {
emptyResult := &$.type|raw$List{}
obj, err := c.Fake.
$if .namespaced$Invokes($.NewListActionWithOptions|raw$($.type|allLowercasePlural$Resource, $.type|allLowercasePlural$Kind, c.ns, opts), emptyResult)
$else$Invokes($.NewRootListActionWithOptions|raw$($.type|allLowercasePlural$Resource, $.type|allLowercasePlural$Kind, opts), emptyResult)$end$
if obj == nil {
return emptyResult, err
}
label, _, _ := $.ExtractFromListOptions|raw$(opts)
if label == nil {
label = $.Everything|raw$()
}
list := &$.type|raw$List{ListMeta: obj.(*$.type|raw$List).ListMeta}
for _, item := range obj.(*$.type|raw$List).Items {
if label.Matches(labels.Set(item.Labels)) {
list.Items = append(list.Items, item)
}
}
return list, err
}
`
var getTemplate = `
// Get takes name of the $.type|private$, and returns the corresponding $.resultType|private$ object, and an error if there is any.
func (c *Fake$.type|publicPlural$) Get(ctx context.Context, name string, options $.GetOptions|raw$) (result *$.resultType|raw$, err error) {
func (c *fake$.type|publicPlural$) Get(ctx $.contextContext|raw$, name string, options $.GetOptions|raw$) (result *$.resultType|raw$, err error) {
emptyResult := &$.resultType|raw${}
obj, err := c.Fake.
$if .namespaced$Invokes($.NewGetActionWithOptions|raw$($.type|allLowercasePlural$Resource, c.ns, name, options), emptyResult)
$else$Invokes($.NewRootGetActionWithOptions|raw$($.type|allLowercasePlural$Resource, name, options), emptyResult)$end$
$if .namespaced$Invokes($.NewGetActionWithOptions|raw$(c.Resource(), c.Namespace(), name, options), emptyResult)
$else$Invokes($.NewRootGetActionWithOptions|raw$(c.Resource(), name, options), emptyResult)$end$
if obj == nil {
return emptyResult, err
}
@@ -385,11 +394,11 @@ func (c *Fake$.type|publicPlural$) Get(ctx context.Context, name string, options
var getSubresourceTemplate = `
// Get takes name of the $.type|private$, and returns the corresponding $.resultType|private$ object, and an error if there is any.
func (c *Fake$.type|publicPlural$) Get(ctx context.Context, $.type|private$Name string, options $.GetOptions|raw$) (result *$.resultType|raw$, err error) {
func (c *fake$.type|publicPlural$) Get(ctx $.contextContext|raw$, $.type|private$Name string, options $.GetOptions|raw$) (result *$.resultType|raw$, err error) {
emptyResult := &$.resultType|raw${}
obj, err := c.Fake.
$if .namespaced$Invokes($.NewGetSubresourceActionWithOptions|raw$($.type|allLowercasePlural$Resource, c.ns, "$.subresourcePath$", $.type|private$Name, options), emptyResult)
$else$Invokes($.NewRootGetSubresourceActionWithOptions|raw$($.type|allLowercasePlural$Resource, "$.subresourcePath$", $.type|private$Name, options), emptyResult)$end$
$if .namespaced$Invokes($.NewGetSubresourceActionWithOptions|raw$(c.Resource(), c.Namespace(), "$.subresourcePath$", $.type|private$Name, options), emptyResult)
$else$Invokes($.NewRootGetSubresourceActionWithOptions|raw$(c.Resource(), "$.subresourcePath$", $.type|private$Name, options), emptyResult)$end$
if obj == nil {
return emptyResult, err
}
@@ -399,31 +408,21 @@ func (c *Fake$.type|publicPlural$) Get(ctx context.Context, $.type|private$Name
var deleteTemplate = `
// Delete takes name of the $.type|private$ and deletes it. Returns an error if one occurs.
func (c *Fake$.type|publicPlural$) Delete(ctx context.Context, name string, opts $.DeleteOptions|raw$) error {
func (c *fake$.type|publicPlural$) Delete(ctx $.contextContext|raw$, name string, opts $.DeleteOptions|raw$) error {
_, err := c.Fake.
$if .namespaced$Invokes($.NewDeleteActionWithOptions|raw$($.type|allLowercasePlural$Resource, c.ns, name, opts), &$.type|raw${})
$else$Invokes($.NewRootDeleteActionWithOptions|raw$($.type|allLowercasePlural$Resource, name, opts), &$.type|raw${})$end$
$if .namespaced$Invokes($.NewDeleteActionWithOptions|raw$(c.Resource(), c.Namespace(), name, opts), &$.type|raw${})
$else$Invokes($.NewRootDeleteActionWithOptions|raw$(c.Resource(), name, opts), &$.type|raw${})$end$
return err
}
`
var deleteCollectionTemplate = `
// DeleteCollection deletes a collection of objects.
func (c *Fake$.type|publicPlural$) DeleteCollection(ctx context.Context, opts $.DeleteOptions|raw$, listOpts $.ListOptions|raw$) error {
$if .namespaced$action := $.NewDeleteCollectionActionWithOptions|raw$($.type|allLowercasePlural$Resource, c.ns, opts, listOpts)
$else$action := $.NewRootDeleteCollectionActionWithOptions|raw$($.type|allLowercasePlural$Resource, opts, listOpts)
$end$
_, err := c.Fake.Invokes(action, &$.type|raw$List{})
return err
}
`
var createTemplate = `
// Create takes the representation of a $.inputType|private$ and creates it. Returns the server's representation of the $.resultType|private$, and an error, if there is any.
func (c *Fake$.type|publicPlural$) Create(ctx context.Context, $.inputType|private$ *$.inputType|raw$, opts $.CreateOptions|raw$) (result *$.resultType|raw$, err error) {
func (c *fake$.type|publicPlural$) Create(ctx $.contextContext|raw$, $.inputType|private$ *$.inputType|raw$, opts $.CreateOptions|raw$) (result *$.resultType|raw$, err error) {
emptyResult := &$.resultType|raw${}
obj, err := c.Fake.
$if .namespaced$Invokes($.NewCreateActionWithOptions|raw$($.inputType|allLowercasePlural$Resource, c.ns, $.inputType|private$, opts), emptyResult)
$else$Invokes($.NewRootCreateActionWithOptions|raw$($.inputType|allLowercasePlural$Resource, $.inputType|private$, opts), emptyResult)$end$
$if .namespaced$Invokes($.NewCreateActionWithOptions|raw$(c.Resource(), c.Namespace(), $.inputType|private$, opts), emptyResult)
$else$Invokes($.NewRootCreateActionWithOptions|raw$(c.Resource(), $.inputType|private$, opts), emptyResult)$end$
if obj == nil {
return emptyResult, err
}
@@ -433,11 +432,11 @@ func (c *Fake$.type|publicPlural$) Create(ctx context.Context, $.inputType|priva
var createSubresourceTemplate = `
// Create takes the representation of a $.inputType|private$ and creates it. Returns the server's representation of the $.resultType|private$, and an error, if there is any.
func (c *Fake$.type|publicPlural$) Create(ctx context.Context, $.type|private$Name string, $.inputType|private$ *$.inputType|raw$, opts $.CreateOptions|raw$) (result *$.resultType|raw$, err error) {
func (c *fake$.type|publicPlural$) Create(ctx $.contextContext|raw$, $.type|private$Name string, $.inputType|private$ *$.inputType|raw$, opts $.CreateOptions|raw$) (result *$.resultType|raw$, err error) {
emptyResult := &$.resultType|raw${}
obj, err := c.Fake.
$if .namespaced$Invokes($.NewCreateSubresourceActionWithOptions|raw$($.type|allLowercasePlural$Resource, $.type|private$Name, "$.subresourcePath$", c.ns, $.inputType|private$, opts), emptyResult)
$else$Invokes($.NewRootCreateSubresourceActionWithOptions|raw$($.type|allLowercasePlural$Resource, $.type|private$Name, "$.subresourcePath$", $.inputType|private$, opts), emptyResult)$end$
$if .namespaced$Invokes($.NewCreateSubresourceActionWithOptions|raw$(c.Resource(), $.type|private$Name, "$.subresourcePath$", c.Namespace(), $.inputType|private$, opts), emptyResult)
$else$Invokes($.NewRootCreateSubresourceActionWithOptions|raw$(c.Resource(), $.type|private$Name, "$.subresourcePath$", $.inputType|private$, opts), emptyResult)$end$
if obj == nil {
return emptyResult, err
}
@@ -447,11 +446,11 @@ func (c *Fake$.type|publicPlural$) Create(ctx context.Context, $.type|private$Na
var updateTemplate = `
// Update takes the representation of a $.inputType|private$ and updates it. Returns the server's representation of the $.resultType|private$, and an error, if there is any.
func (c *Fake$.type|publicPlural$) Update(ctx context.Context, $.inputType|private$ *$.inputType|raw$, opts $.UpdateOptions|raw$) (result *$.resultType|raw$, err error) {
func (c *fake$.type|publicPlural$) Update(ctx $.contextContext|raw$, $.inputType|private$ *$.inputType|raw$, opts $.UpdateOptions|raw$) (result *$.resultType|raw$, err error) {
emptyResult := &$.resultType|raw${}
obj, err := c.Fake.
$if .namespaced$Invokes($.NewUpdateActionWithOptions|raw$($.inputType|allLowercasePlural$Resource, c.ns, $.inputType|private$, opts), emptyResult)
$else$Invokes($.NewRootUpdateActionWithOptions|raw$($.inputType|allLowercasePlural$Resource, $.inputType|private$, opts), emptyResult)$end$
$if .namespaced$Invokes($.NewUpdateActionWithOptions|raw$(c.Resource(), c.Namespace(), $.inputType|private$, opts), emptyResult)
$else$Invokes($.NewRootUpdateActionWithOptions|raw$(c.Resource(), $.inputType|private$, opts), emptyResult)$end$
if obj == nil {
return emptyResult, err
}
@@ -461,11 +460,11 @@ func (c *Fake$.type|publicPlural$) Update(ctx context.Context, $.inputType|priva
var updateSubresourceTemplate = `
// Update takes the representation of a $.inputType|private$ and updates it. Returns the server's representation of the $.resultType|private$, and an error, if there is any.
func (c *Fake$.type|publicPlural$) Update(ctx context.Context, $.type|private$Name string, $.inputType|private$ *$.inputType|raw$, opts $.UpdateOptions|raw$) (result *$.resultType|raw$, err error) {
func (c *fake$.type|publicPlural$) Update(ctx $.contextContext|raw$, $.type|private$Name string, $.inputType|private$ *$.inputType|raw$, opts $.UpdateOptions|raw$) (result *$.resultType|raw$, err error) {
emptyResult := &$.resultType|raw${}
obj, err := c.Fake.
$if .namespaced$Invokes($.NewUpdateSubresourceActionWithOptions|raw$($.type|allLowercasePlural$Resource, "$.subresourcePath$", c.ns, $.inputType|private$, opts), &$.inputType|raw${})
$else$Invokes($.NewRootUpdateSubresourceActionWithOptions|raw$($.type|allLowercasePlural$Resource, "$.subresourcePath$", $.inputType|private$, opts), emptyResult)$end$
$if .namespaced$Invokes($.NewUpdateSubresourceActionWithOptions|raw$(c.Resource(), "$.subresourcePath$", c.Namespace(), $.inputType|private$, opts), &$.inputType|raw${})
$else$Invokes($.NewRootUpdateSubresourceActionWithOptions|raw$(c.Resource(), "$.subresourcePath$", $.inputType|private$, opts), emptyResult)$end$
if obj == nil {
return emptyResult, err
}
@@ -473,37 +472,22 @@ func (c *Fake$.type|publicPlural$) Update(ctx context.Context, $.type|private$Na
}
`
var updateStatusTemplate = `
// UpdateStatus was generated because the type contains a Status member.
// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus().
func (c *Fake$.type|publicPlural$) UpdateStatus(ctx context.Context, $.type|private$ *$.type|raw$, opts $.UpdateOptions|raw$) (result *$.type|raw$, err error) {
emptyResult := &$.type|raw${}
obj, err := c.Fake.
$if .namespaced$Invokes($.NewUpdateSubresourceActionWithOptions|raw$($.type|allLowercasePlural$Resource, "status", c.ns, $.type|private$, opts), emptyResult)
$else$Invokes($.NewRootUpdateSubresourceActionWithOptions|raw$($.type|allLowercasePlural$Resource, "status", $.type|private$, opts), emptyResult)$end$
if obj == nil {
return emptyResult, err
}
return obj.(*$.type|raw$), err
}
`
var watchTemplate = `
// Watch returns a $.watchInterface|raw$ that watches the requested $.type|privatePlural$.
func (c *Fake$.type|publicPlural$) Watch(ctx context.Context, opts $.ListOptions|raw$) ($.watchInterface|raw$, error) {
func (c *fake$.type|publicPlural$) Watch(ctx $.contextContext|raw$, opts $.ListOptions|raw$) ($.watchInterface|raw$, error) {
return c.Fake.
$if .namespaced$InvokesWatch($.NewWatchActionWithOptions|raw$($.type|allLowercasePlural$Resource, c.ns, opts))
$else$InvokesWatch($.NewRootWatchActionWithOptions|raw$($.type|allLowercasePlural$Resource, opts))$end$
$if .namespaced$InvokesWatch($.NewWatchActionWithOptions|raw$(c.Resource(), c.Namespace(), opts))
$else$InvokesWatch($.NewRootWatchActionWithOptions|raw$(c.Resource(), opts))$end$
}
`
var patchTemplate = `
// Patch applies the patch and returns the patched $.resultType|private$.
func (c *Fake$.type|publicPlural$) Patch(ctx context.Context, name string, pt $.PatchType|raw$, data []byte, opts $.PatchOptions|raw$, subresources ...string) (result *$.resultType|raw$, err error) {
func (c *fake$.type|publicPlural$) Patch(ctx $.contextContext|raw$, name string, pt $.PatchType|raw$, data []byte, opts $.PatchOptions|raw$, subresources ...string) (result *$.resultType|raw$, err error) {
emptyResult := &$.resultType|raw${}
obj, err := c.Fake.
$if .namespaced$Invokes($.NewPatchSubresourceActionWithOptions|raw$($.type|allLowercasePlural$Resource, c.ns, name, pt, data, opts, subresources... ), emptyResult)
$else$Invokes($.NewRootPatchSubresourceActionWithOptions|raw$($.type|allLowercasePlural$Resource, name, pt, data, opts, subresources...), emptyResult)$end$
$if .namespaced$Invokes($.NewPatchSubresourceActionWithOptions|raw$(c.Resource(), c.Namespace(), name, pt, data, opts, subresources... ), emptyResult)
$else$Invokes($.NewRootPatchSubresourceActionWithOptions|raw$(c.Resource(), name, pt, data, opts, subresources...), emptyResult)$end$
if obj == nil {
return emptyResult, err
}
@@ -513,9 +497,9 @@ func (c *Fake$.type|publicPlural$) Patch(ctx context.Context, name string, pt $.
var applyTemplate = `
// Apply takes the given apply declarative configuration, applies it and returns the applied $.resultType|private$.
func (c *Fake$.type|publicPlural$) Apply(ctx context.Context, $.inputType|private$ *$.inputApplyConfig|raw$, opts $.ApplyOptions|raw$) (result *$.resultType|raw$, err error) {
func (c *fake$.type|publicPlural$) Apply(ctx $.contextContext|raw$, $.inputType|private$ *$.inputApplyConfig|raw$, opts $.ApplyOptions|raw$) (result *$.resultType|raw$, err error) {
if $.inputType|private$ == nil {
return nil, fmt.Errorf("$.inputType|private$ provided to Apply must not be nil")
return nil, $.fmtErrorf|raw$("$.inputType|private$ provided to Apply must not be nil")
}
data, err := $.jsonMarshal|raw$($.inputType|private$)
if err != nil {
@@ -523,38 +507,12 @@ func (c *Fake$.type|publicPlural$) Apply(ctx context.Context, $.inputType|privat
}
name := $.inputType|private$.Name
if name == nil {
return nil, fmt.Errorf("$.inputType|private$.Name must be provided to Apply")
return nil, $.fmtErrorf|raw$("$.inputType|private$.Name must be provided to Apply")
}
emptyResult := &$.resultType|raw${}
obj, err := c.Fake.
$if .namespaced$Invokes($.NewPatchSubresourceActionWithOptions|raw$($.type|allLowercasePlural$Resource, c.ns, *name, $.ApplyPatchType|raw$, data, opts.ToPatchOptions()), emptyResult)
$else$Invokes($.NewRootPatchSubresourceActionWithOptions|raw$($.type|allLowercasePlural$Resource, *name, $.ApplyPatchType|raw$, data, opts.ToPatchOptions()), emptyResult)$end$
if obj == nil {
return emptyResult, err
}
return obj.(*$.resultType|raw$), err
}
`
var applyStatusTemplate = `
// ApplyStatus was generated because the type contains a Status member.
// Add a +genclient:noStatus comment above the type to avoid generating ApplyStatus().
func (c *Fake$.type|publicPlural$) ApplyStatus(ctx context.Context, $.inputType|private$ *$.inputApplyConfig|raw$, opts $.ApplyOptions|raw$) (result *$.resultType|raw$, err error) {
if $.inputType|private$ == nil {
return nil, fmt.Errorf("$.inputType|private$ provided to Apply must not be nil")
}
data, err := $.jsonMarshal|raw$($.inputType|private$)
if err != nil {
return nil, err
}
name := $.inputType|private$.Name
if name == nil {
return nil, fmt.Errorf("$.inputType|private$.Name must be provided to Apply")
}
emptyResult := &$.resultType|raw${}
obj, err := c.Fake.
$if .namespaced$Invokes($.NewPatchSubresourceActionWithOptions|raw$($.type|allLowercasePlural$Resource, c.ns, *name, $.ApplyPatchType|raw$, data, opts.ToPatchOptions(), "status"), emptyResult)
$else$Invokes($.NewRootPatchSubresourceActionWithOptions|raw$($.type|allLowercasePlural$Resource, *name, $.ApplyPatchType|raw$, data, opts.ToPatchOptions(), "status"), emptyResult)$end$
$if .namespaced$Invokes($.NewPatchSubresourceActionWithOptions|raw$(c.Resource(), c.Namespace(), *name, $.ApplyPatchType|raw$, data, opts.ToPatchOptions()), emptyResult)
$else$Invokes($.NewRootPatchSubresourceActionWithOptions|raw$(c.Resource(), *name, $.ApplyPatchType|raw$, data, opts.ToPatchOptions()), emptyResult)$end$
if obj == nil {
return emptyResult, err
}
@@ -565,9 +523,9 @@ func (c *Fake$.type|publicPlural$) ApplyStatus(ctx context.Context, $.inputType|
var applySubresourceTemplate = `
// Apply takes top resource name and the apply declarative configuration for $.subresourcePath$,
// applies it and returns the applied $.resultType|private$, and an error, if there is any.
func (c *Fake$.type|publicPlural$) Apply(ctx context.Context, $.type|private$Name string, $.inputType|private$ *$.inputApplyConfig|raw$, opts $.ApplyOptions|raw$) (result *$.resultType|raw$, err error) {
func (c *fake$.type|publicPlural$) Apply(ctx $.contextContext|raw$, $.type|private$Name string, $.inputType|private$ *$.inputApplyConfig|raw$, opts $.ApplyOptions|raw$) (result *$.resultType|raw$, err error) {
if $.inputType|private$ == nil {
return nil, fmt.Errorf("$.inputType|private$ provided to Apply must not be nil")
return nil, $.fmtErrorf|raw$("$.inputType|private$ provided to Apply must not be nil")
}
data, err := $.jsonMarshal|raw$($.inputType|private$)
if err != nil {
@@ -575,8 +533,8 @@ func (c *Fake$.type|publicPlural$) Apply(ctx context.Context, $.type|private$Nam
}
emptyResult := &$.resultType|raw${}
obj, err := c.Fake.
$if .namespaced$Invokes($.NewPatchSubresourceActionWithOptions|raw$($.type|allLowercasePlural$Resource, c.ns, $.type|private$Name, $.ApplyPatchType|raw$, data, opts.ToPatchOptions(), "$.inputType|private$"), emptyResult)
$else$Invokes($.NewRootPatchSubresourceActionWithOptions|raw$($.type|allLowercasePlural$Resource, $.type|private$Name, $.ApplyPatchType|raw$, data, opts.ToPatchOptions(), "$.inputType|private$"), emptyResult)$end$
$if .namespaced$Invokes($.NewPatchSubresourceActionWithOptions|raw$(c.Resource(), c.Namespace(), $.type|private$Name, $.ApplyPatchType|raw$, data, opts.ToPatchOptions(), "$.inputType|private$"), emptyResult)
$else$Invokes($.NewRootPatchSubresourceActionWithOptions|raw$(c.Resource(), $.type|private$Name, $.ApplyPatchType|raw$, data, opts.ToPatchOptions(), "$.inputType|private$"), emptyResult)$end$
if obj == nil {
return emptyResult, err
}

View File

@@ -73,12 +73,14 @@ func (g *genClientset) GenerateType(c *generator.Context, t *types.Type, w io.Wr
allGroups := clientgentypes.ToGroupVersionInfo(g.groups, g.groupGoNames)
m := map[string]interface{}{
"allGroups": allGroups,
"fmtErrorf": c.Universe.Type(types.Name{Package: "fmt", Name: "Errorf"}),
"Config": c.Universe.Type(types.Name{Package: "k8s.io/client-go/rest", Name: "Config"}),
"DefaultKubernetesUserAgent": c.Universe.Function(types.Name{Package: "k8s.io/client-go/rest", Name: "DefaultKubernetesUserAgent"}),
"RESTClientInterface": c.Universe.Type(types.Name{Package: "k8s.io/client-go/rest", Name: "Interface"}),
"RESTHTTPClientFor": c.Universe.Function(types.Name{Package: "k8s.io/client-go/rest", Name: "HTTPClientFor"}),
"DiscoveryInterface": c.Universe.Type(types.Name{Package: "k8s.io/client-go/discovery", Name: "DiscoveryInterface"}),
"DiscoveryClient": c.Universe.Type(types.Name{Package: "k8s.io/client-go/discovery", Name: "DiscoveryClient"}),
"httpClient": c.Universe.Type(types.Name{Package: "net/http", Name: "Client"}),
"NewDiscoveryClientForConfigAndClient": c.Universe.Function(types.Name{Package: "k8s.io/client-go/discovery", Name: "NewDiscoveryClientForConfigAndClient"}),
"NewDiscoveryClientForConfigOrDie": c.Universe.Function(types.Name{Package: "k8s.io/client-go/discovery", Name: "NewDiscoveryClientForConfigOrDie"}),
"NewDiscoveryClient": c.Universe.Function(types.Name{Package: "k8s.io/client-go/discovery", Name: "NewDiscoveryClient"}),
@@ -160,11 +162,11 @@ var newClientsetForConfigAndClientTemplate = `
// Note the http client provided takes precedence over the configured transport values.
// If config's RateLimiter is not set and QPS and Burst are acceptable,
// NewForConfigAndClient will generate a rate-limiter in configShallowCopy.
func NewForConfigAndClient(c *$.Config|raw$, httpClient *http.Client) (*Clientset, error) {
func NewForConfigAndClient(c *$.Config|raw$, httpClient *$.httpClient|raw$) (*Clientset, error) {
configShallowCopy := *c
if configShallowCopy.RateLimiter == nil && configShallowCopy.QPS > 0 {
if configShallowCopy.Burst <= 0 {
return nil, fmt.Errorf("burst is required to be greater than 0 when RateLimiter is not set and QPS is set to greater than 0")
return nil, $.fmtErrorf|raw$("burst is required to be greater than 0 when RateLimiter is not set and QPS is set to greater than 0")
}
configShallowCopy.RateLimiter = $.flowcontrolNewTokenBucketRateLimiter|raw$(configShallowCopy.QPS, configShallowCopy.Burst)
}

View File

@@ -64,7 +64,6 @@ func (g *genGroup) Namers(c *generator.Context) namer.NameSystems {
func (g *genGroup) Imports(c *generator.Context) (imports []string) {
imports = append(imports, g.imports.ImportLines()...)
imports = append(imports, path.Join(g.clientsetPackage, "scheme"))
return
}
@@ -82,23 +81,28 @@ func (g *genGroup) GenerateType(c *generator.Context, t *types.Type, w io.Writer
if groupName == "" {
apiPath = `"/api"`
}
schemePackage := path.Join(g.clientsetPackage, "scheme")
m := map[string]interface{}{
"version": g.version,
"groupName": groupName,
"GroupGoName": g.groupGoName,
"Version": namer.IC(g.version),
"types": g.types,
"apiPath": apiPath,
"schemaGroupVersion": c.Universe.Type(types.Name{Package: "k8s.io/apimachinery/pkg/runtime/schema", Name: "GroupVersion"}),
"runtimeAPIVersionInternal": c.Universe.Variable(types.Name{Package: "k8s.io/apimachinery/pkg/runtime", Name: "APIVersionInternal"}),
"restConfig": c.Universe.Type(types.Name{Package: "k8s.io/client-go/rest", Name: "Config"}),
"restDefaultKubernetesUserAgent": c.Universe.Function(types.Name{Package: "k8s.io/client-go/rest", Name: "DefaultKubernetesUserAgent"}),
"restRESTClientInterface": c.Universe.Type(types.Name{Package: "k8s.io/client-go/rest", Name: "Interface"}),
"RESTHTTPClientFor": c.Universe.Function(types.Name{Package: "k8s.io/client-go/rest", Name: "HTTPClientFor"}),
"restRESTClientFor": c.Universe.Function(types.Name{Package: "k8s.io/client-go/rest", Name: "RESTClientFor"}),
"restRESTClientForConfigAndClient": c.Universe.Function(types.Name{Package: "k8s.io/client-go/rest", Name: "RESTClientForConfigAndClient"}),
"SchemeGroupVersion": c.Universe.Variable(types.Name{Package: g.inputPackage, Name: "SchemeGroupVersion"}),
"version": g.version,
"groupName": groupName,
"GroupGoName": g.groupGoName,
"Version": namer.IC(g.version),
"types": g.types,
"apiPath": apiPath,
"httpClient": c.Universe.Type(types.Name{Package: "net/http", Name: "Client"}),
"schemaGroupVersion": c.Universe.Type(types.Name{Package: "k8s.io/apimachinery/pkg/runtime/schema", Name: "GroupVersion"}),
"runtimeAPIVersionInternal": c.Universe.Variable(types.Name{Package: "k8s.io/apimachinery/pkg/runtime", Name: "APIVersionInternal"}),
"restConfig": c.Universe.Type(types.Name{Package: "k8s.io/client-go/rest", Name: "Config"}),
"restDefaultKubernetesUserAgent": c.Universe.Function(types.Name{Package: "k8s.io/client-go/rest", Name: "DefaultKubernetesUserAgent"}),
"restRESTClientInterface": c.Universe.Type(types.Name{Package: "k8s.io/client-go/rest", Name: "Interface"}),
"RESTHTTPClientFor": c.Universe.Function(types.Name{Package: "k8s.io/client-go/rest", Name: "HTTPClientFor"}),
"restRESTClientFor": c.Universe.Function(types.Name{Package: "k8s.io/client-go/rest", Name: "RESTClientFor"}),
"restRESTClientForConfigAndClient": c.Universe.Function(types.Name{Package: "k8s.io/client-go/rest", Name: "RESTClientForConfigAndClient"}),
"restCodecFactoryForGeneratedClient": c.Universe.Function(types.Name{Package: "k8s.io/client-go/rest", Name: "CodecFactoryForGeneratedClient"}),
"SchemeGroupVersion": c.Universe.Variable(types.Name{Package: g.inputPackage, Name: "SchemeGroupVersion"}),
"SchemePrioritizedVersionsForGroup": c.Universe.Variable(types.Name{Package: schemePackage, Name: "Scheme.PrioritizedVersionsForGroup"}),
"Codecs": c.Universe.Variable(types.Name{Package: schemePackage, Name: "Codecs"}),
"Scheme": c.Universe.Variable(types.Name{Package: schemePackage, Name: "Scheme"}),
}
sw.Do(groupInterfaceTemplate, m)
sw.Do(groupClientTemplate, m)
@@ -179,7 +183,7 @@ func NewForConfig(c *$.restConfig|raw$) (*$.GroupGoName$$.Version$Client, error)
var newClientForConfigAndClientTemplate = `
// NewForConfigAndClient creates a new $.GroupGoName$$.Version$Client for the given config and http client.
// Note the http client provided takes precedence over the configured transport values.
func NewForConfigAndClient(c *$.restConfig|raw$, h *http.Client) (*$.GroupGoName$$.Version$Client, error) {
func NewForConfigAndClient(c *$.restConfig|raw$, h *$.httpClient|raw$) (*$.GroupGoName$$.Version$Client, error) {
config := *c
if err := setConfigDefaults(&config); err != nil {
return nil, err
@@ -228,11 +232,11 @@ func setConfigDefaults(config *$.restConfig|raw$) error {
if config.UserAgent == "" {
config.UserAgent = $.restDefaultKubernetesUserAgent|raw$()
}
if config.GroupVersion == nil || config.GroupVersion.Group != scheme.Scheme.PrioritizedVersionsForGroup("$.groupName$")[0].Group {
gv := scheme.Scheme.PrioritizedVersionsForGroup("$.groupName$")[0]
if config.GroupVersion == nil || config.GroupVersion.Group != $.SchemePrioritizedVersionsForGroup|raw$("$.groupName$")[0].Group {
gv := $.SchemePrioritizedVersionsForGroup|raw$("$.groupName$")[0]
config.GroupVersion = &gv
}
config.NegotiatedSerializer = scheme.Codecs
config.NegotiatedSerializer = $.restCodecFactoryForGeneratedClient|raw$($.Scheme|raw$, $.Codecs|raw$)
if config.QPS == 0 {
config.QPS = 5
@@ -250,7 +254,7 @@ func setConfigDefaults(config *$.restConfig|raw$) error {
gv := $.SchemeGroupVersion|raw$
config.GroupVersion = &gv
config.APIPath = $.apiPath$
config.NegotiatedSerializer = scheme.Codecs.WithoutConversion()
config.NegotiatedSerializer = $.restCodecFactoryForGeneratedClient|raw$($.Scheme|raw$, $.Codecs|raw$).WithoutConversion()
if config.UserAgent == "" {
config.UserAgent = $.restDefaultKubernetesUserAgent|raw$()

View File

@@ -23,6 +23,7 @@ import (
"golang.org/x/text/cases"
"golang.org/x/text/language"
"k8s.io/gengo/v2/generator"
"k8s.io/gengo/v2/namer"
"k8s.io/gengo/v2/types"
@@ -40,6 +41,7 @@ type genClientForType struct {
group string
version string
groupGoName string
prefersProtobuf bool
typeToMatch *types.Type
imports namer.ImportTracker
}
@@ -139,7 +141,8 @@ func (g *genClientForType) GenerateType(c *generator.Context, t *types.Type, w i
"UpdateOptions": c.Universe.Type(types.Name{Package: "k8s.io/apimachinery/pkg/apis/meta/v1", Name: "UpdateOptions"}),
"ApplyOptions": c.Universe.Type(types.Name{Package: "k8s.io/apimachinery/pkg/apis/meta/v1", Name: "ApplyOptions"}),
"PatchType": c.Universe.Type(types.Name{Package: "k8s.io/apimachinery/pkg/types", Name: "PatchType"}),
"jsonMarshal": c.Universe.Type(types.Name{Package: "encoding/json", Name: "Marshal"}),
"PatchOptions": c.Universe.Type(types.Name{Package: "k8s.io/apimachinery/pkg/apis/meta/v1", Name: "PatchOptions"}),
"context": c.Universe.Type(types.Name{Package: "context", Name: "Context"}),
},
}
if e.HasVerb("apply") {
@@ -158,6 +161,7 @@ func (g *genClientForType) GenerateType(c *generator.Context, t *types.Type, w i
"subresource": false,
"subresourcePath": "",
"GroupGoName": g.groupGoName,
"prefersProtobuf": g.prefersProtobuf,
"Version": namer.IC(g.version),
"CreateOptions": c.Universe.Type(types.Name{Package: "k8s.io/apimachinery/pkg/apis/meta/v1", Name: "CreateOptions"}),
"DeleteOptions": c.Universe.Type(types.Name{Package: "k8s.io/apimachinery/pkg/apis/meta/v1", Name: "DeleteOptions"}),
@@ -167,19 +171,27 @@ func (g *genClientForType) GenerateType(c *generator.Context, t *types.Type, w i
"ApplyOptions": c.Universe.Type(types.Name{Package: "k8s.io/apimachinery/pkg/apis/meta/v1", Name: "ApplyOptions"}),
"UpdateOptions": c.Universe.Type(types.Name{Package: "k8s.io/apimachinery/pkg/apis/meta/v1", Name: "UpdateOptions"}),
"PatchType": c.Universe.Type(types.Name{Package: "k8s.io/apimachinery/pkg/types", Name: "PatchType"}),
"ApplyPatchType": c.Universe.Type(types.Name{Package: "k8s.io/apimachinery/pkg/types", Name: "ApplyPatchType"}),
"watchInterface": c.Universe.Type(types.Name{Package: "k8s.io/apimachinery/pkg/watch", Name: "Interface"}),
"RESTClientInterface": c.Universe.Type(types.Name{Package: "k8s.io/client-go/rest", Name: "Interface"}),
"schemeParameterCodec": c.Universe.Variable(types.Name{Package: path.Join(g.clientsetPackage, "scheme"), Name: "ParameterCodec"}),
"jsonMarshal": c.Universe.Type(types.Name{Package: "encoding/json", Name: "Marshal"}),
"fmtErrorf": c.Universe.Function(types.Name{Package: "fmt", Name: "Errorf"}),
"klogWarningf": c.Universe.Function(types.Name{Package: "k8s.io/klog/v2", Name: "Warningf"}),
"context": c.Universe.Type(types.Name{Package: "context", Name: "Context"}),
"timeDuration": c.Universe.Type(types.Name{Package: "time", Name: "Duration"}),
"timeSecond": c.Universe.Type(types.Name{Package: "time", Name: "Second"}),
"resourceVersionMatchNotOlderThan": c.Universe.Type(types.Name{Package: "k8s.io/apimachinery/pkg/apis/meta/v1", Name: "ResourceVersionMatchNotOlderThan"}),
"CheckListFromCacheDataConsistencyIfRequested": c.Universe.Function(types.Name{Package: "k8s.io/client-go/util/consistencydetector", Name: "CheckListFromCacheDataConsistencyIfRequested"}),
"CheckWatchListFromCacheDataConsistencyIfRequested": c.Universe.Function(types.Name{Package: "k8s.io/client-go/util/consistencydetector", Name: "CheckWatchListFromCacheDataConsistencyIfRequested"}),
"PrepareWatchListOptionsFromListOptions": c.Universe.Function(types.Name{Package: "k8s.io/client-go/util/watchlist", Name: "PrepareWatchListOptionsFromListOptions"}),
"applyNewRequest": c.Universe.Function(types.Name{Package: "k8s.io/client-go/util/apply", Name: "NewRequest"}),
"Client": c.Universe.Type(types.Name{Package: "k8s.io/client-go/gentype", Name: "Client"}),
"ClientWithList": c.Universe.Type(types.Name{Package: "k8s.io/client-go/gentype", Name: "ClientWithList"}),
"ClientWithApply": c.Universe.Type(types.Name{Package: "k8s.io/client-go/gentype", Name: "ClientWithApply"}),
"ClientWithListAndApply": c.Universe.Type(types.Name{Package: "k8s.io/client-go/gentype", Name: "ClientWithListAndApply"}),
"NewClient": c.Universe.Function(types.Name{Package: "k8s.io/client-go/gentype", Name: "NewClient"}),
"NewClientWithApply": c.Universe.Function(types.Name{Package: "k8s.io/client-go/gentype", Name: "NewClientWithApply"}),
"NewClientWithList": c.Universe.Function(types.Name{Package: "k8s.io/client-go/gentype", Name: "NewClientWithList"}),
"NewClientWithListAndApply": c.Universe.Function(types.Name{Package: "k8s.io/client-go/gentype", Name: "NewClientWithListAndApply"}),
}
if generateApply {
@@ -267,64 +279,65 @@ func (g *genClientForType) GenerateType(c *generator.Context, t *types.Type, w i
m["inputType"] = &inputType
m["resultType"] = &resultType
m["subresourcePath"] = e.SubResourcePath
m["verb"] = e.VerbName
if e.HasVerb("apply") {
m["inputApplyConfig"] = types.Ref(path.Join(g.applyConfigurationPackage, inputGVString), inputType.Name.Name+"ApplyConfiguration")
}
if e.HasVerb("get") {
if e.IsSubresource() {
sw.Do(adjustTemplate(e.VerbName, e.VerbType, getSubresourceTemplate), m)
sw.Do(getSubresourceTemplate, m)
} else {
sw.Do(adjustTemplate(e.VerbName, e.VerbType, getTemplate), m)
sw.Do(getTemplate, m)
}
}
if e.HasVerb("list") {
if e.IsSubresource() {
sw.Do(adjustTemplate(e.VerbName, e.VerbType, listSubresourceTemplate), m)
sw.Do(listSubresourceTemplate, m)
} else {
sw.Do(adjustTemplate(e.VerbName, e.VerbType, listTemplate), m)
sw.Do(adjustTemplate(e.VerbName, e.VerbType, privateListTemplate), m)
sw.Do(adjustTemplate(e.VerbName, e.VerbType, watchListTemplate), m)
sw.Do(listTemplate, m)
sw.Do(privateListTemplate, m)
sw.Do(watchListTemplate, m)
}
}
// TODO: Figure out schemantic for watching a sub-resource.
if e.HasVerb("watch") {
sw.Do(adjustTemplate(e.VerbName, e.VerbType, watchTemplate), m)
sw.Do(watchTemplate, m)
}
if e.HasVerb("create") {
if e.IsSubresource() {
sw.Do(adjustTemplate(e.VerbName, e.VerbType, createSubresourceTemplate), m)
sw.Do(createSubresourceTemplate, m)
} else {
sw.Do(adjustTemplate(e.VerbName, e.VerbType, createTemplate), m)
sw.Do(createTemplate, m)
}
}
if e.HasVerb("update") {
if e.IsSubresource() {
sw.Do(adjustTemplate(e.VerbName, e.VerbType, updateSubresourceTemplate), m)
sw.Do(updateSubresourceTemplate, m)
} else {
sw.Do(adjustTemplate(e.VerbName, e.VerbType, updateTemplate), m)
sw.Do(updateTemplate, m)
}
}
// TODO: Figure out schemantic for deleting a sub-resource (what arguments
// are passed, does it need two names? etc.
if e.HasVerb("delete") {
sw.Do(adjustTemplate(e.VerbName, e.VerbType, deleteTemplate), m)
sw.Do(deleteTemplate, m)
}
if e.HasVerb("patch") {
sw.Do(adjustTemplate(e.VerbName, e.VerbType, patchTemplate), m)
sw.Do(patchTemplate, m)
}
if e.HasVerb("apply") {
if e.IsSubresource() {
sw.Do(adjustTemplate(e.VerbName, e.VerbType, applySubresourceTemplate), m)
sw.Do(applySubresourceTemplate, m)
} else {
sw.Do(adjustTemplate(e.VerbName, e.VerbType, applyTemplate), m)
sw.Do(applyTemplate, m)
}
}
}
@@ -332,13 +345,6 @@ func (g *genClientForType) GenerateType(c *generator.Context, t *types.Type, w i
return sw.Error()
}
// adjustTemplate adjust the origin verb template using the expansion name.
// TODO: Make the verbs in templates parametrized so the strings.Replace() is
// not needed.
func adjustTemplate(name, verbType, template string) string {
return strings.ReplaceAll(template, " "+titler.String(verbType), " "+name)
}
func generateInterface(defaultVerbTemplates map[string]string, tags util.Tags) string {
// need an ordered list here to guarantee order of generated methods.
out := []string{}
@@ -352,34 +358,34 @@ func generateInterface(defaultVerbTemplates map[string]string, tags util.Tags) s
func buildSubresourceDefaultVerbTemplates(generateApply bool) map[string]string {
m := map[string]string{
"create": `Create(ctx context.Context, $.type|private$Name string, $.inputType|private$ *$.inputType|raw$, opts $.CreateOptions|raw$) (*$.resultType|raw$, error)`,
"list": `List(ctx context.Context, $.type|private$Name string, opts $.ListOptions|raw$) (*$.resultType|raw$List, error)`,
"update": `Update(ctx context.Context, $.type|private$Name string, $.inputType|private$ *$.inputType|raw$, opts $.UpdateOptions|raw$) (*$.resultType|raw$, error)`,
"get": `Get(ctx context.Context, $.type|private$Name string, options $.GetOptions|raw$) (*$.resultType|raw$, error)`,
"create": `Create(ctx $.context|raw$, $.type|private$Name string, $.inputType|private$ *$.inputType|raw$, opts $.CreateOptions|raw$) (*$.resultType|raw$, error)`,
"list": `List(ctx $.context|raw$, $.type|private$Name string, opts $.ListOptions|raw$) (*$.resultType|raw$List, error)`,
"update": `Update(ctx $.context|raw$, $.type|private$Name string, $.inputType|private$ *$.inputType|raw$, opts $.UpdateOptions|raw$) (*$.resultType|raw$, error)`,
"get": `Get(ctx $.context|raw$, $.type|private$Name string, options $.GetOptions|raw$) (*$.resultType|raw$, error)`,
}
if generateApply {
m["apply"] = `Apply(ctx context.Context, $.type|private$Name string, $.inputType|private$ *$.inputApplyConfig|raw$, opts $.ApplyOptions|raw$) (*$.resultType|raw$, error)`
m["apply"] = `Apply(ctx $.context|raw$, $.type|private$Name string, $.inputType|private$ *$.inputApplyConfig|raw$, opts $.ApplyOptions|raw$) (*$.resultType|raw$, error)`
}
return m
}
func buildDefaultVerbTemplates(generateApply bool) map[string]string {
m := map[string]string{
"create": `Create(ctx context.Context, $.inputType|private$ *$.inputType|raw$, opts $.CreateOptions|raw$) (*$.resultType|raw$, error)`,
"update": `Update(ctx context.Context, $.inputType|private$ *$.inputType|raw$, opts $.UpdateOptions|raw$) (*$.resultType|raw$, error)`,
"create": `Create(ctx $.context|raw$, $.inputType|private$ *$.inputType|raw$, opts $.CreateOptions|raw$) (*$.resultType|raw$, error)`,
"update": `Update(ctx $.context|raw$, $.inputType|private$ *$.inputType|raw$, opts $.UpdateOptions|raw$) (*$.resultType|raw$, error)`,
"updateStatus": `// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus().
UpdateStatus(ctx context.Context, $.inputType|private$ *$.type|raw$, opts $.UpdateOptions|raw$) (*$.type|raw$, error)`,
"delete": `Delete(ctx context.Context, name string, opts $.DeleteOptions|raw$) error`,
"deleteCollection": `DeleteCollection(ctx context.Context, opts $.DeleteOptions|raw$, listOpts $.ListOptions|raw$) error`,
"get": `Get(ctx context.Context, name string, opts $.GetOptions|raw$) (*$.resultType|raw$, error)`,
"list": `List(ctx context.Context, opts $.ListOptions|raw$) (*$.resultType|raw$List, error)`,
"watch": `Watch(ctx context.Context, opts $.ListOptions|raw$) ($.watchInterface|raw$, error)`,
"patch": `Patch(ctx context.Context, name string, pt $.PatchType|raw$, data []byte, opts $.PatchOptions|raw$, subresources ...string) (result *$.resultType|raw$, err error)`,
UpdateStatus(ctx $.context|raw$, $.inputType|private$ *$.type|raw$, opts $.UpdateOptions|raw$) (*$.type|raw$, error)`,
"delete": `Delete(ctx $.context|raw$, name string, opts $.DeleteOptions|raw$) error`,
"deleteCollection": `DeleteCollection(ctx $.context|raw$, opts $.DeleteOptions|raw$, listOpts $.ListOptions|raw$) error`,
"get": `Get(ctx $.context|raw$, name string, opts $.GetOptions|raw$) (*$.resultType|raw$, error)`,
"list": `List(ctx $.context|raw$, opts $.ListOptions|raw$) (*$.resultType|raw$List, error)`,
"watch": `Watch(ctx $.context|raw$, opts $.ListOptions|raw$) ($.watchInterface|raw$, error)`,
"patch": `Patch(ctx $.context|raw$, name string, pt $.PatchType|raw$, data []byte, opts $.PatchOptions|raw$, subresources ...string) (result *$.resultType|raw$, err error)`,
}
if generateApply {
m["apply"] = `Apply(ctx context.Context, $.inputType|private$ *$.inputApplyConfig|raw$, opts $.ApplyOptions|raw$) (result *$.resultType|raw$, err error)`
m["apply"] = `Apply(ctx $.context|raw$, $.inputType|private$ *$.inputApplyConfig|raw$, opts $.ApplyOptions|raw$) (result *$.resultType|raw$, err error)`
m["applyStatus"] = `// Add a +genclient:noStatus comment above the type to avoid generating ApplyStatus().
ApplyStatus(ctx context.Context, $.inputType|private$ *$.inputApplyConfig|raw$, opts $.ApplyOptions|raw$) (result *$.resultType|raw$, err error)`
ApplyStatus(ctx $.context|raw$, $.inputType|private$ *$.inputApplyConfig|raw$, opts $.ApplyOptions|raw$) (result *$.resultType|raw$, err error)`
}
return m
}
@@ -472,12 +478,14 @@ var newStruct = []string{
// new$.type|publicPlural$ returns a $.type|publicPlural$
func new$.type|publicPlural$(c *$.GroupGoName$$.Version$Client, namespace string) *$.type|privatePlural$ {
return &$.type|privatePlural${
gentype.NewClient[*$.resultType|raw$](
$.NewClient|raw$[*$.resultType|raw$](
"$.type|resource$",
c.RESTClient(),
$.schemeParameterCodec|raw$,
namespace,
func() *$.resultType|raw$ { return &$.resultType|raw${} }),
func() *$.resultType|raw$ { return &$.resultType|raw${} },
$if .prefersProtobuf$gentype.PrefersProtobuf[*$.resultType|raw$](),$end$
),
}
}
`,
@@ -485,12 +493,14 @@ var newStruct = []string{
// new$.type|publicPlural$ returns a $.type|publicPlural$
func new$.type|publicPlural$(c *$.GroupGoName$$.Version$Client, namespace string) *$.type|privatePlural$ {
return &$.type|privatePlural${
gentype.NewClientWithApply[*$.resultType|raw$, *$.inputApplyConfig|raw$](
$.NewClientWithApply|raw$[*$.resultType|raw$, *$.inputApplyConfig|raw$](
"$.type|resource$",
c.RESTClient(),
$.schemeParameterCodec|raw$,
namespace,
func() *$.resultType|raw$ { return &$.resultType|raw${} }),
func() *$.resultType|raw$ { return &$.resultType|raw${} },
$if .prefersProtobuf$gentype.PrefersProtobuf[*$.resultType|raw$](),$end$
),
}
}
`,
@@ -498,13 +508,15 @@ var newStruct = []string{
// new$.type|publicPlural$ returns a $.type|publicPlural$
func new$.type|publicPlural$(c *$.GroupGoName$$.Version$Client, namespace string) *$.type|privatePlural$ {
return &$.type|privatePlural${
gentype.NewClientWithList[*$.resultType|raw$, *$.resultType|raw$List](
$.NewClientWithList|raw$[*$.resultType|raw$, *$.resultType|raw$List](
"$.type|resource$",
c.RESTClient(),
$.schemeParameterCodec|raw$,
namespace,
func() *$.resultType|raw$ { return &$.resultType|raw${} },
func() *$.resultType|raw$List { return &$.resultType|raw$List{} }),
func() *$.resultType|raw$List { return &$.resultType|raw$List{} },
$if .prefersProtobuf$gentype.PrefersProtobuf[*$.resultType|raw$](),$end$
),
}
}
`,
@@ -512,13 +524,15 @@ var newStruct = []string{
// new$.type|publicPlural$ returns a $.type|publicPlural$
func new$.type|publicPlural$(c *$.GroupGoName$$.Version$Client, namespace string) *$.type|privatePlural$ {
return &$.type|privatePlural${
gentype.NewClientWithListAndApply[*$.resultType|raw$, *$.resultType|raw$List, *$.inputApplyConfig|raw$](
$.NewClientWithListAndApply|raw$[*$.resultType|raw$, *$.resultType|raw$List, *$.inputApplyConfig|raw$](
"$.type|resource$",
c.RESTClient(),
$.schemeParameterCodec|raw$,
namespace,
func() *$.resultType|raw$ { return &$.resultType|raw${} },
func() *$.resultType|raw$List { return &$.resultType|raw$List{} }),
func() *$.resultType|raw$List { return &$.resultType|raw$List{} },
$if .prefersProtobuf$gentype.PrefersProtobuf[*$.resultType|raw$](),$end$
),
}
}
`,
@@ -526,12 +540,14 @@ var newStruct = []string{
// new$.type|publicPlural$ returns a $.type|publicPlural$
func new$.type|publicPlural$(c *$.GroupGoName$$.Version$Client) *$.type|privatePlural$ {
return &$.type|privatePlural${
gentype.NewClient[*$.resultType|raw$](
$.NewClient|raw$[*$.resultType|raw$](
"$.type|resource$",
c.RESTClient(),
$.schemeParameterCodec|raw$,
"",
func() *$.resultType|raw$ { return &$.resultType|raw${} }),
func() *$.resultType|raw$ { return &$.resultType|raw${} },
$if .prefersProtobuf$gentype.PrefersProtobuf[*$.resultType|raw$](),$end$
),
}
}
`,
@@ -539,12 +555,14 @@ var newStruct = []string{
// new$.type|publicPlural$ returns a $.type|publicPlural$
func new$.type|publicPlural$(c *$.GroupGoName$$.Version$Client) *$.type|privatePlural$ {
return &$.type|privatePlural${
gentype.NewClientWithApply[*$.resultType|raw$, *$.inputApplyConfig|raw$](
$.NewClientWithApply|raw$[*$.resultType|raw$, *$.inputApplyConfig|raw$](
"$.type|resource$",
c.RESTClient(),
$.schemeParameterCodec|raw$,
"",
func() *$.resultType|raw$ { return &$.resultType|raw${} }),
func() *$.resultType|raw$ { return &$.resultType|raw${} },
$if .prefersProtobuf$gentype.PrefersProtobuf[*$.resultType|raw$](),$end$
),
}
}
`,
@@ -552,13 +570,15 @@ var newStruct = []string{
// new$.type|publicPlural$ returns a $.type|publicPlural$
func new$.type|publicPlural$(c *$.GroupGoName$$.Version$Client) *$.type|privatePlural$ {
return &$.type|privatePlural${
gentype.NewClientWithList[*$.resultType|raw$, *$.resultType|raw$List](
$.NewClientWithList|raw$[*$.resultType|raw$, *$.resultType|raw$List](
"$.type|resource$",
c.RESTClient(),
$.schemeParameterCodec|raw$,
"",
func() *$.resultType|raw$ { return &$.resultType|raw${} },
func() *$.resultType|raw$List { return &$.resultType|raw$List{} }),
func() *$.resultType|raw$List { return &$.resultType|raw$List{} },
$if .prefersProtobuf$gentype.PrefersProtobuf[*$.resultType|raw$](),$end$
),
}
}
`,
@@ -566,30 +586,32 @@ var newStruct = []string{
// new$.type|publicPlural$ returns a $.type|publicPlural$
func new$.type|publicPlural$(c *$.GroupGoName$$.Version$Client) *$.type|privatePlural$ {
return &$.type|privatePlural${
gentype.NewClientWithListAndApply[*$.resultType|raw$, *$.resultType|raw$List, *$.inputApplyConfig|raw$](
$.NewClientWithListAndApply|raw$[*$.resultType|raw$, *$.resultType|raw$List, *$.inputApplyConfig|raw$](
"$.type|resource$",
c.RESTClient(),
$.schemeParameterCodec|raw$,
"",
func() *$.resultType|raw$ { return &$.resultType|raw${} },
func() *$.resultType|raw$List { return &$.resultType|raw$List{} }),
func() *$.resultType|raw$List { return &$.resultType|raw$List{} },
$if .prefersProtobuf$gentype.PrefersProtobuf[*$.resultType|raw$](),$end$
),
}
}
`,
}
var listTemplate = `
// List takes label and field selectors, and returns the list of $.resultType|publicPlural$ that match those selectors.
func (c *$.type|privatePlural$) List(ctx context.Context, opts $.ListOptions|raw$) (*$.resultType|raw$List, error) {
// $.verb$ takes label and field selectors, and returns the list of $.resultType|publicPlural$ that match those selectors.
func (c *$.type|privatePlural$) $.verb$(ctx $.context|raw$, opts $.ListOptions|raw$) (*$.resultType|raw$List, error) {
if watchListOptions, hasWatchListOptionsPrepared, watchListOptionsErr := $.PrepareWatchListOptionsFromListOptions|raw$(opts); watchListOptionsErr != nil {
klog.Warningf("Failed preparing watchlist options for $.type|resource$, falling back to the standard LIST semantics, err = %v", watchListOptionsErr )
$.klogWarningf|raw$("Failed preparing watchlist options for $.type|resource$, falling back to the standard LIST semantics, err = %v", watchListOptionsErr )
} else if hasWatchListOptionsPrepared {
result, err := c.watchList(ctx, watchListOptions)
if err == nil {
$.CheckWatchListFromCacheDataConsistencyIfRequested|raw$(ctx, "watchlist request for $.type|resource$", c.list, opts, result)
return result, nil
}
klog.Warningf("The watchlist request for $.type|resource$ ended with an error, falling back to the standard LIST semantics, err = %v", err)
$.klogWarningf|raw$("The watchlist request for $.type|resource$ ended with an error, falling back to the standard LIST semantics, err = %v", err)
}
result, err := c.list(ctx, opts)
if err == nil {
@@ -601,13 +623,14 @@ func (c *$.type|privatePlural$) List(ctx context.Context, opts $.ListOptions|raw
var privateListTemplate = `
// list takes label and field selectors, and returns the list of $.resultType|publicPlural$ that match those selectors.
func (c *$.type|privatePlural$) list(ctx context.Context, opts $.ListOptions|raw$) (result *$.resultType|raw$List, err error) {
var timeout time.Duration
func (c *$.type|privatePlural$) list(ctx $.context|raw$, opts $.ListOptions|raw$) (result *$.resultType|raw$List, err error) {
var timeout $.timeDuration|raw$
if opts.TimeoutSeconds != nil{
timeout = time.Duration(*opts.TimeoutSeconds) * time.Second
timeout = $.timeDuration|raw$(*opts.TimeoutSeconds) * $.timeSecond|raw$
}
result = &$.resultType|raw$List{}
err = c.GetClient().Get().
$if .prefersProtobuf$UseProtobufAsDefault().$end$
$if .namespaced$Namespace(c.GetNamespace()).$end$
Resource("$.type|resource$").
VersionedParams(&opts, $.schemeParameterCodec|raw$).
@@ -619,14 +642,15 @@ func (c *$.type|privatePlural$) list(ctx context.Context, opts $.ListOptions|raw
`
var listSubresourceTemplate = `
// List takes $.type|raw$ name, label and field selectors, and returns the list of $.resultType|publicPlural$ that match those selectors.
func (c *$.type|privatePlural$) List(ctx context.Context, $.type|private$Name string, opts $.ListOptions|raw$) (result *$.resultType|raw$List, err error) {
var timeout time.Duration
// $.verb$ takes $.type|raw$ name, label and field selectors, and returns the list of $.resultType|publicPlural$ that match those selectors.
func (c *$.type|privatePlural$) $.verb$(ctx $.context|raw$, $.type|private$Name string, opts $.ListOptions|raw$) (result *$.resultType|raw$List, err error) {
var timeout $.timeDuration|raw$
if opts.TimeoutSeconds != nil{
timeout = time.Duration(*opts.TimeoutSeconds) * time.Second
timeout = $.timeDuration|raw$(*opts.TimeoutSeconds) * $.timeSecond|raw$
}
result = &$.resultType|raw$List{}
err = c.GetClient().Get().
$if .prefersProtobuf$UseProtobufAsDefault().$end$
$if .namespaced$Namespace(c.GetNamespace()).$end$
Resource("$.type|resource$").
Name($.type|private$Name).
@@ -640,10 +664,11 @@ func (c *$.type|privatePlural$) List(ctx context.Context, $.type|private$Name st
`
var getTemplate = `
// Get takes name of the $.type|private$, and returns the corresponding $.resultType|private$ object, and an error if there is any.
func (c *$.type|privatePlural$) Get(ctx context.Context, name string, options $.GetOptions|raw$) (result *$.resultType|raw$, err error) {
// $.verb$ takes name of the $.type|private$, and returns the corresponding $.resultType|private$ object, and an error if there is any.
func (c *$.type|privatePlural$) $.verb$(ctx $.context|raw$, name string, options $.GetOptions|raw$) (result *$.resultType|raw$, err error) {
result = &$.resultType|raw${}
err = c.GetClient().Get().
$if .prefersProtobuf$UseProtobufAsDefault().$end$
$if .namespaced$Namespace(c.GetNamespace()).$end$
Resource("$.type|resource$").
Name(name).
@@ -655,10 +680,11 @@ func (c *$.type|privatePlural$) Get(ctx context.Context, name string, options $.
`
var getSubresourceTemplate = `
// Get takes name of the $.type|private$, and returns the corresponding $.resultType|raw$ object, and an error if there is any.
func (c *$.type|privatePlural$) Get(ctx context.Context, $.type|private$Name string, options $.GetOptions|raw$) (result *$.resultType|raw$, err error) {
// $.verb$ takes name of the $.type|private$, and returns the corresponding $.resultType|raw$ object, and an error if there is any.
func (c *$.type|privatePlural$) $.verb$(ctx $.context|raw$, $.type|private$Name string, options $.GetOptions|raw$) (result *$.resultType|raw$, err error) {
result = &$.resultType|raw${}
err = c.GetClient().Get().
$if .prefersProtobuf$UseProtobufAsDefault().$end$
$if .namespaced$Namespace(c.GetNamespace()).$end$
Resource("$.type|resource$").
Name($.type|private$Name).
@@ -671,9 +697,10 @@ func (c *$.type|privatePlural$) Get(ctx context.Context, $.type|private$Name str
`
var deleteTemplate = `
// Delete takes name of the $.type|private$ and deletes it. Returns an error if one occurs.
func (c *$.type|privatePlural$) Delete(ctx context.Context, name string, opts $.DeleteOptions|raw$) error {
// $.verb$ takes name of the $.type|private$ and deletes it. Returns an error if one occurs.
func (c *$.type|privatePlural$) $.verb$(ctx $.context|raw$, name string, opts $.DeleteOptions|raw$) error {
return c.GetClient().Delete().
$if .prefersProtobuf$UseProtobufAsDefault().$end$
$if .namespaced$Namespace(c.GetNamespace()).$end$
Resource("$.type|resource$").
Name(name).
@@ -684,10 +711,11 @@ func (c *$.type|privatePlural$) Delete(ctx context.Context, name string, opts $.
`
var createSubresourceTemplate = `
// Create takes the representation of a $.inputType|private$ and creates it. Returns the server's representation of the $.resultType|private$, and an error, if there is any.
func (c *$.type|privatePlural$) Create(ctx context.Context, $.type|private$Name string, $.inputType|private$ *$.inputType|raw$, opts $.CreateOptions|raw$) (result *$.resultType|raw$, err error) {
// $.verb$ takes the representation of a $.inputType|private$ and creates it. Returns the server's representation of the $.resultType|private$, and an error, if there is any.
func (c *$.type|privatePlural$) $.verb$(ctx $.context|raw$, $.type|private$Name string, $.inputType|private$ *$.inputType|raw$, opts $.CreateOptions|raw$) (result *$.resultType|raw$, err error) {
result = &$.resultType|raw${}
err = c.GetClient().Post().
$if .prefersProtobuf$UseProtobufAsDefault().$end$
$if .namespaced$Namespace(c.GetNamespace()).$end$
Resource("$.type|resource$").
Name($.type|private$Name).
@@ -701,10 +729,11 @@ func (c *$.type|privatePlural$) Create(ctx context.Context, $.type|private$Name
`
var createTemplate = `
// Create takes the representation of a $.inputType|private$ and creates it. Returns the server's representation of the $.resultType|private$, and an error, if there is any.
func (c *$.type|privatePlural$) Create(ctx context.Context, $.inputType|private$ *$.inputType|raw$, opts $.CreateOptions|raw$) (result *$.resultType|raw$, err error) {
// $.verb$ takes the representation of a $.inputType|private$ and creates it. Returns the server's representation of the $.resultType|private$, and an error, if there is any.
func (c *$.type|privatePlural$) $.verb$(ctx $.context|raw$, $.inputType|private$ *$.inputType|raw$, opts $.CreateOptions|raw$) (result *$.resultType|raw$, err error) {
result = &$.resultType|raw${}
err = c.GetClient().Post().
$if .prefersProtobuf$UseProtobufAsDefault().$end$
$if .namespaced$Namespace(c.GetNamespace()).$end$
Resource("$.type|resource$").
VersionedParams(&opts, $.schemeParameterCodec|raw$).
@@ -716,10 +745,11 @@ func (c *$.type|privatePlural$) Create(ctx context.Context, $.inputType|private$
`
var updateSubresourceTemplate = `
// Update takes the top resource name and the representation of a $.inputType|private$ and updates it. Returns the server's representation of the $.resultType|private$, and an error, if there is any.
func (c *$.type|privatePlural$) Update(ctx context.Context, $.type|private$Name string, $.inputType|private$ *$.inputType|raw$, opts $.UpdateOptions|raw$) (result *$.resultType|raw$, err error) {
// $.verb$ takes the top resource name and the representation of a $.inputType|private$ and updates it. Returns the server's representation of the $.resultType|private$, and an error, if there is any.
func (c *$.type|privatePlural$) $.verb$(ctx $.context|raw$, $.type|private$Name string, $.inputType|private$ *$.inputType|raw$, opts $.UpdateOptions|raw$) (result *$.resultType|raw$, err error) {
result = &$.resultType|raw${}
err = c.GetClient().Put().
$if .prefersProtobuf$UseProtobufAsDefault().$end$
$if .namespaced$Namespace(c.GetNamespace()).$end$
Resource("$.type|resource$").
Name($.type|private$Name).
@@ -733,10 +763,11 @@ func (c *$.type|privatePlural$) Update(ctx context.Context, $.type|private$Name
`
var updateTemplate = `
// Update takes the representation of a $.inputType|private$ and updates it. Returns the server's representation of the $.resultType|private$, and an error, if there is any.
func (c *$.type|privatePlural$) Update(ctx context.Context, $.inputType|private$ *$.inputType|raw$, opts $.UpdateOptions|raw$) (result *$.resultType|raw$, err error) {
// $.verb$ takes the representation of a $.inputType|private$ and updates it. Returns the server's representation of the $.resultType|private$, and an error, if there is any.
func (c *$.type|privatePlural$) $.verb$(ctx $.context|raw$, $.inputType|private$ *$.inputType|raw$, opts $.UpdateOptions|raw$) (result *$.resultType|raw$, err error) {
result = &$.resultType|raw${}
err = c.GetClient().Put().
$if .prefersProtobuf$UseProtobufAsDefault().$end$
$if .namespaced$Namespace(c.GetNamespace()).$end$
Resource("$.type|resource$").
Name($.inputType|private$.Name).
@@ -749,14 +780,15 @@ func (c *$.type|privatePlural$) Update(ctx context.Context, $.inputType|private$
`
var watchTemplate = `
// Watch returns a $.watchInterface|raw$ that watches the requested $.type|privatePlural$.
func (c *$.type|privatePlural$) Watch(ctx context.Context, opts $.ListOptions|raw$) ($.watchInterface|raw$, error) {
var timeout time.Duration
// $.verb$ returns a $.watchInterface|raw$ that watches the requested $.type|privatePlural$.
func (c *$.type|privatePlural$) $.verb$(ctx $.context|raw$, opts $.ListOptions|raw$) ($.watchInterface|raw$, error) {
var timeout $.timeDuration|raw$
if opts.TimeoutSeconds != nil{
timeout = time.Duration(*opts.TimeoutSeconds) * time.Second
timeout = $.timeDuration|raw$(*opts.TimeoutSeconds) * $.timeSecond|raw$
}
opts.Watch = true
return c.GetClient().Get().
$if .prefersProtobuf$UseProtobufAsDefault().$end$
$if .namespaced$Namespace(c.GetNamespace()).$end$
VersionedParams(&opts, $.schemeParameterCodec|raw$).
Timeout(timeout).
@@ -766,14 +798,15 @@ func (c *$.type|privatePlural$) Watch(ctx context.Context, opts $.ListOptions|ra
var watchListTemplate = `
// watchList establishes a watch stream with the server and returns the list of $.resultType|publicPlural$
func (c *$.type|privatePlural$) watchList(ctx context.Context, opts $.ListOptions|raw$) (result *$.resultType|raw$List, err error) {
var timeout time.Duration
func (c *$.type|privatePlural$) watchList(ctx $.context|raw$, opts $.ListOptions|raw$) (result *$.resultType|raw$List, err error) {
var timeout $.timeDuration|raw$
if opts.TimeoutSeconds != nil{
timeout = time.Duration(*opts.TimeoutSeconds) * time.Second
timeout = $.timeDuration|raw$(*opts.TimeoutSeconds) * $.timeSecond|raw$
}
result = &$.resultType|raw$List{}
err = c.client.Get().
$if .namespaced$Namespace(c.ns).$end$
err = c.GetClient().Get().
$if .prefersProtobuf$UseProtobufAsDefault().$end$
$if .namespaced$Namespace(c.GetNamespace()).$end$
Resource("$.type|resource$").
VersionedParams(&opts, $.schemeParameterCodec|raw$).
Timeout(timeout).
@@ -784,10 +817,11 @@ func (c *$.type|privatePlural$) watchList(ctx context.Context, opts $.ListOption
`
var patchTemplate = `
// Patch applies the patch and returns the patched $.resultType|private$.
func (c *$.type|privatePlural$) Patch(ctx context.Context, name string, pt $.PatchType|raw$, data []byte, opts $.PatchOptions|raw$, subresources ...string) (result *$.resultType|raw$, err error) {
// $.verb$ applies the patch and returns the patched $.resultType|private$.
func (c *$.type|privatePlural$) $.verb$(ctx $.context|raw$, name string, pt $.PatchType|raw$, data []byte, opts $.PatchOptions|raw$, subresources ...string) (result *$.resultType|raw$, err error) {
result = &$.resultType|raw${}
err = c.GetClient().Patch(pt).
$if .prefersProtobuf$UseProtobufAsDefault().$end$
$if .namespaced$Namespace(c.GetNamespace()).$end$
Resource("$.type|resource$").
Name(name).
@@ -801,27 +835,27 @@ func (c *$.type|privatePlural$) Patch(ctx context.Context, name string, pt $.Pat
`
var applyTemplate = `
// Apply takes the given apply declarative configuration, applies it and returns the applied $.resultType|private$.
func (c *$.type|privatePlural$) Apply(ctx context.Context, $.inputType|private$ *$.inputApplyConfig|raw$, opts $.ApplyOptions|raw$) (result *$.resultType|raw$, err error) {
// $.verb$ takes the given apply declarative configuration, applies it and returns the applied $.resultType|private$.
func (c *$.type|privatePlural$) $.verb$(ctx $.context|raw$, $.inputType|private$ *$.inputApplyConfig|raw$, opts $.ApplyOptions|raw$) (result *$.resultType|raw$, err error) {
if $.inputType|private$ == nil {
return nil, fmt.Errorf("$.inputType|private$ provided to Apply must not be nil")
return nil, $.fmtErrorf|raw$("$.inputType|private$ provided to $.verb$ must not be nil")
}
patchOpts := opts.ToPatchOptions()
data, err := $.jsonMarshal|raw$($.inputType|private$)
name := $.inputType|private$.Name
if name == nil {
return nil, $.fmtErrorf|raw$("$.inputType|private$.Name must be provided to $.verb$")
}
request, err := $.applyNewRequest|raw$(c.GetClient(), $.inputType|private$)
if err != nil {
return nil, err
}
name := $.inputType|private$.Name
if name == nil {
return nil, fmt.Errorf("$.inputType|private$.Name must be provided to Apply")
}
result = &$.resultType|raw${}
err = c.GetClient().Patch($.ApplyPatchType|raw$).
err = request.
$if .prefersProtobuf$UseProtobufAsDefault().$end$
$if .namespaced$Namespace(c.GetNamespace()).$end$
Resource("$.type|resource$").
Name(*name).
VersionedParams(&patchOpts, $.schemeParameterCodec|raw$).
Body(data).
Do(ctx).
Into(result)
return
@@ -829,26 +863,26 @@ func (c *$.type|privatePlural$) Apply(ctx context.Context, $.inputType|private$
`
var applySubresourceTemplate = `
// Apply takes top resource name and the apply declarative configuration for $.subresourcePath$,
// $.verb$ takes top resource name and the apply declarative configuration for $.subresourcePath$,
// applies it and returns the applied $.resultType|private$, and an error, if there is any.
func (c *$.type|privatePlural$) Apply(ctx context.Context, $.type|private$Name string, $.inputType|private$ *$.inputApplyConfig|raw$, opts $.ApplyOptions|raw$) (result *$.resultType|raw$, err error) {
func (c *$.type|privatePlural$) $.verb$(ctx $.context|raw$, $.type|private$Name string, $.inputType|private$ *$.inputApplyConfig|raw$, opts $.ApplyOptions|raw$) (result *$.resultType|raw$, err error) {
if $.inputType|private$ == nil {
return nil, fmt.Errorf("$.inputType|private$ provided to Apply must not be nil")
return nil, $.fmtErrorf|raw$("$.inputType|private$ provided to $.verb$ must not be nil")
}
patchOpts := opts.ToPatchOptions()
data, err := $.jsonMarshal|raw$($.inputType|private$)
request, err := $.applyNewRequest|raw$(c.GetClient(), $.inputType|private$)
if err != nil {
return nil, err
}
result = &$.resultType|raw${}
err = c.GetClient().Patch($.ApplyPatchType|raw$).
err = request.
$if .prefersProtobuf$UseProtobufAsDefault().$end$
$if .namespaced$Namespace(c.GetNamespace()).$end$
Resource("$.type|resource$").
Name($.type|private$Name).
SubResource("$.subresourcePath$").
VersionedParams(&patchOpts, $.schemeParameterCodec|raw$).
Body(data).
Do(ctx).
Into(result)
return

View File

@@ -20,6 +20,8 @@ import (
"fmt"
"github.com/spf13/pflag"
"k8s.io/gengo/v2"
)
// DefaultBasePeerDirs are the peer-dirs nearly everybody will use, i.e. those coming from
@@ -43,11 +45,6 @@ type Args struct {
// generator pick up manually written conversion funcs from external packages.
ExtraPeerDirs []string
// Additional dirs to parse and load, but not consider for peers. This is
// useful when packages depend on other packages and want to call
// conversions across them.
ExtraDirs []string
// SkipUnsafe indicates whether to generate unsafe conversions to improve the efficiency
// of these operations. The unsafe operation is a direct pointer assignment via unsafe
// (within the allowed uses of unsafe) and is equivalent to a proposed Golang change to
@@ -57,13 +54,20 @@ type Args struct {
// GoHeaderFile is the path to a boilerplate header file for generated
// code.
GoHeaderFile string
// GeneratedBuildTag is the tag used to identify code generated by execution
// of this type. Each generator should use a different tag, and different
// groups of generators (external API that depends on Kube generations) should
// keep tags distinct as well.
GeneratedBuildTag string
}
// New returns default arguments for the generator.
func New() *Args {
return &Args{
BasePeerDirs: DefaultBasePeerDirs,
SkipUnsafe: false,
BasePeerDirs: DefaultBasePeerDirs,
SkipUnsafe: false,
GeneratedBuildTag: gengo.StdBuildTag,
}
}
@@ -75,12 +79,11 @@ func (args *Args) AddFlags(fs *pflag.FlagSet) {
"Comma-separated list of apimachinery import paths which are considered, after tag-specified peers, for conversions. Only change these if you have very good reasons.")
fs.StringSliceVar(&args.ExtraPeerDirs, "extra-peer-dirs", args.ExtraPeerDirs,
"Application specific comma-separated list of import paths which are considered, after tag-specified peers and base-peer-dirs, for conversions.")
fs.StringSliceVar(&args.ExtraDirs, "extra-dirs", args.ExtraDirs,
"Application specific comma-separated list of import paths which are loaded and considered for callable conversions, but are not considered peers for conversion.")
fs.BoolVar(&args.SkipUnsafe, "skip-unsafe", args.SkipUnsafe,
"If true, will not generate code using unsafe pointer conversions; resulting code may be slower.")
fs.StringVar(&args.GoHeaderFile, "go-header-file", "",
"the path to a file containing boilerplate header text; the string \"YEAR\" will be replaced with the current 4-digit year")
fs.StringVar(&args.GeneratedBuildTag, "build-tag", args.GeneratedBuildTag, "A Go build tag to use to identify files generated by this command. Should be unique.")
}
// Validate checks the given arguments.

View File

@@ -158,16 +158,16 @@ func getManualConversionFunctions(context *generator.Context, pkg *types.Package
klog.V(6).Infof("%s has a receiver", f.Name)
continue
}
if len(signature.Parameters) != 3 || signature.Parameters[2].Name != scopeName {
if len(signature.Parameters) != 3 || signature.Parameters[2].Type.Name != scopeName {
klog.V(6).Infof("%s has wrong parameters", f.Name)
continue
}
if len(signature.Results) != 1 || signature.Results[0].Name != errorName {
if len(signature.Results) != 1 || signature.Results[0].Type.Name != errorName {
klog.V(6).Infof("%s has wrong results", f.Name)
continue
}
inType := signature.Parameters[0]
outType := signature.Parameters[1]
inType := signature.Parameters[0].Type
outType := signature.Parameters[1].Type
if inType.Kind != types.Pointer || outType.Kind != types.Pointer {
klog.V(6).Infof("%s has wrong parameter types", f.Name)
continue
@@ -196,7 +196,7 @@ func getManualConversionFunctions(context *generator.Context, pkg *types.Package
}
func GetTargets(context *generator.Context, args *args.Args) []generator.Target {
boilerplate, err := gengo.GoBoilerplate(args.GoHeaderFile, gengo.StdBuildTag, gengo.StdGeneratedBy)
boilerplate, err := gengo.GoBoilerplate(args.GoHeaderFile, args.GeneratedBuildTag, gengo.StdGeneratedBy)
if err != nil {
klog.Fatalf("Failed loading boilerplate: %v", err)
}
@@ -478,7 +478,7 @@ func NewGenConversion(outputFilename, typesPackage, outputPackage string, manual
outputPackage: outputPackage,
peerPackages: peerPkgs,
manualConversions: manualConversions,
imports: generator.NewImportTracker(),
imports: generator.NewImportTrackerForPackage(outputPackage),
types: []*types.Type{},
explicitConversions: []conversionPair{},
skippedFields: map[*types.Type][]string{},

View File

@@ -128,7 +128,7 @@ func main() {
generators.NameSystems(),
generators.DefaultNameSystem(),
myTargets,
gengo.StdBuildTag,
args.GeneratedBuildTag,
pflag.Args(),
); err != nil {
klog.Fatalf("Error: %v", err)

View File

@@ -222,7 +222,7 @@ func NewGenDeepCopy(outputFilename, targetPackage string, boundingDirs []string,
boundingDirs: boundingDirs,
allTypes: allTypes,
registerTypes: registerTypes,
imports: generator.NewImportTracker(),
imports: generator.NewImportTrackerForPackage(targetPackage),
typesForInit: make([]*types.Type, 0),
}
}
@@ -277,8 +277,8 @@ func deepCopyMethod(t *types.Type) (*types.Signature, error) {
return nil, fmt.Errorf("type %v: invalid DeepCopy signature, expected exactly one result", t)
}
ptrResult := f.Signature.Results[0].Kind == types.Pointer && f.Signature.Results[0].Elem.Name == t.Name
nonPtrResult := f.Signature.Results[0].Name == t.Name
ptrResult := f.Signature.Results[0].Type.Kind == types.Pointer && f.Signature.Results[0].Type.Elem.Name == t.Name
nonPtrResult := f.Signature.Results[0].Type.Name == t.Name
if !ptrResult && !nonPtrResult {
return nil, fmt.Errorf("type %v: invalid DeepCopy signature, expected to return %s or *%s", t, t.Name.Name, t.Name.Name)
@@ -329,7 +329,7 @@ func deepCopyIntoMethod(t *types.Type) (*types.Signature, error) {
return nil, fmt.Errorf("type %v: invalid DeepCopy signature, expected no result type", t)
}
ptrParam := f.Signature.Parameters[0].Kind == types.Pointer && f.Signature.Parameters[0].Elem.Name == t.Name
ptrParam := f.Signature.Parameters[0].Type.Kind == types.Pointer && f.Signature.Parameters[0].Type.Elem.Name == t.Name
if !ptrParam {
return nil, fmt.Errorf("type %v: invalid DeepCopy signature, expected parameter of type *%s", t, t.Name.Name)
@@ -696,7 +696,7 @@ func (g *genDeepCopy) doMap(t *types.Type, sw *generator.SnippetWriter) {
leftPointer := ut.Elem.Kind == types.Pointer
rightPointer := !isReference(ut.Elem)
if dc != nil {
rightPointer = dc.Results[0].Kind == types.Pointer
rightPointer = dc.Results[0].Type.Kind == types.Pointer
}
if leftPointer == rightPointer {
sw.Do("(*out)[key] = val.DeepCopy()\n", nil)
@@ -812,7 +812,7 @@ func (g *genDeepCopy) doStruct(t *types.Type, sw *generator.SnippetWriter) {
leftPointer := ft.Kind == types.Pointer
rightPointer := !isReference(ft)
if dc != nil {
rightPointer = dc.Results[0].Kind == types.Pointer
rightPointer = dc.Results[0].Type.Kind == types.Pointer
}
if leftPointer == rightPointer {
sw.Do("out.$.name$ = in.$.name$.DeepCopy()\n", args)
@@ -866,7 +866,7 @@ func (g *genDeepCopy) doPointer(t *types.Type, sw *generator.SnippetWriter) {
case dc != nil || dci != nil:
rightPointer := !isReference(ut.Elem)
if dc != nil {
rightPointer = dc.Results[0].Kind == types.Pointer
rightPointer = dc.Results[0].Type.Kind == types.Pointer
}
if rightPointer {
sw.Do("*out = (*in).DeepCopy()\n", nil)

View File

@@ -20,17 +20,27 @@ import (
"fmt"
"github.com/spf13/pflag"
"k8s.io/gengo/v2"
)
type Args struct {
OutputFile string
ExtraPeerDirs []string // Always consider these as last-ditch possibilities for conversions.
GoHeaderFile string
// GeneratedBuildTag is the tag used to identify code generated by execution
// of this type. Each generator should use a different tag, and different
// groups of generators (external API that depends on Kube generations) should
// keep tags distinct as well.
GeneratedBuildTag string
}
// New returns default arguments for the generator.
func New() *Args {
return &Args{}
return &Args{
GeneratedBuildTag: gengo.StdBuildTag,
}
}
// AddFlags add the generator flags to the flag set.
@@ -41,6 +51,7 @@ func (args *Args) AddFlags(fs *pflag.FlagSet) {
"Comma-separated list of import paths which are considered, after tag-specified peers, for conversions.")
fs.StringVar(&args.GoHeaderFile, "go-header-file", "",
"the path to a file containing boilerplate header text; the string \"YEAR\" will be replaced with the current 4-digit year")
fs.StringVar(&args.GeneratedBuildTag, "build-tag", args.GeneratedBuildTag, "A Go build tag to use to identify files generated by this command. Should be unique.")
}
// Validate checks the given arguments.

View File

@@ -165,7 +165,7 @@ func getManualDefaultingFunctions(context *generator.Context, pkg *types.Package
if len(signature.Results) != 0 {
continue
}
inType := signature.Parameters[0]
inType := signature.Parameters[0].Type
if inType.Kind != types.Pointer {
continue
}
@@ -222,7 +222,7 @@ func getManualDefaultingFunctions(context *generator.Context, pkg *types.Package
}
func GetTargets(context *generator.Context, args *args.Args) []generator.Target {
boilerplate, err := gengo.GoBoilerplate(args.GoHeaderFile, gengo.StdBuildTag, gengo.StdGeneratedBy)
boilerplate, err := gengo.GoBoilerplate(args.GoHeaderFile, args.GeneratedBuildTag, gengo.StdGeneratedBy)
if err != nil {
klog.Fatalf("Failed loading boilerplate: %v", err)
}
@@ -823,7 +823,7 @@ func (g *genDefaulter) GenerateType(c *generator.Context, t *types.Type, w io.Wr
})
sw := generator.NewSnippetWriter(w, c, "$", "$")
g.generateDefaulter(t, callTree, sw)
g.generateDefaulter(c, t, callTree, sw)
return sw.Error()
}
@@ -833,9 +833,9 @@ func defaultingArgsFromType(inType *types.Type) generator.Args {
}
}
func (g *genDefaulter) generateDefaulter(inType *types.Type, callTree *callNode, sw *generator.SnippetWriter) {
func (g *genDefaulter) generateDefaulter(c *generator.Context, inType *types.Type, callTree *callNode, sw *generator.SnippetWriter) {
sw.Do("func $.inType|objectdefaultfn$(in *$.inType|raw$) {\n", defaultingArgsFromType(inType))
callTree.WriteMethod("in", 0, nil, sw)
callTree.WriteMethod(c, "in", 0, nil, sw)
sw.Do("}\n\n", nil)
}
@@ -996,15 +996,19 @@ func getTypeZeroValue(t string) (interface{}, error) {
return defaultZero, nil
}
func (n *callNode) writeDefaulter(varName string, index string, isVarPointer bool, sw *generator.SnippetWriter) {
func (n *callNode) writeDefaulter(c *generator.Context, varName string, index string, isVarPointer bool, sw *generator.SnippetWriter) {
if n.defaultValue.IsEmpty() {
return
}
jsonUnmarshalType := c.Universe.Type(types.Name{Package: "encoding/json", Name: "Unmarshal"})
args := generator.Args{
"defaultValue": n.defaultValue.Resolved(),
"varName": varName,
"index": index,
"varTopType": n.defaultTopLevelType,
"defaultValue": n.defaultValue.Resolved(),
"varName": varName,
"index": index,
"varTopType": n.defaultTopLevelType,
"jsonUnmarshal": jsonUnmarshalType,
}
variablePlaceholder := ""
@@ -1101,13 +1105,13 @@ func (n *callNode) writeDefaulter(varName string, index string, isVarPointer boo
// This applies to maps with non-primitive values (eg: map[string]SubStruct)
if n.key {
sw.Do("$.mapDefaultVar$ := $.varName$[$.index$]\n", args)
sw.Do("if err := json.Unmarshal([]byte(`$.defaultValue$`), &$.mapDefaultVar$); err != nil {\n", args)
sw.Do("if err := $.jsonUnmarshal|raw$([]byte(`$.defaultValue$`), &$.mapDefaultVar$); err != nil {\n", args)
} else {
variablePointer := variablePlaceholder
if !isVarPointer {
variablePointer = "&" + variablePointer
}
sw.Do(fmt.Sprintf("if err := json.Unmarshal([]byte(`$.defaultValue$`), %s); err != nil {\n", variablePointer), args)
sw.Do(fmt.Sprintf("if err := $.jsonUnmarshal|raw$([]byte(`$.defaultValue$`), %s); err != nil {\n", variablePointer), args)
}
sw.Do("panic(err)\n", nil)
sw.Do("}\n", nil)
@@ -1121,7 +1125,7 @@ func (n *callNode) writeDefaulter(varName string, index string, isVarPointer boo
// WriteMethod performs an in-order traversal of the calltree, generating loops and if blocks as necessary
// to correctly turn the call tree into a method body that invokes all calls on all child nodes of the call tree.
// Depth is used to generate local variables at the proper depth.
func (n *callNode) WriteMethod(varName string, depth int, ancestors []*callNode, sw *generator.SnippetWriter) {
func (n *callNode) WriteMethod(c *generator.Context, varName string, depth int, ancestors []*callNode, sw *generator.SnippetWriter) {
// if len(n.call) > 0 {
// sw.Do(fmt.Sprintf("// %s\n", callPath(append(ancestors, n)).String()), nil)
// }
@@ -1153,10 +1157,10 @@ func (n *callNode) WriteMethod(varName string, depth int, ancestors []*callNode,
}
}
n.writeDefaulter(varName, index, isPointer, sw)
n.writeDefaulter(c, varName, index, isPointer, sw)
n.writeCalls(local, true, sw)
for i := range n.children {
n.children[i].WriteMethod(local, depth+1, append(ancestors, n), sw)
n.children[i].WriteMethod(c, local, depth+1, append(ancestors, n), sw)
}
sw.Do("}\n", nil)
case n.key:
@@ -1165,14 +1169,14 @@ func (n *callNode) WriteMethod(varName string, depth int, ancestors []*callNode,
index = index + "_" + ancestors[len(ancestors)-1].field
vars["index"] = index
sw.Do("for $.index$ := range $.var$ {\n", vars)
n.writeDefaulter(varName, index, isPointer, sw)
n.writeDefaulter(c, varName, index, isPointer, sw)
sw.Do("}\n", nil)
}
default:
n.writeDefaulter(varName, index, isPointer, sw)
n.writeDefaulter(c, varName, index, isPointer, sw)
n.writeCalls(varName, isPointer, sw)
for i := range n.children {
n.children[i].WriteMethod(varName, depth, append(ancestors, n), sw)
n.children[i].WriteMethod(c, varName, depth, append(ancestors, n), sw)
}
}

View File

@@ -74,7 +74,7 @@ func main() {
generators.NameSystems(),
generators.DefaultNameSystem(),
myTargets,
gengo.StdBuildTag,
args.GeneratedBuildTag,
pflag.Args(),
); err != nil {
klog.Fatalf("Error: %v", err)

View File

@@ -145,10 +145,7 @@ func isOptionalAlias(t *types.Type) bool {
if t.Underlying == nil || (t.Underlying.Kind != types.Map && t.Underlying.Kind != types.Slice) {
return false
}
if extractBoolTagOrDie("protobuf.nullable", t.CommentLines) == false {
return false
}
return true
return extractBoolTagOrDie("protobuf.nullable", t.CommentLines)
}
func (g *genProtoIDL) Imports(c *generator.Context) (imports []string) {
@@ -187,7 +184,7 @@ func (g *genProtoIDL) GenerateType(c *generator.Context, t *types.Type, w io.Wri
case types.Struct:
return b.doStruct(sw)
default:
return b.unknown(sw)
return b.unknown()
}
}
@@ -262,7 +259,7 @@ type bodyGen struct {
t *types.Type
}
func (b bodyGen) unknown(sw *generator.SnippetWriter) error {
func (b bodyGen) unknown() error {
return fmt.Errorf("not sure how to generate: %#v", b.t)
}

View File

@@ -61,7 +61,6 @@ func (g *genericGenerator) Namers(c *generator.Context) namer.NameSystems {
func (g *genericGenerator) Imports(c *generator.Context) (imports []string) {
imports = append(imports, g.imports.ImportLines()...)
imports = append(imports, "fmt")
return
}
@@ -127,6 +126,7 @@ func (g *genericGenerator) GenerateType(c *generator.Context, t *types.Type, w i
"cacheGenericLister": c.Universe.Type(cacheGenericLister),
"cacheNewGenericLister": c.Universe.Function(cacheNewGenericLister),
"cacheSharedIndexInformer": c.Universe.Type(cacheSharedIndexInformer),
"fmtErrorf": c.Universe.Type(fmtErrorfFunc),
"groups": groups,
"schemeGVs": schemeGVs,
"schemaGroupResource": c.Universe.Type(schemaGroupResource),
@@ -179,6 +179,6 @@ func (f *sharedInformerFactory) ForResource(resource {{.schemaGroupVersionResour
{{end -}}
}
return nil, fmt.Errorf("no informer found for %v", resource)
return nil, {{.fmtErrorf|raw}}("no informer found for %v", resource)
}
`

View File

@@ -86,6 +86,7 @@ func (g *informerGenerator) GenerateType(c *generator.Context, t *types.Type, w
"cacheNewSharedIndexInformer": c.Universe.Function(cacheNewSharedIndexInformer),
"cacheSharedIndexInformer": c.Universe.Type(cacheSharedIndexInformer),
"clientSetInterface": clientSetInterface,
"contextTODO": c.Universe.Type(contextTODOFunc),
"group": namer.IC(g.groupGoName),
"informerFor": informerFor,
"interfacesTweakListOptionsFunc": c.Universe.Type(types.Name{Package: g.internalInterfacesPackage, Name: "TweakListOptionsFunc"}),
@@ -151,13 +152,13 @@ func NewFiltered$.type|public$Informer(client $.clientSetInterface|raw$$if .name
if tweakListOptions != nil {
tweakListOptions(&options)
}
return client.$.group$$.version$().$.type|publicPlural$($if .namespaced$namespace$end$).List(context.TODO(), options)
return client.$.group$$.version$().$.type|publicPlural$($if .namespaced$namespace$end$).List($.contextTODO|raw$(), options)
},
WatchFunc: func(options $.v1ListOptions|raw$) ($.watchInterface|raw$, error) {
if tweakListOptions != nil {
tweakListOptions(&options)
}
return client.$.group$$.version$().$.type|publicPlural$($if .namespaced$namespace$end$).Watch(context.TODO(), options)
return client.$.group$$.version$().$.type|publicPlural$($if .namespaced$namespace$end$).Watch($.contextTODO|raw$(), options)
},
},
&$.type|raw${},

View File

@@ -249,7 +249,7 @@ func factoryTarget(outputDirBase, outputPkgBase string, boilerplate []byte, grou
OutputFilename: "factory.go",
},
outputPackage: outputPkgBase,
imports: generator.NewImportTracker(),
imports: generator.NewImportTrackerForPackage(outputPkgBase),
groupVersions: groupVersions,
clientSetPackage: clientSetPackage,
internalInterfacesPackage: path.Join(outputPkgBase, subdirForInternalInterfaces),
@@ -261,7 +261,7 @@ func factoryTarget(outputDirBase, outputPkgBase string, boilerplate []byte, grou
OutputFilename: "generic.go",
},
outputPackage: outputPkgBase,
imports: generator.NewImportTracker(),
imports: generator.NewImportTrackerForPackage(outputPkgBase),
groupVersions: groupVersions,
pluralExceptions: pluralExceptions,
typesForGroupVersion: typesForGroupVersion,
@@ -288,7 +288,7 @@ func factoryInterfaceTarget(outputDirBase, outputPkgBase string, boilerplate []b
OutputFilename: "factory_interfaces.go",
},
outputPackage: outputPkg,
imports: generator.NewImportTracker(),
imports: generator.NewImportTrackerForPackage(outputPkg),
clientSetPackage: clientSetPackage,
})
@@ -314,7 +314,7 @@ func groupTarget(outputDirBase, outputPackageBase string, groupVersions clientge
},
outputPackage: outputPkg,
groupVersions: groupVersions,
imports: generator.NewImportTracker(),
imports: generator.NewImportTrackerForPackage(outputPkg),
internalInterfacesPackage: path.Join(outputPackageBase, subdirForInternalInterfaces),
})
return generators
@@ -342,7 +342,7 @@ func versionTarget(outputDirBase, outputPkgBase string, groupPkgName string, gv
OutputFilename: "interface.go",
},
outputPackage: outputPkg,
imports: generator.NewImportTracker(),
imports: generator.NewImportTrackerForPackage(outputPkg),
types: typesToGenerate,
internalInterfacesPackage: path.Join(outputPkgBase, subdirForInternalInterfaces),
})
@@ -357,7 +357,7 @@ func versionTarget(outputDirBase, outputPkgBase string, groupPkgName string, gv
groupVersion: gv,
groupGoName: groupGoName,
typeToGenerate: t,
imports: generator.NewImportTracker(),
imports: generator.NewImportTrackerForPackage(outputPkg),
clientSetPackage: clientSetPackage,
listersPackage: listersPackage,
internalInterfacesPackage: path.Join(outputPkgBase, subdirForInternalInterfaces),

View File

@@ -29,6 +29,8 @@ var (
cacheNewSharedIndexInformer = types.Name{Package: "k8s.io/client-go/tools/cache", Name: "NewSharedIndexInformer"}
cacheSharedIndexInformer = types.Name{Package: "k8s.io/client-go/tools/cache", Name: "SharedIndexInformer"}
cacheTransformFunc = types.Name{Package: "k8s.io/client-go/tools/cache", Name: "TransformFunc"}
contextTODOFunc = types.Name{Package: "context", Name: "TODO"}
fmtErrorfFunc = types.Name{Package: "fmt", Name: "Errorf"}
listOptions = types.Name{Package: "k8s.io/kubernetes/pkg/apis/core", Name: "ListOptions"}
reflectType = types.Name{Package: "reflect", Name: "Type"}
runtimeObject = types.Name{Package: "k8s.io/apimachinery/pkg/runtime", Name: "Object"}

View File

@@ -149,7 +149,7 @@ func GetTargets(context *generator.Context, args *args.Args) []generator.Target
groupVersion: gv,
internalGVPkg: internalGVPkg,
typeToGenerate: t,
imports: generator.NewImportTracker(),
imports: generator.NewImportTrackerForPackage(outputPkg),
objectMeta: objectMeta,
})
}
@@ -213,11 +213,6 @@ func (g *listerGenerator) Namers(c *generator.Context) namer.NameSystems {
func (g *listerGenerator) Imports(c *generator.Context) (imports []string) {
imports = append(imports, g.imports.ImportLines()...)
imports = append(imports, "k8s.io/apimachinery/pkg/api/errors")
imports = append(imports, "k8s.io/apimachinery/pkg/labels")
imports = append(imports, "k8s.io/client-go/listers")
// for Indexer
imports = append(imports, "k8s.io/client-go/tools/cache")
return
}
@@ -226,9 +221,14 @@ func (g *listerGenerator) GenerateType(c *generator.Context, t *types.Type, w io
klog.V(5).Infof("processing type %v", t)
m := map[string]interface{}{
"Resource": c.Universe.Function(types.Name{Package: t.Name.Package, Name: "Resource"}),
"type": t,
"objectMeta": g.objectMeta,
"Resource": c.Universe.Function(types.Name{Package: t.Name.Package, Name: "Resource"}),
"labelsSelector": c.Universe.Function(types.Name{Package: "k8s.io/apimachinery/pkg/labels", Name: "Selector"}),
"listersResourceIndexer": c.Universe.Function(types.Name{Package: "k8s.io/client-go/listers", Name: "ResourceIndexer"}),
"listersNew": c.Universe.Function(types.Name{Package: "k8s.io/client-go/listers", Name: "New"}),
"listersNewNamespaced": c.Universe.Function(types.Name{Package: "k8s.io/client-go/listers", Name: "NewNamespaced"}),
"cacheIndexer": c.Universe.Type(types.Name{Package: "k8s.io/client-go/tools/cache", Name: "Indexer"}),
"type": t,
"objectMeta": g.objectMeta,
}
tags, err := util.ParseClientGenTags(append(t.SecondClosestCommentLines, t.CommentLines...))
@@ -262,7 +262,7 @@ var typeListerInterface = `
type $.type|public$Lister interface {
// List lists all $.type|publicPlural$ in the indexer.
// Objects returned here must be treated as read-only.
List(selector labels.Selector) (ret []*$.type|raw$, err error)
List(selector $.labelsSelector|raw$) (ret []*$.type|raw$, err error)
// $.type|publicPlural$ returns an object that can list and get $.type|publicPlural$.
$.type|publicPlural$(namespace string) $.type|public$NamespaceLister
$.type|public$ListerExpansion
@@ -275,7 +275,7 @@ var typeListerInterfaceNonNamespaced = `
type $.type|public$Lister interface {
// List lists all $.type|publicPlural$ in the indexer.
// Objects returned here must be treated as read-only.
List(selector labels.Selector) (ret []*$.type|raw$, err error)
List(selector $.labelsSelector|raw$) (ret []*$.type|raw$, err error)
// Get retrieves the $.type|public$ from the index for a given name.
// Objects returned here must be treated as read-only.
Get(name string) (*$.type|raw$, error)
@@ -289,21 +289,21 @@ type $.type|public$Lister interface {
var typeListerStruct = `
// $.type|private$Lister implements the $.type|public$Lister interface.
type $.type|private$Lister struct {
listers.ResourceIndexer[*$.type|raw$]
$.listersResourceIndexer|raw$[*$.type|raw$]
}
`
var typeListerConstructor = `
// New$.type|public$Lister returns a new $.type|public$Lister.
func New$.type|public$Lister(indexer cache.Indexer) $.type|public$Lister {
return &$.type|private$Lister{listers.New[*$.type|raw$](indexer, $.Resource|raw$("$.type|lowercaseSingular$"))}
func New$.type|public$Lister(indexer $.cacheIndexer|raw$) $.type|public$Lister {
return &$.type|private$Lister{$.listersNew|raw$[*$.type|raw$](indexer, $.Resource|raw$("$.type|lowercaseSingular$"))}
}
`
var typeListerNamespaceLister = `
// $.type|publicPlural$ returns an object that can list and get $.type|publicPlural$.
func (s *$.type|private$Lister) $.type|publicPlural$(namespace string) $.type|public$NamespaceLister {
return $.type|private$NamespaceLister{listers.NewNamespaced[*$.type|raw$](s.ResourceIndexer, namespace)}
return $.type|private$NamespaceLister{$.listersNewNamespaced|raw$[*$.type|raw$](s.ResourceIndexer, namespace)}
}
`
@@ -313,7 +313,7 @@ var namespaceListerInterface = `
type $.type|public$NamespaceLister interface {
// List lists all $.type|publicPlural$ in the indexer for a given namespace.
// Objects returned here must be treated as read-only.
List(selector labels.Selector) (ret []*$.type|raw$, err error)
List(selector $.labelsSelector|raw$) (ret []*$.type|raw$, err error)
// Get retrieves the $.type|public$ from the indexer for a given namespace and name.
// Objects returned here must be treated as read-only.
Get(name string) (*$.type|raw$, error)
@@ -328,6 +328,6 @@ var namespaceListerStruct = `
// $.type|private$NamespaceLister implements the $.type|public$NamespaceLister
// interface.
type $.type|private$NamespaceLister struct {
listers.ResourceIndexer[*$.type|raw$]
$.listersResourceIndexer|raw$[*$.type|raw$]
}
`

View File

@@ -115,7 +115,7 @@ func GetTargets(context *generator.Context, args *args.Args) []generator.Target
gv: gv,
typesToGenerate: typesToRegister,
outputPackage: pkg.Path,
imports: generator.NewImportTracker(),
imports: generator.NewImportTrackerForPackage(pkg.Path),
},
}
},