Skip to content

Commit

Permalink
Print Krmfile data for cfg tree
Browse files Browse the repository at this point in the history
  • Loading branch information
phanimarupaka committed Sep 14, 2020
1 parent 5c8c7a0 commit 880009b
Show file tree
Hide file tree
Showing 6 changed files with 152 additions and 32 deletions.
1 change: 1 addition & 0 deletions cmd/config/go.sum
Expand Up @@ -623,6 +623,7 @@ sigs.k8s.io/controller-runtime v0.4.0 h1:wATM6/m+3w8lj8FXNaO6Fs/rq/vqoOjO1Q116Z9
sigs.k8s.io/controller-runtime v0.4.0/go.mod h1:ApC79lpY3PHW9xj/w9pj+lYkLgwAAUZwfXkME1Lajns=
sigs.k8s.io/kustomize v2.0.3+incompatible h1:JUufWFNlI44MdtnjUqVnvh29rR37PQFzPbLXqhyOyX0=
sigs.k8s.io/kustomize v2.0.3+incompatible/go.mod h1:MkjgH3RdOWrievjo6c9T245dYlB5QeXV4WCbnt/PEpU=
sigs.k8s.io/kustomize/cmd/config v0.7.0/go.mod h1:ORl2Fv3uSV4Wr8FKynZUFe8Xb5ct/bVZrzbiz+/GEFs=
sigs.k8s.io/structured-merge-diff v0.0.0-20190525122527-15d366b2352e/go.mod h1:wWxsB5ozmmv/SG7nM11ayaAW51xMvak/t1r0CSlcokI=
sigs.k8s.io/structured-merge-diff v0.0.0-20190817042607-6149e4549fca/go.mod h1:IIgPezJWb76P0hotTxzDbWsMYB8APh18qZnxkomBpxA=
sigs.k8s.io/structured-merge-diff v1.0.1-0.20191108220359-b1b620dd3f06 h1:zD2IemQ4LmOcAumeiyDWXKUI2SO0NYDe3H6QGvPOVgU=
Expand Down
7 changes: 2 additions & 5 deletions cmd/config/internal/commands/grep.go
Expand Up @@ -29,8 +29,6 @@ func GetGrepRunner(name string) *GrepRunner {
Args: cobra.MaximumNArgs(2),
}
fixDocs(name, c)
c.Flags().BoolVar(&r.IncludeSubpackages, "include-subpackages", true,
"also print resources from subpackages.")
c.Flags().BoolVar(&r.KeepAnnotations, "annotate", true,
"annotate resources with their file origins.")
c.Flags().BoolVarP(&r.InvertMatch, "invert-match", "", false,
Expand All @@ -47,9 +45,8 @@ func GrepCommand(name string) *cobra.Command {

// GrepRunner contains the run function
type GrepRunner struct {
IncludeSubpackages bool
KeepAnnotations bool
Command *cobra.Command
KeepAnnotations bool
Command *cobra.Command
filters.GrepFilter
Format bool
RecurseSubPackages bool
Expand Down
43 changes: 24 additions & 19 deletions cmd/config/internal/commands/tree.go
Expand Up @@ -7,6 +7,7 @@ import (
"path/filepath"
"strings"

"sigs.k8s.io/kustomize/cmd/config/ext"
"sigs.k8s.io/kustomize/cmd/config/internal/generateddocs/commands"
"sigs.k8s.io/kustomize/kyaml/kio/filters"

Expand All @@ -26,8 +27,6 @@ func GetTreeRunner(name string) *TreeRunner {
Args: cobra.MaximumNArgs(1),
}
fixDocs(name, c)
c.Flags().BoolVar(&r.IncludeSubpackages, "include-subpackages", true,
"also print resources from subpackages.")

// TODO(pwittrock): Figure out if these are the right things to expose, and consider making it
// a list of options instead of individual flags
Expand Down Expand Up @@ -59,29 +58,33 @@ func TreeCommand(name string) *cobra.Command {

// TreeRunner contains the run function
type TreeRunner struct {
IncludeSubpackages bool
Command *cobra.Command
name bool
resources bool
ports bool
images bool
replicas bool
all bool
env bool
args bool
cmd bool
fields []string
includeLocal bool
excludeNonLocal bool
structure string
Command *cobra.Command
name bool
resources bool
ports bool
images bool
replicas bool
all bool
env bool
args bool
cmd bool
fields []string
includeLocal bool
excludeNonLocal bool
structure string
}

func (r *TreeRunner) runE(c *cobra.Command, args []string) error {
var input kio.Reader
var root = "."
openAPIFileName, err := ext.OpenAPIFileName()
if err != nil {
return err
}
matchFilesGlob := append([]string{openAPIFileName}, kio.DefaultMatch...)
if len(args) == 1 {
root = filepath.Clean(args[0])
input = kio.LocalPackageReader{PackagePath: args[0]}
input = kio.LocalPackageReader{PackagePath: args[0], MatchFilesGlob: matchFilesGlob}
} else {
input = &kio.ByteReader{Reader: c.InOrStdin()}
}
Expand Down Expand Up @@ -159,7 +162,9 @@ func (r *TreeRunner) runE(c *cobra.Command, args []string) error {
Root: root,
Writer: c.OutOrStdout(),
Fields: fields,
Structure: kio.TreeStructure(r.structure)}},
Structure: kio.TreeStructure(r.structure),
OpenAPIFileName: openAPIFileName,
}},
}.Execute())
}

Expand Down
103 changes: 103 additions & 0 deletions cmd/config/internal/commands/tree_test.go
Expand Up @@ -90,6 +90,109 @@ spec:
}
}

func TestTreeCommand_subpkgs(t *testing.T) {
d, err := ioutil.TempDir("", "kustomize-tree-test")
defer os.RemoveAll(d)
if !assert.NoError(t, err) {
t.FailNow()
}

err = os.MkdirAll(filepath.Join(d, "subpkg"), 0700)
if !assert.NoError(t, err) {
t.FailNow()
}

err = ioutil.WriteFile(filepath.Join(d, "f1.yaml"), []byte(`
apiVersion: v1
kind: Abstraction
metadata:
name: foo
configFn:
container:
image: gcr.io/example/reconciler:v1
annotations:
config.kubernetes.io/local-config: "true"
spec:
replicas: 1
---
kind: Deployment
metadata:
labels:
app: nginx2
name: foo
annotations:
app: nginx2
spec:
replicas: 1
---
kind: Service
metadata:
name: foo
annotations:
app: nginx
spec:
selector:
app: nginx
`), 0600)
if !assert.NoError(t, err) {
return
}
err = ioutil.WriteFile(filepath.Join(d, "subpkg", "f2.yaml"), []byte(`kind: Deployment
metadata:
labels:
app: nginx
name: bar
annotations:
app: nginx
spec:
replicas: 3
`), 0600)
if !assert.NoError(t, err) {
return
}

err = ioutil.WriteFile(filepath.Join(d, "Krmfile"), []byte(`apiVersion: kpt.dev/v1alpha1
kind: Krmfile
metadata:
name: mainpkg
openAPI:
definitions:
`), 0600)
if !assert.NoError(t, err) {
return
}
err = ioutil.WriteFile(filepath.Join(d, "subpkg", "Krmfile"), []byte(`apiVersion: kpt.dev/v1alpha1
kind: Krmfile
metadata:
name: subpkg
openAPI:
definitions:
`), 0600)
if !assert.NoError(t, err) {
return
}

// fmt the files
b := &bytes.Buffer{}
r := commands.GetTreeRunner("")
r.Command.SetArgs([]string{d})
r.Command.SetOut(b)
if !assert.NoError(t, r.Command.Execute()) {
return
}

if !assert.Equal(t, fmt.Sprintf(`%s
├── [Krmfile] Krmfile mainpkg
├── [f1.yaml] Deployment foo
├── [f1.yaml] Service foo
└── Pkg: subpkg
├── [Krmfile] Krmfile subpkg
└── [f2.yaml] Deployment bar
`, d), b.String()) {
return
}
}

func TestTreeCommand_stdin(t *testing.T) {
// fmt the files
b := &bytes.Buffer{}
Expand Down
25 changes: 20 additions & 5 deletions kyaml/kio/tree.go
Expand Up @@ -6,6 +6,7 @@ package kio
import (
"fmt"
"io"
"os"
"path/filepath"
"sort"
"strings"
Expand Down Expand Up @@ -33,10 +34,11 @@ var GraphStructures = []string{string(TreeStructureGraph), string(TreeStructureP
// TODO(pwittrock): test this package better. it is lower-risk since it is only
// used for printing rather than updating or editing.
type TreeWriter struct {
Writer io.Writer
Root string
Fields []TreeWriterField
Structure TreeStructure
Writer io.Writer
Root string
Fields []TreeWriterField
Structure TreeStructure
OpenAPIFileName string
}

// TreeWriterField configures a Resource field to be included in the tree
Expand Down Expand Up @@ -72,7 +74,7 @@ func (p TreeWriter) packageStructure(nodes []*yaml.RNode) error {
// create a new branch for the package
createOk := pkg != "." // special edge case logic for tree on current working dir
if createOk {
branch = branch.AddBranch(pkg)
branch = branch.AddBranch(branchName(p.Root, pkg, p.OpenAPIFileName))
}

// cache the branch for this package
Expand All @@ -91,6 +93,19 @@ func (p TreeWriter) packageStructure(nodes []*yaml.RNode) error {
return err
}

// branchName takes the root directory and relative path to the directory
// and returns the branch name
func branchName(root, dirRelPath, openAPIFileName string) string {
name := filepath.Base(dirRelPath)
_, err := os.Stat(filepath.Join(root, dirRelPath, openAPIFileName))
if !os.IsNotExist(err) {
// add Pkg: prefix indicating that it is a separate package as it has
// openAPIFile
return fmt.Sprintf("Pkg: %s", name)
}
return name
}

// Write writes the ascii tree to p.Writer
func (p TreeWriter) Write(nodes []*yaml.RNode) error {
switch p.Structure {
Expand Down
5 changes: 2 additions & 3 deletions kyaml/kio/tree_test.go
Expand Up @@ -6,7 +6,6 @@ package kio_test
import (
"bytes"
"fmt"
"path/filepath"
"testing"

"github.com/stretchr/testify/assert"
Expand Down Expand Up @@ -76,9 +75,9 @@ spec:
└── foo-package
├── [f1.yaml] Deployment default/foo
├── [f1.yaml] Service default/foo
└── foo-package%s3
└── 3
└── [f3.yaml] Deployment default/foo
`, string(filepath.Separator)), out.String()) {
`), out.String()) {
t.FailNow()
}
}
Expand Down

0 comments on commit 880009b

Please sign in to comment.