| 1 |
-- Copyright (c) 2020-2021 shadmansaleh |
| 2 |
-- MIT license, see LICENSE for more details. |
| 3 |
|
| 4 |
--- wrapper around job api |
| 5 |
--- creates a job handler when called |
| 6 |
local Job = setmetatable({ |
| 7 |
--- start the job |
| 8 |
start = function(self) |
| 9 |
self.killed = false |
| 10 |
self.job_id = vim.fn.jobstart(self.args.cmd, self.args) |
| 11 |
return self.job_id > 0 |
| 12 |
end, |
| 13 |
--- stop the job. Also immediately disables io from the job. |
| 14 |
stop = function(self) |
| 15 |
if self.killed then |
| 16 |
return |
| 17 |
end |
| 18 |
self.killed = true |
| 19 |
if self.job_id and self.job_id > 0 then |
| 20 |
vim.fn.jobstop(self.job_id) |
| 21 |
end |
| 22 |
self.job_id = 0 |
| 23 |
end, |
| 24 |
-- Wraps callbacks so they are only called when job is alive |
| 25 |
-- This avoids race conditions |
| 26 |
wrap_cb_alive = function(self, name) |
| 27 |
local original_cb = self.args[name] |
| 28 |
if original_cb then |
| 29 |
self.args[name] = function(...) |
| 30 |
if not self.killed then |
| 31 |
return original_cb(...) |
| 32 |
end |
| 33 |
end |
| 34 |
end |
| 35 |
end, |
| 36 |
wrap_on_exit = function(self) |
| 37 |
local original_cb = self.args.on_exit |
| 38 |
if original_cb then |
| 39 |
self.args.on_exit = function(job_id, exit_code, event_type) |
| 40 |
if self.killed then |
| 41 |
exit_code = -1 |
| 42 |
end |
| 43 |
return original_cb(job_id, exit_code, event_type) |
| 44 |
end |
| 45 |
end |
| 46 |
end, |
| 47 |
}, { |
| 48 |
---create new job handler |
| 49 |
---@param self table base job table |
| 50 |
---@param args table same args as jobstart except cmd is also passed in part of it |
| 51 |
---@return table new job handler |
| 52 |
__call = function(self, args) |
| 53 |
args = vim.deepcopy(args or {}) |
| 54 |
if type(args.cmd) == 'string' then |
| 55 |
args.cmd = vim.split(args.cmd, ' ') |
| 56 |
end |
| 57 |
self.__index = self |
| 58 |
local job = setmetatable({ args = args }, self) |
| 59 |
job:wrap_cb_alive('on_stdout') |
| 60 |
job:wrap_cb_alive('on_stderr') |
| 61 |
job:wrap_cb_alive('on_stdin') |
| 62 |
job:wrap_on_exit() |
| 63 |
return job |
| 64 |
end, |
| 65 |
}) |
| 66 |
|
| 67 |
return Job |