helpers.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  1. // Copyright 2017 Google LLC. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package compiler
  15. import (
  16. "fmt"
  17. "regexp"
  18. "sort"
  19. "strconv"
  20. "gopkg.in/yaml.v3"
  21. "github.com/google/gnostic-models/jsonschema"
  22. )
  23. // compiler helper functions, usually called from generated code
  24. // UnpackMap gets a *yaml.Node if possible.
  25. func UnpackMap(in *yaml.Node) (*yaml.Node, bool) {
  26. if in == nil {
  27. return nil, false
  28. }
  29. return in, true
  30. }
  31. // SortedKeysForMap returns the sorted keys of a yamlv2.MapSlice.
  32. func SortedKeysForMap(m *yaml.Node) []string {
  33. keys := make([]string, 0)
  34. if m.Kind == yaml.MappingNode {
  35. for i := 0; i < len(m.Content); i += 2 {
  36. keys = append(keys, m.Content[i].Value)
  37. }
  38. }
  39. sort.Strings(keys)
  40. return keys
  41. }
  42. // MapHasKey returns true if a yamlv2.MapSlice contains a specified key.
  43. func MapHasKey(m *yaml.Node, key string) bool {
  44. if m == nil {
  45. return false
  46. }
  47. if m.Kind == yaml.MappingNode {
  48. for i := 0; i < len(m.Content); i += 2 {
  49. itemKey := m.Content[i].Value
  50. if key == itemKey {
  51. return true
  52. }
  53. }
  54. }
  55. return false
  56. }
  57. // MapValueForKey gets the value of a map value for a specified key.
  58. func MapValueForKey(m *yaml.Node, key string) *yaml.Node {
  59. if m == nil {
  60. return nil
  61. }
  62. if m.Kind == yaml.MappingNode {
  63. for i := 0; i < len(m.Content); i += 2 {
  64. itemKey := m.Content[i].Value
  65. if key == itemKey {
  66. return m.Content[i+1]
  67. }
  68. }
  69. }
  70. return nil
  71. }
  72. // ConvertInterfaceArrayToStringArray converts an array of interfaces to an array of strings, if possible.
  73. func ConvertInterfaceArrayToStringArray(interfaceArray []interface{}) []string {
  74. stringArray := make([]string, 0)
  75. for _, item := range interfaceArray {
  76. v, ok := item.(string)
  77. if ok {
  78. stringArray = append(stringArray, v)
  79. }
  80. }
  81. return stringArray
  82. }
  83. // SequenceNodeForNode returns a node if it is a SequenceNode.
  84. func SequenceNodeForNode(node *yaml.Node) (*yaml.Node, bool) {
  85. if node.Kind != yaml.SequenceNode {
  86. return nil, false
  87. }
  88. return node, true
  89. }
  90. // BoolForScalarNode returns the bool value of a node.
  91. func BoolForScalarNode(node *yaml.Node) (bool, bool) {
  92. if node == nil {
  93. return false, false
  94. }
  95. if node.Kind == yaml.DocumentNode {
  96. return BoolForScalarNode(node.Content[0])
  97. }
  98. if node.Kind != yaml.ScalarNode {
  99. return false, false
  100. }
  101. if node.Tag != "!!bool" {
  102. return false, false
  103. }
  104. v, err := strconv.ParseBool(node.Value)
  105. if err != nil {
  106. return false, false
  107. }
  108. return v, true
  109. }
  110. // IntForScalarNode returns the integer value of a node.
  111. func IntForScalarNode(node *yaml.Node) (int64, bool) {
  112. if node == nil {
  113. return 0, false
  114. }
  115. if node.Kind == yaml.DocumentNode {
  116. return IntForScalarNode(node.Content[0])
  117. }
  118. if node.Kind != yaml.ScalarNode {
  119. return 0, false
  120. }
  121. if node.Tag != "!!int" {
  122. return 0, false
  123. }
  124. v, err := strconv.ParseInt(node.Value, 10, 64)
  125. if err != nil {
  126. return 0, false
  127. }
  128. return v, true
  129. }
  130. // FloatForScalarNode returns the float value of a node.
  131. func FloatForScalarNode(node *yaml.Node) (float64, bool) {
  132. if node == nil {
  133. return 0.0, false
  134. }
  135. if node.Kind == yaml.DocumentNode {
  136. return FloatForScalarNode(node.Content[0])
  137. }
  138. if node.Kind != yaml.ScalarNode {
  139. return 0.0, false
  140. }
  141. if (node.Tag != "!!int") && (node.Tag != "!!float") {
  142. return 0.0, false
  143. }
  144. v, err := strconv.ParseFloat(node.Value, 64)
  145. if err != nil {
  146. return 0.0, false
  147. }
  148. return v, true
  149. }
  150. // StringForScalarNode returns the string value of a node.
  151. func StringForScalarNode(node *yaml.Node) (string, bool) {
  152. if node == nil {
  153. return "", false
  154. }
  155. if node.Kind == yaml.DocumentNode {
  156. return StringForScalarNode(node.Content[0])
  157. }
  158. switch node.Kind {
  159. case yaml.ScalarNode:
  160. switch node.Tag {
  161. case "!!int":
  162. return node.Value, true
  163. case "!!str":
  164. return node.Value, true
  165. case "!!timestamp":
  166. return node.Value, true
  167. case "!!null":
  168. return "", true
  169. default:
  170. return "", false
  171. }
  172. default:
  173. return "", false
  174. }
  175. }
  176. // StringArrayForSequenceNode converts a sequence node to an array of strings, if possible.
  177. func StringArrayForSequenceNode(node *yaml.Node) []string {
  178. stringArray := make([]string, 0)
  179. for _, item := range node.Content {
  180. v, ok := StringForScalarNode(item)
  181. if ok {
  182. stringArray = append(stringArray, v)
  183. }
  184. }
  185. return stringArray
  186. }
  187. // MissingKeysInMap identifies which keys from a list of required keys are not in a map.
  188. func MissingKeysInMap(m *yaml.Node, requiredKeys []string) []string {
  189. missingKeys := make([]string, 0)
  190. for _, k := range requiredKeys {
  191. if !MapHasKey(m, k) {
  192. missingKeys = append(missingKeys, k)
  193. }
  194. }
  195. return missingKeys
  196. }
  197. // InvalidKeysInMap returns keys in a map that don't match a list of allowed keys and patterns.
  198. func InvalidKeysInMap(m *yaml.Node, allowedKeys []string, allowedPatterns []*regexp.Regexp) []string {
  199. invalidKeys := make([]string, 0)
  200. if m == nil || m.Kind != yaml.MappingNode {
  201. return invalidKeys
  202. }
  203. for i := 0; i < len(m.Content); i += 2 {
  204. key := m.Content[i].Value
  205. found := false
  206. // does the key match an allowed key?
  207. for _, allowedKey := range allowedKeys {
  208. if key == allowedKey {
  209. found = true
  210. break
  211. }
  212. }
  213. if !found {
  214. // does the key match an allowed pattern?
  215. for _, allowedPattern := range allowedPatterns {
  216. if allowedPattern.MatchString(key) {
  217. found = true
  218. break
  219. }
  220. }
  221. if !found {
  222. invalidKeys = append(invalidKeys, key)
  223. }
  224. }
  225. }
  226. return invalidKeys
  227. }
  228. // NewNullNode creates a new Null node.
  229. func NewNullNode() *yaml.Node {
  230. node := &yaml.Node{
  231. Kind: yaml.ScalarNode,
  232. Tag: "!!null",
  233. }
  234. return node
  235. }
  236. // NewMappingNode creates a new Mapping node.
  237. func NewMappingNode() *yaml.Node {
  238. return &yaml.Node{
  239. Kind: yaml.MappingNode,
  240. Content: make([]*yaml.Node, 0),
  241. }
  242. }
  243. // NewSequenceNode creates a new Sequence node.
  244. func NewSequenceNode() *yaml.Node {
  245. node := &yaml.Node{
  246. Kind: yaml.SequenceNode,
  247. Content: make([]*yaml.Node, 0),
  248. }
  249. return node
  250. }
  251. // NewScalarNodeForString creates a new node to hold a string.
  252. func NewScalarNodeForString(s string) *yaml.Node {
  253. return &yaml.Node{
  254. Kind: yaml.ScalarNode,
  255. Tag: "!!str",
  256. Value: s,
  257. }
  258. }
  259. // NewSequenceNodeForStringArray creates a new node to hold an array of strings.
  260. func NewSequenceNodeForStringArray(strings []string) *yaml.Node {
  261. node := &yaml.Node{
  262. Kind: yaml.SequenceNode,
  263. Content: make([]*yaml.Node, 0),
  264. }
  265. for _, s := range strings {
  266. node.Content = append(node.Content, NewScalarNodeForString(s))
  267. }
  268. return node
  269. }
  270. // NewScalarNodeForBool creates a new node to hold a bool.
  271. func NewScalarNodeForBool(b bool) *yaml.Node {
  272. return &yaml.Node{
  273. Kind: yaml.ScalarNode,
  274. Tag: "!!bool",
  275. Value: fmt.Sprintf("%t", b),
  276. }
  277. }
  278. // NewScalarNodeForFloat creates a new node to hold a float.
  279. func NewScalarNodeForFloat(f float64) *yaml.Node {
  280. return &yaml.Node{
  281. Kind: yaml.ScalarNode,
  282. Tag: "!!float",
  283. Value: fmt.Sprintf("%g", f),
  284. }
  285. }
  286. // NewScalarNodeForInt creates a new node to hold an integer.
  287. func NewScalarNodeForInt(i int64) *yaml.Node {
  288. return &yaml.Node{
  289. Kind: yaml.ScalarNode,
  290. Tag: "!!int",
  291. Value: fmt.Sprintf("%d", i),
  292. }
  293. }
  294. // PluralProperties returns the string "properties" pluralized.
  295. func PluralProperties(count int) string {
  296. if count == 1 {
  297. return "property"
  298. }
  299. return "properties"
  300. }
  301. // StringArrayContainsValue returns true if a string array contains a specified value.
  302. func StringArrayContainsValue(array []string, value string) bool {
  303. for _, item := range array {
  304. if item == value {
  305. return true
  306. }
  307. }
  308. return false
  309. }
  310. // StringArrayContainsValues returns true if a string array contains all of a list of specified values.
  311. func StringArrayContainsValues(array []string, values []string) bool {
  312. for _, value := range values {
  313. if !StringArrayContainsValue(array, value) {
  314. return false
  315. }
  316. }
  317. return true
  318. }
  319. // StringValue returns the string value of an item.
  320. func StringValue(item interface{}) (value string, ok bool) {
  321. value, ok = item.(string)
  322. if ok {
  323. return value, ok
  324. }
  325. intValue, ok := item.(int)
  326. if ok {
  327. return strconv.Itoa(intValue), true
  328. }
  329. return "", false
  330. }
  331. // Description returns a human-readable represention of an item.
  332. func Description(item interface{}) string {
  333. value, ok := item.(*yaml.Node)
  334. if ok {
  335. return jsonschema.Render(value)
  336. }
  337. return fmt.Sprintf("%+v", item)
  338. }
  339. // Display returns a description of a node for use in error messages.
  340. func Display(node *yaml.Node) string {
  341. switch node.Kind {
  342. case yaml.ScalarNode:
  343. switch node.Tag {
  344. case "!!str":
  345. return fmt.Sprintf("%s (string)", node.Value)
  346. }
  347. }
  348. return fmt.Sprintf("%+v (%T)", node, node)
  349. }
  350. // Marshal creates a yaml version of a structure in our preferred style
  351. func Marshal(in *yaml.Node) []byte {
  352. clearStyle(in)
  353. //bytes, _ := yaml.Marshal(&yaml.Node{Kind: yaml.DocumentNode, Content: []*yaml.Node{in}})
  354. bytes, _ := yaml.Marshal(in)
  355. return bytes
  356. }
  357. func clearStyle(node *yaml.Node) {
  358. node.Style = 0
  359. for _, c := range node.Content {
  360. clearStyle(c)
  361. }
  362. }