explain.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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 (
  15. "io"
  16. "strings"
  17. "k8s.io/apimachinery/pkg/api/meta"
  18. "k8s.io/apimachinery/pkg/runtime/schema"
  19. "k8s.io/kube-openapi/pkg/util/proto"
  20. )
  21. type fieldsPrinter interface {
  22. PrintFields(proto.Schema) error
  23. }
  24. func splitDotNotation(model string) (string, []string) {
  25. var fieldsPath []string
  26. // ignore trailing period
  27. model = strings.TrimSuffix(model, ".")
  28. dotModel := strings.Split(model, ".")
  29. if len(dotModel) >= 1 {
  30. fieldsPath = dotModel[1:]
  31. }
  32. return dotModel[0], fieldsPath
  33. }
  34. // SplitAndParseResourceRequest separates the users input into a model and fields
  35. func SplitAndParseResourceRequest(inResource string, mapper meta.RESTMapper) (string, []string, error) {
  36. inResource, fieldsPath := splitDotNotation(inResource)
  37. inResource, _ = mapper.ResourceSingularizer(inResource)
  38. return inResource, fieldsPath, nil
  39. }
  40. // PrintModelDescription prints the description of a specific model or dot path.
  41. // If recursive, all components nested within the fields of the schema will be
  42. // printed.
  43. func PrintModelDescription(fieldsPath []string, w io.Writer, schema proto.Schema, gvk schema.GroupVersionKind, recursive bool) error {
  44. fieldName := ""
  45. if len(fieldsPath) != 0 {
  46. fieldName = fieldsPath[len(fieldsPath)-1]
  47. }
  48. // Go down the fieldsPath to find what we're trying to explain
  49. schema, err := LookupSchemaForField(schema, fieldsPath)
  50. if err != nil {
  51. return err
  52. }
  53. b := fieldsPrinterBuilder{Recursive: recursive}
  54. f := &Formatter{Writer: w, Wrap: 80}
  55. return PrintModel(fieldName, f, b, schema, gvk)
  56. }