Current section
Files
Jump to
Current section
Files
lib/git_auto_version.ex
defmodule GitAutoVersion do
require Logger
@moduledoc """
This simple library answers the age-old question of "how the f*ck do I version my elixir apps?".
By putting one line of code in your application, you'll be able to version your application
with git tags instead of making code changes.
### Prerequisites
- You must have git installed on your system
- You must tag your application with semvers in the pattern v(major).(minor).(patch).
Notice that there is a leading `v` on the tag
### How it works
In your fil `mix.exs` file, replace the version in config with
```
def project do
[
version: GitAutoVersion.version()
]
end
```
It's as simple as that! Make sure you have at least one tag or the version will default
to 0.1.0
Under the hood, this module uses [git-describe] to get the most recent tag. If your HEAD
is not at a tag, it will append the number of commits and short git hash to the end of
the version. So it should look something like this: `v0.2.1-3-g9af321`.
Also note that when you put a new tag on your application, you have to recompile the code
for this module to pick up the changes. So after you tag it, run a quick `mix do clean, compile`
"""
@doc """
Attepmpts to get the version from your git tags by using `git describe --tags --mathch='v*'`
"""
@spec version() :: String.t
def version do
with {:ok, git_exec} <- find_git(),
{:ok, version} <- get_version(git_exec)
do
version
else
_ ->
Logger.debug("GitAutoVersion defaulting version to 0.1.0")
"0.1.0"
end
end
defp find_git do
case System.find_executable("git") do
nil ->
Logger.debug("GitAutoVersion cannot find git on your system")
{:error, :no_git}
git_exec ->
{:ok, git_exec}
end
end
defp get_version(git_exec) do
version =
git_exec
|> System.cmd(["describe", "--tags", "--match='v*'"])
|> elem(0)
|> String.trim()
|> String.replace(~r{^v}, "")
case Version.parse(version) do
{:ok, _vsn} ->
{:ok, version}
:error ->
Logger.debug("GitAutoVersion cannot parse the git tag version #{version}")
{:error, :invalid_version}
end
end
end