extension.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. /*
  2. Copyright 2018 The Kubernetes Authors.
  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. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package generators
  14. import (
  15. "fmt"
  16. "sort"
  17. "strings"
  18. "k8s.io/gengo/examples/set-gen/sets"
  19. "k8s.io/gengo/types"
  20. )
  21. const extensionPrefix = "x-kubernetes-"
  22. // extensionAttributes encapsulates common traits for particular extensions.
  23. type extensionAttributes struct {
  24. xName string
  25. kind types.Kind
  26. allowedValues sets.String
  27. enforceArray bool
  28. }
  29. // Extension tag to openapi extension attributes
  30. var tagToExtension = map[string]extensionAttributes{
  31. "patchMergeKey": {
  32. xName: "x-kubernetes-patch-merge-key",
  33. kind: types.Slice,
  34. },
  35. "patchStrategy": {
  36. xName: "x-kubernetes-patch-strategy",
  37. kind: types.Slice,
  38. allowedValues: sets.NewString("merge", "retainKeys"),
  39. },
  40. "listMapKey": {
  41. xName: "x-kubernetes-list-map-keys",
  42. kind: types.Slice,
  43. enforceArray: true,
  44. },
  45. "listType": {
  46. xName: "x-kubernetes-list-type",
  47. kind: types.Slice,
  48. allowedValues: sets.NewString("atomic", "set", "map"),
  49. },
  50. }
  51. // Extension encapsulates information necessary to generate an OpenAPI extension.
  52. type extension struct {
  53. idlTag string // Example: listType
  54. xName string // Example: x-kubernetes-list-type
  55. values []string // Example: [atomic]
  56. }
  57. func (e extension) hasAllowedValues() bool {
  58. return tagToExtension[e.idlTag].allowedValues.Len() > 0
  59. }
  60. func (e extension) allowedValues() sets.String {
  61. return tagToExtension[e.idlTag].allowedValues
  62. }
  63. func (e extension) hasKind() bool {
  64. return len(tagToExtension[e.idlTag].kind) > 0
  65. }
  66. func (e extension) kind() types.Kind {
  67. return tagToExtension[e.idlTag].kind
  68. }
  69. func (e extension) validateAllowedValues() error {
  70. // allowedValues not set means no restrictions on values.
  71. if !e.hasAllowedValues() {
  72. return nil
  73. }
  74. // Check for missing value.
  75. if len(e.values) == 0 {
  76. return fmt.Errorf("%s needs a value, none given.", e.idlTag)
  77. }
  78. // For each extension value, validate that it is allowed.
  79. allowedValues := e.allowedValues()
  80. if !allowedValues.HasAll(e.values...) {
  81. return fmt.Errorf("%v not allowed for %s. Allowed values: %v",
  82. e.values, e.idlTag, allowedValues.List())
  83. }
  84. return nil
  85. }
  86. func (e extension) validateType(kind types.Kind) error {
  87. // If this extension class has no kind, then don't validate the type.
  88. if !e.hasKind() {
  89. return nil
  90. }
  91. if kind != e.kind() {
  92. return fmt.Errorf("tag %s on type %v; only allowed on type %v",
  93. e.idlTag, kind, e.kind())
  94. }
  95. return nil
  96. }
  97. func (e extension) hasMultipleValues() bool {
  98. return len(e.values) > 1
  99. }
  100. func (e extension) isAlwaysArrayFormat() bool {
  101. return tagToExtension[e.idlTag].enforceArray
  102. }
  103. // Returns sorted list of map keys. Needed for deterministic testing.
  104. func sortedMapKeys(m map[string][]string) []string {
  105. keys := make([]string, len(m))
  106. i := 0
  107. for k := range m {
  108. keys[i] = k
  109. i++
  110. }
  111. sort.Strings(keys)
  112. return keys
  113. }
  114. // Parses comments to return openapi extensions. Returns a list of
  115. // extensions which parsed correctly, as well as a list of the
  116. // parse errors. Validating extensions is performed separately.
  117. // NOTE: Non-empty errors does not mean extensions is empty.
  118. func parseExtensions(comments []string) ([]extension, []error) {
  119. extensions := []extension{}
  120. errors := []error{}
  121. // First, generate extensions from "+k8s:openapi-gen=x-kubernetes-*" annotations.
  122. values := getOpenAPITagValue(comments)
  123. for _, val := range values {
  124. // Example: x-kubernetes-member-tag:member_test
  125. if strings.HasPrefix(val, extensionPrefix) {
  126. parts := strings.SplitN(val, ":", 2)
  127. if len(parts) != 2 {
  128. errors = append(errors, fmt.Errorf("invalid extension value: %v", val))
  129. continue
  130. }
  131. e := extension{
  132. idlTag: tagName, // Example: k8s:openapi-gen
  133. xName: parts[0], // Example: x-kubernetes-member-tag
  134. values: []string{parts[1]}, // Example: member_test
  135. }
  136. extensions = append(extensions, e)
  137. }
  138. }
  139. // Next, generate extensions from "idlTags" (e.g. +listType)
  140. tagValues := types.ExtractCommentTags("+", comments)
  141. for _, idlTag := range sortedMapKeys(tagValues) {
  142. xAttrs, exists := tagToExtension[idlTag]
  143. if !exists {
  144. continue
  145. }
  146. values := tagValues[idlTag]
  147. e := extension{
  148. idlTag: idlTag, // listType
  149. xName: xAttrs.xName, // x-kubernetes-list-type
  150. values: values, // [atomic]
  151. }
  152. extensions = append(extensions, e)
  153. }
  154. return extensions, errors
  155. }
  156. func validateMemberExtensions(extensions []extension, m *types.Member) []error {
  157. errors := []error{}
  158. for _, e := range extensions {
  159. if err := e.validateAllowedValues(); err != nil {
  160. errors = append(errors, err)
  161. }
  162. if err := e.validateType(m.Type.Kind); err != nil {
  163. errors = append(errors, err)
  164. }
  165. }
  166. return errors
  167. }