4 #define COLOR_RESET "\033[m"
6 int git_use_color_default
= 0;
8 static int parse_color(const char *name
, int len
)
10 static const char * const color_names
[] = {
11 "normal", "black", "red", "green", "yellow",
12 "blue", "magenta", "cyan", "white"
16 for (i
= 0; i
< ARRAY_SIZE(color_names
); i
++) {
17 const char *str
= color_names
[i
];
18 if (!strncasecmp(name
, str
, len
) && !str
[len
])
21 i
= strtol(name
, &end
, 10);
22 if (end
- name
== len
&& i
>= -1 && i
<= 255)
27 static int parse_attr(const char *name
, int len
)
29 static const int attr_values
[] = { 1, 2, 4, 5, 7 };
30 static const char * const attr_names
[] = {
31 "bold", "dim", "ul", "blink", "reverse"
34 for (i
= 0; i
< ARRAY_SIZE(attr_names
); i
++) {
35 const char *str
= attr_names
[i
];
36 if (!strncasecmp(name
, str
, len
) && !str
[len
])
37 return attr_values
[i
];
42 void color_parse(const char *value
, const char *var
, char *dst
)
44 const char *ptr
= value
;
49 if (!strcasecmp(value
, "reset")) {
50 strcpy(dst
, "\033[m");
54 /* [fg [bg]] [attr] */
56 const char *word
= ptr
;
59 while (word
[len
] && !isspace(word
[len
]))
63 while (*ptr
&& isspace(*ptr
))
66 val
= parse_color(word
, len
);
78 val
= parse_attr(word
, len
);
79 if (val
< 0 || attr
!= -1)
84 if (attr
>= 0 || fg
>= 0 || bg
>= 0) {
100 dst
+= sprintf(dst
, "38;5;%d", fg
);
110 dst
+= sprintf(dst
, "48;5;%d", bg
);
118 die("bad config value '%s' for variable '%s'", value
, var
);
121 int git_config_colorbool(const char *var
, const char *value
, int stdout_is_tty
)
124 if (!strcasecmp(value
, "never"))
126 if (!strcasecmp(value
, "always"))
128 if (!strcasecmp(value
, "auto"))
132 /* Missing or explicit false to turn off colorization */
133 if (!git_config_bool(var
, value
))
136 /* any normal truth value defaults to 'auto' */
138 if (stdout_is_tty
< 0)
139 stdout_is_tty
= isatty(1);
140 if (stdout_is_tty
|| (pager_in_use() && pager_use_color
)) {
141 char *term
= getenv("TERM");
142 if (term
&& strcmp(term
, "dumb"))
148 int git_color_default_config(const char *var
, const char *value
, void *cb
)
150 if (!strcmp(var
, "color.ui")) {
151 git_use_color_default
= git_config_colorbool(var
, value
, -1);
155 return git_default_config(var
, value
, cb
);
158 static int color_vfprintf(FILE *fp
, const char *color
, const char *fmt
,
159 va_list args
, const char *trail
)
164 r
+= fprintf(fp
, "%s", color
);
165 r
+= vfprintf(fp
, fmt
, args
);
167 r
+= fprintf(fp
, "%s", COLOR_RESET
);
169 r
+= fprintf(fp
, "%s", trail
);
175 int color_fprintf(FILE *fp
, const char *color
, const char *fmt
, ...)
180 r
= color_vfprintf(fp
, color
, fmt
, args
, NULL
);
185 int color_fprintf_ln(FILE *fp
, const char *color
, const char *fmt
, ...)
190 r
= color_vfprintf(fp
, color
, fmt
, args
, "\n");