Created
October 2, 2013 19:24
-
-
Save cy6erGn0m/6799153 to your computer and use it in GitHub Desktop.
Yet another directory recursive delete function for Erlang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
ensureDirSlash(Dir, Child) -> | |
case lists:suffix("/", Dir) of | |
true -> Dir ++ Child; | |
false -> Dir ++ "/" ++ Child | |
end. | |
-spec deleteDir(Dir :: nonempty_string()) -> none(). | |
deleteDir(Dir) -> | |
case {filelib:is_dir(Dir), isFileOrLink(Dir)} of | |
{_, true} -> throw("The specified path is not a directory: " ++ Dir); | |
{true, _} -> deleteDirImpl([Dir]); | |
{false, _} -> ok %% nothing to delete; | |
end. | |
isFileOrLink(F) -> filelib:is_regular(F) or (ok == element(1, file:read_link(F))). | |
deleteDirImpl([]) -> ok; | |
deleteDirImpl([Current | Rest]) -> | |
{ok, ChildrenNames} = file:list_dir(Current), | |
Children = lists:map(fun(F) -> ensureDirSlash(Current, F) end, ChildrenNames), | |
{FilesOnly, DirsOnly} = lists:partition(fun isFileOrLink/1, Children), | |
lists:foreach(fun(F) -> ok = file:delete(F) end, FilesOnly), | |
if | |
length(DirsOnly) == 0 -> ok = file:del_dir(Current), deleteDirImpl(Rest); | |
true -> deleteDirImpl(DirsOnly ++ [Current] ++ Rest) | |
end. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment