Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Client-gen] add a mock type to test the generated client code #18231

Merged
merged 1 commit into from
Dec 15, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
16 changes: 6 additions & 10 deletions cmd/libs/go2idl/client-gen/generators/client-generator.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,7 @@ limitations under the License.
package generators

import (
"os"
"path/filepath"
"strings"

"k8s.io/kubernetes/cmd/libs/go2idl/args"
"k8s.io/kubernetes/cmd/libs/go2idl/generator"
Expand Down Expand Up @@ -66,6 +64,10 @@ func Packages(context *generator.Context, arguments *args.GeneratorArgs) generat
continue
}
group := filepath.Base(t.Name.Package)
// Special case for the legacy API.
if group == "api" {
group = ""
}
if _, found := groupToTypes[group]; !found {
groupToTypes[group] = []*types.Type{}
}
Expand All @@ -74,15 +76,9 @@ func Packages(context *generator.Context, arguments *args.GeneratorArgs) generat
}

return generator.Packages{&generator.DefaultPackage{
PackageName: "unversioned",
PackageName: filepath.Base(arguments.OutputPackagePath),
PackagePath: arguments.OutputPackagePath,
HeaderText: append(boilerplate, []byte(
`
// This file was autogenerated by the command:
// $ `+strings.Join(os.Args, " ")+`
// Do not edit it manually!

`)...),
HeaderText: boilerplate,
PackageDocumentation: []byte(
`// Package unversioned has the automatically generated clients for unversioned resources.
`),
Expand Down
19 changes: 14 additions & 5 deletions cmd/libs/go2idl/client-gen/generators/generator-for-group.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,13 +46,20 @@ func (g *genGroup) Namers(c *generator.Context) namer.NameSystems {
}

func (g *genGroup) Imports(c *generator.Context) (imports []string) {
return append(g.imports.ImportLines(), "fmt", "strings")
return append(g.imports.ImportLines(), "fmt")
}

func (g *genGroup) GenerateType(c *generator.Context, t *types.Type, w io.Writer) error {
sw := generator.NewSnippetWriter(w, c, "$", "$")
const pkgUnversioned = "k8s.io/kubernetes/pkg/client/unversioned"
const pkgLatest = "k8s.io/kubernetes/pkg/api/latest"
prefix := func(group string) string {
if group == "" {
return `"/api"`
}
return `"/apis"`
}

m := map[string]interface{}{
"group": g.group,
"Group": namer.IC(g.group),
Expand All @@ -63,6 +70,7 @@ func (g *genGroup) GenerateType(c *generator.Context, t *types.Type, w io.Writer
"RESTClientFor": c.Universe.Function(types.Name{Package: pkgUnversioned, Name: "RESTClientFor"}),
"latestGroup": c.Universe.Variable(types.Name{Package: pkgLatest, Name: "Group"}),
"GroupOrDie": c.Universe.Variable(types.Name{Package: pkgLatest, Name: "GroupOrDie"}),
"prefix": prefix(g.group),
}
sw.Do(groupInterfaceTemplate, m)
sw.Do(groupClientTemplate, m)
Expand Down Expand Up @@ -135,19 +143,20 @@ func set$.Group$Defaults(config *$.Config|raw$) error {
if err != nil {
return err
}
config.Prefix = "apis/"
config.Prefix = $.prefix$
if config.UserAgent == "" {
config.UserAgent = $.DefaultKubernetesUserAgent|raw$()
}
// TODO: Unconditionally set the config.Version, until we fix the config.
//if config.Version == "" {
config.Version = g.GroupVersion
copyGroupVersion := g.GroupVersion
config.GroupVersion = &copyGroupVersion
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is tracking the recent changes in the client package.

//}

versionInterfaces, err := g.InterfacesFor(config.Version)
versionInterfaces, err := g.InterfacesFor(*config.GroupVersion)
if err != nil {
return fmt.Errorf("$.Group$ API version '%s' is not recognized (valid values: %s)",
config.Version, strings.Join($.GroupOrDie|raw$("$.group$").Versions, ", "))
config.GroupVersion, g.GroupVersions)
}
config.Codec = versionInterfaces.Codec
if config.QPS == 0 {
Expand Down
4 changes: 2 additions & 2 deletions cmd/libs/go2idl/client-gen/generators/generator-for-type.go
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ type $.type|privatePlural$ struct {
`
var newStructTemplate = `
// new$.type|publicPlural$ returns a $.type|publicPlural$
func new$.type|publicPlural$(c *ExtensionsClient, namespace string) *$.type|privatePlural$ {
func new$.type|publicPlural$(c *$.Package$Client, namespace string) *$.type|privatePlural$ {
return &$.type|privatePlural${
client: c,
ns: namespace,
Expand Down Expand Up @@ -143,7 +143,7 @@ func (c *$.type|privatePlural$) Delete(name string, options *$.apiDeleteOptions|
if options == nil {
return c.client.Delete().Namespace(c.ns).Resource("$.type|privatePlural$").Name(name).Do().Error()
}
body, err := api.Scheme.EncodeToVersion(options, c.client.APIVersion())
body, err := api.Scheme.EncodeToVersion(options, c.client.APIVersion().String())
if err != nil {
return err
}
Expand Down
44 changes: 31 additions & 13 deletions cmd/libs/go2idl/client-gen/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,24 +22,42 @@ import (
"k8s.io/kubernetes/cmd/libs/go2idl/client-gen/generators"

"github.com/golang/glog"
flag "github.com/spf13/pflag"
)

var test = flag.BoolP("test", "t", false, "set this flag to generate the client code for the testdata")

func main() {
arguments := args.Default()

// Override defaults. These are Kubernetes specific input and output
// locations.
arguments.InputDirs = []string{
"k8s.io/kubernetes/pkg/api",
"k8s.io/kubernetes/pkg/apis/extensions",
"k8s.io/kubernetes/pkg/fields",
"k8s.io/kubernetes/pkg/labels",
"k8s.io/kubernetes/pkg/watch",
"k8s.io/kubernetes/pkg/client/unversioned",
"k8s.io/kubernetes/pkg/api/latest",
flag.Parse()
if *test {
// Override defaults. These are Kubernetes specific input and output
// locations.
arguments.InputDirs = []string{
"k8s.io/kubernetes/cmd/libs/go2idl/client-gen/testdata/apis/testgroup",
"k8s.io/kubernetes/pkg/fields",
"k8s.io/kubernetes/pkg/labels",
"k8s.io/kubernetes/pkg/watch",
"k8s.io/kubernetes/pkg/client/unversioned",
"k8s.io/kubernetes/pkg/api/latest",
}
// We may change the output path later.
arguments.OutputPackagePath = "k8s.io/kubernetes/cmd/libs/go2idl/client-gen/testoutput"
} else {
// Override defaults. These are Kubernetes specific input and output
// locations.
arguments.InputDirs = []string{
"k8s.io/kubernetes/pkg/api",
"k8s.io/kubernetes/pkg/apis/extensions",
"k8s.io/kubernetes/pkg/fields",
"k8s.io/kubernetes/pkg/labels",
"k8s.io/kubernetes/pkg/watch",
"k8s.io/kubernetes/pkg/client/unversioned",
"k8s.io/kubernetes/pkg/api/latest",
}
// We may change the output path later.
arguments.OutputPackagePath = "k8s.io/kubernetes/pkg/client/clientset/unversioned"
}
// We may change the output path later.
arguments.OutputPackagePath = "k8s.io/kubernetes/pkg/client/clientset/unversioned"

if err := arguments.Execute(
generators.NameSystems(),
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
/*
Copyright 2015 The Kubernetes Authors All rights reserved.

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.
*/

// Package install installs the experimental API group, making it available as
// an option to all of the API encoding/decoding machinery.
package install

import (
"fmt"

"github.com/golang/glog"

"k8s.io/kubernetes/cmd/libs/go2idl/client-gen/testdata/apis/testgroup/v1"
"k8s.io/kubernetes/pkg/api"
"k8s.io/kubernetes/pkg/api/latest"
"k8s.io/kubernetes/pkg/api/meta"
"k8s.io/kubernetes/pkg/api/registered"
"k8s.io/kubernetes/pkg/api/unversioned"
"k8s.io/kubernetes/pkg/runtime"
"k8s.io/kubernetes/pkg/util/sets"
)

const importPrefix = "k8s.io/kubernetes/pkg/apis/testgroup"

var accessor = meta.NewAccessor()

func init() {
registered.RegisteredGroupVersions = append(registered.RegisteredGroupVersions, v1.SchemeGroupVersion)
groupMeta, err := latest.RegisterGroup("testgroup")
if err != nil {
glog.V(4).Infof("%v", err)
return
}

registeredGroupVersions := []unversioned.GroupVersion{
{
"testgroup",
"v1",
},
}
groupVersion := registeredGroupVersions[0]
*groupMeta = latest.GroupMeta{
GroupVersion: groupVersion,
Codec: runtime.CodecFor(api.Scheme, groupVersion.String()),
}

worstToBestGroupVersions := []unversioned.GroupVersion{}
for i := len(registeredGroupVersions) - 1; i >= 0; i-- {
worstToBestGroupVersions = append(worstToBestGroupVersions, registeredGroupVersions[i])
}
groupMeta.GroupVersions = registeredGroupVersions

groupMeta.SelfLinker = runtime.SelfLinker(accessor)

// the list of kinds that are scoped at the root of the api hierarchy
// if a kind is not enumerated here, it is assumed to have a namespace scope
rootScoped := sets.NewString()

ignoredKinds := sets.NewString()

groupMeta.RESTMapper = api.NewDefaultRESTMapper(worstToBestGroupVersions, interfacesFor, importPrefix, ignoredKinds, rootScoped)
api.RegisterRESTMapper(groupMeta.RESTMapper)
groupMeta.InterfacesFor = interfacesFor
}

// InterfacesFor returns the default Codec and ResourceVersioner for a given version
// string, or an error if the version is not known.
func interfacesFor(version unversioned.GroupVersion) (*meta.VersionInterfaces, error) {
switch version {
case v1.SchemeGroupVersion:
return &meta.VersionInterfaces{
Codec: v1.Codec,
ObjectConvertor: api.Scheme,
MetadataAccessor: accessor,
}, nil
default:
g, _ := latest.Group("testgroup")
return nil, fmt.Errorf("unsupported storage version: %s (valid: %v)", version, g.GroupVersions)
}
}
43 changes: 43 additions & 0 deletions cmd/libs/go2idl/client-gen/testdata/apis/testgroup/register.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
/*
Copyright 2015 The Kubernetes Authors All rights reserved.

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.
*/

package testgroup

import (
"k8s.io/kubernetes/pkg/api"
"k8s.io/kubernetes/pkg/api/unversioned"
)

var SchemeGroupVersion = unversioned.GroupVersion{Group: "testgroup", Version: ""}

func init() {
// Register the API.
addKnownTypes()
}

// Adds the list of known types to api.Scheme.
func addKnownTypes() {
api.Scheme.AddKnownTypes(SchemeGroupVersion,
&TestType{},
&TestTypeList{},
)

api.Scheme.AddKnownTypes(SchemeGroupVersion,
&unversioned.ListOptions{})
}

func (*TestType) IsAnAPIObject() {}
func (*TestTypeList) IsAnAPIObject() {}