terminal: specialize color_mode to stdout only

By specializing this to stdout, we can cache the isatty result.

Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
This commit is contained in:
Jason A. Donenfeld 2020-04-20 22:52:35 -06:00
parent 3377409bb3
commit 891fb523a2
2 changed files with 7 additions and 17 deletions

View file

@ -12,7 +12,7 @@
#include <stdbool.h> #include <stdbool.h>
#include <unistd.h> #include <unistd.h>
static bool color_mode(FILE *file) static bool color_mode(void)
{ {
static int mode = -1; static int mode = -1;
const char *var; const char *var;
@ -25,17 +25,17 @@ static bool color_mode(FILE *file)
else if (var && !strcmp(var, "never")) else if (var && !strcmp(var, "never"))
mode = false; mode = false;
else else
return isatty(fileno(file)); mode = isatty(fileno(stdout));
return mode; return mode;
} }
static void filter_ansi(FILE *file, const char *fmt, va_list args) static void filter_ansi(const char *fmt, va_list args)
{ {
char *str = NULL; char *str = NULL;
size_t len, i, j; size_t len, i, j;
if (color_mode(file)) { if (color_mode()) {
vfprintf(file, fmt, args); vfprintf(stdout, fmt, args);
return; return;
} }
@ -55,7 +55,7 @@ static void filter_ansi(FILE *file, const char *fmt, va_list args)
} }
} }
for (i = 0; i < len; i = j) { for (i = 0; i < len; i = j) {
fputs(&str[i], file); fputs(&str[i], stdout);
for (j = i + strlen(&str[i]); j < len; ++j) { for (j = i + strlen(&str[i]); j < len; ++j) {
if (str[j] != '\0') if (str[j] != '\0')
break; break;
@ -70,15 +70,6 @@ void terminal_printf(const char *fmt, ...)
va_list args; va_list args;
va_start(args, fmt); va_start(args, fmt);
filter_ansi(stdout, fmt, args); filter_ansi(fmt, args);
va_end(args);
}
void terminal_fprintf(FILE *file, const char *fmt, ...)
{
va_list args;
va_start(args, fmt);
filter_ansi(file, fmt, args);
va_end(args); va_end(args);
} }

View file

@ -47,6 +47,5 @@
#define TERMINAL_CLEAR_ALL "\x1b[2J" #define TERMINAL_CLEAR_ALL "\x1b[2J"
void terminal_printf(const char *fmt, ...) __attribute__((format(printf, 1, 2))); void terminal_printf(const char *fmt, ...) __attribute__((format(printf, 1, 2)));
void terminal_fprintf(FILE *file, const char *fmt, ...) __attribute__((format(printf, 2, 3)));
#endif #endif