From 318e8a990ebe94c48f69d3bb1d342a31cf55f1db Mon Sep 17 00:00:00 2001 From: Philipp Gesang Date: Sat, 8 Sep 2018 18:38:09 +0200 Subject: common, cal: rework debug printers * prefix messages to indicate the debug level * colorize when printing to terminal This introduces a dependency on luaposix. --- common.lua | 45 +++++++++++++++++++++++++++++++++++++++------ 1 file changed, 39 insertions(+), 6 deletions(-) (limited to 'common.lua') diff --git a/common.lua b/common.lua index 2c68aee..89153d8 100644 --- a/common.lua +++ b/common.lua @@ -1,18 +1,51 @@ -local lpeg = require "lpeg" +local lpeg = require "lpeg" local string = require "string" local stringformat = string.format local verboselvl = 0 +local colorize = false -local mk_out = function (stream, threshold, newlinep) +--- check if stderr is pipe; use color otherwise +local ok, unistd = pcall (require, "posix.unistd") +if ok then + local stderr_fd = unistd.STDERR_FILENO + colorize = unistd.isatty (unistd.STDERR_FILENO) == 1 +end + +local esc = '\27[' + +local colors = + { black = esc .. "0;30m" + , red = esc .. "0;31m" + , green = esc .. "0;32m" + , yellow = esc .. "0;33m" + , blue = esc .. "0;34m" + , purple = esc .. "0;35m" + , cyan = esc .. "0;36m" + , white = esc .. "0;37m" + , reset = esc .. "m" + } + +local mk_out = function (stream, threshold, newlinep, pfx, color) + if pfx == nil then + pfx = "" + else + if colorize and color ~= nil then + local col = colors [color] + if col ~= nil then + pfx = col .. pfx .. colors.reset end + end + pfx = "["..pfx.."] " + end local out = io.stdout if stream == "err" or stream == "stderr" then out = io.stderr end return function (...) if verboselvl >= threshold then local ok, msg = pcall (stringformat, ...) if ok then - out:write (msg) + out.write (out, pfx) + out.write (out, msg) if newlinep == true then out:write "\n" end ---else silently ignore end @@ -62,9 +95,9 @@ end return { println = mk_out ("stdout", 0, true) - , errorln = mk_out ("stderr", 0, true) - , noiseln = mk_out ("stderr", 1, true) - , debugln = mk_out ("stderr", 2, true) + , errorln = mk_out ("stderr", 0, true, "error", "red") + , noiseln = mk_out ("stderr", 1, true, "info" , "yellow") + , debugln = mk_out ("stderr", 2, true, "debug", "purple") , set_verbosity = set_verbosity , trim_whitespace = trim_whitespace , unescape_string = unescape_string -- cgit v1.2.3