How to check if an imported name is used in a module?

I want to check if all the names being imported in a module are being used somewhere, and return a list of names that aren’t being used in the module. The simple way to do this is to grep for every name, but I was wondering if someone has automated this.

E.g. in the following case

julia> module A
           f(x) = x
           g(x) = x^2
       end

julia> module B
          import Main.A: f, g
          h(x) = f(x)
       end

I want the search on B to return g.

A naive solution that I thought of, assuming that I have the list of imported names available, is

function count_names(v)
	@assert isdir("src")
	count = zeros(Int, length(v))
	for (root, dirs, files) in walkdir("src")
		for fname in files
			f = joinpath(root, fname)
			open(f, "r") do io
				for line in eachline(io)
					for (ind, name) in enumerate(v)
						if occursin(name, line)
							count[ind] += 1
						end
					end
				end
			end
		end
	end
	v[count .== 1]
end
1 Like