Skip to content

Commit

Permalink
More flexible options for table JSON output
Browse files Browse the repository at this point in the history
  • Loading branch information
stoewer committed Oct 12, 2023
1 parent dfe8aa8 commit 23fe51d
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 8 deletions.
4 changes: 0 additions & 4 deletions pkg/inspect/file_info.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,10 +76,6 @@ func (r infoRow) Cells() []any {
return r
}

func (r infoRow) Data() any {
return r
}

func footerSize(file *os.File) (uint32, error) {
stat, err := file.Stat()
if err != nil {
Expand Down
22 changes: 18 additions & 4 deletions pkg/output/output.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,15 +37,19 @@ type Table interface {
NextRow() (TableRow, error)
}

// SerializableData represents table data that can be converted to JSON.
type SerializableData interface {
// Data returns the table data suitable for structured data formats
// such as json.
Data() any
}

// A TableRow represents all data that belongs to a table row.
type TableRow interface {
// Cells returns all table cells for this row. This is used to
// print tabular formats such csv. The returned slice has the same
// length as the header slice returned by the parent Table.
Cells() []any
// Data returns the table row suitable for structured data formats
// such as json.
Data() any
}

// PrintTable writes the Table data to w using the provided format.
Expand Down Expand Up @@ -125,6 +129,12 @@ func printCSV(w io.Writer, data Table) error {
}

func printJSON(w io.Writer, data Table) error {
if serializable, ok := data.(SerializableData); ok {
enc := json.NewEncoder(w)
enc.SetIndent("", " ")
return enc.Encode(serializable.Data())
}

_, err := fmt.Fprintln(w, "[")
if err != nil {
return err
Expand All @@ -143,9 +153,13 @@ func printJSON(w io.Writer, data Table) error {
if err != nil {
return err
}
serializableRow, ok := row.(SerializableData)
if !ok {
return errors.New("JSON not supported for sub command")
}

buf.Reset()
err = json.NewEncoder(buf).Encode(row.Data())
err = json.NewEncoder(buf).Encode(serializableRow.Data())
if err != nil {
return err
}
Expand Down

0 comments on commit 23fe51d

Please sign in to comment.