rin
Public Open-source lightweight git hosting.
merge_test.go · 80 lines · 2.4 KB
Raw
1 package git
2
3 import (
4 "context"
5 "os"
6 "os/exec"
7 "path/filepath"
8 "strings"
9 "testing"
10 )
11
12 // TestMergeFromPath verifies cross-repository (fork) merging through a
13 // temporary ref fetched from another local repository.
14 func TestMergeFromPath(t *testing.T) {
15 ctx := context.Background()
16 tmp := t.TempDir()
17
18 basePath := filepath.Join(tmp, "base.git")
19 if err := InitBare(ctx, basePath, "main"); err != nil {
20 t.Fatalf("InitBare: %v", err)
21 }
22
23 work := filepath.Join(tmp, "work")
24 if err := os.MkdirAll(work, 0o755); err != nil {
25 t.Fatalf("mkdir: %v", err)
26 }
27 run := func(dir string, args ...string) {
28 t.Helper()
29 cmd := exec.CommandContext(ctx, "git", args...)
30 cmd.Dir = dir
31 if out, err := cmd.CombinedOutput(); err != nil {
32 t.Fatalf("git %v: %v (%s)", args, err, string(out))
33 }
34 }
35
36 run(work, "init", "-b", "main")
37 run(work, "config", "user.name", "Alice")
38 run(work, "config", "user.email", "alice@example.com")
39 if err := os.WriteFile(filepath.Join(work, "file.txt"), []byte("base\n"), 0o644); err != nil {
40 t.Fatalf("write: %v", err)
41 }
42 run(work, "add", ".")
43 run(work, "commit", "-m", "base commit")
44 run(work, "push", basePath, "main")
45
46 forkPath := filepath.Join(tmp, "fork.git")
47 if err := CloneBare(ctx, basePath, forkPath); err != nil {
48 t.Fatalf("CloneBare: %v", err)
49 }
50
51 // Add a feature branch on the fork.
52 run(work, "checkout", "-b", "feature")
53 if err := os.WriteFile(filepath.Join(work, "feature.txt"), []byte("feature\n"), 0o644); err != nil {
54 t.Fatalf("write: %v", err)
55 }
56 run(work, "add", ".")
57 run(work, "commit", "-m", "add feature")
58 run(work, "push", forkPath, "feature")
59
60 hash, err := MergeFromPath(ctx, basePath, forkPath, "main", "feature", "refs/polar/tmp-merge-test", "Merge PR #1", "Alice", "alice@example.com")
61 if err != nil {
62 t.Fatalf("MergeFromPath: %v", err)
63 }
64 if hash == "" {
65 t.Fatalf("expected merge commit hash")
66 }
67
68 out, err := runGit(ctx, basePath, 10_000_000_000, "ls-tree", "-r", "--name-only", "main")
69 if err != nil {
70 t.Fatalf("ls-tree: %v", err)
71 }
72 if !strings.Contains(string(out), "feature.txt") {
73 t.Fatalf("expected feature.txt on merged main, got: %s", string(out))
74 }
75
76 // The temporary ref must be gone after the merge.
77 if out, err := runGit(ctx, basePath, 10_000_000_000, "show-ref", "--verify", "--quiet", "refs/polar/tmp-merge-test"); err == nil {
78 t.Fatalf("expected temp ref to be deleted, got %s", string(out))
79 }
80 }
81