Skip to content

Commit

Permalink
Format output of describe cmds as json
Browse files Browse the repository at this point in the history
  • Loading branch information
buddhike committed Oct 28, 2017
1 parent f0bdd8e commit af364e5
Showing 1 changed file with 35 additions and 6 deletions.
41 changes: 35 additions & 6 deletions cmd/describe.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package cmd

import (
"encoding/json"
"errors"
"fmt"
"strings"
Expand All @@ -9,6 +10,16 @@ import (
"github.com/spf13/cobra"
)

var (
formatAsJson bool
)

type applicationView struct {
Name string
Path string
Version string
}

func init() {
describePrCmd.Flags().StringVar(&src, "src", "", "source branch")
describePrCmd.Flags().StringVar(&dst, "dst", "", "destination branch")
Expand All @@ -17,6 +28,7 @@ func init() {
describeIntersectionCmd.Flags().StringVar(&first, "first", "", "first item")
describeIntersectionCmd.Flags().StringVar(&second, "second", "", "second item")

describeCmd.PersistentFlags().BoolVar(&formatAsJson, "json", false, "format output as json")
describeCmd.AddCommand(describeCommitCmd)
describeCmd.AddCommand(describeBranchCmd)
describeCmd.AddCommand(describePrCmd)
Expand Down Expand Up @@ -124,8 +136,7 @@ var describeIntersectionCmd = &cobra.Command{
return handle(err)
}

output(apps)
return nil
return handle(output(apps))
},
}

Expand All @@ -144,9 +155,27 @@ func formatRow(args ...interface{}) string {
return fmt.Sprintf("%s\t\t%s\t\t%s\n", padded...)
}

func output(apps lib.Applications) {
fmt.Print(formatRow("NAME", "PATH", "VERSION"))
for _, a := range apps {
fmt.Printf(formatRow(a.Name(), a.Path(), a.Version()))
func output(apps lib.Applications) error {
if formatAsJson {
v := make([]applicationView, len(apps))
for i, a := range apps {
v[i] = applicationView{
Name: a.Name(),
Path: a.Path(),
Version: a.Version(),
}
}
buff, err := json.MarshalIndent(v, "", " ")
if err != nil {
return err
}
fmt.Println(string(buff))
} else {
fmt.Print(formatRow("NAME", "PATH", "VERSION"))
for _, a := range apps {
fmt.Printf(formatRow(a.Name(), a.Path(), a.Version()))
}
}

return nil
}

0 comments on commit af364e5

Please sign in to comment.