2021-09-20 11:46:38 +00:00
|
|
|
-- Copyright (c) 2020-2021 shadmansaleh
|
|
|
|
-- MIT license, see LICENSE for more details.
|
|
|
|
|
2021-10-12 14:04:47 +00:00
|
|
|
--- wrapper arround job api
|
|
|
|
--- creates a job handler when called
|
2021-08-08 08:47:20 +00:00
|
|
|
local Job = setmetatable({
|
2021-10-12 14:04:47 +00:00
|
|
|
--- start the job
|
2021-08-08 08:47:20 +00:00
|
|
|
start = function(self)
|
|
|
|
self.job_id = vim.fn.jobstart(self.args.cmd, self.args)
|
|
|
|
return self.job_id > 0
|
|
|
|
end,
|
2021-10-12 14:04:47 +00:00
|
|
|
--- stop the job. also imidiately disables io from the job.
|
2021-08-08 08:47:20 +00:00
|
|
|
stop = function(self)
|
2021-09-03 18:28:20 +00:00
|
|
|
if self.killed then
|
|
|
|
return
|
|
|
|
end
|
|
|
|
if self.job_id and self.job_id > 0 then
|
|
|
|
vim.fn.jobstop(self.job_id)
|
|
|
|
end
|
2021-08-08 08:47:20 +00:00
|
|
|
self.job_id = 0
|
|
|
|
self.killed = true
|
|
|
|
end,
|
|
|
|
-- Wraps callbacks so they are only called when job is alive
|
|
|
|
-- This avoids race conditions
|
|
|
|
wrap_cb_alive = function(self, name)
|
|
|
|
local original_cb = self.args[name]
|
|
|
|
if original_cb then
|
|
|
|
self.args[name] = function(...)
|
2021-09-03 18:28:20 +00:00
|
|
|
if not self.killed then
|
|
|
|
return original_cb(...)
|
|
|
|
end
|
2021-08-08 08:47:20 +00:00
|
|
|
end
|
|
|
|
end
|
2021-09-03 18:28:20 +00:00
|
|
|
end,
|
|
|
|
}, {
|
2021-10-12 14:04:47 +00:00
|
|
|
---create new job handler
|
|
|
|
---@param self table base job table
|
|
|
|
---@param args table same args as jobstart except cmd is also passed in part of it
|
|
|
|
---@return table new job handler
|
2021-08-08 08:47:20 +00:00
|
|
|
__call = function(self, args)
|
|
|
|
args = vim.deepcopy(args or {})
|
2021-09-03 18:28:20 +00:00
|
|
|
if type(args.cmd) == 'string' then
|
|
|
|
args.cmd = vim.split(args.cmd, ' ')
|
|
|
|
end
|
2021-08-08 08:47:20 +00:00
|
|
|
self.__index = self
|
2021-09-03 18:28:20 +00:00
|
|
|
local job = setmetatable({ args = args }, self)
|
|
|
|
job:wrap_cb_alive 'on_stdout'
|
|
|
|
job:wrap_cb_alive 'on_stderr'
|
|
|
|
job:wrap_cb_alive 'on_stdin'
|
2021-08-08 08:47:20 +00:00
|
|
|
return job
|
|
|
|
end,
|
|
|
|
})
|
|
|
|
|
|
|
|
return Job
|