-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathmanager_test.go
More file actions
681 lines (564 loc) · 21.4 KB
/
Copy pathmanager_test.go
File metadata and controls
681 lines (564 loc) · 21.4 KB
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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
package gitclone //nolint:testpackage // white-box testing required for unexported fields
import (
"context"
"fmt"
"log/slog"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
"time"
"github.com/alecthomas/assert/v2"
"github.com/block/cachew/internal/logging"
)
// testRepoConfig returns a Config with timeouts populated, suitable for
// constructing Repository values directly in tests that bypass NewManager.
func testRepoConfig() Config {
return Config{
CloneTimeout: 1 * time.Hour,
FetchTimeout: 5 * time.Minute,
LsRemoteTimeout: 60 * time.Second,
RepackTimeout: 10 * time.Minute,
}
}
// createBareRepo creates a bare git repository at the given path, suitable for
// use as an upstream or as a mirror clone target.
func createBareRepo(t *testing.T, dir string) string {
t.Helper()
workPath := filepath.Join(dir, "work")
barePath := filepath.Join(dir, "upstream.git")
assert.NoError(t, os.MkdirAll(workPath, 0o755))
for _, args := range [][]string{
{"git", "-C", workPath, "init"},
{"git", "-C", workPath, "config", "user.email", "test@example.com"},
{"git", "-C", workPath, "config", "user.name", "Test"},
} {
assert.NoError(t, exec.Command(args[0], args[1:]...).Run())
}
assert.NoError(t, os.WriteFile(filepath.Join(workPath, "f.txt"), []byte("x"), 0o644))
for _, args := range [][]string{
{"git", "-C", workPath, "add", "."},
{"git", "-C", workPath, "commit", "-m", "init"},
{"git", "clone", "--bare", workPath, barePath},
} {
assert.NoError(t, exec.Command(args[0], args[1:]...).Run())
}
return barePath
}
func TestNewManager(t *testing.T) {
_, ctx := logging.Configure(t.Context(), logging.Config{Level: slog.LevelError})
tmpDir := t.TempDir()
config := Config{
MirrorRoot: tmpDir,
FetchInterval: 15 * time.Minute,
RefCheckInterval: 10 * time.Second,
}
manager, err := NewManager(ctx, config, nil)
assert.NoError(t, err)
assert.NotZero(t, manager)
assert.Equal(t, tmpDir, manager.config.MirrorRoot)
}
func TestNewManager_RequiresRootDir(t *testing.T) {
_, ctx := logging.Configure(t.Context(), logging.Config{Level: slog.LevelError})
config := Config{
FetchInterval: 15 * time.Minute,
RefCheckInterval: 10 * time.Second,
}
_, err := NewManager(ctx, config, nil)
assert.Error(t, err)
assert.Contains(t, err.Error(), "mirror-root is required")
}
func TestManager_GetOrCreate(t *testing.T) {
_, ctx := logging.Configure(t.Context(), logging.Config{Level: slog.LevelError})
tmpDir := t.TempDir()
config := Config{
MirrorRoot: tmpDir,
FetchInterval: 15 * time.Minute,
RefCheckInterval: 10 * time.Second,
}
manager, err := NewManager(ctx, config, nil)
assert.NoError(t, err)
upstreamURL := "https://github.com/user/repo"
repo, err := manager.GetOrCreate(context.Background(), upstreamURL)
assert.NoError(t, err)
assert.NotZero(t, repo)
assert.Equal(t, upstreamURL, repo.UpstreamURL())
assert.Equal(t, StateEmpty, repo.State())
assert.Equal(t, filepath.Join(tmpDir, "github.com", "user", "repo"), repo.Path())
repo2, err := manager.GetOrCreate(context.Background(), upstreamURL)
assert.NoError(t, err)
assert.True(t, repo == repo2, "expected same repository instance")
}
func TestManager_GetOrCreate_ExistingClone(t *testing.T) {
_, ctx := logging.Configure(t.Context(), logging.Config{Level: slog.LevelError})
tmpDir := t.TempDir()
config := Config{
MirrorRoot: tmpDir,
FetchInterval: 15 * time.Minute,
RefCheckInterval: 10 * time.Second,
}
manager, err := NewManager(ctx, config, nil)
assert.NoError(t, err)
repoPath := filepath.Join(tmpDir, "github.com", "user", "repo")
assert.NoError(t, os.MkdirAll(repoPath, 0o755))
assert.NoError(t, os.WriteFile(filepath.Join(repoPath, "HEAD"), []byte("ref: refs/heads/main\n"), 0o644))
upstreamURL := "https://github.com/user/repo"
repo, err := manager.GetOrCreate(context.Background(), upstreamURL)
assert.NoError(t, err)
assert.NotZero(t, repo)
assert.Equal(t, StateReady, repo.State())
}
func TestManager_Get(t *testing.T) {
_, ctx := logging.Configure(t.Context(), logging.Config{Level: slog.LevelError})
tmpDir := t.TempDir()
config := Config{
MirrorRoot: tmpDir,
FetchInterval: 15 * time.Minute,
RefCheckInterval: 10 * time.Second,
}
manager, err := NewManager(ctx, config, nil)
assert.NoError(t, err)
upstreamURL := "https://github.com/user/repo"
repo := manager.Get(upstreamURL)
assert.Zero(t, repo)
_, err = manager.GetOrCreate(context.Background(), upstreamURL)
assert.NoError(t, err)
repo = manager.Get(upstreamURL)
assert.NotZero(t, repo)
assert.Equal(t, upstreamURL, repo.UpstreamURL())
}
func TestManager_DiscoverExisting(t *testing.T) {
_, ctx := logging.Configure(t.Context(), logging.Config{Level: slog.LevelError})
tmpDir := t.TempDir()
config := Config{
MirrorRoot: tmpDir,
FetchInterval: 15 * time.Minute,
RefCheckInterval: 10 * time.Second,
}
manager, err := NewManager(ctx, config, nil)
assert.NoError(t, err)
// Create a real bare repo as a source, then clone it into the mirror paths.
upstreamPath := createBareRepo(t, t.TempDir())
repoPaths := []string{
filepath.Join(tmpDir, "github.com", "user1", "repo1"),
filepath.Join(tmpDir, "github.com", "user2", "repo2"),
filepath.Join(tmpDir, "gitlab.com", "org", "project"),
}
for _, repoPath := range repoPaths {
assert.NoError(t, os.MkdirAll(filepath.Dir(repoPath), 0o755))
cmd := exec.Command("git", "clone", "--bare", upstreamPath, repoPath)
assert.NoError(t, cmd.Run())
}
discovered, err := manager.DiscoverExisting(context.Background())
assert.NoError(t, err)
assert.Equal(t, 3, len(discovered))
repo1 := manager.Get("https://github.com/user1/repo1")
assert.NotZero(t, repo1)
assert.Equal(t, StateReady, repo1.State())
repo2 := manager.Get("https://github.com/user2/repo2")
assert.NotZero(t, repo2)
assert.Equal(t, StateReady, repo2.State())
repo3 := manager.Get("https://gitlab.com/org/project")
assert.NotZero(t, repo3)
assert.Equal(t, StateReady, repo3.State())
// Verify mirror config was applied to discovered repos.
for _, repoPath := range repoPaths {
for _, kv := range mirrorConfigSettings(manager.Config().PackThreads) {
cmd := exec.Command("git", "-C", repoPath, "config", "--get", kv[0])
output, err := cmd.Output()
assert.NoError(t, err, "config key %s in %s", kv[0], repoPath)
assert.Equal(t, kv[1], strings.TrimSpace(string(output)), "config key %s in %s", kv[0], repoPath)
}
}
}
func TestRepository_StateTransitions(t *testing.T) {
repo := &Repository{
state: StateEmpty,
path: "/tmp/test",
upstreamURL: "https://github.com/user/repo",
fetchSem: make(chan struct{}, 1),
}
repo.fetchSem <- struct{}{}
assert.Equal(t, StateEmpty, repo.State())
repo.mu.Lock()
repo.state = StateCloning
repo.mu.Unlock()
assert.Equal(t, StateCloning, repo.State())
repo.mu.Lock()
repo.state = StateReady
repo.mu.Unlock()
assert.Equal(t, StateReady, repo.State())
}
func TestRepository_NeedsFetch(t *testing.T) {
repo := &Repository{
state: StateEmpty,
lastFetch: time.Now().Add(-20 * time.Minute),
fetchSem: make(chan struct{}, 1),
}
repo.fetchSem <- struct{}{}
assert.True(t, repo.NeedsFetch(15*time.Minute))
assert.False(t, repo.NeedsFetch(30*time.Minute))
repo.mu.Lock()
repo.lastFetch = time.Now()
repo.mu.Unlock()
assert.False(t, repo.NeedsFetch(15*time.Minute))
}
func TestParseGitRefs(t *testing.T) {
output := []byte(`
abc123 refs/heads/main
def456 refs/heads/develop
789012 refs/tags/v1.0.0
`)
refs := ParseGitRefs(output)
assert.Equal(t, "abc123", refs["refs/heads/main"])
assert.Equal(t, "def456", refs["refs/heads/develop"])
assert.Equal(t, "789012", refs["refs/tags/v1.0.0"])
}
func TestState_String(t *testing.T) {
assert.Equal(t, "empty", StateEmpty.String())
assert.Equal(t, "cloning", StateCloning.String())
assert.Equal(t, "ready", StateReady.String())
}
func TestRepository_Clone_StateVisibleDuringClone(t *testing.T) {
ctx := context.Background()
tmpDir := t.TempDir()
upstreamPath := createBareRepo(t, tmpDir)
clonePath := filepath.Join(tmpDir, "clone")
repo := &Repository{
state: StateEmpty,
config: testRepoConfig(),
path: clonePath,
upstreamURL: upstreamPath,
fetchSem: make(chan struct{}, 1),
}
repo.fetchSem <- struct{}{}
// Start clone in background
cloneDone := make(chan error, 1)
go func() {
cloneDone <- repo.Clone(ctx)
}()
// Poll until we observe StateCloning (should not block)
deadline := time.After(10 * time.Second)
sawCloning := false
for !sawCloning {
select {
case <-deadline:
t.Fatal("timed out waiting to observe StateCloning — State() likely blocked on the clone lock")
default:
if repo.State() == StateCloning {
sawCloning = true
}
}
}
assert.True(t, sawCloning)
// Wait for clone to finish
assert.NoError(t, <-cloneDone)
assert.Equal(t, StateReady, repo.State())
}
func TestRepository_CloneSetsMirrorConfig(t *testing.T) {
ctx := context.Background()
tmpDir := t.TempDir()
upstreamPath := createBareRepo(t, tmpDir)
clonePath := filepath.Join(tmpDir, "clone")
cfg := testRepoConfig()
cfg.PackThreads = 4
repo := &Repository{
state: StateEmpty,
config: cfg,
path: clonePath,
upstreamURL: upstreamPath,
fetchSem: make(chan struct{}, 1),
}
repo.fetchSem <- struct{}{}
assert.NoError(t, repo.Clone(ctx))
assert.Equal(t, StateReady, repo.State())
for _, kv := range mirrorConfigSettings(4) {
cmd := exec.Command("git", "-C", clonePath, "config", "--get", kv[0])
output, err := cmd.Output()
assert.NoError(t, err, "config key %s", kv[0])
assert.Equal(t, kv[1], strings.TrimSpace(string(output)), "config key %s", kv[0])
}
}
func TestRepository_CloneFailedLeavesNoDebris(t *testing.T) {
ctx := context.Background()
tmpDir := t.TempDir()
clonePath := filepath.Join(tmpDir, "mirrors", "github.com", "owner", "repo")
repo := &Repository{
state: StateEmpty,
config: testRepoConfig(),
path: clonePath,
upstreamURL: "https://github.com/nonexistent-owner-abc123/nonexistent-repo-abc123",
fetchSem: make(chan struct{}, 1),
}
repo.fetchSem <- struct{}{}
err := repo.Clone(ctx)
assert.Error(t, err)
assert.Equal(t, StateEmpty, repo.State())
_, statErr := os.Stat(clonePath)
assert.True(t, os.IsNotExist(statErr), "repo.Path() should not exist after failed clone")
}
func TestRepository_CloneDoesNotClobberSiblings(t *testing.T) {
ctx := context.Background()
tmpDir := t.TempDir()
mirrorRoot := filepath.Join(tmpDir, "mirrors")
siblingPath := filepath.Join(mirrorRoot, "github.com", "owner", "sibling")
assert.NoError(t, os.MkdirAll(siblingPath, 0o755))
assert.NoError(t, os.WriteFile(filepath.Join(siblingPath, "HEAD"), []byte("ref: refs/heads/main\n"), 0o644))
clonePath := filepath.Join(mirrorRoot, "github.com")
repo := &Repository{
state: StateEmpty,
config: testRepoConfig(),
path: clonePath,
upstreamURL: "https://github.com/",
fetchSem: make(chan struct{}, 1),
}
repo.fetchSem <- struct{}{}
err := repo.Clone(ctx)
assert.Error(t, err)
_, statErr := os.Stat(siblingPath)
assert.NoError(t, statErr, "sibling mirror should still exist after failed clone")
}
func TestRepository_Repack(t *testing.T) {
_, ctx := logging.Configure(t.Context(), logging.Config{Level: slog.LevelError})
tmpDir := t.TempDir()
upstreamPath := createBareRepo(t, tmpDir)
clonePath := filepath.Join(tmpDir, "mirror")
cmd := exec.Command("git", "clone", "--mirror", upstreamPath, clonePath)
assert.NoError(t, cmd.Run())
repo := &Repository{
state: StateReady,
config: testRepoConfig(),
path: clonePath,
upstreamURL: upstreamPath,
fetchSem: make(chan struct{}, 1),
}
repo.fetchSem <- struct{}{}
assert.NoError(t, repo.Repack(ctx))
// Verify a pack file exists after repack.
packs, err := filepath.Glob(filepath.Join(clonePath, "objects", "pack", "*.pack"))
assert.NoError(t, err)
assert.True(t, len(packs) > 0, "expected at least one pack file after repack")
// Verify multi-pack-index was written.
_, err = os.Stat(filepath.Join(clonePath, "objects", "pack", "multi-pack-index"))
assert.NoError(t, err)
}
func TestRepository_RepackFull(t *testing.T) {
_, ctx := logging.Configure(t.Context(), logging.Config{Level: slog.LevelError})
tmpDir := t.TempDir()
upstreamPath := createBareRepo(t, tmpDir)
clonePath := filepath.Join(tmpDir, "mirror")
cmd := exec.Command("git", "clone", "--mirror", upstreamPath, clonePath)
assert.NoError(t, cmd.Run())
repo := &Repository{
state: StateReady,
config: testRepoConfig(),
path: clonePath,
upstreamURL: upstreamPath,
fetchSem: make(chan struct{}, 1),
}
repo.fetchSem <- struct{}{}
// Unset full-repack-timeout exercises the fallback to repack-timeout.
assert.NoError(t, repo.RepackFull(ctx))
packs, err := filepath.Glob(filepath.Join(clonePath, "objects", "pack", "*.pack"))
assert.NoError(t, err)
assert.True(t, len(packs) > 0, "expected at least one pack file after full repack")
_, err = os.Stat(filepath.Join(clonePath, "objects", "pack", "multi-pack-index"))
assert.NoError(t, err)
}
func TestRepository_Repack_CleansUpStaleLockOnFailure(t *testing.T) {
_, ctx := logging.Configure(t.Context(), logging.Config{Level: slog.LevelError})
tmpDir := t.TempDir()
upstreamPath := createBareRepo(t, tmpDir)
clonePath := filepath.Join(tmpDir, "mirror")
cmd := exec.Command("git", "clone", "--mirror", upstreamPath, clonePath)
assert.NoError(t, cmd.Run())
repo := &Repository{
state: StateReady,
config: testRepoConfig(),
path: clonePath,
upstreamURL: upstreamPath,
fetchSem: make(chan struct{}, 1),
}
repo.fetchSem <- struct{}{}
// Place a stale lock file simulating a killed repack.
lockPath := filepath.Join(clonePath, "objects", "pack", "multi-pack-index.lock")
assert.NoError(t, os.WriteFile(lockPath, []byte("stale"), 0o644))
// Repack should fail because of the lock, but should clean it up.
err := repo.Repack(ctx)
assert.Error(t, err)
// The stale lock should have been removed.
_, statErr := os.Stat(lockPath)
assert.True(t, os.IsNotExist(statErr), "expected multi-pack-index.lock to be removed after failed repack")
}
func TestRepository_HasCommit(t *testing.T) {
ctx := context.Background()
tmpDir := t.TempDir()
repoPath := filepath.Join(tmpDir, "test-repo")
assert.NoError(t, os.MkdirAll(repoPath, 0o755))
cmd := exec.Command("git", "-C", repoPath, "init")
assert.NoError(t, cmd.Run())
cmd = exec.Command("git", "-C", repoPath, "config", "user.email", "test@example.com")
assert.NoError(t, cmd.Run())
cmd = exec.Command("git", "-C", repoPath, "config", "user.name", "Test User")
assert.NoError(t, cmd.Run())
testFile := filepath.Join(repoPath, "test.txt")
assert.NoError(t, os.WriteFile(testFile, []byte("test content"), 0o644))
cmd = exec.Command("git", "-C", repoPath, "add", "test.txt")
assert.NoError(t, cmd.Run())
cmd = exec.Command("git", "-C", repoPath, "commit", "-m", "Initial commit")
assert.NoError(t, cmd.Run())
cmd = exec.Command("git", "-C", repoPath, "tag", "v1.0.0")
assert.NoError(t, cmd.Run())
repo := &Repository{
state: StateReady,
path: repoPath,
upstreamURL: "https://example.com/test-repo",
fetchSem: make(chan struct{}, 1),
}
repo.fetchSem <- struct{}{}
assert.True(t, repo.HasCommit(ctx, "HEAD"))
assert.True(t, repo.HasCommit(ctx, "v1.0.0"))
assert.False(t, repo.HasCommit(ctx, "nonexistent"))
assert.False(t, repo.HasCommit(ctx, "v9.9.9"))
}
func TestRepository_EnsureRefs(t *testing.T) {
ctx := context.Background()
tmpDir := t.TempDir()
upstreamPath := createBareRepo(t, tmpDir)
clonePath := filepath.Join(tmpDir, "clone")
repo := &Repository{
state: StateEmpty,
config: testRepoConfig(),
path: clonePath,
upstreamURL: upstreamPath,
fetchSem: make(chan struct{}, 1),
}
repo.fetchSem <- struct{}{}
assert.NoError(t, repo.Clone(ctx))
local, err := repo.GetLocalRefs(ctx)
assert.NoError(t, err)
mainSHA, ok := local["refs/heads/main"]
if !ok {
mainSHA = local["refs/heads/master"]
}
assert.NotEqual(t, "", mainSHA)
head := "refs/heads/main"
if !ok {
head = "refs/heads/master"
}
// Mirror already satisfies the request → no fetch.
resolved, missing, fetched, err := repo.EnsureRefs(ctx, map[string]string{head: mainSHA}, nil)
assert.NoError(t, err)
assert.False(t, fetched)
assert.Equal(t, 0, len(missing))
assert.Equal(t, mainSHA, resolved[head])
// Add a new commit to upstream so the mirror is now behind.
workPath := filepath.Join(tmpDir, "work")
assert.NoError(t, os.WriteFile(filepath.Join(workPath, "f.txt"), []byte("y"), 0o644))
for _, args := range [][]string{
{"git", "-C", workPath, "commit", "-am", "update"},
{"git", "-C", workPath, "push", upstreamPath, "HEAD:" + strings.TrimPrefix(head, "refs/heads/")},
} {
assert.NoError(t, exec.Command(args[0], args[1:]...).Run())
}
newSHAOut, err := exec.Command("git", "-C", workPath, "rev-parse", "HEAD").Output()
assert.NoError(t, err)
newSHA := strings.TrimSpace(string(newSHAOut))
assert.NotEqual(t, mainSHA, newSHA)
// Asking for the new SHA triggers a fetch and the mirror catches up.
resolved, missing, fetched, err = repo.EnsureRefs(ctx, map[string]string{head: newSHA}, nil)
assert.NoError(t, err)
assert.True(t, fetched)
assert.Equal(t, 0, len(missing))
assert.Equal(t, newSHA, resolved[head])
// Empty SHA means "any": already satisfied without fetching.
resolved, _, fetched, err = repo.EnsureRefs(ctx, map[string]string{head: ""}, nil)
assert.NoError(t, err)
assert.False(t, fetched)
assert.Equal(t, newSHA, resolved[head])
// Missing ref: fetch runs but ref remains missing → empty resolved SHA.
resolved, _, fetched, err = repo.EnsureRefs(ctx, map[string]string{"refs/heads/does-not-exist": ""}, nil)
assert.NoError(t, err)
assert.True(t, fetched)
assert.Equal(t, "", resolved["refs/heads/does-not-exist"])
// Commit-only request that's already present → no fetch.
resolved, missing, fetched, err = repo.EnsureRefs(ctx, nil, []string{newSHA})
assert.NoError(t, err)
assert.False(t, fetched)
assert.Equal(t, 0, len(missing))
assert.Equal(t, 0, len(resolved))
// Commit-only request that's missing → fetch runs and commit is reported missing.
resolved, missing, fetched, err = repo.EnsureRefs(ctx, nil,
[]string{"0000000000000000000000000000000000000000"})
assert.NoError(t, err)
assert.True(t, fetched)
assert.Equal(t, []string{"0000000000000000000000000000000000000000"}, missing)
assert.Equal(t, 0, len(resolved))
// Mixed request, both already satisfied.
resolved, missing, fetched, err = repo.EnsureRefs(ctx,
map[string]string{head: newSHA}, []string{newSHA})
assert.NoError(t, err)
assert.False(t, fetched)
assert.Equal(t, 0, len(missing))
assert.Equal(t, newSHA, resolved[head])
}
// TestMirrorConfigAllowsUnreachableSHA verifies that the mirror config lets
// git upload-pack serve objects that are present in the ODB but unreachable
// from any ref (e.g. after a force-push orphans a commit).
func TestMirrorConfigAllowsUnreachableSHA(t *testing.T) {
if _, err := exec.LookPath("git"); err != nil {
t.Skip("git not found in PATH")
}
tmpDir := t.TempDir()
workDir := filepath.Join(tmpDir, "work")
upstreamDir := filepath.Join(tmpDir, "upstream.git")
mirrorDir := filepath.Join(tmpDir, "mirror.git")
// Create upstream repo with an initial commit.
run := func(args ...string) {
t.Helper()
cmd := exec.Command(args[0], args[1:]...)
cmd.Env = append(os.Environ(),
"GIT_AUTHOR_NAME=Test", "GIT_AUTHOR_EMAIL=test@test.com",
"GIT_COMMITTER_NAME=Test", "GIT_COMMITTER_EMAIL=test@test.com",
)
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("%v: %v\n%s", args, err, out)
}
}
run("git", "init", "--bare", upstreamDir)
run("git", "clone", upstreamDir, workDir)
assert.NoError(t, os.WriteFile(filepath.Join(workDir, "f.txt"), []byte("v1"), 0o644))
run("git", "-C", workDir, "add", ".")
run("git", "-C", workDir, "commit", "-m", "initial")
run("git", "-C", workDir, "push", "origin", "HEAD:main")
// Record the SHA that will become orphaned.
out, err := exec.Command("git", "-C", workDir, "rev-parse", "HEAD").CombinedOutput()
assert.NoError(t, err)
orphanedSHA := strings.TrimSpace(string(out))
// Mirror-clone and apply the cachew mirror config.
run("git", "clone", "--mirror", upstreamDir, mirrorDir)
assert.NoError(t, configureMirror(context.Background(), mirrorDir, 1))
// Force-push a new root commit to upstream, then fetch into mirror.
run("git", "-C", workDir, "checkout", "--orphan", "newroot")
assert.NoError(t, os.WriteFile(filepath.Join(workDir, "f.txt"), []byte("v2"), 0o644))
run("git", "-C", workDir, "add", ".")
run("git", "-C", workDir, "commit", "-m", "replacement")
run("git", "-C", workDir, "push", "--force", "origin", "newroot:main")
run("git", "-C", mirrorDir, "fetch", "--prune")
// Sanity: orphaned SHA exists in ODB but is unreachable.
assert.NoError(t, exec.Command("git", "-C", mirrorDir, "cat-file", "-e", orphanedSHA).Run())
branchOut, _ := exec.Command("git", "-C", mirrorDir, "branch", "--contains", orphanedSHA).CombinedOutput()
assert.Equal(t, "", strings.TrimSpace(string(branchOut)))
// The key assertion: upload-pack should accept the unreachable SHA.
// With allowReachableSHA1InWant this fails; with allowAnySHA1InWant it passes.
cmd := exec.Command("git", "-C", mirrorDir, "upload-pack", "--strict", ".")
cmd.Stdin = strings.NewReader(
fmt.Sprintf("0032want %s\n00000009done\n", orphanedSHA),
)
uploadOut, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("upload-pack rejected unreachable SHA (mirror config should allow it):\n%s", uploadOut)
}
}