aboutsummaryrefslogtreecommitdiff
path: root/lua/extregs/file.lua
blob: 0dfe88c6a934cf8ad13489e1e4f987d805a0e9ec (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
local util = require('extregs.util')
local storage = require('extregs.storage')
local M = {}

function M.get_provider(cfg)
  local function path() return util.path(cfg.path) end
  return {
    read = function()
      local fd, err = io.open(path(), 'rb')
      if not fd then error('cannot read ' .. path() .. ': ' .. tostring(err)) end
      local data = fd:read('*a')
      fd:close()
      return storage.decode(data)
    end,
    write = function(_, reg)
      local dest = path()
      vim.fn.mkdir(vim.fn.fnamemodify(dest, ':h'), 'p')
      local fd, err = io.open(dest, 'wb')
      if not fd then error('cannot write ' .. dest .. ': ' .. tostring(err)) end
      assert(fd:write(storage.encode(reg)))
      assert(fd:close())
      return true
    end,
  }
end
return M