From b6384c2601f41308b8b01e6f781eb8403165597a Mon Sep 17 00:00:00 2001 From: =?utf8?q?Alexis=20Laferri=C3=A8re?= Date: Fri, 16 Mar 2018 10:42:22 -0400 Subject: [PATCH] console: only color outputs if stdout isa TTY MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit Signed-off-by: Alexis Laferrière --- lib/console.nit | 17 ++++++++++++++++- lib/core/posix.nit | 5 +++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/lib/console.nit b/lib/console.nit index 917f893..1a68ff3 100644 --- a/lib/console.nit +++ b/lib/console.nit @@ -13,6 +13,10 @@ # limitations under the License. # Defines some ANSI Terminal Control Escape Sequences. +# +# The color methods (e.g. `Text::green`) format the text to appear colored +# in a ANSI/VT100 terminal. By default, this coloring is skipped if stdout +# is not a TTY, but it can be forced by setting `force_console_colors = true`. module console # A ANSI/VT100 escape sequence. @@ -282,7 +286,9 @@ end # Services to color terminal output redef class Text private fun apply_format(f: TermCharFormat): String do - return "{f}{self}{normal}" + if stdout_isatty or force_console_colors then + return "{f}{self}{normal}" + else return to_s end private fun normal: TermCharFormat do return new TermCharFormat @@ -409,3 +415,12 @@ class TermProgress display(metadata) end end + +redef class Sys + private var stdout_isatty: Bool = 1.isatty is lazy + + # Force coloring terminal output, even if stdout is not a TTY? + # + # Defaults to `false`. + var force_console_colors = false is writable +end diff --git a/lib/core/posix.nit b/lib/core/posix.nit index 2969830..587e606 100644 --- a/lib/core/posix.nit +++ b/lib/core/posix.nit @@ -111,3 +111,8 @@ extern class Group `{struct group*`} return ret; `} end + +redef class Int + # Does the file descriptor `self` refer to a terminal? + fun isatty: Bool `{ return isatty(self); `} +end -- 1.7.9.5