defmodule GitGud.GitTest do
use ExUnit.Case, async: true
alias GitGud.Git
@moduletag :git_required
setup do
if System.find_executable("git") == nil do
{:skip, "git not on PATH"}
else
dir =
Path.join(System.tmp_dir!(), "gitgud-git-test-#{System.unique_integer([:positive])}")
on_exit(fn -> _ = File.rm_rf(dir) end)
File.mkdir_p!(dir)
{:ok, dir: dir}
end
end
test "init_bare creates a bare repo", %{dir: dir} do
assert :ok = Git.init_bare(dir)
assert File.exists?(Path.join(dir, "HEAD"))
assert File.exists?(Path.join(dir, "objects"))
end
test "round-trip blob + tree + commit via plumbing", %{dir: dir} do
:ok = Git.init_bare(dir)
# Write a blob via tempfile.
tmp = Path.join(System.tmp_dir!(), "git-test-blob-#{System.unique_integer([:positive])}")
File.write!(tmp, "hello\n")
on_exit(fn -> _ = File.rm(tmp) end)
{hex_blob, 0} =
System.cmd("git", ["-C", dir, "hash-object", "-w", tmp], stderr_to_stdout: false)
{:ok, blob_sha} = Git.from_hex(String.trim(hex_blob))
assert {:ok, meta} = Git.blob_meta(dir, blob_sha)
assert meta.size == 6
assert meta.is_binary == false
# Build a tree with that blob and commit it.
index = Path.join(System.tmp_dir!(), "git-test-index-#{System.unique_integer([:positive])}")
on_exit(fn -> _ = File.rm(index) end)
{_, 0} =
System.cmd(
"git",
[
"-C",
dir,
"update-index",
"--add",
"--cacheinfo",
"100644," <> Git.to_hex(blob_sha) <> ",hello.txt"
],
env: [{"GIT_INDEX_FILE", index}]
)
{tree_hex, 0} =
System.cmd("git", ["-C", dir, "write-tree"], env: [{"GIT_INDEX_FILE", index}])
{:ok, tree_sha} = Git.from_hex(String.trim(tree_hex))
assert {:ok, commit_sha} =
Git.commit_tree(dir, tree_sha, [], "initial",
author: {"Test", "test@example.com", DateTime.utc_now(:second)}
)
assert :ok = Git.update_ref(dir, "refs/heads/main", commit_sha, nil)
# List refs picks it up.
assert {:ok, refs} = Git.list_refs(dir)
assert Enum.any?(refs, &(&1.name == "refs/heads/main" and &1.target_sha == commit_sha))
# tree() returns the entry we put in.
assert {:ok, entries} = Git.tree(dir, tree_sha)
assert [%{name: "hello.txt", type: "blob", sha: ^blob_sha}] = entries
end
end
2.4 KiB · text
5af55d9