[PATCH 1 of 3] chg: use color in log conditionally

Jun Wu quark at fb.com
Tue Apr 5 14:21:16 UTC 2016


# HG changeset patch
# User Jun Wu <quark at fb.com>
# Date 1459864089 -3600
#      Tue Apr 05 14:48:09 2016 +0100
# Node ID 704d3febf4b7ea1063c2c3a58788de13fea31e79
# Parent  97067764c768447c376d6614b3fdb30e498519c9
chg: use color in log 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 @@
 	if (getenv("CHGDEBUG"))
 		enabledebugmsg();
 
+	if (!getenv("HGPLAIN") && isatty(STDERR_FILENO))
+		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 @@
 
 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);
 }
 
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_;
 


More information about the Mercurial-devel mailing list