-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlib_find.erl
53 lines (46 loc) · 1.27 KB
/
lib_find.erl
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
-module(lib_find).
-export([files/3, files/5]).
-include_lib("kernel/include/file.hrl").
files(Dir, Re, Flag) ->
Re1 = regexp:sh_to_awk(Re),
lists:reverse(files(Dir, Re1, Flag, fun(File, Acc) ->[File|Acc] end, [])).
files(Dir, Reg, Recursive, Fun, Acc) ->
case file:list_dir(Dir) of
{ok, Files} -> find_files(Files, Dir, Reg, Recursive, Fun, Acc);
{error, _} -> Acc
end.
find_files([File|T], Dir, Reg, Recursive, Fun, Acc0) ->
FullName = Dir ++ [$/|File],
case file_type(FullName) of
regular ->
case regexp:match(FullName, Reg) of
{match, _, _} ->
Acc = Fun(FullName, Acc0),
find_files(T, Dir, Reg, Recursive, Fun, Acc);
_ ->
find_files(T, Dir, Reg, Recursive, Fun, Acc0)
end;
directory ->
case Recursive of
true ->
Acc1 = files(FullName, Reg, Recursive, Fun, Acc0),
find_files(T, Dir, Reg, Recursive, Fun, Acc1);
false ->
find_files(T, Dir, Reg, Recursive, Fun, Acc0)
end;
error ->
find_files(T, Dir, Reg, Recursive, Fun, Acc0)
end;
find_files([], _, _, _, _, A) ->
A.
file_type(File) ->
case file:read_file_info(File) of
{ok, Facts} ->
case Facts#file_info.type of
regular -> regular;
directory -> directory;
_ -> error
end;
_ ->
error
end.