-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfile_utils.lua
93 lines (74 loc) · 2.02 KB
/
file_utils.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
local utils = {}
utils.slash = package.config:sub(1, 1)
local function getOS()
if utils.slash == "\\" then
return "windows"
end
if utils.slash == "/" then
return "unix"
end
print("Error: unknown type of OS!")
os.exit(1)
end
utils.osType = getOS()
function utils.fileExists(file)
local ok, err, code = os.rename(file, file)
if code == 13 then -- permission denied, file exists
return true
end
return ok, err
end
function utils.directoryExists(dir)
local slashes = utils.osType == "windows" and "\\" or "/"
return utils.fileExists(dir .. slashes)
end
function utils.createDirectory(dir)
os.execute("mkdir " .. dir)
end
function utils.getListOfFiles(dir)
local files = {}
local loop = utils.osType == "windows" and 'dir "' .. dir .. '" /b' or "ls -pa " .. dir .. " | grep -v /"
for file in io.popen(loop):lines() do
files[#files + 1] = file
end
return files
end
function utils.getScriptDir()
local dir = debug.getinfo(2, "S").source
if dir:sub(1, 1) == "@" then
dir = dir:sub(2)
end
local path
if not dir:match("^/") or not dir:match("^%a:") then
path = (os.getenv("PWD") or io.popen("cd"):read("*l")) .. "/" .. dir
else
path = dir
end
path = path:gsub(utils.slash, "/")
return dir:match("(.*/)")
end
function utils.expandPath(path)
if path:sub(1, 1) == "~" then
local home = os.getenv("HOME") or "~"
path = home .. path:sub(2)
end
path = path:gsub("%$(%w+)", function(env)
return os.getenv(env) or ("$" .. env)
end)
return path
end
function utils.isModuleAvailable(name)
if package.loaded[name] then
return true
else
for _, searcher in ipairs(package.searchers or package.loaders) do
local loader = searcher(name)
if type(loader) == "function" then
package.preload[name] = loader
return true
end
end
return false
end
end
return utils