Skip to content

Instantly share code, notes, and snippets.

@cy6erGn0m
Created October 2, 2013 19:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cy6erGn0m/6799153 to your computer and use it in GitHub Desktop.
Save cy6erGn0m/6799153 to your computer and use it in GitHub Desktop.
Yet another directory recursive delete function for Erlang
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