ansi-color: follow-ups for $SYSTEMD_COLOR=auto-* (#40442)

Follow-ups for #40303
This commit is contained in:
Yu Watanabe
2026-01-28 16:00:38 +09:00
committed by GitHub
6 changed files with 38 additions and 22 deletions
+7 -5
View File
@@ -55,11 +55,11 @@ static ColorMode get_color_mode_impl(void) {
/* First, we check $SYSTEMD_COLORS, which is the explicit way to change the mode. */
ColorMode m = parse_systemd_colors();
if (IN_SET(m, COLOR_OFF, COLOR_16, COLOR_256, COLOR_24BIT))
if (m >= 0 && m < _COLOR_MODE_FIXED_MAX)
return m;
/* Next, check for the presence of $NO_COLOR; value is ignored. */
if (getenv("NO_COLOR"))
if (m != COLOR_TRUE && getenv("NO_COLOR"))
return COLOR_OFF;
/* If the above didn't work, we turn colors off unless we are on a TTY. And if we are on a TTY we
@@ -92,13 +92,14 @@ static ColorMode get_color_mode_impl(void) {
}
ColorMode get_color_mode(void) {
if (cached_color_mode < 0)
if (cached_color_mode < 0) {
cached_color_mode = get_color_mode_impl();
assert(cached_color_mode >= 0 && cached_color_mode < _COLOR_MODE_FIXED_MAX);
}
return cached_color_mode;
}
static const char* const color_mode_table[_COLOR_MODE_MAX] = {
[COLOR_OFF] = "off",
[COLOR_16] = "16",
@@ -107,9 +108,10 @@ static const char* const color_mode_table[_COLOR_MODE_MAX] = {
[COLOR_AUTO_16] = "auto-16",
[COLOR_AUTO_256] = "auto-256",
[COLOR_AUTO_24BIT] = "auto-24bit",
[COLOR_TRUE] = "true",
};
DEFINE_STRING_TABLE_LOOKUP_WITH_BOOLEAN(color_mode, ColorMode, COLOR_24BIT);
DEFINE_STRING_TABLE_LOOKUP_WITH_BOOLEAN(color_mode, ColorMode, COLOR_TRUE);
/*
* Check that the string is formatted like an ANSI color code, i.e. that it consists of one or more
+10 -2
View File
@@ -9,9 +9,17 @@ typedef enum ColorMode {
COLOR_16, /* Only the base 16 colors. */
COLOR_256, /* Only 256 colors. */
COLOR_24BIT, /* For truecolor or 24bit color support, no restriction. */
COLOR_AUTO_16, /* The "AUTO" modes are as the above, but subject to suitable settings for */
COLOR_AUTO_256, /* the environment variables TERM and NO_COLOR. */
_COLOR_MODE_FIXED_MAX,
/* The "AUTO" modes are as the above, but subject to suitable settings for the environment variables
* TERM and NO_COLOR. */
COLOR_AUTO_16 = _COLOR_MODE_FIXED_MAX,
COLOR_AUTO_256,
COLOR_AUTO_24BIT,
/* Same as default (unset), except that $NO_COLOR is ignored/overridden */
COLOR_TRUE,
_COLOR_MODE_MAX,
_COLOR_MODE_INVALID = -EINVAL,
} ColorMode;