]>
Commit | Line | Data |
---|---|---|
dfa68ad1 OO |
1 | /* |
2 | * Copyright (C) 2012 Ondrej Oprala <ooprala@redhat.com> | |
3 | * | |
4 | * This file may be distributed under the terms of the | |
5 | * GNU Lesser General Public License. | |
6 | */ | |
a10c0434 KZ |
7 | #include <c.h> |
8 | #include <assert.h> | |
dfa68ad1 OO |
9 | |
10 | #include "colors.h" | |
11 | ||
12 | static int ul_color_term_ok; | |
13 | ||
a10c0434 | 14 | int colors_init(int mode) |
dfa68ad1 | 15 | { |
a10c0434 KZ |
16 | switch (mode) { |
17 | case UL_COLORMODE_AUTO: | |
18 | ul_color_term_ok = isatty(STDOUT_FILENO); | |
19 | break; | |
20 | case UL_COLORMODE_ALWAYS: | |
21 | ul_color_term_ok = 1; | |
22 | break; | |
23 | case UL_COLORMODE_NEVER: | |
24 | default: | |
25 | ul_color_term_ok = 0; | |
26 | } | |
dfa68ad1 OO |
27 | return ul_color_term_ok; |
28 | } | |
29 | ||
30 | void color_enable(const char *color_scheme) | |
31 | { | |
5aaee63c | 32 | if (ul_color_term_ok && color_scheme) |
dfa68ad1 OO |
33 | fputs(color_scheme, stdout); |
34 | } | |
35 | ||
36 | void color_disable(void) | |
37 | { | |
38 | if (ul_color_term_ok) | |
39 | fputs(UL_COLOR_RESET, stdout); | |
40 | } | |
a10c0434 KZ |
41 | |
42 | int colormode_from_string(const char *str) | |
43 | { | |
44 | size_t i; | |
45 | static const char *modes[] = { | |
46 | [UL_COLORMODE_AUTO] = "auto", | |
47 | [UL_COLORMODE_NEVER] = "never", | |
48 | [UL_COLORMODE_ALWAYS] = "always" | |
49 | }; | |
50 | ||
51 | if (!str || !*str) | |
52 | return -EINVAL; | |
53 | ||
54 | assert(ARRAY_SIZE(modes) == __UL_NCOLORMODES); | |
55 | ||
56 | for (i = 0; i < ARRAY_SIZE(modes); i++) { | |
57 | if (strcasecmp(str, modes[i]) == 0) | |
58 | return i; | |
59 | } | |
60 | ||
61 | return -EINVAL; | |
62 | } | |
63 | ||
64 | #ifdef TEST_PROGRAM | |
65 | # include <getopt.h> | |
66 | # include <err.h> | |
67 | ||
68 | int main(int argc, char *argv[]) | |
69 | { | |
70 | static const struct option longopts[] = { | |
71 | { "colors", optional_argument, 0, 'c' }, | |
72 | { NULL, 0, 0, 0 } | |
73 | }; | |
74 | int c, mode = UL_COLORMODE_NEVER; /* default */ | |
75 | ||
76 | while ((c = getopt_long(argc, argv, "c::", longopts, NULL)) != -1) { | |
77 | switch (c) { | |
78 | case 'c': | |
79 | mode = UL_COLORMODE_AUTO; | |
80 | if (optarg) { | |
81 | char *p = *optarg == '=' ? optarg + 1 : optarg; | |
82 | ||
83 | mode = colormode_from_string(p); | |
84 | if (mode < 0) | |
85 | errx(EXIT_FAILURE, "'%s' unsupported color mode", p); | |
86 | } | |
87 | break; | |
88 | } | |
89 | } | |
90 | ||
91 | colors_init(mode); | |
92 | color_enable(UL_COLOR_RED); | |
93 | printf("Hello World!"); | |
94 | color_disable(); | |
95 | return EXIT_SUCCESS; | |
96 | } | |
97 | #endif | |
98 |