From fb10b4906aadaeff295883d171c05246943e5571 Mon Sep 17 00:00:00 2001 From: Hennadii Chernyshchyk Date: Sat, 10 Sep 2022 14:05:32 +0300 Subject: Initial commit --- lua/tasks/config.lua | 32 +++++ lua/tasks/constants.lua | 5 + lua/tasks/init.lua | 142 ++++++++++++++++++++++ lua/tasks/module/cargo.lua | 171 +++++++++++++++++++++++++++ lua/tasks/module/cmake.lua | 272 +++++++++++++++++++++++++++++++++++++++++++ lua/tasks/project_config.lua | 29 +++++ lua/tasks/runner.lua | 226 +++++++++++++++++++++++++++++++++++ lua/tasks/subcommands.lua | 79 +++++++++++++ lua/tasks/utils.lua | 100 ++++++++++++++++ 9 files changed, 1056 insertions(+) create mode 100644 lua/tasks/config.lua create mode 100644 lua/tasks/constants.lua create mode 100644 lua/tasks/init.lua create mode 100644 lua/tasks/module/cargo.lua create mode 100644 lua/tasks/module/cmake.lua create mode 100644 lua/tasks/project_config.lua create mode 100644 lua/tasks/runner.lua create mode 100644 lua/tasks/subcommands.lua create mode 100644 lua/tasks/utils.lua (limited to 'lua/tasks') diff --git a/lua/tasks/config.lua b/lua/tasks/config.lua new file mode 100644 index 0000000..0d5da61 --- /dev/null +++ b/lua/tasks/config.lua @@ -0,0 +1,32 @@ +local Path = require('plenary.path') + +local config = { + defaults = { + default_params = { + cmake = { + cmd = 'cmake', + build_dir = tostring(Path:new('{cwd}', 'build', '{os}-{build_type}')), + build_type = 'Debug', + dap_name = 'lldb', + args = { + configure = { '-D', 'CMAKE_EXPORT_COMPILE_COMMANDS=1', '-G', 'Ninja' }, + }, + }, + cargo = { + dap_name = 'lldb', + }, + }, + save_before_run = true, + params_file = 'neovim.json', + quickfix = { + pos = 'botright', + height = 12, + only_on_error = false, + }, + dap_open_command = function() return require('dap').repl.open() end, + }, +} + +setmetatable(config, { __index = config.defaults }) + +return config diff --git a/lua/tasks/constants.lua b/lua/tasks/constants.lua new file mode 100644 index 0000000..4e236b2 --- /dev/null +++ b/lua/tasks/constants.lua @@ -0,0 +1,5 @@ +local constants = { + task_params = { 'args', 'env' }, -- Parameters available for all tasks +} + +return constants diff --git a/lua/tasks/init.lua b/lua/tasks/init.lua new file mode 100644 index 0000000..4b6c893 --- /dev/null +++ b/lua/tasks/init.lua @@ -0,0 +1,142 @@ +local config = require('tasks.config') +local runner = require('tasks.runner') +local constants = require('tasks.constants') +local utils = require('tasks.utils') +local ProjectConfig = require('tasks.project_config') +local tasks = {} + +--- Apply user settings. +---@param values table +function tasks.setup(values) setmetatable(config, { __index = vim.tbl_deep_extend('force', config.defaults, values) }) end + +--- Execute a task from a module. +---@param module_type string: Name of a module or `auto` string to pick a first module that match a condition. +---@param task_name string +---@vararg string additional arguments that will be passed to the last task. +function tasks.start(module_type, task_name, ...) + local current_job_name = runner.get_current_job_name() + if current_job_name then + utils.notify(string.format('Another job is currently running: "%s"', current_job_name), vim.log.levels.ERROR) + return + end + + local module, module_name = utils.get_module(module_type) + if not module then + return + end + + local commands = module.tasks[task_name] + if not commands then + utils.notify(string.format('Unable to find a task named "%s" in module "%s"', task_name, module_name), vim.log.levels.ERROR) + return + end + + if config.save_before_run then + vim.api.nvim_command('silent! wall') + end + + local project_config = ProjectConfig.new() + local module_config = project_config[module_name] + if not vim.tbl_islist(commands) then + commands = { commands } + end + runner.chain_commands(task_name, commands, module_config, { ... }) +end + +--- Set a module-specific parameter. Settings will be stored on disk. +---@param module_type string: Name of a module or `auto` string to pick a first module that match a condition. +---@param param_name string +function tasks.set_module_param(module_type, param_name) + local module, module_name = utils.get_module(module_type) + if not module then + return + end + + if not module then + return + end + + local project_config = ProjectConfig.new() + local current_value = vim.tbl_get(project_config, module_name, param_name) + + local param = module.params[param_name] + if not param then + if vim.tbl_contains(module.params, param_name) then + -- Contains a string without a value, request for input + vim.ui.input({ prompt = string.format('Set "%s" for module "%s"', param_name, module_name), default = current_value }, function(input) + project_config[module_name][param_name] = input + project_config:write() + end) + else + utils.notify(string.format('No such parameter "%s" for module "%s"', param_name, module_name), vim.log.levels.ERROR) + end + return + end + + if vim.is_callable(param) then + param = param() + if not param then + return + end + end + + -- Put current value first + if current_value then + for index, value in ipairs(param) do + if value == current_value then + table.remove(param, index) + break + end + end + table.insert(param, 1, current_value) + end + + vim.ui.select(param, { prompt = string.format('Select "%s"', param_name) }, function(choice, idx) + if not idx then + return + end + if not project_config[module_name] then + project_config[module_name] = {} + end + project_config[module_name][param_name] = choice + project_config:write() + end) +end + +--- Set a parameter for a module task. Settings will be stored on disk. +---@param module_type string: Name of a module or `auto` string to pick a first module that match a condition. +---@param task_name string +---@param param_name string +function tasks.set_task_param(module_type, task_name, param_name) + local module, module_name = utils.get_module(module_type) + if not module then + return + end + if not vim.tbl_contains(constants.task_params, param_name) then + utils.notify(string.format('Unknown task parameter "%s"\nAvailable task parameters: %s', param_name, table.concat(constants.task_params, ', ')), vim.log.levels.ERROR) + return + end + + local project_config = ProjectConfig.new() + local current_value = vim.tbl_get(project_config, module_name, param_name, task_name) + current_value = current_value and utils.join_args(current_value) or '' + vim.ui.input({ prompt = string.format('Set "%s" for task "%s" from module "%s": ', param_name, task_name, module_name), default = current_value, completion = 'file' }, function(input) + if not project_config[module_name] then + project_config[module_name] = {} + end + if not project_config[module_name][param_name] then + project_config[module_name][param_name] = {} + end + project_config[module_name][param_name][task_name] = utils.split_args(input) + project_config:write() + end) +end + +--- Cancel last current task. +function tasks.cancel() + if not runner.cancel_job() then + utils.notify('No running process') + end +end + +return tasks diff --git a/lua/tasks/module/cargo.lua b/lua/tasks/module/cargo.lua new file mode 100644 index 0000000..3e21371 --- /dev/null +++ b/lua/tasks/module/cargo.lua @@ -0,0 +1,171 @@ +local utils = require('tasks.utils') +local Job = require('plenary.job') +local Path = require('plenary.path') +local cargo = {} + +-- Modified version of `errorformat` from the official Rust plugin for Vim: +-- https://github.com/rust-lang/rust.vim/blob/4aa69b84c8a58fcec6b6dad6fe244b916b1cf830/compiler/rustc.vim#L32 +-- https://github.com/rust-lang/rust.vim/blob/4aa69b84c8a58fcec6b6dad6fe244b916b1cf830/compiler/cargo.vim#L35 +-- We display all lines (not only error messages) since we show output in quickfix. +-- Zero-width look-ahead regex is used to avoid marking general messages as errors: %\%%(ignored text%\)%\@!. +local errorformat = [[%Eerror: %\%%(aborting %\|could not compile%\)%\@!%m,]] + .. [[%Eerror[E%n]: %m,]] + .. [[%Inote: %m,]] + .. [[%Wwarning: %\%%(%.%# warning%\)%\@!%m,]] + .. [[%C %#--> %f:%l:%c,]] + .. [[%E left:%m,%C right:%m %f:%l:%c,%Z,]] + .. [[%.%#panicked at \'%m\'\, %f:%l:%c]] + +--- Detects package name from command line arguments. +---@param args table +---@return string? +local function detect_package_name(args) + for index, value in ipairs(args) do + if value == '-p' or value == '--package' or value == '--bin' then + return args[index + 1] + end + end + return nil +end + +--- Returns only a packages that can be executed. +---@param packages table: Packages to filter. +---@return table +local function find_executable_packages(packages) + local executables = {} + for _, line in pairs(packages) do + local package = vim.json.decode(line) + if package.executable and package.executable ~= vim.NIL then + table.insert(executables, package) + end + end + return executables +end + +--- Finds executable package name from a list of packages. +---@param packages table +---@param args table?: Command line arguments that will be used to detect an executable if JSON message from cargo is missing this info. +---@return table? +local function get_executable_package(packages, args) + local executable_packages = find_executable_packages(packages) + if #executable_packages == 1 then + return executable_packages[1] + end + + -- Try to detect package name from arguments + local package_name = detect_package_name(args or {}) + if not package_name then + local available_names = {} + for _, package in ipairs(executable_packages) do + table.insert(available_names, package.target.name) + end + utils.notify( + 'Could not determine which binary to run\nUse the "--bin" or "--package" option to specify a binary\nAvailable binaries: ' .. table.concat(available_names, ', '), + vim.log.levels.ERROR + ) + return nil + end + + for _, package in ipairs(executable_packages) do + if package.target.name == package_name then + return package + end + end + + utils.notify(string.format('Unable to find package named "%s"', package_name), vim.log.levels.ERROR) + return nil +end + +---@return table: List of functions for each cargo subcommand that return a task table. +local function get_cargo_subcommands() + local cargo_subcommands = {} + + local job = Job:new({ + command = 'cargo', + args = { '--list' }, + enabled_recording = true, + }) + job:sync() + + if job.code ~= 0 or job.signal ~= 0 then + utils.notify('Unable to get list of available cargo subcommands', vim.log.levels.ERROR) + return {} + end + + local start_offset = 5 + for index, line in ipairs(job:result()) do + if index ~= 1 and not line:find('alias:') then + local subcommand_end = line:find(' ', start_offset) + local subcommand = line:sub(start_offset, subcommand_end and subcommand_end - 1 or nil) + cargo_subcommands[subcommand] = + function(module_config, _) return { cmd = 'cargo', args = vim.list_extend({ subcommand }, utils.split_args(module_config.global_cargo_args)), errorformat = errorformat } end + end + end + + return cargo_subcommands +end + +--- Task +---@return table? +local function build_test(module_config, _) + return { + cmd = 'cargo', + args = vim.list_extend({ 'test', '--no-run', '--message-format=json' }, utils.split_args(module_config.global_cargo_args)), + errorformat = errorformat, + ignore_stdout = true, + } +end + +--- Task +---@param module_config table +---@param previous_job table +---@return table? +local function debug_test(module_config, previous_job) + local package = get_executable_package(previous_job:result(), vim.tbl_get(module_config, 'args', 'debug_test')) + if not package then + return + end + + return { + cmd = package.executable, + dap_name = module_config.dap_name, + errorformat = errorformat, + } +end + +--- Task +---@param module_config table +---@return table? +local function build(module_config, _) + return { + cmd = 'cargo', + args = vim.list_extend({ 'build', '--message-format=json' }, utils.split_args(module_config.global_cargo_args)), + ignore_stdout = true, + } +end + +--- Task +---@param module_config table +---@param previous_job table +---@return table? +local function debug(module_config, previous_job) + local package = get_executable_package(previous_job:result(), vim.tbl_get(module_config, 'args', 'debug')) + if not package then + return + end + + return { + cmd = package.executable, + dap_name = module_config.dap_name, + errorformat = errorformat, + } +end + +cargo.params = { + 'dap_name', + 'global_cargo_args', +} +cargo.condition = function() return Path:new('Cargo.toml'):exists() end +cargo.tasks = vim.tbl_extend('force', get_cargo_subcommands(), { debug_test = { build_test, debug_test }, debug = { build, debug } }) + +return cargo diff --git a/lua/tasks/module/cmake.lua b/lua/tasks/module/cmake.lua new file mode 100644 index 0000000..4900aec --- /dev/null +++ b/lua/tasks/module/cmake.lua @@ -0,0 +1,272 @@ +local Path = require('plenary.path') +local utils = require('tasks.utils') +local scandir = require('plenary.scandir') +local ProjectConfig = require('tasks.project_config') +local os = require('ffi').os:lower() +local cmake = {} + +--- Parses build dir expression. +---@param dir string: Path with expressions to replace. +---@param build_type string +---@return table +local function parse_dir(dir, build_type) + local parsed_dir = dir:gsub('{cwd}', vim.loop.cwd()) + parsed_dir = parsed_dir:gsub('{os}', os) + parsed_dir = parsed_dir:gsub('{build_type}', build_type:lower()) + return Path:new(parsed_dir) +end + +--- Returns reply directory that contains targets information. +---@param build_dir table +---@return unknown +local function get_reply_dir(build_dir) return build_dir / '.cmake' / 'api' / 'v1' / 'reply' end + +--- Reads information about target. +---@param codemodel_target table +---@param reply_dir table +---@return table +local function get_target_info(codemodel_target, reply_dir) return vim.json.decode((reply_dir / codemodel_target['jsonFile']):read()) end + +--- Creates query files that to acess information about targets after CMake configuration. +---@param build_dir table +---@return boolean: Returns `true` on success. +local function make_query_files(build_dir) + local query_dir = build_dir / '.cmake' / 'api' / 'v1' / 'query' + if not query_dir:mkdir({ parents = true }) then + utils.notify(string.format('Unable to create "%s"', query_dir.filename), vim.log.levels.ERROR) + return false + end + + local codemodel_file = query_dir / 'codemodel-v2' + if not codemodel_file:is_file() then + if not codemodel_file:touch() then + utils.notify(string.format('Unable to create "%s"', codemodel_file.filename), vim.log.levels.ERROR) + return false + end + end + return true +end + +--- Reads targets information. +---@param reply_dir table +---@return table? +local function get_codemodel_targets(reply_dir) + local found_files = scandir.scan_dir(reply_dir.filename, { search_pattern = 'codemodel*' }) + if #found_files == 0 then + utils.notify('Unable to find codemodel file', vim.log.levels.ERROR) + return nil + end + local codemodel = Path:new(found_files[1]) + local codemodel_json = vim.json.decode(codemodel:read()) + return codemodel_json['configurations'][1]['targets'] +end + +---@return table? +local function get_target_names() + local project_config = ProjectConfig.new() + local build_dir = parse_dir(project_config.cmake.build_dir, project_config.cmake.build_type) + if not build_dir:is_dir() then + utils.notify(string.format('Build directory "%s" does not exist, you need to run "configure" task first', build_dir), vim.log.levels.ERROR) + return nil + end + + local reply_dir = get_reply_dir(build_dir) + local codemodel_targets = get_codemodel_targets(reply_dir) + if not codemodel_targets then + return nil + end + + local targets = {} + for _, target in ipairs(codemodel_targets) do + local target_info = get_target_info(target, reply_dir) + local target_name = target_info['name'] + if target_name:find('_autogen') == nil then + table.insert(targets, target_name) + end + end + + return targets +end + +--- Finds path to an executable. +---@param build_dir table +---@param name string +---@param reply_dir table +---@return unknown? +local function get_executable_path(build_dir, name, reply_dir) + for _, target in ipairs(get_codemodel_targets(reply_dir)) do + if name == target['name'] then + local target_info = get_target_info(target, reply_dir) + if target_info['type'] ~= 'EXECUTABLE' then + utils.notify(string.format('Specified target "%s" is not an executable', name), vim.log.levels.ERROR) + return nil + end + + local target_path = Path:new(target_info['artifacts'][1]['path']) + if not target_path:is_absolute() then + target_path = build_dir / target_path + end + + return target_path + end + end + + utils.notify(string.format('Unable to find target named "%s"', name), vim.log.levels.ERROR) + return nil +end + +--- Copies compile_commands.json file from build directory to the current working directory for LSP integration. +local function copy_compile_commands() + local project_config = ProjectConfig.new() + local filename = 'compile_commands.json' + local source = parse_dir(project_config.cmake.build_dir, project_config.cmake.build_type) / filename + local destination = Path:new(vim.loop.cwd(), filename) + source:copy({ destination = destination.filename }) +end + +--- Task +---@param module_config table +---@return table? +local function configure(module_config, _) + local build_dir = parse_dir(module_config.build_dir, module_config.build_type) + build_dir:mkdir({ parents = true }) + if not make_query_files(build_dir) then + return nil + end + + return { + cmd = module_config.cmd, + args = { '-B', build_dir.filename, '-D', 'CMAKE_BUILD_TYPE=' .. module_config.build_type }, + after_success = copy_compile_commands, + } +end + +--- Task +---@param module_config table +---@return table +local function build(module_config, _) + local build_dir = parse_dir(module_config.build_dir, module_config.build_type) + + local args = { '--build', build_dir.filename } + if module_config.target then + vim.list_extend(args, { '--target', module_config.target }) + end + + return { + cmd = module_config.cmd, + args = args, + after_success = copy_compile_commands, + } +end + +--- Task +---@param module_config table +---@return table +local function build_all(module_config, _) + local build_dir = parse_dir(module_config.build_dir, module_config.build_type) + + return { + cmd = module_config.cmd, + args = { '--build', build_dir.filename }, + after_success = copy_compile_commands, + } +end + +--- Task +---@param module_config table +---@return table? +local function run(module_config, _) + if not module_config.target then + utils.notify('No selected target, please set "target" parameter', vim.log.levels.ERROR) + return nil + end + + local build_dir = parse_dir(module_config.build_dir, module_config.build_type) + if not build_dir:is_dir() then + utils.notify(string.format('Build directory "%s" does not exist, you need to run "configure" task first', build_dir), vim.log.levels.ERROR) + return nil + end + + local target_path = get_executable_path(build_dir, module_config.target, get_reply_dir(build_dir)) + if not target_path then + return + end + + if not target_path:is_file() then + utils.notify(string.format('Selected target "%s" is not built', target_path.filename), vim.log.levels.ERROR) + return nil + end + + return { + cmd = target_path.filename, + cwd = target_path:parent().filename, + } +end + +--- Task +---@param module_config table +---@return table? +local function debug(module_config, _) + if module_config.build_type ~= 'Debug' and module_config.build_type ~= 'RelWithDebInfo' then + utils.notify( + string.format('For debugging your "build_type" param should be set to "Debug" or "RelWithDebInfo", but your current build type is "%s"'), + module_config.build_type, + vim.log.levels.ERROR + ) + return nil + end + + local command = run(module_config, nil) + if not command then + return nil + end + + command.dap_name = module_config.dap_name + return command +end + +--- Task +---@param module_config table +---@return table +local function clean(module_config, _) + local build_dir = parse_dir(module_config.build_dir, module_config.build_type) + + return { + cmd = module_config.cmd, + args = { '--build', build_dir.filename, '--target', 'clean' }, + after_success = copy_compile_commands, + } +end + +--- Task +---@param module_config table +---@return table +local function open_build_dir(module_config, _) + local build_dir = parse_dir(module_config.build_dir, module_config.build_type) + + return { + cmd = os == 'windows' and 'start' or 'xdg-open', + args = { build_dir.filename }, + ignore_stdout = true, + ignore_stderr = true, + } +end + +cmake.params = { + target = get_target_names, + build_type = { 'Debug', 'Release', 'RelWithDebInfo', 'MinSizeRel' }, + 'cmake', + 'dap_name', +} +cmake.condition = function() return Path:new('CMakeLists.txt'):exists() end +cmake.tasks = { + configure = configure, + build = build, + build_all = build_all, + run = { build, run }, + debug = debug, + clean = clean, + open_build_dir = open_build_dir, +} + +return cmake diff --git a/lua/tasks/project_config.lua b/lua/tasks/project_config.lua new file mode 100644 index 0000000..2d366c6 --- /dev/null +++ b/lua/tasks/project_config.lua @@ -0,0 +1,29 @@ +local config = require('tasks.config') +local Path = require('plenary.path') + +--- Contains all fields from configuration. +---@class ProjectConfig +local ProjectConfig = {} +ProjectConfig.__index = ProjectConfig + +--- Reads project configuration JSON into a table. +---@return ProjectConfig +function ProjectConfig.new() + local project_config = {} + local params_file = Path:new(config.params_file) + if params_file:is_file() then + project_config = vim.json.decode(params_file:read()) + else + project_config = {} + end + project_config = vim.tbl_extend('keep', project_config, config.default_params) + return setmetatable(project_config, ProjectConfig) +end + +--- Writes all values as JSON to disk. +function ProjectConfig:write() + local params_file = Path:new(config.params_file) + params_file:write(vim.json.encode(self), 'w') +end + +return ProjectConfig diff --git a/lua/tasks/runner.lua b/lua/tasks/runner.lua new file mode 100644 index 0000000..21bf765 --- /dev/null +++ b/lua/tasks/runner.lua @@ -0,0 +1,226 @@ +local config = require('tasks.config') +local Job = require('plenary.job') +local runner = {} + +local last_job + +---@param lines table +---@param errorformat string? +local function append_to_quickfix(lines, errorformat) + vim.fn.setqflist({}, 'a', { efm = errorformat, lines = lines }) + -- Scrolls the quickfix buffer if not active + if vim.bo.buftype ~= 'quickfix' then + vim.api.nvim_command('cbottom') + end +end + +---@param errorformat? string +---@return function: A coroutine that reads job data into quickfix. +local function read_to_quickfix(errorformat) + -- Modified from https://github.com/nvim-lua/plenary.nvim/blob/968a4b9afec0c633bc369662e78f8c5db0eba249/lua/plenary/job.lua#L287 + -- We use our own implementation to process data in chunks because + -- default Plenary callback processes every line which is very slow for adding to quickfix. + return coroutine.wrap(function(err, data, is_complete) + -- We repeat forever as a coroutine so that we can keep calling this. + local lines = {} + local result_index = 1 + local result_line = nil + local found_newline = nil + + while true do + if data then + data = data:gsub('\r', '') + + local processed_index = 1 + local data_length = #data + 1 + + repeat + local start = data:find('\n', processed_index, true) or data_length + local line = data:sub(processed_index, start - 1) + found_newline = start ~= data_length + + -- Concat to last line if there was something there already. + -- This happens when "data" is broken into chunks and sometimes + -- the content is sent without any newlines. + if result_line then + result_line = result_line .. line + + -- Only put in a new line when we actually have new data to split. + -- This is generally only false when we do end with a new line. + -- It prevents putting in a "" to the end of the results. + elseif start ~= processed_index or found_newline then + result_line = line + + -- Otherwise, we don't need to do anything. + end + + if found_newline then + if not result_line then + return vim.api.nvim_err_writeln('Broken data thing due to: ' .. tostring(result_line) .. ' ' .. tostring(data)) + end + + table.insert(lines, err and err or result_line) + + result_index = result_index + 1 + result_line = nil + end + + processed_index = start + 1 + until not found_newline + end + + if is_complete and not found_newline then + table.insert(lines, err and err or result_line) + end + + if #lines ~= 0 then + -- Move lines to another variable and send them to quickfix + local processed_lines = lines + lines = {} + vim.schedule(function() append_to_quickfix(processed_lines, errorformat) end) + end + + if data == nil or is_complete then + return + end + + err, data, is_complete = coroutine.yield() + end + end) +end + +--- Run specified commands in chain. +---@param task_name string: Name of a task to read properties. +---@param commands table: Commands to chain. +---@param module_config table: Module configuration. +---@param addition_args table?: Additional arguments that will be applied to the last command. +---@param previous_job table?: Previous job to read data from, used by this function for recursion. +function runner.chain_commands(task_name, commands, module_config, addition_args, previous_job) + local command = commands[1] + if vim.is_callable(command) then + command = command(module_config, previous_job) + if not command then + return + end + end + + local cwd = command.cwd or vim.loop.cwd() + local args = command.args and command.args or {} + local env = vim.tbl_extend('force', vim.loop.os_environ(), command.env and command.env or {}) + if #commands == 1 then + -- Apply task parameters only to the last command + vim.list_extend(args, addition_args) + vim.list_extend(args, vim.tbl_get(module_config, 'args', task_name) or {}) + env = vim.tbl_extend('force', env, vim.tbl_get(module_config, 'env', task_name) or {}) + end + + if command.dap_name then + vim.schedule(function() + local dap = require('dap') + local dap_config = dap.configurations[command.dap_name] -- Try to get an existing configuration + dap.run(vim.tbl_extend('force', dap_config and dap_config or { type = command.dap_name }, { + name = command.cmd, + request = 'launch', + program = command.cmd, + args = args, + })) + if config.dap_open_command then + vim.api.nvim_command('cclose') + config.dap_open_command() + end + last_job = dap + end) + return + end + + local quickfix_output = not command.ignore_stdout and not command.ignore_stderr + local job = Job:new({ + command = command.cmd, + args = args, + cwd = cwd, + env = env, + enable_recording = #commands ~= 1, + on_start = quickfix_output and vim.schedule_wrap(function() + vim.fn.setqflist({}, ' ', { title = command.cmd .. ' ' .. table.concat(args, ' ') }) + vim.api.nvim_command(string.format('%s copen %d', config.quickfix.pos, config.quickfix.height)) + vim.api.nvim_command('wincmd p') + end) or nil, + on_exit = vim.schedule_wrap(function(_, code, signal) + if quickfix_output then + append_to_quickfix({ 'Exited with code ' .. (signal == 0 and code or 128 + signal) }) + end + if code == 0 and signal == 0 and command.after_success then + command.after_success() + end + end), + }) + + job:start() + if not command.ignore_stdout then + job.stdout:read_start(read_to_quickfix(command.errorformat)) + end + if not command.ignore_stderr then + job.stderr:read_start(read_to_quickfix(command.errorformat)) + end + + if #commands ~= 1 then + job:after_success(function() runner.chain_commands(task_name, vim.list_slice(commands, 2), module_config, addition_args, job) end) + end + last_job = job +end + +---@return string? +function runner.get_current_job_name() + if not last_job then + return nil + end + + -- Check if this job was run through debugger. + if last_job.session then + local session = last_job.session() + if not session then + return nil + end + return session.config.program + end + + if last_job.is_shutdown then + return nil + end + + return last_job.cmd +end + +---@return boolean: `true` if a job was canceled or `false` if there is no active job. +function runner.cancel_job() + if not last_job then + return false + end + + -- Check if this job was run through debugger. + if last_job.session then + if not last_job.session() then + return false + end + last_job.terminate() + return true + end + + if last_job.is_shutdown then + return false + end + + last_job:shutdown(1, 9) + + if vim.fn.has('win32') == 1 then + -- Kill all children. + for _, pid in ipairs(vim.api.nvim_get_proc_children(last_job.pid)) do + vim.loop.kill(pid, 9) + end + else + vim.loop.kill(last_job.pid, 9) + end + return true +end + +return runner diff --git a/lua/tasks/subcommands.lua b/lua/tasks/subcommands.lua new file mode 100644 index 0000000..a4ec9ca --- /dev/null +++ b/lua/tasks/subcommands.lua @@ -0,0 +1,79 @@ +local tasks = require('tasks') +local utils = require('tasks.utils') +local constants = require('tasks.constants') +local subcommands = {} + +--- Completes `:Task` command. +---@param arg string: Current argument under cursor. +---@param cmd_line string: All arguments. +---@return table: List of all commands matched with `arg`. +function subcommands.complete(arg, cmd_line) + local matches = {} + + local words = vim.split(cmd_line, ' ', { trimempty = true }) + if not vim.endswith(cmd_line, ' ') then + -- Last word is not fully typed, don't count it + table.remove(words, #words) + end + + if #words == 1 then + for subcommand in pairs(tasks) do + if vim.startswith(subcommand, arg) and subcommand ~= 'setup' then + table.insert(matches, subcommand) + end + end + elseif #words == 2 then + if words[2] == 'start' or words[2] == 'set_task_param' or words[2] == 'set_module_param' then + local module_names = utils.get_module_names() + table.insert(module_names, 'auto') -- Special value for automatic module detection + for _, module_name in ipairs(module_names) do + if vim.startswith(module_name, arg) then + table.insert(matches, module_name) + end + end + end + elseif #words == 3 then + if words[2] == 'start' or words[2] == 'set_task_param' or words[2] == 'set_module_param' then + local ok, module = pcall(require, 'tasks.module.' .. words[3]) + if ok then + for key, value in pairs(words[2] == 'set_module_param' and module.params or module.tasks) do + local name = type(key) == 'number' and value or key -- Handle arrays + if vim.startswith(name, arg) then + table.insert(matches, name) + end + end + end + end + elseif #words == 4 then + if words[2] == 'set_task_param' then + for _, param_name in ipairs(constants.task_params) do + if vim.startswith(param_name, arg) then + table.insert(matches, param_name) + end + end + end + end + + return matches +end + +--- Run specified subcommand received from completion. +---@param subcommand table +function subcommands.run(subcommand) + local subcommand_func = tasks[subcommand.fargs[1]] + if not subcommand_func then + utils.notify(string.format('No such subcommand named "%s"', subcommand.fargs[1]), vim.log.levels.ERROR) + return + end + local subcommand_info = debug.getinfo(subcommand_func) + if subcommand_info.isvararg and #subcommand.fargs - 1 < subcommand_info.nparams then + utils.notify(string.format('Subcommand %s should have at least %s argument(s)', subcommand.fargs[1], subcommand_info.nparams + 1), vim.log.levels.ERROR) + return + elseif not subcommand_info.isvararg and #subcommand.fargs - 1 ~= subcommand_info.nparams then + utils.notify(string.format('Subcommand %s should have %s argument(s)', subcommand.fargs[1], subcommand_info.nparams + 1), vim.log.levels.ERROR) + return + end + subcommand_func(unpack(subcommand.fargs, 2)) +end + +return subcommands diff --git a/lua/tasks/utils.lua b/lua/tasks/utils.lua new file mode 100644 index 0000000..983bde7 --- /dev/null +++ b/lua/tasks/utils.lua @@ -0,0 +1,100 @@ +local scandir = require('plenary.scandir') +local Path = require('plenary.path') +local utils = {} + +local args_regex = vim.regex([[\s\%(\%([^'"]*\(['"]\)[^'"]*\1\)*[^'"]*$\)\@=]]) + +--- A small wrapper around `vim.notify` that adds plugin title. +---@param msg string +---@param log_level number +function utils.notify(msg, log_level) vim.notify(msg, log_level, { title = 'Tasks' }) end + +--- Splits command line arguments respecting quotes. +---@param args string? +---@return table +function utils.split_args(args) + if not args then + return {} + end + + -- Split on spaces unless in quotes. + local splitted_args = {} + local match_beg + while true do + match_beg = args_regex:match_str(args) + if match_beg then + table.insert(splitted_args, args:sub(1, match_beg)) + args = args:sub(match_beg + 2) + else + -- Insert last arg left. + table.insert(splitted_args, args) + break + end + end + + -- Remove quotes + for i, arg in ipairs(splitted_args) do + splitted_args[i] = arg:gsub('"', ''):gsub("'", '') + end + return splitted_args +end + +--- Joins command line arguments respecting spaces by putting double quotes around them. +---@param args table? +---@return string +function utils.join_args(args) + if not args then + return '' + end + + -- Add quotes if argument contain spaces + for index, arg in ipairs(args) do + if arg:find(' ') then + args[index] = '"' .. arg .. '"' + end + end + + return table.concat(args, ' ') +end + +---@return table +function utils.get_module_names() + local module_dir = Path:new(debug.getinfo(1).source:sub(2)):parent() / 'module' + + local modules = {} + for _, entry in ipairs(scandir.scan_dir(module_dir.filename, { depth = 1 })) do + -- Strip full path and extension + local extension_len = 4 + local parent_offset = 2 + table.insert(modules, entry:sub(#Path:new(entry):parent().filename + parent_offset, #entry - extension_len)) + end + + return modules +end + +--- Find a module by name +---@param module_type string name of a module or `auto` string to pick a first module that match a condition. +---@return table?, string?: module and its name. +function utils.get_module(module_type) + if module_type == 'auto' then + for _, name in ipairs(utils.get_module_names()) do + local module = require('tasks.module.' .. name) + if module.condition() then + return module, name + end + end + + utils.notify('Unable to autodetect module for this working directory', vim.log.levels.ERROR) + return nil, nil + end + + local module = require('tasks.module.' .. module_type) + if not module then + utils.notify('Unable to find a module named ' .. module_type, vim.log.levels.ERROR) + return nil, nil + end + + return module, module_type +end + +return utils -- cgit v1.2.3