vrod
Get app versions at compile time?
I encountered this interesting thing while trying to add more info to Logger messages.
I can get the version of an app by running something like this:
:myapp
|> Application.spec()
|> Keyword.get(:vsn)
|> List.to_string()
However, I thought this calculation maybe is expensive, so I tried to save this at compile time by putting it into a module attribute:
@app_ver :myapp
|> Application.spec()
|> Keyword.get(:vsn)
|> List.to_string()
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?
Most Liked
wojtekmach
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
wojtekmach
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 
vrod
I found solution to this: just add mix.lock to .formatter.exs:
[
inputs: ["{mix,.formatter}.exs", "{config,lib,test}/**/*.{ex,exs}", "mix.lock"]
]
and then the above works!
jpcaruana
for me, this works very well:
{:ok, version} = :application.get_key(:myapp, :vsn)
Logger.info("Application xxx #{version}: started")
cenotaph
I doubt any measurable performance drawbacks will occur with the following
<%= Application.get_env(:ex, :env) %>:<%= Application.spec(:ex, :vsn) %>








