Debian Codegraph @

cmd/config/internal/commands/cat.go

raw symbols SCIP
1 // Copyright 2019 The Kubernetes Authors.
2 // SPDX-License-Identifier: Apache-2.0
3
4 package commands
5
6 import (
7 "bytes"
8 "fmt"
9 "io"
10 "os"
11 "strings"
12
13 "github.com/spf13/cobra"
14 "sigs.k8s.io/kustomize/cmd/config/ext"
15 "sigs.k8s.io/kustomize/cmd/config/internal/generateddocs/commands"
16 "sigs.k8s.io/kustomize/cmd/config/runner"
17 "sigs.k8s.io/kustomize/kyaml/errors"
18 "sigs.k8s.io/kustomize/kyaml/kio"
19 "sigs.k8s.io/kustomize/kyaml/kio/filters"
20 "sigs.k8s.io/kustomize/kyaml/kio/kioutil"
21 "sigs.k8s.io/kustomize/kyaml/yaml"
22 )
23
24 // GetCatRunner returns a command CatRunner.
25 func GetCatRunner(name string) *CatRunner {
26 r := &CatRunner{}
27 c := &cobra.Command{
28 Use: "cat DIR",
29 Short: commands.CatShort,
30 Long: commands.CatLong,
31 Example: commands.CatExamples,
32 RunE: r.runE,
33 Args: cobra.MaximumNArgs(1),
34 }
35 runner.FixDocs(name, c)
36 c.Flags().BoolVar(&r.Format, "format", true,
37 "format resource config yaml before printing.")
38 c.Flags().BoolVar(&r.KeepAnnotations, "annotate", false,
39 "annotate resources with their file origins.")
40 c.Flags().StringVar(&r.WrapKind, "wrap-kind", "",
41 "if set, wrap the output in this list type kind.")
42 c.Flags().StringVar(&r.WrapApiVersion, "wrap-version", "",
43 "if set, wrap the output in this list type apiVersion.")
44 c.Flags().StringVar(&r.FunctionConfig, "function-config", "",
45 "path to function config to put in ResourceList -- only if wrapped in a ResourceList.")
46 c.Flags().StringSliceVar(&r.Styles, "style", []string{},
47 "yaml styles to apply. may be 'TaggedStyle', 'DoubleQuotedStyle', 'LiteralStyle', "+
48 "'FoldedStyle', 'FlowStyle'.")
49 c.Flags().BoolVar(&r.StripComments, "strip-comments", false,
50 "remove comments from yaml.")
51 c.Flags().BoolVar(&r.IncludeLocal, "include-local", false,
52 "if true, include local-config in the output.")
53 c.Flags().BoolVar(&r.ExcludeNonLocal, "exclude-non-local", false,
54 "if true, exclude non-local-config in the output.")
55 c.Flags().StringVar(&r.OutputDest, "dest", "",
56 "if specified, write output to a file rather than stdout")
57 c.Flags().BoolVarP(&r.RecurseSubPackages, "recurse-subpackages", "R", true,
58 "print resources recursively in all the nested subpackages")
59 r.Command = c
60 return r
61 }
62
63 func CatCommand(name string) *cobra.Command {
64 return GetCatRunner(name).Command
65 }
66
67 // CatRunner contains the run function
68 type CatRunner struct {
69 Format bool
70 KeepAnnotations bool
71 WrapKind string
72 WrapApiVersion string
73 FunctionConfig string
74 OutputDest string
75 Styles []string
76 StripComments bool
77 IncludeLocal bool
78 ExcludeNonLocal bool
79 Command *cobra.Command
80 RecurseSubPackages bool
81 }
82
83 func (r *CatRunner) runE(c *cobra.Command, args []string) error {
84 var writer = c.OutOrStdout()
85 if r.OutputDest != "" {
86 o, err := os.Create(r.OutputDest)
87 if err != nil {
88 return errors.Wrap(err)
89 }
90 defer o.Close()
91 writer = o
92 }
93 if len(args) == 0 {
94 input := &kio.ByteReader{Reader: c.InOrStdin()}
95 // if there is a function-config specified, emit it
96 outputs, err := r.out(writer)
97 if err != nil {
98 return err
99 }
100 return runner.HandleError(c, kio.Pipeline{Inputs: []kio.Reader{input}, Filters: r.catFilters(), Outputs: outputs}.Execute())
101 }
102
103 out := &bytes.Buffer{}
104
105 e := runner.ExecuteCmdOnPkgs{
106 Writer: out,
107 NeedOpenAPI: false,
108 RecurseSubPackages: r.RecurseSubPackages,
109 CmdRunner: r,
110 RootPkgPath: args[0],
111 SkipPkgPathPrint: true,
112 }
113
114 err := e.Execute()
115 if err != nil {
116 return err
117 }
118
119 res := strings.TrimSuffix(out.String(), "---")
120 fmt.Fprintf(writer, "%s", res)
121
122 return nil
123 }
124
125 func (r *CatRunner) ExecuteCmd(w io.Writer, pkgPath string) error {
126 input := kio.LocalPackageReader{PackagePath: pkgPath, PackageFileName: ext.KRMFileName()}
127 out := &bytes.Buffer{}
128 outputs, err := r.out(out)
129 if err != nil {
130 return err
131 }
132 err = kio.Pipeline{
133 Inputs: []kio.Reader{input},
134 Filters: r.catFilters(),
135 Outputs: outputs,
136 }.Execute()
137
138 if err != nil {
139 // return err if there is only package
140 if !r.RecurseSubPackages {
141 return err
142 }
143 // print error message and continue if there are multiple packages to annotate
144 fmt.Fprintf(w, "%s in package %q\n", err.Error(), pkgPath)
145 }
146 fmt.Fprint(w, out.String())
147 if out.String() != "" {
148 fmt.Fprint(w, "---")
149 }
150 return nil
151 }
152
153 func (r *CatRunner) catFilters() []kio.Filter {
154 var fltrs []kio.Filter
155 // don't include reconcilers
156 fltrs = append(fltrs, &filters.IsLocalConfig{
157 IncludeLocalConfig: r.IncludeLocal,
158 ExcludeNonLocalConfig: r.ExcludeNonLocal,
159 })
160 if r.Format {
161 fltrs = append(fltrs, filters.FormatFilter{})
162 }
163 if r.StripComments {
164 fltrs = append(fltrs, filters.StripCommentsFilter{})
165 }
166 return fltrs
167 }
168
169 func (r *CatRunner) out(w io.Writer) ([]kio.Writer, error) {
170 var outputs []kio.Writer
171 var functionConfig *yaml.RNode
172 if r.FunctionConfig != "" {
173 configs, err := kio.LocalPackageReader{PackagePath: r.FunctionConfig,
174 OmitReaderAnnotations: !r.KeepAnnotations}.Read()
175 if err != nil {
176 return outputs, err
177 }
178 if len(configs) != 1 {
179 return outputs, fmt.Errorf("expected exactly 1 functionConfig, found %d", len(configs))
180 }
181 functionConfig = configs[0]
182 }
183
184 // remove this annotation explicitly, the ByteWriter won't clear it by
185 // default because it doesn't set it
186 clear := []string{kioutil.LegacyPathAnnotation, kioutil.PathAnnotation}
187 if r.KeepAnnotations {
188 clear = nil
189 }
190
191 outputs = append(outputs, kio.ByteWriter{
192 Writer: w,
193 KeepReaderAnnotations: r.KeepAnnotations,
194 WrappingKind: r.WrapKind,
195 WrappingAPIVersion: r.WrapApiVersion,
196 FunctionConfig: functionConfig,
197 Style: yaml.GetStyle(r.Styles...),
198 ClearAnnotations: clear,
199 })
200
201 return outputs, nil
202 }