summaryrefslogtreecommitdiff
path: root/db.lua
blob: 0a9d0f49f1e41ed6f0caf53002e9e46d198f1c54 (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
--[[--

  JSON file database.

--]]--

local inspect = require "ext.inspect"

local cjson               = require "cjson"

local pcall               = pcall

local io                  = require "io"
local iostdout            = io.stdout
local iostdin             = io.stdin

local common              = require "common"
local common_status       = common.status
local status_ok           = common_status.codes.ok
local status_error        = common_status.codes.error
local println             = common.println
local errorln             = common.errorln
local noiseln             = common.noiseln
local debugln             = common.debugln

local json_internalize = function (jsdata)
  local jsdec = cjson.new ()
  local parsed = jsdec.decode (jsdata)
  if parsed == nil then return status_error end
  return status_ok, parsed
end

-------------------------------------------------------------------------------
--- API
-------------------------------------------------------------------------------

local read_json_db = function (cal, fh)
  fh = fh or iostdin
  local jsdata = fh:read "*all"
  fh:close ()
  if jsdata == nil then return status_error end
  return json_internalize (jsdata)
end

local output_calendar = function (cal, fh)
  fh = fh or iostdout
  local jsenc = cjson.new ()
  local ok, str = pcall (jsenc.encode, cal)
  if ok == false then
          errorln ("todb: failed to serialize calendar: %s", str)
    return status_error
  end
  fh:write (str)
  return status_ok
end

return { output_calendar = output_calendar
       , read_json_db    = read_json_db
       }