Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Erlang: programmatically get application version

Tags:

erlang

I have an OTP application. The version of this application is found in two places: the src/application_name.src file (standard with OTP applications), and in my rebar.config.

Is there an "official" way for an application to get it's own version, or does this need to be hacked via sed/grep etc? I want to have an "info" endpoint in my application that prints it's own version. Of course I can always do something like grep the version out of my rebar.config, but it seems hacky.

like image 710
Tommy Avatar asked Dec 14 '22 23:12

Tommy


2 Answers

According to the Erlang documentation you can use API of application module.

Example:

Erlang/OTP 19 [erts-8.2.2] [source-1ca84a4] [64-bit] [smp:4:4] [async-threads:10] [hipe] [kernel-poll:false]

Eshell V8.2.2  (abort with ^G)
1> application:loaded_applications().
[{stdlib,"ERTS  CXC 138 10","3.2"},
{kernel,"ERTS  CXC 138 10","5.1.1"}]

2> GetVer = 
fun(App) ->
    case lists:keyfind(App, 1, application:loaded_applications()) of
        {_, _, Ver} ->
            Ver;
        false ->
            not_found
    end
end.
#Fun<erl_eval.6.52032458>

3> GetVer(stdlib).
"3.2"

4> GetVer(eunit). 
not_found

5> application:load(eunit).
ok

6> GetVer(eunit).          
"2.3.2"

7>
like image 191
Pouriya Avatar answered Dec 26 '22 09:12

Pouriya


If it is properly packaged as an application, you can get it using application:which_applications(). I have some sample code, but basically you'd do something like this:

vsn() -> vsn(your_application_atom_name).

vsn(Application) -> vsn(Application, application:which_applications()).
vsn(_Application, []) -> undefined;
vsn(Application, [{Application,_,Vsn}|_]) -> Vsn;
vsn(Application, [_|Rest]) -> vsn(Application, Rest).

The downside is that you do have to hardcode the name of your application (as an atom). I never found a way around this, but you might be able to cook something up.

like image 37
mipadi Avatar answered Dec 26 '22 07:12

mipadi