Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
quarto-dev
GitHub Repository: quarto-dev/quarto-cli
Path: blob/main/src/resources/pandoc/datadir/luacov/util.lua
12923 views
1
---------------------------------------------------
2
-- Utility module.
3
-- @class module
4
-- @name luacov.util
5
local util = {}
6
7
--- Removes a prefix from a string if it's present.
8
-- @param str a string.
9
-- @param prefix a prefix string.
10
-- @return original string if does not start with prefix
11
-- or string without prefix.
12
function util.unprefix(str, prefix)
13
if str:sub(1, #prefix) == prefix then
14
return str:sub(#prefix + 1)
15
else
16
return str
17
end
18
end
19
20
-- Returns contents of a file or nil + error message.
21
local function read_file(name)
22
local f, open_err = io.open(name, "rb")
23
24
if not f then
25
return nil, util.unprefix(open_err, name .. ": ")
26
end
27
28
local contents, read_err = f:read("*a")
29
f:close()
30
31
if contents then
32
return contents
33
else
34
return nil, read_err
35
end
36
end
37
38
--- Loads a string.
39
-- @param str a string.
40
-- @param[opt] env environment table.
41
-- @param[opt] chunkname chunk name.
42
function util.load_string(str, env, chunkname)
43
if _VERSION:find("5%.1") then
44
local func, err = loadstring(str, chunkname) -- luacheck: compat
45
46
if not func then
47
return nil, err
48
end
49
50
if env then
51
setfenv(func, env) -- luacheck: compat
52
end
53
54
return func
55
else
56
return load(str, chunkname, "bt", env or _ENV) -- luacheck: compat
57
end
58
end
59
60
--- Load a config file.
61
-- Reads, loads and runs a Lua file in an environment.
62
-- @param name file name.
63
-- @param env environment table.
64
-- @return true and the first return value of config on success,
65
-- nil + error type + error message on failure, where error type
66
-- can be "read", "load" or "run".
67
function util.load_config(name, env)
68
local src, read_err = read_file(name)
69
70
if not src then
71
return nil, "read", read_err
72
end
73
74
local func, load_err = util.load_string(src, env, "@config")
75
76
if not func then
77
return nil, "load", "line " .. util.unprefix(load_err, "config:")
78
end
79
80
local ok, ret = pcall(func)
81
82
if not ok then
83
return nil, "run", "line " .. util.unprefix(ret, "config:")
84
end
85
86
return true, ret
87
end
88
89
--- Checks if a file exists.
90
-- @param name file name.
91
-- @return true if file can be opened, false otherwise.
92
function util.file_exists(name)
93
local f = io.open(name)
94
95
if f then
96
f:close()
97
return true
98
else
99
return false
100
end
101
end
102
103
return util
104
105