package git import ( "context" "os" "os/exec" "path/filepath" "strings" "testing" ) // TestMergeFromPath verifies cross-repository (fork) merging through a // temporary ref fetched from another local repository. func TestMergeFromPath(t *testing.T) { ctx := context.Background() tmp := t.TempDir() basePath := filepath.Join(tmp, "base.git") if err := InitBare(ctx, basePath, "main"); err != nil { t.Fatalf("InitBare: %v", err) } work := filepath.Join(tmp, "work") if err := os.MkdirAll(work, 0o755); err != nil { t.Fatalf("mkdir: %v", err) } run := func(dir string, args ...string) { t.Helper() cmd := exec.CommandContext(ctx, "git", args...) cmd.Dir = dir if out, err := cmd.CombinedOutput(); err != nil { t.Fatalf("git %v: %v (%s)", args, err, string(out)) } } run(work, "init", "-b", "main") run(work, "config", "user.name", "Alice") run(work, "config", "user.email", "alice@example.com") if err := os.WriteFile(filepath.Join(work, "file.txt"), []byte("base\n"), 0o644); err != nil { t.Fatalf("write: %v", err) } run(work, "add", ".") run(work, "commit", "-m", "base commit") run(work, "push", basePath, "main") forkPath := filepath.Join(tmp, "fork.git") if err := CloneBare(ctx, basePath, forkPath); err != nil { t.Fatalf("CloneBare: %v", err) } // Add a feature branch on the fork. run(work, "checkout", "-b", "feature") if err := os.WriteFile(filepath.Join(work, "feature.txt"), []byte("feature\n"), 0o644); err != nil { t.Fatalf("write: %v", err) } run(work, "add", ".") run(work, "commit", "-m", "add feature") run(work, "push", forkPath, "feature") hash, err := MergeFromPath(ctx, basePath, forkPath, "main", "feature", "refs/polar/tmp-merge-test", "Merge PR #1", "Alice", "alice@example.com") if err != nil { t.Fatalf("MergeFromPath: %v", err) } if hash == "" { t.Fatalf("expected merge commit hash") } out, err := runGit(ctx, basePath, 10_000_000_000, "ls-tree", "-r", "--name-only", "main") if err != nil { t.Fatalf("ls-tree: %v", err) } if !strings.Contains(string(out), "feature.txt") { t.Fatalf("expected feature.txt on merged main, got: %s", string(out)) } // The temporary ref must be gone after the merge. if out, err := runGit(ctx, basePath, 10_000_000_000, "show-ref", "--verify", "--quiet", "refs/polar/tmp-merge-test"); err == nil { t.Fatalf("expected temp ref to be deleted, got %s", string(out)) } }