How to fetch git commit info in `mix.exs` when on Gigalixir

I am using Gigalixir to deploy our Phoenix app, it’s really easy and makes life better.

For my app I want to add some info from current commit like sha of the commit and the time of the commit.

I used git show -s --format=%h and git log -1 --date=raw --format=%cd and all I got is fatal: bad object HEAD.

I don’t know what Gigalixir does when deploying and what I can do with git command.
Do you guys have any ideas?

1 Like

The idea is from this post: Add git commit info to your Elixir Phoenix app – Fiqus

I used the code below in my mix.exs, to write a VERSION file when mix deps.get or mix phx.server:

# ...
   defp aliases do
    [
      "deps.get": [&update_version/1, "deps.get"],
      "phx.server": [&update_version/1, "phx.server"],
      setup: ["deps.get", "ecto.setup", "cmd npm install --prefix assets"],
      "ecto.setup": ["ecto.create", "ecto.migrate", "run priv/repo/seeds.exs"],
      "ecto.reset": ["ecto.drop", "ecto.setup"],
      test: ["ecto.create --quiet", "ecto.migrate --quiet", "test"]
    ]
  end

  defp version(), do: "0.1.0"

  defp update_version(_) do
    contents = [
      version(),
      get_commit_sha(),
      get_commit_date()
    ]

    Mix.shell().info("Updating version with: #{inspect(contents)}")
    File.write("VERSION", Enum.join(contents, "\n"), [:write])
  end

  defp get_commit_sha() do
    System.cmd("git", ~w|show -s --format=%h|)
    |> elem(0)
    |> String.trim()
  end

  defp get_commit_date() do
    [sec, tz] =
      System.cmd("git", ~w|log -1 --date=raw --format=%cd|)
      |> elem(0)
      |> String.split(~r/\s+/, trim: true)
      |> Enum.map(&String.to_integer/1)

    DateTime.from_unix!(sec + tz * 36)
  end

It works well on my dev machine so I want to know how to achieve things like this on Gigalixir.

I am on the same boat, I cannot execute git in Gigalixir via System.cmd/3. Did you manage to sort this out @tannineo?

Not a solution for the given problem, but probably an alternative.
If all you want is the commit SHA.
Nearly every CI system gives you access to the commit SHA via an environment variable.
It seems to also be true for Gigalixir → SOURCE_VERSION

System.get_env("SOURCE_VERSION")

Take with caution. I don’t use Gigaelixir.

1 Like