Debian Codegraph @

v2/parser/tags/json.go

raw
1 /*
2 Copyright 2021 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 // This is based on the highly efficient approach from https://golang.org/src/encoding/json/encode.go
18
19 package tags
20
21 import (
22 "reflect"
23 "strings"
24
25 "k8s.io/gengo/v2/types"
26 )
27
28 // JSON represents a go json field tag.
29 type JSON struct {
30 Name string
31 Omit bool
32 Inline bool
33 Omitempty bool
34 }
35
36 func (t JSON) String() string {
37 var tag string
38 if !t.Inline {
39 tag += t.Name
40 }
41 if t.Omitempty {
42 tag += ",omitempty"
43 }
44 if t.Inline {
45 tag += ",inline"
46 }
47 return tag
48 }
49
50 func LookupJSON(m types.Member) (JSON, bool) {
51 tag := reflect.StructTag(m.Tags).Get("json")
52 if tag == "-" {
53 return JSON{Omit: true}, true
54 }
55 name, opts := parse(tag)
56 inline := opts.Contains("inline")
57 omitempty := opts.Contains("omitempty")
58 if !inline && name == "" {
59 name = m.Name
60 }
61 return JSON{
62 Name: name,
63 Omit: false,
64 Inline: inline,
65 Omitempty: omitempty,
66 }, true
67 }
68
69 type options string
70
71 // parse splits a struct field's json tag into its Name and
72 // comma-separated options.
73 func parse(tag string) (string, options) {
74 if idx := strings.Index(tag, ","); idx != -1 {
75 return tag[:idx], options(tag[idx+1:])
76 }
77 return tag, ""
78 }
79
80 // Contains reports whether a comma-separated listAlias of options
81 // contains a particular substr flag. substr must be surrounded by a
82 // string boundary or commas.
83 func (o options) Contains(optionName string) bool {
84 if len(o) == 0 {
85 return false
86 }
87 s := string(o)
88 for s != "" {
89 var next string
90 i := strings.Index(s, ",")
91 if i >= 0 {
92 s, next = s[:i], s[i+1:]
93 }
94 if s == optionName {
95 return true
96 }
97 s = next
98 }
99 return false
100 }