diff --git a/.luacov b/.luacov index 22cfe71..5f02cf4 100644 --- a/.luacov +++ b/.luacov @@ -11,5 +11,6 @@ return { ".*/.luarocks/.*", ".*/site/pack/.*", ".*/tests/cases/.*", + ".*/kibi2/logger/.*", }, } \ No newline at end of file diff --git a/lua/keyevent/init.lua b/lua/keyevent/init.lua index a79d9a6..53b6baf 100644 --- a/lua/keyevent/init.lua +++ b/lua/keyevent/init.lua @@ -1,5 +1,3 @@ -local api = vim.api -- Neovim - local config = require("keyevent.config") local os = require("keyevent.os") local KeyEvent = require("keyevent.keyevent") diff --git a/lua/keyevent/log.lua b/lua/keyevent/log.lua index a4b7354..9e009a4 100644 --- a/lua/keyevent/log.lua +++ b/lua/keyevent/log.lua @@ -1,471 +1,92 @@ -local api = vim.api -- Neovim -local bo = vim.bo -local fn = vim.fn - -local notify = require("keyevent.notify") -local config = require("keyevent.config") - --- ============================================================================= - -local M = {} - -local levels = vim.log.levels - -local level_names = {} -local PREFIX = "KB2" -local uv = vim.loop -local queue = {} -local scheduled = false -local log_bufnr = nil - -for name, value in pairs(levels) do - level_names[value] = name -end - -local last_tick = {} -local last_mem = 0 -local last_time = uv.hrtime() -local monitoring = false - --- ============================================================================= ---#region Private - ----@return integer -local function get_tick() - local bufnr = api.nvim_get_current_buf() - return api.nvim_buf_get_changedtick(bufnr) -end - ----@return integer -local function get_delta_tick() - local bufnr = api.nvim_get_current_buf() - local curr_tick = api.nvim_buf_get_changedtick(bufnr) - local prev_tick = last_tick[bufnr] - last_tick[bufnr] = curr_tick - if not prev_tick then - return 0 - end - -- local delta_tick = curr_tick - prev_tick - -- if delta_tick > 1 then - -- M.probe( - -- "TICK [%d] %d - %d = %d", - -- bufnr, - -- curr_tick, - -- prev_tick, - -- delta_tick - -- ) - -- end - return curr_tick - prev_tick -end - ----@return integer -local function get_mem_mb() - return collectgarbage("count") / 1024 -end - ----@return string -local function get_monitor() - if not config.log.monitor then - return "" - end - local current_mem = get_mem_mb() - local delta_mem = current_mem - last_mem - return string.format("[%d:%d(+%d)MB]", get_tick(), current_mem, delta_mem) -end - -local function monitor() - if monitoring then - return - end - monitoring = true - - local mem = get_mem_mb() - local now = uv.hrtime() - - local delta_tick = get_delta_tick() - if now - last_time < 1000 * 1e6 then - if delta_tick > 100 then - M.error("changedtick runaway detected") - end - end - - if mem > 2000 then - M.error("memory runaway: " .. mem .. "MB") - end - - last_mem = mem - last_time = now - - monitoring = false -end - ----@param value any ----@return any -local function normalize_for_log(value) - local v_type = type(value) - if v_type ~= "table" then - return value - end - local mt = getmetatable(value) - if mt and mt.__tostring then - return tostring(value) - end - local result = {} - for key, val in pairs(value) do - result[key] = normalize_for_log(val) - end - return result -end - ----@param value any ----@return string -local function stringify(value) - local v_type = type(value) - - if v_type == "table" then - local normalized = normalize_for_log(value) - if config.log.single_line then - return string.format( - " %s", - vim.inspect(normalized, { - newline = " ", - indent = "", - depth = 4, - }) - ) - else - return string.format("
\n%s", vim.inspect(value)) - end - elseif v_type == "string" then - return string.format(" %s", value) - else - return string.format("<%s> %s", v_type, tostring(value)) - end -end - ----@return string -local function get_timestamp() - if not config.log.use_timestamp then - return "" - end - local now = uv.hrtime() - if not last_time then - last_time = now - ---@type string - return os.date("[%H:%M:%S]") - end - local delta_ms = (now - last_time) / 1e6 - last_time = now - return string.format("[+%.0fms]", delta_ms) -end - -local function get_bufnr_by_name(name) - for _, bufnr in ipairs(api.nvim_list_bufs()) do - if api.nvim_buf_get_name(bufnr) == name then - return bufnr - end - end - return nil -end - -local category_hl_map = {} -local category_match_id = {} -api.nvim_set_hl(0, "TirLog_Entry", { fg = "#55ffff", bold = true }) -api.nvim_set_hl( - 0, - "TirLog_Error", - { fg = "#ffffff", bg = "#ff0000", bold = true } -) -api.nvim_set_hl(0, "TirLog_num", { fg = "#cc55cc", bold = true }) -api.nvim_set_hl(0, "Multi_Byte", { bg = "#664422", bold = true }) - ----@param bufnr number -local function apply_log_highlight(bufnr) - local winid = fn.bufwinid(bufnr) - if winid == -1 then - return - end - api.nvim_win_call(winid, function() - fn.clearmatches() - fn.matchadd("Multi_Byte", "[^\\x00-\\x7F]") - fn.matchadd("TirLog_Entry", "===") - --fn.matchadd("TirLog_Error", [[\[[0-9,]\+\]]]) - fn.matchadd("TirLog_num", "\\[[0-9,]\\+\\]") - fn.matchadd("TirLog_Error", "\\[ERROR\\]") - for cat, hl in pairs(category_hl_map) do - fn.matchadd(hl, "\\[" .. cat .. "\\]") - end - end) -end - -local aug = api.nvim_create_augroup("Kbi2LogHL", { clear = true }) ----@param bufnr number -local function register_autocmds(bufnr) - api.nvim_create_autocmd("BufWinEnter", { - group = aug, - buffer = bufnr, - callback = function(args) - --if args.buf == log_bufnr then - apply_log_highlight(args.buf) - --end +local ok, logger = pcall(require, "kibi2.logger.logger") + +if not ok then + logger = { + debug = function() end, + info = function() end, + warn = function() end, + error = function(fmt, ...) + local args = { ... } + local message + if type(fmt) == "string" or #args == 0 then + local ok, result = pcall(function() + return string.format(fmt, unpack(args)) + end) + if ok then + message = result + end + end + if not message then + local args = { fmt, ... } + local parts = vim.tbl_map(tostring, args) + message = table.concat(parts, " ") + end + vim.schedule(function() + vim.notify(message, vim.log.levels.ERROR) + end) end, - }) -end - ----@return number -local function ensure_log_buf() - if log_bufnr and api.nvim_buf_is_valid(log_bufnr) then - return log_bufnr - end - log_bufnr = get_bufnr_by_name(config.log.buffer_name) - if log_bufnr then - return log_bufnr - end - ---@type number - log_bufnr = api.nvim_create_buf(false, true) - api.nvim_buf_set_name(log_bufnr, config.log.buffer_name) - - bo[log_bufnr].buftype = "nofile" - bo[log_bufnr].bufhidden = "hide" - bo[log_bufnr].swapfile = false - register_autocmds(log_bufnr) - return log_bufnr -end - -local function flush_buffer(buf_string) - local bufnr = ensure_log_buf() - api.nvim_buf_set_lines(bufnr, -1, -1, false, vim.split(buf_string, "\n")) - local line_count = api.nvim_buf_line_count(bufnr) - local win = fn.bufwinid(bufnr) - if win ~= -1 then - api.nvim_win_set_cursor(win, { line_count, 0 }) - api.nvim_win_call(win, function() - -- vim.cmd("normal! 3kzz") - end) - end -end - -local initialized = false -local function flush_file(buf_string) - local file = config.log.file_name or "/tmp/kibi2.log" - if not initialized then - local fds = io.open(file, "w") - if fds then - fds:close() - else - error("kibi2: failed to open log file: " .. file) - end - initialized = true - end - local fds = io.open(file, "a") - if fds then - fds:write(buf_string .. "\n") - fds:close() - end -end - -local function flush() - scheduled = false - if #queue == 0 then - return - end - local buf_string = table.concat(queue, "\n") - buf_string = buf_string:gsub("\r", "") - if config.log.output == "buffer" then - flush_buffer(buf_string) - elseif config.log.output == "file" then - flush_file(buf_string) - end - queue = {} -end - ----@param msg string -local function write_buffer(msg) - table.insert(queue, msg) - if not scheduled then - scheduled = true - vim.schedule(flush) - end -end - -local unpack = table.unpack or unpack -- Lua 5.1/5.2 compatibility -local palette = { - "#ff5555", - "#55aaaa", - "#ffff55", - "#aaff55", - "#aa55ff", - "#ffaa55", -} - -local assigned = {} -local used = {} - -local function pick_color(cat) - if assigned[cat] then - return assigned[cat] - end - local hash = fn.sha256(cat) - local base = (fn.str2nr(hash:sub(1, 8), 16) % #palette) + 1 - for i = 0, #palette - 1 do - local idx = ((base + i - 1) % #palette) + 1 - local color = palette[idx] - if not used[color] then - assigned[cat] = color - used[color] = true - return color - end - end - local color = palette[base] - assigned[cat] = color - return color -end - -local function ensure_category_highlight(category) - if category_hl_map[category] then - return category_hl_map[category] - end - - local hl = "TirLog_" .. category - local color = pick_color(category) - - api.nvim_set_hl(0, hl, { fg = color, bold = true }) - - category_hl_map[category] = hl - return hl + probe = function() end, + watch = function() end, + is_debug = function() + return false + end, + assert = function(condition, message, ...) + if not condition then + error(string.format(message, ...), 2) + end + return condition + end, + } end -local function ensure_match(bufnr, category, hl) - if category_match_id[category] then - return - end - - api.nvim_buf_call(bufnr, function() - local pattern = "\\[" .. category .. "\\]" - local id = fn.matchadd(hl, pattern) - category_match_id[category] = id - end) -end +-- ============================================================================= ----@param force boolean ----@param level integer ----@param opts? table ----@param fmt any ----@param ... unknown -local function emit(force, level, opts, fmt, ...) - monitor() - if not force and level < config.log.level then - return - end - if opts == nil or fmt == nil then - return - end - local category = opts and opts.category - if category then - local bufnr = ensure_log_buf() - local hl = ensure_category_highlight(category) - ensure_match(bufnr, category, hl) - end - local info = debug.getinfo(3, "Sl") - local file = info and (info.short_src:match("([^/\\]+)$")) or "?" - local line = info and info.currentline or 0 - local args = { ... } - local msg - local ok, result = pcall(function() - return string.format(fmt, unpack(args)) - end) - if ok then - msg = result - else - local args = { fmt, ... } - local parts = vim.tbl_map(stringify, args) - msg = table.concat(parts, " ") - end - local ts = get_timestamp() - local mon = get_monitor() - local name = level_names[level] - if force then - name = "🟧PRB" - elseif category then - name = category - end - local final = string.format( - "[%s]%s%s[%s][%s %d] %s", - PREFIX, - ts, - mon, - name, - file, - line, - msg - ) - if config.log.output == "buffer" then - write_buffer(final) - elseif config.log.output == "file" then - write_buffer(final) - elseif config.log.output == "print" then - print(final) - else - notify.notify(final, level) - end -end +local M = {} ---#endregion -- ============================================================================= -- Public API ---@param ... unknown function M.debug(...) - emit(false, levels.DEBUG, {}, ...) + logger.debug(...) end ---@param ... unknown function M.info(...) - emit(false, levels.INFO, {}, ...) + logger.info(...) end ---@param ... unknown function M.warn(...) - emit(false, levels.WARN, {}, ...) + logger.warn(...) end ---@param ... unknown function M.error(...) - emit(false, levels.ERROR, {}, ...) + logger.error(...) end ---@param ... unknown function M.probe(...) - if not config.log.probe then - return - end - emit(true, levels.ERROR, {}, ...) + logger.probe(...) end ---@param category string ---@param ... unknown function M.watch(category, ...) - if levels.DEBUG < config.log.level then - return - end - emit(false, levels.DEBUG, { category = category }, ...) + logger.watch(category, ...) end ---@return boolean function M.is_debug() - return levels.DEBUG >= config.log.level + return logger.is_debug() end ---@param condition any ---@param message string ---@param ... unknown function M.assert(condition, message, ...) - if M.is_debug() then - assert(condition, message, ...) - end - if not condition then - M.error(message, ...) - end + logger.assert(condition, message, ...) end return M diff --git a/lua/keyevent/notify.lua b/lua/keyevent/notify.lua deleted file mode 100644 index a410be1..0000000 --- a/lua/keyevent/notify.lua +++ /dev/null @@ -1,51 +0,0 @@ --- ============================================================================= - -local M = {} - --- ============================================================================= ---#region Private - ----@param msg string ----@param level integer -local function emit(msg, level) - if msg == nil then - return - end - -- In test mode, avoid scheduling for deterministic behavior. - if vim.g.kibi2_test_mode then - if msg ~= "" then - print(msg) - end - else - vim.schedule(function() - vim.notify(msg, level) - end) - end -end - ---#endregion --- ============================================================================= --- Public API - ----@param msg string -function M.error(msg) - emit(msg, vim.log.levels.ERROR) -end - ----@param msg string -function M.warn(msg) - emit(msg, vim.log.levels.WARN) -end - ----@param msg string -function M.info(msg) - emit(msg, vim.log.levels.INFO) -end - ----@param msg string ----@param level integer -function M.notify(msg, level) - emit(msg, level) -end - -return M diff --git a/tests/cases/check/rg_ng_char/out-expected.txt b/tests/cases/check/rg_ng_char/out-expected.txt index 47af43a..c7eccd5 100644 --- a/tests/cases/check/rg_ng_char/out-expected.txt +++ b/tests/cases/check/rg_ng_char/out-expected.txt @@ -1,2 +1 @@ /Users/ogawa/oss/keyevent.nvim/lua/keyevent/keyevent.lua: note = string.format("↻") -/Users/ogawa/oss/keyevent.nvim/lua/keyevent/log.lua: name = "🟧PRB" diff --git a/tests/cases/logger/logger_error/out-expected.txt b/tests/cases/logger/logger_error/out-expected.txt new file mode 100644 index 0000000..c5074ad --- /dev/null +++ b/tests/cases/logger/logger_error/out-expected.txt @@ -0,0 +1,15 @@ +--- logger --- +=== MESSAGE === + +--- CASE 6: logger --- +[KB2][DEBUG][log.lua] log debug 1 two three +[KB2][INFO][log.lua] log info 1 two three +[KB2][WARN][log.lua] log warn 1 two three +[KB2][🟧PRB][log.lua 71] log probe 1 two three +[KB2][LOG][log.lua] watch +true +[KB2][ERROR][log.lua] log error 1 2 three +[KB2][ERROR][log.lua] 1 2 three + +=== DISPLAY === + diff --git a/tests/cases/logger/logger_error/run.vim b/tests/cases/logger/logger_error/run.vim new file mode 100644 index 0000000..5a7f3ae --- /dev/null +++ b/tests/cases/logger/logger_error/run.vim @@ -0,0 +1,30 @@ +source $KIBI2_REPO_ROOT/tests/common.vim + +" ===== logger ===== +new + +CASE logger + +lua << EOF + local root = assert(os.getenv("KIBI2_REPO_ROOT")) + vim.opt.rtp:prepend(root) + vim.opt.rtp:prepend(root .. "/../logger.nvim") + require("kibi2.logger").setup({ + level = vim.log.levels.DEBUG, + output = "print", + }) + + package.loaded["keyevent.log"] = nil + log = require("keyevent.log") + log.debug("log debug %d %s %s", 1, "two", "three") + log.info("log info %d %s %s", 1, "two", "three") + log.warn("log warn %d %s %s", 1, "two", "three") + log.probe("log probe %d %s %s", 1, "two", "three") + log.watch("LOG", "watch") + print(log.is_debug()) + log.assert(true, "OK") + log.error("log error %d %d %s", 1, 2, "three") + log.error(1, 2, "three") +EOF + +call Snapshot({ 'desc': 'logger' }) diff --git a/tests/cases/logger/logger_error/skip-ci b/tests/cases/logger/logger_error/skip-ci new file mode 100644 index 0000000..e69de29 diff --git a/tests/cases/logger/no_logger_error/hook.sh b/tests/cases/logger/no_logger_error/hook.sh new file mode 100755 index 0000000..3d6e6ae --- /dev/null +++ b/tests/cases/logger/no_logger_error/hook.sh @@ -0,0 +1,15 @@ +#!/bin/sh +set -eu + +case "${1:-run}" in + pre) + ;; + post) + LC_ALL=C sed \ + -e 's/t .*\/tests\//t \/tests\//' \ + stderr.txt > gen.txt + mv gen.txt out-actual.txt + ;; +esac + + #-e 's/^while processing //g' \ diff --git a/tests/cases/logger/no_logger_error/out-expected.txt b/tests/cases/logger/no_logger_error/out-expected.txt new file mode 100644 index 0000000..0b39f6b --- /dev/null +++ b/tests/cases/logger/no_logger_error/out-expected.txt @@ -0,0 +1,7 @@ + +--- CASE 6: logger --- +false +Error detected while processing command line..script /tests/cases/logger/no_logger_error/run.vim[22]..function Snapshot: +line 1: +log error 1 2 three +1 2 three \ No newline at end of file diff --git a/tests/cases/logger/no_logger_error/run.vim b/tests/cases/logger/no_logger_error/run.vim new file mode 100644 index 0000000..c027ec1 --- /dev/null +++ b/tests/cases/logger/no_logger_error/run.vim @@ -0,0 +1,22 @@ +source $KIBI2_REPO_ROOT/tests/common.vim + +" ===== logger ===== +new + +CASE logger + +lua << EOF + package.loaded["keyevent.log"] = nil + log = require("keyevent.log") + log.debug("log debug %d %s %s", 1, "two", "three") + log.info("log info %d %s %s", 1, "two", "three") + log.warn("log warn %d %s %s", 1, "two", "three") + log.probe("log probe %d %s %s", 1, "two", "three") + log.watch("LOG", "watch") + print(log.is_debug()) + log.assert(true, "OK") + log.error("log error %d %d %s", 1, 2, "three") + log.error(1, 2, "three") +EOF + +call Snapshot({ 'desc': 'logger' }) diff --git a/tests/cases/logger/no_logger_error/skip-ci b/tests/cases/logger/no_logger_error/skip-ci new file mode 100644 index 0000000..e69de29 diff --git a/tests/common_key.lua b/tests/common_key.lua index 8bf1223..a6d6055 100644 --- a/tests/common_key.lua +++ b/tests/common_key.lua @@ -1,7 +1,6 @@ KeyEvent = require("keyevent.keyevent") Config = require("keyevent.config") Os = require("keyevent.os") -local log = require("keyevent.log") local M = {}