3 #include "git-compat-util.h"
7 #define COLOR_RESET "\033[m"
9 static int parse_color(const char *name
, int len
)
11 static const char * const color_names
[] = {
12 "normal", "black", "red", "green", "yellow",
13 "blue", "magenta", "cyan", "white"
17 for (i
= 0; i
< ARRAY_SIZE(color_names
); i
++) {
18 const char *str
= color_names
[i
];
19 if (!strncasecmp(name
, str
, len
) && !str
[len
])
22 i
= strtol(name
, &end
, 10);
23 if (*name
&& !*end
&& i
>= -1 && i
<= 255)
28 static int parse_attr(const char *name
, int len
)
30 static const int attr_values
[] = { 1, 2, 4, 5, 7 };
31 static const char * const attr_names
[] = {
32 "bold", "dim", "ul", "blink", "reverse"
35 for (i
= 0; i
< ARRAY_SIZE(attr_names
); i
++) {
36 const char *str
= attr_names
[i
];
37 if (!strncasecmp(name
, str
, len
) && !str
[len
])
38 return attr_values
[i
];
43 void color_parse(const char *value
, const char *var
, char *dst
)
45 const char *ptr
= value
;
50 if (!strcasecmp(value
, "reset")) {
51 strcpy(dst
, "\033[m");
55 /* [fg [bg]] [attr] */
57 const char *word
= ptr
;
60 while (word
[len
] && !isspace(word
[len
]))
64 while (*ptr
&& isspace(*ptr
))
67 val
= parse_color(word
, len
);
79 val
= parse_attr(word
, len
);
80 if (val
< 0 || attr
!= -1)
85 if (attr
>= 0 || fg
>= 0 || bg
>= 0) {
101 dst
+= sprintf(dst
, "38;5;%d", fg
);
111 dst
+= sprintf(dst
, "48;5;%d", bg
);
119 die("bad config value '%s' for variable '%s'", value
, var
);
122 int git_config_colorbool(const char *var
, const char *value
)
126 if (!strcasecmp(value
, "auto")) {
127 if (isatty(1) || (pager_in_use
&& pager_use_color
)) {
128 char *term
= getenv("TERM");
129 if (term
&& strcmp(term
, "dumb"))
134 if (!strcasecmp(value
, "never"))
136 if (!strcasecmp(value
, "always"))
138 return git_config_bool(var
, value
);
141 static int color_vprintf(const char *color
, const char *fmt
,
142 va_list args
, const char *trail
)
147 r
+= printf("%s", color
);
148 r
+= vprintf(fmt
, args
);
150 r
+= printf("%s", COLOR_RESET
);
152 r
+= printf("%s", trail
);
158 int color_printf(const char *color
, const char *fmt
, ...)
163 r
= color_vprintf(color
, fmt
, args
, NULL
);
168 int color_printf_ln(const char *color
, const char *fmt
, ...)
173 r
= color_vprintf(color
, fmt
, args
, "\n");