github.com/ungtb10d/cli/v2@v2.0.0-20221110210412-98537dd9d6a1/internal/tableprinter/table_printer.go (about)

     1  package tableprinter
     2  
     3  import (
     4  	"strings"
     5  	"time"
     6  
     7  	"github.com/ungtb10d/cli/v2/internal/text"
     8  	"github.com/ungtb10d/cli/v2/pkg/iostreams"
     9  	"github.com/cli/go-gh/pkg/tableprinter"
    10  )
    11  
    12  type TablePrinter struct {
    13  	tableprinter.TablePrinter
    14  	isTTY bool
    15  }
    16  
    17  func (t *TablePrinter) HeaderRow(columns ...string) {
    18  	if !t.isTTY {
    19  		return
    20  	}
    21  	for _, col := range columns {
    22  		t.AddField(strings.ToUpper(col))
    23  	}
    24  	t.EndRow()
    25  }
    26  
    27  func (tp *TablePrinter) AddTimeField(t time.Time, c func(string) string) {
    28  	tf := t.Format(time.RFC3339)
    29  	if tp.isTTY {
    30  		// TODO: use a static time.Now
    31  		tf = text.FuzzyAgo(time.Now(), t)
    32  	}
    33  	tp.AddField(tf, tableprinter.WithColor(c))
    34  }
    35  
    36  var (
    37  	WithTruncate = tableprinter.WithTruncate
    38  	WithColor    = tableprinter.WithColor
    39  )
    40  
    41  func New(ios *iostreams.IOStreams) *TablePrinter {
    42  	maxWidth := 80
    43  	isTTY := ios.IsStdoutTTY()
    44  	if isTTY {
    45  		maxWidth = ios.TerminalWidth()
    46  	}
    47  	tp := tableprinter.New(ios.Out, isTTY, maxWidth)
    48  	return &TablePrinter{
    49  		TablePrinter: tp,
    50  		isTTY:        isTTY,
    51  	}
    52  }