golang.org/x/build@v0.0.0-20240506185731-218518f32b70/cmd/greplogs/color.go (about)

     1  // Copyright 2018 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package main
     6  
     7  import (
     8  	"math/bits"
     9  	"os"
    10  	"strconv"
    11  
    12  	"golang.org/x/term"
    13  )
    14  
    15  func canColor() bool {
    16  	if os.Getenv("TERM") == "" || os.Getenv("TERM") == "dumb" {
    17  		return false
    18  	}
    19  	if !term.IsTerminal(1) {
    20  		return false
    21  	}
    22  	return true
    23  }
    24  
    25  type colorizer struct {
    26  	enabled bool
    27  }
    28  
    29  func newColorizer(enabled bool) *colorizer {
    30  	return &colorizer{enabled}
    31  }
    32  
    33  type colorFlags uint64
    34  
    35  const (
    36  	colorBold      colorFlags = 1 << 1
    37  	colorFgBlack              = 1 << 30
    38  	colorFgRed                = 1 << 31
    39  	colorFgGreen              = 1 << 32
    40  	colorFgYellow             = 1 << 33
    41  	colorFgBlue               = 1 << 34
    42  	colorFgMagenta            = 1 << 35
    43  	colorFgCyan               = 1 << 36
    44  	colorFgWhite              = 1 << 37
    45  )
    46  
    47  func (c colorizer) color(s string, f colorFlags) string {
    48  	if !c.enabled || f == 0 {
    49  		return s
    50  	}
    51  	pfx := make([]byte, 0, 16)
    52  	pfx = append(pfx, 0x1b, '[')
    53  	for f != 0 {
    54  		flag := uint64(bits.TrailingZeros64(uint64(f)))
    55  		f &^= 1 << flag
    56  		if len(pfx) > 2 {
    57  			pfx = append(pfx, ';')
    58  		}
    59  		pfx = strconv.AppendUint(pfx, flag, 10)
    60  	}
    61  	pfx = append(pfx, 'm')
    62  	return string(pfx) + s + "\x1b[0m"
    63  }