| 1 | /* |
| 2 | Copyright 2018 The Kubernetes Authors. |
| 3 | |
| 4 | Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | you may not use this file except in compliance with the License. |
| 6 | You may obtain a copy of the License at |
| 7 | |
| 8 | http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | |
| 10 | Unless required by applicable law or agreed to in writing, software |
| 11 | distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | See the License for the specific language governing permissions and |
| 14 | limitations under the License. |
| 15 | */ |
| 16 | |
| 17 | package rules |
| 18 | |
| 19 | import ( |
| 20 | "reflect" |
| 21 | "strings" |
| 22 | |
| 23 | "k8s.io/kube-openapi/pkg/util/sets" |
| 24 | |
| 25 | "k8s.io/gengo/v2/types" |
| 26 | ) |
| 27 | |
| 28 | var ( |
| 29 | // Blacklist of JSON tags that should skip match evaluation |
| 30 | jsonTagBlacklist = sets.NewString( |
| 31 | // Omitted field is ignored by the package |
| 32 | "-", |
| 33 | ) |
| 34 | |
| 35 | // List of substrings that aren't allowed in Go name and JSON name |
| 36 | disallowedNameSubstrings = sets.NewString( |
| 37 | // Underscore is not allowed in either name |
| 38 | "_", |
| 39 | // Dash is not allowed in either name. Note that since dash is a valid JSON tag, this should be checked |
| 40 | // after JSON tag blacklist check. |
| 41 | "-", |
| 42 | ) |
| 43 | ) |
| 44 | |
| 45 | /* |
| 46 | NamesMatch implements APIRule interface. |
| 47 | Go field names must be CamelCase. JSON field names must be camelCase. Other than capitalization of the |
| 48 | initial letter, the two should almost always match. No underscores nor dashes in either. |
| 49 | This rule verifies the convention "Other than capitalization of the initial letter, the two should almost always match." |
| 50 | Examples (also in unit test): |
| 51 | |
| 52 | Go name | JSON name | match |
| 53 | podSpec false |
| 54 | PodSpec podSpec true |
| 55 | PodSpec PodSpec false |
| 56 | podSpec podSpec false |
| 57 | PodSpec spec false |
| 58 | Spec podSpec false |
| 59 | JSONSpec jsonSpec true |
| 60 | JSONSpec jsonspec false |
| 61 | HTTPJSONSpec httpJSONSpec true |
| 62 | |
| 63 | NOTE: this validator cannot tell two sequential all-capital words from one word, therefore the case below |
| 64 | is also considered matched. |
| 65 | |
| 66 | HTTPJSONSpec httpjsonSpec true |
| 67 | |
| 68 | NOTE: an empty JSON name is valid only for inlined structs or pointer to structs. |
| 69 | It cannot be empty for anything else because capitalization must be set explicitly. |
| 70 | |
| 71 | NOTE: metav1.ListMeta and metav1.ObjectMeta by convention must have "metadata" as name. |
| 72 | Other fields may have that JSON name if the field name matches. |
| 73 | */ |
| 74 | type NamesMatch struct{} |
| 75 | |
| 76 | // Name returns the name of APIRule |
| 77 | func (n *NamesMatch) Name() string { |
| 78 | return "names_match" |
| 79 | } |
| 80 | |
| 81 | // Validate evaluates API rule on type t and returns a list of field names in |
| 82 | // the type that violate the rule. Empty field name [""] implies the entire |
| 83 | // type violates the rule. |
| 84 | func (n *NamesMatch) Validate(t *types.Type) ([]string, error) { |
| 85 | fields := make([]string, 0) |
| 86 | |
| 87 | // Only validate struct type and ignore the rest |
| 88 | switch t.Kind { |
| 89 | case types.Struct: |
| 90 | for _, m := range t.Members { |
| 91 | goName := m.Name |
| 92 | jsonTag, ok := reflect.StructTag(m.Tags).Lookup("json") |
| 93 | // Distinguish empty JSON tag and missing JSON tag. Empty JSON tag / name is |
| 94 | // allowed (in JSON name blacklist) but missing JSON tag is invalid. |
| 95 | if !ok { |
| 96 | fields = append(fields, goName) |
| 97 | continue |
| 98 | } |
| 99 | if jsonTagBlacklist.Has(jsonTag) { |
| 100 | continue |
| 101 | } |
| 102 | jsonName := strings.Split(jsonTag, ",")[0] |
| 103 | if !nameIsOkay(m, jsonName) { |
| 104 | fields = append(fields, goName) |
| 105 | } |
| 106 | } |
| 107 | } |
| 108 | return fields, nil |
| 109 | } |
| 110 | |
| 111 | func nameIsOkay(member types.Member, jsonName string) bool { |
| 112 | if jsonName == "" { |
| 113 | return member.Type.Kind == types.Struct || |
| 114 | member.Type.Kind == types.Pointer && member.Type.Elem.Kind == types.Struct |
| 115 | } |
| 116 | |
| 117 | typeName := member.Type.String() |
| 118 | switch typeName { |
| 119 | case "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta", |
| 120 | "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta": |
| 121 | return jsonName == "metadata" |
| 122 | } |
| 123 | |
| 124 | return namesMatch(member.Name, jsonName) |
| 125 | } |
| 126 | |
| 127 | // namesMatch evaluates if goName and jsonName match the API rule |
| 128 | // TODO: Use an off-the-shelf CamelCase solution instead of implementing this logic. The following existing |
| 129 | // |
| 130 | // packages have been tried out: |
| 131 | // github.com/markbates/inflect |
| 132 | // github.com/segmentio/go-camelcase |
| 133 | // github.com/iancoleman/strcase |
| 134 | // github.com/fatih/camelcase |
| 135 | // Please see https://github.com/kubernetes/kube-openapi/pull/83#issuecomment-400842314 for more details |
| 136 | // about why they don't satisfy our need. What we need can be a function that detects an acronym at the |
| 137 | // beginning of a string. |
| 138 | func namesMatch(goName, jsonName string) bool { |
| 139 | if !isAllowedName(goName) || !isAllowedName(jsonName) { |
| 140 | return false |
| 141 | } |
| 142 | if !strings.EqualFold(goName, jsonName) { |
| 143 | return false |
| 144 | } |
| 145 | // Go field names must be CamelCase. JSON field names must be camelCase. |
| 146 | if !isCapital(goName[0]) || isCapital(jsonName[0]) { |
| 147 | return false |
| 148 | } |
| 149 | for i := 0; i < len(goName); i++ { |
| 150 | if goName[i] == jsonName[i] { |
| 151 | // goName[0:i-1] is uppercase and jsonName[0:i-1] is lowercase, goName[i:] |
| 152 | // and jsonName[i:] should match; |
| 153 | // goName[i] should be lowercase if i is equal to 1, e.g.: |
| 154 | // goName | jsonName |
| 155 | // PodSpec podSpec |
| 156 | // or uppercase if i is greater than 1, e.g.: |
| 157 | // goname | jsonName |
| 158 | // JSONSpec jsonSpec |
| 159 | // This is to rule out cases like: |
| 160 | // goname | jsonName |
| 161 | // JSONSpec jsonspec |
| 162 | return goName[i:] == jsonName[i:] && (i == 1 || isCapital(goName[i])) |
| 163 | } |
| 164 | } |
| 165 | return true |
| 166 | } |
| 167 | |
| 168 | // isCapital returns true if one character is capital |
| 169 | func isCapital(b byte) bool { |
| 170 | return b >= 'A' && b <= 'Z' |
| 171 | } |
| 172 | |
| 173 | // isAllowedName checks the list of disallowedNameSubstrings and returns true if name doesn't contain |
| 174 | // any disallowed substring. |
| 175 | func isAllowedName(name string) bool { |
| 176 | for _, substr := range disallowedNameSubstrings.UnsortedList() { |
| 177 | if strings.Contains(name, substr) { |
| 178 | return false |
| 179 | } |
| 180 | } |
| 181 | return true |
| 182 | } |