Skip to content

Latest commit

 

History

History
165 lines (127 loc) · 3.77 KB

README.adoc

File metadata and controls

165 lines (127 loc) · 3.77 KB

CLITable

Pretty print Data as tables on the command line.

CLI tool

The csvtable cli tool allows printing CSV data as a table:

go install github.com/DavidGamba/dgtools/clitable/cmd/csvtable@latest

To parse TSV data use the --tsv flag.

To normalize CSV data use the --normalize flag.

Library

Go Reference

import "github.com/DavidGamba/dgtools/clitable"

For simple tables of type [][]string:

simpleData := [][]string{{"Hello", "1"}, {"World", "2"}}
clitable.NewTablePrinter().Print(clitable.SimpleTable{simpleData})
┌───────┬───┐
│ Hello │ 1 │
├───────┼───┤
│ World │ 2 │
└───────┴───┘

For CSV from an io.Reader:

r := strings.NewReader("Hello,1\nWorld,2\n")
clitable.NewTablePrinter().FprintCSVReader(os.Stdout, r)

For TSV from an io.Reader:

r := strings.NewReader("Hello	1\nWorld	2\n")
clitable.NewTablePrinter().Separator('\t').FprintCSVReader(os.Stdout, r)
┌───────┬───┐
│ Hello │ 1 │
├───────┼───┤
│ World │ 2 │
└───────┴───┘

For iterating over structs you need to implement the table interface by adding a RowIterator function:

type Data struct {
	Info []struct {
		Name string
		ID   int
	}
}

func (d *Data) RowIterator() <-chan clitable.Row {
	c := make(chan clitable.Row)
	go func() {
		c <- clitable.Row{Fields: []string{"", "Name", "ID"}}
		for i, row := range d.Info {
			c <- clitable.Row{Fields: []string{strconv.Itoa(i + 1), row.Name, strconv.Itoa(row.ID)}}
		}
		close(c)
	}()
	return c
}

Then print:

data := &Data{[]struct {
  Name string
  ID   int
}{{"Hello", 1}, {"World", 2}}}

clitable.NewTablePrinter().Fprint(os.Stdout, data)
┌───┬───────┬────┐
│   │ Name  │ ID │
╞═══╪═══════╪════╡
│ 1 │ Hello │ 1  │
├───┼───────┼────┤
│ 2 │ World │ 2  │
└───┴───────┴────┘

Controlling style:

clitable.NewTablePrinter().SetStyle(clitable.Full).Print(data)

┌───┬───────┬────┐
│   │ NameID │
╞═══╪═══════╪════╡
│ 1Hello1  │
├───┼───────┼────┤
│ 2World2  │
└───┴───────┴────┘

clitable.NewTablePrinter().SetStyle(clitable.Full).HasHeader(false).Print(data)

┌───┬───────┬────┐
│   │ NameID │
├───┼───────┼────┤
│ 1Hello1  │
├───┼───────┼────┤
│ 2World2  │
└───┴───────┴────┘

clitable.NewTablePrinter().SetStyle(clitable.Compact).Print(data)

───┬───────┬────
   │ NameID
═══╪═══════╪════
 1Hello1
 2World2
───┴───────┴────

clitable.NewTablePrinter().SetStyle(clitable.Ascii).Print(data)

+---+-------+----+
|   | Name  | ID |
+===+=======+====+
| 1 | Hello | 1  |
+---+-------+----+
| 2 | World | 2  |
+---+-------+----+

clitable.NewTablePrinter().SetStyle(clitable.Space).Print(data)

     Name    ID
 1   Hello   1
 2   World   2

clitable.NewTablePrinter().SetStyle(clitable.CSV).Print(data)

,Name,ID
1,Hello,1
2,World,2