using System.Net; using Forge.Data; using Forge.Features.History; using Forge.Features.Repos; using Forge.Tests.Support; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; namespace Forge.Tests; /// Compare, merge, and creating or deleting branches and tags from the web UI. public class MergeTests(ForgeHost host) : IClassFixture { private sealed record Scenario(Repository Repo, string Work, string Url, string MainSha, string FeatureSha); /// /// A repository with main and a branch "feature/x" that adds b.txt and edits line two of a.txt. /// With , main also gets a commit of its own: a different file, or the same line for a conflict. /// private async Task CreateAsync(string name, bool diverge = false, bool conflict = false, Visibility visibility = Visibility.Public) { var user = await host.CreateUserAsync(); var repo = await host.CreateRepoAsync(user, name, visibility); var token = await host.CreateTokenAsync(user, canWrite: true); var url = host.GitUrl("jessie", name, token); var work = host.NewDir("work"); await host.Git.CreateWorkRepoAsync(work, fileName: "a.txt", content: "one\ntwo\nthree\n"); await host.Git.MustAsync(work, "checkout", "-b", "feature/x"); await File.WriteAllTextAsync(Path.Combine(work, "a.txt"), "one\nTWO from feature\nthree\n"); await File.WriteAllTextAsync(Path.Combine(work, "b.txt"), "new file\n"); await host.Git.MustAsync(work, "add", "-A"); await host.Git.MustAsync(work, "commit", "-m", "Feature work"); await File.WriteAllTextAsync(Path.Combine(work, "b.txt"), "new file\nsecond line\n"); await host.Git.MustAsync(work, "commit", "-am", "More feature work"); var featureSha = await host.Git.MustAsync(work, "rev-parse", "HEAD"); await host.Git.MustAsync(work, "checkout", "main"); if (diverge) { var (file, content) = conflict ? ("a.txt", "one\nTWO from main\nthree\n") : ("c.txt", "only on main\n"); await File.WriteAllTextAsync(Path.Combine(work, file), content); await host.Git.MustAsync(work, "add", "-A"); await host.Git.MustAsync(work, "commit", "-m", "Main moves on"); } var mainSha = await host.Git.MustAsync(work, "rev-parse", "HEAD"); await host.Git.MustAsync(work, "push", url, "main", "feature/x"); return new Scenario(repo, work, url, mainSha, featureSha); } /// Fetches the server's state into the scenario's working repository and returns `git` output for it. private async Task ServerAsync(Scenario s, params string[] args) { await host.Git.MustAsync(s.Work, "fetch", "--prune", s.Url, "+refs/heads/*:refs/remotes/server/*"); return await host.Git.MustAsync(s.Work, args); } private Task> EventsAsync(long repoId) => host.WithScopeAsync(sp => sp.GetRequiredService().PushEvents .Where(e => e.RepoId == repoId).OrderBy(e => e.Id).ToListAsync()); private Task MergeViaServiceAsync(Scenario s, MergeMethod method) => host.WithScopeAsync(async sp => { var repo = await sp.GetRequiredService().FindAsync("jessie", s.Repo.Name); var refs = sp.GetRequiredService(); return await refs.MergeAsync(repo!, new Git.GitIdentity("Jessie", "jessie@forge.test"), "main", "feature/x", method, null); }); [Fact] public async Task Compare_shows_commits_and_diff_and_offers_merge_only_to_the_owner() { var s = await CreateAsync("compare", diverge: true); using var anonymous = host.CreateClient(); using var owner = await host.CreateSignedInClientAsync(); var page = await anonymous.GetStringAsync("/jessie/compare/compare/main...feature/x"); Assert.Contains("Feature work", page); Assert.Contains("More feature work", page); Assert.DoesNotContain("Main moves on", page); Assert.Contains("2 commits", page); Assert.Contains("b.txt", page); Assert.Contains("TWO from feature", page); // The diff is taken from the point where the branches diverged, so main's own change is not in it. Assert.DoesNotContain("only on main", page); Assert.DoesNotContain("name=\"Method\"", page); var ownerPage = await owner.GetStringAsync("/jessie/compare/compare/main...feature/x"); Assert.Contains("These branches can be merged automatically.", ownerPage); Assert.Contains("name=\"Method\"", ownerPage); // Diverged branches cannot fast-forward. Assert.DoesNotContain("value=\"ff\"", ownerPage); // Two SHAs work too (webhook payloads link like this), and so does the picker's query form. Assert.Equal(HttpStatusCode.OK, (await anonymous.GetAsync($"/jessie/compare/compare/{s.MainSha}...{s.FeatureSha}")).StatusCode); var picked = await anonymous.GetAsync("/jessie/compare/compare?base=main&head=feature%2Fx"); Assert.Equal("/jessie/compare/compare/main...feature/x", picked.Headers.Location?.PathAndQuery); Assert.Equal(HttpStatusCode.OK, (await anonymous.GetAsync("/jessie/compare/compare")).StatusCode); Assert.Equal(HttpStatusCode.NotFound, (await anonymous.GetAsync("/jessie/compare/compare/main...nope")).StatusCode); Assert.Equal(HttpStatusCode.NotFound, (await anonymous.GetAsync("/jessie/compare/compare/--all...main")).StatusCode); // The branches page links to the comparison. Assert.Contains("href=\"/jessie/compare/compare/main...feature/x\"", await anonymous.GetStringAsync("/jessie/compare/branches")); } [Fact] public async Task Merge_commit_from_the_page_joins_both_histories_and_can_delete_the_branch() { var s = await CreateAsync("merge-commit", diverge: true); using var owner = await host.CreateSignedInClientAsync(); var merged = await ForgeHost.PostFormAsync(owner, "/jessie/merge-commit/compare/main...feature/x", "merge", new() { ["Method"] = "merge", ["Message"] = "", ["DeleteBranch"] = "true", }); Assert.Equal("/jessie/merge-commit/tree/main", merged.Headers.Location?.PathAndQuery); // The new commit has both tips as parents and carries both sides' changes. var parents = (await ServerAsync(s, "log", "-1", "--format=%P", "server/main")).Split(' '); Assert.Equal([s.MainSha, s.FeatureSha], parents); Assert.Equal("Merge branch 'feature/x' into main", await host.Git.MustAsync(s.Work, "log", "-1", "--format=%s", "server/main")); Assert.Equal("jessie ", await host.Git.MustAsync(s.Work, "log", "-1", "--format=%an <%ae>", "server/main")); var files = await host.Git.MustAsync(s.Work, "ls-tree", "--name-only", "server/main"); Assert.Equal(["a.txt", "b.txt", "c.txt"], files.Split('\n')); Assert.Contains("TWO from feature", await host.Git.MustAsync(s.Work, "show", "server/main:a.txt")); // The branch is gone, and both changes were recorded like pushes. Assert.DoesNotContain("server/feature/x", await host.Git.MustAsync(s.Work, "branch", "-r")); var events = (await EventsAsync(s.Repo.Id)).Skip(2).ToList(); Assert.Collection( events, e => Assert.Equal(("refs/heads/main", s.MainSha), (e.RefName, e.OldSha)), e => Assert.Equal(("refs/heads/feature/x", s.FeatureSha, Git.GitParsers.ZeroSha), (e.RefName, e.OldSha, e.NewSha))); // A normal git client accepts the result: pulling it is a fast-forward. await host.Git.MustAsync(s.Work, "pull", "--ff-only", s.Url, "main"); } [Fact] public async Task Squash_creates_one_commit_with_a_single_parent() { var s = await CreateAsync("squash", diverge: true); using var owner = await host.CreateSignedInClientAsync(); await ForgeHost.PostFormAsync(owner, "/jessie/squash/compare/main...feature/x", "merge", new() { ["Method"] = "squash", ["Message"] = "", }); Assert.Equal(s.MainSha, await ServerAsync(s, "log", "-1", "--format=%P", "server/main")); var message = await host.Git.MustAsync(s.Work, "log", "-1", "--format=%B", "server/main"); Assert.StartsWith("Squash branch 'feature/x' into main", message); Assert.Contains("* Feature work", message); Assert.Contains("* More feature work", message); Assert.Equal("new file\nsecond line", await host.Git.MustAsync(s.Work, "show", "server/main:b.txt")); // Without the checkbox the branch stays. Assert.Contains("server/feature/x", await host.Git.MustAsync(s.Work, "branch", "-r")); } [Fact] public async Task Fast_forward_moves_the_branch_without_a_new_commit() { var s = await CreateAsync("fast-forward"); using var owner = await host.CreateSignedInClientAsync(); var page = await owner.GetStringAsync("/jessie/fast-forward/compare/main...feature/x"); Assert.Contains("value=\"ff\"", page); await ForgeHost.PostFormAsync(owner, "/jessie/fast-forward/compare/main...feature/x", "merge", new() { ["Method"] = "ff", ["Message"] = "ignored", }); Assert.Equal(s.FeatureSha, await ServerAsync(s, "rev-parse", "server/main")); // Now there is nothing left to merge, and the page says so instead of offering the form. var after = await owner.GetStringAsync("/jessie/fast-forward/compare/main...feature/x"); Assert.DoesNotContain("name=\"Method\"", after); Assert.Equal("There is nothing to merge.", (await MergeViaServiceAsync(s, MergeMethod.MergeCommit)).Error); } [Fact] public async Task Custom_message_is_used_for_the_merge_commit() { var s = await CreateAsync("message", diverge: true); using var owner = await host.CreateSignedInClientAsync(); await ForgeHost.PostFormAsync(owner, "/jessie/message/compare/main...feature/x", "merge", new() { ["Method"] = "merge", ["Message"] = "--amend is just text here", }); Assert.Equal("--amend is just text here", await ServerAsync(s, "log", "-1", "--format=%s", "server/main")); } [Fact] public async Task Conflicting_branches_are_reported_and_left_alone() { var s = await CreateAsync("conflict", diverge: true, conflict: true); using var owner = await host.CreateSignedInClientAsync(); var page = await owner.GetStringAsync("/jessie/conflict/compare/main...feature/x"); Assert.Contains("These branches have conflicts", page); Assert.Contains("a.txt", page); Assert.DoesNotContain("name=\"Method\"", page); foreach (var method in (MergeMethod[])[MergeMethod.MergeCommit, MergeMethod.Squash]) { var result = await MergeViaServiceAsync(s, method); Assert.Equal("The branches have conflicts and cannot be merged automatically.", result.Error); Assert.Equal(["a.txt"], result.Conflicts); } Assert.Equal( "Fast-forward is not possible because the branches have diverged.", (await MergeViaServiceAsync(s, MergeMethod.FastForward)).Error); Assert.Equal(s.MainSha, await ServerAsync(s, "rev-parse", "server/main")); Assert.Equal(2, (await EventsAsync(s.Repo.Id)).Count); } [Fact] public async Task Visitors_cannot_merge_or_change_refs() { var s = await CreateAsync("visitor", diverge: true); using var anonymous = host.CreateClient(); // The compare page renders no merge form for a visitor, so the post has nothing to bind to. var merge = await ForgeHost.PostFormAsync(anonymous, "/jessie/visitor/compare/main...feature/x", "merge", new() { ["Method"] = "merge" }); Assert.Equal(HttpStatusCode.BadRequest, merge.StatusCode); // The delete form is on the page for everyone (its buttons are not); the handler must refuse on its own. await ForgeHost.PostFormAsync(anonymous, "/jessie/visitor/branches", "delete-branch", new() { ["DeleteName"] = "feature/x" }); await ForgeHost.PostFormAsync(anonymous, "/jessie/visitor/branches", "create-branch", new() { ["NewName"] = "sneaky", ["From"] = "main" }); var branches = await ServerAsync(s, "branch", "-r"); Assert.Contains("server/feature/x", branches); Assert.DoesNotContain("sneaky", branches); Assert.Equal(s.MainSha, await host.Git.MustAsync(s.Work, "rev-parse", "server/main")); // Nothing in a private repository is reachable at all. await CreateAsync("visitor-private", visibility: Visibility.Private); Assert.Equal(HttpStatusCode.NotFound, (await anonymous.GetAsync("/jessie/visitor-private/compare/main...feature/x")).StatusCode); Assert.Equal(HttpStatusCode.NotFound, (await anonymous.GetAsync("/jessie/visitor-private/compare")).StatusCode); } [Fact] public async Task Branches_are_created_and_deleted_from_the_page() { var s = await CreateAsync("branches"); using var owner = await host.CreateSignedInClientAsync(); const string page = "/jessie/branches/branches"; var created = await ForgeHost.PostFormAsync(owner, page, "create-branch", new() { ["NewName"] = "release/1.0", ["From"] = "feature/x" }); Assert.Contains("Branch release/1.0 was created.", await ForgeHost.TextAsync(created)); Assert.Equal(s.FeatureSha, await ServerAsync(s, "rev-parse", "server/release/1.0")); // From a commit SHA. await ForgeHost.PostFormAsync(owner, page, "create-branch", new() { ["NewName"] = "from-sha", ["From"] = s.MainSha }); Assert.Equal(s.MainSha, await ServerAsync(s, "rev-parse", "server/from-sha")); var duplicate = await ForgeHost.PostFormAsync(owner, page, "create-branch", new() { ["NewName"] = "from-sha", ["From"] = "main" }); Assert.Contains("A branch with this name already exists.", await ForgeHost.TextAsync(duplicate)); var missing = await ForgeHost.PostFormAsync(owner, page, "create-branch", new() { ["NewName"] = "ok-name", ["From"] = "nope" }); Assert.Contains("The starting point does not exist.", await ForgeHost.TextAsync(missing)); foreach (var bad in (string[])["-x", "--force", "a..b", "has space", "ends.lock", "a~1", "HEAD", "x/", "a:b"]) { var refused = await ForgeHost.PostFormAsync(owner, page, "create-branch", new() { ["NewName"] = bad, ["From"] = "main" }); Assert.True( (await ForgeHost.TextAsync(refused)).Contains("This is not a valid branch name."), $"Branch name '{bad}' was not refused."); } var deleted = await ForgeHost.PostFormAsync(owner, page, "delete-branch", new() { ["DeleteName"] = "release/1.0" }); Assert.Contains($"Branch release/1.0 was deleted (it pointed at {s.FeatureSha}).", await ForgeHost.TextAsync(deleted)); var protectedDefault = await ForgeHost.PostFormAsync(owner, page, "delete-branch", new() { ["DeleteName"] = "main" }); Assert.Contains("The default branch cannot be deleted.", await ForgeHost.TextAsync(protectedDefault)); var branches = (await ServerAsync(s, "branch", "-r")).Split('\n').Select(b => b.Trim()).Order().ToList(); Assert.Equal(["server/feature/x", "server/from-sha", "server/main"], branches); // Creations and the deletion were recorded as push events, after the two from the initial push. var events = (await EventsAsync(s.Repo.Id)).Skip(2).Select(e => (e.RefName, Created: e.OldSha == Git.GitParsers.ZeroSha, Deleted: e.NewSha == Git.GitParsers.ZeroSha)).ToList(); Assert.Equal( [ ("refs/heads/release/1.0", true, false), ("refs/heads/from-sha", true, false), ("refs/heads/release/1.0", false, true), ], events); } [Fact] public async Task Tags_are_created_and_deleted_from_the_page() { var s = await CreateAsync("tags"); using var owner = await host.CreateSignedInClientAsync(); const string page = "/jessie/tags/tags"; var created = await ForgeHost.PostFormAsync(owner, page, "create-tag", new() { ["NewName"] = "v1.0", ["From"] = "feature/x" }); var html = await ForgeHost.TextAsync(created); Assert.Contains("Tag v1.0 was created.", html); Assert.Contains("href=\"/jessie/tags/tree/v1.0\"", html); await host.Git.MustAsync(s.Work, "fetch", "--tags", s.Url); Assert.Equal(s.FeatureSha, await host.Git.MustAsync(s.Work, "rev-parse", "v1.0^{commit}")); var duplicate = await ForgeHost.PostFormAsync(owner, page, "create-tag", new() { ["NewName"] = "v1.0", ["From"] = "main" }); Assert.Contains("A tag with this name already exists.", await ForgeHost.TextAsync(duplicate)); var invalid = await ForgeHost.PostFormAsync(owner, page, "create-tag", new() { ["NewName"] = "-d", ["From"] = "main" }); Assert.Contains("This is not a valid tag name.", await ForgeHost.TextAsync(invalid)); var deleted = await ForgeHost.PostFormAsync(owner, page, "delete-tag", new() { ["DeleteName"] = "v1.0" }); Assert.Contains($"Tag v1.0 was deleted (it pointed at {s.FeatureSha}).", await ForgeHost.TextAsync(deleted)); Assert.Equal("", await host.Git.MustAsync(s.Work, "ls-remote", "--tags", s.Url)); } }