Closed cmanley closed 1 year ago
@cmanley It is already implemented! See the following lines: https://github.com/twoixter/ansicolors/blob/190e968360cfd2bb12ecfd75a5653d186862011b/lib/ansi.php#L130-L133
You can safely pipe your scripts without mangling your log files. It already uses the posix_isatty
method as you suggested.
Cool! Thanks. But has detecting if console actually supports ANSI codes been implemented too? That'll probably come down to checking the value the env variable TERM but I haven't looked into how it can be done myself.
No, the actual capabilities of the terminal are not detected. The intention is that the posix_isatty
check is enough for ANSI stripping. It is also fast and cached (static property). Nowadays most of the terminals supports simple ANSI escape codes, even CI/CD pipelines.
If you want to test it yourself, I would suggest you not to check the terminal name in $TERM
, but use the proper database check of terminfo
. The reason is that you can look for names like xterm
, xterm-256
, etc, which are known terminal names. But what about terminal names like vt52
and vt100
? How can you be sure which one supports colors?
The tput
shell command outputs the correct escape sequences for the current terminal, so tput bold
will output the sequences to put text in bold, or none if the terminal does not support bold text:
$ export TERM=xterm
$ tput bold | wc -c
4
$ export TERM=dumb
$ tput bold | wc -c
0
@cmanley You can put it out together in a shell script with something like:
if [ $(tput bold | wc -c) -gt 0 ]; then
echo "Your terminal supports ANSI colors"
else
echo "Dooh! This is a dumb terminal"
fi
Alright, thanks for the examples. I PHP'ed it: $supports_ansi = (bool)strlen((string)system('tput bold 2>/dev/null')));
...and also detect if stdout is in a terminal, otherwise unwanted ansi codes could be directed (using >) to a log file. In case it helps: Get tty device name: posix_ttyname(STDOUT) Is stdout going to a terminal? posix_isatty(STDOUT)