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

     1  package utils
     2  
     3  import (
     4  	"io"
     5  	"strings"
     6  
     7  	"github.com/ungtb10d/cli/v2/pkg/iostreams"
     8  	"github.com/cli/go-gh/pkg/tableprinter"
     9  )
    10  
    11  type TablePrinter interface {
    12  	IsTTY() bool
    13  	AddField(string, func(int, string) string, func(string) string)
    14  	EndRow()
    15  	Render() error
    16  }
    17  
    18  type TablePrinterOptions struct {
    19  	IsTTY    bool
    20  	MaxWidth int
    21  	Out      io.Writer
    22  }
    23  
    24  // Deprecated: use internal/tableprinter
    25  func NewTablePrinter(io *iostreams.IOStreams) TablePrinter {
    26  	return NewTablePrinterWithOptions(io, TablePrinterOptions{
    27  		IsTTY: io.IsStdoutTTY(),
    28  	})
    29  }
    30  
    31  // Deprecated: use internal/tableprinter
    32  func NewTablePrinterWithOptions(ios *iostreams.IOStreams, opts TablePrinterOptions) TablePrinter {
    33  	var out io.Writer
    34  	if opts.Out != nil {
    35  		out = opts.Out
    36  	} else {
    37  		out = ios.Out
    38  	}
    39  	var maxWidth int
    40  	if opts.IsTTY {
    41  		if opts.MaxWidth > 0 {
    42  			maxWidth = opts.MaxWidth
    43  		} else {
    44  			maxWidth = ios.TerminalWidth()
    45  		}
    46  	}
    47  	tp := tableprinter.New(out, opts.IsTTY, maxWidth)
    48  	return &printer{
    49  		tp:    tp,
    50  		isTTY: opts.IsTTY,
    51  	}
    52  }
    53  
    54  type printer struct {
    55  	tp       tableprinter.TablePrinter
    56  	colIndex int
    57  	isTTY    bool
    58  }
    59  
    60  func (p printer) IsTTY() bool {
    61  	return p.isTTY
    62  }
    63  
    64  func (p *printer) AddField(s string, truncateFunc func(int, string) string, colorFunc func(string) string) {
    65  	if truncateFunc == nil {
    66  		// Disallow ever truncating the 1st colum or any URL value
    67  		if p.colIndex == 0 || isURL(s) {
    68  			p.tp.AddField(s, tableprinter.WithTruncate(nil), tableprinter.WithColor(colorFunc))
    69  		} else {
    70  			p.tp.AddField(s, tableprinter.WithColor(colorFunc))
    71  		}
    72  	} else {
    73  		p.tp.AddField(s, tableprinter.WithTruncate(truncateFunc), tableprinter.WithColor(colorFunc))
    74  	}
    75  	p.colIndex++
    76  }
    77  
    78  func (p *printer) EndRow() {
    79  	p.tp.EndRow()
    80  	p.colIndex = 0
    81  }
    82  
    83  func (p *printer) Render() error {
    84  	return p.tp.Render()
    85  }
    86  
    87  func isURL(s string) bool {
    88  	return strings.HasPrefix(s, "https://") || strings.HasPrefix(s, "http://")
    89  }