From d9537e72ba3707f80edae6b86e078330261a3d0d Mon Sep 17 00:00:00 2001 From: Barrett Ruth Date: Thu, 2 Oct 2025 22:35:30 -0400 Subject: [PATCH] many fixes --- lua/cp/cache.lua | 5 - lua/cp/health.lua | 22 +++ lua/cp/runner/execute.lua | 332 +++++++++++++---------------------- lua/cp/runner/run.lua | 313 +++++++++++++-------------------- lua/cp/runner/run_render.lua | 27 +-- lua/cp/ui/layouts.lua | 38 ++-- lua/cp/ui/panel.lua | 6 +- lua/cp/utils.lua | 104 ++++++++++- lua/cp/utils/buffer.lua | 31 ---- 9 files changed, 396 insertions(+), 482 deletions(-) delete mode 100644 lua/cp/utils/buffer.lua diff --git a/lua/cp/cache.lua b/lua/cp/cache.lua index 8a45294..696d8ae 100644 --- a/lua/cp/cache.lua +++ b/lua/cp/cache.lua @@ -15,11 +15,6 @@ ---@field name string ---@field id string ----@class CacheData ----@field [string] table ----@field file_states? table ----@field contest_lists? table - ---@class Problem ---@field id string ---@field name? string diff --git a/lua/cp/health.lua b/lua/cp/health.lua index c2193ec..71c4f12 100644 --- a/lua/cp/health.lua +++ b/lua/cp/health.lua @@ -10,6 +10,27 @@ local function check_nvim_version() end end +local function check_gnu_time() + local sysname = vim.loop.os_uname().sysname + if sysname == 'Windows_NT' then + vim.health.error('Windows is not supported for runs (GNU time is required).') + return + end + + local cap = utils.time_capability() + if cap.ok then + vim.health.ok('GNU time found: ' .. cap.path) + return + end + + vim.health.error('GNU time not found: ' .. (cap.reason or '')) + if sysname == 'Darwin' then + vim.health.info('Install via Homebrew: brew install coreutils (binary: gtime)') + else + vim.health.info('Install via your package manager, e.g., Debian/Ubuntu: sudo apt install time') + end +end + local function check_uv() if vim.fn.executable('uv') == 1 then vim.health.ok('uv executable found') @@ -55,6 +76,7 @@ function M.check() check_uv() check_python_env() check_luasnip() + check_gnu_time() end return M diff --git a/lua/cp/runner/execute.lua b/lua/cp/runner/execute.lua index b9cd9b5..89a1816 100644 --- a/lua/cp/runner/execute.lua +++ b/lua/cp/runner/execute.lua @@ -2,42 +2,35 @@ ---@field stdout string ---@field code integer ---@field time_ms number ----@field timed_out boolean +---@field tled boolean +---@field mled boolean +---@field peak_mb number +---@field signal string|nil local M = {} -local logger = require('cp.log') - local constants = require('cp.constants') +local logger = require('cp.log') +local utils = require('cp.utils') + local filetype_to_language = constants.filetype_to_language ----@param source_file string ----@param contest_config table ----@return string local function get_language_from_file(source_file, contest_config) - local extension = vim.fn.fnamemodify(source_file, ':e') - local language = filetype_to_language[extension] or contest_config.default_language - return language + local ext = vim.fn.fnamemodify(source_file, ':e') + return filetype_to_language[ext] or contest_config.default_language end ----@param cmd_template string[] ----@param substitutions table ----@return string[] local function substitute_template(cmd_template, substitutions) - local result = {} - for _, arg in ipairs(cmd_template) do - local substituted = arg - for key, value in pairs(substitutions) do - substituted = substituted:gsub('{' .. key .. '}', value) + local out = {} + for _, a in ipairs(cmd_template) do + local s = a + for k, v in pairs(substitutions) do + s = s:gsub('{' .. k .. '}', v) end - table.insert(result, substituted) + table.insert(out, s) end - return result + return out end ----@param cmd_template string[] ----@param executable? string ----@param substitutions table ----@return string[] local function build_command(cmd_template, executable, substitutions) local cmd = substitute_template(cmd_template, substitutions) if executable then @@ -46,245 +39,158 @@ local function build_command(cmd_template, executable, substitutions) return cmd end ----@param language_config table ----@param substitutions table ----@return {code: integer, stdout: string} -function M.compile_generic(language_config, substitutions) +function M.compile(language_config, substitutions) if not language_config.compile then - logger.log('No compilation step required for language - skipping.') - return { code = 0, stderr = '' } + return { code = 0, stdout = '' } end - local compile_cmd = substitute_template(language_config.compile, substitutions) - local redirected_cmd = vim.deepcopy(compile_cmd) - if #redirected_cmd > 0 then - redirected_cmd[#redirected_cmd] = redirected_cmd[#redirected_cmd] .. ' 2>&1' - end + local cmd = substitute_template(language_config.compile, substitutions) + local sh = table.concat(cmd, ' ') .. ' 2>&1' - local start_time = vim.uv.hrtime() - local result = vim - .system({ 'sh', '-c', table.concat(redirected_cmd, ' ') }, { text = false }) - :wait() - local compile_time = (vim.uv.hrtime() - start_time) / 1000000 + local t0 = vim.uv.hrtime() + local r = vim.system({ 'sh', '-c', sh }, { text = false }):wait() + local dt = (vim.uv.hrtime() - t0) / 1e6 local ansi = require('cp.ui.ansi') - result.stdout = ansi.bytes_to_string(result.stdout or '') + r.stdout = ansi.bytes_to_string(r.stdout or '') - if result.code == 0 then - logger.log(('Compilation successful in %.1fms.'):format(compile_time), vim.log.levels.INFO) + if r.code == 0 then + logger.log(('Compilation successful in %.1fms.'):format(dt), vim.log.levels.INFO) else - logger.log(('Compilation failed in %.1fms.'):format(compile_time)) + logger.log(('Compilation failed in %.1fms.'):format(dt)) end - return result + return r end ----@param cmd string[] ----@param input_data string ----@param timeout_ms number ----@return ExecuteResult -local function execute_command(cmd, input_data, timeout_ms) - local redirected_cmd = vim.deepcopy(cmd) - if #redirected_cmd > 0 then - redirected_cmd[#redirected_cmd] = redirected_cmd[#redirected_cmd] .. ' 2>&1' +local function parse_and_strip_time_v(output, memory_mb) + local lines = vim.split(output or '', '\n', { plain = true }) + + local timing_idx + for i = #lines, 1, -1 do + if lines[i]:match('^%s*Command being timed:') then + timing_idx = i + break + end end - local start_time = vim.uv.hrtime() + local start_idx = timing_idx + local k = timing_idx - 1 + while k >= 1 and lines[k]:match('^%s*Command ') do + start_idx = k + k = k - 1 + end - local result = vim - .system({ 'sh', '-c', table.concat(redirected_cmd, ' ') }, { - stdin = input_data, + local peak_mb, mled = 0, false + for j = timing_idx, #lines do + local kb = lines[j]:match('Maximum resident set size %(kbytes%):%s*(%d+)') + if kb then + peak_mb = tonumber(kb) / 1024.0 + if memory_mb and memory_mb > 0 and peak_mb > memory_mb then + mled = true + end + end + end + + for j = #lines, start_idx, -1 do + table.remove(lines, j) + end + + while #lines > 0 and lines[#lines]:match('^%s*$') do + table.remove(lines, #lines) + end + + return table.concat(lines, '\n'), peak_mb, mled +end + +function M.run(cmd, stdin, timeout_ms, memory_mb) + local prog = table.concat(cmd, ' ') + local pre = {} + if memory_mb and memory_mb > 0 then + table.insert(pre, ('ulimit -v %d'):format(memory_mb * 1024)) + end + local prefix = (#pre > 0) and (table.concat(pre, '; ') .. '; ') or '' + local time_bin = utils.time_path() + local sh = prefix .. ('%s -v sh -c %q 2>&1'):format(time_bin, prog) + + local t0 = vim.uv.hrtime() + local r = vim + .system({ 'sh', '-c', sh }, { + stdin = stdin, timeout = timeout_ms, text = true, }) :wait() + local dt = (vim.uv.hrtime() - t0) / 1e6 - local end_time = vim.uv.hrtime() - local execution_time = (end_time - start_time) / 1000000 + local code = r.code or 0 + local raw = r.stdout or '' + local cleaned, peak_mb, mled = parse_and_strip_time_v(raw, memory_mb) + local tled = (code == 124) - local actual_code = result.code or 0 + local signal = nil + if code >= 128 then + signal = constants.signal_codes[code] + end - if result.code == 124 then - logger.log(('Execution timed out in %.1fms.'):format(execution_time), vim.log.levels.WARN) - elseif actual_code ~= 0 then - logger.log( - ('Execution failed in %.1fms (exit code %d).'):format(execution_time, actual_code), - vim.log.levels.WARN - ) + if tled then + logger.log(('Execution timed out in %.1fms.'):format(dt), vim.log.levels.WARN) + elseif mled then + logger.log(('Execution memory limit exceeded in %.1fms.'):format(dt)) + elseif code ~= 0 then + logger.log(('Execution failed in %.1fms (exit code %d).'):format(dt, code)) else - logger.log(('Execution successful in %.1fms.'):format(execution_time)) + logger.log(('Execution successful in %.1fms.'):format(dt)) end return { - stdout = result.stdout or '', - code = actual_code, - time_ms = execution_time, - timed_out = result.code == 124, + stdout = cleaned, + code = code, + time_ms = dt, + tled = tled, + mled = mled, + peak_mb = peak_mb, + signal = signal, } end ----@param exec_result ExecuteResult ----@param expected_file string ----@param is_debug boolean ----@return string -local function format_output(exec_result, expected_file, is_debug) - local output_lines = { exec_result.stdout } - local metadata_lines = {} - - if exec_result.timed_out then - table.insert(metadata_lines, '[code]: 124 (TIMEOUT)') - elseif exec_result.code >= 128 then - local signal_name = constants.signal_codes[exec_result.code] or 'SIGNAL' - table.insert(metadata_lines, ('[code]: %d (%s)'):format(exec_result.code, signal_name)) - else - table.insert(metadata_lines, ('[code]: %d'):format(exec_result.code)) - end - - table.insert(metadata_lines, ('[time]: %.2f ms'):format(exec_result.time_ms)) - table.insert(metadata_lines, ('[debug]: %s'):format(is_debug and 'true' or 'false')) - - if vim.fn.filereadable(expected_file) == 1 and exec_result.code == 0 then - local expected_content = vim.fn.readfile(expected_file) - local actual_lines = vim.split(exec_result.stdout, '\n') - - while #actual_lines > 0 and actual_lines[#actual_lines] == '' do - table.remove(actual_lines) - end - - local ok = #actual_lines == #expected_content - if ok then - for i, line in ipairs(actual_lines) do - if line ~= expected_content[i] then - ok = false - break - end - end - end - - table.insert(metadata_lines, ('[ok]: %s'):format(ok and 'true' or 'false')) - end - - return table.concat(output_lines, '') .. '\n' .. table.concat(metadata_lines, '\n') -end - ----@param contest_config ContestConfig ----@param is_debug? boolean ----@return {success: boolean, output: string?} function M.compile_problem(contest_config, is_debug) local state = require('cp.state') local source_file = state.get_source_file() if not source_file then - logger.log('No source file found.', vim.log.levels.ERROR) return { success = false, output = 'No source file found.' } end local language = get_language_from_file(source_file, contest_config) local language_config = contest_config[language] - if not language_config then - logger.log('No configuration for language: ' .. language, vim.log.levels.ERROR) return { success = false, output = ('No configuration for language %s.'):format(language) } end local binary_file = state.get_binary_file() - local substitutions = { - source = source_file, - binary = binary_file, - } + local substitutions = { source = source_file, binary = binary_file } - local compile_cmd = (is_debug and language_config.debug) and language_config.debug + local chosen = (is_debug and language_config.debug) and language_config.debug or language_config.compile - if compile_cmd then - language_config.compile = compile_cmd - local compile_result = M.compile_generic(language_config, substitutions) - if compile_result.code ~= 0 then - return { success = false, output = compile_result.stdout or 'unknown error' } - end + if not chosen then + return { success = true, output = nil } end + local saved = language_config.compile + language_config.compile = chosen + local r = M.compile(language_config, substitutions) + language_config.compile = saved + + if r.code ~= 0 then + return { success = false, output = r.stdout or 'unknown error' } + end return { success = true, output = nil } end ----@param contest_config ContestConfig ----@param is_debug boolean -function M.run_problem(contest_config, is_debug) - local state = require('cp.state') - local source_file = state.get_source_file() - local output_file = state.get_output_file() - - if not source_file or not output_file then - logger.log( - ('Missing required file paths %s and %s'):format(source_file, output_file), - vim.log.levels.ERROR - ) - return - end - - vim.system({ 'mkdir', '-p', 'build', 'io' }):wait() - - local language = get_language_from_file(source_file, contest_config) - local language_config = contest_config[language] - - if not language_config then - vim.fn.writefile({ 'Error: No configuration for language: ' .. language }, output_file) - return - end - - local binary_file = state.get_binary_file() - local substitutions = { - source = source_file, - binary = binary_file, - } - - local compile_cmd = is_debug and language_config.debug or language_config.compile - if compile_cmd then - local compile_result = M.compile_generic(language_config, substitutions) - if compile_result.code ~= 0 then - vim.fn.writefile({ compile_result.stdout }, output_file) - return - end - end - - local input_file = state.get_input_file() - local input_data = '' - if input_file and vim.fn.filereadable(input_file) == 1 then - input_data = table.concat(vim.fn.readfile(input_file), '\n') .. '\n' - end - - local cache = require('cp.cache') - cache.load() - - local platform = state.get_platform() - local contest_id = state.get_contest_id() - local problem_id = state.get_problem_id() - local expected_file = state.get_expected_file() - - if not platform or not contest_id or not expected_file then - logger.log('Configure a contest before running a problem', vim.log.levels.ERROR) - return - end - local timeout_ms, _ = cache.get_constraints(platform, contest_id, problem_id) - timeout_ms = timeout_ms or 2000 - - local run_cmd = build_command(language_config.test, language_config.executable, substitutions) - local exec_result = execute_command(run_cmd, input_data, timeout_ms) - local formatted_output = format_output(exec_result, expected_file, is_debug) - - local output_buf = vim.fn.bufnr(output_file) - if output_buf ~= -1 then - local was_modifiable = vim.api.nvim_get_option_value('modifiable', { buf = output_buf }) - local was_readonly = vim.api.nvim_get_option_value('readonly', { buf = output_buf }) - vim.api.nvim_set_option_value('readonly', false, { buf = output_buf }) - vim.api.nvim_set_option_value('modifiable', true, { buf = output_buf }) - vim.api.nvim_buf_set_lines(output_buf, 0, -1, false, vim.split(formatted_output, '\n')) - vim.api.nvim_set_option_value('modifiable', was_modifiable, { buf = output_buf }) - vim.api.nvim_set_option_value('readonly', was_readonly, { buf = output_buf }) - vim.api.nvim_buf_call(output_buf, function() - vim.cmd.write() - end) - else - vim.fn.writefile(vim.split(formatted_output, '\n'), output_file) - end -end +M._util = { + get_language_from_file = get_language_from_file, + substitute_template = substitute_template, + build_command = build_command, +} return M diff --git a/lua/cp/runner/run.lua b/lua/cp/runner/run.lua index 4588257..fcad160 100644 --- a/lua/cp/runner/run.lua +++ b/lua/cp/runner/run.lua @@ -2,7 +2,7 @@ ---@field index number ---@field input string ---@field expected string ----@field status "pending"|"pass"|"fail"|"running"|"timeout" +---@field status "pending"|"pass"|"fail"|"running"|"tle"|"mle" ---@field actual string? ---@field actual_highlights? Highlight[] ---@field time_ms number? @@ -12,7 +12,8 @@ ---@field code number? ---@field ok boolean? ---@field signal string? ----@field timed_out boolean? +---@field tled boolean? +---@field mled boolean? ---@class ProblemConstraints ---@field timeout_ms number @@ -42,221 +43,149 @@ local run_panel_state = { constraints = nil, } ----@param index number ----@param input string ----@param expected string ----@return RanTestCase -local function create_test_case(index, input, expected) - return { - index = index, - input = input, - expected = expected, - status = 'pending', - actual = nil, - time_ms = nil, - error = nil, - selected = true, - } -end - ----@param platform string ----@param contest_id string ----@param problem_id string? ----@return RanTestCase[] local function parse_test_cases_from_cache(platform, contest_id, problem_id) local cache = require('cp.cache') cache.load() - local cached_test_cases = cache.get_test_cases(platform, contest_id, problem_id) or {} - - if vim.tbl_isempty(cached_test_cases) then - return {} - end - - local test_cases = {} - - for i, test_case in ipairs(cached_test_cases) do - local index = test_case.index or i - local expected = test_case.expected or test_case.output or '' - table.insert(test_cases, create_test_case(index, test_case.input, expected)) - end - - return test_cases + return cache.get_test_cases(platform, contest_id, problem_id) or {} end ----@param platform string ----@param contest_id string ----@param problem_id string? ----@return ProblemConstraints? local function load_constraints_from_cache(platform, contest_id, problem_id) local cache = require('cp.cache') cache.load() local timeout_ms, memory_mb = cache.get_constraints(platform, contest_id, problem_id) - if timeout_ms and memory_mb then - return { - timeout_ms = timeout_ms, - memory_mb = memory_mb, - } + return { timeout_ms = timeout_ms, memory_mb = memory_mb } end - return nil end ----@param contest_config ContestConfig ----@param test_case RanTestCase ----@return table +local function create_sentinal_panel_data(test_cases) + local out = {} + for i, tc in ipairs(test_cases) do + out[i] = { + index = tc.index or i, + input = tc.input or '', + expected = tc.expected or '', + status = 'pending', + selected = false, + } + end + return out +end + +local function build_command(language_config, substitutions) + local exec_util = require('cp.runner.execute')._util + return exec_util.build_command(language_config.test, language_config.executable, substitutions) +end + local function run_single_test_case(contest_config, cp_config, test_case) local state = require('cp.state') + local exec = require('cp.runner.execute') + local source_file = state.get_source_file() - - local language = vim.fn.fnamemodify(source_file or '', ':e') - local language_name = constants.filetype_to_language[language] or contest_config.default_language - local language_config = contest_config[language_name] - - local function substitute_template(cmd_template, substitutions) - local result = {} - for _, arg in ipairs(cmd_template) do - local substituted = arg - for key, value in pairs(substitutions) do - substituted = substituted:gsub('{' .. key .. '}', value) - end - table.insert(result, substituted) - end - return result - end - - local function build_command(cmd_template, executable, substitutions) - local cmd = substitute_template(cmd_template, substitutions) - if executable then - table.insert(cmd, 1, executable) - end - return cmd - end + local ext = vim.fn.fnamemodify(source_file or '', ':e') + local lang_name = constants.filetype_to_language[ext] or contest_config.default_language + local language_config = contest_config[lang_name] local binary_file = state.get_binary_file() - local substitutions = { - source = source_file, - binary = binary_file, - } + local substitutions = { source = source_file, binary = binary_file } if language_config.compile and binary_file and vim.fn.filereadable(binary_file) == 0 then - logger.log('Binary not found - compiling first.') - local compile_cmd = substitute_template(language_config.compile, substitutions) - local redirected_cmd = vim.deepcopy(compile_cmd) - redirected_cmd[#redirected_cmd] = redirected_cmd[#redirected_cmd] .. ' 2>&1' - local compile_result = vim - .system({ 'sh', '-c', table.concat(redirected_cmd, ' ') }, { text = false }) - :wait() - + local cr = exec.compile(language_config, substitutions) local ansi = require('cp.ui.ansi') - compile_result.stdout = ansi.bytes_to_string(compile_result.stdout or '') - compile_result.stderr = ansi.bytes_to_string(compile_result.stderr or '') - - if compile_result.code ~= 0 then + local clean = ansi.bytes_to_string(cr.stdout or '') + if cr.code ~= 0 then return { status = 'fail', - actual = '', - error = 'Compilation failed: ' .. (compile_result.stdout or 'Unknown error'), - stderr = compile_result.stdout or '', + actual = clean, + actual_highlights = {}, + error = 'Compilation failed', + stderr = clean, time_ms = 0, - code = compile_result.code, + code = cr.code, ok = false, signal = nil, - timed_out = false, - actual_highlights = {}, + tled = false, + mled = false, } end end - local run_cmd = build_command(language_config.test, language_config.executable, substitutions) + local cmd = build_command(language_config, substitutions) + local stdin_content = (test_case.input or '') .. '\n' + local timeout_ms = (run_panel_state.constraints and run_panel_state.constraints.timeout_ms) + or 2000 + local memory_mb = run_panel_state.constraints and run_panel_state.constraints.memory_mb or nil - local stdin_content = test_case.input .. '\n' - - local start_time = vim.uv.hrtime() - local timeout_ms = run_panel_state.constraints and run_panel_state.constraints.timeout_ms or 2000 - - local redirected_run_cmd = vim.deepcopy(run_cmd) - redirected_run_cmd[#redirected_run_cmd] = redirected_run_cmd[#redirected_run_cmd] .. ' 2>&1' - local result = vim - .system({ 'sh', '-c', table.concat(redirected_run_cmd, ' ') }, { - stdin = stdin_content, - timeout = timeout_ms, - text = false, - }) - :wait() - local execution_time = (vim.uv.hrtime() - start_time) / 1000000 + local r = exec.run(cmd, stdin_content, timeout_ms, memory_mb) local ansi = require('cp.ui.ansi') - local stdout_str = ansi.bytes_to_string(result.stdout or '') - local actual_output = stdout_str:gsub('\n$', '') + local out = (r.stdout or ''):gsub('\n$', '') - local actual_highlights = {} - - if actual_output ~= '' then + local highlights = {} + if out ~= '' then if cp_config.run_panel.ansi then - local parsed = ansi.parse_ansi_text(actual_output) - actual_output = table.concat(parsed.lines, '\n') - actual_highlights = parsed.highlights + local parsed = ansi.parse_ansi_text(out) + out = table.concat(parsed.lines, '\n') + highlights = parsed.highlights else - actual_output = actual_output:gsub('\027%[[%d;]*[a-zA-Z]', '') + out = out:gsub('\027%[[%d;]*[a-zA-Z]', '') end end local max_lines = cp_config.run_panel.max_output_lines - local output_lines = vim.split(actual_output, '\n') - if #output_lines > max_lines then - local trimmed_lines = {} + local lines = vim.split(out, '\n') + if #lines > max_lines then + local trimmed = {} for i = 1, max_lines do - table.insert(trimmed_lines, output_lines[i]) + table.insert(trimmed, lines[i]) end - table.insert(trimmed_lines, string.format('... (output trimmed after %d lines)', max_lines)) - actual_output = table.concat(trimmed_lines, '\n') + table.insert(trimmed, string.format('... (output trimmed after %d lines)', max_lines)) + out = table.concat(trimmed, '\n') end - local expected_output = test_case.expected:gsub('\n$', '') - local ok = actual_output == expected_output + local expected = (test_case.expected or ''):gsub('\n$', '') + local ok = out == expected + + local signal = r.signal + if not signal and r.code and r.code >= 128 then + signal = constants.signal_codes[r.code] + end local status - local timed_out = result.code == 143 or result.code == 124 - if timed_out then - status = 'timeout' - elseif result.code == 0 and ok then + if r.tled then + status = 'tle' + elseif r.mled then + status = 'mle' + elseif ok then status = 'pass' else status = 'fail' end - local signal = nil - if result.code >= 128 then - signal = constants.signal_codes[result.code] - end - return { status = status, - actual = actual_output, - actual_highlights = actual_highlights, - error = result.code ~= 0 and actual_output or nil, + actual = out, + actual_highlights = highlights, + error = (r.code ~= 0 and not ok) and out or nil, stderr = '', - time_ms = execution_time, - code = result.code, + time_ms = r.time_ms, + code = r.code, ok = ok, signal = signal, - timed_out = timed_out, + tled = r.tled or false, + mled = r.mled or false, } end ----@param state table ----@return boolean function M.load_test_cases(state) - local test_cases = parse_test_cases_from_cache( + local tcs = parse_test_cases_from_cache( state.get_platform() or '', state.get_contest_id() or '', state.get_problem_id() - ) or {} + ) - -- TODO: re-fetch/cache-populating mechanism to ge the test cases if not in the cache - - run_panel_state.test_cases = test_cases + run_panel_state.test_cases = create_sentinal_panel_data(tcs) run_panel_state.current_index = 1 run_panel_state.constraints = load_constraints_from_cache( state.get_platform() or '', @@ -264,50 +193,43 @@ function M.load_test_cases(state) state.get_problem_id() ) - logger.log(('Loaded %d test case(s)'):format(#test_cases), vim.log.levels.INFO) - return #test_cases > 0 + logger.log(('Loaded %d test case(s)'):format(#tcs), vim.log.levels.INFO) + return #tcs > 0 end ----@param contest_config ContestConfig ----@param index number ----@return boolean function M.run_test_case(contest_config, cp_config, index) - local test_case = run_panel_state.test_cases[index] - if not test_case then + local tc = run_panel_state.test_cases[index] + if not tc then return false end - test_case.status = 'running' + tc.status = 'running' + local r = run_single_test_case(contest_config, cp_config, tc) - local result = run_single_test_case(contest_config, cp_config, test_case) - - test_case.status = result.status - test_case.actual = result.actual - test_case.actual_highlights = result.actual_highlights - test_case.error = result.error - test_case.stderr = result.stderr - test_case.time_ms = result.time_ms - test_case.code = result.code - test_case.ok = result.ok - test_case.signal = result.signal - test_case.timed_out = result.timed_out + tc.status = r.status + tc.actual = r.actual + tc.actual_highlights = r.actual_highlights + tc.error = r.error + tc.stderr = r.stderr + tc.time_ms = r.time_ms + tc.code = r.code + tc.ok = r.ok + tc.signal = r.signal + tc.tled = r.tled + tc.mled = r.mled return true end ----@param contest_config ContestConfig ----@param cp_config cp.Config ----@return RanTestCase[] function M.run_all_test_cases(contest_config, cp_config) local results = {} - for i, _ in ipairs(run_panel_state.test_cases) do + for i = 1, #run_panel_state.test_cases do M.run_test_case(contest_config, cp_config, i) - table.insert(results, run_panel_state.test_cases[i]) + results[i] = run_panel_state.test_cases[i] end return results end ----@return RunPanelState function M.get_run_panel_state() return run_panel_state end @@ -316,28 +238,29 @@ function M.handle_compilation_failure(compilation_output) local ansi = require('cp.ui.ansi') local config = require('cp.config').setup() - local clean_text - local highlights = {} + local txt + local hl = {} if config.run_panel.ansi then - local parsed = ansi.parse_ansi_text(compilation_output or '') - clean_text = table.concat(parsed.lines, '\n') - highlights = parsed.highlights + local p = ansi.parse_ansi_text(compilation_output or '') + txt = table.concat(p.lines, '\n') + hl = p.highlights else - clean_text = (compilation_output or ''):gsub('\027%[[%d;]*[a-zA-Z]', '') + txt = (compilation_output or ''):gsub('\027%[[%d;]*[a-zA-Z]', '') end - for _, test_case in ipairs(run_panel_state.test_cases) do - test_case.status = 'fail' - test_case.actual = clean_text - test_case.actual_highlights = highlights - test_case.error = 'Compilation failed' - test_case.stderr = '' - test_case.time_ms = 0 - test_case.code = 1 - test_case.ok = false - test_case.signal = nil - test_case.timed_out = false + for _, tc in ipairs(run_panel_state.test_cases) do + tc.status = 'fail' + tc.actual = txt + tc.actual_highlights = hl + tc.error = 'Compilation failed' + tc.stderr = '' + tc.time_ms = 0 + tc.code = 1 + tc.ok = false + tc.signal = nil + tc.tled = false + tc.mled = false end end diff --git a/lua/cp/runner/run_render.lua b/lua/cp/runner/run_render.lua index 99fbcbe..324c359 100644 --- a/lua/cp/runner/run_render.lua +++ b/lua/cp/runner/run_render.lua @@ -26,22 +26,22 @@ local exit_code_names = { ---@param ran_test_case RanTestCase ---@return StatusInfo function M.get_status_info(ran_test_case) - if ran_test_case.status == 'pass' then + if ran_test_case.ok then return { text = 'AC', highlight_group = 'CpTestAC' } - elseif ran_test_case.status == 'fail' then - if ran_test_case.timed_out then - return { text = 'TLE', highlight_group = 'CpTestTLE' } - elseif ran_test_case.code and ran_test_case.code >= 128 then - return { text = 'RTE', highlight_group = 'CpTestRTE' } - else - return { text = 'WA', highlight_group = 'CpTestWA' } - end - elseif ran_test_case.status == 'timeout' then - return { text = 'TLE', highlight_group = 'CpTestTLE' } - elseif ran_test_case.status == 'running' then + end + + if ran_test_case.actual == '' then return { text = '...', highlight_group = 'CpTestPending' } + end + + if ran_test_case.tled then + return { text = 'TLE', highlight_group = 'CpTestTLE' } + elseif ran_test_case.mled then + return { text = 'MLE', highlight_group = 'CpTestMLE' } + elseif ran_test_case.code and ran_test_case.code >= 128 then + return { text = 'RTE', highlight_group = 'CpTestRTE' } else - return { text = '', highlight_group = 'CpTestPending' } + return { text = 'WA', highlight_group = 'CpTestWA' } end end @@ -354,6 +354,7 @@ function M.get_highlight_groups() CpTestAC = { fg = '#10b981' }, CpTestWA = { fg = '#ef4444' }, CpTestTLE = { fg = '#f59e0b' }, + CpTestMLE = { fg = '#f59e0b' }, CpTestRTE = { fg = '#8b5cf6' }, CpTestPending = { fg = '#6b7280' }, CpDiffRemoved = { fg = '#ef4444', bg = '#1f1f1f' }, diff --git a/lua/cp/ui/layouts.lua b/lua/cp/ui/layouts.lua index f3d6dd3..84d667a 100644 --- a/lua/cp/ui/layouts.lua +++ b/lua/cp/ui/layouts.lua @@ -1,10 +1,10 @@ local M = {} -local buffer_utils = require('cp.utils.buffer') +local utils = require('cp.utils') local function create_none_diff_layout(parent_win, expected_content, actual_content) - local expected_buf = buffer_utils.create_buffer_with_options() - local actual_buf = buffer_utils.create_buffer_with_options() + local expected_buf = utils.create_buffer_with_options() + local actual_buf = utils.create_buffer_with_options() vim.api.nvim_set_current_win(parent_win) vim.cmd.split() @@ -24,8 +24,8 @@ local function create_none_diff_layout(parent_win, expected_content, actual_cont local expected_lines = vim.split(expected_content, '\n', { plain = true, trimempty = true }) local actual_lines = vim.split(actual_content, '\n', { plain = true, trimempty = true }) - buffer_utils.update_buffer_content(expected_buf, expected_lines, {}) - buffer_utils.update_buffer_content(actual_buf, actual_lines, {}) + utils.update_buffer_content(expected_buf, expected_lines, {}) + utils.update_buffer_content(actual_buf, actual_lines, {}) return { buffers = { expected_buf, actual_buf }, @@ -40,8 +40,8 @@ local function create_none_diff_layout(parent_win, expected_content, actual_cont end local function create_vim_diff_layout(parent_win, expected_content, actual_content) - local expected_buf = buffer_utils.create_buffer_with_options() - local actual_buf = buffer_utils.create_buffer_with_options() + local expected_buf = utils.create_buffer_with_options() + local actual_buf = utils.create_buffer_with_options() vim.api.nvim_set_current_win(parent_win) vim.cmd.split() @@ -61,8 +61,8 @@ local function create_vim_diff_layout(parent_win, expected_content, actual_conte local expected_lines = vim.split(expected_content, '\n', { plain = true, trimempty = true }) local actual_lines = vim.split(actual_content, '\n', { plain = true, trimempty = true }) - buffer_utils.update_buffer_content(expected_buf, expected_lines, {}) - buffer_utils.update_buffer_content(actual_buf, actual_lines, {}) + utils.update_buffer_content(expected_buf, expected_lines, {}) + utils.update_buffer_content(actual_buf, actual_lines, {}) vim.api.nvim_set_option_value('diff', true, { win = expected_win }) vim.api.nvim_set_option_value('diff', true, { win = actual_win }) @@ -88,7 +88,7 @@ local function create_vim_diff_layout(parent_win, expected_content, actual_conte end local function create_git_diff_layout(parent_win, expected_content, actual_content) - local diff_buf = buffer_utils.create_buffer_with_options() + local diff_buf = utils.create_buffer_with_options() vim.api.nvim_set_current_win(parent_win) vim.cmd.split() @@ -109,7 +109,7 @@ local function create_git_diff_layout(parent_win, expected_content, actual_conte highlight.parse_and_apply_diff(diff_buf, diff_result.raw_diff, diff_namespace) else local lines = vim.split(actual_content, '\n', { plain = true, trimempty = true }) - buffer_utils.update_buffer_content(diff_buf, lines, {}) + utils.update_buffer_content(diff_buf, lines, {}) end return { @@ -123,9 +123,9 @@ local function create_git_diff_layout(parent_win, expected_content, actual_conte end local function create_single_layout(parent_win, content) - local buf = buffer_utils.create_buffer_with_options() + local buf = utils.create_buffer_with_options() local lines = vim.split(content, '\n', { plain = true, trimempty = true }) - buffer_utils.update_buffer_content(buf, lines, {}) + utils.update_buffer_content(buf, lines, {}) vim.api.nvim_set_current_win(parent_win) vim.cmd.split() @@ -219,7 +219,7 @@ function M.update_diff_panes( else if desired_mode == 'single' then local lines = vim.split(actual_content, '\n', { plain = true, trimempty = true }) - buffer_utils.update_buffer_content( + utils.update_buffer_content( current_diff_layout.buffers[1], lines, actual_highlights, @@ -238,7 +238,7 @@ function M.update_diff_panes( ) else local lines = vim.split(actual_content, '\n', { plain = true, trimempty = true }) - buffer_utils.update_buffer_content( + utils.update_buffer_content( current_diff_layout.buffers[1], lines, actual_highlights, @@ -248,8 +248,8 @@ function M.update_diff_panes( elseif desired_mode == 'none' then local expected_lines = vim.split(expected_content, '\n', { plain = true, trimempty = true }) local actual_lines = vim.split(actual_content, '\n', { plain = true, trimempty = true }) - buffer_utils.update_buffer_content(current_diff_layout.buffers[1], expected_lines, {}) - buffer_utils.update_buffer_content( + utils.update_buffer_content(current_diff_layout.buffers[1], expected_lines, {}) + utils.update_buffer_content( current_diff_layout.buffers[2], actual_lines, actual_highlights, @@ -258,8 +258,8 @@ function M.update_diff_panes( else local expected_lines = vim.split(expected_content, '\n', { plain = true, trimempty = true }) local actual_lines = vim.split(actual_content, '\n', { plain = true, trimempty = true }) - buffer_utils.update_buffer_content(current_diff_layout.buffers[1], expected_lines, {}) - buffer_utils.update_buffer_content( + utils.update_buffer_content(current_diff_layout.buffers[1], expected_lines, {}) + utils.update_buffer_content( current_diff_layout.buffers[2], actual_lines, actual_highlights, diff --git a/lua/cp/ui/panel.lua b/lua/cp/ui/panel.lua index f9accc7..02d339c 100644 --- a/lua/cp/ui/panel.lua +++ b/lua/cp/ui/panel.lua @@ -1,10 +1,10 @@ local M = {} -local buffer_utils = require('cp.utils.buffer') local config_module = require('cp.config') local layouts = require('cp.ui.layouts') local logger = require('cp.log') local state = require('cp.state') +local utils = require('cp.utils') local current_diff_layout = nil local current_mode = nil @@ -194,7 +194,7 @@ function M.toggle_run_panel(is_debug) vim.cmd(('mksession! %s'):format(state.saved_session)) vim.cmd('silent only') - local tab_buf = buffer_utils.create_buffer_with_options() + local tab_buf = utils.create_buffer_with_options() local main_win = vim.api.nvim_get_current_win() vim.api.nvim_win_set_buf(main_win, tab_buf) vim.api.nvim_set_option_value('filetype', 'cptest', { buf = tab_buf }) @@ -224,7 +224,7 @@ function M.toggle_run_panel(is_debug) run_render.setup_highlights() local test_state = run.get_run_panel_state() local tab_lines, tab_highlights = run_render.render_test_list(test_state) - buffer_utils.update_buffer_content( + utils.update_buffer_content( test_buffers.tab_buf, tab_lines, tab_highlights, diff --git a/lua/cp/utils.lua b/lua/cp/utils.lua index ff97a11..60c23d8 100644 --- a/lua/cp/utils.lua +++ b/lua/cp/utils.lua @@ -2,6 +2,76 @@ local M = {} local logger = require('cp.log') +local uname = vim.loop.os_uname() + +local _time_cached = false +local _time_path = nil +local _time_reason = nil + +local function is_windows() + return uname and uname.sysname == 'Windows_NT' +end + +local function check_time_is_gnu_time(bin) + local ok = vim.fn.executable(bin) == 1 + if not ok then + return false + end + local r = vim.system({ bin, '--version' }, { text = true }):wait() + if r and r.code == 0 and r.stdout and r.stdout:lower():find('gnu time', 1, true) then + return true + end + return false +end + +local function find_gnu_time() + if _time_cached then + return _time_path, _time_reason + end + + if is_windows() then + _time_cached = true + _time_path = nil + _time_reason = 'unsupported on Windows' + return _time_path, _time_reason + end + + local candidates + if uname and uname.sysname == 'Darwin' then + candidates = { 'gtime', '/opt/homebrew/bin/gtime', '/usr/local/bin/gtime' } + else + candidates = { '/usr/bin/time', 'time' } + end + + for _, bin in ipairs(candidates) do + if check_time_is_gnu_time(bin) then + _time_cached = true + _time_path = bin + _time_reason = nil + return _time_path, _time_reason + end + end + + _time_cached = true + _time_path = nil + _time_reason = 'GNU time not found (install `time` on Linux or `brew install coreutils` on macOS)' + return _time_path, _time_reason +end + +--- Return the validated GNU time binary path +--- Fails closed: returns nil if GNU time is unavailable. +---@return string|nil path +function M.time_path() + local path = find_gnu_time() + return path +end + +---@return {ok:boolean, path:string|nil, reason:string|nil} +function M.time_capability() + local path, reason = find_gnu_time() + return { ok = path ~= nil, path = path, reason = reason } +end + ---@return string function M.get_plugin_path() local plugin_path = debug.getinfo(1, 'S').source:sub(2) @@ -28,17 +98,45 @@ function M.setup_python_env() end if vim.fn.isdirectory(venv_dir) == 0 then - logger.log('setting up Python environment for scrapers...') + logger.log('Setting up Python environment for scrapers...') local result = vim.system({ 'uv', 'sync' }, { cwd = plugin_path, text = true }):wait() if result.code ~= 0 then - logger.log('failed to setup Python environment: ' .. result.stderr, vim.log.levels.ERROR) + logger.log('Failed to setup Python environment: ' .. result.stderr, vim.log.levels.ERROR) return false end - logger.log('Python environment setup complete') + logger.log('Python environment setup complete.') end python_env_setup = true return true end +--- Configure the buffer with good defaults +---@param filetype? string +function M.create_buffer_with_options(filetype) + local buf = vim.api.nvim_create_buf(false, true) + vim.api.nvim_set_option_value('bufhidden', 'wipe', { buf = buf }) + vim.api.nvim_set_option_value('readonly', true, { buf = buf }) + vim.api.nvim_set_option_value('modifiable', false, { buf = buf }) + if filetype then + vim.api.nvim_set_option_value('filetype', filetype, { buf = buf }) + end + return buf +end + +function M.update_buffer_content(bufnr, lines, highlights, namespace) + local was_readonly = vim.api.nvim_get_option_value('readonly', { buf = bufnr }) + + vim.api.nvim_set_option_value('readonly', false, { buf = bufnr }) + vim.api.nvim_set_option_value('modifiable', true, { buf = bufnr }) + vim.api.nvim_buf_set_lines(bufnr, 0, -1, false, lines) + vim.api.nvim_set_option_value('modifiable', false, { buf = bufnr }) + vim.api.nvim_set_option_value('readonly', was_readonly, { buf = bufnr }) + + if highlights and namespace then + local highlight = require('cp.ui.highlight') + highlight.apply_highlights(bufnr, highlights, namespace) + end +end + return M diff --git a/lua/cp/utils/buffer.lua b/lua/cp/utils/buffer.lua deleted file mode 100644 index 55a4070..0000000 --- a/lua/cp/utils/buffer.lua +++ /dev/null @@ -1,31 +0,0 @@ -local M = {} - ---- Configure the buffer with good defaults ----@param filetype? string -function M.create_buffer_with_options(filetype) - local buf = vim.api.nvim_create_buf(false, true) - vim.api.nvim_set_option_value('bufhidden', 'wipe', { buf = buf }) - vim.api.nvim_set_option_value('readonly', true, { buf = buf }) - vim.api.nvim_set_option_value('modifiable', false, { buf = buf }) - if filetype then - vim.api.nvim_set_option_value('filetype', filetype, { buf = buf }) - end - return buf -end - -function M.update_buffer_content(bufnr, lines, highlights, namespace) - local was_readonly = vim.api.nvim_get_option_value('readonly', { buf = bufnr }) - - vim.api.nvim_set_option_value('readonly', false, { buf = bufnr }) - vim.api.nvim_set_option_value('modifiable', true, { buf = bufnr }) - vim.api.nvim_buf_set_lines(bufnr, 0, -1, false, lines) - vim.api.nvim_set_option_value('modifiable', false, { buf = bufnr }) - vim.api.nvim_set_option_value('readonly', was_readonly, { buf = bufnr }) - - if highlights and namespace then - local highlight = require('cp.ui.highlight') - highlight.apply_highlights(bufnr, highlights, namespace) - end -end - -return M