Add simple ascii table implementation

This commit is contained in:
Alexander Neumann 2014-11-25 22:38:14 +01:00
parent 553053afd9
commit ad7e1d043f

View file

@ -3,6 +3,7 @@ package main
import ( import (
"errors" "errors"
"fmt" "fmt"
"io"
"os" "os"
"sort" "sort"
"strings" "strings"
@ -19,6 +20,39 @@ const (
week = 7 * day week = 7 * day
) )
type Table struct {
Header string
Rows [][]interface{}
RowFormat string
}
func NewTable() Table {
return Table{
Rows: [][]interface{}{},
}
}
func (t Table) Print(w io.Writer) error {
_, err := fmt.Fprintln(w, t.Header)
if err != nil {
return err
}
_, err = fmt.Fprintln(w, strings.Repeat("-", 70))
if err != nil {
return err
}
for _, row := range t.Rows {
_, err = fmt.Fprintf(w, t.RowFormat+"\n", row...)
if err != nil {
return err
}
}
return nil
}
const TimeFormat = "2006-01-02 15:04:05" const TimeFormat = "2006-01-02 15:04:05"
func reltime(t time.Time) string { func reltime(t time.Time) string {
@ -48,15 +82,11 @@ func commandSnapshots(be backend.Server, key *khepri.Key, args []string) error {
return err return err
} }
fmt.Printf("%-8s %-19s %-10s %s\n", "ID", "Date", "Source", "Directory") tab := NewTable()
fmt.Printf("%s\n", strings.Repeat("-", 80)) tab.Header = fmt.Sprintf("%-8s %-19s %-10s %s\n", "ID", "Date", "Source", "Directory")
tab.RowFormat = "%-8s %-19s %-10s %s"
list := []*khepri.Snapshot{} list := []*khepri.Snapshot{}
plen, err := backend.PrefixLength(be, backend.Snapshot)
if err != nil {
return err
}
backend.EachID(be, backend.Snapshot, func(id backend.ID) { backend.EachID(be, backend.Snapshot, func(id backend.ID) {
sn, err := ch.LoadSnapshot(id) sn, err := ch.LoadSnapshot(id)
if err != nil { if err != nil {
@ -77,9 +107,16 @@ func commandSnapshots(be backend.Server, key *khepri.Key, args []string) error {
} }
}) })
for _, sn := range list { plen, err := backend.PrefixLength(be, backend.Snapshot)
fmt.Printf("%-8s %-19s %-10s %s\n", sn.ID()[:plen], sn.Time.Format(TimeFormat), sn.Hostname, sn.Dir) if err != nil {
return err
} }
for _, sn := range list {
tab.Rows = append(tab.Rows, []interface{}{sn.ID()[:plen], sn.Time.Format(TimeFormat), sn.Hostname, sn.Dir})
}
tab.Print(os.Stdout)
return nil return nil
} }