/
grapherl.erl
258 lines (227 loc) · 8.48 KB
/
grapherl.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
%%==============================================================================
%% Copyright 2010 Erlang Solutions Ltd.
%%
%% Licensed under the Apache License, Version 2.0 (the "License");
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% http://www.apache.org/licenses/LICENSE-2.0
%%
%% Unless required by applicable law or agreed to in writing, software
%% distributed under the License is distributed on an "AS IS" BASIS,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%==============================================================================
%% @author Adam Lindberg <eproxus@gmail.com>
%% @doc Create graphs of Erlang systems and programs.
%%
%% Valid options are the following:
%% <dl>
%% <dt>`type'</dt><dd>The type of the file as an atom. This can be
%% all extensions that graphviz (`dot') supports. Default is `png'.</dd>
%% <dt>`open'</dt><dd>Command to run on resulting file as a
%% string. This command will with the output file generated from
%% `dot' as input.</dd>
%% <dt>`verbose'</dt><dd>Make `xref' verdbose. Default is `false'.</dd>
%% <dt>`warnings'</dt><dd>Make `xref' print warnings. Default is `false'</dd>
%% </dl>
-module(grapherl).
-copyright("Erlang Solutions Ltd.").
-author("Adam Lindberg <eproxus@gmail.com>").
-export([main/1]).
-export([applications/2]).
-export([applications/3]).
-export([modules/2]).
-export([modules/3]).
-ifdef(TEST).
-include("grapherl_tests.hrl").
-endif.
%%==============================================================================
%% API Functions
%%==============================================================================
%% @hidden
main(Args) ->
{ok, {Flags, _Rest} = Options} = getopt:parse(options(), Args),
case lists:member(help, Flags) of
true -> print_options(), halt(0);
false -> run(Options)
end.
run({Options, [Dir, Target]}) ->
case get_mode(Options) of
{app, RestOpt} -> run(applications, [Dir, Target, RestOpt]);
{mod, RestOpt} -> run(modules, [Dir, Target, RestOpt])
end;
run({_Options, _Other}) ->
print_options(), halt(1).
get_mode(Options) ->
case proplists:split(Options, [app, mod]) of
{[[app], []], Rest} -> {app, Rest};
{[[], [mod]], Rest} -> {mod, Rest}
end.
options() ->
[{help, $h, "help", undefined,
"Display this help text"},
{mod, $m, "modules", undefined,
"Analyse module dependencies (mutually exclusive)"},
{app, $a, "applications", undefined,
"Analyse application dependencies (mutually exclusive)"},
{type, $t, "type", string,
"Output file type (also deduced from file name)"}].
print_options() ->
getopt:usage(options(), filename:basename(escript:script_name()),
"SOURCE OUTPUT",
[{"SOURCE", "The source directory to analyse"},
{"OUTPUT", "Target ouput file"}]).
run(Fun, Args) ->
try apply(?MODULE, Fun, Args) of
ok ->
halt(0);
{error, Error} ->
io:format("grapherl: error: ~p~n", [Error]),
halt(2)
catch
error:type_not_specified ->
io:format("grapherl: error: File type not specified~n"),
halt(2)
end.
%% @equiv applications(Dir, Target, [{type, png}])
applications(Dir, Target) ->
applications(Dir, Target, [{type, png}]).
%% @doc Generate an application dependency graph based on function calls.
%%
%% `Dir' is the library directory of the release you want to graph. `Target'
%5 is the target filename (without extension).
applications(Dir, Target, Options) ->
check_dot(),
try
initialize_xref(?MODULE, Options),
ok(xref:add_release(?MODULE, Dir, {name, ?MODULE})),
Excluded = ifc(proplists:is_defined(include_otp, Options),
[], otp_apps())
++ proplists:get_value(excluded, Options, []),
{ok, Results} = xref:q(?MODULE, "AE"),
Relations = [uses(F, T) ||
{F, T} <- Results,
F =/= T,
not lists:member(F, Excluded),
not lists:member(T, Excluded)],
create(["node [shape = tab];"] ++ Relations, Target, Options),
stop_xref(?MODULE)
catch
throw:Error ->
stop_xref(?MODULE),
Error
end.
%% @equiv application(App, Target, [{type, png}])
modules(Dir, Target) ->
modules(Dir, Target, []).
%% @doc Generate a module dependency graph for an application.
%%
%% `Dir' is the directory of the application. `Target' is the target
%% filename (without extension).
%%
%% All modules in the `ebin' folder in the directory specified in
%% `Dir' will be included in the graph. The option `no_ebin' will, if
%% set to true or just included as an atom, use the `Dir' directory as
%% a direct source for .beam files.
modules(Dir, Target, Options) ->
%% TODO: Thickness of arrows could be number of calls?
check_dot(),
try
initialize_xref(?MODULE, Options),
Path = get_path(Dir),
ok(xref:add_directory(?MODULE, Path)),
Modules = case ok(xref:q(?MODULE, "AM")) of
[] -> throw({error, no_modules_found});
Else -> Else
end,
Query = "ME ||| ["
++ string:join(["'" ++ atom_to_list(M) ++ "'" || M <- Modules], ",")
++ "]",
{ok, Results} = xref:q(?MODULE, Query),
Relations = [uses(F, T) || {F, T} <- Results, F =/= T],
create(["node [shape = box];"]
++ [["\"" ++ atom_to_list(M) ++ "\"", $;] || M <- Modules]
++ Relations, Target, Options),
stop_xref(?MODULE)
catch
throw:Error ->
stop_xref(?MODULE),
Error
end.
%%==============================================================================
%% Internal Functions
%%==============================================================================
get_path(Dir) ->
case filelib:wildcard(filename:join(Dir, "*.beam")) of
[] -> filename:join(Dir, "ebin");
_Beams -> Dir
end.
initialize_xref(Name, Options) ->
case xref:start(Name) of
{error, {already_started, _}} ->
stop_xref(Name),
xref:start(Name);
{ok, _Ref} ->
ok
end,
XRefOpts = [{verbose, proplists:is_defined(verbose, Options)},
{warnings, proplists:is_defined(warnings, Options)}],
ok = xref:set_default(Name, XRefOpts).
stop_xref(Ref) ->
xref:stop(Ref),
ok.
get_type(Options, Target) ->
case proplists:get_value(type, Options) of
undefined -> type_from_filename(Target);
Type when is_atom(Type) -> atom_to_list(Type);
Type -> Type
end.
type_from_filename(Filename) ->
case filename:extension(Filename) of
"" -> erlang:error(type_not_specified);
"." ++ Type -> Type
end.
file(Lines) ->
["digraph application_graph {", Lines, "}"].
uses(From, To) ->
["\"" ++ atom_to_list(From) ++ "\"", " -> ",
"\"" ++ atom_to_list(To) ++ "\"", $;].
create(Lines, Target, Options) ->
case dot(file(Lines), Target, get_type(Options, Target)) of
{"", File} ->
case proplists:get_value(open, Options) of
undefined -> ok;
Command -> os:cmd(Command ++ " " ++ File), ok
end;
{Error, _File} ->
{error, hd(string:tokens(Error, "\n"))}
end.
check_dot() ->
case os:cmd("dot -V") of
"dot " ++ _ ->
ok;
_Else ->
erlang:error("dot was not found, please install graphviz",[])
end.
dot(File, Target, Type) ->
TmpFile = string:strip(os:cmd("mktemp -t " ?MODULE_STRING ".XXXX"), both, $\n),
ok = file:write_file(TmpFile, File),
TargetName = add_extension(Target, Type),
Result = os:cmd(io_lib:format("dot -T~p -o~p ~p",
[Type, TargetName, TmpFile])),
ok = file:delete(TmpFile),
{Result, TargetName}.
add_extension(Target, Type) ->
case filename:extension(Target) of
"." ++ Type -> Target;
_Else -> Target ++ "." ++ Type
end.
otp_apps() ->
{ok, Apps} = file:list_dir(filename:join(code:root_dir(), "lib")),
[list_to_atom(hd(string:tokens(A, "-"))) || A <- Apps].
ok({ok, Result}) -> Result;
ok(Error) -> throw(Error).
ifc(true, True, _) -> True;
ifc(false, _, False) -> False.