Is there a way to get mix xref to show me exports that are not used

Hi folks,

I was trying to find a way to get mix xref to show me the functions that my modules export when they should not be exported. Basically, what we get in Erlang with rebar3 or xref_runner if we add exports_not_used to the list of warnings (more info here).

Is there any way to specifically tell mix xref to run xref:analyze/2,3 with the parameters I want?

Thanks in advance.

2 Likes

Just as a clarification - mix xref has nothing to do with the Erlang’s xref module. Elixir does its own analysis based on data gathered during compilation of Elixir modules. The Erlang’s xref was just too slow to run on every compilation like the Elixir’s analysis does.

I see… OK. In any case, is there any way to use it to find functions that a module exports but no other module uses in my codebase?

I have checked and it should be possible to do so. I am working on simple mix task that will be able to do so.

1 Like

First “quick and dirty” example https://github.com/hauleth/mix_unused. Adds new mix command mix unused that will list unused functions.

4 Likes

You may want to try:

server = :my_xref_server
{:ok, pid} = :xref.start(server)
Enum.each(:code.get_path(), &:xref.add_directory(server, &1, {:warnings, false}))
{:ok, unused_exports} = :xref.q(server, ~c"X - XU")

Here X - XU is a query that means "Exported" minus "Exported and Used", which essentially leaves you with Exported and Unused. See these references for more advanced queries and a reference:

But be prepare to do some aggressive filtering of the results. For example, drop modules not belonging to your app, structs, etc.