Files
2026-06-08 15:03:41 -05:00

105 lines
2.5 KiB
Go

package gitutil
import (
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
)
func requireGit(t *testing.T) {
t.Helper()
if _, err := exec.LookPath("git"); err != nil {
t.Skip("git not installed")
}
}
func TestRunFailureIncludesCommandOutput(t *testing.T) {
requireGit(t)
err := Run("", "definitely-not-a-git-command")
if err == nil {
t.Fatal("expected git command to fail")
}
if !strings.Contains(err.Error(), "git definitely-not-a-git-command failed") {
t.Fatalf("unexpected error: %v", err)
}
}
func TestInitBareBranchExistsAndRefs(t *testing.T) {
requireGit(t)
root := t.TempDir()
bare := filepath.Join(root, "repo.git")
if err := InitBare(bare); err != nil {
t.Fatal(err)
}
head, err := os.ReadFile(filepath.Join(bare, "HEAD"))
if err != nil {
t.Fatal(err)
}
if strings.TrimSpace(string(head)) != "ref: refs/heads/main" {
t.Fatalf("HEAD = %q", string(head))
}
if BranchExists(bare, "main") {
t.Fatal("new empty bare repo should not have a main branch commit yet")
}
if BranchExists(bare, "bad branch") {
t.Fatal("invalid branch should not exist")
}
work := filepath.Join(root, "work")
if err := Run("", "clone", bare, work); err != nil {
t.Fatal(err)
}
for _, args := range [][]string{
{"config", "user.name", "Test User"},
{"config", "user.email", "test@example.com"},
} {
if err := Run(work, args...); err != nil {
t.Fatal(err)
}
}
if err := os.WriteFile(filepath.Join(work, "README.md"), []byte("hello\n"), 0644); err != nil {
t.Fatal(err)
}
if err := Run(work, "add", "README.md"); err != nil {
t.Fatal(err)
}
if err := Run(work, "commit", "-m", "initial commit"); err != nil {
t.Fatal(err)
}
if err := Run(work, "push", "origin", "HEAD:main"); err != nil {
t.Fatal(err)
}
if err := Run(work, "tag", "v1.0.0"); err != nil {
t.Fatal(err)
}
if err := Run(work, "push", "origin", "v1.0.0"); err != nil {
t.Fatal(err)
}
if !BranchExists(bare, "main") {
t.Fatal("main branch should exist after push")
}
branches, err := Refs(bare, "refs/heads")
if err != nil {
t.Fatal(err)
}
if len(branches) != 1 || branches[0].Name != "main" || branches[0].Message != "initial commit" {
t.Fatalf("unexpected branches: %#v", branches)
}
tags, err := Refs(bare, "refs/tags")
if err != nil {
t.Fatal(err)
}
if len(tags) != 1 || tags[0].Name != "v1.0.0" {
t.Fatalf("unexpected tags: %#v", tags)
}
}
func TestRefsInvalidRepo(t *testing.T) {
requireGit(t)
if _, err := Refs(filepath.Join(t.TempDir(), "missing.git"), "refs/heads"); err == nil {
t.Fatal("expected missing repo refs to fail")
}
}