github.com/keybase/client/go@v0.0.0-20240309051027-028f7c731f8b/libkb/tablify.go (about)

     1  // Copyright 2015 Keybase, Inc. All rights reserved. Use of
     2  // this source code is governed by the included BSD license.
     3  
     4  package libkb
     5  
     6  import (
     7  	"fmt"
     8  	"io"
     9  	"strings"
    10  	"text/tabwriter"
    11  )
    12  
    13  func Tablify(writer io.Writer, headings []string, rowfunc func() []string) {
    14  	w := new(tabwriter.Writer)
    15  	w.Init(writer, 5, 0, 3, ' ', 0)
    16  
    17  	TablifyWithTabWriter(w, headings, rowfunc)
    18  }
    19  
    20  func TablifyWithTabWriter(w *tabwriter.Writer, headings []string, rowfunc func() []string) {
    21  	dorow := func(cells []string) {
    22  		fmt.Fprintln(w, strings.Join(cells, "\t"))
    23  	}
    24  
    25  	if headings != nil {
    26  		dorow(headings)
    27  		seps := make([]string, len(headings))
    28  		for i, h := range headings {
    29  			seps[i] = strings.Repeat("=", len(h)+1)
    30  		}
    31  		dorow(seps)
    32  	}
    33  
    34  	for {
    35  		row := rowfunc()
    36  		if row == nil {
    37  			break
    38  		}
    39  		dorow(row)
    40  	}
    41  
    42  	w.Flush()
    43  }