aboutsummaryrefslogtreecommitdiff
path: root/test/functional/shada/helpers.lua
blob: fb3ec4a87ce0ebddea538373d80731bd0320d54f (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
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
local helpers = require('test.functional.helpers')(nil)
local meths = helpers.meths
local write_file = helpers.write_file
local concat_tables = helpers.concat_tables

local mpack = require('mpack')

local tmpname = helpers.tmpname()

--   o={
--     args=…,
--     args_rm=…,
--     shadafile=…,
--   }
local function reset(o)
  assert(o == nil or type(o) == 'table' or type(o) == 'string')
  o = o and o or {}
  local args_rm = o.args_rm or {}
  table.insert(args_rm, '-i')
  local args={
    '-i', o.shadafile or tmpname,
  }
  if type(o) == 'string' then
    args = concat_tables(args, {'--cmd', o})
  elseif o.args then
    args = concat_tables(args, o.args)
  end
  helpers.clear{
    args_rm=args_rm,
    args=args,
  }
  meths.set_var('tmpname', tmpname)
end

local clear = function()
  os.remove(tmpname)
end

local get_shada_rw = function(fname)
  local wshada = function(text)
    write_file(fname, text, true)
  end
  local sdrcmd = function(bang)
    return 'rshada' .. (bang and '!' or '') .. ' ' .. fname
  end
  local clean = function()
    os.remove(fname)
    local i = ('a'):byte()
    while i <= ('z'):byte() do
      if not os.remove(fname .. ('.tmp.%c'):format(i)) then
        break
      end
      i = i + 1
    end
  end
  return wshada, sdrcmd, fname, clean
end

local mpack_keys = {'type', 'timestamp', 'length', 'value'}

local read_shada_file = function(fname)
  local fd = io.open(fname, 'r')
  local mstring = fd:read('*a')
  fd:close()
  local unpack = mpack.Unpacker()
  local ret = {}
  local cur, val
  local i = 0
  local off = 1
  while off <= #mstring do
    val, off = unpack(mstring, off)
    if i % 4 == 0 then
      cur = {}
      ret[#ret + 1] = cur
    end
    cur[mpack_keys[(i % 4) + 1]] = val
    i = i + 1
  end
  return ret
end

return {
  reset=reset,
  clear=clear,
  get_shada_rw=get_shada_rw,
  read_shada_file=read_shada_file,
}