diff --git a/cmd/flux/tree_kustomization.go b/cmd/flux/tree_kustomization.go index 8dff24bf..79964d76 100644 --- a/cmd/flux/tree_kustomization.go +++ b/cmd/flux/tree_kustomization.go @@ -18,6 +18,7 @@ package main import ( "context" + "encoding/json" "fmt" "strings" @@ -28,6 +29,7 @@ import ( "k8s.io/apimachinery/pkg/runtime/schema" "sigs.k8s.io/cli-utils/pkg/object" "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/yaml" ) var treeKsCmd = &cobra.Command{ @@ -45,12 +47,15 @@ var treeKsCmd = &cobra.Command{ type TreeKsFlags struct { compact bool + output string } var treeKsArgs TreeKsFlags func init() { treeKsCmd.Flags().BoolVar(&treeKsArgs.compact, "compact", false, "list Flux resources only.") + treeKsCmd.Flags().StringVarP(&treeKsArgs.output, "output", "o", "", + "the format in which the tree should be printed. can be 'json' or 'yaml'") treeCmd.AddCommand(treeKsCmd) } @@ -89,7 +94,22 @@ func treeKsCmdRun(cmd *cobra.Command, args []string) error { return err } - rootCmd.Println(kTree.Print()) + switch treeKsArgs.output { + case "json": + data, err := json.MarshalIndent(kTree, "", " ") + if err != nil { + return err + } + rootCmd.Println(string(data)) + case "yaml": + data, err := yaml.Marshal(kTree) + if err != nil { + return err + } + rootCmd.Println(string(data)) + default: + rootCmd.Println(kTree.Print()) + } return nil } diff --git a/internal/tree/tree.go b/internal/tree/tree.go index d238effb..b651a19a 100644 --- a/internal/tree/tree.go +++ b/internal/tree/tree.go @@ -36,8 +36,8 @@ const ( type ( objMetadataTree struct { - objMetadata object.ObjMetadata - items []ObjMetadataTree + Resource object.ObjMetadata `json:"resource"` + ResourceTree []ObjMetadataTree `json:"resources,omitempty"` } ObjMetadataTree interface { @@ -58,27 +58,27 @@ type ( func New(objMetadata object.ObjMetadata) ObjMetadataTree { return &objMetadataTree{ - objMetadata: objMetadata, - items: []ObjMetadataTree{}, + Resource: objMetadata, + ResourceTree: []ObjMetadataTree{}, } } func (t *objMetadataTree) Add(objMetadata object.ObjMetadata) ObjMetadataTree { n := New(objMetadata) - t.items = append(t.items, n) + t.ResourceTree = append(t.ResourceTree, n) return n } func (t *objMetadataTree) AddTree(tree ObjMetadataTree) { - t.items = append(t.items, tree) + t.ResourceTree = append(t.ResourceTree, tree) } func (t *objMetadataTree) Text() string { - return ssa.FmtObjMetadata(t.objMetadata) + return ssa.FmtObjMetadata(t.Resource) } func (t *objMetadataTree) Items() []ObjMetadataTree { - return t.items + return t.ResourceTree } func (t *objMetadataTree) Print() string {