-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpath_util.lua
More file actions
68 lines (60 loc) · 1.58 KB
/
path_util.lua
File metadata and controls
68 lines (60 loc) · 1.58 KB
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
local path_util = {}
---@param s string
---@param c string?
---@return string
function path_util.fix_illegal(s, c)
return (s:gsub('[/\\?%*:|"<>]', c or "_"))
end
---@param s string
---@return string
function path_util.fix_separators(s)
return (s:gsub('[\\¥]', "/"))
end
---@param path string
---@return string
function path_util.dirname(path)
path = path_util.fix_separators(path)
local dir = path:match("^(.+)/[^/]+$")
return dir or ""
end
---@param ... string?
---@return string
function path_util.join(...)
local t = {}
for i = 1, select("#", ...) do
local p = select(i, ...)
if p then
p = tostring(p):gsub("\\", "/"):gsub("/[^/]-/%.%./", "/")
table.insert(t, p)
end
end
return table.concat(t, "/")
end
---@param name string
---@param lower boolean?
---@return string?
function path_util.ext(name, lower)
---@type string?
local ext = name:match("^.+%.(.-)$")
if ext and lower then
ext = ext:lower()
end
return ext
end
---@param name string
---@return string
---@return string?
function path_util.name_ext(name)
local _name, ext = name:match("^(.+)%.([^%.]-)$")
if not _name then
return name
end
return _name, ext
end
assert(table.concat({path_util.name_ext("file.zip")}, " ") == "file zip")
assert(table.concat({path_util.name_ext("file.zip.zip")}, " ") == "file.zip zip")
assert(table.concat({path_util.name_ext(".file")}, " ") == ".file")
assert(table.concat({path_util.name_ext("..file")}, " ") == ". file")
assert(table.concat({path_util.name_ext("...file")}, " ") == ".. file")
assert(table.concat({path_util.name_ext(".file.zip")}, " ") == ".file zip")
return path_util