Commit | Line | Data |
---|---|---|
1479465f GJ |
1 | /* |
2 | * libdpkg - Debian packaging suite library routines | |
3 | * color.c - color support | |
4 | * | |
5 | * Copyright © 2015-2016 Guillem Jover <guillem@debian.org> | |
6 | * | |
7 | * This is free software; you can redistribute it and/or modify | |
8 | * it under the terms of the GNU General Public License as published by | |
9 | * the Free Software Foundation; either version 2 of the License, or | |
10 | * (at your option) any later version. | |
11 | * | |
12 | * This is distributed in the hope that it will be useful, | |
13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of | |
14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | |
15 | * GNU General Public License for more details. | |
16 | * | |
17 | * You should have received a copy of the GNU General Public License | |
18 | * along with this program. If not, see <http://www.gnu.org/licenses/>. | |
19 | */ | |
20 | ||
21 | #include <config.h> | |
22 | #include <compat.h> | |
23 | ||
24 | #include <stdbool.h> | |
25 | #include <stdlib.h> | |
26 | #include <string.h> | |
27 | #include <unistd.h> | |
28 | ||
29 | #include <dpkg/macros.h> | |
30 | #include <dpkg/color.h> | |
31 | ||
32 | static enum color_mode color_mode = COLOR_MODE_UNKNOWN; | |
33 | static bool use_color = false; | |
34 | ||
35 | bool | |
36 | color_set_mode(const char *mode) | |
37 | { | |
38 | if (strcmp(mode, "auto") == 0) { | |
39 | color_mode = COLOR_MODE_AUTO; | |
40 | use_color = isatty(STDOUT_FILENO); | |
41 | } else if (strcmp(mode, "always") == 0) { | |
42 | color_mode = COLOR_MODE_ALWAYS; | |
43 | use_color = true; | |
44 | } else { | |
45 | color_mode = COLOR_MODE_NEVER; | |
46 | use_color = false; | |
47 | } | |
48 | ||
49 | return use_color; | |
50 | } | |
51 | ||
52 | static bool | |
53 | color_enabled(void) | |
54 | { | |
55 | const char *mode; | |
56 | ||
57 | if (color_mode != COLOR_MODE_UNKNOWN) | |
58 | return use_color; | |
59 | ||
60 | mode = getenv("DPKG_COLORS"); | |
61 | if (mode == NULL) | |
62 | mode = "auto"; | |
63 | ||
64 | return color_set_mode(mode); | |
65 | } | |
66 | ||
67 | const char * | |
68 | color_get(const char *color) | |
69 | { | |
70 | if (!color_enabled()) | |
71 | return ""; | |
72 | ||
73 | return color; | |
74 | } |