summaryrefslogtreecommitdiffstats
path: root/acf/persistence/backends/files.lua
blob: 8e59ab9a7f15498faae9e02406df7ebe29970de4 (plain)
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
--[[
Copyright (c) 2012 Kaarle Ritvanen
See LICENSE file for license details
--]]

module(..., package.seeall)

local pth = require('acf.path')
local util = require('acf.persistence.util')

require 'lfs'


backend = require('acf.object').class()

-- TODO cache expiration
function backend:init() self.cache = {} end

function backend:get(path)
   local name = pth.join('/', unpack(path))

   if not self.cache[name] then
      local attrs = lfs.attributes(name)
      if not attrs then return end

      if attrs.mode == 'file' then
	 self.cache[name] = util.read_file(name)

      elseif attrs.mode == 'directory' then
	 local res = {}
	 for fname in lfs.dir(name) do
	    if not ({['.']=true, ['..']=true})[fname] then
	       table.insert(res, fname)
	    end
	 end
	 return res

      else error('Unsupported file type: '..name) end

      -- TODO present symlinks as references
   end

   return self.cache[name]
end

function backend:set(mods)
   for _, mod in pairs(mods) do
      local path, t, value = unpack(mod)
      local name = pth.join('/', unpack(path))

      -- TODO save references (t == 'reference') as symlinks

      if not t then
	 -- TODO del files & dirs
	 print('DEL', name)

      elseif t == 'table' then
	 lfs.mkdir(name)

      else
	 local file = util.open_file(name, 'w')
	 file:write(value)
	 file:close()

	 self.cache[name] = value
      end
   end
end