From e0875f173becf86f27be543ab06331b8f8451afd Mon Sep 17 00:00:00 2001 From: kubevirt-bot Date: Mon, 31 May 2021 13:07:04 +0200 Subject: [PATCH] bump controller-tools to v0.5.0 (#309) Signed-off-by: Ram Lavi Co-authored-by: Ram Lavi --- go.mod | 2 +- go.sum | 6 + .../gobuffalo/flect/azure-pipelines.yml | 71 --------- .../gobuffalo/flect/azure-tests.yml | 19 --- .../github.com/gobuffalo/flect/capitalize.go | 9 +- vendor/github.com/gobuffalo/flect/go.mod | 7 +- vendor/github.com/gobuffalo/flect/go.sum | 10 +- vendor/github.com/gobuffalo/flect/humanize.go | 10 +- vendor/github.com/gobuffalo/flect/ident.go | 42 +++-- .../gobuffalo/flect/plural_rules.go | 11 +- .../github.com/gobuffalo/flect/pluralize.go | 16 +- .../github.com/gobuffalo/flect/singularize.go | 10 ++ .../github.com/gobuffalo/flect/underscore.go | 11 +- .../github.com/mattn/go-colorable/.travis.yml | 12 +- .../github.com/mattn/go-colorable/README.md | 4 +- .../mattn/go-colorable/colorable_appengine.go | 8 + .../mattn/go-colorable/colorable_others.go | 8 + .../mattn/go-colorable/colorable_windows.go | 56 +++++-- vendor/github.com/mattn/go-colorable/go.mod | 7 +- vendor/github.com/mattn/go-colorable/go.sum | 9 +- .../github.com/mattn/go-colorable/go.test.sh | 12 ++ vendor/modules.txt | 8 +- .../controller-tools/pkg/crd/gen.go | 117 ++++++++++++++ .../controller-tools/pkg/crd/known_types.go | 8 + .../pkg/crd/markers/validation.go | 64 +++++++- .../crd/markers/zz_generated.markerhelp.go | 37 ++++- .../controller-tools/pkg/crd/parser.go | 22 +-- .../controller-tools/pkg/crd/schema.go | 27 +--- .../pkg/crd/schema_visitor.go | 6 + .../controller-tools/pkg/crd/spec.go | 2 +- .../controller-tools/pkg/deepcopy/gen.go | 20 ++- .../controller-tools/pkg/deepcopy/traverse.go | 53 ++++--- .../controller-tools/pkg/genall/genall.go | 41 ++++- .../controller-tools/pkg/loader/errors.go | 8 +- .../controller-tools/pkg/loader/refs.go | 46 ++++-- .../controller-tools/pkg/markers/parse.go | 19 ++- .../controller-tools/pkg/schemapatcher/gen.go | 5 + .../controller-tools/pkg/webhook/conv.go | 44 ------ .../controller-tools/pkg/webhook/parser.go | 143 ++++++++---------- .../pkg/webhook/zz_generated.markerhelp.go | 4 + 40 files changed, 636 insertions(+), 378 deletions(-) delete mode 100644 vendor/github.com/gobuffalo/flect/azure-pipelines.yml delete mode 100644 vendor/github.com/gobuffalo/flect/azure-tests.yml create mode 100644 vendor/github.com/mattn/go-colorable/go.test.sh delete mode 100644 vendor/sigs.k8s.io/controller-tools/pkg/webhook/conv.go diff --git a/go.mod b/go.mod index 984ad3277..027b4dfca 100644 --- a/go.mod +++ b/go.mod @@ -19,7 +19,7 @@ require ( kubevirt.io/kubevirt v0.37.1 kubevirt.io/qe-tools v0.1.6 sigs.k8s.io/controller-runtime v0.8.2 - sigs.k8s.io/controller-tools v0.4.0 + sigs.k8s.io/controller-tools v0.5.0 sigs.k8s.io/kustomize/kustomize/v3 v3.3.0 ) diff --git a/go.sum b/go.sum index 769278f8a..bc223f3dd 100644 --- a/go.sum +++ b/go.sum @@ -299,6 +299,8 @@ github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/me github.com/gobuffalo/flect v0.1.5/go.mod h1:W3K3X9ksuZfir8f/LrfVtWmCDQFfayuylOJ7sz/Fj80= github.com/gobuffalo/flect v0.2.0 h1:EWCvMGGxOjsgwlWaP+f4+Hh6yrrte7JeFL2S6b+0hdM= github.com/gobuffalo/flect v0.2.0/go.mod h1:W3K3X9ksuZfir8f/LrfVtWmCDQFfayuylOJ7sz/Fj80= +github.com/gobuffalo/flect v0.2.2 h1:PAVD7sp0KOdfswjAw9BpLCU9hXo7wFSzgpQ+zNeks/A= +github.com/gobuffalo/flect v0.2.2/go.mod h1:vmkQwuZYhN5Pc4ljYQZzP+1sq+NEkK+lh20jmEmX3jc= github.com/godbus/dbus v0.0.0-20180201030542-885f9cc04c9c/go.mod h1:/YcGZj5zSblfDWMMoOzV4fas9FZnQYTkDnsGvmh2Grw= github.com/godbus/dbus v0.0.0-20190422162347-ade71ed3457e/go.mod h1:bBOAhwG1umN6/6ZUMtDFBMQR8jRg9O75tm9K00oMsK4= github.com/godbus/dbus/v5 v5.0.3/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= @@ -527,6 +529,8 @@ github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaO github.com/mattn/go-colorable v0.1.2/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE= github.com/mattn/go-colorable v0.1.4 h1:snbPLB8fVfU9iwbbo30TPtbLRzwWu6aJS6Xh4eaaviA= github.com/mattn/go-colorable v0.1.4/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE= +github.com/mattn/go-colorable v0.1.8 h1:c1ghPdyEDarC70ftn0y+A/Ee++9zz8ljHG1b13eJ0s8= +github.com/mattn/go-colorable v0.1.8/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= github.com/mattn/go-isatty v0.0.4/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= github.com/mattn/go-isatty v0.0.6/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= @@ -1326,6 +1330,8 @@ sigs.k8s.io/controller-runtime v0.8.2/go.mod h1:U/l+DUopBc1ecfRZ5aviA9JDmGFQKvLf sigs.k8s.io/controller-tools v0.2.4/go.mod h1:m/ztfQNocGYBgTTCmFdnK94uVvgxeZeE3LtJvd/jIzA= sigs.k8s.io/controller-tools v0.4.0 h1:9zIdrc6q9RKke8+DnVPVBVZ+cfF9L0TwM01cxNnklYo= sigs.k8s.io/controller-tools v0.4.0/go.mod h1:G9rHdZMVlBDocIxGkK3jHLWqcTMNvveypYJwrvYKjWU= +sigs.k8s.io/controller-tools v0.5.0 h1:3u2RCwOlp0cjCALAigpOcbAf50pE+kHSdueUosrC/AE= +sigs.k8s.io/controller-tools v0.5.0/go.mod h1:JTsstrMpxs+9BUj6eGuAaEb6SDSPTeVtUyp0jmnAM/I= sigs.k8s.io/kustomize/api v0.1.1 h1:W2dWXex2MhF4/EZNokZllvet2RejCHqdAFklufN7VTg= sigs.k8s.io/kustomize/api v0.1.1/go.mod h1:FyfJD1q1QMjC/TvK78b6cCtZB+mbpnGIo9YOvbucJes= sigs.k8s.io/kustomize/kustomize/v3 v3.3.0 h1:1uBNN0OUo7jKHIyvvTYtjNIZNFcyG3d4i2xbWr3dKVc= diff --git a/vendor/github.com/gobuffalo/flect/azure-pipelines.yml b/vendor/github.com/gobuffalo/flect/azure-pipelines.yml deleted file mode 100644 index 417e2c579..000000000 --- a/vendor/github.com/gobuffalo/flect/azure-pipelines.yml +++ /dev/null @@ -1,71 +0,0 @@ -variables: - GOBIN: "$(GOPATH)/bin" # Go binaries path - GOPATH: "$(system.defaultWorkingDirectory)/gopath" # Go workspace path - modulePath: "$(GOPATH)/src/github.com/$(build.repository.name)" # Path to the module"s code - -jobs: -- job: Windows - pool: - vmImage: "vs2017-win2016" - strategy: - matrix: - go 1.10: - go_version: "1.10" - go 1.11 (on): - go_version: "1.11.5" - GO111MODULE: "on" - go 1.11 (off): - go_version: "1.11.5" - GO111MODULE: "off" - go 1.12 (on): - go_version: "1.12" - GO111MODULE: "on" - go 1.12 (off): - go_version: "1.12" - GO111MODULE: "off" - steps: - - template: azure-tests.yml - -- job: macOS - pool: - vmImage: "macOS-10.13" - strategy: - matrix: - go 1.10: - go_version: "1.10" - go 1.11 (on): - go_version: "1.11.5" - GO111MODULE: "on" - go 1.11 (off): - go_version: "1.11.5" - GO111MODULE: "off" - go 1.12 (on): - go_version: "1.12" - GO111MODULE: "on" - go 1.12 (off): - go_version: "1.12" - GO111MODULE: "off" - steps: - - template: azure-tests.yml - -- job: Linux - pool: - vmImage: "ubuntu-16.04" - strategy: - matrix: - go 1.10: - go_version: "1.10" - go 1.11 (on): - go_version: "1.11.5" - GO111MODULE: "on" - go 1.11 (off): - go_version: "1.11.5" - GO111MODULE: "off" - go 1.12 (on): - go_version: "1.12" - GO111MODULE: "on" - go 1.12 (off): - go_version: "1.12" - GO111MODULE: "off" - steps: - - template: azure-tests.yml diff --git a/vendor/github.com/gobuffalo/flect/azure-tests.yml b/vendor/github.com/gobuffalo/flect/azure-tests.yml deleted file mode 100644 index eea5822fa..000000000 --- a/vendor/github.com/gobuffalo/flect/azure-tests.yml +++ /dev/null @@ -1,19 +0,0 @@ -steps: - - task: GoTool@0 - inputs: - version: $(go_version) - - task: Bash@3 - inputs: - targetType: inline - script: | - mkdir -p "$(GOBIN)" - mkdir -p "$(GOPATH)/pkg" - mkdir -p "$(modulePath)" - shopt -s extglob - mv !(gopath) "$(modulePath)" - displayName: "Setup Go Workspace" - - script: | - go get -t -v ./... - go test -race ./... - workingDirectory: "$(modulePath)" - displayName: "Tests" diff --git a/vendor/github.com/gobuffalo/flect/capitalize.go b/vendor/github.com/gobuffalo/flect/capitalize.go index 42ecc166c..78334fc0f 100644 --- a/vendor/github.com/gobuffalo/flect/capitalize.go +++ b/vendor/github.com/gobuffalo/flect/capitalize.go @@ -15,13 +15,10 @@ func Capitalize(s string) string { // bob dylan = Bob dylan // widget_id = Widget_id func (i Ident) Capitalize() Ident { - var x string if len(i.Parts) == 0 { return New("") } - x = string(unicode.ToTitle(rune(i.Original[0]))) - if len(i.Original) > 1 { - x += i.Original[1:] - } - return New(x) + runes := []rune(i.Original) + runes[0] = unicode.ToTitle(runes[0]) + return New(string(runes)) } diff --git a/vendor/github.com/gobuffalo/flect/go.mod b/vendor/github.com/gobuffalo/flect/go.mod index cd02d074b..7c8d049ab 100644 --- a/vendor/github.com/gobuffalo/flect/go.mod +++ b/vendor/github.com/gobuffalo/flect/go.mod @@ -1,8 +1,5 @@ module github.com/gobuffalo/flect -go 1.12 +go 1.13 -require ( - github.com/davecgh/go-spew v1.1.1 // indirect - github.com/stretchr/testify v1.3.0 -) +require github.com/stretchr/testify v1.4.0 diff --git a/vendor/github.com/gobuffalo/flect/go.sum b/vendor/github.com/gobuffalo/flect/go.sum index 4f76e62c1..8fdee5854 100644 --- a/vendor/github.com/gobuffalo/flect/go.sum +++ b/vendor/github.com/gobuffalo/flect/go.sum @@ -1,9 +1,11 @@ github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= -github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q= -github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk= +github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= diff --git a/vendor/github.com/gobuffalo/flect/humanize.go b/vendor/github.com/gobuffalo/flect/humanize.go index ded093970..6a0b75af7 100644 --- a/vendor/github.com/gobuffalo/flect/humanize.go +++ b/vendor/github.com/gobuffalo/flect/humanize.go @@ -7,11 +7,11 @@ import ( // Humanize returns first letter of sentence capitalized. // Common acronyms are capitalized as well. // Other capital letters in string are left as provided. -// employee_salary = Employee salary -// employee_id = employee ID -// employee_mobile_number = Employee mobile number -// first_Name = First Name -// firstName = First Name +// employee_salary = Employee salary +// employee_id = employee ID +// employee_mobile_number = Employee mobile number +// first_Name = First Name +// firstName = First Name func Humanize(s string) string { return New(s).Humanize().String() } diff --git a/vendor/github.com/gobuffalo/flect/ident.go b/vendor/github.com/gobuffalo/flect/ident.go index 78b51d457..9189e9a39 100644 --- a/vendor/github.com/gobuffalo/flect/ident.go +++ b/vendor/github.com/gobuffalo/flect/ident.go @@ -38,9 +38,9 @@ func toParts(s string) []string { return []string{strings.ToUpper(s)} } var prev rune - var x string + var x strings.Builder + x.Grow(len(s)) for _, c := range s { - cs := string(c) // fmt.Println("### cs ->", cs) // fmt.Println("### unicode.IsControl(c) ->", unicode.IsControl(c)) // fmt.Println("### unicode.IsDigit(c) ->", unicode.IsDigit(c)) @@ -58,35 +58,38 @@ func toParts(s string) []string { } if isSpace(c) { - parts = xappend(parts, x) - x = cs + parts = xappend(parts, x.String()) + x.Reset() + x.WriteRune(c) prev = c continue } if unicode.IsUpper(c) && !unicode.IsUpper(prev) { - parts = xappend(parts, x) - x = cs + parts = xappend(parts, x.String()) + x.Reset() + x.WriteRune(c) prev = c continue } - if unicode.IsUpper(c) && baseAcronyms[strings.ToUpper(x)] { - parts = xappend(parts, x) - x = cs + if unicode.IsUpper(c) && baseAcronyms[strings.ToUpper(x.String())] { + parts = xappend(parts, x.String()) + x.Reset() + x.WriteRune(c) prev = c continue } if unicode.IsLetter(c) || unicode.IsDigit(c) || unicode.IsPunct(c) || c == '`' { prev = c - x += cs + x.WriteRune(c) continue } - parts = xappend(parts, x) - x = "" + parts = xappend(parts, x.String()) + x.Reset() prev = c } - parts = xappend(parts, x) + parts = xappend(parts, x.String()) return parts } @@ -94,6 +97,19 @@ func toParts(s string) []string { var _ encoding.TextUnmarshaler = &Ident{} var _ encoding.TextMarshaler = &Ident{} +// LastPart returns the last part/word of the original string +func (i *Ident) LastPart() string { + if len(i.Parts) == 0 { + return "" + } + return i.Parts[len(i.Parts)-1] +} + +// ReplaceSuffix creates a new Ident with the original suffix replaced by new +func (i Ident) ReplaceSuffix(orig, new string) Ident { + return New(strings.TrimSuffix(i.Original, orig) + new) +} + //UnmarshalText unmarshalls byte array into the Ident func (i *Ident) UnmarshalText(data []byte) error { (*i) = New(string(data)) diff --git a/vendor/github.com/gobuffalo/flect/plural_rules.go b/vendor/github.com/gobuffalo/flect/plural_rules.go index 86fca8c5f..8cd3ba72e 100644 --- a/vendor/github.com/gobuffalo/flect/plural_rules.go +++ b/vendor/github.com/gobuffalo/flect/plural_rules.go @@ -40,6 +40,7 @@ var singleToPlural = map[string]string{ "bus": "buses", "campus": "campuses", "caucus": "caucuses", + "child": "children", "château": "châteaux", "circus": "circuses", "codex": "codices", @@ -48,7 +49,6 @@ var singleToPlural = map[string]string{ "crisis": "crises", "curriculum": "curriculums", "datum": "data", - "dear": "dear", "deer": "deer", "diagnosis": "diagnoses", "die": "dice", @@ -105,11 +105,13 @@ var singleToPlural = map[string]string{ "prognosis": "prognoses", "prometheus": "prometheuses", "quiz": "quizzes", + "quota": "quotas", "radius": "radiuses", "referendum": "referendums", "ress": "resses", "rice": "rice", "salmon": "salmon", + "sex": "sexes", "series": "series", "sheep": "sheep", "shoe": "shoes", @@ -120,6 +122,7 @@ var singleToPlural = map[string]string{ "swine": "swine", "syllabus": "syllabi", "symposium": "symposiums", + "synapse": "synapses", "synopsis": "synopses", "tableau": "tableaus", "testis": "testes", @@ -128,12 +131,14 @@ var singleToPlural = map[string]string{ "tooth": "teeth", "trout": "trout", "tuna": "tuna", + "vedalia": "vedalias", "vertebra": "vertebrae", "vertix": "vertices", "vita": "vitae", "vortex": "vortices", "wharf": "wharves", "wife": "wives", + "woman": "women", "wolf": "wolves", "you": "you", } @@ -160,7 +165,6 @@ var singularToPluralSuffixList = []singularToPluralSuffix{ {"randum", "randa"}, {"actus", "acti"}, {"adium", "adia"}, - {"alias", "aliases"}, {"basis", "basis"}, {"child", "children"}, {"chive", "chives"}, @@ -168,6 +172,7 @@ var singularToPluralSuffixList = []singularToPluralSuffix{ {"hello", "hellos"}, {"jeans", "jeans"}, {"louse", "lice"}, + {"media", "media"}, {"mouse", "mice"}, {"movie", "movies"}, {"oasis", "oasis"}, @@ -251,12 +256,10 @@ var singularToPluralSuffixList = []singularToPluralSuffix{ {"io", "ios"}, {"jy", "jies"}, {"ky", "kies"}, - {"ld", "ldren"}, {"lf", "lves"}, {"ly", "lies"}, {"my", "mies"}, {"ny", "nies"}, - {"ox", "oxen"}, {"py", "pies"}, {"qy", "qies"}, {"rf", "rves"}, diff --git a/vendor/github.com/gobuffalo/flect/pluralize.go b/vendor/github.com/gobuffalo/flect/pluralize.go index 1b9d43e46..e265f84e9 100644 --- a/vendor/github.com/gobuffalo/flect/pluralize.go +++ b/vendor/github.com/gobuffalo/flect/pluralize.go @@ -15,12 +15,22 @@ func Pluralize(s string) string { return New(s).Pluralize().String() } +// PluralizeWithSize will pluralize a string taking a number number into account. +// PluralizeWithSize("user", 1) = user +// PluralizeWithSize("user", 2) = users +func PluralizeWithSize(s string, i int) string { + if i == 1 || i == -1 { + return New(s).Singularize().String() + } + return New(s).Pluralize().String() +} + // Pluralize returns a plural version of the string // user = users // person = people // datum = data func (i Ident) Pluralize() Ident { - s := i.Original + s := i.LastPart() if len(s) == 0 { return New("") } @@ -33,11 +43,11 @@ func (i Ident) Pluralize() Ident { return i } if p, ok := singleToPlural[ls]; ok { - return New(p) + return i.ReplaceSuffix(s, p) } for _, r := range pluralRules { if strings.HasSuffix(ls, r.suffix) { - return New(r.fn(s)) + return i.ReplaceSuffix(s, r.fn(s)) } } diff --git a/vendor/github.com/gobuffalo/flect/singularize.go b/vendor/github.com/gobuffalo/flect/singularize.go index a0f8545ef..1ed499505 100644 --- a/vendor/github.com/gobuffalo/flect/singularize.go +++ b/vendor/github.com/gobuffalo/flect/singularize.go @@ -15,6 +15,16 @@ func Singularize(s string) string { return New(s).Singularize().String() } +// SingularizeWithSize will singular a string taking a number number into account. +// SingularizeWithSize("user", 1) = user +// SingularizeWithSize("user", 2) = users +func SingularizeWithSize(s string, i int) string { + if i == 1 || i == -1 { + return New(s).Singularize().String() + } + return New(s).Pluralize().String() +} + // Singularize returns a singular version of the string // users = user // data = datum diff --git a/vendor/github.com/gobuffalo/flect/underscore.go b/vendor/github.com/gobuffalo/flect/underscore.go index b92488aa0..e1466d99b 100644 --- a/vendor/github.com/gobuffalo/flect/underscore.go +++ b/vendor/github.com/gobuffalo/flect/underscore.go @@ -18,16 +18,17 @@ func Underscore(s string) string { // Nice to see you! = nice_to_see_you // widgetID = widget_id func (i Ident) Underscore() Ident { - var out []string + out := make([]string, 0, len(i.Parts)) for _, part := range i.Parts { - var x string + var x strings.Builder + x.Grow(len(part)) for _, c := range part { if unicode.IsLetter(c) || unicode.IsDigit(c) { - x += string(c) + x.WriteRune(c) } } - if x != "" { - out = append(out, x) + if x.Len() > 0 { + out = append(out, x.String()) } } return New(strings.ToLower(strings.Join(out, "_"))) diff --git a/vendor/github.com/mattn/go-colorable/.travis.yml b/vendor/github.com/mattn/go-colorable/.travis.yml index 98db8f060..7942c565c 100644 --- a/vendor/github.com/mattn/go-colorable/.travis.yml +++ b/vendor/github.com/mattn/go-colorable/.travis.yml @@ -1,9 +1,15 @@ language: go +sudo: false go: + - 1.13.x - tip before_install: - - go get github.com/mattn/goveralls - - go get golang.org/x/tools/cmd/cover + - go get -t -v ./... + script: - - $HOME/gopath/bin/goveralls -repotoken xnXqRGwgW3SXIguzxf90ZSK1GPYZPaGrw + - ./go.test.sh + +after_success: + - bash <(curl -s https://codecov.io/bash) + diff --git a/vendor/github.com/mattn/go-colorable/README.md b/vendor/github.com/mattn/go-colorable/README.md index 56729a92c..e055952b6 100644 --- a/vendor/github.com/mattn/go-colorable/README.md +++ b/vendor/github.com/mattn/go-colorable/README.md @@ -1,8 +1,8 @@ # go-colorable -[![Godoc Reference](https://godoc.org/github.com/mattn/go-colorable?status.svg)](http://godoc.org/github.com/mattn/go-colorable) [![Build Status](https://travis-ci.org/mattn/go-colorable.svg?branch=master)](https://travis-ci.org/mattn/go-colorable) -[![Coverage Status](https://coveralls.io/repos/github/mattn/go-colorable/badge.svg?branch=master)](https://coveralls.io/github/mattn/go-colorable?branch=master) +[![Codecov](https://codecov.io/gh/mattn/go-colorable/branch/master/graph/badge.svg)](https://codecov.io/gh/mattn/go-colorable) +[![GoDoc](https://godoc.org/github.com/mattn/go-colorable?status.svg)](http://godoc.org/github.com/mattn/go-colorable) [![Go Report Card](https://goreportcard.com/badge/mattn/go-colorable)](https://goreportcard.com/report/mattn/go-colorable) Colorable writer for windows. diff --git a/vendor/github.com/mattn/go-colorable/colorable_appengine.go b/vendor/github.com/mattn/go-colorable/colorable_appengine.go index 0b0aef837..1f7806fe1 100644 --- a/vendor/github.com/mattn/go-colorable/colorable_appengine.go +++ b/vendor/github.com/mattn/go-colorable/colorable_appengine.go @@ -27,3 +27,11 @@ func NewColorableStdout() io.Writer { func NewColorableStderr() io.Writer { return os.Stderr } + +// EnableColorsStdout enable colors if possible. +func EnableColorsStdout(enabled *bool) func() { + if enabled != nil { + *enabled = true + } + return func() {} +} diff --git a/vendor/github.com/mattn/go-colorable/colorable_others.go b/vendor/github.com/mattn/go-colorable/colorable_others.go index 3fb771dcc..08cbd1e0f 100644 --- a/vendor/github.com/mattn/go-colorable/colorable_others.go +++ b/vendor/github.com/mattn/go-colorable/colorable_others.go @@ -28,3 +28,11 @@ func NewColorableStdout() io.Writer { func NewColorableStderr() io.Writer { return os.Stderr } + +// EnableColorsStdout enable colors if possible. +func EnableColorsStdout(enabled *bool) func() { + if enabled != nil { + *enabled = true + } + return func() {} +} diff --git a/vendor/github.com/mattn/go-colorable/colorable_windows.go b/vendor/github.com/mattn/go-colorable/colorable_windows.go index 1bd628f25..41215d7fc 100644 --- a/vendor/github.com/mattn/go-colorable/colorable_windows.go +++ b/vendor/github.com/mattn/go-colorable/colorable_windows.go @@ -10,6 +10,7 @@ import ( "os" "strconv" "strings" + "sync" "syscall" "unsafe" @@ -27,6 +28,9 @@ const ( backgroundRed = 0x40 backgroundIntensity = 0x80 backgroundMask = (backgroundRed | backgroundBlue | backgroundGreen | backgroundIntensity) + commonLvbUnderscore = 0x8000 + + cENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x4 ) const ( @@ -78,6 +82,8 @@ var ( procGetConsoleCursorInfo = kernel32.NewProc("GetConsoleCursorInfo") procSetConsoleCursorInfo = kernel32.NewProc("SetConsoleCursorInfo") procSetConsoleTitle = kernel32.NewProc("SetConsoleTitleW") + procGetConsoleMode = kernel32.NewProc("GetConsoleMode") + procSetConsoleMode = kernel32.NewProc("SetConsoleMode") procCreateConsoleScreenBuffer = kernel32.NewProc("CreateConsoleScreenBuffer") ) @@ -89,6 +95,7 @@ type Writer struct { oldattr word oldpos coord rest bytes.Buffer + mutex sync.Mutex } // NewColorable returns new instance of Writer which handles escape sequence from File. @@ -98,6 +105,10 @@ func NewColorable(file *os.File) io.Writer { } if isatty.IsTerminal(file.Fd()) { + var mode uint32 + if r, _, _ := procGetConsoleMode.Call(file.Fd(), uintptr(unsafe.Pointer(&mode))); r != 0 && mode&cENABLE_VIRTUAL_TERMINAL_PROCESSING != 0 { + return file + } var csbi consoleScreenBufferInfo handle := syscall.Handle(file.Fd()) procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) @@ -424,6 +435,8 @@ func atoiWithDefault(s string, def int) (int, error) { // Write writes data on console func (w *Writer) Write(data []byte) (n int, err error) { + w.mutex.Lock() + defer w.mutex.Unlock() var csbi consoleScreenBufferInfo procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) @@ -675,14 +688,19 @@ loop: switch { case n == 0 || n == 100: attr = w.oldattr - case 1 <= n && n <= 5: - attr |= foregroundIntensity - case n == 7: - attr = ((attr & foregroundMask) << 4) | ((attr & backgroundMask) >> 4) - case n == 22 || n == 25: + case n == 4: + attr |= commonLvbUnderscore + case (1 <= n && n <= 3) || n == 5: attr |= foregroundIntensity - case n == 27: - attr = ((attr & foregroundMask) << 4) | ((attr & backgroundMask) >> 4) + case n == 7 || n == 27: + attr = + (attr &^ (foregroundMask | backgroundMask)) | + ((attr & foregroundMask) << 4) | + ((attr & backgroundMask) >> 4) + case n == 22: + attr &^= foregroundIntensity + case n == 24: + attr &^= commonLvbUnderscore case 30 <= n && n <= 37: attr &= backgroundMask if (n-30)&1 != 0 { @@ -701,7 +719,7 @@ loop: n256setup() } attr &= backgroundMask - attr |= n256foreAttr[n256] + attr |= n256foreAttr[n256%len(n256foreAttr)] i += 2 } } else if len(token) == 5 && token[i+1] == "2" { @@ -743,7 +761,7 @@ loop: n256setup() } attr &= foregroundMask - attr |= n256backAttr[n256] + attr |= n256backAttr[n256%len(n256backAttr)] i += 2 } } else if len(token) == 5 && token[i+1] == "2" { @@ -1003,3 +1021,23 @@ func n256setup() { n256backAttr[i] = c.backgroundAttr() } } + +// EnableColorsStdout enable colors if possible. +func EnableColorsStdout(enabled *bool) func() { + var mode uint32 + h := os.Stdout.Fd() + if r, _, _ := procGetConsoleMode.Call(h, uintptr(unsafe.Pointer(&mode))); r != 0 { + if r, _, _ = procSetConsoleMode.Call(h, uintptr(mode|cENABLE_VIRTUAL_TERMINAL_PROCESSING)); r != 0 { + if enabled != nil { + *enabled = true + } + return func() { + procSetConsoleMode.Call(h, uintptr(mode)) + } + } + } + if enabled != nil { + *enabled = true + } + return func() {} +} diff --git a/vendor/github.com/mattn/go-colorable/go.mod b/vendor/github.com/mattn/go-colorable/go.mod index ef3ca9d4c..1e590b819 100644 --- a/vendor/github.com/mattn/go-colorable/go.mod +++ b/vendor/github.com/mattn/go-colorable/go.mod @@ -1,3 +1,8 @@ module github.com/mattn/go-colorable -require github.com/mattn/go-isatty v0.0.8 +require ( + github.com/mattn/go-isatty v0.0.12 + golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae // indirect +) + +go 1.13 diff --git a/vendor/github.com/mattn/go-colorable/go.sum b/vendor/github.com/mattn/go-colorable/go.sum index 2c12960ec..cf5b95d97 100644 --- a/vendor/github.com/mattn/go-colorable/go.sum +++ b/vendor/github.com/mattn/go-colorable/go.sum @@ -1,4 +1,5 @@ -github.com/mattn/go-isatty v0.0.5 h1:tHXDdz1cpzGaovsTB+TVB8q90WEokoVmfMqoVcrLUgw= -github.com/mattn/go-isatty v0.0.5/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= -golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223 h1:DH4skfRX4EBpamg7iV4ZlCpblAHI6s6TDM39bFZumv8= -golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHXY= +github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= +golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae h1:/WDfKMnPU+m5M4xB+6x4kaepxRw6jWvR5iDRdvjHgy8= +golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= diff --git a/vendor/github.com/mattn/go-colorable/go.test.sh b/vendor/github.com/mattn/go-colorable/go.test.sh new file mode 100644 index 000000000..012162b07 --- /dev/null +++ b/vendor/github.com/mattn/go-colorable/go.test.sh @@ -0,0 +1,12 @@ +#!/usr/bin/env bash + +set -e +echo "" > coverage.txt + +for d in $(go list ./... | grep -v vendor); do + go test -race -coverprofile=profile.out -covermode=atomic "$d" + if [ -f profile.out ]; then + cat profile.out >> coverage.txt + rm profile.out + fi +done diff --git a/vendor/modules.txt b/vendor/modules.txt index 190fc31ce..4a4668134 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -38,7 +38,7 @@ github.com/go-openapi/jsonreference github.com/go-openapi/spec # github.com/go-openapi/swag v0.19.7 github.com/go-openapi/swag -# github.com/gobuffalo/flect v0.2.0 +# github.com/gobuffalo/flect v0.2.2 github.com/gobuffalo/flect # github.com/gogo/protobuf v1.3.1 github.com/gogo/protobuf/proto @@ -83,7 +83,7 @@ github.com/json-iterator/go github.com/mailru/easyjson/buffer github.com/mailru/easyjson/jlexer github.com/mailru/easyjson/jwriter -# github.com/mattn/go-colorable v0.1.4 +# github.com/mattn/go-colorable v0.1.8 github.com/mattn/go-colorable # github.com/mattn/go-isatty v0.0.12 github.com/mattn/go-isatty @@ -347,7 +347,7 @@ k8s.io/api/scheduling/v1beta1 k8s.io/api/storage/v1 k8s.io/api/storage/v1alpha1 k8s.io/api/storage/v1beta1 -# k8s.io/apiextensions-apiserver v0.20.1 => k8s.io/apiextensions-apiserver v0.20.2 +# k8s.io/apiextensions-apiserver v0.20.2 => k8s.io/apiextensions-apiserver v0.20.2 k8s.io/apiextensions-apiserver/pkg/apis/apiextensions k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1 k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1 @@ -618,7 +618,7 @@ sigs.k8s.io/controller-runtime/pkg/webhook/admission sigs.k8s.io/controller-runtime/pkg/webhook/conversion sigs.k8s.io/controller-runtime/pkg/webhook/internal/certwatcher sigs.k8s.io/controller-runtime/pkg/webhook/internal/metrics -# sigs.k8s.io/controller-tools v0.4.0 +# sigs.k8s.io/controller-tools v0.5.0 ## explicit sigs.k8s.io/controller-tools/cmd/controller-gen sigs.k8s.io/controller-tools/pkg/crd diff --git a/vendor/sigs.k8s.io/controller-tools/pkg/crd/gen.go b/vendor/sigs.k8s.io/controller-tools/pkg/crd/gen.go index c3e2ff7e9..5253977b9 100644 --- a/vendor/sigs.k8s.io/controller-tools/pkg/crd/gen.go +++ b/vendor/sigs.k8s.io/controller-tools/pkg/crd/gen.go @@ -18,7 +18,9 @@ package crd import ( "fmt" + "go/ast" "go/types" + "os" apiext "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" apiextlegacy "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1" @@ -84,6 +86,9 @@ type Generator struct { CRDVersions []string `marker:"crdVersions,optional"` } +func (Generator) CheckFilter() loader.NodeFilter { + return filterTypesForCRDs +} func (Generator) RegisterMarkers(into *markers.Registry) error { return crdmarkers.Register(into) } @@ -156,6 +161,15 @@ func (g Generator) Generate(ctx *genall.GenerationContext) error { } for i, crd := range versionedCRDs { + // defaults are not allowed to be specified in v1beta1 CRDs and + // decriptions are not allowed on the metadata regardless of version + // strip them before writing to a file + if crdVersions[i] == "v1beta1" { + removeDefaultsFromSchemas(crd.(*apiextlegacy.CustomResourceDefinition)) + removeDescriptionFromMetadataLegacy(crd.(*apiextlegacy.CustomResourceDefinition)) + } else { + removeDescriptionFromMetadata(crd.(*apiext.CustomResourceDefinition)) + } var fileName string if i == 0 { fileName = fmt.Sprintf("%s_%s.yaml", crdRaw.Spec.Group, crdRaw.Spec.Names.Plural) @@ -171,6 +185,90 @@ func (g Generator) Generate(ctx *genall.GenerationContext) error { return nil } +func removeDescriptionFromMetadata(crd *apiext.CustomResourceDefinition) { + for _, versionSpec := range crd.Spec.Versions { + if versionSpec.Schema != nil { + removeDescriptionFromMetadataProps(versionSpec.Schema.OpenAPIV3Schema) + } + } +} + +func removeDescriptionFromMetadataProps(v *apiext.JSONSchemaProps) { + if m, ok := v.Properties["metadata"]; ok { + meta := &m + if meta.Description != "" { + meta.Description = "" + v.Properties["metadata"] = m + + } + } +} + +func removeDescriptionFromMetadataLegacy(crd *apiextlegacy.CustomResourceDefinition) { + if crd.Spec.Validation != nil { + removeDescriptionFromMetadataPropsLegacy(crd.Spec.Validation.OpenAPIV3Schema) + } + for _, versionSpec := range crd.Spec.Versions { + if versionSpec.Schema != nil { + removeDescriptionFromMetadataPropsLegacy(versionSpec.Schema.OpenAPIV3Schema) + } + } +} + +func removeDescriptionFromMetadataPropsLegacy(v *apiextlegacy.JSONSchemaProps) { + if m, ok := v.Properties["metadata"]; ok { + meta := &m + if meta.Description != "" { + meta.Description = "" + v.Properties["metadata"] = m + + } + } +} + +// removeDefaultsFromSchemas will remove all instances of default values being +// specified across all defined API versions +func removeDefaultsFromSchemas(crd *apiextlegacy.CustomResourceDefinition) { + if crd.Spec.Validation != nil { + removeDefaultsFromSchemaProps(crd.Spec.Validation.OpenAPIV3Schema) + } + + for _, versionSpec := range crd.Spec.Versions { + if versionSpec.Schema != nil { + removeDefaultsFromSchemaProps(versionSpec.Schema.OpenAPIV3Schema) + } + } +} + +// removeDefaultsFromSchemaProps will recurse into JSONSchemaProps to remove +// all instances of default values being specified +func removeDefaultsFromSchemaProps(v *apiextlegacy.JSONSchemaProps) { + if v == nil { + return + } + + if v.Default != nil { + fmt.Fprintln(os.Stderr, "Warning: default unsupported in CRD version v1beta1, v1 required. Removing defaults.") + } + + // nil-out the default field + v.Default = nil + for name, prop := range v.Properties { + // iter var reference is fine -- we handle the persistence of the modfications on the line below + //nolint:gosec + removeDefaultsFromSchemaProps(&prop) + v.Properties[name] = prop + } + if v.Items != nil { + removeDefaultsFromSchemaProps(v.Items.Schema) + for i := range v.Items.JSONSchemas { + props := v.Items.JSONSchemas[i] + removeDefaultsFromSchemaProps(&props) + v.Items.JSONSchemas[i] = props + } + } +} + // toTrivialVersions strips out all schemata except for the storage schema, // and moves that up into the root object. This makes the CRD compatible // with pre 1.13 clusters. @@ -277,3 +375,22 @@ func FindKubeKinds(parser *Parser, metav1Pkg *loader.Package) map[schema.GroupKi return kubeKinds } + +// filterTypesForCRDs filters out all nodes that aren't used in CRD generation, +// like interfaces and struct fields without JSON tag. +func filterTypesForCRDs(node ast.Node) bool { + switch node := node.(type) { + case *ast.InterfaceType: + // skip interfaces, we never care about references in them + return false + case *ast.StructType: + return true + case *ast.Field: + _, hasTag := loader.ParseAstTag(node.Tag).Lookup("json") + // fields without JSON tags mean we have custom serialization, + // so only visit fields with tags. + return hasTag + default: + return true + } +} diff --git a/vendor/sigs.k8s.io/controller-tools/pkg/crd/known_types.go b/vendor/sigs.k8s.io/controller-tools/pkg/crd/known_types.go index 4649ca3ac..e247dcf4f 100644 --- a/vendor/sigs.k8s.io/controller-tools/pkg/crd/known_types.go +++ b/vendor/sigs.k8s.io/controller-tools/pkg/crd/known_types.go @@ -24,6 +24,14 @@ import ( // KnownPackages overrides types in some comment packages that have custom validation // but don't have validation markers on them (since they're from core Kubernetes). var KnownPackages = map[string]PackageOverride{ + "k8s.io/api/core/v1": func(p *Parser, pkg *loader.Package) { + // Explicit defaulting for the corev1.Protocol type in lieu of https://github.com/kubernetes/enhancements/pull/1928 + p.Schemata[TypeIdent{Name: "Protocol", Package: pkg}] = apiext.JSONSchemaProps{ + Type: "string", + Default: &apiext.JSON{Raw: []byte(`"TCP"`)}, + } + p.AddPackage(pkg) + }, "k8s.io/apimachinery/pkg/apis/meta/v1": func(p *Parser, pkg *loader.Package) { // ObjectMeta is managed by the Kubernetes API server, so no need to diff --git a/vendor/sigs.k8s.io/controller-tools/pkg/crd/markers/validation.go b/vendor/sigs.k8s.io/controller-tools/pkg/crd/markers/validation.go index d765e6d92..5a038e4e6 100644 --- a/vendor/sigs.k8s.io/controller-tools/pkg/crd/markers/validation.go +++ b/vendor/sigs.k8s.io/controller-tools/pkg/crd/markers/validation.go @@ -26,6 +26,10 @@ import ( "sigs.k8s.io/controller-tools/pkg/markers" ) +const ( + SchemalessName = "kubebuilder:validation:Schemaless" +) + // ValidationMarkers lists all available markers that affect CRD schema generation, // except for the few that don't make sense as type-level markers (see FieldOnlyMarkers). // All markers start with `+kubebuilder:validation:`, and continue with their type name. @@ -40,6 +44,8 @@ var ValidationMarkers = mustMakeAllWithPrefix("kubebuilder:validation", markers. ExclusiveMaximum(false), ExclusiveMinimum(false), MultipleOf(0), + MinProperties(0), + MaxProperties(0), // string markers @@ -78,10 +84,21 @@ var FieldOnlyMarkers = []*definitionWithHelp{ must(markers.MakeAnyTypeDefinition("kubebuilder:default", markers.DescribesField, Default{})). WithHelp(Default{}.Help()), - must(markers.MakeDefinition("kubebuilder:pruning:PreserveUnknownFields", markers.DescribesField, XPreserveUnknownFields{})). - WithHelp(XPreserveUnknownFields{}.Help()), must(markers.MakeDefinition("kubebuilder:validation:EmbeddedResource", markers.DescribesField, XEmbeddedResource{})). WithHelp(XEmbeddedResource{}.Help()), + + must(markers.MakeDefinition(SchemalessName, markers.DescribesField, Schemaless{})). + WithHelp(Schemaless{}.Help()), +} + +// ValidationIshMarkers are field-and-type markers that don't fall under the +// :validation: prefix, and/or don't have a name that directly matches their +// type. +var ValidationIshMarkers = []*definitionWithHelp{ + must(markers.MakeDefinition("kubebuilder:pruning:PreserveUnknownFields", markers.DescribesField, XPreserveUnknownFields{})). + WithHelp(XPreserveUnknownFields{}.Help()), + must(markers.MakeDefinition("kubebuilder:pruning:PreserveUnknownFields", markers.DescribesType, XPreserveUnknownFields{})). + WithHelp(XPreserveUnknownFields{}.Help()), } func init() { @@ -99,6 +116,7 @@ func init() { } AllDefinitions = append(AllDefinitions, FieldOnlyMarkers...) + AllDefinitions = append(AllDefinitions, ValidationIshMarkers...) } // +controllertools:marker:generateHelp:category="CRD validation" @@ -106,7 +124,7 @@ func init() { type Maximum int // +controllertools:marker:generateHelp:category="CRD validation" -// Minimum specifies the minimum numeric value that this field can have. +// Minimum specifies the minimum numeric value that this field can have. Negative integers are supported. type Minimum int // +controllertools:marker:generateHelp:category="CRD validation" @@ -145,6 +163,14 @@ type MinItems int // UniqueItems specifies that all items in this list must be unique. type UniqueItems bool +// +controllertools:marker:generateHelp:category="CRD validation" +// MaxProperties restricts the number of keys in an object +type MaxProperties int + +// +controllertools:marker:generateHelp:category="CRD validation" +// MinProperties restricts the number of keys in an object +type MinProperties int + // +controllertools:marker:generateHelp:category="CRD validation" // Enum specifies that this (scalar) field is restricted to the *exact* values specified here. type Enum []interface{} @@ -191,6 +217,10 @@ type Default struct { // if nested properties or additionalProperties are specified in the schema. // This can either be true or undefined. False // is forbidden. +// +// NB: The kubebuilder:validation:XPreserveUnknownFields variant is deprecated +// in favor of the kubebuilder:pruning:PreserveUnknownFields variant. They function +// identically. type XPreserveUnknownFields struct{} // +controllertools:marker:generateHelp:category="CRD validation" @@ -202,6 +232,16 @@ type XPreserveUnknownFields struct{} // field, yet it is possible. This can be combined with PreserveUnknownFields. type XEmbeddedResource struct{} +// +controllertools:marker:generateHelp:category="CRD validation" +// Schemaless marks a field as being a schemaless object. +// +// Schemaless objects are not introspected, so you must provide +// any type and validation information yourself. One use for this +// tag is for embedding fields that hold JSONSchema typed objects. +// Because this field disables all type checking, it is recommended +// to be used only as a last resort. +type Schemaless struct{} + func (m Maximum) ApplyToSchema(schema *apiext.JSONSchemaProps) error { if schema.Type != "integer" { return fmt.Errorf("must apply maximum to an integer") @@ -289,6 +329,24 @@ func (m UniqueItems) ApplyToSchema(schema *apiext.JSONSchemaProps) error { return nil } +func (m MinProperties) ApplyToSchema(schema *apiext.JSONSchemaProps) error { + if schema.Type != "object" { + return fmt.Errorf("must apply minproperties to an object") + } + val := int64(m) + schema.MinProperties = &val + return nil +} + +func (m MaxProperties) ApplyToSchema(schema *apiext.JSONSchemaProps) error { + if schema.Type != "object" { + return fmt.Errorf("must apply maxproperties to an object") + } + val := int64(m) + schema.MaxProperties = &val + return nil +} + func (m Enum) ApplyToSchema(schema *apiext.JSONSchemaProps) error { // TODO(directxman12): this is a bit hacky -- we should // probably support AnyType better + using the schema structure diff --git a/vendor/sigs.k8s.io/controller-tools/pkg/crd/markers/zz_generated.markerhelp.go b/vendor/sigs.k8s.io/controller-tools/pkg/crd/markers/zz_generated.markerhelp.go index 152432bee..7c6aca4e1 100644 --- a/vendor/sigs.k8s.io/controller-tools/pkg/crd/markers/zz_generated.markerhelp.go +++ b/vendor/sigs.k8s.io/controller-tools/pkg/crd/markers/zz_generated.markerhelp.go @@ -139,6 +139,17 @@ func (MaxLength) Help() *markers.DefinitionHelp { } } +func (MaxProperties) Help() *markers.DefinitionHelp { + return &markers.DefinitionHelp{ + Category: "CRD validation", + DetailedHelp: markers.DetailedHelp{ + Summary: "restricts the number of keys in an object", + Details: "", + }, + FieldHelp: map[string]markers.DetailedHelp{}, + } +} + func (Maximum) Help() *markers.DefinitionHelp { return &markers.DefinitionHelp{ Category: "CRD validation", @@ -172,11 +183,22 @@ func (MinLength) Help() *markers.DefinitionHelp { } } +func (MinProperties) Help() *markers.DefinitionHelp { + return &markers.DefinitionHelp{ + Category: "CRD validation", + DetailedHelp: markers.DetailedHelp{ + Summary: "restricts the number of keys in an object", + Details: "", + }, + FieldHelp: map[string]markers.DetailedHelp{}, + } +} + func (Minimum) Help() *markers.DefinitionHelp { return &markers.DefinitionHelp{ Category: "CRD validation", DetailedHelp: markers.DetailedHelp{ - Summary: "specifies the minimum numeric value that this field can have.", + Summary: "specifies the minimum numeric value that this field can have. Negative integers are supported.", Details: "", }, FieldHelp: map[string]markers.DetailedHelp{}, @@ -284,6 +306,17 @@ func (Resource) Help() *markers.DefinitionHelp { } } +func (Schemaless) Help() *markers.DefinitionHelp { + return &markers.DefinitionHelp{ + Category: "CRD validation", + DetailedHelp: markers.DetailedHelp{ + Summary: "marks a field as being a schemaless object. ", + Details: "Schemaless objects are not introspected, so you must provide any type and validation information yourself. One use for this tag is for embedding fields that hold JSONSchema typed objects. Because this field disables all type checking, it is recommended to be used only as a last resort.", + }, + FieldHelp: map[string]markers.DetailedHelp{}, + } +} + func (SkipVersion) Help() *markers.DefinitionHelp { return &markers.DefinitionHelp{ Category: "CRD", @@ -401,7 +434,7 @@ func (XPreserveUnknownFields) Help() *markers.DefinitionHelp { Category: "CRD processing", DetailedHelp: markers.DetailedHelp{ Summary: "PreserveUnknownFields stops the apiserver from pruning fields which are not specified. ", - Details: "By default the apiserver drops unknown fields from the request payload during the decoding step. This marker stops the API server from doing so. It affects fields recursively, but switches back to normal pruning behaviour if nested properties or additionalProperties are specified in the schema. This can either be true or undefined. False is forbidden.", + Details: "By default the apiserver drops unknown fields from the request payload during the decoding step. This marker stops the API server from doing so. It affects fields recursively, but switches back to normal pruning behaviour if nested properties or additionalProperties are specified in the schema. This can either be true or undefined. False is forbidden. \n NB: The kubebuilder:validation:XPreserveUnknownFields variant is deprecated in favor of the kubebuilder:pruning:PreserveUnknownFields variant. They function identically.", }, FieldHelp: map[string]markers.DetailedHelp{}, } diff --git a/vendor/sigs.k8s.io/controller-tools/pkg/crd/parser.go b/vendor/sigs.k8s.io/controller-tools/pkg/crd/parser.go index 46aba45cd..60bea3295 100644 --- a/vendor/sigs.k8s.io/controller-tools/pkg/crd/parser.go +++ b/vendor/sigs.k8s.io/controller-tools/pkg/crd/parser.go @@ -18,7 +18,6 @@ package crd import ( "fmt" - "go/ast" apiext "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" "k8s.io/apimachinery/pkg/runtime/schema" @@ -216,7 +215,7 @@ func (p *Parser) AddPackage(pkg *loader.Package) { return } p.indexTypes(pkg) - p.Checker.Check(pkg, filterTypesForCRDs) + p.Checker.Check(pkg) p.packages[pkg] = struct{}{} } @@ -236,22 +235,3 @@ func (p *Parser) NeedPackage(pkg *loader.Package) { } p.AddPackage(pkg) } - -// filterTypesForCRDs filters out all nodes that aren't used in CRD generation, -// like interfaces and struct fields without JSON tag. -func filterTypesForCRDs(node ast.Node) bool { - switch node := node.(type) { - case *ast.InterfaceType: - // skip interfaces, we never care about references in them - return false - case *ast.StructType: - return true - case *ast.Field: - _, hasTag := loader.ParseAstTag(node.Tag).Lookup("json") - // fields without JSON tags mean we have custom serialization, - // so only visit fields with tags. - return hasTag - default: - return true - } -} diff --git a/vendor/sigs.k8s.io/controller-tools/pkg/crd/schema.go b/vendor/sigs.k8s.io/controller-tools/pkg/crd/schema.go index 20394a42b..0f682808b 100644 --- a/vendor/sigs.k8s.io/controller-tools/pkg/crd/schema.go +++ b/vendor/sigs.k8s.io/controller-tools/pkg/crd/schema.go @@ -19,11 +19,11 @@ package crd import ( "fmt" "go/ast" - "go/token" "go/types" "strings" apiext "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" + crdmarkers "sigs.k8s.io/controller-tools/pkg/crd/markers" "sigs.k8s.io/controller-tools/pkg/loader" "sigs.k8s.io/controller-tools/pkg/markers" @@ -109,11 +109,6 @@ func (c *schemaContext) requestSchema(pkgPath, typeName string) { // infoToSchema creates a schema for the type in the given set of type information. func infoToSchema(ctx *schemaContext) *apiext.JSONSchemaProps { - if obj := ctx.pkg.Types.Scope().Lookup(ctx.info.Name); obj != nil && implementsJSONMarshaler(obj.Type()) { - schema := &apiext.JSONSchemaProps{Type: "Any"} - applyMarkers(ctx, ctx.info.Markers, schema, ctx.info.RawSpec.Type) - return schema - } return typeToSchema(ctx, ctx.info.RawSpec.Type) } @@ -384,7 +379,12 @@ func structToSchema(ctx *schemaContext, structType *ast.StructType) *apiext.JSON } } - propSchema := typeToSchema(ctx.ForInfo(&markers.TypeInfo{}), field.RawField.Type) + var propSchema *apiext.JSONSchemaProps + if field.Markers.Get(crdmarkers.SchemalessName) != nil { + propSchema = &apiext.JSONSchemaProps{} + } else { + propSchema = typeToSchema(ctx.ForInfo(&markers.TypeInfo{}), field.RawField.Type) + } propSchema.Description = field.Doc applyMarkers(ctx, field.Markers, propSchema, field.RawField) @@ -431,16 +431,3 @@ func builtinToType(basic *types.Basic, allowDangerousTypes bool) (typ string, fo return typ, format, nil } - -// Open coded go/types representation of encoding/json.Marshaller -var jsonMarshaler = types.NewInterfaceType([]*types.Func{ - types.NewFunc(token.NoPos, nil, "MarshalJSON", - types.NewSignature(nil, nil, - types.NewTuple( - types.NewVar(token.NoPos, nil, "", types.NewSlice(types.Universe.Lookup("byte").Type())), - types.NewVar(token.NoPos, nil, "", types.Universe.Lookup("error").Type())), false)), -}, nil).Complete() - -func implementsJSONMarshaler(typ types.Type) bool { - return types.Implements(typ, jsonMarshaler) || types.Implements(types.NewPointer(typ), jsonMarshaler) -} diff --git a/vendor/sigs.k8s.io/controller-tools/pkg/crd/schema_visitor.go b/vendor/sigs.k8s.io/controller-tools/pkg/crd/schema_visitor.go index c42524ce5..2604d739b 100644 --- a/vendor/sigs.k8s.io/controller-tools/pkg/crd/schema_visitor.go +++ b/vendor/sigs.k8s.io/controller-tools/pkg/crd/schema_visitor.go @@ -27,6 +27,10 @@ type SchemaVisitor interface { // this visitor will be called again with `nil` to indicate that // all children have been visited. If a nil visitor is returned, // children are not visited. + // + // It is *NOT* safe to save references to the given schema. + // Make deepcopies if you need to keep things around beyond + // the lifetime of the call. Visit(schema *apiext.JSONSchemaProps) SchemaVisitor } @@ -102,6 +106,8 @@ func (w schemaWalker) walkSchema(schema *apiext.JSONSchemaProps) { // walkMap walks over values of the given map, saving changes to them. func (w schemaWalker) walkMap(defs map[string]apiext.JSONSchemaProps) { for name, def := range defs { + // this is iter var reference is because we immediately preseve it below + //nolint:gosec w.walkSchema(&def) // make sure the edits actually go through since we can't // take a reference to the value in the map diff --git a/vendor/sigs.k8s.io/controller-tools/pkg/crd/spec.go b/vendor/sigs.k8s.io/controller-tools/pkg/crd/spec.go index e00349a41..d48ce2525 100644 --- a/vendor/sigs.k8s.io/controller-tools/pkg/crd/spec.go +++ b/vendor/sigs.k8s.io/controller-tools/pkg/crd/spec.go @@ -55,7 +55,7 @@ func (p *Parser) NeedCRDFor(groupKind schema.GroupKind, maxDescLen *int) { packages = append(packages, pkg) } - defaultPlural := flect.Pluralize(strings.ToLower(groupKind.Kind)) + defaultPlural := strings.ToLower(flect.Pluralize(groupKind.Kind)) crd := apiext.CustomResourceDefinition{ TypeMeta: metav1.TypeMeta{ APIVersion: apiext.SchemeGroupVersion.String(), diff --git a/vendor/sigs.k8s.io/controller-tools/pkg/deepcopy/gen.go b/vendor/sigs.k8s.io/controller-tools/pkg/deepcopy/gen.go index a10c70589..54a72363b 100644 --- a/vendor/sigs.k8s.io/controller-tools/pkg/deepcopy/gen.go +++ b/vendor/sigs.k8s.io/controller-tools/pkg/deepcopy/gen.go @@ -58,6 +58,14 @@ type Generator struct { Year string `marker:",optional"` } +func (Generator) CheckFilter() loader.NodeFilter { + return func(node ast.Node) bool { + // ignore interfaces + _, isIface := node.(*ast.InterfaceType) + return !isIface + } +} + func (Generator) RegisterMarkers(into *markers.Registry) error { if err := markers.RegisterAll(into, enablePkgMarker, legacyEnablePkgMarker, enableTypeMarker, @@ -144,7 +152,7 @@ func (d Generator) Generate(ctx *genall.GenerationContext) error { } for _, root := range ctx.Roots { - outContents := objGenCtx.GenerateForPackage(root) + outContents := objGenCtx.generateForPackage(root) if outContents == nil { continue } @@ -186,21 +194,17 @@ import ( } -// GenerateForPackage generates DeepCopy and runtime.Object implementations for +// generateForPackage generates DeepCopy and runtime.Object implementations for // types in the given package, writing the formatted result to given writer. // May return nil if source could not be generated. -func (ctx *ObjectGenCtx) GenerateForPackage(root *loader.Package) []byte { +func (ctx *ObjectGenCtx) generateForPackage(root *loader.Package) []byte { allTypes, err := enabledOnPackage(ctx.Collector, root) if err != nil { root.AddError(err) return nil } - ctx.Checker.Check(root, func(node ast.Node) bool { - // ignore interfaces - _, isIface := node.(*ast.InterfaceType) - return !isIface - }) + ctx.Checker.Check(root) root.NeedTypesInfo() diff --git a/vendor/sigs.k8s.io/controller-tools/pkg/deepcopy/traverse.go b/vendor/sigs.k8s.io/controller-tools/pkg/deepcopy/traverse.go index 1c92e48a0..3a751757d 100644 --- a/vendor/sigs.k8s.io/controller-tools/pkg/deepcopy/traverse.go +++ b/vendor/sigs.k8s.io/controller-tools/pkg/deepcopy/traverse.go @@ -197,7 +197,7 @@ func (n *namingInfo) Syntax(basePkg *loader.Package, imports *importsList) strin (&namingInfo{typeInfo: typeInfo.Key()}).Syntax(basePkg, imports), (&namingInfo{typeInfo: typeInfo.Elem()}).Syntax(basePkg, imports)) default: - basePkg.AddError(fmt.Errorf("name requested for invalid type %s", typeInfo)) + basePkg.AddError(fmt.Errorf("name requested for invalid type: %s", typeInfo)) return typeInfo.String() } } @@ -215,7 +215,7 @@ type copyMethodMaker struct { func (c *copyMethodMaker) GenerateMethodsFor(root *loader.Package, info *markers.TypeInfo) { typeInfo := root.TypesInfo.TypeOf(info.RawSpec.Name) if typeInfo == types.Typ[types.Invalid] { - root.AddError(loader.ErrFromNode(fmt.Errorf("unknown type %s", info.Name), info.RawSpec)) + root.AddError(loader.ErrFromNode(fmt.Errorf("unknown type: %s", info.Name), info.RawSpec)) } // figure out if we need to use a pointer receiver -- most types get a pointer receiver, @@ -293,13 +293,18 @@ func (c *copyMethodMaker) genDeepCopyIntoBlock(actualName *namingInfo, typeInfo switch last := last.(type) { case *types.Basic: - // basic types themselves can be "shallow" copied, so all we need - // to do is check if our *actual* type (not the underlying one) has - // a custom method implemented. - if hasMethod, _ := hasDeepCopyMethod(c.pkg, typeInfo); hasMethod { - c.Line("*out = in.DeepCopy()") + switch last.Kind() { + case types.Invalid, types.UnsafePointer: + c.pkg.AddError(fmt.Errorf("invalid type: %s", last)) + default: + // basic types themselves can be "shallow" copied, so all we need + // to do is check if our *actual* type (not the underlying one) has + // a custom method implemented. + if hasMethod, _ := hasDeepCopyMethod(c.pkg, typeInfo); hasMethod { + c.Line("*out = in.DeepCopy()") + } + c.Line("*out = *in") } - c.Line("*out = *in") case *types.Map: c.genMapDeepCopy(actualName, last) case *types.Slice: @@ -312,7 +317,7 @@ func (c *copyMethodMaker) genDeepCopyIntoBlock(actualName *namingInfo, typeInfo // handled via the above loop, should never happen c.pkg.AddError(fmt.Errorf("interface type %s encountered directly, invalid condition", last)) default: - c.pkg.AddError(fmt.Errorf("invalid type %s", last)) + c.pkg.AddError(fmt.Errorf("invalid type: %s", last)) } } @@ -322,7 +327,7 @@ func (c *copyMethodMaker) genMapDeepCopy(actualName *namingInfo, mapType *types. // maps *must* have shallow-copiable types, since we just iterate // through the keys, only trying to deepcopy the values. if !fineToShallowCopy(mapType.Key()) { - c.pkg.AddError(fmt.Errorf("invalid map key type %s", mapType.Key())) + c.pkg.AddError(fmt.Errorf("invalid map key type: %s", mapType.Key())) return } @@ -383,7 +388,7 @@ func (c *copyMethodMaker) genMapDeepCopy(actualName *namingInfo, mapType *types. // structs will have deepcopy generated for them, so use that c.Line("(*out)[key] = *val.DeepCopy()") default: - c.pkg.AddError(fmt.Errorf("invalid map value type %s", underlyingElem)) + c.pkg.AddError(fmt.Errorf("invalid map value type: %s", underlyingElem)) return } } @@ -425,7 +430,7 @@ func (c *copyMethodMaker) genSliceDeepCopy(actualName *namingInfo, sliceType *ty // structs will always have deepcopy c.Linef("(*in)[i].DeepCopyInto(&(*out)[i])") default: - c.pkg.AddError(fmt.Errorf("invalid slice element type %s", underlyingElem)) + c.pkg.AddError(fmt.Errorf("invalid slice element type: %s", underlyingElem)) } }) } @@ -483,7 +488,13 @@ func (c *copyMethodMaker) genStructDeepCopy(_ *namingInfo, structType *types.Str // otherwise... switch underlyingField := underlyingField.(type) { case *types.Basic: - // nothing to do, initial assignment copied this + switch underlyingField.Kind() { + case types.Invalid, types.UnsafePointer: + c.pkg.AddError(loader.ErrFromNode(fmt.Errorf("invalid field type: %s", underlyingField), field)) + return + default: + // nothing to do, initial assignment copied this + } case *types.Struct: if fineToShallowCopy(field.Type()) { c.Linef("out.%[1]s = in.%[1]s", field.Name()) @@ -491,7 +502,7 @@ func (c *copyMethodMaker) genStructDeepCopy(_ *namingInfo, structType *types.Str c.Linef("in.%[1]s.DeepCopyInto(&out.%[1]s)", field.Name()) } default: - c.pkg.AddError(fmt.Errorf("invalid field type %s", underlyingField)) + c.pkg.AddError(loader.ErrFromNode(fmt.Errorf("invalid field type: %s", underlyingField), field)) return } } @@ -542,7 +553,7 @@ func (c *copyMethodMaker) genPointerDeepCopy(_ *namingInfo, pointerType *types.P c.Linef("*out = new(%[1]s)", (&namingInfo{typeInfo: pointerType.Elem()}).Syntax(c.pkg, c.importsList)) c.Line("(*in).DeepCopyInto(*out)") default: - c.pkg.AddError(fmt.Errorf("invalid pointer element type %s", underlyingElem)) + c.pkg.AddError(fmt.Errorf("invalid pointer element type: %s", underlyingElem)) return } } @@ -602,7 +613,7 @@ func shouldBeCopied(pkg *loader.Package, info *markers.TypeInfo) bool { typeInfo := pkg.TypesInfo.TypeOf(info.RawSpec.Name) if typeInfo == types.Typ[types.Invalid] { - pkg.AddError(loader.ErrFromNode(fmt.Errorf("unknown type %s", info.Name), info.RawSpec)) + pkg.AddError(loader.ErrFromNode(fmt.Errorf("unknown type: %s", info.Name), info.RawSpec)) return false } @@ -735,8 +746,14 @@ func eventualUnderlyingType(typeInfo types.Type) types.Type { func fineToShallowCopy(typeInfo types.Type) bool { switch typeInfo := typeInfo.(type) { case *types.Basic: - // basic types (int, string, etc) are always fine to shallow-copy - return true + // basic types (int, string, etc) are always fine to shallow-copy, + // except for Invalid and UnsafePointer, which can't be copied at all. + switch typeInfo.Kind() { + case types.Invalid, types.UnsafePointer: + return false + default: + return true + } case *types.Named: // aliases are fine to shallow-copy as long as they resolve to a shallow-copyable type return fineToShallowCopy(typeInfo.Underlying()) diff --git a/vendor/sigs.k8s.io/controller-tools/pkg/genall/genall.go b/vendor/sigs.k8s.io/controller-tools/pkg/genall/genall.go index 9fcc76236..0206a4afa 100644 --- a/vendor/sigs.k8s.io/controller-tools/pkg/genall/genall.go +++ b/vendor/sigs.k8s.io/controller-tools/pkg/genall/genall.go @@ -46,6 +46,32 @@ func (g Generators) RegisterMarkers(reg *markers.Registry) error { return nil } +// CheckFilters returns the set of NodeFilters for all Generators that +// implement NeedsTypeChecking. +func (g Generators) CheckFilters() []loader.NodeFilter { + var filters []loader.NodeFilter + for _, gen := range g { + withFilter, needsChecking := (*gen).(NeedsTypeChecking) + if !needsChecking { + continue + } + filters = append(filters, withFilter.CheckFilter()) + } + return filters +} + +// NeedsTypeChecking indicates that a particular generator needs & has opinions +// on typechecking. If this is not implemented, a generator will be given a +// context with a nil typechecker. +type NeedsTypeChecking interface { + // CheckFilter indicates the loader.NodeFilter (if any) that should be used + // to prune out unused types/packages when type-checking (nodes for which + // the filter returns true are considered "interesting"). This filter acts + // as a baseline -- all types the pass through this filter will be checked, + // but more than that may also be checked due to other generators' filters. + CheckFilter() loader.NodeFilter +} + // Generator knows how to register some set of markers, and then produce // output artifacts based on loaded code containing those markers, // sharing common loaded data. @@ -144,7 +170,9 @@ func (g Generators) ForRoots(rootPaths ...string) (*Runtime, error) { }, Roots: roots, InputRule: InputFromFileSystem, - Checker: &loader.TypeChecker{}, + Checker: &loader.TypeChecker{ + NodeFilters: g.CheckFilters(), + }, }, OutputRules: OutputRules{Default: OutputToNothing}, } @@ -165,14 +193,23 @@ func (r *Runtime) Run() bool { return true } + hadErrs := false for _, gen := range r.Generators { ctx := r.GenerationContext // make a shallow copy ctx.OutputRule = r.OutputRules.ForGenerator(gen) + + // don't pass a typechecker to generators that don't provide a filter + // to avoid accidents + if _, needsChecking := (*gen).(NeedsTypeChecking); !needsChecking { + ctx.Checker = nil + } + if err := (*gen).Generate(&ctx); err != nil { fmt.Fprintln(os.Stderr, err) + hadErrs = true } } // skip TypeErrors -- they're probably just from partial typechecking in crd-gen - return loader.PrintErrors(r.Roots, packages.TypeError) + return loader.PrintErrors(r.Roots, packages.TypeError) || hadErrs } diff --git a/vendor/sigs.k8s.io/controller-tools/pkg/loader/errors.go b/vendor/sigs.k8s.io/controller-tools/pkg/loader/errors.go index aae8ef39f..5a675798e 100644 --- a/vendor/sigs.k8s.io/controller-tools/pkg/loader/errors.go +++ b/vendor/sigs.k8s.io/controller-tools/pkg/loader/errors.go @@ -18,7 +18,6 @@ package loader import ( "fmt" - "go/ast" "go/token" ) @@ -29,10 +28,15 @@ type PositionedError struct { error } +// Node is the intersection of go/ast.Node and go/types.Var. +type Node interface { + Pos() token.Pos // position of first character belonging to the node +} + // ErrFromNode returns the given error, with additional information // attaching it to the given AST node. It will automatically map // over error lists. -func ErrFromNode(err error, node ast.Node) error { +func ErrFromNode(err error, node Node) error { if asList, isList := err.(ErrList); isList { resList := make(ErrList, len(asList)) for i, baseErr := range asList { diff --git a/vendor/sigs.k8s.io/controller-tools/pkg/loader/refs.go b/vendor/sigs.k8s.io/controller-tools/pkg/loader/refs.go index 9e2989cf5..59ea262bb 100644 --- a/vendor/sigs.k8s.io/controller-tools/pkg/loader/refs.go +++ b/vendor/sigs.k8s.io/controller-tools/pkg/loader/refs.go @@ -185,37 +185,51 @@ func allReferencedPackages(pkg *Package, filterNodes NodeFilter) []*Package { // checking each package's types' externally-referenced types, and only // type-checking those packages. type TypeChecker struct { + // NodeFilters are used to filter the set of references that are followed + // when typechecking. If any of the filters returns true for a given node, + // its package will be added to the set of packages to check. + // + // If no filters are specified, all references are followed (this may be slow). + // + // Modifying this after the first call to check may yield strange/invalid + // results. + NodeFilters []NodeFilter + checkedPackages map[*Package]struct{} - filterNodes NodeFilter sync.Mutex } -// Check type-checks the given package and all packages referenced -// by types that pass through (have true returned by) filterNodes. -func (c *TypeChecker) Check(root *Package, filterNodes NodeFilter) { +// Check type-checks the given package and all packages referenced by types +// that pass through (have true returned by) any of the NodeFilters. +func (c *TypeChecker) Check(root *Package) { c.init() - if filterNodes == nil { - filterNodes = c.filterNodes - } - // use a sub-checker with the appropriate settings (&TypeChecker{ - filterNodes: filterNodes, + NodeFilters: c.NodeFilters, checkedPackages: c.checkedPackages, }).check(root) } -func (c *TypeChecker) init() { - if c.checkedPackages == nil { - c.checkedPackages = make(map[*Package]struct{}) +func (c *TypeChecker) isNodeInteresting(node ast.Node) bool { + // no filters --> everything is important + if len(c.NodeFilters) == 0 { + return true } - if c.filterNodes == nil { - // check every type by default - c.filterNodes = func(_ ast.Node) bool { + + // otherwise, passing through any one filter means this node is important + for _, filter := range c.NodeFilters { + if filter(node) { return true } } + return false +} + +func (c *TypeChecker) init() { + if c.checkedPackages == nil { + c.checkedPackages = make(map[*Package]struct{}) + } } // check recursively type-checks the given package, only loading packages that @@ -232,7 +246,7 @@ func (c *TypeChecker) check(root *Package) { return } - refedPackages := allReferencedPackages(root, c.filterNodes) + refedPackages := allReferencedPackages(root, c.isNodeInteresting) // first, resolve imports for all leaf packages... var wg sync.WaitGroup diff --git a/vendor/sigs.k8s.io/controller-tools/pkg/markers/parse.go b/vendor/sigs.k8s.io/controller-tools/pkg/markers/parse.go index 4034c25ab..fcb33925e 100644 --- a/vendor/sigs.k8s.io/controller-tools/pkg/markers/parse.go +++ b/vendor/sigs.k8s.io/controller-tools/pkg/markers/parse.go @@ -340,8 +340,13 @@ func guessType(scanner *sc.Scanner, raw string, allowSlice bool) *Argument { } } + // then, integers... if !probablyString { - if nextTok := subScanner.Scan(); nextTok == sc.Int { + nextTok := subScanner.Scan() + if nextTok == '-' { + nextTok = subScanner.Scan() + } + if nextTok == sc.Int { return &Argument{Type: IntType} } } @@ -481,11 +486,21 @@ func (a *Argument) parse(scanner *sc.Scanner, raw string, out reflect.Value, inS for tok := scanner.Scan(); tok != sc.EOF; tok = scanner.Scan() { } case IntType: + nextChar := scanner.Peek() + isNegative := false + if nextChar == '-' { + isNegative = true + scanner.Scan() // eat the '-' + } if !expect(scanner, sc.Int, "integer") { return } // TODO(directxman12): respect the size when parsing - val, err := strconv.Atoi(scanner.TokenText()) + text := scanner.TokenText() + if isNegative { + text = "-" + text + } + val, err := strconv.Atoi(text) if err != nil { scanner.Error(scanner, fmt.Sprintf("unable to parse integer: %v", err)) return diff --git a/vendor/sigs.k8s.io/controller-tools/pkg/schemapatcher/gen.go b/vendor/sigs.k8s.io/controller-tools/pkg/schemapatcher/gen.go index 3b233650c..6e71cbcfa 100644 --- a/vendor/sigs.k8s.io/controller-tools/pkg/schemapatcher/gen.go +++ b/vendor/sigs.k8s.io/controller-tools/pkg/schemapatcher/gen.go @@ -32,6 +32,7 @@ import ( crdgen "sigs.k8s.io/controller-tools/pkg/crd" crdmarkers "sigs.k8s.io/controller-tools/pkg/crd/markers" "sigs.k8s.io/controller-tools/pkg/genall" + "sigs.k8s.io/controller-tools/pkg/loader" "sigs.k8s.io/controller-tools/pkg/markers" yamlop "sigs.k8s.io/controller-tools/pkg/schemapatcher/internal/yaml" ) @@ -87,6 +88,10 @@ type Generator struct { var _ genall.Generator = &Generator{} +func (Generator) CheckFilter() loader.NodeFilter { + return crdgen.Generator{}.CheckFilter() +} + func (Generator) RegisterMarkers(into *markers.Registry) error { return crdmarkers.Register(into) } diff --git a/vendor/sigs.k8s.io/controller-tools/pkg/webhook/conv.go b/vendor/sigs.k8s.io/controller-tools/pkg/webhook/conv.go deleted file mode 100644 index e85b06b1a..000000000 --- a/vendor/sigs.k8s.io/controller-tools/pkg/webhook/conv.go +++ /dev/null @@ -1,44 +0,0 @@ -/* -Copyright 2020 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. -*/ - -package webhook - -import ( - admissionregv1 "k8s.io/api/admissionregistration/v1" - admissionregv1beta1 "k8s.io/api/admissionregistration/v1beta1" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" - utilruntime "k8s.io/apimachinery/pkg/util/runtime" -) - -var ( - conversionScheme = runtime.NewScheme() -) - -func init() { - utilruntime.Must(admissionregv1.AddToScheme(conversionScheme)) - utilruntime.Must(admissionregv1beta1.AddToScheme(conversionScheme)) -} - -// MutatingWebhookConfigurationAsVersion converts a MutatingWebhookConfiguration from the canonical internal form (currently v1) to some external form. -func MutatingWebhookConfigurationAsVersion(original *admissionregv1.MutatingWebhookConfiguration, gv schema.GroupVersion) (runtime.Object, error) { - return conversionScheme.ConvertToVersion(original, gv) -} - -// ValidatingWebhookConfigurationAsVersion converts a ValidatingWebhookConfiguration from the canonical internal form (currently v1) to some external form. -func ValidatingWebhookConfigurationAsVersion(original *admissionregv1.ValidatingWebhookConfiguration, gv schema.GroupVersion) (runtime.Object, error) { - return conversionScheme.ConvertToVersion(original, gv) -} diff --git a/vendor/sigs.k8s.io/controller-tools/pkg/webhook/parser.go b/vendor/sigs.k8s.io/controller-tools/pkg/webhook/parser.go index a4c5077fe..30d1360da 100644 --- a/vendor/sigs.k8s.io/controller-tools/pkg/webhook/parser.go +++ b/vendor/sigs.k8s.io/controller-tools/pkg/webhook/parser.go @@ -19,7 +19,7 @@ limitations under the License. // // The markers take the form: // -// +kubebuilder:webhook:webhookVersions=<[]string>,failurePolicy=,matchPolicy=,groups=<[]string>,resources=<[]string>,verbs=<[]string>,versions=<[]string>,name=,path=,mutating=,sideEffects= +// +kubebuilder:webhook:webhookVersions=<[]string>,failurePolicy=,matchPolicy=,groups=<[]string>,resources=<[]string>,verbs=<[]string>,versions=<[]string>,name=,path=,mutating=,sideEffects=,admissionReviewVersions=<[]string> package webhook import ( @@ -27,7 +27,6 @@ import ( "strings" admissionregv1 "k8s.io/api/admissionregistration/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/util/sets" @@ -107,6 +106,12 @@ type Config struct { // WebhookVersions specifies the target API versions of the {Mutating,Validating}WebhookConfiguration objects // itself to generate. Defaults to v1. WebhookVersions []string `marker:"webhookVersions,optional"` + + // AdmissionReviewVersions is an ordered list of preferred `AdmissionReview` + // versions the Webhook expects. + // For generating v1 {Mutating,Validating}WebhookConfiguration, this is mandatory. + // For generating v1beta1 {Mutating,Validating}WebhookConfiguration, this is optional, and default to v1beta1. + AdmissionReviewVersions []string `marker:"admissionReviewVersions,optional"` } // verbToAPIVariant converts a marker's verb to the proper value for the API. @@ -140,15 +145,13 @@ func (c Config) ToMutatingWebhook() (admissionregv1.MutatingWebhook, error) { } return admissionregv1.MutatingWebhook{ - Name: c.Name, - Rules: c.rules(), - FailurePolicy: c.failurePolicy(), - MatchPolicy: matchPolicy, - ClientConfig: c.clientConfig(), - SideEffects: c.sideEffects(), - // TODO(jiachengxu): AdmissionReviewVersions becomes required in admissionregistration/v1, here we default it - // to `v1` and `v1beta1`, and we should support to config the `AdmissionReviewVersions` as a marker. - AdmissionReviewVersions: []string{defaultWebhookVersion, "v1beta1"}, + Name: c.Name, + Rules: c.rules(), + FailurePolicy: c.failurePolicy(), + MatchPolicy: matchPolicy, + ClientConfig: c.clientConfig(), + SideEffects: c.sideEffects(), + AdmissionReviewVersions: c.AdmissionReviewVersions, }, nil } @@ -164,15 +167,13 @@ func (c Config) ToValidatingWebhook() (admissionregv1.ValidatingWebhook, error) } return admissionregv1.ValidatingWebhook{ - Name: c.Name, - Rules: c.rules(), - FailurePolicy: c.failurePolicy(), - MatchPolicy: matchPolicy, - ClientConfig: c.clientConfig(), - SideEffects: c.sideEffects(), - // TODO(jiachengxu): AdmissionReviewVersions becomes required in admissionregistration/v1, here we default it - // to `v1` and `v1beta1`, and we should support to config the `AdmissionReviewVersions` as a marker. - AdmissionReviewVersions: []string{defaultWebhookVersion, "v1beta1"}, + Name: c.Name, + Rules: c.rules(), + FailurePolicy: c.failurePolicy(), + MatchPolicy: matchPolicy, + ClientConfig: c.clientConfig(), + SideEffects: c.sideEffects(), + AdmissionReviewVersions: c.AdmissionReviewVersions, }, nil } @@ -242,10 +243,6 @@ func (c Config) clientConfig() admissionregv1.WebhookClientConfig { Namespace: "system", Path: &path, }, - // OpenAPI marks the field as required before 1.13 because of a bug that got fixed in - // https://github.com/kubernetes/api/commit/e7d9121e9ffd63cea0288b36a82bcc87b073bd1b - // Put "\n" as an placeholder as a workaround til 1.13+ is almost everywhere. - CABundle: []byte("\n"), } } @@ -334,77 +331,63 @@ func (Generator) Generate(ctx *genall.GenerationContext) error { versionedWebhooks := make(map[string][]interface{}, len(supportedWebhookVersions)) for _, version := range supportedWebhookVersions { if cfgs, ok := mutatingCfgs[version]; ok { - objRaw := &admissionregv1.MutatingWebhookConfiguration{ - TypeMeta: metav1.TypeMeta{ - Kind: "MutatingWebhookConfiguration", - APIVersion: admissionregv1.SchemeGroupVersion.String(), - }, - ObjectMeta: metav1.ObjectMeta{ - Name: "mutating-webhook-configuration", - }, - Webhooks: cfgs, - } - // SideEffects in required in admissionregistration/v1, if this is not set or set to `Some` or `Known`, - // we return an error - if version == defaultWebhookVersion { + // All webhook config versions in supportedWebhookVersions have the same general form, with a few + // stricter requirements for v1. Since no conversion scheme exists for webhook configs, the v1 + // type can be used for all versioned types in this context. + objRaw := &admissionregv1.MutatingWebhookConfiguration{} + objRaw.SetGroupVersionKind(schema.GroupVersionKind{ + Group: admissionregv1.SchemeGroupVersion.Group, + Version: version, + Kind: "MutatingWebhookConfiguration", + }) + objRaw.SetName("mutating-webhook-configuration") + objRaw.Webhooks = cfgs + switch version { + case admissionregv1.SchemeGroupVersion.Version: for i := range objRaw.Webhooks { + // SideEffects is required in admissionregistration/v1, if this is not set or set to `Some` or `Known`, + // return an error if err := checkSideEffectsForV1(objRaw.Webhooks[i].SideEffects); err != nil { return err } + // AdmissionReviewVersions is required in admissionregistration/v1, if this is not set, + // return an error + if len(objRaw.Webhooks[i].AdmissionReviewVersions) == 0 { + return fmt.Errorf("AdmissionReviewVersions is mandatory for v1 {Mutating,Validating}WebhookConfiguration") + } } } - // AdmissionReviewVersions is optional in admissionregistration/v1beta1, so let kubernetes to default it. - if version == "v1beta1" { - for i := range objRaw.Webhooks { - objRaw.Webhooks[i].AdmissionReviewVersions = nil - } - } - if version != defaultWebhookVersion { - conv, err := MutatingWebhookConfigurationAsVersion(objRaw, schema.GroupVersion{Group: admissionregv1.SchemeGroupVersion.Group, Version: version}) - versionedWebhooks[version] = append(versionedWebhooks[version], conv) - if err != nil { - return err - } - } else { - versionedWebhooks[version] = append(versionedWebhooks[version], objRaw) - } + versionedWebhooks[version] = append(versionedWebhooks[version], objRaw) } if cfgs, ok := validatingCfgs[version]; ok { - objRaw := &admissionregv1.ValidatingWebhookConfiguration{ - TypeMeta: metav1.TypeMeta{ - Kind: "ValidatingWebhookConfiguration", - APIVersion: admissionregv1.SchemeGroupVersion.String(), - }, - ObjectMeta: metav1.ObjectMeta{ - Name: "validating-webhook-configuration", - }, - Webhooks: cfgs, - } - // SideEffects in required in admissionregistration/v1, if this is not set or set to `Some` or `Known`, - // we return an error - if version == defaultWebhookVersion { + // All webhook config versions in supportedWebhookVersions have the same general form, with a few + // stricter requirements for v1. Since no conversion scheme exists for webhook configs, the v1 + // type can be used for all versioned types in this context. + objRaw := &admissionregv1.ValidatingWebhookConfiguration{} + objRaw.SetGroupVersionKind(schema.GroupVersionKind{ + Group: admissionregv1.SchemeGroupVersion.Group, + Version: version, + Kind: "ValidatingWebhookConfiguration", + }) + objRaw.SetName("validating-webhook-configuration") + objRaw.Webhooks = cfgs + switch version { + case admissionregv1.SchemeGroupVersion.Version: for i := range objRaw.Webhooks { + // SideEffects is required in admissionregistration/v1, if this is not set or set to `Some` or `Known`, + // return an error if err := checkSideEffectsForV1(objRaw.Webhooks[i].SideEffects); err != nil { return err } + // AdmissionReviewVersions is required in admissionregistration/v1, if this is not set, + // return an error + if len(objRaw.Webhooks[i].AdmissionReviewVersions) == 0 { + return fmt.Errorf("AdmissionReviewVersions is mandatory for v1 {Mutating,Validating}WebhookConfiguration") + } } } - // AdmissionReviewVersions is optional in admissionregistration/v1beta1, so let kubernetes to default it. - if version == "v1beta1" { - for i := range objRaw.Webhooks { - objRaw.Webhooks[i].AdmissionReviewVersions = nil - } - } - if version != defaultWebhookVersion { - conv, err := ValidatingWebhookConfigurationAsVersion(objRaw, schema.GroupVersion{Group: admissionregv1.SchemeGroupVersion.Group, Version: version}) - versionedWebhooks[version] = append(versionedWebhooks[version], conv) - if err != nil { - return err - } - } else { - versionedWebhooks[version] = append(versionedWebhooks[version], objRaw) - } + versionedWebhooks[version] = append(versionedWebhooks[version], objRaw) } } diff --git a/vendor/sigs.k8s.io/controller-tools/pkg/webhook/zz_generated.markerhelp.go b/vendor/sigs.k8s.io/controller-tools/pkg/webhook/zz_generated.markerhelp.go index 92d179dcd..84e86cdbb 100644 --- a/vendor/sigs.k8s.io/controller-tools/pkg/webhook/zz_generated.markerhelp.go +++ b/vendor/sigs.k8s.io/controller-tools/pkg/webhook/zz_generated.markerhelp.go @@ -76,6 +76,10 @@ func (Config) Help() *markers.DefinitionHelp { Summary: "specifies the target API versions of the {Mutating,Validating}WebhookConfiguration objects itself to generate. Defaults to v1.", Details: "", }, + "AdmissionReviewVersions": markers.DetailedHelp{ + Summary: "is an ordered list of preferred `AdmissionReview` versions the Webhook expects. For generating v1 {Mutating,Validating}WebhookConfiguration, this is mandatory. For generating v1beta1 {Mutating,Validating}WebhookConfiguration, this is optional, and default to v1beta1.", + Details: "", + }, }, } }