fix: ensure parent directories exist before file operations in WriteToFileTool

Fixes ENOENT errors when creating files in non-existent subdirectories by:
- Wrapping fileExistsAtPath calls in try-catch blocks
- Creating parent directories recursively when they do not exist
- Treating files as new when parent directories need to be created

This applies the fix from issue #9635 to the source code rather than the minified distribution file.
This commit is contained in:
Roo Code 2025-11-26 23:54:11 +00:00
parent ba09228015
commit 9747413924

View file

@ -75,7 +75,20 @@ export class WriteToFileTool extends BaseTool<"write_to_file"> {
fileExists = task.diffViewProvider.editType === "modify"
} else {
const absolutePath = path.resolve(task.cwd, relPath)
fileExists = await fileExistsAtPath(absolutePath)
// Ensure parent directory exists before checking file existence
try {
fileExists = await fileExistsAtPath(absolutePath)
} catch (error) {
// If we get ENOENT, the parent directory might not exist
// Create the parent directory and treat this as a new file
const parentDir = path.dirname(absolutePath)
try {
await fs.mkdir(parentDir, { recursive: true })
} catch {
// Ignore errors from mkdir, we'll handle them when writing
}
fileExists = false
}
task.diffViewProvider.editType = fileExists ? "modify" : "create"
}
@ -311,7 +324,20 @@ export class WriteToFileTool extends BaseTool<"write_to_file"> {
fileExists = task.diffViewProvider.editType === "modify"
} else {
const absolutePath = path.resolve(task.cwd, relPath)
fileExists = await fileExistsAtPath(absolutePath)
// Ensure parent directory exists before checking file existence
try {
fileExists = await fileExistsAtPath(absolutePath)
} catch (error) {
// If we get ENOENT, the parent directory might not exist
// Create the parent directory and treat this as a new file
const parentDir = path.dirname(absolutePath)
try {
await fs.mkdir(parentDir, { recursive: true })
} catch {
// Ignore errors from mkdir, we'll handle them when writing
}
fileExists = false
}
task.diffViewProvider.editType = fileExists ? "modify" : "create"
}