chg: use color in debug/error messages conditionally
Before this patch, chg always uses color in its debugmsg and abortmsg and
there is no way to turn it off.
This patch adds a global flag to control whether chg should use color or
not and only enables it when stderr is a tty and HGPLAIN is not set.
--- a/contrib/chg/chg.c Mon Apr 04 17:45:54 2016 -0700
+++ b/contrib/chg/chg.c Tue Apr 05 14:48:09 2016 +0100
@@ -522,6 +522,9 @@
if (getenv("CHGDEBUG"))
enabledebugmsg();
+ if (!getenv("HGPLAIN") && isatty(fileno(stderr)))
+ enablecolor();
+
if (getenv("CHGINTERNALMARK"))
abortmsg("chg started by chg detected.\n"
"Please make sure ${HG:-hg} is not a symlink or "
--- a/contrib/chg/util.c Mon Apr 04 17:45:54 2016 -0700
+++ b/contrib/chg/util.c Tue Apr 05 14:48:09 2016 +0100
@@ -18,13 +18,24 @@
#include "util.h"
+static int colorenabled = 0;
+
+static inline void fsetcolor(FILE *fp, const char *code)
+{
+ if (!colorenabled)
+ return;
+ fprintf(fp, "\033[%sm", code);
+}
+
void abortmsg(const char *fmt, ...)
{
va_list args;
va_start(args, fmt);
- fputs("\033[1;31mchg: abort: ", stderr);
+ fsetcolor(stderr, "1;31");
+ fputs("chg: abort: ", stderr);
vfprintf(stderr, fmt, args);
- fputs("\033[m\n", stderr);
+ fsetcolor(stderr, "");
+ fputc('\n', stderr);
va_end(args);
exit(255);
@@ -32,6 +43,11 @@
static int debugmsgenabled = 0;
+void enablecolor(void)
+{
+ colorenabled = 1;
+}
+
void enabledebugmsg(void)
{
debugmsgenabled = 1;
@@ -44,9 +60,11 @@
va_list args;
va_start(args, fmt);
- fputs("\033[1;30mchg: debug: ", stderr);
+ fsetcolor(stderr, "1;30");
+ fputs("chg: debug: ", stderr);
vfprintf(stderr, fmt, args);
- fputs("\033[m\n", stderr);
+ fsetcolor(stderr, "");
+ fputc('\n', stderr);
va_end(args);
}
--- a/contrib/chg/util.h Mon Apr 04 17:45:54 2016 -0700
+++ b/contrib/chg/util.h Tue Apr 05 14:48:09 2016 +0100
@@ -18,6 +18,7 @@
void abortmsg(const char *fmt, ...) PRINTF_FORMAT_;
+void enablecolor(void);
void enabledebugmsg(void);
void debugmsg(const char *fmt, ...) PRINTF_FORMAT_;