Skip to content
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

Json format in getall and list #53

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 19 additions & 2 deletions cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 {
Expand All @@ -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
Expand Down
6 changes: 6 additions & 0 deletions cmd/unicreds/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()})
Expand All @@ -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})
Expand Down