...

Source file src/oss.terrastruct.com/util-go/xterm/xterm.go

Documentation: oss.terrastruct.com/util-go/xterm

     1  package xterm
     2  
     3  import (
     4  	"fmt"
     5  	"hash/crc64"
     6  	"io"
     7  	"math/rand"
     8  	"os"
     9  
    10  	"golang.org/x/term"
    11  
    12  	"oss.terrastruct.com/util-go/xos"
    13  )
    14  
    15  // See https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-Functions-using-CSI-_-ordered-by-the-final-character_s_
    16  const (
    17  	csi   = "\x1b["
    18  	reset = csi + "0m"
    19  
    20  	Bold = csi + "1m"
    21  
    22  	Red     = csi + "31m"
    23  	Green   = csi + "32m"
    24  	Yellow  = csi + "33m"
    25  	Blue    = csi + "34m"
    26  	Magenta = csi + "35m"
    27  	Cyan    = csi + "36m"
    28  
    29  	BrightRed     = csi + "91m"
    30  	BrightGreen   = csi + "92m"
    31  	BrightYellow  = csi + "93m"
    32  	BrightBlue    = csi + "94m"
    33  	BrightMagenta = csi + "95m"
    34  	BrightCyan    = csi + "96m"
    35  )
    36  
    37  var colors = [...]string{
    38  	Red,
    39  	Green,
    40  	Yellow,
    41  	Blue,
    42  	Magenta,
    43  	Cyan,
    44  
    45  	BrightRed,
    46  	BrightGreen,
    47  	BrightYellow,
    48  	BrightBlue,
    49  	BrightMagenta,
    50  	BrightCyan,
    51  }
    52  
    53  // isTTY checks whether the given writer is a *os.File TTY.
    54  func isTTY(w io.Writer) bool {
    55  	f, ok := w.(interface {
    56  		Fd() uintptr
    57  	})
    58  	return ok && term.IsTerminal(int(f.Fd()))
    59  }
    60  
    61  func shouldColor(env *xos.Env, w io.Writer) bool {
    62  	eb, err := env.Bool("COLOR")
    63  	if eb != nil {
    64  		return *eb
    65  	}
    66  	if err != nil {
    67  		os.Stderr.WriteString(fmt.Sprintf("xterm: %v", err))
    68  	}
    69  	if env.Getenv("TERM") == "dumb" {
    70  		return false
    71  	}
    72  	return isTTY(w)
    73  }
    74  
    75  func Tput(env *xos.Env, w io.Writer, caps, s string) string {
    76  	if caps == "" {
    77  		return s
    78  	}
    79  	if !shouldColor(env, w) {
    80  		return s
    81  	}
    82  	return caps + s + reset
    83  }
    84  
    85  func Prefix(env *xos.Env, w io.Writer, caps, s string) string {
    86  	s = fmt.Sprintf("%s", s)
    87  	return Tput(env, w, caps, s) + ":"
    88  }
    89  
    90  var crc64Table = crc64.MakeTable(crc64.ISO)
    91  
    92  // CC meaning constant color. So constant color prefix.
    93  func CCPrefix(env *xos.Env, w io.Writer, s string) string {
    94  	sum := crc64.Checksum([]byte(s), crc64Table)
    95  	rand := rand.New(rand.NewSource(int64(sum)))
    96  
    97  	color := colors[rand.Intn(len(colors))]
    98  	return Prefix(env, w, color, s)
    99  }
   100  

View as plain text