+/* SPDX-License-Identifier: GPL-2.0 */
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
+#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <linux/if.h>
#include "color.h"
+#include "utils.h"
enum color {
C_RED,
NULL,
};
-static enum color attr_colors[] = {
- /* light background */
+/* light background */
+static enum color attr_colors_light[] = {
C_CYAN,
C_YELLOW,
C_MAGENTA,
C_GREEN,
C_RED,
C_CLEAR,
+};
- /* dark background */
+/* dark background */
+static enum color attr_colors_dark[] = {
C_BOLD_CYAN,
C_BOLD_YELLOW,
C_BOLD_MAGENTA,
set_color_palette();
}
+bool check_enable_color(int color, int json)
+{
+ if (json || color == COLOR_OPT_NEVER)
+ return false;
+
+ if (color == COLOR_OPT_ALWAYS || isatty(fileno(stdout))) {
+ enable_color();
+ return true;
+ }
+ return false;
+}
+
+bool matches_color(const char *arg, int *val)
+{
+ char *dup, *p;
+
+ if (!val)
+ return false;
+
+ dup = strdupa(arg);
+ p = strchrnul(dup, '=');
+ if (*p)
+ *(p++) = '\0';
+
+ if (matches(dup, "-color"))
+ return false;
+
+ if (*p == '\0' || !strcmp(p, "always"))
+ *val = COLOR_OPT_ALWAYS;
+ else if (!strcmp(p, "auto"))
+ *val = COLOR_OPT_AUTO;
+ else if (!strcmp(p, "never"))
+ *val = COLOR_OPT_NEVER;
+ else
+ return false;
+ return true;
+}
+
void set_color_palette(void)
{
char *p = getenv("COLORFGBG");
is_dark_bg = 1;
}
-void check_if_color_enabled(void)
-{
- if (color_is_enabled) {
- fprintf(stderr, "Option \"-json\" conflicts with \"-color\".\n");
- exit(1);
- }
-}
-
+__attribute__((format(printf, 3, 4)))
int color_fprintf(FILE *fp, enum color_attr attr, const char *fmt, ...)
{
int ret = 0;
goto end;
}
- ret += fprintf(fp, "%s",
- color_codes[attr_colors[is_dark_bg ? attr + 8 : attr]]);
+ ret += fprintf(fp, "%s", color_codes[is_dark_bg ?
+ attr_colors_dark[attr] : attr_colors_light[attr]]);
+
ret += vfprintf(fp, fmt, args);
ret += fprintf(fp, "%s", color_codes[C_CLEAR]);
case AF_INET6:
return COLOR_INET6;
default:
- return COLOR_CLEAR;
+ return COLOR_NONE;
}
}
case IF_OPER_DOWN:
return COLOR_OPERSTATE_DOWN;
default:
- return COLOR_CLEAR;
+ return COLOR_NONE;
}
}