diff --git a/CHANGELOG.md b/CHANGELOG.md index b75527b..2b9f370 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,10 @@ repository. Changes up to that version are documented in its ## [Unreleased] +### Fixed + +- Pressing escape now closes the commit editor without prompt if there are no unsaved changes. + ## [1.1.1] - 2026-11-10 ### Fixed diff --git a/src/comment-discard.ts b/src/comment-discard.ts index 3bf8d77..aae350c 100644 --- a/src/comment-discard.ts +++ b/src/comment-discard.ts @@ -1,5 +1,22 @@ -export async function confirmCommentDiscard(hasOpenComment: boolean, askToDiscard: () => Promise): Promise { - if (!hasOpenComment) { +export class CommentDraft { + private document?: { getText(): string }; + + constructor(private readonly initialBody: string) {} + + trackDocument(document: { uri: { scheme: string; path: string }; getText(): string }) { + if (!this.document && document.uri.scheme === "comment" && document.uri.path.startsWith("/commentinput-")) { + this.document = document; + } + } + + get hasChanges(): boolean { + const body = this.document?.getText() ?? this.initialBody; + return body.replace(/\r\n/g, "\n") !== this.initialBody.replace(/\r\n/g, "\n"); + } +} + +export async function confirmCommentDiscard(hasUnsavedChanges: boolean, askToDiscard: () => Promise): Promise { + if (!hasUnsavedChanges) { return true; } return await askToDiscard(); diff --git a/src/stgit.ts b/src/stgit.ts index 520e907..a1187d6 100644 --- a/src/stgit.ts +++ b/src/stgit.ts @@ -3,7 +3,7 @@ import * as vscode from "vscode"; import { commands, window, workspace } from "vscode"; -import { confirmCommentDiscard } from "./comment-discard"; +import { CommentDraft, confirmCommentDiscard } from "./comment-discard"; import { getStGitConfig } from "./config"; import { openAndShowDiffDocument, refreshDiff } from "./diff-provider"; import { getUserConfirmation, info, log, showStatusMessage } from "./extension"; @@ -413,6 +413,7 @@ class StGitDoc { private baseSha: string | null = null; private commentThread: vscode.CommentThread | null = null; + private commentDraft: CommentDraft | null = null; // Patch being edited in editor private editPatch: Patch | null = null; @@ -448,6 +449,11 @@ class StGitDoc { this.updateEditorDecorations(); } }), + workspace.onDidOpenTextDocument((document) => { + if (window.activeTextEditor?.document === this.doc) { + this.commentDraft?.trackDocument(document); + } + }), // this event fires when an entire tab group is added or removed window.onDidChangeTextEditorViewColumn((ev) => { if (ev.textEditor.document === this.doc) { @@ -752,6 +758,7 @@ class StGitDoc { }, }; this.commentThread?.dispose(); + this.commentDraft = new CommentDraft(body); const comments: vscode.Comment[] = [comment]; const pos = new vscode.Position(line, 0); const range = new vscode.Range(pos, pos); @@ -842,12 +849,13 @@ class StGitDoc { private async closeCommentEditor() { this.commentThread?.dispose(); this.commentThread = null; + this.commentDraft = null; this.editPatch = null; await this.closeAllDiffEditors(); await this.focusWindow(); } private confirmDiscardComment(): Promise { - return confirmCommentDiscard(!!this.commentThread, async () => { + return confirmCommentDiscard(this.commentDraft?.hasChanges ?? false, async () => { const choice = await window.showWarningMessage("Close the commit message editor? Unsaved changes may be lost.", { modal: true }, "Discard and Close"); return choice === "Discard and Close"; }); diff --git a/src/test/suite/extension.test.ts b/src/test/suite/extension.test.ts index 5a39634..ced20ad 100644 --- a/src/test/suite/extension.test.ts +++ b/src/test/suite/extension.test.ts @@ -3,6 +3,7 @@ import * as assert from "assert"; // You can import and use all API from the 'vscode' module // as well as import your extension to test it import * as vscode from "vscode"; +import { CommentDraft } from "../../comment-discard"; import { findHunkTargetLine, HunkTarget } from "../../diff-mode"; import { RepoReader } from "../../repo-reader"; import { correspondingLine } from "../../stage-selection"; @@ -16,6 +17,57 @@ suite("Extension Test Suite", () => { assert.strictEqual(-1, [1, 2, 3].indexOf(0)); }); + test("Tracks unsaved changes in native comment drafts", async function () { + this.timeout(10000); + const document = await vscode.workspace.openTextDocument({ content: "Comment draft test" }); + await vscode.window.showTextDocument(document); + const controller = vscode.comments.createCommentController("stgit-discard-test", "StGit discard test"); + const body = "Original commit message"; + const commentDraft = new CommentDraft(body); + let listener: vscode.Disposable | undefined; + let timer: NodeJS.Timeout | undefined; + try { + const draftOpened = new Promise((resolve, reject) => { + timer = setTimeout(() => reject(new Error("Comment draft was not exposed as a text document")), 5000); + const checkDocument = (draft: vscode.TextDocument) => { + if (draft.uri.scheme === "comment" && draft.getText() === body) { + resolve(draft); + } + }; + const opened = vscode.workspace.onDidOpenTextDocument((draft) => { + if (vscode.window.activeTextEditor?.document === document) { + commentDraft.trackDocument(draft); + } + checkDocument(draft); + }); + const changed = vscode.workspace.onDidChangeTextDocument((event) => checkDocument(event.document)); + listener = vscode.Disposable.from(opened, changed); + }); + const thread = controller.createCommentThread(document.uri, new vscode.Range(0, 0, 0, 0), [ + { body, mode: vscode.CommentMode.Editing, author: { name: "Commit Message" } }, + ]); + thread.canReply = false; + thread.collapsibleState = vscode.CommentThreadCollapsibleState.Expanded; + const draft = await draftOpened; + assert.strictEqual(draft.getText(), body); + assert.strictEqual(commentDraft.hasChanges, false); + const edit = new vscode.WorkspaceEdit(); + edit.insert(draft.uri, new vscode.Position(0, body.length), " changed"); + assert.strictEqual(await vscode.workspace.applyEdit(edit), true); + assert.strictEqual(draft.getText(), `${body} changed`); + assert.strictEqual(commentDraft.hasChanges, true); + const revert = new vscode.WorkspaceEdit(); + revert.replace(draft.uri, new vscode.Range(0, 0, 0, draft.getText().length), body); + assert.strictEqual(await vscode.workspace.applyEdit(revert), true); + assert.strictEqual(commentDraft.hasChanges, false); + } finally { + clearTimeout(timer); + listener?.dispose(); + controller.dispose(); + await vscode.commands.executeCommand("workbench.action.closeActiveEditor"); + } + }); + test("Formats multiline commit descriptions", () => { assert.strictEqual(formatCommitDescription("Title", "Title\n\nBody\n"), "Title […]"); assert.strictEqual(formatCommitDescription("Title", "Title\n\n \n"), "Title"); diff --git a/src/test/unit/comment-discard.test.ts b/src/test/unit/comment-discard.test.ts index 2e7b97d..9bdd2b6 100644 --- a/src/test/unit/comment-discard.test.ts +++ b/src/test/unit/comment-discard.test.ts @@ -1,7 +1,7 @@ import * as assert from "assert"; import { readFileSync } from "fs"; import * as path from "path"; -import { confirmCommentDiscard } from "../../comment-discard"; +import { CommentDraft, confirmCommentDiscard } from "../../comment-discard"; suite("Comment discard", () => { test("Escape closes an empty focused comment without prompting", () => { @@ -17,7 +17,7 @@ suite("Comment discard", () => { }); }); - test("closes when no comment is open without asking", async () => { + test("closes without asking when there are no unsaved changes", async () => { let asked = false; const allowed = await confirmCommentDiscard(false, async () => { asked = true; @@ -27,7 +27,7 @@ suite("Comment discard", () => { assert.strictEqual(asked, false); }); - test("keeps an open comment when the prompt is dismissed", async () => { + test("keeps a changed comment when the prompt is dismissed", async () => { let asked = false; const allowed = await confirmCommentDiscard(true, async () => { asked = true; @@ -37,8 +37,47 @@ suite("Comment discard", () => { assert.strictEqual(asked, true); }); - test("closes an open comment when discard is confirmed", async () => { + test("closes a changed comment when discard is confirmed", async () => { const allowed = await confirmCommentDiscard(true, async () => true); assert.strictEqual(allowed, true); }); + + test("does not mark a draft as changed before its input opens", () => { + assert.strictEqual(new CommentDraft("").hasChanges, false); + assert.strictEqual(new CommentDraft("Original message").hasChanges, false); + }); + + for (const [name, initialBody, body, expected] of [ + ["empty new message", "", "", false], + ["unchanged existing message", "Original message", "Original message", false], + ["new message", "", "New message", true], + ["changed existing message", "Original message", "Changed message", true], + ["deleted existing message", "Original message", "", true], + ["normalized line endings", "Subject\r\n\r\nBody\r\n", "Subject\n\nBody\n", false], + ] as const) { + test(`detects unsaved changes for ${name}`, () => { + const draft = new CommentDraft(initialBody); + draft.trackDocument({ uri: { scheme: "comment", path: "/commentinput-1.md" }, getText: () => body }); + assert.strictEqual(draft.hasChanges, expected); + }); + } + + test("stops prompting when edits are reverted to the original text", () => { + const draft = new CommentDraft("Original message"); + let body = "Changed message"; + draft.trackDocument({ uri: { scheme: "comment", path: "/commentinput-1.md" }, getText: () => body }); + assert.strictEqual(draft.hasChanges, true); + body = "Original message"; + assert.strictEqual(draft.hasChanges, false); + }); + + test("ignores unrelated documents and other drafts opened later", () => { + const draft = new CommentDraft("Original message"); + draft.trackDocument({ uri: { scheme: "file", path: "/commentinput-1.md" }, getText: () => "Other message" }); + draft.trackDocument({ uri: { scheme: "comment", path: "/other-comment.md" }, getText: () => "Other message" }); + assert.strictEqual(draft.hasChanges, false); + draft.trackDocument({ uri: { scheme: "comment", path: "/commentinput-1.md" }, getText: () => "Original message" }); + draft.trackDocument({ uri: { scheme: "comment", path: "/commentinput-2.md" }, getText: () => "Other message" }); + assert.strictEqual(draft.hasChanges, false); + }); });