-
Notifications
You must be signed in to change notification settings - Fork 257
feat: add 'cat' command for displaying package resources #4505
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
aravindtga
wants to merge
4
commits into
kptdev:main
Choose a base branch
from
Nordix:add-kpt-pkg-cat
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
73e1bca
feat: add 'cat' command for displaying package resources
aravindtga fcc0434
Address copilot review comments
aravindtga bdffd40
update copyright year and improve error handling in cmdcat
aravindtga 145d498
improve error handling in pkg cat command to include package context
aravindtga File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,162 @@ | ||
| // Copyright 2019,2026 The Kubernetes Authors. | ||
| // SPDX-License-Identifier: Apache-2.0 | ||
|
|
||
| package cmdcat | ||
|
|
||
| import ( | ||
| "bytes" | ||
| "context" | ||
| "fmt" | ||
| "io" | ||
| "os" | ||
| "path/filepath" | ||
| "strings" | ||
|
|
||
| "github.com/kptdev/kpt/internal/docs/generated/pkgdocs" | ||
| kptfilev1 "github.com/kptdev/kpt/pkg/api/kptfile/v1" | ||
| "github.com/kptdev/kpt/thirdparty/cmdconfig/commands/runner" | ||
| "github.com/spf13/cobra" | ||
| "sigs.k8s.io/kustomize/kyaml/kio" | ||
| "sigs.k8s.io/kustomize/kyaml/kio/filters" | ||
| "sigs.k8s.io/kustomize/kyaml/yaml" | ||
| ) | ||
|
|
||
| // GetCatRunner returns a command CatRunner. | ||
| func GetCatRunner(ctx context.Context, _ string) *CatRunner { | ||
| r := &CatRunner{ | ||
| Ctx: ctx, | ||
| } | ||
| c := &cobra.Command{ | ||
| Use: "cat [FILE | DIR]", | ||
| Short: pkgdocs.CatShort, | ||
| Long: pkgdocs.CatLong, | ||
| Example: pkgdocs.CatExamples, | ||
| RunE: r.runE, | ||
| Args: cobra.MaximumNArgs(1), | ||
| } | ||
| c.Flags().BoolVar(&r.Format, "format", true, | ||
| "format resource config yaml before printing.") | ||
| c.Flags().BoolVar(&r.KeepAnnotations, "annotate", false, | ||
| "annotate resources with their file origins.") | ||
| c.Flags().StringSliceVar(&r.Styles, "style", []string{}, | ||
| "yaml styles to apply. may be 'TaggedStyle', 'DoubleQuotedStyle', 'LiteralStyle', "+ | ||
| "'FoldedStyle', 'FlowStyle'.") | ||
| c.Flags().BoolVar(&r.StripComments, "strip-comments", false, | ||
| "remove comments from yaml.") | ||
| c.Flags().BoolVarP(&r.RecurseSubPackages, "recurse-subpackages", "R", true, | ||
| "print resources recursively in all the nested subpackages") | ||
| r.Command = c | ||
| return r | ||
| } | ||
|
|
||
| func NewCommand(ctx context.Context, name string) *cobra.Command { | ||
| return GetCatRunner(ctx, name).Command | ||
| } | ||
|
|
||
| // CatRunner contains the run function | ||
| type CatRunner struct { | ||
| Command *cobra.Command | ||
| Ctx context.Context | ||
| Format bool | ||
| KeepAnnotations bool | ||
| Styles []string | ||
| StripComments bool | ||
| RecurseSubPackages bool | ||
| } | ||
|
|
||
| func (r *CatRunner) runE(c *cobra.Command, args []string) error { | ||
| var writer = c.OutOrStdout() | ||
| if len(args) == 0 { | ||
| args = append(args, ".") | ||
| } | ||
|
|
||
| if info, err := os.Stat(args[0]); err == nil && !info.IsDir() { | ||
| switch strings.ToLower(filepath.Ext(args[0])) { | ||
| case ".yaml", ".yml", ".json": | ||
| default: | ||
| if filepath.Base(args[0]) == kptfilev1.KptFileName { | ||
| return fmt.Errorf("%q is a %s package metadata file, not a resource file; no resources will be read", args[0], kptfilev1.KptFileName) | ||
| } | ||
| return fmt.Errorf("%q is not a YAML/JSON file; no resources will be read", args[0]) | ||
| } | ||
| } | ||
|
|
||
| out := &bytes.Buffer{} | ||
| e := runner.ExecuteCmdOnPkgs{ | ||
| Writer: out, | ||
| NeedOpenAPI: false, | ||
| RecurseSubPackages: r.RecurseSubPackages, | ||
| CmdRunner: r, | ||
| RootPkgPath: filepath.Clean(args[0]), | ||
| SkipPkgPathPrint: true, | ||
| } | ||
|
|
||
| err := e.Execute() | ||
| if err != nil { | ||
| return err | ||
| } | ||
|
|
||
| res := strings.TrimSuffix(out.String(), "---\n") | ||
| res = strings.TrimSuffix(res, "---") | ||
| fmt.Fprintf(writer, "%s", res) | ||
|
|
||
|
aravindtga marked this conversation as resolved.
|
||
| return nil | ||
| } | ||
|
|
||
| func (r *CatRunner) ExecuteCmd(w io.Writer, pkgPath string) error { | ||
| input := kio.LocalPackageReader{PackagePath: pkgPath, PackageFileName: kptfilev1.KptFileName} | ||
| out := &bytes.Buffer{} | ||
| err := kio.Pipeline{ | ||
| Inputs: []kio.Reader{input}, | ||
| Filters: r.catFilters(), | ||
| Outputs: r.outputWriter(out), | ||
| }.Execute() | ||
|
|
||
| if err != nil { | ||
| // Wrap with package context so the user knows which package failed; | ||
| // the root command's error handler is responsible for printing. | ||
| return fmt.Errorf("kpt pkg cat: %q: %w", pkgPath, err) | ||
| } | ||
| outStr := out.String() | ||
| fmt.Fprint(w, outStr) | ||
| if outStr != "" { | ||
| fmt.Fprint(w, "---") | ||
| } | ||
| return nil | ||
| } | ||
|
|
||
| func (r *CatRunner) catFilters() []kio.Filter { | ||
| var fltrs []kio.Filter | ||
| if r.Format { | ||
| fltrs = append(fltrs, filters.FormatFilter{}) | ||
| } | ||
| if r.StripComments { | ||
| fltrs = append(fltrs, filters.StripCommentsFilter{}) | ||
| } | ||
| return fltrs | ||
| } | ||
|
|
||
| func (r *CatRunner) outputWriter(w io.Writer) []kio.Writer { | ||
| var outputs []kio.Writer | ||
| var functionConfig *yaml.RNode | ||
|
|
||
| // remove these annotations explicitly; the ByteWriter won't clear them by | ||
| // default because they were set by the LocalPackageReader, not by it. | ||
| clear := []string{ | ||
| "config.kubernetes.io/path", | ||
| "internal.config.kubernetes.io/path", | ||
| } | ||
| if r.KeepAnnotations { | ||
| clear = nil | ||
| } | ||
|
|
||
| outputs = append(outputs, kio.ByteWriter{ | ||
| Writer: w, | ||
| KeepReaderAnnotations: r.KeepAnnotations, | ||
| FunctionConfig: functionConfig, | ||
| Style: yaml.GetStyle(r.Styles...), | ||
| ClearAnnotations: clear, | ||
| }) | ||
|
|
||
| return outputs | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.