From 73bed41634e10d14952abd5685ff04681caf4c65 Mon Sep 17 00:00:00 2001 From: Mikko Date: Thu, 20 Oct 2016 17:45:05 +0100 Subject: [PATCH] Json format in getall and list --- cli.go | 21 +++++++++++++++++++-- cmd/unicreds/main.go | 6 ++++++ 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/cli.go b/cli.go index 5a4c293..47dbdf2 100644 --- a/cli.go +++ b/cli.go @@ -2,16 +2,18 @@ package unicreds import ( "encoding/csv" + "encoding/json" "io" - "github.com/olekukonko/tablewriter" + "strings" ) const ( // TableFormatTerm format the table for a terminal session TableFormatTerm = iota // 0 // TableFormatCSV format the table as CSV - TableFormatCSV // 1 + TableFormatCSV = 1 // 1 + TableFormatJSON = 2 // 2 ) // TableWriter enables writing of tables in a variety of formats @@ -46,6 +48,7 @@ func (tw *TableWriter) BulkWrite(rows [][]string) { tw.rows = append(tw.rows, rows...) } + // Render render the table out to the supplied writer func (tw *TableWriter) Render() error { switch tw.tableFormat { @@ -67,6 +70,20 @@ func (tw *TableWriter) Render() error { if err := w.Error(); err != nil { return err } + + case TableFormatJSON: + + encoder := json.NewEncoder(tw.wr) + value := make([] map[string]string, len(tw.rows)) + + for i := 0; i < len(tw.rows); i++ { + value[i] = make(map[string]string) + for j := 0; j < len(tw.headers); j++ { + value[i][tw.headers[j]] = tw.rows[i][j] + } + } + encoder.SetIndent(" ", " ") + encoder.Encode(value) } return nil diff --git a/cmd/unicreds/main.go b/cmd/unicreds/main.go index 9e0b33e..59e2e1b 100644 --- a/cmd/unicreds/main.go +++ b/cmd/unicreds/main.go @@ -152,6 +152,9 @@ func main() { if *csv { table.SetFormat(unicreds.TableFormatCSV) } + if *logJSON { + table.SetFormat(unicreds.TableFormatJSON) + } for _, cred := range creds { table.Write([]string{cred.Name, cred.Version, cred.CreatedAtDate()}) @@ -171,6 +174,9 @@ func main() { if *csv { table.SetFormat(unicreds.TableFormatCSV) } + if *logJSON { + table.SetFormat(unicreds.TableFormatJSON) + } for _, cred := range creds { table.Write([]string{cred.Name, cred.Secret})