-
Notifications
You must be signed in to change notification settings - Fork 1
/
helpers.lua
94 lines (58 loc) · 1.98 KB
/
helpers.lua
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
88
89
90
91
92
93
94
--[[ Some helper functions I use from more than one script.
Author: Stefan Klinger (www.stefan-klinger.de)
License: GNU General Public License Version 3
]]
local h = {} -- module export
--[[ Append all following arguments to the table given as first
argument. ]]
h.append = function(t, ...)
for _, v in pairs({...}) do
table.insert(t, v)
end
end
--[[ Lua provides no interface to `execve`. So we must go through
`os.execute`, which takes one shell command as string, and thus
requires special care when quoting arguments (xkcd.com/327).
From a list (Lua: table) of arguments as one would pass them to
execve(2), create a command string to be passed to the shell via
`os.execute`, assuming that `'` is strong quoting as in
bash(1). ]]
h.mkCmdString = function(argv)
local words = {}
for _, a in pairs(argv) do
h.append(words, "'" .. a:gsub("'", "'\\''") .. "'")
end
return table.concat(words, ' ')
end
--[[ Try `h.runCmd{'echo', "'", '"', ";", '\nla"l\'a'}` ]]
h.runCmd = function(argv)
-- FIXME: better use a builtin function when available
local cmd = h.mkCmdString(argv)
if not os.execute(cmd) then
print("Failed to run command: " .. cmd)
return false
end
return true
end
-- create the path passed as argument
h.mkDir = function(path)
-- FIXME: better use builtin function if available
return h.runCmd{'mkdir', '-p', path}
end
-- copy file `src` to directory `dst`
h.copyToDir = function(dst, src)
-- FIXME: better use builtin function if available
return h.runCmd{ 'cp', '-t', dst, src }
end
-- copy `src` to `dst`, which must be a file, not a directory
h.copyTo = function(dst, src)
-- FIXME: better use builtin function if available
return h.runCmd{ 'cp', '-T', src, dst }
end
-- Print all fields of a table to stdout.
h.printAllFields = function(name, t)
for k, v in pairs(t) do
print(name .. '.' .. k, type(v), v)
end
end
return h