diff --git a/src/features/vcs/__tests__/mergeCommitLeftOut.test.tsx b/src/features/vcs/__tests__/mergeCommitLeftOut.test.tsx new file mode 100644 index 000000000..73ebd5ba1 --- /dev/null +++ b/src/features/vcs/__tests__/mergeCommitLeftOut.test.tsx @@ -0,0 +1,336 @@ +import { act, cleanup, fireEvent, render, screen } from "@testing-library/react"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +const commit = vi.hoisted(() => vi.fn()); +const pendingPatch = vi.hoisted(() => vi.fn()); +const fileAt = vi.hoisted(() => vi.fn()); +const readText = vi.hoisted(() => vi.fn()); +const diffHunks = vi.hoisted(() => vi.fn()); + +vi.mock("@/platform/ipc", async (importOriginal) => { + const real = await importOriginal(); + const ok = (data: unknown) => Promise.resolve({ status: "ok" as const, data }); + return { + ...real, + isTauri: () => false, + call: async (p: Promise<{ status: "ok"; data: unknown }>) => (await p).data, + commands: { + ...real.commands, + vcsCommit: commit.mockImplementation(() => ok("commit1")), + vcsPendingPatch: pendingPatch.mockImplementation(() => ok("diff --git a/f b/f\n")), + vcsConfigGet: () => ok("configured"), + vcsFileAt: fileAt, + fsReadText: readText, + vcsDiffHunks: diffHunks, + }, + }; +}); + +import type { BranchInfo, CommitOptions, FileStatus } from "@/bindings"; +import { useProject } from "@/platform/project"; +import { maybeCommitService, provideNotificationService } from "@/workbench/contributions"; +import { MessagesHost } from "@/workbench/messages"; +import { checkCommitChanges, commitChanges } from "../changeOps"; +import { useChangelists } from "../changelists"; +import { provideCommit } from "../commitSelection"; +import { useCommit } from "../commitStore"; +import { hunkKeys } from "../hunks"; +import { useVcs } from "../store"; + +const TITLE = "Changes Excluded from Merge Commit"; + +const file = (path: string, staged: FileStatus["staged"], unstaged: FileStatus["unstaged"] = null): FileStatus => ({ + path, + relPath: path.replace(/^\/(p\/lib|p)\//, ""), + staged, + unstaged, + renamedFrom: null, +}); + +// What a merge with one resolved conflict leaves: f.txt resolved, g.txt and n.txt merged by Git. +const incoming = [file("/p/f.txt", "modified"), file("/p/g.txt", "modified"), file("/p/n.txt", "added")]; + +const branch = (operation: string | null) => ({ head: "main", operation }) as BranchInfo; +const settings = (vcs: object) => useProject.setState({ settings: { vcs } as never }); +const uncheck = (...paths: string[]) => useCommit.setState({ checks: new Map(paths.map((p) => [p, "none" as const])) }); +const sent = (call = 0) => commit.mock.calls[call]?.[2] as CommitOptions; +const notify = vi.fn(); + +/** Starts the commit; the returned function answers the dialog, which must be showing, and ends it. */ +async function startCommit() { + let result: ReturnType; + await act(async () => { + result = commitChanges(); + for (let i = 0; i < 40; i++) { + // oxlint-disable-next-line no-await-in-loop -- each await flushes one microtask turn; the number of turns is the point + await Promise.resolve(); + } + }); + return { + asked: () => screen.queryByText(TITLE) !== null, + answer: async (act_: () => void) => { + await act(async () => { + act_(); + await result; + }); + return result; + }, + result: async () => result, + }; +} +const press = (name: string) => () => fireEvent.click(screen.getByRole("button", { name })); + +let dispose: () => void; + +beforeEach(() => { + localStorage.clear(); + commit.mockClear(); + pendingPatch.mockClear(); + notify.mockClear(); + provideNotificationService({ notify } as never); + useProject.setState({ settings: null }); + useChangelists.setState({ + state: { lists: [{ id: "default", name: "Changes", comment: "" }], active: "default", files: {} }, + }); + useVcs.setState({ + available: false, + root: "/p", + repo: "/p", + roots: ["/p"], + kinds: { "/p": "git" }, + status: incoming, + branch: branch("merge"), + operations: { "/p": "merge" }, + heads: {}, + }); + useCommit.setState({ + message: "Merge branch 'topic'", + amend: false, + checks: new Map(), + excludedHunks: new Map(), + excludedHunkLines: new Map(), + checkResult: null, + operation: null, + }); + dispose = provideCommit(); + render(); +}); + +afterEach(() => { + dispose(); + cleanup(); +}); + +describe("a merge commit with nothing checked", () => { + beforeEach(() => settings({ commit: { includeChangesByDefault: false } })); + + it("takes the merge as it is", async () => { + const started = await startCommit(); + expect(started.asked()).toBe(false); + expect(await started.result()).toEqual([{ repo: "/p", id: "commit1" }]); + expect(sent()).toMatchObject({ stage: [], exclude: [], partial: [] }); + }); + + it("is the same when the user unchecked every file", async () => { + settings({}); + uncheck(...incoming.map((f) => f.path)); + const started = await startCommit(); + expect(started.asked()).toBe(false); + expect(await started.result()).toEqual([{ repo: "/p", id: "commit1" }]); + expect(sent().exclude).toEqual([]); + }); + + it("is what plugins see", async () => { + const service = maybeCommitService()!; + expect((await service.selection())!.repositories[0]!.options.exclude).toEqual([]); + expect((await service.changes())!.patch).toContain("diff --git"); + expect(pendingPatch.mock.calls[0]?.[1]).toMatchObject({ stage: [], exclude: [], partial: [] }); + }); + + it("commits nothing outside a merge", async () => { + useVcs.setState({ branch: branch(null), operations: {} }); + expect(await (await startCommit()).result()).toBeUndefined(); + expect(commit).not.toHaveBeenCalled(); + expect(notify).toHaveBeenCalledWith(expect.objectContaining({ title: "No changes selected for commit" })); + }); + + it("commits nothing in a rebase", async () => { + useVcs.setState({ branch: branch("rebase"), operations: { "/p": "rebase" } }); + expect(await (await startCommit()).result()).toBeUndefined(); + expect(commit).not.toHaveBeenCalled(); + }); + + it("still leaves the staged files out of an amended commit's message change", async () => { + useVcs.setState({ branch: branch(null), operations: {} }); + useCommit.setState({ amend: true }); + expect(await (await startCommit()).result()).toEqual([{ repo: "/p", id: "commit1" }]); + expect(sent().exclude).toEqual(incoming.map((f) => f.path)); + }); +}); + +describe("a merge commit with some changes left out", () => { + it("asks first, with Cancel as the default, and Cancel leaves everything as it was", async () => { + uncheck("/p/g.txt"); + const checks = useCommit.getState().checks; + const started = await startCommit(); + expect(started.asked()).toBe(true); + expect(commit).not.toHaveBeenCalled(); + const dialog = screen.getByRole("dialog"); + expect(dialog.textContent).toContain("g.txt"); + expect(dialog.textContent).not.toContain("n.txt"); + expect(document.activeElement).toBe(screen.getByRole("button", { name: "Cancel" })); + + expect(await started.answer(press("Cancel"))).toBeUndefined(); + expect(commit).not.toHaveBeenCalled(); + expect(useCommit.getState()).toMatchObject({ checks, message: "Merge branch 'topic'", operation: null }); + expect(useVcs.getState().status).toBe(incoming); + }); + + it("is cancelled by Enter and Escape", async () => { + uncheck("/p/g.txt"); + for (const key of ["Enter", "Escape"]) { + // oxlint-disable-next-line no-await-in-loop -- one commit at a time + const started = await startCommit(); + // oxlint-disable-next-line no-await-in-loop -- one commit at a time + expect(await started.answer(() => fireEvent.keyDown(screen.getByRole("dialog"), { key }))).toBeUndefined(); + } + expect(commit).not.toHaveBeenCalled(); + }); + + it("goes on as the user chose with Commit Anyway", async () => { + uncheck("/p/g.txt"); + const started = await startCommit(); + expect(await started.answer(press("Commit Anyway"))).toEqual([{ repo: "/p", id: "commit1" }]); + expect(sent().exclude).toEqual(["/p/g.txt"]); + }); + + it("names the files of another change list", async () => { + useChangelists.setState({ + state: { + lists: [ + { id: "default", name: "Changes", comment: "" }, + { id: "other", name: "Other", comment: "" }, + ], + active: "default", + files: { "n.txt": "other" }, + }, + }); + const started = await startCommit(); + expect(started.asked()).toBe(true); + expect(screen.getByRole("dialog").textContent).toContain("n.txt"); + await started.answer(press("Cancel")); + }); + + it("asks about a file with only some of its blocks checked", async () => { + const hunk = { kind: "modified", start: 0, lines: 1, oldStart: 0, oldLines: 1, oldText: "old\n" } as const; + fileAt.mockResolvedValue({ status: "ok", data: "old\nsame\n" }); + readText.mockResolvedValue({ status: "ok", data: "new\nsame\n" }); + diffHunks.mockResolvedValue([hunk]); + useCommit.setState({ + checks: new Map([["/p/g.txt", "hunks"]]), + excludedHunks: new Map([["/p/g.txt", new Set(hunkKeys("new\nsame\n", [hunk]))]]), + }); + let started = await startCommit(); + expect(started.asked()).toBe(true); + expect(screen.getByRole("dialog").textContent).toContain("g.txt"); + await started.answer(press("Cancel")); + expect(commit).not.toHaveBeenCalled(); + + // Every block is checked again: the file goes in whole. + useCommit.setState({ excludedHunks: new Map() }); + started = await startCommit(); + expect(started.asked()).toBe(false); + await started.result(); + expect(sent()).toMatchObject({ stage: ["/p/g.txt"], exclude: [], partial: [] }); + }); + + it("does not ask about local edits that are not part of the merge, or with everything checked", async () => { + useVcs.setState({ status: [...incoming, file("/p/local.txt", null, "modified"), file("/p/u", null, "untracked")] }); + uncheck("/p/local.txt"); + const started = await startCommit(); + expect(started.asked()).toBe(false); + expect(await started.result()).toEqual([{ repo: "/p", id: "commit1" }]); + expect(sent().exclude).toEqual([]); + }); + + it("does not ask outside a merge, in a rebase, or when only the checks run", async () => { + uncheck("/p/g.txt"); + await act(async () => checkCommitChanges()); + expect(screen.queryByText(TITLE)).toBeNull(); + for (const operation of [null, "rebase"]) { + useVcs.setState({ branch: branch(operation), operations: operation ? { "/p": operation } : {} }); + // oxlint-disable-next-line no-await-in-loop -- one commit at a time + const started = await startCommit(); + expect(started.asked()).toBe(false); + // oxlint-disable-next-line no-await-in-loop -- one commit at a time + expect(await started.result()).toEqual([{ repo: "/p", id: "commit1" }]); + } + expect(sent(1).exclude).toEqual(["/p/g.txt"]); + }); + + it("asks only for the repositories that are merging and take part in the commit", async () => { + const lib = [file("/p/lib/a.txt", "modified"), file("/p/lib/b.txt", "modified")]; + useVcs.setState({ + roots: ["/p", "/p/lib"], + kinds: { "/p": "git", "/p/lib": "git" }, + status: [...incoming, ...lib], + operations: { "/p": "merge" }, + }); + uncheck("/p/g.txt", "/p/lib/b.txt"); + let started = await startCommit(); + expect(screen.getByRole("dialog").textContent).toContain("g.txt"); + expect(screen.getByRole("dialog").textContent).not.toContain("b.txt"); + expect(await started.answer(press("Commit Anyway"))).toHaveLength(2); + expect(commit.mock.calls.map(([root, , options]) => [root, options.exclude])).toEqual([ + ["/p/lib", ["/p/lib/b.txt"]], + ["/p", ["/p/g.txt"]], + ]); + + // The merging repository has nothing checked: it is not committed at all. + commit.mockClear(); + uncheck(...incoming.map((f) => f.path)); + started = await startCommit(); + expect(started.asked()).toBe(false); + expect(await started.result()).toEqual([{ repo: "/p/lib", id: "commit1" }]); + }); +}); + +describe("unresolved conflicts", () => { + const conflict = file("/p/c.txt", null, "conflicted"); + const refused = expect.objectContaining({ title: "Resolve merge conflicts before committing", body: "c.txt" }); + + it("refuse the commit before anything is asked, checked or not", async () => { + useVcs.setState({ status: [...incoming, conflict] }); + uncheck("/p/g.txt", "/p/c.txt"); + const started = await startCommit(); + expect(started.asked()).toBe(false); + expect(await started.result()).toBeUndefined(); + expect(commit).not.toHaveBeenCalled(); + expect(notify).toHaveBeenCalledWith(refused); + }); + + it("of a repository that is not committed are no obstacle", async () => { + useVcs.setState({ + roots: ["/p", "/p/lib"], + kinds: { "/p": "git", "/p/lib": "git" }, + status: [conflict, file("/p/lib/a.txt", "modified")], + }); + expect(await (await startCommit()).result()).toEqual([{ repo: "/p/lib", id: "commit1" }]); + }); + + it("left unchecked in a Subversion working copy are no obstacle", async () => { + useVcs.setState({ + kinds: { "/p": "subversion" }, + operations: {}, + branch: null, + status: [file("/p/a.txt", null, "modified"), conflict], + }); + expect(await (await startCommit()).result()).toEqual([{ repo: "/p", id: "commit1" }]); + }); + + it("left unchecked do not stop the checks from running on their own", async () => { + useVcs.setState({ status: [...incoming, conflict] }); + await act(async () => checkCommitChanges()); + expect(notify).not.toHaveBeenCalledWith(refused); + }); +}); diff --git a/src/features/vcs/changeOps.tsx b/src/features/vcs/changeOps.tsx index 5a2b562ce..2eeb998c5 100644 --- a/src/features/vcs/changeOps.tsx +++ b/src/features/vcs/changeOps.tsx @@ -33,6 +33,7 @@ import { ensureCommitIdentity } from "./commitIdentity"; import { startPostCommitChecks, startPostCommitTests } from "./postCommitChecks"; import { commitTestSelection } from "./commitTests"; import { commitTodoRules } from "./commitTodo"; +import { confirmLeftOutOfMerge, leftOutOfMerge } from "./mergeCommitLeftOut"; import { controlLabel, controlOperation } from "./operations"; import { FileChecklist } from "./shelf"; import { reloadLog } from "./logStore"; @@ -284,12 +285,17 @@ async function prepareAndCommit( } } // Concluding a merge needs no further changes (e.g. every conflict resolved as "yours"). - const merging = useVcs.getState().branch?.operation === "merge"; - if (!plan.repositories.length || (!plan.included.length && !amend && !merging)) { + if (!plan.repositories.length || (!plan.included.length && !amend && !plan.concludesMerge)) { notifications().notify({ group: "vcs", level: "warning", title: "No changes selected for commit" }); return undefined; } - const unresolved = plan.included.filter((f) => effectiveKind(f) === "conflicted"); + // Git refuses to commit with any unresolved conflict in the repository, checked or not. + const gitRepos = onlyChecks ? [] : plan.repositories.filter((repo) => vcsKindOf(repo) === "git"); + const unresolved = useVcs + .getState() + .status.filter( + (f) => effectiveKind(f) === "conflicted" && (plan.included.includes(f) || gitRepos.includes(repoOf(f.path))), + ); if (unresolved.length) { notifications().notify({ group: "vcs", @@ -299,6 +305,12 @@ async function prepareAndCommit( }); return undefined; } + // Before the checks, which may already modify files. + if (!onlyChecks) { + const leftOut = await leftOutOfMerge(plan); + if (leftOut.length && !(await confirmLeftOutOfMerge(leftOut))) return undefined; + if (!current()) return; + } // IDEA: failed checks show in the commit panel; the next Commit ("Commit Anyway") skips them. const previous = useCommit.getState().checkResult; const checked = onlyChecks || !previous?.blocked || previous.stale; diff --git a/src/features/vcs/commitSelection.ts b/src/features/vcs/commitSelection.ts index 1ff3e7550..c325629af 100644 --- a/src/features/vcs/commitSelection.ts +++ b/src/features/vcs/commitSelection.ts @@ -143,9 +143,15 @@ export function installDraftRevision(): () => void { }; } -interface PlannedCommit extends CommitPlan { +export interface PlannedCommit extends CommitPlan { repositories: Array; stagedRepositorySelection: boolean; + /** Nothing is checked and a merge is in progress: the commit takes the merge as the index holds it. */ + concludesMerge: boolean; +} + +export function mergeInProgress(repo: string | null): boolean { + return repo !== null && useVcs.getState().operations[repo] === "merge"; } /** @@ -177,7 +183,7 @@ export function commitTargetsGit(): boolean { /** The included changes and their target repositories from a single status snapshot. */ export function currentPlan(): PlannedCommit { const { status, root, roots, unavailableRoots } = useVcs.getState(); - const { checks: overrides, groupByRepo, excludedStagedRepos } = useCommit.getState(); + const { amend, checks: overrides, groupByRepo, excludedStagedRepos } = useCommit.getState(); const staging = stagingAreaOn(); const scope = stagedRepositoryScope(status, roots, staging && groupByRepo); const files = statusForCommit(status, roots, scope, excludedStagedRepos); @@ -187,14 +193,18 @@ export function currentPlan(): PlannedCommit { (scope && !plan.included.length) || (roots.length === 0 && unavailableRoots.length > 0) ? [] : commitRepos(plan.included, roots, currentRepo()); + const concludesMerge = !plan.included.length && !amend && repositories.some(mergeInProgress); return { ...plan, + // Excluded files are committed as HEAD has them: the merge would be recorded without its changes. + exclude: concludesMerge ? [] : plan.exclude, // A root of another system commits only the files checked in it: with none, it is no target // (Subversion has no staging area or Amend to commit without files). repositories: repositories.filter( (repo) => vcsKindOf(repo) === "git" || plan.included.some((f) => rootOf(f.path, roots) === repo), ), stagedRepositorySelection: scope !== null, + concludesMerge, }; } @@ -203,7 +213,9 @@ export function currentPlan(): PlannedCommit { * text on disk (saved just before). A file whose blocks are all included again (e.g. it * was edited since) is committed whole. */ -async function partialCommitFiles(paths: readonly string[]): Promise<{ files: PartialCommitFile[]; whole: string[] }> { +export async function partialCommitFiles( + paths: readonly string[], +): Promise<{ files: PartialCommitFile[]; whole: string[] }> { const files: PartialCommitFile[] = []; const whole: string[] = []; const { excludedHunks, excludedHunkLines } = useCommit.getState(); @@ -314,7 +326,7 @@ async function pendingChanges(): Promise { if (!useVcs.getState().root) return null; const rev = revision; const plan = currentPlan(); - if (!plan.included.length) return { revision: rev, roots: [], patch: "" }; + if (!plan.included.length && !plan.concludesMerge) return { revision: rev, roots: [], patch: "" }; const selection = await selectionOf(plan); const patches = ( await Promise.all( diff --git a/src/features/vcs/mergeCommitLeftOut.ts b/src/features/vcs/mergeCommitLeftOut.ts new file mode 100644 index 000000000..f6b070400 --- /dev/null +++ b/src/features/vcs/mergeCommitLeftOut.ts @@ -0,0 +1,57 @@ +/** + * Changes left out of a merge commit are recorded there as HEAD has them: the merge counts as + * done, so merging the branch again does not bring them back. + */ +import type { FileStatus } from "@/bindings"; +import { tx } from "@/platform/i18n"; +import { ask } from "@/workbench/messages"; +import { groupOf } from "./changes"; +import { mergeInProgress, partialCommitFiles, type PlannedCommit } from "./commitSelection"; +import { useCommit } from "./commitStore"; +import { relTo, stripSlash } from "./model"; +import { repoOf, useVcs } from "./store"; + +const SHOWN = 10; + +/** + * Staged files that a commit of `plan` leaves out of a merge, in whole or in part. Files changed + * only in the working tree are local edits: the merge commit loses nothing without them. + */ +export async function leftOutOfMerge(plan: PlannedCommit): Promise { + // Git does not amend during a merge, and amending an earlier commit does not conclude it. + if (useCommit.getState().amend) return []; + const merging = new Set(plan.repositories.filter(mergeInProgress)); + const incoming = useVcs + .getState() + .status.filter((f) => f.staged && groupOf(f) === "changes" && merging.has(repoOf(f.path))); + const paths = new Set(incoming.map((f) => stripSlash(f.path))); + const partial = await partialCommitFiles(plan.partial.filter((path) => paths.has(path))); + const leftOut = new Set([...plan.exclude, ...partial.files.map((f) => f.path)]); + return incoming.filter((f) => leftOut.has(stripSlash(f.path))); +} + +/** IDEA's "Changes Excluded from Merge Commit", with Cancel as the default. */ +export async function confirmLeftOutOfMerge(files: readonly FileStatus[]): Promise { + const { root, roots } = useVcs.getState(); + const n = files.length; + const question = + n === 1 + ? tx("Are you sure you want to exclude changes in this file from the merge commit?") + : tx`Are you sure you want to exclude changes in these ${n} files from the merge commit?`; + const list = files + .slice(0, SHOWN) + .map((f) => (roots.length > 1 ? relTo(root ?? "", stripSlash(f.path)) : f.relPath)) + .join("\n"); + const consequence = tx("Git records the branch as merged, so merging it again won't bring these changes in."); + const { button } = await ask({ + title: "Changes Excluded from Merge Commit", + body: `${question}\n\n${list}${n > SHOWN ? "\n…" : ""}\n\n${consequence}`, + icon: "warning", + width: 480, + buttons: [ + { id: "commit", label: "Commit Anyway" }, + { id: "cancel", label: "Cancel", primary: true }, + ], + }); + return button === "commit"; +} diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index 7d52de884..296419d98 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -103,6 +103,10 @@ "Create Amend Commit Anyway": "Create Amend Commit Anyway", "Amend commit created": "Amend commit created", "Could not keep the prepared amend commit": "Could not keep the prepared amend commit", + "Changes Excluded from Merge Commit": "Changes Excluded from Merge Commit", + "Are you sure you want to exclude changes in this file from the merge commit?": "Are you sure you want to exclude changes in this file from the merge commit?", + "Are you sure you want to exclude changes in these {n} files from the merge commit?": "Are you sure you want to exclude changes in these {n} files from the merge commit?", + "Git records the branch as merged, so merging it again won't bring these changes in.": "Git records the branch as merged, so merging it again won't bring these changes in.", "The prepared amend commit is no longer available.": "The prepared amend commit is no longer available.", "Show query results in": "Show query results in", "Staged changes for the prepared amend commit have changed.": "Staged changes for the prepared amend commit have changed.", diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index ba8598a18..615af2acc 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -104,6 +104,10 @@ "Create Amend Commit Anyway": "仍然创建修订提交", "Amend commit created": "已创建修订提交", "Could not keep the prepared amend commit": "无法保留已准备好的修订提交", + "Changes Excluded from Merge Commit": "合并提交排除了更改", + "Are you sure you want to exclude changes in this file from the merge commit?": "确定要将此文件中的更改排除在合并提交之外吗?", + "Are you sure you want to exclude changes in these {n} files from the merge commit?": "确定要将这 {n} 个文件中的更改排除在合并提交之外吗?", + "Git records the branch as merged, so merging it again won't bring these changes in.": "Git 会将该分支记录为已合并,再次合并不会带入这些更改。", "The prepared amend commit is no longer available.": "已准备好的修订提交已失效。", "Show query results in": "显示查询结果的位置", "Staged changes for the prepared amend commit have changed.": "此修订提交涉及的暂存改动已发生变化。",