internal/gitutil/lastcommit_test.go

v1.33.0
gitbay/internal/gitutil/lastcommit_test.go history · blame · raw

91 lines · 2611 bytes

 1package gitutil
 2
 3import (
 4	"os"
 5	"os/exec"
 6	"path/filepath"
 7	"testing"
 8)
 9
10func git(t *testing.T, dir string, args ...string) {
11	t.Helper()
12	cmd := exec.Command("git", append([]string{"-C", dir}, args...)...)
13	cmd.Env = append(os.Environ(),
14		"GIT_AUTHOR_NAME=t", "GIT_AUTHOR_EMAIL=t@e",
15		"GIT_COMMITTER_NAME=t", "GIT_COMMITTER_EMAIL=t@e")
16	if out, err := cmd.CombinedOutput(); err != nil {
17		t.Fatalf("git %v: %v\n%s", args, err, out)
18	}
19}
20
21func write(t *testing.T, dir, rel, body string) {
22	t.Helper()
23	p := filepath.Join(dir, rel)
24	if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
25		t.Fatal(err)
26	}
27	if err := os.WriteFile(p, []byte(body), 0o644); err != nil {
28		t.Fatal(err)
29	}
30}
31
32func TestLastCommits(t *testing.T) {
33	dir := t.TempDir()
34	git(t, dir, "init", "-q", "-b", "main")
35
36	write(t, dir, "README.md", "one\n")
37	write(t, dir, "src/main.go", "one\n")
38	write(t, dir, "docs/guide.md", "one\n")
39	git(t, dir, "add", ".")
40	git(t, dir, "commit", "-qm", "first")
41
42	// Touching a file deep inside src/ must move the src/ entry without
43	// disturbing README.md or docs/.
44	write(t, dir, "src/lib/helper.go", "two\n")
45	git(t, dir, "add", ".")
46	git(t, dir, "commit", "-qm", "add helper")
47
48	write(t, dir, "README.md", "three\n")
49	git(t, dir, "commit", "-qam", "update readme")
50
51	got := LastCommits(dir, "main", "", []string{"README.md", "src", "docs"})
52	for name, wantSubject := range map[string]string{
53		"README.md": "update readme",
54		"src":       "add helper",
55		"docs":      "first",
56	} {
57		c, ok := got[name]
58		if !ok {
59			t.Errorf("%s unresolved", name)
60			continue
61		}
62		if c.Subject != wantSubject {
63			t.Errorf("%s = %q, want %q", name, c.Subject, wantSubject)
64		}
65		if c.SHA == "" || c.When.IsZero() {
66			t.Errorf("%s missing sha or time: %+v", name, c)
67		}
68	}
69
70	// Inside a subdirectory the prefix is stripped, so entries resolve
71	// against their own names rather than full paths.
72	sub := LastCommits(dir, "main", "src", []string{"main.go", "lib"})
73	if c := sub["main.go"]; c.Subject != "first" {
74		t.Errorf("src/main.go = %q, want %q", c.Subject, "first")
75	}
76	if c := sub["lib"]; c.Subject != "add helper" {
77		t.Errorf("src/lib = %q, want %q", c.Subject, "add helper")
78	}
79
80	// A name nobody asked about never appears, and an unknown one is
81	// simply absent rather than an error.
82	if _, ok := sub["README.md"]; ok {
83		t.Error("src listing leaked a root entry")
84	}
85	if _, ok := LastCommits(dir, "main", "", []string{"nope"})["nope"]; ok {
86		t.Error("resolved a path that does not exist")
87	}
88	if LastCommits(dir, "main", "", nil) != nil {
89		t.Error("empty name list should not run git")
90	}
91}