69 lines
1.6 KiB
Go
69 lines
1.6 KiB
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"io"
|
|
"strings"
|
|
"text/tabwriter"
|
|
"time"
|
|
)
|
|
|
|
// printTable writes a formatted table with tabwriter. The first row is treated
|
|
// as the header and separated from data rows by a rule of dashes.
|
|
func printTable(w io.Writer, rows [][]string) {
|
|
if len(rows) == 0 {
|
|
return
|
|
}
|
|
tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)
|
|
for i, row := range rows {
|
|
fmt.Fprintln(tw, strings.Join(row, "\t"))
|
|
if i == 0 {
|
|
// Print a divider matching the header width.
|
|
dashes := make([]string, len(row))
|
|
for j, h := range row {
|
|
dashes[j] = strings.Repeat("-", len(h))
|
|
}
|
|
fmt.Fprintln(tw, strings.Join(dashes, "\t"))
|
|
}
|
|
}
|
|
tw.Flush()
|
|
}
|
|
|
|
// fmtCount formats a count with a space as the thousands separator.
|
|
// e.g. 1234567 → "1 234 567"
|
|
func fmtCount(n int64) string {
|
|
s := fmt.Sprintf("%d", n)
|
|
if len(s) <= 3 {
|
|
return s
|
|
}
|
|
var b strings.Builder
|
|
start := len(s) % 3
|
|
if start > 0 {
|
|
b.WriteString(s[:start])
|
|
}
|
|
for i := start; i < len(s); i += 3 {
|
|
if i > 0 {
|
|
b.WriteByte(' ')
|
|
}
|
|
b.WriteString(s[i : i+3])
|
|
}
|
|
return b.String()
|
|
}
|
|
|
|
// fmtTime formats a unix timestamp as "2006-01-02 15:04" UTC.
|
|
func fmtTime(unix int64) string {
|
|
return time.Unix(unix, 0).UTC().Format("2006-01-02 15:04")
|
|
}
|
|
|
|
// targetHeader returns the header line to print before each target's results.
|
|
// Returns empty string when there is only one target (clean single-target output).
|
|
func targetHeader(target, source string, nTargets int) string {
|
|
if nTargets <= 1 {
|
|
return ""
|
|
}
|
|
if source != "" && source != target {
|
|
return fmt.Sprintf("=== %s (%s) ===", source, target)
|
|
}
|
|
return fmt.Sprintf("=== %s ===", target)
|
|
}
|