forked from rosejn/lua-util
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathfile.lua
90 lines (69 loc) · 2.01 KB
/
file.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
require 'os'
require 'fs'
require 'paths'
-- Boolean predicate to determine if a path points to a valid file or directory.
function is_file(path)
return paths.filep(path) or paths.dirp(path)
end
-- Assert that a file exists.
function assert_file(path, msg)
if not is_file(path) then
assert(false, msg)
end
end
-- Check that a data directory exists, and create it if not.
function check_and_mkdir(dir)
if not paths.filep(dir) then
fs.mkdir(dir)
end
end
-- Decompress a .tgz or .tar.gz file.
function decompress_tarball(path)
os.execute('tar -xvzf ' .. path)
end
-- unzip a .zip file
function unzip(path)
os.execute('unzip ' .. path)
end
-- gunzip a .gz file
function gunzip(path)
os.execute('gunzip ' .. path)
end
-- Decompress tarballs and zip files, using the suffix to determine which
-- method to use.
function decompress_file(path)
if string.find(path, "%.tar%.gz$") or string.find(path, "%.tgz$") then
decompress_tarball(path)
elseif string.find(path, "%.zip$") or string.find(path, "%.gz$") then
unzip(path)
elseif string.find(path, "%.gz$") or string.find(path, "%.gzip$") then
gunzip(path)
else
print("Don't know how to decompress file: ", path)
end
end
-- Download the file at location url.
function download_file(url)
local protocol, scpurl, filename = url:match('(.-)://(.*)/(.-)$')
if protocol == 'scp' then
os.execute(string.format('%s %s %s', 'scp', scpurl .. '/' .. filename, filename))
else
os.execute('wget ' .. url)
end
end
-- Temporarily changes the current working directory to call fn, returning its
-- result.
function do_with_cwd(path, fn)
local cur_dir = fs.cwd()
fs.chdir(path)
local res = fn()
fs.chdir(cur_dir)
return res
end
-- Check that a file exists at path, and if not downloads it from url.
function check_and_download_file(path, url)
if not paths.filep(path) then
do_with_cwd(paths.dirname(path), function() download_file(url) end)
end
return path
end