From 6a677a65b288fe22c645389c55f64efde090569b Mon Sep 17 00:00:00 2001 From: Jon Michael Aanes Date: Sat, 15 Jul 2017 23:29:51 +0200 Subject: [PATCH] Found and fixed issue occuring when function was loaded from a module pretty couldn't find. --- function.lua | 14 ++++++++++---- test/test_pretty.lua | 23 +++++++++++++++++++++++ 2 files changed, 33 insertions(+), 4 deletions(-) diff --git a/function.lua b/function.lua index fd51040..907be62 100644 --- a/function.lua +++ b/function.lua @@ -181,10 +181,16 @@ local function get_function_body_info (info) if info.defined_how == 'file' then -- Read file local file = io.open(info.short_src, 'r') - str = file:read '*all' - file:close() + if file then + str = file:read '*all' + file:close() + else + str = nil + end end + if not str then return info end + -- Calculate indices of the lines the function should be defined at. local start_line_index = get_line_index(str, info.linedefined) local end_line_index = get_line_index(str, info.lastlinedefined + 1) @@ -255,10 +261,10 @@ return function (value, depth, l, format_value) local function_params, function_body = nil, '...' - if not info.docs then + if not info.docs and info.defined_how ~= 'C' then info = get_function_body_info(info) - if #info.body <= NR_CHARS_IN_LONG_FUNCTION_BODY and not info.body:find '\n' and not info.body:find(FUNCTION_KEYWORD_MATCH) then + if info.body and #info.body <= NR_CHARS_IN_LONG_FUNCTION_BODY and not info.body:find '\n' and not info.body:find(FUNCTION_KEYWORD_MATCH) then if info.defined_how == 'string' then function_body = info.body end end end diff --git a/test/test_pretty.lua b/test/test_pretty.lua index 1bf7235..bb72972 100644 --- a/test/test_pretty.lua +++ b/test/test_pretty.lua @@ -377,6 +377,29 @@ if HAS_JIT_LIBRARY then } end +-------------------------------------------------------------------------------- +-- General + +SUITE:addTest('UseCase: Can print _G with max_depth = 1', function () + format(_G, {max_depth = 1}) + assert(true) +end) + +SUITE:addTest('UseCase: Can load function from file that is shortly deleted', function () + local module_name = 'tmp_'..os.time() + -- Create module + local file = io.open('./'..module_name..'.lua', 'w') + file:write '\nlocal function yo ()\n -- Hello World\n return math.random()\nend\n\nreturn yo\n' + file:close() + -- Load module + local yo = require(module_name) + -- Remove module + os.remove('./'..module_name..'.lua') + -- Format the function, even though the module it came from is gone. + format(yo) + assert(true) +end) + -------------------------------------------------------------------------------- return SUITE