Access project version within elixir application

自古美人都是妖i 提交于 2019-12-21 03:18:22

问题


I have an elixir project with a defined version. How can I access this from within the running application.

in mix.exs

  def project do
    [app: :my_app,
     version: "0.0.1"]
  end

I would like to be access this version number in the application so I can add it to the returned message. I looking for something in the env hash like the following

__ENV__.version
# => 0.0.1

回答1:


Here's a similar approach to retrieve the version string. It also relies on the :application module, but is maybe a bit more straightforward:

{:ok, vsn} = :application.get_key(:my_app, :vsn)
List.to_string(vsn)



回答2:


Mix.Project itself provides access to all project keywords defined in mix.exs using its config/0 (api doc) function. For concise access it might be wrapped into a function:

@version Mix.Project.config[:version]
def version(), do: @version



回答3:


In recent versions of Elixir, the Application module now wraps this for you:

https://github.com/elixir-lang/elixir/blob/master/lib/elixir/lib/application.ex

Application.spec(:my_app, :vsn)




回答4:


I found the version inside of :application.which_applications, but it requires some parsing:

defmodule AppHelper do
  @spec app_version(atom) :: {integer, integer, integer}
  def app_version(target_app) do
    :application.which_applications
    |> Enum.filter(fn({app, _, _}) ->
                    app == target_app
                   end)
    |> get_app_vsn
  end

  # I use a sensible fallback when we can't find the app,
  # you could omit the first signature and just crash when the app DNE.
  defp get_app_vsn([]), do: {0,0,0} 
  defp get_app_vsn([{_app, _desc, vsn}]) do
    [maj, min, rev] = vsn
                      |> List.to_string
                      |> String.split(".")
                      |> Enum.map(&String.to_integer/1)
    {maj, min, rev}
  end
end

And then for usage:

iex(1)> AppHelper.app_version(:logger)
{1, 0, 5}

As always, there's probably a better way.




回答5:


What about :

YourApp.Mixfile.project[:version]



回答6:


Application.spec(:my_app, :vsn) works when the application is started. If you're in a Mix task and you don't need to start the application, in Elixir 1.8 you can use:

MyApp.MixProject.project |> Keyword.fetch!(:version)


来源:https://stackoverflow.com/questions/32968253/access-project-version-within-elixir-application

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!