recursive_fields_printer.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /*
  2. Copyright 2017 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 explain
  14. import "k8s.io/kube-openapi/pkg/util/proto"
  15. // indentPerLevel is the level of indentation for each field recursion.
  16. const indentPerLevel = 3
  17. // recursiveFieldsPrinter recursively prints all the fields for a given
  18. // schema.
  19. type recursiveFieldsPrinter struct {
  20. Writer *Formatter
  21. Error error
  22. }
  23. var _ proto.SchemaVisitor = &recursiveFieldsPrinter{}
  24. var _ fieldsPrinter = &recursiveFieldsPrinter{}
  25. var visitedReferences = map[string]struct{}{}
  26. // VisitArray is just a passthrough.
  27. func (f *recursiveFieldsPrinter) VisitArray(a *proto.Array) {
  28. a.SubType.Accept(f)
  29. }
  30. // VisitKind prints all its fields with their type, and then recurses
  31. // inside each of these (pre-order).
  32. func (f *recursiveFieldsPrinter) VisitKind(k *proto.Kind) {
  33. for _, key := range k.Keys() {
  34. v := k.Fields[key]
  35. f.Writer.Write("%s\t<%s>", key, GetTypeName(v))
  36. subFields := &recursiveFieldsPrinter{
  37. Writer: f.Writer.Indent(indentPerLevel),
  38. }
  39. if err := subFields.PrintFields(v); err != nil {
  40. f.Error = err
  41. return
  42. }
  43. }
  44. }
  45. // VisitMap is just a passthrough.
  46. func (f *recursiveFieldsPrinter) VisitMap(m *proto.Map) {
  47. m.SubType.Accept(f)
  48. }
  49. // VisitPrimitive does nothing, since it doesn't have sub-fields.
  50. func (f *recursiveFieldsPrinter) VisitPrimitive(p *proto.Primitive) {
  51. // Nothing to do.
  52. }
  53. // VisitReference is just a passthrough.
  54. func (f *recursiveFieldsPrinter) VisitReference(r proto.Reference) {
  55. if _, ok := visitedReferences[r.Reference()]; ok {
  56. return
  57. }
  58. visitedReferences[r.Reference()] = struct{}{}
  59. r.SubSchema().Accept(f)
  60. delete(visitedReferences, r.Reference())
  61. }
  62. // PrintFields will recursively print all the fields for the given
  63. // schema.
  64. func (f *recursiveFieldsPrinter) PrintFields(schema proto.Schema) error {
  65. schema.Accept(f)
  66. return f.Error
  67. }