Luigit
repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by admin

neovim/lua/bugabinga/pivi/extension/client.lua

Raw
-- Throwaway client used by the companion Pi extension.
-- Usage: nvim --headless --clean -l client.lua <address> <request.json> <response.json>

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

write_response( result )