1
0
mirror of https://github.com/SpaceVim/SpaceVim.git synced 2025-03-13 02:05:40 +08:00

feat(job): improve job api

This commit is contained in:
wsdjeg 2023-07-13 00:53:03 +08:00
parent aa57658a58
commit 9cc323a07c
3 changed files with 76 additions and 20 deletions

View File

@ -42,6 +42,39 @@ call s:JOB.start(cmd,
\ )
```
The lua job api:
```lua
local job = require('spacevim.api.job')
local jobid = job.start({'lua53', '-'}, {
-- the on_stdout and on_stderr function can be:
-- fun(id, data) end or fun(id, data, event) end
on_stdout = function(id, data)
vim.print(id)
vim.print(vim.inspect(data))
end,
on_stderr = function(id, data)
vim.print(id)
vim.print(vim.inspect(data))
end,
on_exit = function(id, code, signal)
vim.print(id)
vim.print('exit code', code)
vim.print('exit signal', signal)
end,
})
job.send(jobid, 'print(1)\n')
job.send(jobid, 'print(1)\n')
job.send(jobid, 'print(1)\n')
job.send(jobid, 'print(1)\n')
job.chanclose(jobid, 'stdin')
job.stop(jobid)
```
## Functions
| function name | description |

View File

@ -110,25 +110,50 @@ function M.start(cmd, opts)
pid = pid,
})
if opts.on_stdout then
uv.read_start(stdout, function(err, data)
if data then
data = data:gsub('\r', '')
vim.schedule(function()
opts.on_stdout(current_id, vim.split(data, '\n'), 'stdout')
end)
end
end)
-- define on_stdout function based on stdout's nparams
local nparams = debug.getinfo(opts.on_stdout).nparams
if nparams == 2 then
uv.read_start(stdout, function(err, data)
if data then
data = data:gsub('\r', '')
vim.schedule(function()
opts.on_stdout(current_id, vim.split(data, '\n'))
end)
end
end)
else
uv.read_start(stdout, function(err, data)
if data then
data = data:gsub('\r', '')
vim.schedule(function()
opts.on_stdout(current_id, vim.split(data, '\n'), 'stdout')
end)
end
end)
end
end
if opts.on_stderr then
uv.read_start(stderr, function(err, data)
if data then
data = data:gsub('\r', '')
vim.schedule(function()
opts.on_stderr(current_id, vim.split(data, '\n'), 'stderr')
end)
end
end)
local nparams = debug.getinfo(opts.on_stderr).nparams
if nparams == 2 then
uv.read_start(stderr, function(err, data)
if data then
data = data:gsub('\r', '')
vim.schedule(function()
opts.on_stderr(current_id, vim.split(data, '\n'))
end)
end
end)
else
uv.read_start(stderr, function(err, data)
if data then
data = data:gsub('\r', '')
vim.schedule(function()
opts.on_stderr(current_id, vim.split(data, '\n'), 'stderr')
end)
end
end)
end
end
return current_id
end

View File

@ -1,15 +1,13 @@
local job = require('spacevim.api.job')
local jobid = job.start({'lua53', '-'}, {
on_stdout = function(id, data, event)
on_stdout = function(id, data)
vim.print(id)
vim.print(vim.inspect(data))
vim.print(event)
end,
on_stderr = function(id, data, event)
on_stderr = function(id, data)
vim.print(id)
vim.print(vim.inspect(data))
vim.print(event)
end,
on_exit = function(id, code, signal)
vim.print(id)