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