]> git.proxmox.com Git - mirror_iproute2.git/blob - lib/color.c
ip: add support for seg6local End.BPF action
[mirror_iproute2.git] / lib / color.c
1 /* SPDX-License-Identifier: GPL-2.0 */
2 #include <stdio.h>
3 #include <stdarg.h>
4 #include <stdlib.h>
5 #include <string.h>
6 #include <sys/socket.h>
7 #include <sys/types.h>
8 #include <linux/if.h>
9
10 #include "color.h"
11
12 enum color {
13 C_RED,
14 C_GREEN,
15 C_YELLOW,
16 C_BLUE,
17 C_MAGENTA,
18 C_CYAN,
19 C_WHITE,
20 C_BOLD_RED,
21 C_BOLD_GREEN,
22 C_BOLD_YELLOW,
23 C_BOLD_BLUE,
24 C_BOLD_MAGENTA,
25 C_BOLD_CYAN,
26 C_BOLD_WHITE,
27 C_CLEAR
28 };
29
30 static const char * const color_codes[] = {
31 "\e[31m",
32 "\e[32m",
33 "\e[33m",
34 "\e[34m",
35 "\e[35m",
36 "\e[36m",
37 "\e[37m",
38 "\e[1;31m",
39 "\e[1;32m",
40 "\e[1;33m",
41 "\e[1;34m",
42 "\e[1;35m",
43 "\e[1;36m",
44 "\e[1;37m",
45 "\e[0m",
46 NULL,
47 };
48
49 /* light background */
50 static enum color attr_colors_light[] = {
51 C_CYAN,
52 C_YELLOW,
53 C_MAGENTA,
54 C_BLUE,
55 C_GREEN,
56 C_RED,
57 C_CLEAR,
58 };
59
60 /* dark background */
61 static enum color attr_colors_dark[] = {
62 C_BOLD_CYAN,
63 C_BOLD_YELLOW,
64 C_BOLD_MAGENTA,
65 C_BOLD_BLUE,
66 C_BOLD_GREEN,
67 C_BOLD_RED,
68 C_CLEAR
69 };
70
71 static int is_dark_bg;
72 static int color_is_enabled;
73
74 void enable_color(void)
75 {
76 color_is_enabled = 1;
77 set_color_palette();
78 }
79
80 void set_color_palette(void)
81 {
82 char *p = getenv("COLORFGBG");
83
84 /*
85 * COLORFGBG environment variable usually contains either two or three
86 * values separated by semicolons; we want the last value in either case.
87 * If this value is 0-6 or 8, background is dark.
88 */
89 if (p && (p = strrchr(p, ';')) != NULL
90 && ((p[1] >= '0' && p[1] <= '6') || p[1] == '8')
91 && p[2] == '\0')
92 is_dark_bg = 1;
93 }
94
95 int color_fprintf(FILE *fp, enum color_attr attr, const char *fmt, ...)
96 {
97 int ret = 0;
98 va_list args;
99
100 va_start(args, fmt);
101
102 if (!color_is_enabled || attr == COLOR_NONE) {
103 ret = vfprintf(fp, fmt, args);
104 goto end;
105 }
106
107 ret += fprintf(fp, "%s", color_codes[is_dark_bg ?
108 attr_colors_dark[attr] : attr_colors_light[attr]]);
109
110 ret += vfprintf(fp, fmt, args);
111 ret += fprintf(fp, "%s", color_codes[C_CLEAR]);
112
113 end:
114 va_end(args);
115 return ret;
116 }
117
118 enum color_attr ifa_family_color(__u8 ifa_family)
119 {
120 switch (ifa_family) {
121 case AF_INET:
122 return COLOR_INET;
123 case AF_INET6:
124 return COLOR_INET6;
125 default:
126 return COLOR_NONE;
127 }
128 }
129
130 enum color_attr oper_state_color(__u8 state)
131 {
132 switch (state) {
133 case IF_OPER_UP:
134 return COLOR_OPERSTATE_UP;
135 case IF_OPER_DOWN:
136 return COLOR_OPERSTATE_DOWN;
137 default:
138 return COLOR_NONE;
139 }
140 }