color: introduce support for colorizing stderr
So far, we only ever asked whether stdout wants to be colorful. In the upcoming patches, we will want to make push errors more prominent, which are printed to stderr, though. So let's refactor the want_color() function into a want_color_fd() function (which expects to be called with fd == 1 or fd == 2 for stdout and stderr, respectively), and then define the macro `want_color()` to use the want_color_fd() function. And then also add a macro `want_color_stderr()`, for convenience and for documentation. Signed-off-by: Johannes Schindelin <johannes.schindelin@gmx.de> Signed-off-by: Junio C Hamano <gitster@pobox.com>
Johannes Schindelin committed
Apr 21, 2018 at 12:09 UTC
295d949cfabc18fb588f269c77d1f8ff4a613686
2 files changed
+14
-10
color.c
+11
-9
@@ -319,18 +319,20 @@ int git_config_colorbool(const char *var, const char *value)
319
return GIT_COLOR_AUTO;
320
}
321
322
-static int check_auto_color(void)
322
+static int check_auto_color(int fd)
323
{
324
- if (color_stdout_is_tty < 0)
325
- color_stdout_is_tty = isatty(1);
326
- if (color_stdout_is_tty || (pager_in_use() && pager_use_color)) {
324
+ static int color_stderr_is_tty = -1;
325
+ int *is_tty_p = fd == 1 ? &color_stdout_is_tty : &color_stderr_is_tty;
326
+ if (*is_tty_p < 0)
327
+ *is_tty_p = isatty(fd);
328
+ if (*is_tty_p || (fd == 1 && pager_in_use() && pager_use_color)) {
329
if (!is_terminal_dumb())
330
return 1;
331
}
332
return 0;
333
}
334
333
-int want_color(int var)
335
+int want_color_fd(int fd, int var)
336
{
337
/*
338
* NEEDSWORK: This function is sometimes used from multiple threads, and
@@ -339,15 +341,15 @@ int want_color(int var)
341
* is listed in .tsan-suppressions for the time being.
342
*/
343
342
- static int want_auto = -1;
344
+ static int want_auto[3] = { -1, -1, -1 };
345
346
if (var < 0)
347
var = git_use_color_default;
348
349
if (var == GIT_COLOR_AUTO) {
348
- if (want_auto < 0)
349
- want_auto = check_auto_color();
350
- return want_auto;
350
+ if (want_auto[fd] < 0)
351
+ want_auto[fd] = check_auto_color(fd);
352
+ return want_auto[fd];
353
}
354
return var;
355
}
color.h
+3
-1
@@ -88,7 +88,9 @@ int git_config_colorbool(const char *var, const char *value);
88
* Return a boolean whether to use color, where the argument 'var' is
89
* one of GIT_COLOR_UNKNOWN, GIT_COLOR_NEVER, GIT_COLOR_ALWAYS, GIT_COLOR_AUTO.
90
*/
91
-int want_color(int var);
91
+int want_color_fd(int fd, int var);
92
+#define want_color(colorbool) want_color_fd(1, (colorbool))
93
+#define want_color_stderr(colorbool) want_color_fd(2, (colorbool))
94
95
/*
96
* Translate a Git color from 'value' into a string that the terminal can