~james/core

core/gitutil/sync_test.go -rw-r--r-- 8.7 KiB
452f17b7 — james chore(import): snapshot james.dad.town/core at f70c71c7696a 14 hours ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
package gitutil

import (
	"bufio"
	"context"
	"fmt"
	"io"
	"net"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
	"sync"
	"testing"
	"time"
)

const testSparseDir = "/.tangled/workflows"

func newGitRepo(t *testing.T, initArgs ...string) (string, func(args ...string) string) {
	t.Helper()
	// ignore the developer's git config
	t.Setenv("GIT_CONFIG_GLOBAL", os.DevNull)
	t.Setenv("GIT_CONFIG_SYSTEM", os.DevNull)
	t.Setenv("GIT_AUTHOR_NAME", "spindle")
	t.Setenv("GIT_AUTHOR_EMAIL", "spindle@tangled.org")
	t.Setenv("GIT_COMMITTER_NAME", "spindle")
	t.Setenv("GIT_COMMITTER_EMAIL", "spindle@tangled.org")

	src := t.TempDir()
	run := func(args ...string) string {
		t.Helper()
		cmd := exec.Command("git", append([]string{"-C", src}, args...)...)
		out, err := cmd.CombinedOutput()
		if err != nil {
			t.Fatalf("git %v: %v: %s", args, err, out)
		}
		return strings.TrimSpace(string(out))
	}

	run(append([]string{"init", "-b", "main"}, initArgs...)...)
	return src, run
}

func commitWorkflow(t *testing.T, src string, run func(args ...string) string) string {
	t.Helper()
	if err := os.MkdirAll(filepath.Join(src, ".tangled", "workflows"), 0o755); err != nil {
		t.Fatal(err)
	}
	if err := os.WriteFile(filepath.Join(src, ".tangled", "workflows", "ci.yml"), []byte("when: []\n"), 0o644); err != nil {
		t.Fatal(err)
	}
	run("add", ".")
	run("commit", "-m", "workflows")
	return run("rev-parse", "HEAD")
}

func TestSparseSync(t *testing.T) {
	src, run := newGitRepo(t)

	rev := commitWorkflow(t, src, run)

	path := filepath.Join(t.TempDir(), "repo")
	for _, stage := range []string{"clone", "fetch"} {
		if err := SparseSync(context.Background(), src, path, rev, testSparseDir); err != nil {
			t.Fatalf("%s: %v", stage, err)
		}
		if _, err := os.Stat(filepath.Join(path, ".tangled", "workflows", "ci.yml")); err != nil {
			t.Fatalf("%s: sparse file missing from the checkout: %v", stage, err)
		}
	}
}

func TestSparseSync_DanglingRemoteHead(t *testing.T) {
	src, run := newGitRepo(t)

	sha := commitWorkflow(t, src, run)

	// switch branch to master and point HEAD to unborn main
	run("branch", "-m", "main", "master")
	run("symbolic-ref", "HEAD", "refs/heads/main")

	path := filepath.Join(t.TempDir(), "repo")
	// syncing by commit sha must succeed even when remote HEAD is dangling
	if err := SparseSync(context.Background(), src, path, sha, testSparseDir); err != nil {
		t.Fatalf("sync by sha failed on dangling HEAD remote: %v", err)
	}
	if _, err := os.Stat(filepath.Join(path, ".tangled", "workflows", "ci.yml")); err != nil {
		t.Fatalf("sparse file missing: %v", err)
	}

	// syncing by ref name must also succeed
	path2 := filepath.Join(t.TempDir(), "repo2")
	if err := SparseSync(context.Background(), src, path2, "refs/heads/master", testSparseDir); err != nil {
		t.Fatalf("sync by ref failed on dangling HEAD remote: %v", err)
	}
}

func TestSparseSync_Sha256Remote(t *testing.T) {
	src, run := newGitRepo(t, "--object-format=sha256")
	sha := commitWorkflow(t, src, run)
	if len(sha) != sha256HexLen {
		t.Fatalf("fixture commit %q is not a sha256 id", sha)
	}

	for name, rev := range map[string]string{"by sha": sha, "by HEAD": ""} {
		path := filepath.Join(t.TempDir(), "repo")
		if err := SparseSync(context.Background(), src, path, rev, testSparseDir); err != nil {
			t.Fatalf("%s: %v", name, err)
		}
		if _, err := os.Stat(filepath.Join(path, ".tangled", "workflows", "ci.yml")); err != nil {
			t.Fatalf("%s: sparse file missing: %v", name, err)
		}
	}
}

func TestSparseSync_Sha256DanglingHeadByRef(t *testing.T) {
	src, run := newGitRepo(t, "--object-format=sha256")
	commitWorkflow(t, src, run)
	run("branch", "-m", "main", "master")
	run("symbolic-ref", "HEAD", "refs/heads/main")

	path := filepath.Join(t.TempDir(), "repo")
	if err := SparseSync(context.Background(), src, path, "refs/heads/master", testSparseDir); err != nil {
		t.Fatalf("sync by ref failed on a sha256 remote with a dangling HEAD: %v", err)
	}
}

func TestRefContainsCommit_Sha256Remote(t *testing.T) {
	src, run := newGitRepo(t, "--object-format=sha256")
	sha := commitWorkflow(t, src, run)

	got, err := RefContainsCommit(context.Background(), src, "refs/heads/main", sha)
	if err != nil || !got {
		t.Fatalf("RefContainsCommit() = %t, err = %v, want true on a sha256 remote", got, err)
	}
}

func TestRefContainsCommit(t *testing.T) {
	src, run := newGitRepo(t)

	if err := os.WriteFile(filepath.Join(src, "f"), []byte("a"), 0o644); err != nil {
		t.Fatal(err)
	}
	run("add", ".")
	run("commit", "-m", "a")
	olderThanWindow := run("rev-parse", "HEAD")

	// fill main past the ancestry window RefContainsCommit fetches
	for i := 0; i < maxAncestryDepth+5; i++ {
		if err := os.WriteFile(filepath.Join(src, "f"), []byte(fmt.Sprintf("f%d", i)), 0o644); err != nil {
			t.Fatal(err)
		}
		run("add", ".")
		run("commit", "-m", fmt.Sprintf("fill %d", i))
	}
	tip := run("rev-parse", "HEAD")
	ancestor := run("rev-parse", "HEAD~1")

	// a commit that exists in the repository but not on main
	run("checkout", "-b", "dev")
	if err := os.WriteFile(filepath.Join(src, "f"), []byte("c"), 0o644); err != nil {
		t.Fatal(err)
	}
	run("add", ".")
	run("commit", "-m", "c")
	offBranch := run("rev-parse", "HEAD")
	run("checkout", "main")

	for _, tt := range []struct {
		name string
		sha  string
		want bool
	}{
		{"the ref tip", tip, true},
		{"an ancestor of the tip", ancestor, true},
		{"a commit older than the ancestry window", olderThanWindow, false},
		{"a commit on another branch", offBranch, false},
		{"a commit the repo never had", strings.Repeat("1", 40), false},
	} {
		t.Run(tt.name, func(t *testing.T) {
			got, err := RefContainsCommit(context.Background(), src, "refs/heads/main", tt.sha)
			if got != tt.want {
				t.Fatalf("RefContainsCommit() = %t, err = %v, want %t", got, err, tt.want)
			}
		})
	}
}

// hangingKnot keeps the child process alive until the client closes its socket
func hangingKnot(t *testing.T) (url string, asked, dropped <-chan struct{}) {
	t.Helper()

	ln, err := net.Listen("tcp", "127.0.0.1:0")
	if err != nil {
		t.Fatal(err)
	}
	t.Cleanup(func() { ln.Close() })

	askedCh := make(chan struct{})
	droppedCh := make(chan struct{})
	var askOnce, dropOnce sync.Once

	go func() {
		for {
			conn, err := ln.Accept()
			if err != nil {
				return
			}
			go func() {
				defer conn.Close()
				br := bufio.NewReader(conn)
				for {
					line, err := br.ReadString('\n')
					if err != nil {
						return
					}
					if strings.TrimSpace(line) == "" {
						break
					}
				}
				io.WriteString(conn, "HTTP/1.1 200 OK\r\n"+
					"Content-Type: application/x-git-upload-pack-advertisement\r\n"+
					"Transfer-Encoding: chunked\r\n\r\n")
				askOnce.Do(func() { close(askedCh) })
				// this ends only when the child process dies
				io.Copy(io.Discard, br)
				dropOnce.Do(func() { close(droppedCh) })
			}()
		}
	}()

	return "http://" + ln.Addr().String(), askedCh, droppedCh
}

func TestRunCancelKillsRemoteHelper(t *testing.T) {
	knot, asked, dropped := hangingKnot(t)
	path := filepath.Join(t.TempDir(), "repo")

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	done := make(chan error, 1)
	go func() { done <- Run(ctx, "clone", "--no-checkout", "--depth=1", knot+"/repo.git", path) }()

	select {
	case <-asked:
	case err := <-done:
		t.Fatalf("clone returned before it reached the knot: %v", err)
	case <-time.After(30 * time.Second):
		t.Fatal("git never asked the knot for refs")
	}

	cancel()

	select {
	case err := <-done:
		if err == nil {
			t.Fatal("a cancelled clone reported success")
		}
	case <-time.After(15 * time.Second):
		t.Fatal("Run is still blocked after cancellation: a surviving helper holds the inherited stderr pipe open")
	}

	select {
	case <-dropped:
	case <-time.After(15 * time.Second):
		t.Fatal("git-remote-http outlived the cancelled clone")
	}
}

func TestSparseSyncCancelReleasesRepoLock(t *testing.T) {
	knot, asked, _ := hangingKnot(t)
	path := filepath.Join(t.TempDir(), "repo")

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	done := make(chan error, 1)
	go func() { done <- SparseSync(ctx, knot+"/repo.git", path, "HEAD", testSparseDir) }()

	select {
	case <-asked:
	case err := <-done:
		t.Fatalf("sync returned before it reached the knot: %v", err)
	case <-time.After(30 * time.Second):
		t.Fatal("git never asked the knot for refs")
	}

	cancel()

	select {
	case <-done:
	case <-time.After(15 * time.Second):
		t.Fatal("SparseSync is still blocked after cancellation")
	}

	// another request must be able to use this repo
	dead, cancelDead := context.WithCancel(context.Background())
	cancelDead()

	next := make(chan error, 1)
	go func() { next <- SparseSync(dead, knot+"/repo.git", path, "HEAD", testSparseDir) }()

	select {
	case <-next:
	case <-time.After(15 * time.Second):
		t.Fatal("a cancelled sync never released the repo lock")
	}
}