| 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/gengo/v2/types" |
| 24 | ) |
| 25 | |
| 26 | // OmitEmptyMatchCase implements APIRule interface. |
| 27 | // "omitempty" must appear verbatim (no case variants). |
| 28 | type OmitEmptyMatchCase struct{} |
| 29 | |
| 30 | func (n *OmitEmptyMatchCase) Name() string { |
| 31 | return "omitempty_match_case" |
| 32 | } |
| 33 | |
| 34 | func (n *OmitEmptyMatchCase) Validate(t *types.Type) ([]string, error) { |
| 35 | fields := make([]string, 0) |
| 36 | |
| 37 | // Only validate struct type and ignore the rest |
| 38 | switch t.Kind { |
| 39 | case types.Struct: |
| 40 | for _, m := range t.Members { |
| 41 | goName := m.Name |
| 42 | jsonTag, ok := reflect.StructTag(m.Tags).Lookup("json") |
| 43 | if !ok { |
| 44 | continue |
| 45 | } |
| 46 | |
| 47 | parts := strings.Split(jsonTag, ",") |
| 48 | if len(parts) < 2 { |
| 49 | // no tags other than name |
| 50 | continue |
| 51 | } |
| 52 | if parts[0] == "-" { |
| 53 | // not serialized |
| 54 | continue |
| 55 | } |
| 56 | for _, part := range parts[1:] { |
| 57 | if strings.EqualFold(part, "omitempty") && part != "omitempty" { |
| 58 | fields = append(fields, goName) |
| 59 | } |
| 60 | } |
| 61 | } |
| 62 | } |
| 63 | return fields, nil |
| 64 | } |