]> git.ipfire.org Git - thirdparty/systemd.git/blobdiff - src/basic/terminal-util.c
basic/terminal-util: cache value for colors_enabled
[thirdparty/systemd.git] / src / basic / terminal-util.c
index 68664a152ffcc530289556ae239f002893d450fb..9521b79daa1530580980e4a5b6bdb6f06a13391f 100644 (file)
 #include "fileio.h"
 #include "fs-util.h"
 #include "io-util.h"
+#include "log.h"
+#include "macro.h"
 #include "parse-util.h"
 #include "process-util.h"
 #include "socket-util.h"
-#include "log.h"
-#include "macro.h"
 #include "stat-util.h"
 #include "string-util.h"
 #include "terminal-util.h"
@@ -128,7 +128,7 @@ int read_one_char(FILE *f, char *ret, usec_t t, bool *need_nl) {
 
         errno = 0;
         if (!fgets(line, sizeof(line), f))
-                return errno ? -errno : -EIO;
+                return errno > 0 ? -errno : -EIO;
 
         truncate_nl(line);
 
@@ -212,7 +212,7 @@ int ask_string(char **ret, const char *text, ...) {
 
                 errno = 0;
                 if (!fgets(line, sizeof(line), stdin))
-                        return errno ? -errno : -EIO;
+                        return errno > 0 ? -errno : -EIO;
 
                 if (!endswith(line, "\n"))
                         putchar('\n');
@@ -726,9 +726,7 @@ bool tty_is_vc_resolve(const char *tty) {
 }
 
 const char *default_term_for_tty(const char *tty) {
-        assert(tty);
-
-        return tty_is_vc_resolve(tty) ? "TERM=linux" : "TERM=vt220";
+        return tty && tty_is_vc_resolve(tty) ? "TERM=linux" : "TERM=vt220";
 }
 
 int fd_columns(int fd) {
@@ -1135,3 +1133,21 @@ int open_terminal_in_namespace(pid_t pid, const char *name, int mode) {
 
         return receive_one_fd(pair[0], 0);
 }
+
+bool colors_enabled(void) {
+        static int enabled = -1;
+
+        if (_unlikely_(enabled < 0)) {
+                const char *colors;
+
+                colors = getenv("SYSTEMD_COLORS");
+                if (colors)
+                        enabled = parse_boolean(colors) != 0;
+                else if (streq_ptr(getenv("TERM"), "dumb"))
+                        enabled = false;
+                else
+                        enabled = on_tty();
+        }
+
+        return enabled;
+}