Skip to content

Commit

Permalink
feat: add ansi codes stripping
Browse files Browse the repository at this point in the history
  • Loading branch information
fredrikaverpil committed Jul 22, 2024
1 parent e8f8da8 commit ad6e8eb
Show file tree
Hide file tree
Showing 3 changed files with 64 additions and 0 deletions.
1 change: 1 addition & 0 deletions lua/neotest-golang/lib/init.lua
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,6 @@ M.cmd = require("neotest-golang.lib.cmd")
M.find = require("neotest-golang.lib.find")
M.json = require("neotest-golang.lib.json")
M.string = require("neotest-golang.lib.string")
M.strip = require("neotest-golang.lib.strip")

return M
60 changes: 60 additions & 0 deletions lua/neotest-golang/lib/strip.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
local M = {}

local convert = require("neotest-golang.lib.convert")

-- ANSI escape codes
M.ESCAPE = convert.to_lua_pattern(string.char(27))
M.CURSOR_HIDE = convert.to_lua_pattern(string.char(27) .. "[?25l")
M.CLEAR_SCREEN = convert.to_lua_pattern(string.char(27) .. "[2J")
M.RESET_ATTRIBUTES = convert.to_lua_pattern(string.char(27) .. "[m")
M.CURSOR_HOME = convert.to_lua_pattern(string.char(27) .. "[H")
M.BELL = convert.to_lua_pattern(string.char(7)) -- \a

-- Table of all codes to remove
M.CODES_TO_REMOVE = {
M.ESCAPE .. "%[%d*[%.%d]*[%a%d]*", -- Catches most ANSI sequences
M.CURSOR_HIDE,
M.CLEAR_SCREEN,
M.RESET_ATTRIBUTES,
M.CURSOR_HOME,
M.BELL,
convert.to_lua_pattern("[\0-\31\127]"), -- Control characters
}

-- Function to clean ANSI codes from a string
local function cleanString(str)
if type(str) ~= "string" then
return str
end

for _, code in ipairs(M.CODES_TO_REMOVE) do
str = str:gsub(code, "")
end
return str:gsub("\n$", "") -- Remove trailing newline
end

-- Function to clean ANSI codes from a table
function M.cleanTable(tbl)
if type(tbl) ~= "table" then
return tbl
end

local cleanedTable = {}
for i, item in ipairs(tbl) do
local cleaned = cleanString(item)

-- Attempt to parse JSON
local success, parsed = pcall(function()
return vim.json.decode(cleaned)
end)

if success then
cleanedTable[i] = parsed
else
cleanedTable[i] = cleaned
end
end
return cleanedTable
end

return M
3 changes: 3 additions & 0 deletions lua/neotest-golang/process.lua
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,10 @@ function M.test_results(spec, result, tree)
raw_output = async.fn.readfile(context.test_output_json_filepath)
end

local cleaned_table = lib.strip.cleanTable(raw_output)
logger.debug({ "Table stripped from ansi codes", cleaned_table })
local gotest_output = lib.json.decode_from_table(raw_output)
logger.debug({ "Table JSON-decoded", gotest_output })

--- The 'go list -json' output, converted into a lua table.
local golist_output = context.golist_data
Expand Down

0 comments on commit ad6e8eb

Please sign in to comment.