Debian Codegraph @

cmd/config/internal/commands/grep.go

raw symbols SCIP
1 // Copyright 2019 The Kubernetes Authors.
2 // SPDX-License-Identifier: Apache-2.0
3 package commands
4
5 import (
6 "bytes"
7 "fmt"
8 "io"
9 "strings"
10
11 "github.com/spf13/cobra"
12 "sigs.k8s.io/kustomize/cmd/config/ext"
13 "sigs.k8s.io/kustomize/cmd/config/internal/commands/internal/k8sgen/pkg/api/resource"
14 "sigs.k8s.io/kustomize/cmd/config/internal/generateddocs/commands"
15 "sigs.k8s.io/kustomize/cmd/config/runner"
16 "sigs.k8s.io/kustomize/kyaml/kio"
17 "sigs.k8s.io/kustomize/kyaml/kio/filters"
18 )
19
20 // Cmd returns a command GrepRunner.
21 func GetGrepRunner(name string) *GrepRunner {
22 r := &GrepRunner{}
23 c := &cobra.Command{
24 Use: "grep QUERY [DIR]",
25 Short: commands.GrepShort,
26 Long: commands.GrepLong,
27 Example: commands.GrepExamples,
28 PreRunE: r.preRunE,
29 RunE: r.runE,
30 Args: cobra.MaximumNArgs(2),
31 }
32 runner.FixDocs(name, c)
33 c.Flags().BoolVar(&r.KeepAnnotations, "annotate", true,
34 "annotate resources with their file origins.")
35 c.Flags().BoolVarP(&r.InvertMatch, "invert-match", "", false,
36 "Selected Resources are those not matching any of the specified patterns..")
37 c.Flags().BoolVarP(&r.RecurseSubPackages, "recurse-subpackages", "R", true,
38 "also print resources recursively in all the nested subpackages")
39 r.Command = c
40 return r
41 }
42
43 func GrepCommand(name string) *cobra.Command {
44 return GetGrepRunner(name).Command
45 }
46
47 // GrepRunner contains the run function
48 type GrepRunner struct {
49 KeepAnnotations bool
50 Command *cobra.Command
51 filters.GrepFilter
52 Format bool
53 RecurseSubPackages bool
54 }
55
56 func (r *GrepRunner) preRunE(c *cobra.Command, args []string) error {
57 if len(args) == 0 {
58 return fmt.Errorf("missing required argument: QUERY")
59 }
60 r.GrepFilter.Compare = func(a, b string) (int, error) {
61 qa, err := resource.ParseQuantity(a)
62 if err != nil {
63 return 0, fmt.Errorf("%s: %v", a, err)
64 }
65 qb, err := resource.ParseQuantity(b)
66 if err != nil {
67 return 0, err
68 }
69
70 return qa.Cmp(qb), err
71 }
72 parts, err := runner.ParseFieldPath(args[0])
73 if err != nil {
74 return err
75 }
76
77 var last []string
78 switch {
79 case strings.Contains(parts[len(parts)-1], ">="):
80 last = strings.Split(parts[len(parts)-1], ">=")
81 r.MatchType = filters.GreaterThanEq
82 case strings.Contains(parts[len(parts)-1], "<="):
83 last = strings.Split(parts[len(parts)-1], "<=")
84 r.MatchType = filters.LessThanEq
85 case strings.Contains(parts[len(parts)-1], ">"):
86 last = strings.Split(parts[len(parts)-1], ">")
87 r.MatchType = filters.GreaterThan
88 case strings.Contains(parts[len(parts)-1], "<"):
89 last = strings.Split(parts[len(parts)-1], "<")
90 r.MatchType = filters.LessThan
91 default:
92 last = strings.Split(parts[len(parts)-1], "=")
93 r.MatchType = filters.Regexp
94 }
95 if len(last) > 2 {
96 return fmt.Errorf(
97 "ambiguous match -- multiple of ['<', '>', '<=', '>=', '=' in final path element: %s",
98 parts[len(parts)-1])
99 }
100
101 if len(last) > 1 {
102 r.Value = last[1]
103 }
104
105 r.Path = append(parts[:len(parts)-1], last[0]) //nolint:gocritic
106 return nil
107 }
108
109 func (r *GrepRunner) runE(c *cobra.Command, args []string) error {
110 if len(args) == 1 {
111 input := &kio.ByteReader{Reader: c.InOrStdin()}
112 return runner.HandleError(c, kio.Pipeline{
113 Inputs: []kio.Reader{input},
114 Filters: []kio.Filter{r.GrepFilter},
115 Outputs: []kio.Writer{kio.ByteWriter{
116 Writer: c.OutOrStdout(),
117 KeepReaderAnnotations: r.KeepAnnotations,
118 }},
119 }.Execute())
120 }
121
122 out := bytes.Buffer{}
123
124 e := runner.ExecuteCmdOnPkgs{
125 Writer: &out,
126 NeedOpenAPI: false,
127 RecurseSubPackages: r.RecurseSubPackages,
128 CmdRunner: r,
129 RootPkgPath: args[1],
130 SkipPkgPathPrint: true,
131 }
132
133 err := e.Execute()
134 if err != nil {
135 return err
136 }
137
138 res := strings.TrimSuffix(out.String(), "---")
139 fmt.Fprintf(c.OutOrStdout(), "%s", res)
140
141 return nil
142 }
143
144 func (r *GrepRunner) ExecuteCmd(w io.Writer, pkgPath string) error {
145 input := kio.LocalPackageReader{PackagePath: pkgPath, PackageFileName: ext.KRMFileName()}
146 out := &bytes.Buffer{}
147 err := kio.Pipeline{
148 Inputs: []kio.Reader{input},
149 Filters: []kio.Filter{r.GrepFilter},
150 Outputs: []kio.Writer{kio.ByteWriter{
151 Writer: out,
152 KeepReaderAnnotations: r.KeepAnnotations,
153 }},
154 }.Execute()
155
156 if err != nil {
157 // return err if there is only package
158 if !r.RecurseSubPackages {
159 return err
160 }
161 // print error message and continue if there are multiple packages to annotate
162 fmt.Fprintf(w, "%s\n", err.Error())
163 }
164 fmt.Fprint(w, out.String())
165 if out.String() != "" {
166 fmt.Fprint(w, "---")
167 }
168 return nil
169 }