# HG changeset patch # User Jun Wu # Date 1459864089 -3600 # 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 -r 69c6e9623bdc -r ea86cdcd9b50 contrib/chg/chg.c --- 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 " diff -r 69c6e9623bdc -r ea86cdcd9b50 contrib/chg/util.c --- 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); } diff -r 69c6e9623bdc -r ea86cdcd9b50 contrib/chg/util.h --- 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_;