fatih / color

Color package for Go (golang)
https://pkg.go.dev/github.com/fatih/color
MIT License
7.24k stars 615 forks source link

Properly decide when to disable colors #85

Closed jgkamat closed 5 years ago

jgkamat commented 6 years ago

51 and #50 are an improper method of determining whether a terminal supports color. There are many dumb terms that support color, and there are non-dumb terminals that don't support color.

I currently use a dumb terminal as my main terminal, and all apps built with faith/color don't show color, but all other applications I use seem to work fine.

The proper way to do this is to use the terminfo database, for a simple example:

tput colors shows how many colors this terminal supports.

Simple workaround to avoid loosing colors:

    if os.Getenv("TERM") == "dumb" && isatty.IsTerminal(os.Stdout.Fd()) {
        color.NoColor = false
    }
fatih commented 6 years ago

Hi @jgkamat

What's your suggestion? It works well for most usecases, and to be honest, that part gets more and more complicated. I'm open to suggestions or PR's. Otherwise you always have the option to enable/disable it yourself.

jgkamat commented 6 years ago

The simplest way is just checking to see if the terminal has more than 8 colors available

if [ $(tput colors) -ge 8 ]; then <set colors true> fi

According to the terminfo manual, this will also fix showing colors when we are explicitly told not to as well (usually when TERM ends in -m).

The more 'proper' way is to get the ansi codes from tput directly, so that this checking isn't needed:

RED_CODE="$(tput setaf 1)"

and using the code appropriately. I don't think this is a good idea though, since we won't be able to be force colors on, but it's a lot less hacky.

I'm not sure if there's a go library for interacting with the terminfo database, but there is one in C.

benitogf commented 6 years ago

Hi all, when running with systemd the colors are lost on the journal, same applies to using nohup, it only seems to work with script -q -c "app" test.log which I guess would be detected and a "non dumb" terminal, ~maybe we could have a flag to bypass the check?~ even bypassing the noColor check doesn't make a difference

update: using the output option shows the colors: journalctl -u app.service -o cat if the noColor check is bypassed

fatih commented 5 years ago

Hi,

Unfortunately, I'm archiving this project and will no longer maintaining it. For more information, please read my blog post: Taking an indefinite sabbatical from my projects.

Thanks for the feedback and contribution.