git
/
color.c
487 строк · 10.7 Кб
1#include "git-compat-util.h"2#include "config.h"3#include "color.h"4#include "editor.h"5#include "gettext.h"6#include "hex-ll.h"7#include "pager.h"8#include "strbuf.h"9
10static int git_use_color_default = GIT_COLOR_AUTO;11int color_stdout_is_tty = -1;12
13/*
14* The list of available column colors.
15*/
16const char *column_colors_ansi[] = {17GIT_COLOR_RED,18GIT_COLOR_GREEN,19GIT_COLOR_YELLOW,20GIT_COLOR_BLUE,21GIT_COLOR_MAGENTA,22GIT_COLOR_CYAN,23GIT_COLOR_BOLD_RED,24GIT_COLOR_BOLD_GREEN,25GIT_COLOR_BOLD_YELLOW,26GIT_COLOR_BOLD_BLUE,27GIT_COLOR_BOLD_MAGENTA,28GIT_COLOR_BOLD_CYAN,29GIT_COLOR_RESET,30};31
32enum {33COLOR_BACKGROUND_OFFSET = 10,34COLOR_FOREGROUND_ANSI = 30,35COLOR_FOREGROUND_RGB = 38,36COLOR_FOREGROUND_256 = 38,37COLOR_FOREGROUND_BRIGHT_ANSI = 90,38};39
40/* Ignore the RESET at the end when giving the size */
41const int column_colors_ansi_max = ARRAY_SIZE(column_colors_ansi) - 1;42
43/* An individual foreground or background color. */
44struct color {45enum {46COLOR_UNSPECIFIED = 0,47COLOR_NORMAL,48COLOR_ANSI, /* basic 0-7 ANSI colors + "default" (value = 9) */49COLOR_256,50COLOR_RGB
51} type;52/* The numeric value for ANSI and 256-color modes */53unsigned char value;54/* 24-bit RGB color values */55unsigned char red, green, blue;56};57
58/*
59* "word" is a buffer of length "len"; does it match the NUL-terminated
60* "match" exactly?
61*/
62static int match_word(const char *word, int len, const char *match)63{
64return !strncasecmp(word, match, len) && !match[len];65}
66
67static int get_hex_color(const char **inp, int width, unsigned char *out)68{
69const char *in = *inp;70unsigned int val;71
72assert(width == 1 || width == 2);73val = (hexval(in[0]) << 4) | hexval(in[width - 1]);74if (val & ~0xff)75return -1;76*inp += width;77*out = val;78return 0;79}
80
81/*
82* If an ANSI color is recognized in "name", fill "out" and return 0.
83* Otherwise, leave out unchanged and return -1.
84*/
85static int parse_ansi_color(struct color *out, const char *name, int len)86{
87/* Positions in array must match ANSI color codes */88static const char * const color_names[] = {89"black", "red", "green", "yellow",90"blue", "magenta", "cyan", "white"91};92int i;93int color_offset = COLOR_FOREGROUND_ANSI;94
95if (match_word(name, len, "default")) {96/*97* Restores to the terminal's default color, which may not be
98* the same as explicitly setting "white" or "black".
99*
100* ECMA-48 - Control Functions \
101* for Coded Character Sets, 5th edition (June 1991):
102* > 39 default display colour (implementation-defined)
103* > 49 default background colour (implementation-defined)
104*
105* Although not supported /everywhere/--according to terminfo,
106* some terminals define "op" (original pair) as a blunt
107* "set to white on black", or even "send full SGR reset"--
108* it's standard and well-supported enough that if a user
109* asks for it in their config this will do the right thing.
110*/
111out->type = COLOR_ANSI;112out->value = 9 + color_offset;113return 0;114}115
116if (strncasecmp(name, "bright", 6) == 0) {117color_offset = COLOR_FOREGROUND_BRIGHT_ANSI;118name += 6;119len -= 6;120}121for (i = 0; i < ARRAY_SIZE(color_names); i++) {122if (match_word(name, len, color_names[i])) {123out->type = COLOR_ANSI;124out->value = i + color_offset;125return 0;126}127}128return -1;129}
130
131static int parse_color(struct color *out, const char *name, int len)132{
133char *end;134long val;135
136/* First try the special word "normal"... */137if (match_word(name, len, "normal")) {138out->type = COLOR_NORMAL;139return 0;140}141
142/* Try a 24- or 12-bit RGB value prefixed with '#' */143if ((len == 7 || len == 4) && name[0] == '#') {144int width_per_color = (len == 7) ? 2 : 1;145const char *color = name + 1;146
147if (!get_hex_color(&color, width_per_color, &out->red) &&148!get_hex_color(&color, width_per_color, &out->green) &&149!get_hex_color(&color, width_per_color, &out->blue)) {150out->type = COLOR_RGB;151return 0;152}153}154
155/* Then pick from our human-readable color names... */156if (parse_ansi_color(out, name, len) == 0) {157return 0;158}159
160/* And finally try a literal 256-color-mode number */161val = strtol(name, &end, 10);162if (end - name == len) {163/*164* Allow "-1" as an alias for "normal", but other negative
165* numbers are bogus.
166*/
167if (val < -1)168; /* fall through to error */169else if (val < 0) {170out->type = COLOR_NORMAL;171return 0;172/* Rewrite 0-7 as more-portable standard colors. */173} else if (val < 8) {174out->type = COLOR_ANSI;175out->value = val + COLOR_FOREGROUND_ANSI;176return 0;177/* Rewrite 8-15 as more-portable aixterm colors. */178} else if (val < 16) {179out->type = COLOR_ANSI;180out->value = val - 8 + COLOR_FOREGROUND_BRIGHT_ANSI;181return 0;182} else if (val < 256) {183out->type = COLOR_256;184out->value = val;185return 0;186}187}188
189return -1;190}
191
192static int parse_attr(const char *name, size_t len)193{
194static const struct {195const char *name;196size_t len;197int val, neg;198} attrs[] = {199#define ATTR(x, val, neg) { (x), sizeof(x)-1, (val), (neg) }200ATTR("bold", 1, 22),201ATTR("dim", 2, 22),202ATTR("italic", 3, 23),203ATTR("ul", 4, 24),204ATTR("blink", 5, 25),205ATTR("reverse", 7, 27),206ATTR("strike", 9, 29)207#undef ATTR208};209int negate = 0;210int i;211
212if (skip_prefix_mem(name, len, "no", &name, &len)) {213skip_prefix_mem(name, len, "-", &name, &len);214negate = 1;215}216
217for (i = 0; i < ARRAY_SIZE(attrs); i++) {218if (attrs[i].len == len && !memcmp(attrs[i].name, name, len))219return negate ? attrs[i].neg : attrs[i].val;220}221return -1;222}
223
224int color_parse(const char *value, char *dst)225{
226return color_parse_mem(value, strlen(value), dst);227}
228
229/*
230* Write the ANSI color codes for "c" to "out"; the string should
231* already have the ANSI escape code in it. "out" should have enough
232* space in it to fit any color.
233*/
234static char *color_output(char *out, int len, const struct color *c, int background)235{
236int offset = 0;237
238if (background)239offset = COLOR_BACKGROUND_OFFSET;240switch (c->type) {241case COLOR_UNSPECIFIED:242case COLOR_NORMAL:243break;244case COLOR_ANSI:245out += xsnprintf(out, len, "%d", c->value + offset);246break;247case COLOR_256:248out += xsnprintf(out, len, "%d;5;%d", COLOR_FOREGROUND_256 + offset,249c->value);250break;251case COLOR_RGB:252out += xsnprintf(out, len, "%d;2;%d;%d;%d",253COLOR_FOREGROUND_RGB + offset,254c->red, c->green, c->blue);255break;256}257return out;258}
259
260static int color_empty(const struct color *c)261{
262return c->type <= COLOR_NORMAL;263}
264
265int color_parse_mem(const char *value, int value_len, char *dst)266{
267const char *ptr = value;268int len = value_len;269char *end = dst + COLOR_MAXLEN;270unsigned int has_reset = 0;271unsigned int attr = 0;272struct color fg = { COLOR_UNSPECIFIED };273struct color bg = { COLOR_UNSPECIFIED };274
275while (len > 0 && isspace(*ptr)) {276ptr++;277len--;278}279
280if (!len) {281dst[0] = '\0';282return 0;283}284
285/* [reset] [fg [bg]] [attr]... */286while (len > 0) {287const char *word = ptr;288struct color c = { COLOR_UNSPECIFIED };289int val, wordlen = 0;290
291while (len > 0 && !isspace(word[wordlen])) {292wordlen++;293len--;294}295
296ptr = word + wordlen;297while (len > 0 && isspace(*ptr)) {298ptr++;299len--;300}301
302if (match_word(word, wordlen, "reset")) {303has_reset = 1;304continue;305}306
307if (!parse_color(&c, word, wordlen)) {308if (fg.type == COLOR_UNSPECIFIED) {309fg = c;310continue;311}312if (bg.type == COLOR_UNSPECIFIED) {313bg = c;314continue;315}316goto bad;317}318val = parse_attr(word, wordlen);319if (0 <= val)320attr |= (1 << val);321else322goto bad;323}324
325#undef OUT326#define OUT(x) do { \327if (dst == end) \328BUG("color parsing ran out of space"); \329*dst++ = (x); \330} while(0)331
332if (has_reset || attr || !color_empty(&fg) || !color_empty(&bg)) {333int sep = 0;334int i;335
336OUT('\033');337OUT('[');338
339if (has_reset)340sep++;341
342for (i = 0; attr; i++) {343unsigned bit = (1 << i);344if (!(attr & bit))345continue;346attr &= ~bit;347if (sep++)348OUT(';');349dst += xsnprintf(dst, end - dst, "%d", i);350}351if (!color_empty(&fg)) {352if (sep++)353OUT(';');354dst = color_output(dst, end - dst, &fg, 0);355}356if (!color_empty(&bg)) {357if (sep++)358OUT(';');359dst = color_output(dst, end - dst, &bg, 1);360}361OUT('m');362}363OUT(0);364return 0;365bad:366return error(_("invalid color value: %.*s"), value_len, value);367#undef OUT368}
369
370int git_config_colorbool(const char *var, const char *value)371{
372if (value) {373if (!strcasecmp(value, "never"))374return 0;375if (!strcasecmp(value, "always"))376return 1;377if (!strcasecmp(value, "auto"))378return GIT_COLOR_AUTO;379}380
381if (!var)382return -1;383
384/* Missing or explicit false to turn off colorization */385if (!git_config_bool(var, value))386return 0;387
388/* any normal truth value defaults to 'auto' */389return GIT_COLOR_AUTO;390}
391
392static int check_auto_color(int fd)393{
394static int color_stderr_is_tty = -1;395int *is_tty_p = fd == 1 ? &color_stdout_is_tty : &color_stderr_is_tty;396if (*is_tty_p < 0)397*is_tty_p = isatty(fd);398if (*is_tty_p || (fd == 1 && pager_in_use() && pager_use_color)) {399if (!is_terminal_dumb())400return 1;401}402return 0;403}
404
405int want_color_fd(int fd, int var)406{
407/*408* NEEDSWORK: This function is sometimes used from multiple threads, and
409* we end up using want_auto racily. That "should not matter" since
410* we always write the same value, but it's still wrong. This function
411* is listed in .tsan-suppressions for the time being.
412*/
413
414static int want_auto[3] = { -1, -1, -1 };415
416if (fd < 1 || fd >= ARRAY_SIZE(want_auto))417BUG("file descriptor out of range: %d", fd);418
419if (var < 0)420var = git_use_color_default;421
422if (var == GIT_COLOR_AUTO) {423if (want_auto[fd] < 0)424want_auto[fd] = check_auto_color(fd);425return want_auto[fd];426}427return var;428}
429
430int git_color_config(const char *var, const char *value, void *cb UNUSED)431{
432if (!strcmp(var, "color.ui")) {433git_use_color_default = git_config_colorbool(var, value);434return 0;435}436
437return 0;438}
439
440void color_print_strbuf(FILE *fp, const char *color, const struct strbuf *sb)441{
442if (*color)443fprintf(fp, "%s", color);444fprintf(fp, "%s", sb->buf);445if (*color)446fprintf(fp, "%s", GIT_COLOR_RESET);447}
448
449static int color_vfprintf(FILE *fp, const char *color, const char *fmt,450va_list args, const char *trail)451{
452int r = 0;453
454if (*color)455r += fprintf(fp, "%s", color);456r += vfprintf(fp, fmt, args);457if (*color)458r += fprintf(fp, "%s", GIT_COLOR_RESET);459if (trail)460r += fprintf(fp, "%s", trail);461return r;462}
463
464int color_fprintf(FILE *fp, const char *color, const char *fmt, ...)465{
466va_list args;467int r;468va_start(args, fmt);469r = color_vfprintf(fp, color, fmt, args, NULL);470va_end(args);471return r;472}
473
474int color_fprintf_ln(FILE *fp, const char *color, const char *fmt, ...)475{
476va_list args;477int r;478va_start(args, fmt);479r = color_vfprintf(fp, color, fmt, args, "\n");480va_end(args);481return r;482}
483
484int color_is_nil(const char *c)485{
486return !strcmp(c, "NIL");487}
488