mukan-ignite/ignite/pkg/cliui/entrywriter/entrywriter.go
Mukan Erkin Törük c32551b6f7
Some checks failed
Docs Deploy / build_and_deploy (push) Has been cancelled
Generate Docs / cli (push) Has been cancelled
Generate Config Doc / cli (push) Has been cancelled
Go formatting / go-formatting (push) Has been cancelled
Check links / markdown-link-check (push) Has been cancelled
Integration / pre-test (push) Has been cancelled
Integration / test on (push) Has been cancelled
Integration / status (push) Has been cancelled
Lint / Lint Go code (push) Has been cancelled
Test / test (ubuntu-latest) (push) Has been cancelled
refactor: replace all github.com upstream refs with git.cw.tr/mukan-network
2026-05-11 03:36:24 +03:00

65 lines
1.4 KiB
Go

package entrywriter
import (
"fmt"
"io"
"text/tabwriter"
"git.cw.tr/mukan-network/mukan-ignite/ignite/pkg/errors"
"git.cw.tr/mukan-network/mukan-ignite/ignite/pkg/xstrings"
)
const (
None = "-"
)
var ErrInvalidFormat = errors.New("invalid entry format")
// MustWrite writes into out the tabulated entries and panic if the entry format is invalid.
func MustWrite(out io.Writer, header []string, entries ...[]string) error {
err := Write(out, header, entries...)
if errors.Is(err, ErrInvalidFormat) {
panic(err)
}
return err
}
// Write writes into out the tabulated entries.
func Write(out io.Writer, header []string, entries ...[]string) error {
w := &tabwriter.Writer{}
w.Init(out, 0, 8, 0, '\t', 0)
formatLine := func(line []string, title bool) (formatted string) {
for _, cell := range line {
if title {
cell = xstrings.Title(cell)
}
formatted += fmt.Sprintf("%s \t", cell)
}
return formatted
}
if len(header) == 0 {
return errors.Wrap(ErrInvalidFormat, "empty header")
}
// write header
if _, err := fmt.Fprintln(w, formatLine(header, true)); err != nil {
return err
}
// write entries
for i, entry := range entries {
if len(entry) != len(header) {
return errors.Wrapf(ErrInvalidFormat, "entry %d doesn't match header length", i)
}
if _, err := fmt.Fprint(w, formatLine(entry, false)+"\n"); err != nil {
return err
}
}
if _, err := fmt.Fprintln(w); err != nil {
return err
}
return w.Flush()
}