From c38f443ec4454bd26cffcf2d559b7f349baf98f2 Mon Sep 17 00:00:00 2001 From: Sarah Fortune Date: Fri, 11 Jul 2025 10:49:13 -0700 Subject: [PATCH] DiffViewProvider clean-up (#4835) * In the DiffViewProvider, store the absolutePath instead of the cwd. Remove unused var `scrollListener`. * Remove cwd param * Don't call getCwd in a loop --- src/core/mentions/index.ts | 10 ++-- src/core/task/index.ts | 2 +- src/integrations/diagnostics/index.ts | 7 +-- src/integrations/editor/DiffViewProvider.ts | 59 +++++++++------------ 4 files changed, 33 insertions(+), 45 deletions(-) diff --git a/src/core/mentions/index.ts b/src/core/mentions/index.ts index 623248e4..7e780b60 100644 --- a/src/core/mentions/index.ts +++ b/src/core/mentions/index.ts @@ -120,7 +120,7 @@ export async function parseMentions( } } else if (mention === "problems") { try { - const problems = getWorkspaceProblems(cwd) + const problems = await getWorkspaceProblems() parsedText += `\n\n\n${problems}\n` } catch (error) { parsedText += `\n\n\nError fetching diagnostics: ${error.message}\n` @@ -216,13 +216,9 @@ async function getFileOrFolderContent(mentionPath: string, cwd: string): Promise } } -function getWorkspaceProblems(cwd: string): string { +async function getWorkspaceProblems(): Promise { const diagnostics = vscode.languages.getDiagnostics() - const result = diagnosticsToProblemsString( - diagnostics, - [vscode.DiagnosticSeverity.Error, vscode.DiagnosticSeverity.Warning], - cwd, - ) + const result = diagnosticsToProblemsString(diagnostics, [vscode.DiagnosticSeverity.Error, vscode.DiagnosticSeverity.Warning]) if (!result) { return "No errors or warnings detected." } diff --git a/src/core/task/index.ts b/src/core/task/index.ts index 1c166b5b..dae73ee0 100644 --- a/src/core/task/index.ts +++ b/src/core/task/index.ts @@ -174,7 +174,7 @@ export class Task { this.urlContentFetcher = new UrlContentFetcher(context) this.browserSession = new BrowserSession(context, browserSettings) this.contextManager = new ContextManager() - this.diffViewProvider = new DiffViewProvider(cwd) + this.diffViewProvider = new DiffViewProvider() this.autoApprovalSettings = autoApprovalSettings this.browserSettings = browserSettings this.chatSettings = chatSettings diff --git a/src/integrations/diagnostics/index.ts b/src/integrations/diagnostics/index.ts index ad4ee775..0e8eb616 100644 --- a/src/integrations/diagnostics/index.ts +++ b/src/integrations/diagnostics/index.ts @@ -1,6 +1,7 @@ import * as vscode from "vscode" import * as path from "path" import deepEqual from "fast-deep-equal" +import { getCwd } from "@/utils/path" export function getNewDiagnostics( oldDiagnostics: [vscode.Uri, vscode.Diagnostic[]][], @@ -70,11 +71,11 @@ export function getNewDiagnostics( // // - New error in file3 (1:1) // will return empty string if no problems with the given severity are found -export function diagnosticsToProblemsString( +export async function diagnosticsToProblemsString( diagnostics: [vscode.Uri, vscode.Diagnostic[]][], severities: vscode.DiagnosticSeverity[], - cwd: string, -): string { +): Promise { + const cwd = await getCwd() let result = "" for (const [uri, fileDiagnostics] of diagnostics) { const problems = fileDiagnostics.filter((d) => severities.includes(d.severity)) diff --git a/src/integrations/editor/DiffViewProvider.ts b/src/integrations/editor/DiffViewProvider.ts index 5a1f642e..ca96c509 100644 --- a/src/integrations/editor/DiffViewProvider.ts +++ b/src/integrations/editor/DiffViewProvider.ts @@ -2,7 +2,7 @@ import * as vscode from "vscode" import * as path from "path" import * as fs from "fs/promises" import { createDirectoriesForFile } from "@utils/fs" -import { arePathsEqual } from "@utils/path" +import { arePathsEqual, getCwd } from "@utils/path" import { formatResponse } from "@core/prompts/responses" import { DecorationController } from "./DecorationController" import * as diff from "diff" @@ -21,6 +21,7 @@ export class DiffViewProvider { private createdDirs: string[] = [] private documentWasOpen = false private relPath?: string + private absolutePath?: string private newContent?: string private activeDiffEditor?: vscode.TextEditor private fadedOverlayController?: DecorationController @@ -28,18 +29,20 @@ export class DiffViewProvider { private streamedLines: string[] = [] private preDiagnostics: [vscode.Uri, vscode.Diagnostic[]][] = [] private fileEncoding: string = "utf8" - private scrollListener?: vscode.Disposable - constructor(private cwd: string) {} + constructor() {} async open(relPath: string): Promise { - this.relPath = relPath - const fileExists = this.editType === "modify" - const absolutePath = path.resolve(this.cwd, relPath) this.isEditing = true + this.relPath = relPath + this.absolutePath = path.resolve(await getCwd(), relPath) + const fileExists = this.editType === "modify" + // if the file is already open, ensure it's not dirty before getting its contents if (fileExists) { - const existingDocument = vscode.workspace.textDocuments.find((doc) => arePathsEqual(doc.uri.fsPath, absolutePath)) + const existingDocument = vscode.workspace.textDocuments.find((doc) => + arePathsEqual(doc.uri.fsPath, this.absolutePath), + ) if (existingDocument && existingDocument.isDirty) { await existingDocument.save() } @@ -49,7 +52,7 @@ export class DiffViewProvider { this.preDiagnostics = vscode.languages.getDiagnostics() if (fileExists) { - const fileBuffer = await fs.readFile(absolutePath) + const fileBuffer = await fs.readFile(this.absolutePath) this.fileEncoding = await detectEncoding(fileBuffer) this.originalContent = iconv.decode(fileBuffer, this.fileEncoding) } else { @@ -57,10 +60,10 @@ export class DiffViewProvider { this.fileEncoding = "utf8" } // for new files, create any necessary directories and keep track of new directories to delete if the user denies the operation - this.createdDirs = await createDirectoriesForFile(absolutePath) + this.createdDirs = await createDirectoriesForFile(this.absolutePath) // make sure the file exists before we open it if (!fileExists) { - await fs.writeFile(absolutePath, "") + await fs.writeFile(this.absolutePath, "") } // if the file was already open, close it (must happen after showing the diff view since if it's the only tab the column will close) this.documentWasOpen = false @@ -68,7 +71,7 @@ export class DiffViewProvider { const tabs = vscode.window.tabGroups.all .map((tg) => tg.tabs) .flat() - .filter((tab) => tab.input instanceof vscode.TabInputText && arePathsEqual(tab.input.uri.fsPath, absolutePath)) + .filter((tab) => tab.input instanceof vscode.TabInputText && arePathsEqual(tab.input.uri.fsPath, this.absolutePath)) for (const tab of tabs) { if (!tab.isDirty) { await vscode.window.tabGroups.close(tab) @@ -204,7 +207,6 @@ export class DiffViewProvider { finalContent: undefined, } } - const absolutePath = path.resolve(this.cwd, this.relPath) const updatedDocument = this.activeDiffEditor.document // get the contents before save operation which may do auto-formatting @@ -219,7 +221,7 @@ export class DiffViewProvider { await getHostBridgeProvider().windowClient.showTextDocument( ShowTextDocumentRequest.create({ - path: absolutePath, + path: this.absolutePath, options: ShowTextDocumentOptions.create({ preview: false, preserveFocus: true, @@ -246,13 +248,9 @@ export class DiffViewProvider { initial fix is usually correct and it may just take time for linters to catch up. */ const postDiagnostics = vscode.languages.getDiagnostics() - const newProblems = diagnosticsToProblemsString( - getNewDiagnostics(this.preDiagnostics, postDiagnostics), - [ - vscode.DiagnosticSeverity.Error, // only including errors since warnings can be distracting (if user wants to fix warnings they can use the @problems mention) - ], - this.cwd, - ) // will be empty string if no errors + const newProblems = await diagnosticsToProblemsString(getNewDiagnostics(this.preDiagnostics, postDiagnostics), [ + vscode.DiagnosticSeverity.Error, // only including errors since warnings can be distracting (if user wants to fix warnings they can use the @problems mention) + ]) // will be empty string if no errors const newProblemsMessage = newProblems.length > 0 ? `\n\nNew problems detected after saving the file:\n${newProblems}` : "" @@ -292,24 +290,23 @@ export class DiffViewProvider { } async revertChanges(): Promise { - if (!this.relPath || !this.activeDiffEditor) { + if (!this.absolutePath || !this.activeDiffEditor) { return } const fileExists = this.editType === "modify" const updatedDocument = this.activeDiffEditor.document - const absolutePath = path.resolve(this.cwd, this.relPath) if (!fileExists) { if (updatedDocument.isDirty) { await updatedDocument.save() } await this.closeAllDiffViews() - await fs.unlink(absolutePath) + await fs.unlink(this.absolutePath) // Remove only the directories we created, in reverse order for (let i = this.createdDirs.length - 1; i >= 0; i--) { await fs.rmdir(this.createdDirs[i]) console.log(`Directory ${this.createdDirs[i]} has been deleted.`) } - console.log(`File ${absolutePath} has been deleted.`) + console.log(`File ${this.absolutePath} has been deleted.`) } else { // revert document const edit = new vscode.WorkspaceEdit() @@ -321,11 +318,11 @@ export class DiffViewProvider { // Apply the edit and save, since contents shouldn't have changed this won't show in local history unless of course the user made changes and saved during the edit await vscode.workspace.applyEdit(edit) await updatedDocument.save() - console.log(`File ${absolutePath} has been reverted to its original content.`) + console.log(`File ${this.absolutePath} has been reverted to its original content.`) if (this.documentWasOpen) { await getHostBridgeProvider().windowClient.showTextDocument( ShowTextDocumentRequest.create({ - path: absolutePath, + path: this.absolutePath, options: ShowTextDocumentOptions.create({ preview: false, preserveFocus: true, @@ -353,10 +350,10 @@ export class DiffViewProvider { } private async openDiffEditor(): Promise { - if (!this.relPath) { + if (!this.absolutePath) { throw new Error("No file path set") } - const uri = vscode.Uri.file(path.resolve(this.cwd, this.relPath)) + const uri = vscode.Uri.file(this.absolutePath) // If this diff editor is already open (ie if a previous write file was interrupted) then we should activate that instead of opening a new diff const diffTab = vscode.window.tabGroups.all .flatMap((group) => group.tabs) @@ -455,11 +452,5 @@ export class DiffViewProvider { this.activeLineController = undefined this.streamedLines = [] this.preDiagnostics = [] - - // Clean up the scroll listener - if (this.scrollListener) { - this.scrollListener.dispose() - this.scrollListener = undefined - } } }