--@action Remove empty folders --@version 1.0.0 --@author TheFile.Ninja --@id remove-empty-folders --@description Finds the folders below the active pane's that hold nothing, or only other empty folders, shows them, and sends them to the Recycle Bin. --@tags cleanup --@requires file_write -- A folder with a single hidden file in it (desktop.ini, Thumbs.db) is not -- empty: it is kept. One delete for all of them, so one Ctrl+Z brings them -- all back. local p = pane.active() if p:is_virtual() then ui.message("This works on a folder on a disk or a share.", "Remove empty folders") return end local root = p:path() -- Paths compared without case and without a trailing backslash. local function key(s) return (s:gsub("[\\/]+$", "")):lower() end local top = key(root) local entries = fs.list(root, { recursive = true }) if #entries >= 100000 then -- fs.list stops at 100 000: a folder it did not get to could look empty. ui.message("There is too much below " .. root .. " to be sure. Run it in a smaller folder.", "Remove empty folders", "warning") return end -- Every folder above a file holds something. local holds = {} for _, e in ipairs(entries) do if not e.is_directory then local dir = path.parent(e.full_path) while dir ~= "" and key(dir) ~= top and not holds[key(dir)] do holds[key(dir)] = true dir = path.parent(dir) end end end -- The empty folders whose parent is not empty itself: deleting those takes the rest. local empty = {} for _, e in ipairs(entries) do if e.is_directory and not holds[key(e.full_path)] then local parent = key(path.parent(e.full_path)) if parent == top or holds[parent] then empty[#empty + 1] = e.full_path end end end if #empty == 0 then ui.message("No empty folders below " .. root .. ".", "Remove empty folders") return end table.sort(empty) local lines = {} for i = 1, math.min(#empty, 25) do lines[i] = " " .. empty[i]:sub(#root + 2) end if #empty > 25 then lines[#lines + 1] = " … and " .. (#empty - 25) .. " more" end if ui.confirm(#empty .. " empty folder(s) to the Recycle Bin?\n\n" .. table.concat(lines, "\n"), "Remove empty folders") then file_ops.delete(empty) ui.status(#empty .. " empty folder(s) to the Recycle Bin; Ctrl+Z brings them back") end