util: Add removePath (#10129)

Will attempt to prune empty directories from the given path, going as far back up as possible.
reviewable/pr10135/r1
NiLuJe 1 year ago committed by GitHub
parent 328670b515
commit 08b0c088e5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -1 +1 @@
Subproject commit cea0a73556679b2d36fe9b8e9370b3377d785117
Subproject commit 96b2a16e685a75de1b7fcfe30b9dd19d54f5f306

@ -781,7 +781,7 @@ function util.makePath(path)
for component in path:gmatch("([^/]+)") do
-- The trailing slash ensures we properly fail via mkdir if the composite path already exists as a file/link
components = components .. component .. "/"
if not util.pathExists(components) then
if lfs.attributes(components, "mode") == nil then
success, err = lfs.mkdir(components)
if not success then
return nil, err .. " (creating `" .. components .. "` for `" .. path .. "`)"
@ -792,6 +792,30 @@ function util.makePath(path)
return success, err
end
--- Remove as many of the empty directories specified in path, children-first.
-- Does not fail if the directory is already gone.
-- @string path the directory tree to prune
-- @treturn bool true on success; nil, err_message on error
function util.removePath(path)
local component = path
repeat
local attr = lfs.attributes(component, "mode")
if attr == "directory" then
local success, err = lfs.rmdir(component)
if not success then
-- Most likely because ENOTEMPTY ;)
return nil, err .. " (removing `" .. component .. "` for `" .. path .. "`)"
end
elseif attr ~= nil then
return nil, "Encountered a component that isn't a directory" .. " (removing `" .. component .. "` for `" .. path .. "`)"
end
local parent = BaseUtil.dirname(component)
component = parent
until parent == "." or parent == "/"
return true, nil
end
--- As `rm`
-- @string path of the file to remove
-- @treturn bool true on success; nil, err_message on error

Loading…
Cancel
Save