package main import ( "context" "os" "os/exec" "path/filepath" "strings" "testing" ) func TestGitAnalyzer(t *testing.T) { if _, e := exec.LookPath("git"); e != nil { t.Skip("git unavailable") } d := t.TempDir() run := func(args ...string) { c := exec.Command("git", append([]string{"-C", d}, args...)...) c.Env = append(os.Environ(), "GIT_AUTHOR_NAME=Test User", "GIT_AUTHOR_EMAIL=test@example.com", "GIT_COMMITTER_NAME=Test User", "GIT_COMMITTER_EMAIL=test@example.com") if b, e := c.CombinedOutput(); e != nil { t.Fatalf("git %v: %v %s", args, e, b) } } run("init") if e := os.WriteFile(filepath.Join(d, "main.go"), []byte("package main\n"), 0644); e != nil { t.Fatal(e) } run("add", ".") run("commit", "-m", "initial") g, e := (GitAnalyzer{}).Analyze(context.Background(), d) if e != nil { t.Fatal(e) } if g.CommitCount != 1 || g.Added != 1 || g.ContributorCount != 1 { t.Fatalf("unexpected git stats: %#v", g) } } func TestGitRefDetailsAndSafeCheckout(t *testing.T) { if _, e := exec.LookPath("git"); e != nil { t.Skip("git unavailable") } d := t.TempDir() run := func(args ...string) { c := exec.Command("git", append([]string{"-C", d}, args...)...) c.Env = append(os.Environ(), "GIT_AUTHOR_NAME=Test User", "GIT_AUTHOR_EMAIL=test@example.com", "GIT_COMMITTER_NAME=Test User", "GIT_COMMITTER_EMAIL=test@example.com") if b, e := c.CombinedOutput(); e != nil { t.Fatalf("git %v: %v %s", args, e, b) } } run("init") if e := os.WriteFile(filepath.Join(d, "main.go"), []byte("package main\n"), 0644); e != nil { t.Fatal(e) } run("add", ".") run("commit", "-m", "initial") run("switch", "-c", "feature") if e := os.WriteFile(filepath.Join(d, "main.go"), []byte("package main\n// feature\n"), 0644); e != nil { t.Fatal(e) } run("add", ".") run("commit", "-m", "feature") g := GitAnalyzer{} stats, e := g.AnalyzeRef(context.Background(), d, "feature") if e != nil { t.Fatal(e) } if stats.ViewRef != "feature" || stats.CommitCount != 2 { t.Fatalf("unexpected ref stats: %#v", stats) } detail, e := g.CommitDetail(context.Background(), d, stats.Commits[0].Hash) if e != nil { t.Fatal(e) } if len(detail.Files) == 0 { t.Fatal("commit files missing") } if e = os.WriteFile(filepath.Join(d, "dirty.txt"), []byte("dirty"), 0644); e != nil { t.Fatal(e) } if _, e = g.CheckoutBranch(context.Background(), d, "master"); e == nil || !strings.Contains(e.Error(), "GIT_WORKTREE_DIRTY") { t.Fatalf("dirty checkout error=%v", e) } }