Merge pull request #1077 from lanurmi/no-colors-on-non-tty

Do not output colors e.g. into a pipe, unless forced.
This commit is contained in:
Tom van Dijck 2018-05-08 12:19:56 +02:00 committed by GitHub
commit f8c7edf20d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -10,6 +10,30 @@
static int s_currentColor = -1;
#endif
#if PLATFORM_WINDOWS
int canUseColors() {
return 1;
}
#else
int canUseColors() {
return isatty(1);
}
#endif
static const char *getenvOrFallback(const char *var, const char *fallback) {
const char *value = getenv(var);
if (value)
return value;
else
return fallback;
}
static int shouldUseColors() {
// CLICOLOR* documented at: http://bixense.com/clicolors/
return ((getenvOrFallback("CLICOLOR", "1")[0] != '0') && canUseColors())
|| getenvOrFallback("CLICOLOR_FORCE", "0")[0] != '0';
}
int term_doGetTextColor()
{
#if PLATFORM_WINDOWS
@ -25,12 +49,17 @@ int term_doGetTextColor()
void term_doSetTextColor(int color)
{
#if PLATFORM_WINDOWS
if (color >= 0)
if (color >= 0 && shouldUseColors())
{
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), (WORD)color);
SetConsoleTextAttribute(GetStdHandle(STD_ERROR_HANDLE), (WORD)color);
}
#else
// Do not output colors e.g. into a pipe, unless forced.
if (!shouldUseColors())
return;
s_currentColor = color;
const char* colorTable[] =