Skip to content

Commit f6d460b

Browse files
author
easonLiangWorldedtech
committed
fix(diff-view): let one teardown path own a cancelled save
Cancellation can reach revertChanges() while a rejected save is still discarding the same buffer, so both paths edited the document and closed the same tabs. The second caller now awaits the cleanup already in flight instead of repeating it.
1 parent 0ba7af0 commit f6d460b

2 files changed

Lines changed: 134 additions & 80 deletions

File tree

‎src/integrations/editor/DiffViewProvider.ts‎

Lines changed: 106 additions & 80 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@ export class DiffViewProvider {
4343
// it when re-showing the edited file afterward.
4444
private documentWasPinned = false
4545
private relPath?: string
46+
private teardownInFlight: Promise<void> | undefined
4647
private newContent?: string
4748
private activeDiffEditor?: vscode.TextEditor
4849
private fadedOverlayController?: DecorationController
@@ -555,48 +556,53 @@ export class DiffViewProvider {
555556
this.disposeActiveEditorListener()
556557
this.cancelDeferredScroll()
557558

558-
let discardSucceeded = !updatedDocument.isDirty
559-
if (updatedDocument.isDirty) {
560-
discardSucceeded = await this.revertDocument(updatedDocument)
561-
}
562-
if (discardSucceeded && this.editType === "create" && this.placeholderVersion) {
563-
// Cleanup has to be serialized with the same resolved-path advisory lock
564-
// every other writer to this file uses. A token check and an unlink in
565-
// separate steps let a peer writer commit in the gap and lose its write.
566-
// A differing token, or a lock that cannot be taken, leaves the file in place.
567-
await withFileLock(await resolveLockKey(absolutePath), async () => {
568-
const placeholderStats = await fs
569-
.stat(absolutePath, { bigint: true })
570-
.catch(() => undefined)
571-
if (!placeholderStats || versionTokenOfStat(placeholderStats) !== this.placeholderVersion) {
572-
return
573-
}
574-
let unlinked = false
575-
try {
576-
await fs.unlink(absolutePath)
577-
unlinked = true
578-
} catch {
579-
// the placeholder vanished or the unlink failed
580-
}
581-
if (!unlinked) {
582-
return
583-
}
584-
// The file is gone, so its tab must go too: closing only the diff
585-
// views would leave a clean plain-text tab for a deleted file.
586-
await this.closeFileTab(absolutePath)
587-
// The directories open() created for the new file must go with it,
588-
// innermost first. rmdir refuses a directory another writer populated
589-
// in the meantime, so the cleanup stops at the first failure.
590-
for (let i = this.createdDirs.length - 1; i >= 0; i--) {
559+
await this.runTeardown(async () => {
560+
let discardSucceeded = !updatedDocument.isDirty
561+
if (updatedDocument.isDirty) {
562+
discardSucceeded = await this.revertDocument(updatedDocument)
563+
}
564+
if (discardSucceeded && this.editType === "create" && this.placeholderVersion) {
565+
// Cleanup has to be serialized with the same resolved-path advisory lock
566+
// every other writer to this file uses. A token check and an unlink in
567+
// separate steps let a peer writer commit in the gap and lose its write.
568+
// A differing token, or a lock that cannot be taken, leaves the file in place.
569+
await withFileLock(await resolveLockKey(absolutePath), async () => {
570+
const placeholderStats = await fs
571+
.stat(absolutePath, { bigint: true })
572+
.catch(() => undefined)
573+
if (
574+
!placeholderStats ||
575+
versionTokenOfStat(placeholderStats) !== this.placeholderVersion
576+
) {
577+
return
578+
}
579+
let unlinked = false
591580
try {
592-
await fs.rmdir(this.createdDirs[i])
581+
await fs.unlink(absolutePath)
582+
unlinked = true
593583
} catch {
594-
break
584+
// the placeholder vanished or the unlink failed
595585
}
596-
}
597-
})
598-
}
599-
await this.closeOwnDiffView(absolutePath)
586+
if (!unlinked) {
587+
return
588+
}
589+
// The file is gone, so its tab must go too: closing only the diff
590+
// views would leave a clean plain-text tab for a deleted file.
591+
await this.closeFileTab(absolutePath)
592+
// The directories open() created for the new file must go with it,
593+
// innermost first. rmdir refuses a directory another writer populated
594+
// in the meantime, so the cleanup stops at the first failure.
595+
for (let i = this.createdDirs.length - 1; i >= 0; i--) {
596+
try {
597+
await fs.rmdir(this.createdDirs[i])
598+
} catch {
599+
break
600+
}
601+
}
602+
})
603+
}
604+
await this.closeOwnDiffView(absolutePath)
605+
})
600606
} catch {
601607
// cleanup is best-effort; the guard verdict below is the outcome
602608
}
@@ -806,55 +812,56 @@ export class DiffViewProvider {
806812
this.disposeActiveEditorListener()
807813
this.cancelDeferredScroll()
808814

809-
if (!fileExists) {
810-
if (updatedDocument.isDirty) {
811-
await updatedDocument.save()
812-
}
815+
await this.runTeardown(async () => {
816+
if (!fileExists) {
817+
if (updatedDocument.isDirty) {
818+
await updatedDocument.save()
819+
}
813820

814-
await this.closeAllDiffViews()
815-
// The file was newly created for this edit; close its transiently
816-
// opened tab before deleting it from disk.
817-
await this.closeFileTab(absolutePath)
818-
await fs.unlink(absolutePath)
821+
await this.closeAllDiffViews()
822+
// The file was newly created for this edit; close its transiently
823+
// opened tab before deleting it from disk.
824+
await this.closeFileTab(absolutePath)
825+
await fs.unlink(absolutePath)
819826

820-
// Remove only the directories we created, in reverse order.
821-
for (let i = this.createdDirs.length - 1; i >= 0; i--) {
822-
await fs.rmdir(this.createdDirs[i])
823-
}
824-
} else {
825-
// Revert document.
826-
const edit = new vscode.WorkspaceEdit()
827+
// Remove only the directories we created, in reverse order.
828+
for (let i = this.createdDirs.length - 1; i >= 0; i--) {
829+
await fs.rmdir(this.createdDirs[i])
830+
}
831+
} else {
832+
// Revert document.
833+
const edit = new vscode.WorkspaceEdit()
827834

828-
const fullRange = new vscode.Range(
829-
updatedDocument.positionAt(0),
830-
updatedDocument.positionAt(updatedDocument.getText().length),
831-
)
835+
const fullRange = new vscode.Range(
836+
updatedDocument.positionAt(0),
837+
updatedDocument.positionAt(updatedDocument.getText().length),
838+
)
832839

833-
edit.replace(updatedDocument.uri, fullRange, this.stripAllBOMs(this.originalContent ?? ""))
840+
edit.replace(updatedDocument.uri, fullRange, this.stripAllBOMs(this.originalContent ?? ""))
834841

835-
// Apply the edit and save, since contents shouldn't have changed
836-
// this won't show in local history unless of course the user made
837-
// changes and saved during the edit.
838-
await vscode.workspace.applyEdit(edit)
839-
await updatedDocument.save()
842+
// Apply the edit and save, since contents shouldn't have changed
843+
// this won't show in local history unless of course the user made
844+
// changes and saved during the edit.
845+
await vscode.workspace.applyEdit(edit)
846+
await updatedDocument.save()
840847

841-
await this.closeAllDiffViews()
848+
await this.closeAllDiffViews()
842849

843-
// Read auto-close preferences from state; fall back to defaults that
844-
// preserve the existing behavior when unset.
845-
const revertTask = this.taskRef.deref()
846-
const revertState = await revertTask?.providerRef.deref()?.getState()
847-
848-
await this.keepOrCloseEditedFile(
849-
absolutePath,
850-
false,
851-
revertState?.autoCloseZooOpenedFiles ?? DEFAULT_AUTO_CLOSE_ZOO_OPENED_FILES,
852-
revertState?.autoCloseZooOpenedFilesAfterUserEdited ??
853-
DEFAULT_AUTO_CLOSE_ZOO_OPENED_FILES_AFTER_USER_EDITED,
854-
revertState?.autoCloseZooOpenedNewFiles ?? DEFAULT_AUTO_CLOSE_ZOO_OPENED_NEW_FILES,
855-
)
856-
}
850+
// Read auto-close preferences from state; fall back to defaults that
851+
// preserve the existing behavior when unset.
852+
const revertTask = this.taskRef.deref()
853+
const revertState = await revertTask?.providerRef.deref()?.getState()
857854

855+
await this.keepOrCloseEditedFile(
856+
absolutePath,
857+
false,
858+
revertState?.autoCloseZooOpenedFiles ?? DEFAULT_AUTO_CLOSE_ZOO_OPENED_FILES,
859+
revertState?.autoCloseZooOpenedFilesAfterUserEdited ??
860+
DEFAULT_AUTO_CLOSE_ZOO_OPENED_FILES_AFTER_USER_EDITED,
861+
revertState?.autoCloseZooOpenedNewFiles ?? DEFAULT_AUTO_CLOSE_ZOO_OPENED_NEW_FILES,
862+
)
863+
}
864+
})
858865
// Restore any preview tabs the diff evicted, reconstructing the user's
859866
// prior not-yet-edited tab state.
860867
await this.restorePreviewTabs()
@@ -940,6 +947,25 @@ export class DiffViewProvider {
940947
}
941948
}
942949
}
950+
/**
951+
* Only one teardown path may act on a document at a time. A cancellation can reach
952+
* revertChanges() while a rejected save is already discarding the same buffer, and
953+
* both would edit the document and close the same tabs. The second caller awaits the
954+
* cleanup already in flight instead of repeating it.
955+
*/
956+
private async runTeardown(cleanup: () => Promise<void>): Promise<void> {
957+
if (this.teardownInFlight !== undefined) {
958+
await this.teardownInFlight
959+
return
960+
}
961+
const inFlight = cleanup()
962+
this.teardownInFlight = inFlight
963+
try {
964+
await inFlight
965+
} finally {
966+
this.teardownInFlight = undefined
967+
}
968+
}
943969

944970
// Stop tracking user activation of the target file. Called before any
945971
// programmatic showTextDocument so our own re-show never counts as a "touch".

‎src/integrations/editor/__tests__/DiffViewProvider.spec.ts‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2914,6 +2914,34 @@ describe("DiffViewProvider", () => {
29142914
expect(vscode.window.showTextDocument).not.toHaveBeenCalled()
29152915
})
29162916

2917+
it("revertChanges() does not run a second teardown while one is already in flight", async () => {
2918+
// Cancellation can reach revertChanges() while a rejected save is still
2919+
// discarding the same buffer. Both paths acting on the document and the same
2920+
// tabs is duplicate cleanup, so the second caller waits for the first.
2921+
const applyEdit = vi.mocked(vscode.workspace.applyEdit)
2922+
applyEdit.mockResolvedValue(true)
2923+
diffViewProvider["closeAllDiffViews"] = vi.fn().mockResolvedValue(undefined)
2924+
diffViewProvider["closeFileTab"] = vi.fn().mockResolvedValue(undefined)
2925+
diffViewProvider["relPath"] = "mock-target-file.ts"
2926+
diffViewProvider["editType"] = "modify"
2927+
diffViewProvider["originalContent"] = "original"
2928+
const editor = makeTextEditor({
2929+
document: makeTextDocument({
2930+
uri: makeUri(mockTargetPath),
2931+
getText: vi.fn().mockReturnValue("content"),
2932+
isDirty: false,
2933+
save: vi.fn().mockResolvedValue(undefined),
2934+
}),
2935+
})
2936+
diffViewProvider["activeDiffEditor"] = editor
2937+
2938+
const first = diffViewProvider.revertChanges()
2939+
const second = diffViewProvider.revertChanges()
2940+
await Promise.all([first, second])
2941+
2942+
expect(applyEdit).toHaveBeenCalledTimes(1)
2943+
})
2944+
29172945
it("saveChanges() keeps the file open when the user touched it", async () => {
29182946
const closeFileTab = vi.fn().mockResolvedValue(undefined)
29192947
vi.mocked(vscode.window.showTextDocument).mockResolvedValue({ revealRange: vi.fn() } as any)

0 commit comments

Comments
 (0)