github.com/neilotoole/jsoncolor@v0.7.2-0.20231115150201-1637fae69be1/terminal.go (about)

     1  //go:build !windows
     2  
     3  package jsoncolor
     4  
     5  import (
     6  	"io"
     7  	"os"
     8  
     9  	"golang.org/x/term"
    10  )
    11  
    12  // IsColorTerminal returns true if w is a colorable terminal.
    13  // It respects [NO_COLOR], [FORCE_COLOR] and TERM=dumb environment variables.
    14  //
    15  // [NO_COLOR]: https://no-color.org/
    16  // [FORCE_COLOR]: https://force-color.org/
    17  func IsColorTerminal(w io.Writer) bool {
    18  	if os.Getenv("NO_COLOR") != "" {
    19  		return false
    20  	}
    21  	if os.Getenv("FORCE_COLOR") != "" {
    22  		return true
    23  	}
    24  	if os.Getenv("TERM") == "dumb" {
    25  		return false
    26  	}
    27  
    28  	if w == nil {
    29  		return false
    30  	}
    31  
    32  	f, ok := w.(*os.File)
    33  	if !ok {
    34  		return false
    35  	}
    36  
    37  	if !term.IsTerminal(int(f.Fd())) {
    38  		return false
    39  	}
    40  
    41  	return true
    42  }