From e0ea844d50690ea54c4faa02e34a51f7176fbcc9 Mon Sep 17 00:00:00 2001 From: Ico Doornekamp Date: Fri, 2 Jun 2023 10:52:13 +0200 Subject: [PATCH] added os/isatty, do not enable colors if stdout is not a tty --- src/boot/boot.janet | 4 +++- src/core/os.c | 18 ++++++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/src/boot/boot.janet b/src/boot/boot.janet index 0004f954..7d7afcf2 100644 --- a/src/boot/boot.janet +++ b/src/boot/boot.janet @@ -3903,7 +3903,9 @@ (if-let [jp (getenv-alias "JANET_PATH")] (setdyn *syspath* jp)) (if-let [jprofile (getenv-alias "JANET_PROFILE")] (setdyn *profilepath* jprofile)) - (set colorize (not (getenv-alias "NO_COLOR"))) + (set colorize (and + (not (getenv-alias "NO_COLOR")) + (os/isatty stdout))) (defn- get-lint-level [i] diff --git a/src/core/os.c b/src/core/os.c index 4d3a3448..d59bec98 100644 --- a/src/core/os.c +++ b/src/core/os.c @@ -1431,6 +1431,23 @@ JANET_CORE_FN(os_sleep, return janet_wrap_nil(); } +JANET_CORE_FN(os_isatty, + "(os/isatty &opt file)", + "Returns true if `file` is a terminal. If `file` is not specified, " + "it will default to standard output.") { + janet_arity(argc, 0, 1); + FILE *f = (argc == 1) ? janet_getfile(argv, 0, NULL) : stdout; +#ifdef JANET_WINDOWS + int fd = _fileno(f); + if (fd == -1) janet_panicv(janet_ev_lasterr()); + return janet_wrap_boolean(_isatty(fd)); +#else + int fd = fileno(f); + if (fd == -1) janet_panicv(janet_ev_lasterr()); + return janet_wrap_boolean(isatty(fd)); +#endif +} + JANET_CORE_FN(os_cwd, "(os/cwd)", "Returns the current working directory.") { @@ -2469,6 +2486,7 @@ void janet_lib_os(JanetTable *env) { JANET_CORE_REG("os/date", os_date), /* not high resolution */ JANET_CORE_REG("os/strftime", os_strftime), JANET_CORE_REG("os/sleep", os_sleep), + JANET_CORE_REG("os/isatty", os_isatty), /* env functions */ JANET_CORE_REG("os/environ", os_environ),