However I have noticed that Application.spec/1 returns nil at compile time. Is there a way to read and store an application version at compile time? Or is the version only known AFTER compilation?
You cannot access the application spec because your application is being compiled. Fortunately, you can access information about your Mix project like this:
defmodule Foo do
IO.inspect(Mix.Project.config()[:version])
end
You can grab information about your deps in that project config too.
I believe the dep apps are automatically loaded (if not, you can Application.load/1 them) so you can definitely call Application.spec/1 and it will work
your MixProject module is nothing special, it’s a module like any other (I mean aside from the fact that it’s only available at compile time). Make the deps/0 function public instead of private, and you’re good to go.
it just occurred to me that won’t tell you what the version is, just what version you wanted. You could also read the mix.lock file using Code.eval_file/1
I’m not sure it is expensive (a benchmark would give us some clues here), I haven’t noticed any timing issue when running my app with :application.get_key(:myapp, :vsn)