refact(deps): bump k8s and client-go deps to version v0.20.2 (#294)

Signed-off-by: prateekpandey14 <prateek.pandey@mayadata.io>
This commit is contained in:
Prateek Pandey 2021-03-31 16:43:42 +05:30 committed by GitHub
parent 533e17a9aa
commit b1aa6ab51a
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2196 changed files with 306727 additions and 251810 deletions

View file

@ -49,6 +49,9 @@ type CustomArgs struct {
ClientsetOnly bool
// FakeClient determines if client-gen generates the fake clients.
FakeClient bool
// PluralExceptions specify list of exceptions used when pluralizing certain types.
// For example 'Endpoints:Endpoints', otherwise the pluralizer will generate 'Endpointes'.
PluralExceptions []string
}
func NewDefaults() (*args.GeneratorArgs, *CustomArgs) {
@ -58,6 +61,7 @@ func NewDefaults() (*args.GeneratorArgs, *CustomArgs) {
ClientsetAPIPath: "/apis",
ClientsetOnly: false,
FakeClient: true,
PluralExceptions: []string{"Endpoints:Endpoints"},
}
genericArgs.CustomArgs = customArgs
genericArgs.InputDirs = DefaultInputDirs
@ -79,6 +83,8 @@ func (ca *CustomArgs) AddFlags(fs *pflag.FlagSet, inputBase string) {
pflag.BoolVar(&ca.ClientsetOnly, "clientset-only", ca.ClientsetOnly, "when set, client-gen only generates the clientset shell, without generating the individual typed clients")
pflag.BoolVar(&ca.FakeClient, "fake-clientset", ca.FakeClient, "when set, client-gen will generate the fake clientset that can be used in tests")
fs.StringSliceVar(&ca.PluralExceptions, "plural-exceptions", ca.PluralExceptions, "list of comma separated plural exception definitions in Type:PluralizedType form")
// support old flags
fs.SetNormalizeFunc(mapFlagName("clientset-path", "output-package", fs.GetNormalizeFunc()))
}

View file

@ -28,19 +28,17 @@ import (
"k8s.io/code-generator/cmd/client-gen/path"
clientgentypes "k8s.io/code-generator/cmd/client-gen/types"
codegennamer "k8s.io/code-generator/pkg/namer"
genutil "k8s.io/code-generator/pkg/util"
"k8s.io/gengo/args"
"k8s.io/gengo/generator"
"k8s.io/gengo/namer"
"k8s.io/gengo/types"
"k8s.io/klog"
"k8s.io/klog/v2"
)
// NameSystems returns the name system used by the generators in this package.
func NameSystems() namer.NameSystems {
pluralExceptions := map[string]string{
"Endpoints": "Endpoints",
}
func NameSystems(pluralExceptions map[string]string) namer.NameSystems {
lowercaseNamer := namer.NewAllLowercasePluralNamer(pluralExceptions)
publicNamer := &ExceptionNamer{
@ -282,7 +280,7 @@ func applyGroupOverrides(universe types.Universe, customArgs *clientgenargs.Cust
// Create a map from "old GV" to "new GV" so we know what changes we need to make.
changes := make(map[clientgentypes.GroupVersion]clientgentypes.GroupVersion)
for gv, inputDir := range customArgs.GroupVersionPackages() {
p := universe.Package(inputDir)
p := universe.Package(genutil.Vendorless(inputDir))
if override := types.ExtractCommentTags("+", p.Comments)["groupName"]; override != nil {
newGV := clientgentypes.GroupVersion{
Group: clientgentypes.Group(override[0]),

View file

@ -165,10 +165,3 @@ func (c *Clientset) $.GroupGoName$$.Version$() $.PackageAlias$.$.GroupGoName$$.V
return &fake$.PackageAlias$.Fake$.GroupGoName$$.Version${Fake: &c.Fake}
}
`
var clientsetInterfaceDefaultVersionImpl = `
// $.GroupGoName$ retrieves the $.GroupGoName$$.Version$Client
func (c *Clientset) $.GroupGoName$() $.PackageAlias$.$.GroupGoName$$.Version$Interface {
return &fake$.PackageAlias$.Fake$.GroupGoName$$.Version${Fake: &c.Fake}
}
`

View file

@ -122,9 +122,12 @@ func (g *genFakeForType) GenerateType(c *generator.Context, t *types.Type, w io.
"group": canonicalGroup,
"groupName": groupName,
"version": 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"}),
"ListOptions": c.Universe.Type(types.Name{Package: "k8s.io/apimachinery/pkg/apis/meta/v1", Name: "ListOptions"}),
"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"}),
"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"}),
"GroupVersionResource": c.Universe.Type(types.Name{Package: "k8s.io/apimachinery/pkg/runtime/schema", Name: "GroupVersionResource"}),
"GroupVersionKind": c.Universe.Type(types.Name{Package: "k8s.io/apimachinery/pkg/runtime/schema", Name: "GroupVersionKind"}),
@ -309,7 +312,7 @@ var $.type|allLowercasePlural$Kind = $.GroupVersionKind|raw${Group: "$.groupName
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(opts $.ListOptions|raw$) (result *$.type|raw$List, err error) {
func (c *Fake$.type|publicPlural$) List(ctx context.Context, opts $.ListOptions|raw$) (result *$.type|raw$List, err error) {
obj, err := c.Fake.
$if .namespaced$Invokes($.NewListAction|raw$($.type|allLowercasePlural$Resource, $.type|allLowercasePlural$Kind, c.ns, opts), &$.type|raw$List{})
$else$Invokes($.NewRootListAction|raw$($.type|allLowercasePlural$Resource, $.type|allLowercasePlural$Kind, opts), &$.type|raw$List{})$end$
@ -322,7 +325,7 @@ func (c *Fake$.type|publicPlural$) List(opts $.ListOptions|raw$) (result *$.type
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(opts $.ListOptions|raw$) (result *$.type|raw$List, err error) {
func (c *Fake$.type|publicPlural$) List(ctx context.Context, opts $.ListOptions|raw$) (result *$.type|raw$List, err error) {
obj, err := c.Fake.
$if .namespaced$Invokes($.NewListAction|raw$($.type|allLowercasePlural$Resource, $.type|allLowercasePlural$Kind, c.ns, opts), &$.type|raw$List{})
$else$Invokes($.NewRootListAction|raw$($.type|allLowercasePlural$Resource, $.type|allLowercasePlural$Kind, opts), &$.type|raw$List{})$end$
@ -346,7 +349,7 @@ func (c *Fake$.type|publicPlural$) List(opts $.ListOptions|raw$) (result *$.type
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(name string, options $.GetOptions|raw$) (result *$.resultType|raw$, err error) {
func (c *Fake$.type|publicPlural$) Get(ctx context.Context, name string, options $.GetOptions|raw$) (result *$.resultType|raw$, err error) {
obj, err := c.Fake.
$if .namespaced$Invokes($.NewGetAction|raw$($.type|allLowercasePlural$Resource, c.ns, name), &$.resultType|raw${})
$else$Invokes($.NewRootGetAction|raw$($.type|allLowercasePlural$Resource, name), &$.resultType|raw${})$end$
@ -359,7 +362,7 @@ func (c *Fake$.type|publicPlural$) Get(name string, options $.GetOptions|raw$) (
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($.type|private$Name string, options $.GetOptions|raw$) (result *$.resultType|raw$, err error) {
func (c *Fake$.type|publicPlural$) Get(ctx context.Context, $.type|private$Name string, options $.GetOptions|raw$) (result *$.resultType|raw$, err error) {
obj, err := c.Fake.
$if .namespaced$Invokes($.NewGetSubresourceAction|raw$($.type|allLowercasePlural$Resource, c.ns, "$.subresourcePath$", $.type|private$Name), &$.resultType|raw${})
$else$Invokes($.NewRootGetSubresourceAction|raw$($.type|allLowercasePlural$Resource, "$.subresourcePath$", $.type|private$Name), &$.resultType|raw${})$end$
@ -372,7 +375,7 @@ func (c *Fake$.type|publicPlural$) Get($.type|private$Name string, options $.Get
var deleteTemplate = `
// Delete takes name of the $.type|private$ and deletes it. Returns an error if one occurs.
func (c *Fake$.type|publicPlural$) Delete(name string, options *$.DeleteOptions|raw$) error {
func (c *Fake$.type|publicPlural$) Delete(ctx context.Context, name string, opts $.DeleteOptions|raw$) error {
_, err := c.Fake.
$if .namespaced$Invokes($.NewDeleteAction|raw$($.type|allLowercasePlural$Resource, c.ns, name), &$.type|raw${})
$else$Invokes($.NewRootDeleteAction|raw$($.type|allLowercasePlural$Resource, name), &$.type|raw${})$end$
@ -382,9 +385,9 @@ func (c *Fake$.type|publicPlural$) Delete(name string, options *$.DeleteOptions|
var deleteCollectionTemplate = `
// DeleteCollection deletes a collection of objects.
func (c *Fake$.type|publicPlural$) DeleteCollection(options *$.DeleteOptions|raw$, listOptions $.ListOptions|raw$) error {
$if .namespaced$action := $.NewDeleteCollectionAction|raw$($.type|allLowercasePlural$Resource, c.ns, listOptions)
$else$action := $.NewRootDeleteCollectionAction|raw$($.type|allLowercasePlural$Resource, listOptions)
func (c *Fake$.type|publicPlural$) DeleteCollection(ctx context.Context, opts $.DeleteOptions|raw$, listOpts $.ListOptions|raw$) error {
$if .namespaced$action := $.NewDeleteCollectionAction|raw$($.type|allLowercasePlural$Resource, c.ns, listOpts)
$else$action := $.NewRootDeleteCollectionAction|raw$($.type|allLowercasePlural$Resource, listOpts)
$end$
_, err := c.Fake.Invokes(action, &$.type|raw$List{})
return err
@ -392,7 +395,7 @@ func (c *Fake$.type|publicPlural$) DeleteCollection(options *$.DeleteOptions|raw
`
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($.inputType|private$ *$.inputType|raw$) (result *$.resultType|raw$, err error) {
func (c *Fake$.type|publicPlural$) Create(ctx context.Context, $.inputType|private$ *$.inputType|raw$, opts $.CreateOptions|raw$) (result *$.resultType|raw$, err error) {
obj, err := c.Fake.
$if .namespaced$Invokes($.NewCreateAction|raw$($.inputType|allLowercasePlural$Resource, c.ns, $.inputType|private$), &$.resultType|raw${})
$else$Invokes($.NewRootCreateAction|raw$($.inputType|allLowercasePlural$Resource, $.inputType|private$), &$.resultType|raw${})$end$
@ -405,10 +408,10 @@ func (c *Fake$.type|publicPlural$) Create($.inputType|private$ *$.inputType|raw$
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($.type|private$Name string, $.inputType|private$ *$.inputType|raw$) (result *$.resultType|raw$, err error) {
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) {
obj, err := c.Fake.
$if .namespaced$Invokes($.NewCreateSubresourceAction|raw$($.type|allLowercasePlural$Resource, $.type|private$Name, "$.subresourcePath$", c.ns, $.inputType|private$), &$.resultType|raw${})
$else$Invokes($.NewRootCreateSubresourceAction|raw$($.type|allLowercasePlural$Resource, "$.subresourcePath$", $.inputType|private$), &$.resultType|raw${})$end$
$else$Invokes($.NewRootCreateSubresourceAction|raw$($.type|allLowercasePlural$Resource, $.type|private$Name, "$.subresourcePath$", $.inputType|private$), &$.resultType|raw${})$end$
if obj == nil {
return nil, err
}
@ -418,7 +421,7 @@ func (c *Fake$.type|publicPlural$) Create($.type|private$Name string, $.inputTyp
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($.inputType|private$ *$.inputType|raw$) (result *$.resultType|raw$, err error) {
func (c *Fake$.type|publicPlural$) Update(ctx context.Context, $.inputType|private$ *$.inputType|raw$, opts $.UpdateOptions|raw$) (result *$.resultType|raw$, err error) {
obj, err := c.Fake.
$if .namespaced$Invokes($.NewUpdateAction|raw$($.inputType|allLowercasePlural$Resource, c.ns, $.inputType|private$), &$.resultType|raw${})
$else$Invokes($.NewRootUpdateAction|raw$($.inputType|allLowercasePlural$Resource, $.inputType|private$), &$.resultType|raw${})$end$
@ -431,7 +434,7 @@ func (c *Fake$.type|publicPlural$) Update($.inputType|private$ *$.inputType|raw$
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($.type|private$Name string, $.inputType|private$ *$.inputType|raw$) (result *$.resultType|raw$, err error) {
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) {
obj, err := c.Fake.
$if .namespaced$Invokes($.NewUpdateSubresourceAction|raw$($.type|allLowercasePlural$Resource, "$.subresourcePath$", c.ns, $.inputType|private$), &$.inputType|raw${})
$else$Invokes($.NewRootUpdateSubresourceAction|raw$($.type|allLowercasePlural$Resource, "$.subresourcePath$", $.inputType|private$), &$.resultType|raw${})$end$
@ -445,7 +448,7 @@ func (c *Fake$.type|publicPlural$) Update($.type|private$Name string, $.inputTyp
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($.type|private$ *$.type|raw$) (*$.type|raw$, error) {
func (c *Fake$.type|publicPlural$) UpdateStatus(ctx context.Context, $.type|private$ *$.type|raw$, opts $.UpdateOptions|raw$) (*$.type|raw$, error) {
obj, err := c.Fake.
$if .namespaced$Invokes($.NewUpdateSubresourceAction|raw$($.type|allLowercasePlural$Resource, "status", c.ns, $.type|private$), &$.type|raw${})
$else$Invokes($.NewRootUpdateSubresourceAction|raw$($.type|allLowercasePlural$Resource, "status", $.type|private$), &$.type|raw${})$end$
@ -458,7 +461,7 @@ func (c *Fake$.type|publicPlural$) UpdateStatus($.type|private$ *$.type|raw$) (*
var watchTemplate = `
// Watch returns a $.watchInterface|raw$ that watches the requested $.type|privatePlural$.
func (c *Fake$.type|publicPlural$) Watch(opts $.ListOptions|raw$) ($.watchInterface|raw$, error) {
func (c *Fake$.type|publicPlural$) Watch(ctx context.Context, opts $.ListOptions|raw$) ($.watchInterface|raw$, error) {
return c.Fake.
$if .namespaced$InvokesWatch($.NewWatchAction|raw$($.type|allLowercasePlural$Resource, c.ns, opts))
$else$InvokesWatch($.NewRootWatchAction|raw$($.type|allLowercasePlural$Resource, opts))$end$
@ -467,7 +470,7 @@ func (c *Fake$.type|publicPlural$) Watch(opts $.ListOptions|raw$) ($.watchInterf
var patchTemplate = `
// Patch applies the patch and returns the patched $.resultType|private$.
func (c *Fake$.type|publicPlural$) Patch(name string, pt $.PatchType|raw$, data []byte, subresources ...string) (result *$.resultType|raw$, err error) {
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) {
obj, err := c.Fake.
$if .namespaced$Invokes($.NewPatchSubresourceAction|raw$($.type|allLowercasePlural$Resource, c.ns, name, pt, data, subresources... ), &$.resultType|raw${})
$else$Invokes($.NewRootPatchSubresourceAction|raw$($.type|allLowercasePlural$Resource, name, pt, data, subresources...), &$.resultType|raw${})$end$

View file

@ -134,9 +134,14 @@ func (c *Clientset) Discovery() $.DiscoveryInterface|raw$ {
var newClientsetForConfigTemplate = `
// NewForConfig creates a new Clientset for the given config.
// If config's RateLimiter is not set and QPS and Burst are acceptable,
// NewForConfig will generate a rate-limiter in configShallowCopy.
func NewForConfig(c *$.Config|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")
}
configShallowCopy.RateLimiter = $.flowcontrolNewTokenBucketRateLimiter|raw$(configShallowCopy.QPS, configShallowCopy.Burst)
}
var cs Clientset

View file

@ -43,7 +43,9 @@ type genClientForType struct {
var _ generator.Generator = &genClientForType{}
// Filter ignores all but one type because we're making a single file per type.
func (g *genClientForType) Filter(c *generator.Context, t *types.Type) bool { return t == g.typeToMatch }
func (g *genClientForType) Filter(c *generator.Context, t *types.Type) bool {
return t == g.typeToMatch
}
func (g *genClientForType) Namers(c *generator.Context) namer.NameSystems {
return namer.NameSystems{
@ -116,9 +118,10 @@ func (g *genClientForType) GenerateType(c *generator.Context, t *types.Type, w i
"type": t,
"inputType": &inputType,
"resultType": &resultType,
"DeleteOptions": c.Universe.Type(types.Name{Package: "k8s.io/apimachinery/pkg/apis/meta/v1", Name: "DeleteOptions"}),
"ListOptions": c.Universe.Type(types.Name{Package: "k8s.io/apimachinery/pkg/apis/meta/v1", Name: "ListOptions"}),
"CreateOptions": c.Universe.Type(types.Name{Package: "k8s.io/apimachinery/pkg/apis/meta/v1", Name: "CreateOptions"}),
"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"}),
"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"}),
},
})
@ -135,9 +138,12 @@ func (g *genClientForType) GenerateType(c *generator.Context, t *types.Type, w i
"subresourcePath": "",
"GroupGoName": g.groupGoName,
"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"}),
"ListOptions": c.Universe.Type(types.Name{Package: "k8s.io/apimachinery/pkg/apis/meta/v1", Name: "ListOptions"}),
"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"}),
"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"}),
"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"}),
@ -304,22 +310,22 @@ func generateInterface(tags util.Tags) string {
}
var subresourceDefaultVerbTemplates = map[string]string{
"create": `Create($.type|private$Name string, $.inputType|private$ *$.inputType|raw$) (*$.resultType|raw$, error)`,
"list": `List($.type|private$Name string, opts $.ListOptions|raw$) (*$.resultType|raw$List, error)`,
"update": `Update($.type|private$Name string, $.inputType|private$ *$.inputType|raw$) (*$.resultType|raw$, error)`,
"get": `Get($.type|private$Name string, options $.GetOptions|raw$) (*$.resultType|raw$, error)`,
"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)`,
}
var defaultVerbTemplates = map[string]string{
"create": `Create(*$.inputType|raw$) (*$.resultType|raw$, error)`,
"update": `Update(*$.inputType|raw$) (*$.resultType|raw$, error)`,
"updateStatus": `UpdateStatus(*$.type|raw$) (*$.type|raw$, error)`,
"delete": `Delete(name string, options *$.DeleteOptions|raw$) error`,
"deleteCollection": `DeleteCollection(options *$.DeleteOptions|raw$, listOptions $.ListOptions|raw$) error`,
"get": `Get(name string, options $.GetOptions|raw$) (*$.resultType|raw$, error)`,
"list": `List(opts $.ListOptions|raw$) (*$.resultType|raw$List, error)`,
"watch": `Watch(opts $.ListOptions|raw$) ($.watchInterface|raw$, error)`,
"patch": `Patch(name string, pt $.PatchType|raw$, data []byte, subresources ...string) (result *$.resultType|raw$, err error)`,
"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)`,
"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)`,
}
// group client will implement this interface.
@ -386,7 +392,7 @@ func new$.type|publicPlural$(c *$.GroupGoName$$.Version$Client) *$.type|privateP
`
var listTemplate = `
// List takes label and field selectors, and returns the list of $.resultType|publicPlural$ that match those selectors.
func (c *$.type|privatePlural$) List(opts $.ListOptions|raw$) (result *$.resultType|raw$List, err error) {
func (c *$.type|privatePlural$) List(ctx context.Context, opts $.ListOptions|raw$) (result *$.resultType|raw$List, err error) {
var timeout time.Duration
if opts.TimeoutSeconds != nil{
timeout = time.Duration(*opts.TimeoutSeconds) * time.Second
@ -397,7 +403,7 @@ func (c *$.type|privatePlural$) List(opts $.ListOptions|raw$) (result *$.resultT
Resource("$.type|resource$").
VersionedParams(&opts, $.schemeParameterCodec|raw$).
Timeout(timeout).
Do().
Do(ctx).
Into(result)
return
}
@ -405,7 +411,7 @@ func (c *$.type|privatePlural$) List(opts $.ListOptions|raw$) (result *$.resultT
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($.type|private$Name string, opts $.ListOptions|raw$) (result *$.resultType|raw$List, err error) {
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
if opts.TimeoutSeconds != nil{
timeout = time.Duration(*opts.TimeoutSeconds) * time.Second
@ -418,7 +424,7 @@ func (c *$.type|privatePlural$) List($.type|private$Name string, opts $.ListOpti
SubResource("$.subresourcePath$").
VersionedParams(&opts, $.schemeParameterCodec|raw$).
Timeout(timeout).
Do().
Do(ctx).
Into(result)
return
}
@ -426,14 +432,14 @@ func (c *$.type|privatePlural$) List($.type|private$Name string, opts $.ListOpti
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(name string, options $.GetOptions|raw$) (result *$.resultType|raw$, err error) {
func (c *$.type|privatePlural$) Get(ctx context.Context, name string, options $.GetOptions|raw$) (result *$.resultType|raw$, err error) {
result = &$.resultType|raw${}
err = c.client.Get().
$if .namespaced$Namespace(c.ns).$end$
Resource("$.type|resource$").
Name(name).
VersionedParams(&options, $.schemeParameterCodec|raw$).
Do().
Do(ctx).
Into(result)
return
}
@ -441,7 +447,7 @@ func (c *$.type|privatePlural$) Get(name string, options $.GetOptions|raw$) (res
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($.type|private$Name string, options $.GetOptions|raw$) (result *$.resultType|raw$, err error) {
func (c *$.type|privatePlural$) Get(ctx context.Context, $.type|private$Name string, options $.GetOptions|raw$) (result *$.resultType|raw$, err error) {
result = &$.resultType|raw${}
err = c.client.Get().
$if .namespaced$Namespace(c.ns).$end$
@ -449,7 +455,7 @@ func (c *$.type|privatePlural$) Get($.type|private$Name string, options $.GetOpt
Name($.type|private$Name).
SubResource("$.subresourcePath$").
VersionedParams(&options, $.schemeParameterCodec|raw$).
Do().
Do(ctx).
Into(result)
return
}
@ -457,46 +463,47 @@ func (c *$.type|privatePlural$) Get($.type|private$Name string, options $.GetOpt
var deleteTemplate = `
// Delete takes name of the $.type|private$ and deletes it. Returns an error if one occurs.
func (c *$.type|privatePlural$) Delete(name string, options *$.DeleteOptions|raw$) error {
func (c *$.type|privatePlural$) Delete(ctx context.Context, name string, opts $.DeleteOptions|raw$) error {
return c.client.Delete().
$if .namespaced$Namespace(c.ns).$end$
Resource("$.type|resource$").
Name(name).
Body(options).
Do().
Body(&opts).
Do(ctx).
Error()
}
`
var deleteCollectionTemplate = `
// DeleteCollection deletes a collection of objects.
func (c *$.type|privatePlural$) DeleteCollection(options *$.DeleteOptions|raw$, listOptions $.ListOptions|raw$) error {
func (c *$.type|privatePlural$) DeleteCollection(ctx context.Context, opts $.DeleteOptions|raw$, listOpts $.ListOptions|raw$) error {
var timeout time.Duration
if listOptions.TimeoutSeconds != nil{
timeout = time.Duration(*listOptions.TimeoutSeconds) * time.Second
if listOpts.TimeoutSeconds != nil{
timeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second
}
return c.client.Delete().
$if .namespaced$Namespace(c.ns).$end$
Resource("$.type|resource$").
VersionedParams(&listOptions, $.schemeParameterCodec|raw$).
VersionedParams(&listOpts, $.schemeParameterCodec|raw$).
Timeout(timeout).
Body(options).
Do().
Body(&opts).
Do(ctx).
Error()
}
`
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($.type|private$Name string, $.inputType|private$ *$.inputType|raw$) (result *$.resultType|raw$, err error) {
func (c *$.type|privatePlural$) Create(ctx context.Context, $.type|private$Name string, $.inputType|private$ *$.inputType|raw$, opts $.CreateOptions|raw$) (result *$.resultType|raw$, err error) {
result = &$.resultType|raw${}
err = c.client.Post().
$if .namespaced$Namespace(c.ns).$end$
Resource("$.type|resource$").
Name($.type|private$Name).
SubResource("$.subresourcePath$").
VersionedParams(&opts, $.schemeParameterCodec|raw$).
Body($.inputType|private$).
Do().
Do(ctx).
Into(result)
return
}
@ -504,13 +511,14 @@ func (c *$.type|privatePlural$) Create($.type|private$Name string, $.inputType|p
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($.inputType|private$ *$.inputType|raw$) (result *$.resultType|raw$, err error) {
func (c *$.type|privatePlural$) Create(ctx context.Context, $.inputType|private$ *$.inputType|raw$, opts $.CreateOptions|raw$) (result *$.resultType|raw$, err error) {
result = &$.resultType|raw${}
err = c.client.Post().
$if .namespaced$Namespace(c.ns).$end$
Resource("$.type|resource$").
VersionedParams(&opts, $.schemeParameterCodec|raw$).
Body($.inputType|private$).
Do().
Do(ctx).
Into(result)
return
}
@ -518,15 +526,16 @@ func (c *$.type|privatePlural$) Create($.inputType|private$ *$.inputType|raw$) (
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($.type|private$Name string, $.inputType|private$ *$.inputType|raw$) (result *$.resultType|raw$, err error) {
func (c *$.type|privatePlural$) Update(ctx context.Context, $.type|private$Name string, $.inputType|private$ *$.inputType|raw$, opts $.UpdateOptions|raw$) (result *$.resultType|raw$, err error) {
result = &$.resultType|raw${}
err = c.client.Put().
$if .namespaced$Namespace(c.ns).$end$
Resource("$.type|resource$").
Name($.type|private$Name).
SubResource("$.subresourcePath$").
VersionedParams(&opts, $.schemeParameterCodec|raw$).
Body($.inputType|private$).
Do().
Do(ctx).
Into(result)
return
}
@ -534,14 +543,15 @@ func (c *$.type|privatePlural$) Update($.type|private$Name string, $.inputType|p
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($.inputType|private$ *$.inputType|raw$) (result *$.resultType|raw$, err error) {
func (c *$.type|privatePlural$) Update(ctx context.Context, $.inputType|private$ *$.inputType|raw$, opts $.UpdateOptions|raw$) (result *$.resultType|raw$, err error) {
result = &$.resultType|raw${}
err = c.client.Put().
$if .namespaced$Namespace(c.ns).$end$
Resource("$.type|resource$").
Name($.inputType|private$.Name).
VersionedParams(&opts, $.schemeParameterCodec|raw$).
Body($.inputType|private$).
Do().
Do(ctx).
Into(result)
return
}
@ -550,16 +560,16 @@ func (c *$.type|privatePlural$) Update($.inputType|private$ *$.inputType|raw$) (
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 *$.type|privatePlural$) UpdateStatus($.type|private$ *$.type|raw$) (result *$.type|raw$, err error) {
func (c *$.type|privatePlural$) UpdateStatus(ctx context.Context, $.type|private$ *$.type|raw$, opts $.UpdateOptions|raw$) (result *$.type|raw$, err error) {
result = &$.type|raw${}
err = c.client.Put().
$if .namespaced$Namespace(c.ns).$end$
Resource("$.type|resource$").
Name($.type|private$.Name).
SubResource("status").
VersionedParams(&opts, $.schemeParameterCodec|raw$).
Body($.type|private$).
Do().
Do(ctx).
Into(result)
return
}
@ -567,7 +577,7 @@ func (c *$.type|privatePlural$) UpdateStatus($.type|private$ *$.type|raw$) (resu
var watchTemplate = `
// Watch returns a $.watchInterface|raw$ that watches the requested $.type|privatePlural$.
func (c *$.type|privatePlural$) Watch(opts $.ListOptions|raw$) ($.watchInterface|raw$, error) {
func (c *$.type|privatePlural$) Watch(ctx context.Context, opts $.ListOptions|raw$) ($.watchInterface|raw$, error) {
var timeout time.Duration
if opts.TimeoutSeconds != nil{
timeout = time.Duration(*opts.TimeoutSeconds) * time.Second
@ -578,21 +588,22 @@ func (c *$.type|privatePlural$) Watch(opts $.ListOptions|raw$) ($.watchInterface
Resource("$.type|resource$").
VersionedParams(&opts, $.schemeParameterCodec|raw$).
Timeout(timeout).
Watch()
Watch(ctx)
}
`
var patchTemplate = `
// Patch applies the patch and returns the patched $.resultType|private$.
func (c *$.type|privatePlural$) Patch(name string, pt $.PatchType|raw$, data []byte, subresources ...string) (result *$.resultType|raw$, err error) {
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) {
result = &$.resultType|raw${}
err = c.client.Patch(pt).
$if .namespaced$Namespace(c.ns).$end$
Resource("$.type|resource$").
SubResource(subresources...).
Name(name).
SubResource(subresources...).
VersionedParams(&opts, $.schemeParameterCodec|raw$).
Body(data).
Do().
Do(ctx).
Into(result)
return
}

View file

@ -87,6 +87,7 @@ func (g *GenScheme) GenerateType(c *generator.Context, t *types.Type, w io.Write
allInstallGroups := clientgentypes.ToGroupInstallPackages(g.Groups, g.GroupGoNames)
m := map[string]interface{}{
"publicScheme": !g.PrivateScheme,
"allGroupVersions": allGroupVersions,
"allInstallGroups": allInstallGroups,
"customRegister": false,
@ -133,7 +134,7 @@ func (g *GenScheme) GenerateType(c *generator.Context, t *types.Type, w io.Write
var globalsTemplate = `
var $.Scheme$ = $.runtimeNewScheme|raw$()
var $.Codecs$ = $.serializerNewCodecFactory|raw$($.Scheme$)
var $.ParameterCodec$ = $.runtimeNewParameterCodec|raw$($.Scheme$)`
$if .publicScheme$var $.ParameterCodec$ = $.runtimeNewParameterCodec|raw$($.Scheme$)$end -$`
var registryRegistration = `

View file

@ -190,7 +190,7 @@ func MustParseClientGenTags(lines []string) Tags {
func ParseClientGenTags(lines []string) (Tags, error) {
ret := Tags{}
values := types.ExtractCommentTags("+", lines)
value := []string{}
var value []string
value, ret.GenerateClient = values["genclient"]
// Check the old format and error when used to avoid generating client when //+genclient=false
if len(value) > 0 && len(value[0]) > 0 {

View file

@ -23,7 +23,7 @@ import (
"github.com/spf13/pflag"
"k8s.io/gengo/args"
"k8s.io/klog"
"k8s.io/klog/v2"
generatorargs "k8s.io/code-generator/cmd/client-gen/args"
"k8s.io/code-generator/cmd/client-gen/generators"
@ -57,7 +57,7 @@ func main() {
}
if err := genericArgs.Execute(
generators.NameSystems(),
generators.NameSystems(util.PluralExceptionListToMapOrDie(customArgs.PluralExceptions)),
generators.DefaultNameSystem(),
generators.Packages,
); err != nil {

View file

@ -42,6 +42,11 @@ type CustomArgs 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
@ -67,6 +72,8 @@ func (ca *CustomArgs) 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.")
pflag.CommandLine.StringSliceVar(&ca.ExtraPeerDirs, "extra-peer-dirs", ca.ExtraPeerDirs,
"Application specific comma-separated list of import paths which are considered, after tag-specified peers and base-peer-dirs, for conversions.")
pflag.CommandLine.StringSliceVar(&ca.ExtraDirs, "extra-dirs", ca.ExtraDirs,
"Application specific comma-separated list of import paths which are loaded and considered for callable conversions, but are not considered peers for conversion.")
pflag.CommandLine.BoolVar(&ca.SkipUnsafe, "skip-unsafe", ca.SkipUnsafe,
"If true, will not generate code using unsafe pointer conversions; resulting code may be slower.")
}

View file

@ -21,6 +21,7 @@ import (
"fmt"
"io"
"path/filepath"
"reflect"
"sort"
"strings"
@ -29,9 +30,10 @@ import (
"k8s.io/gengo/namer"
"k8s.io/gengo/types"
"k8s.io/klog"
"k8s.io/klog/v2"
conversionargs "k8s.io/code-generator/cmd/conversion-gen/args"
genutil "k8s.io/code-generator/pkg/util"
)
// These are the comment tags that carry parameters for conversion generation.
@ -41,6 +43,9 @@ const (
// e.g., "+k8s:conversion-gen=false" in a type's comment will let
// conversion-gen skip that type.
tagName = "k8s:conversion-gen"
// e.g. "+k8s:conversion-gen:explicit-from=net/url.Values" in the type comment
// will result in generating conversion from net/url.Values.
explicitFromTagName = "k8s:conversion-gen:explicit-from"
// e.g., "+k8s:conversion-gen-external-types=<type-pkg>" in doc.go, where
// <type-pkg> is the relative path to the package the types are defined in.
externalTypesTagName = "k8s:conversion-gen-external-types"
@ -50,6 +55,10 @@ func extractTag(comments []string) []string {
return types.ExtractCommentTags("+", comments)[tagName]
}
func extractExplicitFromTag(comments []string) []string {
return types.ExtractCommentTags("+", comments)[explicitFromTagName]
}
func extractExternalTypesTag(comments []string) []string {
return types.ExtractCommentTags("+", comments)[externalTypesTagName]
}
@ -240,14 +249,24 @@ func Packages(context *generator.Context, arguments *args.GeneratorArgs) generat
peerPkgs := extractTag(pkg.Comments)
if peerPkgs != nil {
klog.V(5).Infof(" tags: %q", peerPkgs)
if len(peerPkgs) == 1 && peerPkgs[0] == "false" {
// If a single +k8s:conversion-gen=false tag is defined, we still want
// the generator to fire for this package for explicit conversions, but
// we are clearing the peerPkgs to not generate any standard conversions.
peerPkgs = nil
}
} else {
klog.V(5).Infof(" no tag")
continue
}
skipUnsafe := false
extraDirs := []string{}
if customArgs, ok := arguments.CustomArgs.(*conversionargs.CustomArgs); ok {
peerPkgs = append(peerPkgs, customArgs.BasePeerDirs...)
peerPkgs = append(peerPkgs, customArgs.ExtraPeerDirs...)
if len(peerPkgs) > 0 {
peerPkgs = append(peerPkgs, customArgs.BasePeerDirs...)
peerPkgs = append(peerPkgs, customArgs.ExtraPeerDirs...)
}
extraDirs = customArgs.ExtraDirs
skipUnsafe = customArgs.SkipUnsafe
}
@ -276,18 +295,15 @@ func Packages(context *generator.Context, arguments *args.GeneratorArgs) generat
// in the output directory.
// TODO: build a more fundamental concept in gengo for dealing with modifications
// to vendored packages.
vendorless := func(pkg string) string {
if pos := strings.LastIndex(pkg, "/vendor/"); pos != -1 {
return pkg[pos+len("/vendor/"):]
}
return pkg
}
for i := range peerPkgs {
peerPkgs[i] = vendorless(peerPkgs[i])
peerPkgs[i] = genutil.Vendorless(peerPkgs[i])
}
for i := range extraDirs {
extraDirs[i] = genutil.Vendorless(extraDirs[i])
}
// Make sure our peer-packages are added and fully parsed.
for _, pp := range peerPkgs {
for _, pp := range append(peerPkgs, extraDirs...) {
context.AddDir(pp)
p := context.Universe[pp]
if nil == p {
@ -457,12 +473,13 @@ type genConversion struct {
// the package that the conversion funcs are going to be output to
outputPackage string
// packages that contain the peer of types in typesPacakge
peerPackages []string
manualConversions conversionFuncMap
imports namer.ImportTracker
types []*types.Type
skippedFields map[*types.Type][]string
useUnsafe TypesEqual
peerPackages []string
manualConversions conversionFuncMap
imports namer.ImportTracker
types []*types.Type
explicitConversions []conversionPair
skippedFields map[*types.Type][]string
useUnsafe TypesEqual
}
func NewGenConversion(sanitizedName, typesPackage, outputPackage string, manualConversions conversionFuncMap, peerPkgs []string, useUnsafe TypesEqual) generator.Generator {
@ -470,14 +487,15 @@ func NewGenConversion(sanitizedName, typesPackage, outputPackage string, manualC
DefaultGen: generator.DefaultGen{
OptionalName: sanitizedName,
},
typesPackage: typesPackage,
outputPackage: outputPackage,
peerPackages: peerPkgs,
manualConversions: manualConversions,
imports: generator.NewImportTracker(),
types: []*types.Type{},
skippedFields: map[*types.Type][]string{},
useUnsafe: useUnsafe,
typesPackage: typesPackage,
outputPackage: outputPackage,
peerPackages: peerPkgs,
manualConversions: manualConversions,
imports: generator.NewImportTracker(),
types: []*types.Type{},
explicitConversions: []conversionPair{},
skippedFields: map[*types.Type][]string{},
useUnsafe: useUnsafe,
}
}
@ -534,17 +552,55 @@ func (g *genConversion) convertibleOnlyWithinPackage(inType, outType *types.Type
return true
}
func (g *genConversion) Filter(c *generator.Context, t *types.Type) bool {
peerType := getPeerTypeFor(c, t, g.peerPackages)
if peerType == nil {
return false
}
if !g.convertibleOnlyWithinPackage(t, peerType) {
return false
func getExplicitFromTypes(t *types.Type) []types.Name {
comments := append(t.SecondClosestCommentLines, t.CommentLines...)
paths := extractExplicitFromTag(comments)
result := []types.Name{}
for _, path := range paths {
items := strings.Split(path, ".")
if len(items) != 2 {
klog.Errorf("Unexpected k8s:conversion-gen:explicit-from tag: %s", path)
continue
}
switch {
case items[0] == "net/url" && items[1] == "Values":
default:
klog.Fatalf("Not supported k8s:conversion-gen:explicit-from tag: %s", path)
}
result = append(result, types.Name{Package: items[0], Name: items[1]})
}
return result
}
g.types = append(g.types, t)
return true
func (g *genConversion) Filter(c *generator.Context, t *types.Type) bool {
convertibleWithPeer := func() bool {
peerType := getPeerTypeFor(c, t, g.peerPackages)
if peerType == nil {
return false
}
if !g.convertibleOnlyWithinPackage(t, peerType) {
return false
}
g.types = append(g.types, t)
return true
}()
explicitlyConvertible := func() bool {
inTypes := getExplicitFromTypes(t)
if len(inTypes) == 0 {
return false
}
for i := range inTypes {
pair := conversionPair{
inType: &types.Type{Name: inTypes[i]},
outType: t,
}
g.explicitConversions = append(g.explicitConversions, pair)
}
return true
}()
return convertibleWithPeer || explicitlyConvertible
}
func (g *genConversion) isOtherPackage(pkg string) bool {
@ -582,7 +638,7 @@ func (g *genConversion) preexists(inType, outType *types.Type) (*types.Type, boo
}
func (g *genConversion) Init(c *generator.Context, w io.Writer) error {
if klog.V(5) {
if klog.V(5).Enabled() {
if m, ok := g.useUnsafe.(equalMemoryTypes); ok {
var result []string
klog.Infof("All objects without identical memory layout:")
@ -613,11 +669,21 @@ func (g *genConversion) Init(c *generator.Context, w io.Writer) error {
sw.Do("func RegisterConversions(s $.|raw$) error {\n", schemePtr)
for _, t := range g.types {
peerType := getPeerTypeFor(c, t, g.peerPackages)
args := argsFromType(t, peerType).With("Scope", types.Ref(conversionPackagePath, "Scope"))
sw.Do("if err := s.AddGeneratedConversionFunc((*$.inType|raw$)(nil), (*$.outType|raw$)(nil), func(a, b interface{}, scope $.Scope|raw$) error { return "+nameTmpl+"(a.(*$.inType|raw$), b.(*$.outType|raw$), scope) }); err != nil { return err }\n", args)
args = argsFromType(peerType, t).With("Scope", types.Ref(conversionPackagePath, "Scope"))
if _, found := g.preexists(t, peerType); !found {
args := argsFromType(t, peerType).With("Scope", types.Ref(conversionPackagePath, "Scope"))
sw.Do("if err := s.AddGeneratedConversionFunc((*$.inType|raw$)(nil), (*$.outType|raw$)(nil), func(a, b interface{}, scope $.Scope|raw$) error { return "+nameTmpl+"(a.(*$.inType|raw$), b.(*$.outType|raw$), scope) }); err != nil { return err }\n", args)
}
if _, found := g.preexists(peerType, t); !found {
args := argsFromType(peerType, t).With("Scope", types.Ref(conversionPackagePath, "Scope"))
sw.Do("if err := s.AddGeneratedConversionFunc((*$.inType|raw$)(nil), (*$.outType|raw$)(nil), func(a, b interface{}, scope $.Scope|raw$) error { return "+nameTmpl+"(a.(*$.inType|raw$), b.(*$.outType|raw$), scope) }); err != nil { return err }\n", args)
}
}
for i := range g.explicitConversions {
args := argsFromType(g.explicitConversions[i].inType, g.explicitConversions[i].outType).With("Scope", types.Ref(conversionPackagePath, "Scope"))
sw.Do("if err := s.AddGeneratedConversionFunc((*$.inType|raw$)(nil), (*$.outType|raw$)(nil), func(a, b interface{}, scope $.Scope|raw$) error { return "+nameTmpl+"(a.(*$.inType|raw$), b.(*$.outType|raw$), scope) }); err != nil { return err }\n", args)
}
var pairs []conversionPair
for pair, t := range g.manualConversions {
if t.Name.Package != g.outputPackage {
@ -644,10 +710,32 @@ func (g *genConversion) Init(c *generator.Context, w io.Writer) error {
func (g *genConversion) GenerateType(c *generator.Context, t *types.Type, w io.Writer) error {
klog.V(5).Infof("generating for type %v", t)
peerType := getPeerTypeFor(c, t, g.peerPackages)
sw := generator.NewSnippetWriter(w, c, "$", "$")
g.generateConversion(t, peerType, sw)
g.generateConversion(peerType, t, sw)
if peerType := getPeerTypeFor(c, t, g.peerPackages); peerType != nil {
g.generateConversion(t, peerType, sw)
g.generateConversion(peerType, t, sw)
}
for _, inTypeName := range getExplicitFromTypes(t) {
inPkg, ok := c.Universe[inTypeName.Package]
if !ok {
klog.Errorf("Unrecognized package: %s", inTypeName.Package)
continue
}
inType, ok := inPkg.Types[inTypeName.Name]
if !ok {
klog.Errorf("Unrecognized type in package %s: %s", inTypeName.Package, inTypeName.Name)
continue
}
switch {
case inType.Name.Package == "net/url" && inType.Name.Name == "Values":
g.generateFromUrlValues(inType, t, sw)
default:
klog.Errorf("Not supported input type: %#v", inType.Name)
}
}
return sw.Error()
}
@ -729,21 +817,27 @@ func (g *genConversion) doMap(inType, outType *types.Type, sw *generator.Snippet
sw.Do("$.|raw$(val)\n", outType.Elem)
}
} else {
sw.Do("newVal := new($.|raw$)\n", outType.Elem)
conversionExists := true
if function, ok := g.preexists(inType.Elem, outType.Elem); ok {
sw.Do("newVal := new($.|raw$)\n", outType.Elem)
sw.Do("if err := $.|raw$(&val, newVal, s); err != nil {\n", function)
} else if g.convertibleOnlyWithinPackage(inType.Elem, outType.Elem) {
sw.Do("newVal := new($.|raw$)\n", outType.Elem)
sw.Do("if err := "+nameTmpl+"(&val, newVal, s); err != nil {\n", argsFromType(inType.Elem, outType.Elem))
} else {
sw.Do("// TODO: Inefficient conversion - can we improve it?\n", nil)
sw.Do("if err := s.Convert(&val, newVal, 0); err != nil {\n", nil)
args := argsFromType(inType.Elem, outType.Elem)
sw.Do("// FIXME: Provide conversion function to convert $.inType|raw$ to $.outType|raw$\n", args)
sw.Do("compileErrorOnMissingConversion()\n", nil)
conversionExists = false
}
sw.Do("return err\n", nil)
sw.Do("}\n", nil)
if inType.Key == outType.Key {
sw.Do("(*out)[key] = *newVal\n", nil)
} else {
sw.Do("(*out)[$.|raw$(key)] = *newVal\n", outType.Key)
if conversionExists {
sw.Do("return err\n", nil)
sw.Do("}\n", nil)
if inType.Key == outType.Key {
sw.Do("(*out)[key] = *newVal\n", nil)
} else {
sw.Do("(*out)[$.|raw$(key)] = *newVal\n", outType.Key)
}
}
}
} else {
@ -767,21 +861,21 @@ func (g *genConversion) doSlice(inType, outType *types.Type, sw *generator.Snipp
sw.Do("(*out)[i] = $.|raw$((*in)[i])\n", outType.Elem)
}
} else {
conversionExists := true
if function, ok := g.preexists(inType.Elem, outType.Elem); ok {
sw.Do("if err := $.|raw$(&(*in)[i], &(*out)[i], s); err != nil {\n", function)
} else if g.convertibleOnlyWithinPackage(inType.Elem, outType.Elem) {
sw.Do("if err := "+nameTmpl+"(&(*in)[i], &(*out)[i], s); err != nil {\n", argsFromType(inType.Elem, outType.Elem))
} else {
// TODO: This triggers on metav1.ObjectMeta <-> metav1.ObjectMeta and
// similar because neither package is the target package, and
// we really don't know which package will have the conversion
// function defined. This fires on basically every object
// conversion outside of pkg/api/v1.
sw.Do("// TODO: Inefficient conversion - can we improve it?\n", nil)
sw.Do("if err := s.Convert(&(*in)[i], &(*out)[i], 0); err != nil {\n", nil)
args := argsFromType(inType.Elem, outType.Elem)
sw.Do("// FIXME: Provide conversion function to convert $.inType|raw$ to $.outType|raw$\n", args)
sw.Do("compileErrorOnMissingConversion()\n", nil)
conversionExists = false
}
if conversionExists {
sw.Do("return err\n", nil)
sw.Do("}\n", nil)
}
sw.Do("return err\n", nil)
sw.Do("}\n", nil)
}
sw.Do("}\n", nil)
}
@ -888,14 +982,19 @@ func (g *genConversion) doStruct(inType, outType *types.Type, sw *generator.Snip
sw.Do("out.$.name$ = in.$.name$\n", args)
continue
}
conversionExists := true
if g.convertibleOnlyWithinPackage(inMemberType, outMemberType) {
sw.Do("if err := "+nameTmpl+"(&in.$.name$, &out.$.name$, s); err != nil {\n", args)
} else {
sw.Do("// TODO: Inefficient conversion - can we improve it?\n", nil)
sw.Do("if err := s.Convert(&in.$.name$, &out.$.name$, 0); err != nil {\n", args)
args := argsFromType(inMemberType, outMemberType)
sw.Do("// FIXME: Provide conversion function to convert $.inType|raw$ to $.outType|raw$\n", args)
sw.Do("compileErrorOnMissingConversion()\n", nil)
conversionExists = false
}
if conversionExists {
sw.Do("return err\n", nil)
sw.Do("}\n", nil)
}
sw.Do("return err\n", nil)
sw.Do("}\n", nil)
case types.Alias:
if isDirectlyAssignable(inMemberType, outMemberType) {
if inMemberType == outMemberType {
@ -904,24 +1003,34 @@ func (g *genConversion) doStruct(inType, outType *types.Type, sw *generator.Snip
sw.Do("out.$.name$ = $.outType|raw$(in.$.name$)\n", args)
}
} else {
conversionExists := true
if g.convertibleOnlyWithinPackage(inMemberType, outMemberType) {
sw.Do("if err := "+nameTmpl+"(&in.$.name$, &out.$.name$, s); err != nil {\n", args)
} else {
sw.Do("// TODO: Inefficient conversion - can we improve it?\n", nil)
sw.Do("if err := s.Convert(&in.$.name$, &out.$.name$, 0); err != nil {\n", args)
args := argsFromType(inMemberType, outMemberType)
sw.Do("// FIXME: Provide conversion function to convert $.inType|raw$ to $.outType|raw$\n", args)
sw.Do("compileErrorOnMissingConversion()\n", nil)
conversionExists = false
}
if conversionExists {
sw.Do("return err\n", nil)
sw.Do("}\n", nil)
}
sw.Do("return err\n", nil)
sw.Do("}\n", nil)
}
default:
conversionExists := true
if g.convertibleOnlyWithinPackage(inMemberType, outMemberType) {
sw.Do("if err := "+nameTmpl+"(&in.$.name$, &out.$.name$, s); err != nil {\n", args)
} else {
sw.Do("// TODO: Inefficient conversion - can we improve it?\n", nil)
sw.Do("if err := s.Convert(&in.$.name$, &out.$.name$, 0); err != nil {\n", args)
args := argsFromType(inMemberType, outMemberType)
sw.Do("// FIXME: Provide conversion function to convert $.inType|raw$ to $.outType|raw$\n", args)
sw.Do("compileErrorOnMissingConversion()\n", nil)
conversionExists = false
}
if conversionExists {
sw.Do("return err\n", nil)
sw.Do("}\n", nil)
}
sw.Do("return err\n", nil)
sw.Do("}\n", nil)
}
}
}
@ -950,16 +1059,21 @@ func (g *genConversion) doPointer(inType, outType *types.Type, sw *generator.Sni
sw.Do("**out = $.|raw$(**in)\n", outType.Elem)
}
} else {
conversionExists := true
if function, ok := g.preexists(inType.Elem, outType.Elem); ok {
sw.Do("if err := $.|raw$(*in, *out, s); err != nil {\n", function)
} else if g.convertibleOnlyWithinPackage(inType.Elem, outType.Elem) {
sw.Do("if err := "+nameTmpl+"(*in, *out, s); err != nil {\n", argsFromType(inType.Elem, outType.Elem))
} else {
sw.Do("// TODO: Inefficient conversion - can we improve it?\n", nil)
sw.Do("if err := s.Convert(*in, *out, 0); err != nil {\n", nil)
args := argsFromType(inType.Elem, outType.Elem)
sw.Do("// FIXME: Provide conversion function to convert $.inType|raw$ to $.outType|raw$\n", args)
sw.Do("compileErrorOnMissingConversion()\n", nil)
conversionExists = false
}
if conversionExists {
sw.Do("return err\n", nil)
sw.Do("}\n", nil)
}
sw.Do("return err\n", nil)
sw.Do("}\n", nil)
}
}
@ -972,6 +1086,129 @@ func (g *genConversion) doUnknown(inType, outType *types.Type, sw *generator.Sni
sw.Do("// FIXME: Type $.|raw$ is unsupported.\n", inType)
}
func (g *genConversion) generateFromUrlValues(inType, outType *types.Type, sw *generator.SnippetWriter) {
args := generator.Args{
"inType": inType,
"outType": outType,
"Scope": types.Ref(conversionPackagePath, "Scope"),
}
sw.Do("func auto"+nameTmpl+"(in *$.inType|raw$, out *$.outType|raw$, s $.Scope|raw$) error {\n", args)
for _, outMember := range outType.Members {
if tagvals := extractTag(outMember.CommentLines); tagvals != nil && tagvals[0] == "false" {
// This field is excluded from conversion.
sw.Do("// INFO: in."+outMember.Name+" opted out of conversion generation\n", nil)
continue
}
jsonTag := reflect.StructTag(outMember.Tags).Get("json")
index := strings.Index(jsonTag, ",")
if index == -1 {
index = len(jsonTag)
}
if index == 0 {
memberArgs := generator.Args{
"name": outMember.Name,
}
sw.Do("// WARNING: Field $.name$ does not have json tag, skipping.\n\n", memberArgs)
continue
}
memberArgs := generator.Args{
"name": outMember.Name,
"tag": jsonTag[:index],
}
sw.Do("if values, ok := map[string][]string(*in)[\"$.tag$\"]; ok && len(values) > 0 {\n", memberArgs)
g.fromValuesEntry(inType.Underlying.Elem, outMember, sw)
sw.Do("} else {\n", nil)
g.setZeroValue(outMember, sw)
sw.Do("}\n", nil)
}
sw.Do("return nil\n", nil)
sw.Do("}\n\n", nil)
if _, found := g.preexists(inType, outType); found {
// There is a public manual Conversion method: use it.
} else {
// Emit a public conversion function.
sw.Do("// "+nameTmpl+" is an autogenerated conversion function.\n", args)
sw.Do("func "+nameTmpl+"(in *$.inType|raw$, out *$.outType|raw$, s $.Scope|raw$) error {\n", args)
sw.Do("return auto"+nameTmpl+"(in, out, s)\n", args)
sw.Do("}\n\n", nil)
}
}
func (g *genConversion) fromValuesEntry(inType *types.Type, outMember types.Member, sw *generator.SnippetWriter) {
memberArgs := generator.Args{
"name": outMember.Name,
"type": outMember.Type,
}
if function, ok := g.preexists(inType, outMember.Type); ok {
args := memberArgs.With("function", function)
sw.Do("if err := $.function|raw$(&values, &out.$.name$, s); err != nil {\n", args)
sw.Do("return err\n", nil)
sw.Do("}\n", nil)
return
}
switch {
case outMember.Type == types.String:
sw.Do("out.$.name$ = values[0]\n", memberArgs)
case g.useUnsafe.Equal(inType, outMember.Type):
args := memberArgs.With("Pointer", types.Ref("unsafe", "Pointer"))
switch inType.Kind {
case types.Pointer:
sw.Do("out.$.name$ = ($.type|raw$)($.Pointer|raw$(&values))\n", args)
case types.Map, types.Slice:
sw.Do("out.$.name$ = *(*$.type|raw$)($.Pointer|raw$(&values))\n", args)
default:
// TODO: Support other types to allow more auto-conversions.
sw.Do("// FIXME: out.$.name$ is of not yet supported type and requires manual conversion\n", memberArgs)
}
default:
// TODO: Support other types to allow more auto-conversions.
sw.Do("// FIXME: out.$.name$ is of not yet supported type and requires manual conversion\n", memberArgs)
}
}
func (g *genConversion) setZeroValue(outMember types.Member, sw *generator.SnippetWriter) {
outMemberType := unwrapAlias(outMember.Type)
memberArgs := generator.Args{
"name": outMember.Name,
"alias": outMember.Type,
"type": outMemberType,
}
switch outMemberType.Kind {
case types.Builtin:
switch outMemberType {
case types.String:
sw.Do("out.$.name$ = \"\"\n", memberArgs)
case types.Int64, types.Int32, types.Int16, types.Int, types.Uint64, types.Uint32, types.Uint16, types.Uint:
sw.Do("out.$.name$ = 0\n", memberArgs)
case types.Uintptr, types.Byte:
sw.Do("out.$.name$ = 0\n", memberArgs)
case types.Float64, types.Float32, types.Float:
sw.Do("out.$.name$ = 0\n", memberArgs)
case types.Bool:
sw.Do("out.$.name$ = false\n", memberArgs)
default:
sw.Do("// FIXME: out.$.name$ is of unsupported type and requires manual conversion\n", memberArgs)
}
case types.Struct:
if outMemberType == outMember.Type {
sw.Do("out.$.name$ = $.type|raw${}\n", memberArgs)
} else {
sw.Do("out.$.name$ = $.alias|raw$($.type|raw${})\n", memberArgs)
}
case types.Map, types.Slice, types.Pointer:
sw.Do("out.$.name$ = nil\n", memberArgs)
case types.Alias:
// outMemberType was already unwrapped from aliases - so that should never happen.
sw.Do("// FIXME: unexpected error for out.$.name$\n", memberArgs)
case types.Interface, types.Array:
sw.Do("out.$.name$ = nil\n", memberArgs)
default:
sw.Do("// FIXME: out.$.name$ is of unsupported type and requires manual conversion\n", memberArgs)
}
}
func isDirectlyAssignable(inType, outType *types.Type) bool {
// TODO: This should maybe check for actual assignability between the two
// types, rather than superficial traits that happen to indicate it is

View file

@ -30,21 +30,33 @@ limitations under the License.
// ones named
// autoConvert_<pkg1>_<type>_To_<pkg2>_<type>
// for each such pair of types --- both with (pkg1,pkg2) =
// (internal,external) and (pkg1,pkg2) = (external,internal).
// Additionally: if the destination package does not contain one in a
// non-generated file then a function named
// (internal,external) and (pkg1,pkg2) = (external,internal). The
// generated conversion functions recurse on the structure of the data
// types. For structs, source and destination fields are matched up
// according to name; if a source field has no corresponding
// destination or there is a fundamental mismatch in the type of the
// field then the generated autoConvert_... function has just a
// warning comment about that field. The generated conversion
// functions use standard value assignment wherever possible. For
// compound types, the generated conversion functions call the
// `Convert...` functions for the subsidiary types.
//
// For each pair of types `conversion-gen` will also generate a
// function named
// Convert_<pkg1>_<type>_To_<pkg2>_<type>
// is also generated and it simply calls the `autoConvert...`
// function. The generated conversion functions use standard value
// assignment wherever possible. For compound types, the generated
// conversion functions call the `Convert...` functions for the
// subsidiary types. Thus developers can override the behavior for
// selected types. For a top-level object type (i.e., the type of an
// object that will be input to an apiserver), for such an override to
// be used by the apiserver the developer-maintained conversion
// functions must also be registered by invoking the
// `AddConversionFuncs` method of the relevant `Scheme` object from
// k8s.io/apimachinery/pkg/runtime.
// if both of two conditions are met: (1) the destination package does
// not contain a function of that name in a non-generated file and (2)
// the generation of the corresponding autoConvert_... function did
// not run into trouble with a missing or fundamentally differently
// typed field. A generated Convert_... function simply calls the
// corresponding `autoConvert...` function. `conversion_gen` also
// generates a function that updates a given `runtime.Scheme` by
// registering all the Convert_... functions found and generated.
// Thus developers can override the generated behavior for selected
// type pairs by putting the desired Convert_... functions in
// non-generated files. Further, developers are practically required
// to override the generated behavior when there are missing or
// fundamentally differently typed fields.
//
// `conversion-gen` will scan its `--input-dirs`, looking at the
// package defined in each of those directories for comment tags that
@ -79,7 +91,7 @@ import (
"github.com/spf13/pflag"
"k8s.io/gengo/args"
"k8s.io/klog"
"k8s.io/klog/v2"
generatorargs "k8s.io/code-generator/cmd/conversion-gen/args"
"k8s.io/code-generator/cmd/conversion-gen/generators"
@ -100,6 +112,15 @@ func main() {
pflag.CommandLine.AddGoFlagSet(flag.CommandLine)
pflag.Parse()
// k8s.io/apimachinery/pkg/runtime contains a number of manual conversions,
// that we need to generate conversions.
// Packages being dependencies of explicitly requested packages are only
// partially scanned - only types explicitly used are being traversed.
// Not used functions or types are omitted.
// Adding this explicitly to InputDirs ensures that the package is fully
// scanned and all functions are parsed and processed.
genericArgs.InputDirs = append(genericArgs.InputDirs, "k8s.io/apimachinery/pkg/runtime")
if err := generatorargs.Validate(genericArgs); err != nil {
klog.Fatalf("Error: %v", err)
}

View file

@ -49,7 +49,7 @@ import (
"github.com/spf13/pflag"
"k8s.io/gengo/args"
"k8s.io/gengo/examples/deepcopy-gen/generators"
"k8s.io/klog"
"k8s.io/klog/v2"
generatorargs "k8s.io/code-generator/cmd/deepcopy-gen/args"
"k8s.io/code-generator/pkg/util"

View file

@ -48,7 +48,7 @@ import (
"github.com/spf13/pflag"
"k8s.io/gengo/args"
"k8s.io/gengo/examples/defaulter-gen/generators"
"k8s.io/klog"
"k8s.io/klog/v2"
generatorargs "k8s.io/code-generator/cmd/defaulter-gen/args"
"k8s.io/code-generator/pkg/util"

View file

@ -29,9 +29,6 @@ import (
"strings"
flag "github.com/spf13/pflag"
"gonum.org/v1/gonum/graph"
"gonum.org/v1/gonum/graph/simple"
"gonum.org/v1/gonum/graph/topo"
"k8s.io/code-generator/pkg/util"
"k8s.io/gengo/args"
@ -279,7 +276,7 @@ func Run(g *Generator) {
cmd := exec.Command("protoc", append(args, path)...)
out, err := cmd.CombinedOutput()
if len(out) > 0 {
log.Printf(string(out))
log.Print(string(out))
}
if err != nil {
log.Println(strings.Join(cmd.Args, " "))
@ -300,7 +297,7 @@ func Run(g *Generator) {
cmd = exec.Command("goimports", "-w", outputPath)
out, err = cmd.CombinedOutput()
if len(out) > 0 {
log.Printf(string(out))
log.Print(string(out))
}
if err != nil {
log.Println(strings.Join(cmd.Args, " "))
@ -311,7 +308,7 @@ func Run(g *Generator) {
cmd = exec.Command("gofmt", "-s", "-w", outputPath)
out, err = cmd.CombinedOutput()
if len(out) > 0 {
log.Printf(string(out))
log.Print(string(out))
}
if err != nil {
log.Println(strings.Join(cmd.Args, " "))
@ -374,38 +371,73 @@ func deps(c *generator.Context, pkgs []*protobufPackage) map[string][]string {
return ret
}
// given a set of pkg->[]deps, return the order that ensures all deps are processed before the things that depend on them
func importOrder(deps map[string][]string) ([]string, error) {
nodes := map[string]graph.Node{}
names := map[int64]string{}
g := simple.NewDirectedGraph()
for pkg, imports := range deps {
for _, imp := range imports {
if _, found := nodes[pkg]; !found {
n := g.NewNode()
g.AddNode(n)
nodes[pkg] = n
names[n.ID()] = pkg
}
if _, found := nodes[imp]; !found {
n := g.NewNode()
g.AddNode(n)
nodes[imp] = n
names[n.ID()] = imp
}
g.SetEdge(g.NewEdge(nodes[imp], nodes[pkg]))
// add all nodes and edges
var remainingNodes = map[string]struct{}{}
var graph = map[edge]struct{}{}
for to, froms := range deps {
remainingNodes[to] = struct{}{}
for _, from := range froms {
remainingNodes[from] = struct{}{}
graph[edge{from: from, to: to}] = struct{}{}
}
}
ret := []string{}
sorted, err := topo.Sort(g)
if err != nil {
return nil, err
// find initial nodes without any dependencies
sorted := findAndRemoveNodesWithoutDependencies(remainingNodes, graph)
for i := 0; i < len(sorted); i++ {
node := sorted[i]
removeEdgesFrom(node, graph)
sorted = append(sorted, findAndRemoveNodesWithoutDependencies(remainingNodes, graph)...)
}
if len(remainingNodes) > 0 {
return nil, fmt.Errorf("cycle: remaining nodes: %#v, remaining edges: %#v", remainingNodes, graph)
}
for _, n := range sorted {
ret = append(ret, names[n.ID()])
fmt.Println("topological order", names[n.ID()])
fmt.Println("topological order", n)
}
return sorted, nil
}
// edge describes a from->to relationship in a graph
type edge struct {
from string
to string
}
// findAndRemoveNodesWithoutDependencies finds nodes in the given set which are not pointed to by any edges in the graph,
// removes them from the set of nodes, and returns them in sorted order
func findAndRemoveNodesWithoutDependencies(nodes map[string]struct{}, graph map[edge]struct{}) []string {
roots := []string{}
// iterate over all nodes as potential "to" nodes
for node := range nodes {
incoming := false
// iterate over all remaining edges
for edge := range graph {
// if there's any edge to the node we care about, it's not a root
if edge.to == node {
incoming = true
break
}
}
// if there are no incoming edges, remove from the set of remaining nodes and add to our results
if !incoming {
delete(nodes, node)
roots = append(roots, node)
}
}
sort.Strings(roots)
return roots
}
// removeEdgesFrom removes any edges from the graph where edge.from == node
func removeEdgesFrom(node string, graph map[edge]struct{}) {
for edge := range graph {
if edge.from == node {
delete(graph, edge)
}
}
return ret, nil
}
type positionOrder struct {

View file

@ -25,7 +25,7 @@ import (
"strconv"
"strings"
"k8s.io/klog"
"k8s.io/klog/v2"
"k8s.io/gengo/generator"
"k8s.io/gengo/namer"
@ -371,7 +371,7 @@ func (b bodyGen) doStruct(sw *generator.SnippetWriter) error {
`, b.t)
if len(options) > 0 {
sort.Sort(sort.StringSlice(options))
sort.Strings(options)
for _, s := range options {
fmt.Fprintf(out, " option %s;\n", s)
}
@ -399,7 +399,7 @@ func (b bodyGen) doStruct(sw *generator.SnippetWriter) error {
}
extras = append(extras, fmt.Sprintf("%s = %s", k, v))
}
sort.Sort(sort.StringSlice(extras))
sort.Strings(extras)
if len(extras) > 0 {
fmt.Fprintf(out, " [")
fmt.Fprint(out, strings.Join(extras, ", "))
@ -740,7 +740,7 @@ func formatProtoFile(source []byte) ([]byte, error) {
func assembleProtoFile(w io.Writer, f *generator.File) {
w.Write(f.Header)
fmt.Fprint(w, "syntax = 'proto2';\n\n")
fmt.Fprint(w, "syntax = \"proto2\";\n\n")
if len(f.PackageName) > 0 {
fmt.Fprintf(w, "package %s;\n\n", f.PackageName)

View file

@ -132,7 +132,7 @@ func rewriteOptionalMethods(decl ast.Decl, isOptional OptionalFunc) {
switch t.Name.Name {
case "Unmarshal":
ast.Walk(&optionalItemsVisitor{}, t.Body)
case "MarshalTo", "Size", "String":
case "MarshalTo", "Size", "String", "MarshalToSizedBuffer":
ast.Walk(&optionalItemsVisitor{}, t.Body)
fallthrough
case "Marshal":
@ -375,6 +375,21 @@ func RewriteTypesWithProtobufStructTags(name string, structTags map[string]map[s
})
}
func getFieldName(expr ast.Expr, structname string) (name string, err error) {
for {
switch t := expr.(type) {
case *ast.Ident:
return t.Name, nil
case *ast.SelectorExpr:
return t.Sel.Name, nil
case *ast.StarExpr:
expr = t.X
default:
return "", fmt.Errorf("unable to get name for tag from struct %q, field %#v", structname, t)
}
}
}
func updateStructTags(decl ast.Decl, structTags map[string]map[string]string, toCopy []string) []error {
var errs []error
t, ok := decl.(*ast.GenDecl)
@ -403,14 +418,11 @@ func updateStructTags(decl ast.Decl, structTags map[string]map[string]string, to
for i := range st.Fields.List {
f := st.Fields.List[i]
var name string
var err error
if len(f.Names) == 0 {
switch t := f.Type.(type) {
case *ast.Ident:
name = t.Name
case *ast.SelectorExpr:
name = t.Sel.Name
default:
errs = append(errs, fmt.Errorf("unable to get name for tag from struct %q, field %#v", spec.Name.Name, t))
name, err = getFieldName(f.Type, spec.Name.Name)
if err != nil {
errs = append(errs, err)
continue
}
} else {

View file

@ -18,7 +18,7 @@ package protobuf
import (
"k8s.io/gengo/types"
"k8s.io/klog"
"k8s.io/klog/v2"
)
// extractBoolTagOrDie gets the comment-tags for the key and asserts that, if

97
vendor/k8s.io/code-generator/cmd/import-boss/README.md generated vendored Normal file
View file

@ -0,0 +1,97 @@
## Purpose
- `import-boss` enforces import restrictions against all pull requests submitted to the [k/k](https://github.com/kubernetes/kubernetes) repository. There are a number of `.import-restrictions` files that in the [k/k](https://github.com/kubernetes/kubernetes) repository, all of which are defined in `YAML` (or `JSON`) format.
## How does it work?
- When a directory is verified, `import-boss` looks for a file called `.import-restrictions`. If this file is not found, `import-boss` will go up to the parent directory until it finds this `.import-restrictions` file.
- Adding `.import-restrictions` files does not add them to CI runs. They need to be explicitly added to `hack/verify-import-boss.sh`. Once an `.import-restrictions` file is added, all of the sub-packages of this file's directory are added as well.
### What are Rules?
- If an `.import-restrictions` file is found, then all imports of the package are checked against each `rule` in the file. A `rule` consists of three parts:
- A `SelectorRegexp`, to select the import paths that the rule applies to.
- A list of `AllowedPrefixes`
- A list of `ForbiddenPrefixes`
- An import is allowed if it matches at least one allowed prefix and does not match any forbidden prefixes. An example `.import-restrictions` file looks like this:
```json
{
"Rules": [
{
"SelectorRegexp": "k8s[.]io",
"AllowedPrefixes": [
"k8s.io/gengo/examples",
"k8s.io/kubernetes/third_party"
],
"ForbiddenPrefixes": [
"k8s.io/kubernetes/pkg/third_party/deprecated"
]
},
{
"SelectorRegexp": "^unsafe$",
"AllowedPrefixes": [
],
"ForbiddenPrefixes": [
""
]
}
]
}
```
- Take note of `"SelectorRegexp": "k8s[.]io"` in the first block. This specifies that we are applying these rules to the `"k8s.io"` import path.
- The second block explicitly matches the "unsafe" package, and forbids it ("" is a prefix of everything).
### What are Inverse Rules?
- In contrast to non-inverse rules, which are defined in importing packages, inverse rules are defined in imported packages.
- Inverse rules allow for fine-grained import restrictions for "private packages" where we don't want to spread use inside of [kubernetes/kubernetes](https://github.com/kubernetes/kubernetes).
- If an `.import-restrictions` file is found, then all imports of the package are checked against each `inverse rule` in the file. This check will continue, climbing up the directory tree, until a match is found and accepted.
- Inverse rules also have a boolean `transitive` option. When this option is true, the import rule is also applied to `transitive` imports.
- `transitive` imports are dependencies not directly depended on by the code, but are needed to run the application. Use this option if you want to apply restrictions to those indirect dependencies.
```yaml
rules:
- selectorRegexp: k8s[.]io
allowedPrefixes:
- k8s.io/gengo/examples
- k8s.io/kubernetes/third_party
forbiddenPrefixes:
- k8s.io/kubernetes/pkg/third_party/deprecated
- selectorRegexp: ^unsafe$
forbiddenPrefixes:
- ""
inverseRules:
- selectorRegexp: k8s[.]io
allowedPrefixes:
- k8s.io/same-repo
- k8s.io/kubernetes/pkg/legacy
forbiddenPrefixes:
- k8s.io/kubernetes/pkg/legacy/subpkg
- selectorRegexp: k8s[.]io
transitive: true
forbiddenPrefixes:
- k8s.io/kubernetes/cmd/kubelet
- k8s.io/kubernetes/cmd/kubectl
```
## How do I run import-boss within the k/k repo?
- In order to include _test.go files, make sure to pass in the `include-test-files` flag:
```sh
hack/verify-import-boss.sh --include-test-files=true
```
- To include other directories, pass in a directory or directories using the `input-dirs` flag:
```sh
hack/verify-import-boss.sh --input-dirs="k8s.io/kubernetes/test/e2e/framework/..."
```
## Reference
- [import-boss](https://github.com/kubernetes/gengo/tree/master/examples/import-boss)

View file

@ -15,59 +15,18 @@ limitations under the License.
*/
// import-boss enforces import restrictions in a given repository.
//
// When a directory is verified, import-boss looks for a file called
// ".import-restrictions". If this file is not found, parent directories will be
// recursively searched.
//
// If an ".import-restrictions" file is found, then all imports of the package
// are checked against each "rule" in the file. A rule consists of three parts:
//
// - A SelectorRegexp, to select the import paths that the rule applies to.
//
// - A list of AllowedPrefixes
//
// - A list of ForbiddenPrefixes
//
// An import is allowed if it matches at least one allowed prefix and does not
// match any forbidden prefix. An example file looks like this:
//
// {
// "Rules": [
// {
// "SelectorRegexp": "k8s[.]io",
// "AllowedPrefixes": [
// "k8s.io/gengo/examples",
// "k8s.io/kubernetes/third_party"
// ],
// "ForbiddenPrefixes": [
// "k8s.io/kubernetes/pkg/third_party/deprecated"
// ]
// },
// {
// "SelectorRegexp": "^unsafe$",
// "AllowedPrefixes": [
// ],
// "ForbiddenPrefixes": [
// ""
// ]
// }
// ]
// }
//
// Note the second block explicitly matches the unsafe package, and forbids it
// ("" is a prefix of everything).
package main
import (
"os"
"path/filepath"
"github.com/spf13/pflag"
"k8s.io/code-generator/pkg/util"
"k8s.io/gengo/args"
"k8s.io/gengo/examples/import-boss/generators"
"k8s.io/klog"
"k8s.io/klog/v2"
)
func main() {
@ -76,11 +35,7 @@ func main() {
// Override defaults.
arguments.GoHeaderFilePath = filepath.Join(args.DefaultSourceTree(), util.BoilerplatePath())
arguments.InputDirs = []string{
"k8s.io/kubernetes/pkg/...",
"k8s.io/kubernetes/cmd/...",
"k8s.io/kubernetes/plugin/...",
}
pflag.CommandLine.BoolVar(&arguments.IncludeTestFiles, "include-test-files", false, "If true, include *_test.go files.")
if err := arguments.Execute(
generators.NameSystems(),

View file

@ -31,13 +31,18 @@ type CustomArgs struct {
InternalClientSetPackage string
ListersPackage string
SingleDirectory bool
// PluralExceptions define a list of pluralizer exceptions in Type:PluralType format.
// The default list is "Endpoints:Endpoints"
PluralExceptions []string
}
// NewDefaults returns default arguments for the generator.
func NewDefaults() (*args.GeneratorArgs, *CustomArgs) {
genericArgs := args.Default().WithoutDefaultFlagParsing()
customArgs := &CustomArgs{
SingleDirectory: false,
SingleDirectory: false,
PluralExceptions: []string{"Endpoints:Endpoints"},
}
genericArgs.CustomArgs = customArgs
@ -57,6 +62,7 @@ func (ca *CustomArgs) AddFlags(fs *pflag.FlagSet) {
fs.StringVar(&ca.VersionedClientSetPackage, "versioned-clientset-package", ca.VersionedClientSetPackage, "the full package name for the versioned clientset to use")
fs.StringVar(&ca.ListersPackage, "listers-package", ca.ListersPackage, "the full package name for the listers to use")
fs.BoolVar(&ca.SingleDirectory, "single-directory", ca.SingleDirectory, "if true, omit the intermediate \"internalversion\" and \"externalversions\" subdirectories")
fs.StringSliceVar(&ca.PluralExceptions, "plural-exceptions", ca.PluralExceptions, "list of comma separated plural exception definitions in Type:PluralizedType format")
}
// Validate checks the given arguments.

View file

@ -25,7 +25,7 @@ import (
"k8s.io/gengo/namer"
"k8s.io/gengo/types"
"k8s.io/klog"
"k8s.io/klog/v2"
)
// factoryGenerator produces a file of listers for a given GroupVersion and

View file

@ -23,7 +23,7 @@ import (
"k8s.io/gengo/namer"
"k8s.io/gengo/types"
"k8s.io/klog"
"k8s.io/klog/v2"
)
// factoryInterfaceGenerator produces a file of interfaces used to break a dependency cycle for

View file

@ -35,6 +35,7 @@ type genericGenerator struct {
imports namer.ImportTracker
groupVersions map[string]clientgentypes.GroupVersions
groupGoNames map[string]string
pluralExceptions map[string]string
typesForGroupVersion map[clientgentypes.GroupVersion][]*types.Type
filtered bool
}
@ -50,14 +51,11 @@ func (g *genericGenerator) Filter(c *generator.Context, t *types.Type) bool {
}
func (g *genericGenerator) Namers(c *generator.Context) namer.NameSystems {
pluralExceptions := map[string]string{
"Endpoints": "Endpoints",
}
return namer.NameSystems{
"raw": namer.NewRawNamer(g.outputPackage, g.imports),
"allLowercasePlural": namer.NewAllLowercasePluralNamer(pluralExceptions),
"publicPlural": namer.NewPublicPluralNamer(pluralExceptions),
"resource": codegennamer.NewTagOverrideNamer("resourceName", namer.NewAllLowercasePluralNamer(pluralExceptions)),
"allLowercasePlural": namer.NewAllLowercasePluralNamer(g.pluralExceptions),
"publicPlural": namer.NewPublicPluralNamer(g.pluralExceptions),
"resource": codegennamer.NewTagOverrideNamer("resourceName", namer.NewAllLowercasePluralNamer(g.pluralExceptions)),
}
}
@ -75,9 +73,11 @@ type group struct {
type groupSort []group
func (g groupSort) Len() int { return len(g) }
func (g groupSort) Less(i, j int) bool { return strings.ToLower(g[i].Name) < strings.ToLower(g[j].Name) }
func (g groupSort) Swap(i, j int) { g[i], g[j] = g[j], g[i] }
func (g groupSort) Len() int { return len(g) }
func (g groupSort) Less(i, j int) bool {
return strings.ToLower(g[i].Name) < strings.ToLower(g[j].Name)
}
func (g groupSort) Swap(i, j int) { g[i], g[j] = g[j], g[i] }
type version struct {
Name string

View file

@ -28,7 +28,7 @@ import (
"k8s.io/code-generator/cmd/client-gen/generators/util"
clientgentypes "k8s.io/code-generator/cmd/client-gen/types"
"k8s.io/klog"
"k8s.io/klog/v2"
)
// informerGenerator produces a file of listers for a given GroupVersion and
@ -151,13 +151,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(options)
return client.$.group$$.version$().$.type|publicPlural$($if .namespaced$namespace$end$).List(context.TODO(), 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(options)
return client.$.group$$.version$().$.type|publicPlural$($if .namespaced$namespace$end$).Watch(context.TODO(), options)
},
},
&$.type|raw${},

View file

@ -26,18 +26,16 @@ import (
"k8s.io/gengo/generator"
"k8s.io/gengo/namer"
"k8s.io/gengo/types"
"k8s.io/klog"
"k8s.io/klog/v2"
"k8s.io/code-generator/cmd/client-gen/generators/util"
clientgentypes "k8s.io/code-generator/cmd/client-gen/types"
informergenargs "k8s.io/code-generator/cmd/informer-gen/args"
genutil "k8s.io/code-generator/pkg/util"
)
// NameSystems returns the name system used by the generators in this package.
func NameSystems() namer.NameSystems {
pluralExceptions := map[string]string{
"Endpoints": "Endpoints",
}
func NameSystems(pluralExceptions map[string]string) namer.NameSystems {
return namer.NameSystems{
"public": namer.NewPublicNamer(0),
"private": namer.NewPrivateNamer(0),
@ -91,13 +89,6 @@ func packageForInternalInterfaces(base string) string {
return filepath.Join(base, "internalinterfaces")
}
func vendorless(p string) string {
if pos := strings.LastIndex(p, "/vendor/"); pos != -1 {
return p[pos+len("/vendor/"):]
}
return p
}
// Packages makes the client package definition.
func Packages(context *generator.Context, arguments *args.GeneratorArgs) generator.Packages {
boilerplate, err := arguments.LoadGoBoilerplate()
@ -124,7 +115,7 @@ func Packages(context *generator.Context, arguments *args.GeneratorArgs) generat
internalGroupVersions := make(map[string]clientgentypes.GroupVersions)
groupGoNames := make(map[string]string)
for _, inputDir := range arguments.InputDirs {
p := context.Universe.Package(vendorless(inputDir))
p := context.Universe.Package(genutil.Vendorless(inputDir))
objectMeta, internal, err := objectMetaForPackage(p)
if err != nil {
@ -208,7 +199,9 @@ func Packages(context *generator.Context, arguments *args.GeneratorArgs) generat
if len(externalGroupVersions) != 0 {
packageList = append(packageList, factoryInterfacePackage(externalVersionPackagePath, boilerplate, customArgs.VersionedClientSetPackage))
packageList = append(packageList, factoryPackage(externalVersionPackagePath, boilerplate, groupGoNames, externalGroupVersions, customArgs.VersionedClientSetPackage, typesForGroupVersion))
packageList = append(packageList, factoryPackage(externalVersionPackagePath, boilerplate, groupGoNames, genutil.PluralExceptionListToMapOrDie(customArgs.PluralExceptions), externalGroupVersions,
customArgs.VersionedClientSetPackage,
typesForGroupVersion))
for _, gvs := range externalGroupVersions {
packageList = append(packageList, groupPackage(externalVersionPackagePath, gvs, boilerplate))
}
@ -216,7 +209,7 @@ func Packages(context *generator.Context, arguments *args.GeneratorArgs) generat
if len(internalGroupVersions) != 0 {
packageList = append(packageList, factoryInterfacePackage(internalVersionPackagePath, boilerplate, customArgs.InternalClientSetPackage))
packageList = append(packageList, factoryPackage(internalVersionPackagePath, boilerplate, groupGoNames, internalGroupVersions, customArgs.InternalClientSetPackage, typesForGroupVersion))
packageList = append(packageList, factoryPackage(internalVersionPackagePath, boilerplate, groupGoNames, genutil.PluralExceptionListToMapOrDie(customArgs.PluralExceptions), internalGroupVersions, customArgs.InternalClientSetPackage, typesForGroupVersion))
for _, gvs := range internalGroupVersions {
packageList = append(packageList, groupPackage(internalVersionPackagePath, gvs, boilerplate))
}
@ -225,7 +218,8 @@ func Packages(context *generator.Context, arguments *args.GeneratorArgs) generat
return packageList
}
func factoryPackage(basePackage string, boilerplate []byte, groupGoNames map[string]string, groupVersions map[string]clientgentypes.GroupVersions, clientSetPackage string, typesForGroupVersion map[clientgentypes.GroupVersion][]*types.Type) generator.Package {
func factoryPackage(basePackage string, boilerplate []byte, groupGoNames, pluralExceptions map[string]string, groupVersions map[string]clientgentypes.GroupVersions, clientSetPackage string,
typesForGroupVersion map[clientgentypes.GroupVersion][]*types.Type) generator.Package {
return &generator.DefaultPackage{
PackageName: filepath.Base(basePackage),
PackagePath: basePackage,
@ -250,6 +244,7 @@ func factoryPackage(basePackage string, boilerplate []byte, groupGoNames map[str
outputPackage: basePackage,
imports: generator.NewImportTracker(),
groupVersions: groupVersions,
pluralExceptions: pluralExceptions,
typesForGroupVersion: typesForGroupVersion,
groupGoNames: groupGoNames,
})
@ -283,7 +278,7 @@ func factoryInterfacePackage(basePackage string, boilerplate []byte, clientSetPa
func groupPackage(basePackage string, groupVersions clientgentypes.GroupVersions, boilerplate []byte) generator.Package {
packagePath := filepath.Join(basePackage, groupVersions.PackageName)
groupPkgName := strings.Split(string(groupVersions.Group), ".")[0]
groupPkgName := strings.Split(string(groupVersions.PackageName), ".")[0]
return &generator.DefaultPackage{
PackageName: groupPkgName,

View file

@ -68,7 +68,7 @@ func (g *versionInterfaceGenerator) GenerateType(c *generator.Context, t *types.
sw.Do(versionTemplate, m)
for _, typeDef := range g.types {
tags, err := util.ParseClientGenTags(typeDef.SecondClosestCommentLines)
tags, err := util.ParseClientGenTags(append(typeDef.SecondClosestCommentLines, typeDef.CommentLines...))
if err != nil {
return err
}

View file

@ -24,7 +24,7 @@ import (
"k8s.io/code-generator/cmd/informer-gen/generators"
"k8s.io/code-generator/pkg/util"
"k8s.io/gengo/args"
"k8s.io/klog"
"k8s.io/klog/v2"
generatorargs "k8s.io/code-generator/cmd/informer-gen/args"
)
@ -53,7 +53,7 @@ func main() {
// Run it.
if err := genericArgs.Execute(
generators.NameSystems(),
generators.NameSystems(util.PluralExceptionListToMapOrDie(customArgs.PluralExceptions)),
generators.DefaultNameSystem(),
generators.Packages,
); err != nil {

View file

@ -1 +0,0 @@
{}

View file

@ -26,12 +26,18 @@ import (
)
// CustomArgs is used by the gengo framework to pass args specific to this generator.
type CustomArgs struct{}
type CustomArgs struct {
// PluralExceptions specify list of exceptions used when pluralizing certain types.
// For example 'Endpoints:Endpoints', otherwise the pluralizer will generate 'Endpointes'.
PluralExceptions []string
}
// NewDefaults returns default arguments for the generator.
func NewDefaults() (*args.GeneratorArgs, *CustomArgs) {
genericArgs := args.Default().WithoutDefaultFlagParsing()
customArgs := &CustomArgs{}
customArgs := &CustomArgs{
PluralExceptions: []string{"Endpoints:Endpoints"},
}
genericArgs.CustomArgs = customArgs
if pkg := codegenutil.CurrentPackage(); len(pkg) != 0 {
@ -42,7 +48,9 @@ func NewDefaults() (*args.GeneratorArgs, *CustomArgs) {
}
// AddFlags add the generator flags to the flag set.
func (ca *CustomArgs) AddFlags(fs *pflag.FlagSet) {}
func (ca *CustomArgs) AddFlags(fs *pflag.FlagSet) {
fs.StringSliceVar(&ca.PluralExceptions, "plural-exceptions", ca.PluralExceptions, "list of comma separated plural exception definitions in Type:PluralizedType format")
}
// Validate checks the given arguments.
func Validate(genericArgs *args.GeneratorArgs) error {

View file

@ -30,14 +30,11 @@ import (
"k8s.io/code-generator/cmd/client-gen/generators/util"
clientgentypes "k8s.io/code-generator/cmd/client-gen/types"
"k8s.io/klog"
"k8s.io/klog/v2"
)
// NameSystems returns the name system used by the generators in this package.
func NameSystems() namer.NameSystems {
pluralExceptions := map[string]string{
"Endpoints": "Endpoints",
}
func NameSystems(pluralExceptions map[string]string) namer.NameSystems {
return namer.NameSystems{
"public": namer.NewPublicNamer(0),
"private": namer.NewPrivateNamer(0),
@ -261,8 +258,10 @@ func (g *listerGenerator) GenerateType(c *generator.Context, t *types.Type, w io
var typeListerInterface = `
// $.type|public$Lister helps list $.type|publicPlural$.
// All objects returned here must be treated as read-only.
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)
// $.type|publicPlural$ returns an object that can list and get $.type|publicPlural$.
$.type|publicPlural$(namespace string) $.type|public$NamespaceLister
@ -272,10 +271,13 @@ type $.type|public$Lister interface {
var typeListerInterface_NonNamespaced = `
// $.type|public$Lister helps list $.type|publicPlural$.
// All objects returned here must be treated as read-only.
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)
// 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)
$.type|public$ListerExpansion
}
@ -328,10 +330,13 @@ func (s *$.type|private$Lister) Get(name string) (*$.type|raw$, error) {
var namespaceListerInterface = `
// $.type|public$NamespaceLister helps list and get $.type|publicPlural$.
// All objects returned here must be treated as read-only.
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)
// 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)
$.type|public$NamespaceListerExpansion
}

View file

@ -24,7 +24,7 @@ import (
"k8s.io/code-generator/cmd/lister-gen/generators"
"k8s.io/code-generator/pkg/util"
"k8s.io/gengo/args"
"k8s.io/klog"
"k8s.io/klog/v2"
generatorargs "k8s.io/code-generator/cmd/lister-gen/args"
)
@ -50,7 +50,7 @@ func main() {
// Run it.
if err := genericArgs.Execute(
generators.NameSystems(),
generators.NameSystems(util.PluralExceptionListToMapOrDie(customArgs.PluralExceptions)),
generators.DefaultNameSystem(),
generators.Packages,
); err != nil {

57
vendor/k8s.io/code-generator/cmd/openapi-gen/main.go generated vendored Normal file
View file

@ -0,0 +1,57 @@
/*
Copyright 2018 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// This package generates openAPI definition file to be used in open API spec generation on API servers. To generate
// definition for a specific type or package add "+k8s:openapi-gen=true" tag to the type/package comment lines. To
// exclude a type from a tagged package, add "+k8s:openapi-gen=false" tag to the type comment lines.
package main
import (
"flag"
"log"
generatorargs "k8s.io/kube-openapi/cmd/openapi-gen/args"
"k8s.io/kube-openapi/pkg/generators"
"github.com/spf13/pflag"
"k8s.io/klog/v2"
)
func main() {
klog.InitFlags(nil)
genericArgs, customArgs := generatorargs.NewDefaults()
genericArgs.AddFlags(pflag.CommandLine)
customArgs.AddFlags(pflag.CommandLine)
flag.Set("logtostderr", "true")
pflag.CommandLine.AddGoFlagSet(flag.CommandLine)
pflag.Parse()
if err := generatorargs.Validate(genericArgs); err != nil {
log.Fatalf("Arguments validation error: %v", err)
}
// Generates the code for the OpenAPIDefinitions.
if err := genericArgs.Execute(
generators.NameSystems(),
generators.DefaultNameSystem(),
generators.Packages,
); err != nil {
log.Fatalf("OpenAPI code generation error: %v", err)
}
}

View file

@ -22,7 +22,7 @@ import (
"path"
"strings"
"k8s.io/klog"
"k8s.io/klog/v2"
clientgentypes "k8s.io/code-generator/cmd/client-gen/types"
"k8s.io/gengo/args"

View file

@ -21,7 +21,7 @@ import (
"path/filepath"
"github.com/spf13/pflag"
"k8s.io/klog"
"k8s.io/klog/v2"
generatorargs "k8s.io/code-generator/cmd/register-gen/args"
"k8s.io/code-generator/cmd/register-gen/generators"

View file

@ -32,7 +32,7 @@ import (
"k8s.io/gengo/args"
"k8s.io/gengo/examples/set-gen/generators"
"k8s.io/klog"
"k8s.io/klog/v2"
)
func main() {