4 int git_use_color_default = 0;
6 static int parse_color(const char *name, int len)
8 static const char * const color_names[] = {
9 "normal", "black", "red", "green", "yellow",
10 "blue", "magenta", "cyan", "white"
14 for (i = 0; i < ARRAY_SIZE(color_names); i++) {
15 const char *str = color_names[i];
16 if (!strncasecmp(name, str, len) && !str[len])
19 i = strtol(name, &end, 10);
20 if (end - name == len && i >= -1 && i <= 255)
25 static int parse_attr(const char *name, int len)
27 static const int attr_values[] = { 1, 2, 4, 5, 7 };
28 static const char * const attr_names[] = {
29 "bold", "dim", "ul", "blink", "reverse"
32 for (i = 0; i < ARRAY_SIZE(attr_names); i++) {
33 const char *str = attr_names[i];
34 if (!strncasecmp(name, str, len) && !str[len])
35 return attr_values[i];
40 void color_parse(const char *value, const char *var, char *dst)
42 color_parse_mem(value, strlen(value), var, dst);
45 void color_parse_mem(const char *value, int value_len, const char *var,
48 const char *ptr = value;
50 unsigned int attr = 0;
54 if (!strncasecmp(value, "reset", len)) {
55 strcpy(dst, GIT_COLOR_RESET);
59 /* [fg [bg]] [attr]... */
61 const char *word = ptr;
64 while (len > 0 && !isspace(word[wordlen])) {
70 while (len > 0 && isspace(*ptr)) {
75 val = parse_color(word, wordlen);
87 val = parse_attr(word, wordlen);
94 if (attr || fg >= 0 || bg >= 0) {
101 for (i = 0; attr; i++) {
102 unsigned bit = (1 << i);
117 dst += sprintf(dst, "38;5;%d", fg);
127 dst += sprintf(dst, "48;5;%d", bg);
135 die("bad color value '%.*s' for variable '%s'", value_len, value, var);
138 int git_config_colorbool(const char *var, const char *value, int stdout_is_tty)
141 if (!strcasecmp(value, "never"))
143 if (!strcasecmp(value, "always"))
145 if (!strcasecmp(value, "auto"))
152 /* Missing or explicit false to turn off colorization */
153 if (!git_config_bool(var, value))
156 /* any normal truth value defaults to 'auto' */
158 if (stdout_is_tty < 0)
159 stdout_is_tty = isatty(1);
160 if (stdout_is_tty || (pager_in_use() && pager_use_color)) {
161 char *term = getenv("TERM");
162 if (term && strcmp(term, "dumb"))
168 int git_color_default_config(const char *var, const char *value, void *cb)
170 if (!strcmp(var, "color.ui")) {
171 git_use_color_default = git_config_colorbool(var, value, -1);
175 return git_default_config(var, value, cb);
178 static int color_vfprintf(FILE *fp, const char *color, const char *fmt,
179 va_list args, const char *trail)
184 r += fprintf(fp, "%s", color);
185 r += vfprintf(fp, fmt, args);
187 r += fprintf(fp, "%s", GIT_COLOR_RESET);
189 r += fprintf(fp, "%s", trail);
195 int color_fprintf(FILE *fp, const char *color, const char *fmt, ...)
200 r = color_vfprintf(fp, color, fmt, args, NULL);
205 int color_fprintf_ln(FILE *fp, const char *color, const char *fmt, ...)
210 r = color_vfprintf(fp, color, fmt, args, "\n");
215 int color_is_nil(const char *c)
217 return !strcmp(c, "NIL");