Skip to content

Commit

Permalink
update callers to add callers/3 fn.
Browse files Browse the repository at this point in the history
Use mod, fn, arity to match.
  • Loading branch information
ckoch-cars committed Sep 24, 2021
1 parent 86b298e commit bab3323
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 0 deletions.
26 changes: 26 additions & 0 deletions lib/ex_factor/callers.ex
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,32 @@ defmodule ExFactor.Callers do
|> mangle_list()
end

def callers(mod, func, arity) do
Mix.Tasks.Xref.calls([])
|> Enum.filter(fn x ->
x.callee == {cast(mod), cast(func), arity}
end)
end

def cast(value) when is_atom(value), do: value
def cast(value) do
cond do
String.downcase(value) == value -> String.to_atom(value)
true ->
cast_module(value)
end
end

def cast_module(module) do
if String.match?(module, ~r/Elixir\./) do
module
else
"Elixir." <> module
end
|> Module.split()
|> Module.concat()
end

defp mangle_list([""]), do: []
defp mangle_list(["Compiling" <> _ | tail]), do: mangle_list(tail)

Expand Down
30 changes: 30 additions & 0 deletions test/ex_factor/callers_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,34 @@ defmodule ExFactor.CallersTest do
assert [] = Callers.callers(ExFactor.NotAModule)
end
end

describe "callers/3" do
test "it should report callers of a module" do
[one, _two, _three] = Callers.callers(ExFactor.Parser, :all_functions, 1)

assert one.caller_module == ExFactor.Callers
assert one.file == "lib/ex_factor/callers.ex"
assert one.line == 9
end

test "it converts strings to atoms" do
[one, _two, _three] = Callers.callers("ExFactor.Parser", "all_functions", 1)

assert one.caller_module == ExFactor.Callers
assert one.file == "lib/ex_factor/callers.ex"
assert one.line == 9
end

test "when the module is invalid" do
assert [] = Callers.callers("ExFactor.NotParser", "all_functions", 1)
end

test "when the function is invalid" do
assert [] = Callers.callers("ExFactor.Parser", "not_a_function", 1)
end

test "when the arity doesn't match" do
assert [] = Callers.callers("ExFactor.Parser", "all_functions", 7)
end
end
end

0 comments on commit bab3323

Please sign in to comment.