-- Throwaway client used by the companion Pi extension.
-- Usage: nvim --headless --clean -l client.lua
local address = arg[1]
local request_path = arg[2]
local response_path = arg[3]
local write_response = function( value )
vim.fn.writefile( { vim.json.encode( value ), }, response_path )
end
if not address or not request_path or not response_path then
write_response { ok = false, error = 'client needs address, request path, and response path', }
return
end
local ok, request = pcall( function()
return vim.json.decode( table.concat( vim.fn.readfile( request_path ), '\n' ) )
end )
if not ok then
write_response { ok = false, error = 'unreadable request: ' .. tostring( request ), }
return
end
local kind = address:match '^[%w%.%-]+:%d+$' and 'tcp' or 'pipe'
local connected, channel = pcall( vim.fn.sockconnect, kind, address, { rpc = true, } )
if not connected or channel == 0 then
write_response { ok = false, error = 'cannot reach neovim at ' .. address, }
return
end
local answered, result = pcall(
vim.rpcrequest,
channel,
'nvim_exec_lua',
'return require("bugabinga.pivi.bridge").handle(...)',
{ request, }
)
pcall( vim.fn.chanclose, channel )
if not answered then
write_response { ok = false, error = tostring( result ), }
return
end
if request.action == 'capture' and result.ok then
local path = vim.fs.joinpath( vim.fs.dirname( debug.getinfo( 1, 'S' ).source:sub( 2 ) ), '..', 'capture.lua' )
local captured, grid = pcall( function() return dofile( path ).capture( address, result.capture ) end )
result = captured and { ok = true, capture = grid, } or { ok = false, error = tostring( grid ), }
end
write_response( result )