# HG changeset patch
# User Jun Wu <quark@fb.com>
# Date 2016-04-05 13:48:09
# Node ID ea86cdcd9b50bf38c6b9dd7bbaa04b9c8cc0aefb
# Parent  69c6e9623bdc6f7e790f93307502fbe5f8816789

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.

diff --git a/contrib/chg/chg.c b/contrib/chg/chg.c
--- a/contrib/chg/chg.c
+++ b/contrib/chg/chg.c
@@ -522,6 +522,9 @@ int main(int argc, const char *argv[], c
 	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 "
diff --git a/contrib/chg/util.c b/contrib/chg/util.c
--- a/contrib/chg/util.c
+++ b/contrib/chg/util.c
@@ -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 @@ void abortmsg(const char *fmt, ...)
 
 static int debugmsgenabled = 0;
 
+void enablecolor(void)
+{
+	colorenabled = 1;
+}
+
 void enabledebugmsg(void)
 {
 	debugmsgenabled = 1;
@@ -44,9 +60,11 @@ void debugmsg(const char *fmt, ...)
 
 	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);
 }
 
diff --git a/contrib/chg/util.h b/contrib/chg/util.h
--- a/contrib/chg/util.h
+++ b/contrib/chg/util.h
@@ -18,6 +18,7 @@
 
 void abortmsg(const char *fmt, ...) PRINTF_FORMAT_;
 
+void enablecolor(void);
 void enabledebugmsg(void);
 void debugmsg(const char *fmt, ...) PRINTF_FORMAT_;