/** * Tests of merge conflicts (M4.8): the three-way line merge (one-sided, * identical and conflicting changes, touching changes, no base, missing * final line breaks, the initial result), the layout of the three * documents, reading untrusted `git.merge` and `git.conflictVersions` * results and the command params, merging with `flushDirty` first (clean, * up to date, conflicts, refusal, cancelled by a failed save), the dialog * (branches, the conflicts list from the shared status store, the resolve * view's three editors with accept left/right per chunk, accept all, a * chunk opening again when its base text is back, Apply writing the result through the file's buffer * then `git.markResolved`, deleted and binary files, abort with its * confirmation and git's refusal), the Changes window opening a * conflicted file in the resolve view, and the registration of the * commands. The engine is a fake behind the mocked Tauri `invoke` and * `listen`. */ import { flushPromises, mount, type VueWrapper } from "@vue/test-utils"; import { createPinia, setActivePinia, type Pinia } from "pinia"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { EditorView } from "@codemirror/view"; const invoke = vi.hoisted(() => vi.fn()); const listen = vi.hoisted(() => vi.fn()); vi.mock("@tauri-apps/api/core", () => ({ invoke })); vi.mock("@tauri-apps/api/event", () => ({ listen })); import { useModalsStore } from "../../src/commands/modals"; import { useCommandsStore } from "../../src/commands/store"; import { UI_COMMANDS } from "../../src/commands/uiCommands"; import ChangesToolWindow from "../../src/components/vcs/changes/ChangesToolWindow.vue"; import { useChangesStore } from "../../src/components/vcs/changes/changes"; import { initialResult, merge3, splitUnits, type MergeBlock } from "../../src/components/vcs/merge/diff3"; import MergeDialog from "../../src/components/vcs/merge/MergeDialog.vue"; import { parseResolveParams, phaseOf, toConflictVersions, toMergeAnswer, useMergeStore, } from "../../src/components/vcs/merge/merge"; import { layout } from "../../src/components/vcs/merge/resolveView"; import { useNotificationsStore } from "../../src/stores/notifications"; import { useProjectStore } from "../../src/stores/project"; import { useVcsStatusStore } from "../../src/stores/vcsStatus"; /** A buffer of the fake engine. */ interface FakeBuffer { path: string; text: string; version: number; saved: string; } /** A recorded engine call. */ interface Call { /** Command id. */ command: string; /** Its params. */ params: Record; } /** Every engine call, in order. */ let calls: Call[]; /** Fake engine buffers by id. */ let buffers: Map; /** Files on disk. */ let disk: Record; /** Next buffer id. */ let nextId: number; /** What `git.status` answers. */ let gitStatus: { available: boolean; repo: unknown; files: unknown[] }; /** What `git.merge` answers. */ let mergeAnswer: unknown; /** What `git.conflictVersions` answers, by path. */ let versions: Record; /** What `file.saveAll` answers. */ let saveAll: unknown; /** Errors to throw, by command id. */ let failures: Record; /** Pinia of the current test. */ let pinia: Pinia; /** Mounted components. */ let mounted: VueWrapper[]; /** The conflicted status entry of a path. */ function conflicted(path: string): unknown { return { path, index: "conflicted", worktree: "conflicted" }; } /** * The calls of a command. * * @param command - the command id. */ function callsOf(command: string): Call[] { return calls.filter((c) => c.command === command); } /** * Describes a buffer as `file.open` does. * * @param id - its id. */ function describeBuffer(id: number): unknown { const b = buffers.get(id); return b ? { id, path: b.path, text: b.text, version: b.version, dirty: b.text !== b.saved, lineEnding: "lf" } : null; } /** * The fake engine. * * @param command - command id. * @param p - params. */ function execute(command: string, p: Record): Promise { const failure = failures[command]; if (failure) { return Promise.reject(Object.assign(new Error(failure.message), failure)); } const id = typeof p.id === "number" ? p.id : -1; const b = buffers.get(id); switch (command) { case "git.status": return Promise.resolve(gitStatus); case "git.branches": return Promise.resolve({ current: "main", local: [{ name: "main", head: "1" }, { name: "feature", head: "2" }], remote: [{ name: "origin/release", head: "3" }], }); case "git.merge": return Promise.resolve(mergeAnswer); case "git.conflictVersions": return Promise.resolve(versions[String(p.path)] ?? null); case "git.markResolved": { const paths = p.paths as string[]; gitStatus = { ...gitStatus, files: gitStatus.files.filter((f) => !paths.includes((f as { path: string }).path)) }; return Promise.resolve({}); } case "file.saveAll": return Promise.resolve(saveAll); case "file.open": { const path = String(p.path); for (const [existing, buffer] of buffers) { if (buffer.path === path) { return Promise.resolve(describeBuffer(existing)); } } const text = disk[path]; if (text === undefined) { return Promise.reject(Object.assign(new Error(`${path}: not found`), { code: "failed", message: `${path}: not found` })); } const newId = nextId++; buffers.set(newId, { path, text, version: 1, saved: text }); return Promise.resolve(describeBuffer(newId)); } case "buffer.get": return Promise.resolve(describeBuffer(id)); case "buffer.edit": { if (!b || p.baseVersion !== b.version) { return Promise.reject(Object.assign(new Error("stale"), { code: "stale_version", message: "stale" })); } let out = ""; let pos = 0; for (const e of p.edits as { from: number; to: number; insert: string }[]) { out += b.text.slice(pos, e.from) + e.insert; pos = e.to; } b.text = out + b.text.slice(pos); b.version += 1; return Promise.resolve({ id, version: b.version, dirty: true }); } case "file.save": if (b) { b.saved = b.text; disk[b.path] = b.text; } return Promise.resolve({ id, version: b?.version ?? 0, dirty: false }); default: return Promise.resolve({}); } } /** jsdom has no layout; CodeMirror measures text ranges, so give ranges empty rectangles. */ function stubRangeGeometry(): void { const empty = (): DOMRectList => Object.assign([] as DOMRect[], { item: () => null }); Range.prototype.getClientRects = empty; Range.prototype.getBoundingClientRect = () => new DOMRect(0, 0, 0, 0); } /** Mounts the dialog with the status store, commands and a project. */ async function mountDialog(): Promise { useProjectStore(pinia).root = { path: "/p", name: "p" }; useVcsStatusStore(pinia).start(); const wrapper = mount(MergeDialog, { attachTo: document.body, global: { plugins: [pinia] } }); mounted.push(wrapper); await useCommandsStore(pinia).start(); await flushPromises(); return wrapper; } /** * Runs a command through the command store and waits. * * @param id - command id. * @param params - its params. */ async function runCommand(id: string, params: Record = {}): Promise { await useCommandsStore(pinia).execute(id, params as never); await flushPromises(); } /** Kinds of the blocks of a merge. */ function kinds(blocks: MergeBlock[]): string[] { return blocks.map((b) => b.kind); } /** Lines of a text. */ function lines(...items: string[]): string { return items.map((l) => `${l}\n`).join(""); } beforeEach(() => { stubRangeGeometry(); Element.prototype.scrollIntoView = () => undefined; pinia = createPinia(); setActivePinia(pinia); calls = []; buffers = new Map(); nextId = 1; mounted = []; failures = {}; saveAll = { saved: [], failed: [], skipped: [] }; mergeAnswer = { result: "conflicts", conflicts: ["a.php"] }; gitStatus = { available: true, repo: { root: "C:/p", branch: "main", detached: false, head: "0123456789" }, files: [conflicted("a.php"), { path: "b.php", index: "modified", worktree: "unmodified" }], }; disk = { "a.php": "<<<<<<< markers\n" }; versions = { "a.php": { base: lines(" Promise.resolve(() => undefined)); invoke.mockImplementation((cmd: string, args?: { command: string; params: Record }) => { if (cmd === "engine_list_commands") { return Promise.resolve([{ id: "git.status", label: "Git Status", enabled: true }]); } if ((cmd === "engine_execute" || cmd === "engine_execute_waiting") && args) { calls.push({ command: args.command, params: args.params }); return execute(args.command, args.params); } return Promise.resolve(null); }); }); afterEach(async () => { await flushPromises(); for (const wrapper of mounted) { wrapper.unmount(); } useCommandsStore(pinia).stop(); useVcsStatusStore(pinia).stop(); document.body.innerHTML = ""; }); describe("the three-way merge", () => { it("takes one-sided and identical changes and conflicts on different ones", () => { const base = splitUnits(lines("a", "b", "c", "d", "e", "f", "g")); const ours = splitUnits(lines("A", "b", "c", "D", "e", "f", "g", "h")); const theirs = splitUnits(lines("a", "b", "C", "d2", "e", "F", "g", "h")); const blocks = merge3(base, ours, theirs); expect(kinds(blocks)).toEqual(["ours", "stable", "conflict", "stable", "theirs", "stable", "both"]); expect(blocks[2]).toMatchObject({ base: ["c\n", "d\n"], ours: ["c\n", "D\n"], theirs: ["C\n", "d2\n"] }); expect(initialResult(blocks)).toBe(lines("A", "b", "c", "d", "e", "F", "g", "h")); }); it("joins every side's units back to its text", () => { const base = lines("1", "2", "3", "4"); const ours = lines("1", "x", "3", "4", "5"); const theirs = lines("0", "1", "2", "3", "4"); const blocks = merge3(splitUnits(base), splitUnits(ours), splitUnits(theirs)); expect(blocks.map((b) => b.base.join("")).join("")).toBe(base); expect(blocks.map((b) => b.ours.join("")).join("")).toBe(ours); expect(blocks.map((b) => b.theirs.join("")).join("")).toBe(theirs); expect(blocks.some((b) => b.kind === "conflict")).toBe(false); expect(initialResult(blocks)).toBe(lines("0", "1", "x", "3", "4", "5")); }); it("gives every side back for random texts, and equals a side changed alone", () => { let seed = 7; const next = (n: number): number => { seed = (seed * 1103515245 + 12345) % 2147483648; return seed % n; }; const mutate = (units: string[]): string[] => { const out = [...units]; for (let k = next(4); k > 0; k -= 1) { const at = next(out.length + 1); if (next(2) === 0) { out.splice(at, 1); } else { out.splice(at, 0, `${String(next(5))}\n`); } } return out; }; for (let round = 0; round < 300; round += 1) { const base = Array.from({ length: next(8) }, () => `${String(next(5))}\n`); const ours = mutate(base); const theirs = mutate(base); const blocks = merge3(base, ours, theirs); expect(blocks.map((b) => b.base.join("")).join("")).toBe(base.join("")); expect(blocks.map((b) => b.ours.join("")).join("")).toBe(ours.join("")); expect(blocks.map((b) => b.theirs.join("")).join("")).toBe(theirs.join("")); expect(initialResult(merge3(base, ours, base))).toBe(ours.join("")); expect(initialResult(merge3(base, base, theirs))).toBe(theirs.join("")); } }); it("treats touching changes as a conflict, as git does", () => { const blocks = merge3(splitUnits(lines("a", "b", "c")), splitUnits(lines("a", "B", "c")), splitUnits(lines("a", "b", "C"))); expect(kinds(blocks)).toEqual(["stable", "conflict"]); }); it("compares ours and theirs directly without a base", () => { const blocks = merge3(null, splitUnits(lines(" { expect(splitUnits("a\nb")).toEqual(["a\n", "b"]); expect(splitUnits("")).toEqual([]); const blocks = merge3(splitUnits("a\nb"), splitUnits("a\nb\n"), splitUnits("a\nb")); expect(initialResult(blocks)).toBe("a\nb\n"); }); it("lays out the documents with the chunks' places", () => { const lay = layout("x\nbase\ny\n", "x\nours\ny\n", "x\ntheirs\ny\n"); expect(lay.result).toBe("x\nbase\ny\n"); expect(lay.chunks).toEqual([{ ours: "ours\n", theirs: "theirs\n", oursFrom: 2, oursTo: 7, theirsFrom: 2, theirsTo: 9 }]); expect(lay.resultRanges).toEqual([{ from: 2, to: 7 }]); expect(lay.oursMarks).toEqual([{ from: 2, to: 7, conflict: true }]); }); }); describe("reading results and params", () => { it("checks git.merge and git.conflictVersions", () => { expect(toMergeAnswer({ result: "conflicts", conflicts: ["a", 3, ""] })).toEqual({ result: "conflicts", conflicts: ["a"] }); expect(toMergeAnswer({ result: "upToDate" })).toEqual({ result: "upToDate", conflicts: [] }); expect(toMergeAnswer({ result: "weird" })).toBeNull(); expect(toMergeAnswer([1])).toBeNull(); const v = toConflictVersions({ ours: "a\r\nb", theirs: null, binary: false }); expect(v).toEqual({ base: null, ours: "a\nb", theirs: null, binary: false, tooLarge: false }); expect(v && phaseOf(v)).toBe("deleted"); expect(toConflictVersions({ ours: 3, theirs: "x" })).toBeNull(); expect(toConflictVersions(null)).toBeNull(); expect(phaseOf({ base: null, ours: null, theirs: null, binary: true, tooLarge: false })).toBe("binary"); expect(phaseOf({ base: null, ours: "", theirs: "", binary: false, tooLarge: false })).toBe("text"); }); it("checks the params of vcs.resolveConflicts", () => { expect(parseResolveParams({})).toBeNull(); expect(parseResolveParams(null)).toBeNull(); expect(parseResolveParams({ path: "a.php" })).toBe("a.php"); expect(parseResolveParams({ path: 3 })).toBeUndefined(); expect(parseResolveParams({ path: "" })).toBeUndefined(); }); }); describe("merging", () => { it("saves first, merges and opens the conflicts list", async () => { const wrapper = await mountDialog(); await runCommand("vcs.merge", { branch: "feature" }); const order = calls.map((c) => c.command); expect(order.indexOf("file.saveAll")).toBeLessThan(order.indexOf("git.merge")); expect(callsOf("git.merge")[0]?.params).toEqual({ branch: "feature" }); const merge = useMergeStore(pinia); expect(merge.mode).toBe("conflicts"); expect(wrapper.findAll("[data-test=merge-conflict]").map((r) => r.attributes("data-path"))).toEqual(["a.php"]); expect(useNotificationsStore(pinia).toasts.at(-1)?.level).toBe("warning"); expect(useModalsStore(pinia).current).toBe("merge"); }); it("toasts a clean merge and an up-to-date one, and closes", async () => { await mountDialog(); mergeAnswer = { result: "merged", conflicts: [] }; await runCommand("vcs.merge", { branch: "feature" }); expect(useMergeStore(pinia).mode).toBe("closed"); expect(useNotificationsStore(pinia).toasts.at(-1)?.text).toContain("Merged feature"); mergeAnswer = { result: "upToDate", conflicts: [] }; await runCommand("vcs.merge", { branch: "feature" }); expect(useNotificationsStore(pinia).toasts.at(-1)?.text).toContain("up to date"); }); it("toasts git's refusal and a failed save cancels the merge", async () => { await mountDialog(); failures["git.merge"] = { code: "failed", message: "Your local changes would be overwritten" }; await runCommand("vcs.merge", { branch: "feature" }); expect(useNotificationsStore(pinia).toasts.at(-1)?.text).toContain("Your local changes would be overwritten"); delete failures["git.merge"]; calls = []; saveAll = { saved: [], failed: [{ id: 1, path: "x.php", message: "denied" }], skipped: [] }; await runCommand("vcs.merge", { branch: "feature" }); expect(callsOf("git.merge")).toHaveLength(0); expect(useNotificationsStore(pinia).toasts.some((n) => n.text.includes("cancelled"))).toBe(true); }); it("lists the other branches and merges the one chosen", async () => { const wrapper = await mountDialog(); await runCommand("vcs.merge"); expect(wrapper.get("[data-test=merge-title]").text()).toBe("Merge into main"); expect(wrapper.findAll("[data-test=merge-branch]").map((b) => b.text())).toEqual(["feature", "origin/release"]); await wrapper.get("[data-test=merge-filter]").setValue("rel"); expect(wrapper.findAll("[data-test=merge-branch]").map((b) => b.text())).toEqual(["origin/release"]); await wrapper.get("[data-test=merge-filter]").trigger("keydown", { key: "Enter" }); await flushPromises(); expect(callsOf("git.merge")[0]?.params).toEqual({ branch: "origin/release" }); }); }); describe("resolving a file", () => { /** Opens the resolve view of a.php. */ async function openResolve(): Promise { const wrapper = await mountDialog(); await runCommand("vcs.resolveConflicts", { path: "a.php" }); await flushPromises(); return wrapper; } /** * The text of one of the three editors. * * @param wrapper - the dialog. * @param pane - ours, result or theirs. */ function paneText(wrapper: VueWrapper, pane: "ours" | "result" | "theirs"): string { return [...wrapper.get(`[data-test=merge-${pane}]`).element.querySelectorAll(".cm-line")].map((l) => l.textContent).join("\n"); } it("shows ours, the merged result and theirs with the conflict open", async () => { const wrapper = await openResolve(); expect(callsOf("git.conflictVersions")[0]?.params).toEqual({ path: "a.php" }); expect(paneText(wrapper, "ours")).toContain("four (main)"); expect(paneText(wrapper, "theirs")).toContain("three (feature)"); expect(paneText(wrapper, "result")).toContain("ONE"); expect(paneText(wrapper, "result")).toContain("three"); expect(wrapper.get("[data-test=merge-counter]").text()).toBe("1 of 1 conflicts open"); expect(wrapper.get("[data-test=merge-apply]").attributes("disabled")).toBeDefined(); expect(wrapper.findAll(".lt-merge-accept")).toHaveLength(2); }); it("accepts right per chunk, undo reopens it, and Apply writes and marks resolved", async () => { const wrapper = await openResolve(); await wrapper.get("[data-test=merge-accept-right]").trigger("click"); await flushPromises(); expect(paneText(wrapper, "result")).toContain("three (feature)"); expect(wrapper.get("[data-test=merge-counter]").text()).toBe("No open conflicts"); expect(wrapper.findAll(".lt-merge-accept")).toHaveLength(0); await wrapper.get("[data-test=merge-accept-left]").trigger("click"); await wrapper.get("[data-test=merge-apply]").trigger("click"); await flushPromises(); expect(disk["a.php"]).toBe(lines(" c.command); expect(order.lastIndexOf("file.save")).toBeLessThan(order.indexOf("git.markResolved")); expect(callsOf("git.markResolved")[0]?.params).toEqual({ paths: ["a.php"] }); expect(useMergeStore(pinia).mode).toBe("conflicts"); expect(wrapper.find("[data-test=merge-none]").exists()).toBe(true); expect(wrapper.find("[data-test=merge-commit]").exists()).toBe(true); }); it("accepts all left, and restoring the base's text opens the chunk again", async () => { const wrapper = await openResolve(); await wrapper.get("[data-test=merge-all-left]").trigger("click"); await flushPromises(); expect(paneText(wrapper, "result")).toContain("four (main)"); expect(wrapper.get("[data-test=merge-counter]").text()).toBe("No open conflicts"); const dom = wrapper.get("[data-test=merge-result]").element.querySelector(".cm-editor"); const view = dom ? EditorView.findFromDOM(dom as HTMLElement) : null; expect(view).not.toBeNull(); if (view) { const text = view.state.doc.toString(); const taken = "three\nfour (main)\n"; const from = text.indexOf(taken); view.dispatch({ changes: { from, to: from + taken.length, insert: "three\nfour\n" } }); } await flushPromises(); expect(wrapper.get("[data-test=merge-counter]").text()).toBe("1 of 1 conflicts open"); expect(wrapper.findAll(".lt-merge-accept")).toHaveLength(2); }); it("keeps the side that was not deleted, and marks binary files resolved as they are", async () => { versions["a.php"] = { base: "x\n", ours: null, theirs: "y\n", binary: false, tooLarge: false }; const wrapper = await openResolve(); expect(wrapper.find("[data-test=merge-deleted]").exists()).toBe(true); expect(wrapper.find("[data-test=merge-keep-ours]").exists()).toBe(false); await wrapper.get("[data-test=merge-keep-theirs]").trigger("click"); await flushPromises(); expect(disk["a.php"]).toBe("y\n"); gitStatus = { ...gitStatus, files: [conflicted("img.png")] }; versions["img.png"] = { ours: null, theirs: null, binary: true, tooLarge: false }; await useVcsStatusStore(pinia).refresh(); await runCommand("vcs.resolveConflicts", { path: "img.png" }); expect(wrapper.find("[data-test=merge-binary]").exists()).toBe(true); await wrapper.get("[data-test=merge-mark-as-is]").trigger("click"); await flushPromises(); expect(callsOf("git.markResolved").at(-1)?.params).toEqual({ paths: ["img.png"] }); expect(callsOf("file.open").filter((c) => c.params.path === "img.png")).toHaveLength(0); }); it("shows git's error for a file that is not in conflict", async () => { failures["git.conflictVersions"] = { code: "failed", message: "a.php is not in conflict" }; const wrapper = await openResolve(); expect(wrapper.get("[data-test=merge-error]").text()).toContain("a.php is not in conflict"); }); }); describe("aborting", () => { it("asks first, then aborts; git's refusal stays in the dialog", async () => { const wrapper = await mountDialog(); await runCommand("vcs.abortMerge"); expect(callsOf("git.mergeAbort")).toHaveLength(0); failures["git.mergeAbort"] = { code: "failed", message: "There is no merge to abort (MERGE_HEAD missing)." }; await wrapper.get("[data-test=merge-abort]").trigger("click"); await flushPromises(); expect(wrapper.get("[data-test=merge-error]").text()).toContain("MERGE_HEAD missing"); delete failures["git.mergeAbort"]; await wrapper.get("[data-test=merge-abort]").trigger("click"); await flushPromises(); expect(callsOf("git.mergeAbort")).toHaveLength(2); expect(useMergeStore(pinia).mode).toBe("closed"); expect(wrapper.find("[data-test=merge]").exists()).toBe(false); }); it("Escape closes the list", async () => { const wrapper = await mountDialog(); await runCommand("vcs.resolveConflicts"); await wrapper.get("[data-test=merge-dialog]").trigger("keydown", { key: "Escape" }); expect(useMergeStore(pinia).mode).toBe("closed"); expect(useModalsStore(pinia).current).toBeNull(); }); }); describe("entry points", () => { it("registers the merge commands without default shortcuts", () => { for (const id of ["vcs.merge", "vcs.resolveConflicts", "vcs.abortMerge"]) { const spec = UI_COMMANDS.find((c) => c.id === id); expect(spec?.menuPath?.startsWith("Git/")).toBe(true); expect(spec?.defaultShortcut).toBeUndefined(); } }); it("opens a conflicted file from the Changes window in the resolve view", async () => { await mountDialog(); useChangesStore(pinia).start(); const changes = mount(ChangesToolWindow, { attachTo: document.body, global: { plugins: [pinia] } }); mounted.push(changes); await flushPromises(); const row = changes.findAll("[data-test=changes-row]").find((r) => r.text().includes("a.php")); expect(row).toBeDefined(); await row?.trigger("dblclick"); await flushPromises(); expect(useMergeStore(pinia).mode).toBe("resolve"); expect(useMergeStore(pinia).path).toBe("a.php"); useChangesStore(pinia).stop(); }); });