Module documentation not immediatelly available after ensuring then module is compiled

I’m trying to fetch the documentation of a module right after it is compiled, in order to process it. I use the following code to check if the module was compiled. Even though I check if the function whose docs I’m searching exists, I get an error-status when I call Code.fetch_docs/1.

Are there any additional checks I should perform?

if command_compiled?(module, function, arity) do
  docs = fetch_docs(module, function, arity)
  # process docs
else
  IO.warn("#{scope.module}.#{function}/#{arity} does not exist")
  nil
end 

# Helper functions
defp command_compiled?(module, name, arity) do
    case Code.ensure_compiled(module) do
      {:module, ^module} -> function_exported?(module, name, arity)
      _ -> false
    end
  end

defp fetch_docs(module, function, arity) do
    {_, _, _, _, _, _, functions} = Code.fetch_docs(module) # {:error, :module_not_found}

    matcher = fn
      {{:function, ^function, ^arity}, _, _, %{"en" => docs}, _} -> docs
      _ -> nil
    end

    Enum.find_value(functions, matcher)
  end

Someone pointed out that I should provide some code in order to reproduce this error. I didn’t think about it at 1am, but now I you have the luxury to share my pain. GitHub - Awlexus/problematic: Some code that won't compile

1 Like

That’s correct. The documentation is read from the .beam file on disk and the .beam file is only written to disk after all modules have been compiled to avoid dirty state if the compilation fails later on.

2 Likes

I suspected something like this, but didn’t know that the files are written only after everything is done, thank you!