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

     1  package jsoncolor
     2  
     3  import (
     4  	"io"
     5  	"os"
     6  
     7  	"golang.org/x/sys/windows"
     8  )
     9  
    10  // IsColorTerminal returns true if w is a colorable terminal.
    11  // It respects [NO_COLOR], [FORCE_COLOR] and TERM=dumb environment variables.
    12  //
    13  // [NO_COLOR]: https://no-color.org/
    14  // [FORCE_COLOR]: https://force-color.org/
    15  func IsColorTerminal(w io.Writer) bool {
    16  	if os.Getenv("NO_COLOR") != "" {
    17  		return false
    18  	}
    19  	if os.Getenv("FORCE_COLOR") != "" {
    20  		return true
    21  	}
    22  	if os.Getenv("TERM") == "dumb" {
    23  		return false
    24  	}
    25  
    26  	if w == nil {
    27  		return false
    28  	}
    29  
    30  	f, ok := w.(*os.File)
    31  	if !ok {
    32  		return false
    33  	}
    34  	fd := f.Fd()
    35  
    36  	console := windows.Handle(fd)
    37  	var mode uint32
    38  	if err := windows.GetConsoleMode(console, &mode); err != nil {
    39  		return false
    40  	}
    41  
    42  	var want uint32 = windows.ENABLE_PROCESSED_OUTPUT | windows.ENABLE_VIRTUAL_TERMINAL_PROCESSING
    43  	if (mode & want) == want {
    44  		return true
    45  	}
    46  
    47  	mode |= want
    48  	if err := windows.SetConsoleMode(console, mode); err != nil {
    49  		return false
    50  	}
    51  
    52  	return true
    53  }