Path: blob/main/src/resources/pandoc/datadir/luacov/util.lua
12923 views
---------------------------------------------------1-- Utility module.2-- @class module3-- @name luacov.util4local util = {}56--- Removes a prefix from a string if it's present.7-- @param str a string.8-- @param prefix a prefix string.9-- @return original string if does not start with prefix10-- or string without prefix.11function util.unprefix(str, prefix)12if str:sub(1, #prefix) == prefix then13return str:sub(#prefix + 1)14else15return str16end17end1819-- Returns contents of a file or nil + error message.20local function read_file(name)21local f, open_err = io.open(name, "rb")2223if not f then24return nil, util.unprefix(open_err, name .. ": ")25end2627local contents, read_err = f:read("*a")28f:close()2930if contents then31return contents32else33return nil, read_err34end35end3637--- Loads a string.38-- @param str a string.39-- @param[opt] env environment table.40-- @param[opt] chunkname chunk name.41function util.load_string(str, env, chunkname)42if _VERSION:find("5%.1") then43local func, err = loadstring(str, chunkname) -- luacheck: compat4445if not func then46return nil, err47end4849if env then50setfenv(func, env) -- luacheck: compat51end5253return func54else55return load(str, chunkname, "bt", env or _ENV) -- luacheck: compat56end57end5859--- Load a config file.60-- Reads, loads and runs a Lua file in an environment.61-- @param name file name.62-- @param env environment table.63-- @return true and the first return value of config on success,64-- nil + error type + error message on failure, where error type65-- can be "read", "load" or "run".66function util.load_config(name, env)67local src, read_err = read_file(name)6869if not src then70return nil, "read", read_err71end7273local func, load_err = util.load_string(src, env, "@config")7475if not func then76return nil, "load", "line " .. util.unprefix(load_err, "config:")77end7879local ok, ret = pcall(func)8081if not ok then82return nil, "run", "line " .. util.unprefix(ret, "config:")83end8485return true, ret86end8788--- Checks if a file exists.89-- @param name file name.90-- @return true if file can be opened, false otherwise.91function util.file_exists(name)92local f = io.open(name)9394if f then95f:close()96return true97else98return false99end100end101102return util103104105