...
1
16
17 package printers
18
19 import (
20 "fmt"
21 "io"
22 "reflect"
23 "strings"
24
25 "k8s.io/apimachinery/pkg/api/meta"
26 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
27 "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
28 "k8s.io/apimachinery/pkg/runtime"
29 "k8s.io/apimachinery/pkg/runtime/schema"
30 )
31
32
33 type NamePrinter struct {
34
35
36 ShortOutput bool
37
38
39
40 Operation string
41 }
42
43
44
45 func (p *NamePrinter) PrintObj(obj runtime.Object, w io.Writer) error {
46 switch castObj := obj.(type) {
47 case *metav1.WatchEvent:
48 obj = castObj.Object.Object
49 }
50
51
52
53
54 if InternalObjectPreventer.IsForbidden(reflect.Indirect(reflect.ValueOf(obj)).Type().PkgPath()) {
55 return fmt.Errorf(InternalObjectPrinterErr)
56 }
57
58 if meta.IsListType(obj) {
59
60
61
62 if _, ok := obj.(*unstructured.UnstructuredList); !ok {
63 return fmt.Errorf("list types are not supported by name printing: %T", obj)
64 }
65
66 items, err := meta.ExtractList(obj)
67 if err != nil {
68 return err
69 }
70 for _, obj := range items {
71 if err := p.PrintObj(obj, w); err != nil {
72 return err
73 }
74 }
75 return nil
76 }
77
78 if obj.GetObjectKind().GroupVersionKind().Empty() {
79 return fmt.Errorf("missing apiVersion or kind; try GetObjectKind().SetGroupVersionKind() if you know the type")
80 }
81
82 name := "<unknown>"
83 if acc, err := meta.Accessor(obj); err == nil {
84 if n := acc.GetName(); len(n) > 0 {
85 name = n
86 }
87 }
88
89 return printObj(w, name, p.Operation, p.ShortOutput, GetObjectGroupKind(obj))
90 }
91
92 func GetObjectGroupKind(obj runtime.Object) schema.GroupKind {
93 if obj == nil {
94 return schema.GroupKind{Kind: "<unknown>"}
95 }
96 groupVersionKind := obj.GetObjectKind().GroupVersionKind()
97 if len(groupVersionKind.Kind) > 0 {
98 return groupVersionKind.GroupKind()
99 }
100
101 if uns, ok := obj.(*unstructured.Unstructured); ok {
102 if len(uns.GroupVersionKind().Kind) > 0 {
103 return uns.GroupVersionKind().GroupKind()
104 }
105 }
106
107 return schema.GroupKind{Kind: "<unknown>"}
108 }
109
110 func printObj(w io.Writer, name string, operation string, shortOutput bool, groupKind schema.GroupKind) error {
111 if len(groupKind.Kind) == 0 {
112 return fmt.Errorf("missing kind for resource with name %v", name)
113 }
114
115 if len(operation) > 0 {
116 operation = " " + operation
117 }
118
119 if shortOutput {
120 operation = ""
121 }
122
123 if len(groupKind.Group) == 0 {
124 fmt.Fprintf(w, "%s/%s%s\n", strings.ToLower(groupKind.Kind), name, operation)
125 return nil
126 }
127
128 fmt.Fprintf(w, "%s.%s/%s%s\n", strings.ToLower(groupKind.Kind), groupKind.Group, name, operation)
129 return nil
130 }
131
View as plain text