4 #define COLOR_RESET "\033[m"
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 (*name
&& !*end
&& 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 const char *ptr
= value
;
47 if (!strcasecmp(value
, "reset")) {
48 strcpy(dst
, "\033[m");
52 /* [fg [bg]] [attr] */
54 const char *word
= ptr
;
57 while (word
[len
] && !isspace(word
[len
]))
61 while (*ptr
&& isspace(*ptr
))
64 val
= parse_color(word
, len
);
76 val
= parse_attr(word
, len
);
77 if (val
< 0 || attr
!= -1)
82 if (attr
>= 0 || fg
>= 0 || bg
>= 0) {
98 dst
+= sprintf(dst
, "38;5;%d", fg
);
108 dst
+= sprintf(dst
, "48;5;%d", bg
);
116 die("bad config value '%s' for variable '%s'", value
, var
);
119 int git_config_colorbool(const char *var
, const char *value
)
123 if (!strcasecmp(value
, "auto")) {
124 if (isatty(1) || (pager_in_use
&& pager_use_color
)) {
125 char *term
= getenv("TERM");
126 if (term
&& strcmp(term
, "dumb"))
131 if (!strcasecmp(value
, "never"))
133 if (!strcasecmp(value
, "always"))
135 return git_config_bool(var
, value
);
138 static int color_vfprintf(FILE *fp
, const char *color
, const char *fmt
,
139 va_list args
, const char *trail
)
144 r
+= fprintf(fp
, "%s", color
);
145 r
+= vfprintf(fp
, fmt
, args
);
147 r
+= fprintf(fp
, "%s", COLOR_RESET
);
149 r
+= fprintf(fp
, "%s", trail
);
155 int color_fprintf(FILE *fp
, const char *color
, const char *fmt
, ...)
160 r
= color_vfprintf(fp
, color
, fmt
, args
, NULL
);
165 int color_fprintf_ln(FILE *fp
, const char *color
, const char *fmt
, ...)
170 r
= color_vfprintf(fp
, color
, fmt
, args
, "\n");