Some checks are pending
Docs Deploy / build_and_deploy (push) Waiting to run
Generate Docs / cli (push) Waiting to run
Generate Config Doc / cli (push) Waiting to run
Go formatting / go-formatting (push) Waiting to run
Check links / markdown-link-check (push) Waiting to run
Integration / pre-test (push) Waiting to run
Integration / test on (push) Blocked by required conditions
Integration / status (push) Blocked by required conditions
Lint / Lint Go code (push) Waiting to run
Test / test (ubuntu-latest) (push) Waiting to run
65 lines
1.4 KiB
Go
65 lines
1.4 KiB
Go
package entrywriter
|
|
|
|
import (
|
|
"fmt"
|
|
"io"
|
|
"text/tabwriter"
|
|
|
|
"github.com/ignite/cli/v29/ignite/pkg/errors"
|
|
"github.com/ignite/cli/v29/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()
|
|
}
|