xref: /aosp_15_r20/external/ltp/lib/tst_ansi_color.c (revision 49cdfc7efb34551c7342be41a7384b9c40d7cab7)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Copyright (c) 2017 Petr Vorel <[email protected]>
4  */
5 
6 #include <unistd.h>
7 #include <stdlib.h>
8 #include <string.h>
9 
10 #include "tst_res_flags.h"
11 #include "tst_ansi_color.h"
12 
tst_ttype2color(int ttype)13 char* tst_ttype2color(int ttype)
14 {
15 	switch (TTYPE_RESULT(ttype)) {
16 	case TPASS:
17 		return ANSI_COLOR_GREEN;
18 	break;
19 	case TFAIL:
20 		return ANSI_COLOR_RED;
21 	break;
22 	case TBROK:
23 		return ANSI_COLOR_RED;
24 	break;
25 	case TCONF:
26 		return ANSI_COLOR_YELLOW;
27 	break;
28 	case TWARN:
29 		return ANSI_COLOR_MAGENTA;
30 	break;
31 	case TINFO:
32 		return ANSI_COLOR_BLUE;
33 	break;
34 	case TDEBUG:
35 		return ANSI_COLOR_WHITE;
36 	break;
37 	default:
38 		return "";
39 	}
40 }
41 
tst_color_enabled(int fd)42 int tst_color_enabled(int fd)
43 {
44 	static int color;
45 
46 	if (color)
47 		return color - 1;
48 
49 	char *env = getenv("LTP_COLORIZE_OUTPUT");
50 
51 	if (env) {
52 		if (!strcmp(env, "n") || !strcmp(env, "0"))
53 			color = 1;
54 
55 		if (!strcmp(env, "y") || !strcmp(env, "1"))
56 			color = 2;
57 
58 		return color - 1;
59 	}
60 
61 	if (isatty(fd) == 0)
62 		color = 1;
63 	else
64 		color = 2;
65 
66 	return color - 1;
67 }
68