...
1
16
17 package get
18
19 import (
20 "fmt"
21 "os"
22 "sort"
23 "strings"
24
25 "github.com/spf13/cobra"
26
27 "k8s.io/cli-runtime/pkg/genericclioptions"
28 "k8s.io/cli-runtime/pkg/printers"
29 "k8s.io/kubectl/pkg/scheme"
30 )
31
32 var columnsFormats = map[string]bool{
33 "custom-columns-file": true,
34 "custom-columns": true,
35 }
36
37
38
39 type CustomColumnsPrintFlags struct {
40 NoHeaders bool
41 TemplateArgument string
42 }
43
44 func (f *CustomColumnsPrintFlags) AllowedFormats() []string {
45 formats := make([]string, 0, len(columnsFormats))
46 for format := range columnsFormats {
47 formats = append(formats, format)
48 }
49 sort.Strings(formats)
50 return formats
51 }
52
53
54
55
56
57 func (f *CustomColumnsPrintFlags) ToPrinter(templateFormat string) (printers.ResourcePrinter, error) {
58 if len(templateFormat) == 0 {
59 return nil, genericclioptions.NoCompatiblePrinterError{}
60 }
61
62 templateValue := ""
63
64 if len(f.TemplateArgument) == 0 {
65 for format := range columnsFormats {
66 format = format + "="
67 if strings.HasPrefix(templateFormat, format) {
68 templateValue = templateFormat[len(format):]
69 templateFormat = format[:len(format)-1]
70 break
71 }
72 }
73 } else {
74 templateValue = f.TemplateArgument
75 }
76
77 if _, supportedFormat := columnsFormats[templateFormat]; !supportedFormat {
78 return nil, genericclioptions.NoCompatiblePrinterError{OutputFormat: &templateFormat, AllowedFormats: f.AllowedFormats()}
79 }
80
81 if len(templateValue) == 0 {
82 return nil, fmt.Errorf("custom-columns format specified but no custom columns given")
83 }
84
85
86 decoder := scheme.Codecs.UniversalDecoder(scheme.Scheme.PrioritizedVersionsAllGroups()...)
87
88 if templateFormat == "custom-columns-file" {
89 file, err := os.Open(templateValue)
90 if err != nil {
91 return nil, fmt.Errorf("error reading template %s, %v\n", templateValue, err)
92 }
93 defer file.Close()
94 p, err := NewCustomColumnsPrinterFromTemplate(file, decoder)
95 return p, err
96 }
97
98 return NewCustomColumnsPrinterFromSpec(templateValue, decoder, f.NoHeaders)
99 }
100
101
102
103 func (f *CustomColumnsPrintFlags) AddFlags(c *cobra.Command) {}
104
105
106
107
108 func NewCustomColumnsPrintFlags() *CustomColumnsPrintFlags {
109 return &CustomColumnsPrintFlags{
110 NoHeaders: false,
111 TemplateArgument: "",
112 }
113 }
114
View as plain text