@@ -3,6 +3,7 @@ package cli
3
3
import (
4
4
"bytes"
5
5
"encoding/json"
6
+ "errors"
6
7
"fmt"
7
8
"image/color"
8
9
"net/http"
@@ -18,6 +19,7 @@ import (
18
19
"golang.org/x/crypto/ssh/terminal"
19
20
"gopkg.in/yaml.v2"
20
21
22
+ "github.com/alexeyco/simpletable"
21
23
"github.com/eliukblau/pixterm/pkg/ansimage"
22
24
)
23
25
@@ -160,6 +162,22 @@ func (f *DefaultFormatter) Format(resp Response) error {
160
162
161
163
handled := false
162
164
kind := reflect .ValueOf (data ).Kind ()
165
+
166
+ // Handle table formatting
167
+ if viper .GetBool ("rsh-table" ) && kind == reflect .Slice {
168
+ d , ok := data .([]interface {})
169
+ if ok {
170
+ ret , err := setTable (d )
171
+ if err != nil {
172
+ return err
173
+ }
174
+ encoded = * ret
175
+ handled = true
176
+ } else {
177
+ return errors .New ("error building table. Collection not supported. Must be array of objects" )
178
+ }
179
+ }
180
+
163
181
if viper .GetBool ("rsh-raw" ) && kind == reflect .String {
164
182
handled = true
165
183
dStr := data .(string )
@@ -311,3 +329,49 @@ func (f *DefaultFormatter) Format(resp Response) error {
311
329
312
330
return nil
313
331
}
332
+
333
+ // Only applicable to collection of repeating objects.
334
+ // Filter down to a collection of objects first then apply --table.
335
+ // Simpletable has much more styling that can be applied.
336
+ func setTable (data []interface {}) (* []byte , error ) {
337
+ table := simpletable .New ()
338
+
339
+ var headerCells []* simpletable.Cell
340
+ defineHeader := true
341
+ for _ , maps := range data {
342
+ var bodyCells []* simpletable.Cell
343
+ if mapData , ok := maps .(map [string ]interface {}); ok {
344
+ // Discover headers for repeating objects
345
+ // Iterate first instance of one of the repeating objects
346
+ if defineHeader {
347
+ for k , _ := range mapData {
348
+ headerCells = append (headerCells , & simpletable.Cell {Align : simpletable .AlignCenter , Text : k })
349
+ }
350
+ }
351
+ defineHeader = false
352
+
353
+ // Add body cells based on order of header cells
354
+ // Will gt out of order otherwise
355
+ for _ , cellKey := range headerCells {
356
+ if val , ok := mapData [cellKey .Text ]; ok {
357
+ bodyCells = append (bodyCells , & simpletable.Cell {Align : simpletable .AlignRight , Text : fmt .Sprintf ("%v" , val )})
358
+ } else {
359
+ return nil , fmt .Errorf ("error building table. Header Key not found in repeating object: %s" , cellKey .Text )
360
+ }
361
+ }
362
+ table .Body .Cells = append (table .Body .Cells , bodyCells )
363
+ } else {
364
+ // Defensive just in case
365
+ return nil , errors .New ("error building table. Collection not supported" )
366
+ }
367
+ }
368
+
369
+ table .Header = & simpletable.Header {
370
+ Cells : headerCells ,
371
+ }
372
+
373
+ table .SetStyle (simpletable .StyleCompactLite )
374
+
375
+ ret := []byte (table .String ())
376
+ return & ret , nil
377
+ }
0 commit comments