internal/gitutil/subjects_test.go
50 lines · 1213 bytes
1package gitutil
2
3import (
4 "os/exec"
5 "strings"
6 "testing"
7)
8
9func TestSubjects(t *testing.T) {
10 dir := t.TempDir()
11 git(t, dir, "init", "-q", "-b", "main")
12
13 write(t, dir, "a", "one\n")
14 git(t, dir, "add", ".")
15 git(t, dir, "commit", "-qm", "first thing")
16 first := rev(t, dir, "HEAD")
17
18 write(t, dir, "a", "two\n")
19 git(t, dir, "commit", "-qam", "second thing")
20 second := rev(t, dir, "HEAD")
21
22 got := Subjects(dir, []string{second, first})
23 if got[first] != "first thing" || got[second] != "second thing" {
24 t.Fatalf("Subjects = %v", got)
25 }
26
27 // A build outlives the commit it ran on when a branch is
28 // force-pushed. The shas that do resolve still come back.
29 gone := strings.Repeat("1", 40)
30 got = Subjects(dir, []string{gone, first})
31 if got[first] != "first thing" {
32 t.Errorf("a missing sha lost the rest: %v", got)
33 }
34 if _, ok := got[gone]; ok {
35 t.Errorf("resolved a sha that is not there: %v", got)
36 }
37
38 if Subjects(dir, nil) != nil {
39 t.Error("empty sha list should not run git")
40 }
41}
42
43func rev(t *testing.T, dir, ref string) string {
44 t.Helper()
45 out, err := exec.Command("git", "-C", dir, "rev-parse", ref).Output()
46 if err != nil {
47 t.Fatal(err)
48 }
49 return strings.TrimSpace(string(out))
50}