Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
21 changes: 19 additions & 2 deletions src/comment-discard.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,22 @@
export async function confirmCommentDiscard(hasOpenComment: boolean, askToDiscard: () => Promise<boolean>): Promise<boolean> {
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<boolean>): Promise<boolean> {
if (!hasUnsavedChanges) {
return true;
}
return await askToDiscard();
Expand Down
12 changes: 10 additions & 2 deletions src/stgit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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<boolean> {
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";
});
Expand Down
52 changes: 52 additions & 0 deletions src/test/suite/extension.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand All @@ -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<vscode.TextDocument>((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");
Expand Down
47 changes: 43 additions & 4 deletions src/test/unit/comment-discard.test.ts
Original file line number Diff line number Diff line change
@@ -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", () => {
Expand All @@ -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;
Expand All @@ -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;
Expand All @@ -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);
});
});
Loading