Go 89 lines
package gitx
import (
"os"
"os/exec"
"path/filepath"
"testing"
)
// gitInitCommit creates a real git repo with one commit and returns its root.
// Skips when git is unavailable.
func gitInitCommit(t *testing.T) string {
t.Helper()
if _, err := exec.LookPath("git"); err != nil {
t.Skip("git not available")
}
root := t.TempDir()
for _, args := range [][]string{
{"init", "-q"}, {"config", "user.email", "t@x"}, {"config", "user.name", "t"},
} {
c := exec.Command("git", args...)
c.Dir = root
if out, err := c.CombinedOutput(); err != nil {
t.Fatalf("git %v: %v\n%s", args, err, out)
}
}
if err := os.WriteFile(filepath.Join(root, "f.txt"), []byte("x"), 0o644); err != nil {
t.Fatal(err)
}
for _, args := range [][]string{{"add", "-A"}, {"commit", "-qm", "seed"}} {
c := exec.Command("git", args...)
c.Dir = root
if out, err := c.CombinedOutput(); err != nil {
t.Fatalf("git %v: %v\n%s", args, err, out)
}
}
return root
}
func TestIsDirty(t *testing.T) {
root := gitInitCommit(t)
dirty, err := IsDirty(root)
if err != nil {
t.Fatal(err)
}
if dirty {
t.Error("freshly committed tree reported dirty")
}
if err := os.WriteFile(filepath.Join(root, "new.txt"), []byte("y"), 0o644); err != nil {
t.Fatal(err)
}
dirty, err = IsDirty(root)
if err != nil {
t.Fatal(err)
}
if !dirty {
t.Error("tree with an untracked file reported clean")
}
}
func TestLastCommitTime(t *testing.T) {
root := gitInitCommit(t)
ts, ok, err := LastCommitTime(root)
if err != nil {
t.Fatal(err)
}
if !ok {
t.Fatal("LastCommitTime ok=false on a repo with a commit")
}
if ts.IsZero() {
t.Error("LastCommitTime returned a zero time")
}
}
func TestLastCommitTime_NoCommits(t *testing.T) {
if _, err := exec.LookPath("git"); err != nil {
t.Skip("git not available")
}
root := t.TempDir()
c := exec.Command("git", "init", "-q")
c.Dir = root
if out, err := c.CombinedOutput(); err != nil {
t.Fatalf("git init: %v\n%s", err, out)
}
if _, ok, err := LastCommitTime(root); err != nil || ok {
t.Errorf("LastCommitTime on an empty repo = (ok=%v, err=%v), want (false, nil)", ok, err)
}
}