Upgrade k8s package verison (#5358)

* upgrade k8s package version

Signed-off-by: hongzhouzi <hongzhouzi@kubesphere.io>

* Script upgrade and code formatting.

Signed-off-by: hongzhouzi <hongzhouzi@kubesphere.io>

Signed-off-by: hongzhouzi <hongzhouzi@kubesphere.io>
This commit is contained in:
hongzhouzi
2022-11-15 14:56:38 +08:00
committed by GitHub
parent 5f91c1663a
commit 44167aa47a
3106 changed files with 321340 additions and 172080 deletions

6
vendor/k8s.io/gengo/args/args.go generated vendored
View File

@@ -86,6 +86,9 @@ type GeneratorArgs struct {
// Any custom arguments go here
CustomArgs interface{}
// If specified, trim the prefix from OutputPackagePath before writing files.
TrimPathPrefix string
// Whether to use default command line flags
defaultCommandLineFlags bool
}
@@ -104,6 +107,7 @@ func (g *GeneratorArgs) AddFlags(fs *pflag.FlagSet) {
fs.StringVarP(&g.GoHeaderFilePath, "go-header-file", "h", g.GoHeaderFilePath, "File containing boilerplate header text. The string YEAR will be replaced with the current 4-digit year.")
fs.BoolVar(&g.VerifyOnly, "verify-only", g.VerifyOnly, "If true, only verify existing output, do not write anything.")
fs.StringVar(&g.GeneratedBuildTag, "build-tag", g.GeneratedBuildTag, "A Go build tag to use to identify files generated by this command. Should be unique.")
fs.StringVar(&g.TrimPathPrefix, "trim-path-prefix", g.TrimPathPrefix, "If set, trim the specified prefix from --output-package when generating files.")
}
// LoadGoBoilerplate loads the boilerplate file passed to --go-header-file.
@@ -202,6 +206,8 @@ func (g *GeneratorArgs) Execute(nameSystems namer.NameSystems, defaultSystem str
return fmt.Errorf("Failed making a context: %v", err)
}
c.TrimPathPrefix = g.TrimPathPrefix
c.Verify = g.VerifyOnly
packages := pkgs(c, g)
if err := c.ExecutePackages(g.OutputBase, packages); err != nil {

View File

@@ -29,7 +29,7 @@ import (
"k8s.io/gengo/namer"
"k8s.io/gengo/types"
"k8s.io/klog"
"k8s.io/klog/v2"
)
// CustomArgs is used tby the go2idl framework to pass args specific to this
@@ -133,7 +133,7 @@ func Packages(context *generator.Context, arguments *args.GeneratorArgs) generat
inputs := sets.NewString(context.Inputs...)
packages := generator.Packages{}
header := append([]byte(fmt.Sprintf("// +build !%s\n\n", arguments.GeneratedBuildTag)), boilerplate...)
header := append([]byte(fmt.Sprintf("//go:build !%s\n// +build !%s\n\n", arguments.GeneratedBuildTag, arguments.GeneratedBuildTag)), boilerplate...)
boundingDirs := []string{}
if customArgs, ok := arguments.CustomArgs.(*CustomArgs); ok {
@@ -530,7 +530,10 @@ func (g *genDeepCopy) deepCopyableInterfacesInner(c *generator.Context, t *types
var ts []*types.Type
for _, intf := range intfs {
t := types.ParseFullyQualifiedName(intf)
c.AddDir(t.Package)
err := c.AddDir(t.Package)
if err != nil {
return nil, err
}
intfT := c.Universe.Type(t)
if intfT == nil {
return nil, fmt.Errorf("unknown type %q in %s tag of type %s", intf, interfacesTagName, intfT)
@@ -864,6 +867,8 @@ func (g *genDeepCopy) doStruct(t *types.Type, sw *generator.SnippetWriter) {
sw.Do("in, out := &in.$.name$, &out.$.name$\n", args)
g.generateFor(ft, sw)
sw.Do("}\n", nil)
case uft.Kind == types.Array:
sw.Do("out.$.name$ = in.$.name$\n", args)
case uft.Kind == types.Struct:
if ft.IsAssignable() {
sw.Do("out.$.name$ = in.$.name$\n", args)

View File

@@ -28,7 +28,7 @@ type Byte map[byte]Empty
// NewByte creates a Byte from a list of values.
func NewByte(items ...byte) Byte {
ss := Byte{}
ss := make(Byte, len(items))
ss.Insert(items...)
return ss
}
@@ -87,6 +87,15 @@ func (s Byte) HasAny(items ...byte) bool {
return false
}
// Clone returns a new set which is a copy of the current set.
func (s Byte) Clone() Byte {
result := make(Byte, len(s))
for key := range s {
result.Insert(key)
}
return result
}
// Difference returns a set of objects that are not in s2
// For example:
// s1 = {a1, a2, a3}
@@ -110,10 +119,7 @@ func (s Byte) Difference(s2 Byte) Byte {
// s1.Union(s2) = {a1, a2, a3, a4}
// s2.Union(s1) = {a1, a2, a3, a4}
func (s1 Byte) Union(s2 Byte) Byte {
result := NewByte()
for key := range s1 {
result.Insert(key)
}
result := s1.Clone()
for key := range s2 {
result.Insert(key)
}

View File

@@ -28,7 +28,7 @@ type Int map[int]Empty
// NewInt creates a Int from a list of values.
func NewInt(items ...int) Int {
ss := Int{}
ss := make(Int, len(items))
ss.Insert(items...)
return ss
}
@@ -87,6 +87,15 @@ func (s Int) HasAny(items ...int) bool {
return false
}
// Clone returns a new set which is a copy of the current set.
func (s Int) Clone() Int {
result := make(Int, len(s))
for key := range s {
result.Insert(key)
}
return result
}
// Difference returns a set of objects that are not in s2
// For example:
// s1 = {a1, a2, a3}
@@ -110,10 +119,7 @@ func (s Int) Difference(s2 Int) Int {
// s1.Union(s2) = {a1, a2, a3, a4}
// s2.Union(s1) = {a1, a2, a3, a4}
func (s1 Int) Union(s2 Int) Int {
result := NewInt()
for key := range s1 {
result.Insert(key)
}
result := s1.Clone()
for key := range s2 {
result.Insert(key)
}

View File

@@ -28,7 +28,7 @@ type Int64 map[int64]Empty
// NewInt64 creates a Int64 from a list of values.
func NewInt64(items ...int64) Int64 {
ss := Int64{}
ss := make(Int64, len(items))
ss.Insert(items...)
return ss
}
@@ -87,6 +87,15 @@ func (s Int64) HasAny(items ...int64) bool {
return false
}
// Clone returns a new set which is a copy of the current set.
func (s Int64) Clone() Int64 {
result := make(Int64, len(s))
for key := range s {
result.Insert(key)
}
return result
}
// Difference returns a set of objects that are not in s2
// For example:
// s1 = {a1, a2, a3}
@@ -110,10 +119,7 @@ func (s Int64) Difference(s2 Int64) Int64 {
// s1.Union(s2) = {a1, a2, a3, a4}
// s2.Union(s1) = {a1, a2, a3, a4}
func (s1 Int64) Union(s2 Int64) Int64 {
result := NewInt64()
for key := range s1 {
result.Insert(key)
}
result := s1.Clone()
for key := range s2 {
result.Insert(key)
}

View File

@@ -28,7 +28,7 @@ type String map[string]Empty
// NewString creates a String from a list of values.
func NewString(items ...string) String {
ss := String{}
ss := make(String, len(items))
ss.Insert(items...)
return ss
}
@@ -87,6 +87,15 @@ func (s String) HasAny(items ...string) bool {
return false
}
// Clone returns a new set which is a copy of the current set.
func (s String) Clone() String {
result := make(String, len(s))
for key := range s {
result.Insert(key)
}
return result
}
// Difference returns a set of objects that are not in s2
// For example:
// s1 = {a1, a2, a3}
@@ -110,10 +119,7 @@ func (s String) Difference(s2 String) String {
// s1.Union(s2) = {a1, a2, a3, a4}
// s2.Union(s1) = {a1, a2, a3, a4}
func (s1 String) Union(s2 String) String {
result := NewString()
for key := range s1 {
result.Insert(key)
}
result := s1.Clone()
for key := range s2 {
result.Insert(key)
}

View File

@@ -29,7 +29,7 @@ import (
"k8s.io/gengo/namer"
"k8s.io/gengo/types"
"k8s.io/klog"
"k8s.io/klog/v2"
)
func errs2strings(errors []error) []string {
@@ -64,7 +64,7 @@ type DefaultFileType struct {
}
func (ft DefaultFileType) AssembleFile(f *File, pathname string) error {
klog.V(2).Infof("Assembling file %q", pathname)
klog.V(5).Infof("Assembling file %q", pathname)
destFile, err := os.Create(pathname)
if err != nil {
return err
@@ -91,7 +91,7 @@ func (ft DefaultFileType) AssembleFile(f *File, pathname string) error {
}
func (ft DefaultFileType) VerifyFile(f *File, pathname string) error {
klog.V(2).Infof("Verifying file %q", pathname)
klog.V(5).Infof("Verifying file %q", pathname)
friendlyName := filepath.Join(f.PackageName, f.Name)
b := &bytes.Buffer{}
et := NewErrorTracker(b)
@@ -214,7 +214,22 @@ func (c *Context) addNameSystems(namers namer.NameSystems) *Context {
// import path already, this will be appended to 'outDir'.
func (c *Context) ExecutePackage(outDir string, p Package) error {
path := filepath.Join(outDir, p.Path())
klog.V(2).Infof("Processing package %q, disk location %q", p.Name(), path)
// When working outside of GOPATH, we typically won't want to generate the
// full path for a package. For example, if our current project's root/base
// package is github.com/foo/bar, outDir=., p.Path()=github.com/foo/bar/generated,
// then we really want to be writing files to ./generated, not ./github.com/foo/bar/generated.
// The following will trim a path prefix (github.com/foo/bar) from p.Path() to arrive at
// a relative path that works with projects not in GOPATH.
if c.TrimPathPrefix != "" {
separator := string(filepath.Separator)
if !strings.HasSuffix(c.TrimPathPrefix, separator) {
c.TrimPathPrefix += separator
}
path = strings.TrimPrefix(path, c.TrimPathPrefix)
}
klog.V(5).Infof("Processing package %q, disk location %q", p.Name(), path)
// Filter out any types the *package* doesn't care about.
packageContext := c.filteredBy(p.Filter)
os.MkdirAll(path, 0755)

View File

@@ -183,6 +183,9 @@ type Context struct {
// Allows generators to add packages at runtime.
builder *parser.Builder
// If specified, trim the prefix from a package's path before writing files.
TrimPathPrefix string
}
// NewContext generates a context from the given builder, naming systems, and

View File

@@ -20,7 +20,7 @@ import (
"go/token"
"strings"
"k8s.io/klog"
"k8s.io/klog/v2"
"k8s.io/gengo/namer"
"k8s.io/gengo/types"

View File

@@ -57,7 +57,7 @@ func NewSnippetWriter(w io.Writer, c *Context, left, right string) *SnippetWrite
// Do parses format and runs args through it. You can have arbitrary logic in
// the format (see the text/template documentation), but consider running many
// short templaces, with ordinary go logic in between--this may be more
// short templates with ordinary go logic in between--this may be more
// readable. Do is chainable. Any error causes every other call to do to be
// ignored, and the error will be returned by Error(). So you can check it just
// once, at the end of your function.

11
vendor/k8s.io/gengo/namer/namer.go generated vendored
View File

@@ -17,7 +17,9 @@ limitations under the License.
package namer
import (
"fmt"
"path/filepath"
"strconv"
"strings"
"k8s.io/gengo/types"
@@ -246,6 +248,12 @@ func (ns *NameStrategy) Name(t *types.Type) string {
"Slice",
ns.removePrefixAndSuffix(ns.Name(t.Elem)),
}, ns.Suffix)
case types.Array:
name = ns.Join(ns.Prefix, []string{
"Array",
ns.removePrefixAndSuffix(fmt.Sprintf("%d", t.Len)),
ns.removePrefixAndSuffix(ns.Name(t.Elem)),
}, ns.Suffix)
case types.Pointer:
name = ns.Join(ns.Prefix, []string{
"Pointer",
@@ -340,6 +348,9 @@ func (r *rawNamer) Name(t *types.Type) string {
name = "map[" + r.Name(t.Key) + "]" + r.Name(t.Elem)
case types.Slice:
name = "[]" + r.Name(t.Elem)
case types.Array:
l := strconv.Itoa(int(t.Len))
name = "[" + l + "]" + r.Name(t.Elem)
case types.Pointer:
name = "*" + r.Name(t.Elem)
case types.Struct:

View File

@@ -22,7 +22,7 @@ import (
"k8s.io/gengo/types"
)
var consonants = "bcdfghjklmnpqrsttvwxyz"
var consonants = "bcdfghjklmnpqrstvwxyz"
type pluralNamer struct {
// key is the case-sensitive type name, value is the case-insensitive

180
vendor/k8s.io/gengo/parser/parse.go generated vendored
View File

@@ -20,6 +20,7 @@ import (
"fmt"
"go/ast"
"go/build"
"go/constant"
"go/parser"
"go/token"
tc "go/types"
@@ -28,11 +29,12 @@ import (
"os/exec"
"path"
"path/filepath"
"regexp"
"sort"
"strings"
"k8s.io/gengo/types"
"k8s.io/klog"
"k8s.io/klog/v2"
)
// This clarifies when a pkg path has been canonicalized.
@@ -50,7 +52,9 @@ type Builder struct {
// This might hold the same value for multiple names, e.g. if someone
// referenced ./pkg/name or in the case of vendoring, which canonicalizes
// differently that what humans would type.
buildPackages map[string]*build.Package
//
// This must only be accessed via getLoadedBuildPackage and setLoadedBuildPackage
buildPackages map[importPathString]*build.Package
fset *token.FileSet
// map of package path to list of parsed files
@@ -100,7 +104,7 @@ func New() *Builder {
c.CgoEnabled = false
return &Builder{
context: &c,
buildPackages: map[string]*build.Package{},
buildPackages: map[importPathString]*build.Package{},
typeCheckedPackages: map[importPathString]*tc.Package{},
fset: token.NewFileSet(),
parsed: map[importPathString][]parsedFile{},
@@ -116,11 +120,37 @@ func (b *Builder) AddBuildTags(tags ...string) {
b.context.BuildTags = append(b.context.BuildTags, tags...)
}
func (b *Builder) getLoadedBuildPackage(importPath string) (*build.Package, bool) {
canonicalized := canonicalizeImportPath(importPath)
if string(canonicalized) != importPath {
klog.V(5).Infof("getLoadedBuildPackage: %s normalized to %s", importPath, canonicalized)
}
buildPkg, ok := b.buildPackages[canonicalized]
return buildPkg, ok
}
func (b *Builder) setLoadedBuildPackage(importPath string, buildPkg *build.Package) {
canonicalizedImportPath := canonicalizeImportPath(importPath)
if string(canonicalizedImportPath) != importPath {
klog.V(5).Infof("setLoadedBuildPackage: importPath %s normalized to %s", importPath, canonicalizedImportPath)
}
canonicalizedBuildPkgImportPath := canonicalizeImportPath(buildPkg.ImportPath)
if string(canonicalizedBuildPkgImportPath) != buildPkg.ImportPath {
klog.V(5).Infof("setLoadedBuildPackage: buildPkg.ImportPath %s normalized to %s", buildPkg.ImportPath, canonicalizedBuildPkgImportPath)
}
if canonicalizedImportPath != canonicalizedBuildPkgImportPath {
klog.V(5).Infof("setLoadedBuildPackage: normalized importPath (%s) differs from buildPkg.ImportPath (%s)", canonicalizedImportPath, canonicalizedBuildPkgImportPath)
}
b.buildPackages[canonicalizedImportPath] = buildPkg
b.buildPackages[canonicalizedBuildPkgImportPath] = buildPkg
}
// Get package information from the go/build package. Automatically excludes
// e.g. test files and files for other platforms-- there is quite a bit of
// logic of that nature in the build package.
func (b *Builder) importBuildPackage(dir string) (*build.Package, error) {
if buildPkg, ok := b.buildPackages[dir]; ok {
if buildPkg, ok := b.getLoadedBuildPackage(dir); ok {
return buildPkg, nil
}
// This validates the `package foo // github.com/bar/foo` comments.
@@ -140,17 +170,7 @@ func (b *Builder) importBuildPackage(dir string) (*build.Package, error) {
// Remember it under the user-provided name.
klog.V(5).Infof("saving buildPackage %s", dir)
b.buildPackages[dir] = buildPkg
canonicalPackage := canonicalizeImportPath(buildPkg.ImportPath)
if dir != string(canonicalPackage) {
// Since `dir` is not the canonical name, see if we knew it under another name.
if buildPkg, ok := b.buildPackages[string(canonicalPackage)]; ok {
return buildPkg, nil
}
// Must be new, save it under the canonical name, too.
klog.V(5).Infof("saving buildPackage %s", canonicalPackage)
b.buildPackages[string(canonicalPackage)] = buildPkg
}
b.setLoadedBuildPackage(dir, buildPkg)
return buildPkg, nil
}
@@ -165,7 +185,7 @@ func (b *Builder) AddFileForTest(pkg string, path string, src []byte) error {
if err := b.addFile(importPathString(pkg), path, src, true); err != nil {
return err
}
if _, err := b.typeCheckPackage(importPathString(pkg)); err != nil {
if _, err := b.typeCheckPackage(importPathString(pkg), true); err != nil {
return err
}
return nil
@@ -229,7 +249,11 @@ func (b *Builder) AddDirRecursive(dir string) error {
// filepath.Walk does not follow symlinks. We therefore evaluate symlinks and use that with
// filepath.Walk.
realPath, err := filepath.EvalSymlinks(b.buildPackages[dir].Dir)
buildPkg, ok := b.getLoadedBuildPackage(dir)
if !ok {
return fmt.Errorf("no loaded build package for %s", dir)
}
realPath, err := filepath.EvalSymlinks(buildPkg.Dir)
if err != nil {
return err
}
@@ -239,7 +263,11 @@ func (b *Builder) AddDirRecursive(dir string) error {
rel := filepath.ToSlash(strings.TrimPrefix(filePath, realPath))
if rel != "" {
// Make a pkg path.
pkg := path.Join(string(canonicalizeImportPath(b.buildPackages[dir].ImportPath)), rel)
buildPkg, ok := b.getLoadedBuildPackage(dir)
if !ok {
return fmt.Errorf("no loaded build package for %s", dir)
}
pkg := path.Join(string(canonicalizeImportPath(buildPkg.ImportPath)), rel)
// Add it.
if _, err := b.importPackage(pkg, true); err != nil {
@@ -267,7 +295,11 @@ func (b *Builder) AddDirTo(dir string, u *types.Universe) error {
if _, err := b.importPackage(dir, true); err != nil {
return err
}
return b.findTypesIn(canonicalizeImportPath(b.buildPackages[dir].ImportPath), u)
pkg, ok := b.getLoadedBuildPackage(dir)
if !ok {
return fmt.Errorf("no such package: %q", dir)
}
return b.findTypesIn(canonicalizeImportPath(pkg.ImportPath), u)
}
// AddDirectoryTo adds an entire directory to a given Universe. Unlike AddDir,
@@ -281,7 +313,11 @@ func (b *Builder) AddDirectoryTo(dir string, u *types.Universe) (*types.Package,
if _, err := b.importPackage(dir, true); err != nil {
return nil, err
}
path := canonicalizeImportPath(b.buildPackages[dir].ImportPath)
pkg, ok := b.getLoadedBuildPackage(dir)
if !ok || pkg == nil {
return nil, fmt.Errorf("no such package: %q", dir)
}
path := canonicalizeImportPath(pkg.ImportPath)
if err := b.findTypesIn(path, u); err != nil {
return nil, err
}
@@ -334,14 +370,22 @@ func (b *Builder) addDir(dir string, userRequested bool) error {
return nil
}
// regexErrPackageNotFound helps test the expected error for not finding a package.
var regexErrPackageNotFound = regexp.MustCompile(`^unable to import ".*?":.*`)
func isErrPackageNotFound(err error) bool {
return regexErrPackageNotFound.MatchString(err.Error())
}
// importPackage is a function that will be called by the type check package when it
// needs to import a go package. 'path' is the import path.
func (b *Builder) importPackage(dir string, userRequested bool) (*tc.Package, error) {
klog.V(5).Infof("importPackage %s", dir)
var pkgPath = importPathString(dir)
// Get the canonical path if we can.
if buildPkg := b.buildPackages[dir]; buildPkg != nil {
if buildPkg, _ := b.getLoadedBuildPackage(dir); buildPkg != nil {
canonicalPackage := canonicalizeImportPath(buildPkg.ImportPath)
klog.V(5).Infof("importPackage %s, canonical path is %s", dir, canonicalPackage)
pkgPath = canonicalPackage
@@ -356,11 +400,16 @@ func (b *Builder) importPackage(dir string, userRequested bool) (*tc.Package, er
// Add it.
if err := b.addDir(dir, userRequested); err != nil {
if isErrPackageNotFound(err) {
klog.V(6).Info(err)
return nil, nil
}
return nil, err
}
// Get the canonical path now that it has been added.
if buildPkg := b.buildPackages[dir]; buildPkg != nil {
if buildPkg, _ := b.getLoadedBuildPackage(dir); buildPkg != nil {
canonicalPackage := canonicalizeImportPath(buildPkg.ImportPath)
klog.V(5).Infof("importPackage %s, canonical path is %s", dir, canonicalPackage)
pkgPath = canonicalPackage
@@ -374,13 +423,13 @@ func (b *Builder) importPackage(dir string, userRequested bool) (*tc.Package, er
// Run the type checker. We may end up doing this to pkgs that are already
// done, or are in the queue to be done later, but it will short-circuit,
// and we can't miss pkgs that are only depended on.
pkg, err := b.typeCheckPackage(pkgPath)
pkg, err := b.typeCheckPackage(pkgPath, !ignoreError)
if err != nil {
switch {
case ignoreError && pkg != nil:
klog.V(2).Infof("type checking encountered some issues in %q, but ignoring.\n", pkgPath)
klog.V(4).Infof("type checking encountered some issues in %q, but ignoring.\n", pkgPath)
case !ignoreError && pkg != nil:
klog.V(2).Infof("type checking encountered some errors in %q\n", pkgPath)
klog.V(3).Infof("type checking encountered some errors in %q\n", pkgPath)
return nil, err
default:
return nil, err
@@ -401,7 +450,7 @@ func (a importAdapter) Import(path string) (*tc.Package, error) {
// typeCheckPackage will attempt to return the package even if there are some
// errors, so you may check whether the package is nil or not even if you get
// an error.
func (b *Builder) typeCheckPackage(pkgPath importPathString) (*tc.Package, error) {
func (b *Builder) typeCheckPackage(pkgPath importPathString, logErr bool) (*tc.Package, error) {
klog.V(5).Infof("typeCheckPackage %s", pkgPath)
if pkg, ok := b.typeCheckedPackages[pkgPath]; ok {
if pkg != nil {
@@ -429,7 +478,11 @@ func (b *Builder) typeCheckPackage(pkgPath importPathString) (*tc.Package, error
// method. So there can't be cycles in the import graph.
Importer: importAdapter{b},
Error: func(err error) {
klog.V(2).Infof("type checker: %v\n", err)
if logErr {
klog.V(2).Infof("type checker: %v\n", err)
} else {
klog.V(3).Infof("type checker: %v\n", err)
}
},
}
pkg, err := c.Check(string(pkgPath), b.fset, files, nil)
@@ -479,6 +532,19 @@ func (b *Builder) FindTypes() (types.Universe, error) {
return u, nil
}
// addCommentsToType takes any accumulated comment lines prior to obj and
// attaches them to the type t.
func (b *Builder) addCommentsToType(obj tc.Object, t *types.Type) {
c1 := b.priorCommentLines(obj.Pos(), 1)
// c1.Text() is safe if c1 is nil
t.CommentLines = splitLines(c1.Text())
if c1 == nil {
t.SecondClosestCommentLines = splitLines(b.priorCommentLines(obj.Pos(), 2).Text())
} else {
t.SecondClosestCommentLines = splitLines(b.priorCommentLines(c1.List[0].Slash, 2).Text())
}
}
// findTypesIn finalizes the package import and searches through the package
// for types.
func (b *Builder) findTypesIn(pkgPath importPathString, u *types.Universe) error {
@@ -522,35 +588,23 @@ func (b *Builder) findTypesIn(pkgPath importPathString, u *types.Universe) error
tn, ok := obj.(*tc.TypeName)
if ok {
t := b.walkType(*u, nil, tn.Type())
c1 := b.priorCommentLines(obj.Pos(), 1)
// c1.Text() is safe if c1 is nil
t.CommentLines = splitLines(c1.Text())
if c1 == nil {
t.SecondClosestCommentLines = splitLines(b.priorCommentLines(obj.Pos(), 2).Text())
} else {
t.SecondClosestCommentLines = splitLines(b.priorCommentLines(c1.List[0].Slash, 2).Text())
}
b.addCommentsToType(obj, t)
}
tf, ok := obj.(*tc.Func)
// We only care about functions, not concrete/abstract methods.
if ok && tf.Type() != nil && tf.Type().(*tc.Signature).Recv() == nil {
t := b.addFunction(*u, nil, tf)
c1 := b.priorCommentLines(obj.Pos(), 1)
// c1.Text() is safe if c1 is nil
t.CommentLines = splitLines(c1.Text())
if c1 == nil {
t.SecondClosestCommentLines = splitLines(b.priorCommentLines(obj.Pos(), 2).Text())
} else {
t.SecondClosestCommentLines = splitLines(b.priorCommentLines(c1.List[0].Slash, 2).Text())
}
b.addCommentsToType(obj, t)
}
tv, ok := obj.(*tc.Var)
if ok && !tv.IsField() {
b.addVariable(*u, nil, tv)
t := b.addVariable(*u, nil, tv)
b.addCommentsToType(obj, t)
}
tconst, ok := obj.(*tc.Const)
if ok {
b.addConstant(*u, nil, tconst)
t := b.addConstant(*u, nil, tconst)
b.addCommentsToType(obj, t)
}
}
@@ -577,7 +631,11 @@ func (b *Builder) importWithMode(dir string, mode build.ImportMode) (*build.Pack
if err != nil {
return nil, fmt.Errorf("unable to get current directory: %v", err)
}
buildPkg, err := b.context.Import(dir, cwd, mode)
// normalize to drop /vendor/ if present
dir = string(canonicalizeImportPath(dir))
buildPkg, err := b.context.Import(filepath.ToSlash(dir), cwd, mode)
if err != nil {
return nil, err
}
@@ -638,9 +696,11 @@ func (b *Builder) convertSignature(u types.Universe, t *tc.Signature) *types.Sig
signature := &types.Signature{}
for i := 0; i < t.Params().Len(); i++ {
signature.Parameters = append(signature.Parameters, b.walkType(u, nil, t.Params().At(i).Type()))
signature.ParameterNames = append(signature.ParameterNames, t.Params().At(i).Name())
}
for i := 0; i < t.Results().Len(); i++ {
signature.Results = append(signature.Results, b.walkType(u, nil, t.Results().At(i).Type()))
signature.ResultNames = append(signature.ResultNames, t.Results().At(i).Name())
}
if r := t.Recv(); r != nil {
signature.Receiver = b.walkType(u, nil, r.Type())
@@ -708,8 +768,7 @@ func (b *Builder) walkType(u types.Universe, useName *types.Name, in tc.Type) *t
}
out.Kind = types.Array
out.Elem = b.walkType(u, nil, t.Elem())
// TODO: need to store array length, otherwise raw type name
// cannot be properly written.
out.Len = in.(*tc.Array).Len()
return out
case *tc.Chan:
out := u.Type(name)
@@ -750,7 +809,11 @@ func (b *Builder) walkType(u types.Universe, useName *types.Name, in tc.Type) *t
if out.Methods == nil {
out.Methods = map[string]*types.Type{}
}
out.Methods[t.Method(i).Name()] = b.walkType(u, nil, t.Method(i).Type())
method := t.Method(i)
name := tcNameToName(method.String())
mt := b.walkType(u, &name, method.Type())
mt.CommentLines = splitLines(b.priorCommentLines(method.Pos(), 1).Text())
out.Methods[method.Name()] = mt
}
return out
case *tc.Named:
@@ -783,7 +846,8 @@ func (b *Builder) walkType(u types.Universe, useName *types.Name, in tc.Type) *t
out.Methods = map[string]*types.Type{}
}
method := t.Method(i)
mt := b.walkType(u, nil, method.Type())
name := tcNameToName(method.String())
mt := b.walkType(u, &name, method.Type())
mt.CommentLines = splitLines(b.priorCommentLines(method.Pos(), 1).Text())
out.Methods[method.Name()] = mt
}
@@ -830,6 +894,22 @@ func (b *Builder) addConstant(u types.Universe, useName *types.Name, in *tc.Cons
out := u.Constant(name)
out.Kind = types.DeclarationOf
out.Underlying = b.walkType(u, nil, in.Type())
var constval string
// For strings, we use `StringVal()` to get the un-truncated,
// un-quoted string. For other values, `.String()` is preferable to
// get something relatively human readable (especially since for
// floating point types, `ExactString()` will generate numeric
// expressions using `big.(*Float).Text()`.
switch in.Val().Kind() {
case constant.String:
constval = constant.StringVal(in.Val())
default:
constval = in.Val().String()
}
out.ConstValue = &constval
return out
}

29
vendor/k8s.io/gengo/types/types.go generated vendored
View File

@@ -83,11 +83,13 @@ const (
// Interface is any type that could have differing types at run time.
Interface Kind = "Interface"
// Array is just like slice, but has a fixed length.
Array Kind = "Array"
// The remaining types are included for completeness, but are not well
// supported.
Array Kind = "Array" // Array is just like slice, but has a fixed length.
Chan Kind = "Chan"
Func Kind = "Func"
Chan Kind = "Chan"
Func Kind = "Func"
// DeclarationOf is different from other Kinds; it indicates that instead of
// representing an actual Type, the type is a declaration of an instance of
@@ -341,9 +343,18 @@ type Type struct {
// If Kind == func, this is the signature of the function.
Signature *Signature
// ConstValue contains a stringified constant value if
// Kind == DeclarationOf and this is a constant value
// declaration. For string constants, this field contains
// the entire, un-quoted value. For other types, it contains
// a human-readable literal.
ConstValue *string
// TODO: Add:
// * channel direction
// * array length
// If Kind == Array
Len int64
}
// String returns the name of the type.
@@ -412,12 +423,12 @@ func (m Member) String() string {
// Signature is a function's signature.
type Signature struct {
// TODO: store the parameter names, not just types.
// If a method of some type, this is the type it's a member of.
Receiver *Type
Parameters []*Type
Results []*Type
Receiver *Type
Parameters []*Type
ParameterNames []string
Results []*Type
ResultNames []string
// True if the last in parameter is of the form ...T.
Variadic bool