summaryrefslogtreecommitdiff
path: root/common.lua
diff options
context:
space:
mode:
authorPhilipp Gesang <phg@phi-gamma.net>2018-09-08 18:38:09 +0200
committerPhilipp Gesang <phg@phi-gamma.net>2018-09-08 18:38:15 +0200
commit318e8a990ebe94c48f69d3bb1d342a31cf55f1db (patch)
treebd0796fc12ebe6dcc7d6c1a3a5df5eaedb8fdb27 /common.lua
parent35aaedc729970ae2c5aa26738babd6c9939e338c (diff)
downloadcaldr-318e8a990ebe94c48f69d3bb1d342a31cf55f1db.tar.gz
common, cal: rework debug printers
* prefix messages to indicate the debug level * colorize when printing to terminal This introduces a dependency on luaposix.
Diffstat (limited to 'common.lua')
-rw-r--r--common.lua45
1 files changed, 39 insertions, 6 deletions
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