in packages/core/src/tools/write-file.ts [215:325]
async execute(
params: WriteFileToolParams,
abortSignal: AbortSignal,
): Promise<ToolResult> {
const validationError = this.validateToolParams(params);
if (validationError) {
return {
llmContent: `Error: Invalid parameters provided. Reason: ${validationError}`,
returnDisplay: `Error: ${validationError}`,
};
}
const correctedContentResult = await this._getCorrectedFileContent(
params.file_path,
params.content,
abortSignal,
);
if (correctedContentResult.error) {
const errDetails = correctedContentResult.error;
const errorMsg = `Error checking existing file: ${errDetails.message}`;
return {
llmContent: `Error checking existing file ${params.file_path}: ${errDetails.message}`,
returnDisplay: errorMsg,
};
}
const {
originalContent,
correctedContent: fileContent,
fileExists,
} = correctedContentResult;
// fileExists is true if the file existed (and was readable or unreadable but caught by readError).
// fileExists is false if the file did not exist (ENOENT).
const isNewFile =
!fileExists ||
(correctedContentResult.error !== undefined &&
!correctedContentResult.fileExists);
try {
const dirName = path.dirname(params.file_path);
if (!fs.existsSync(dirName)) {
fs.mkdirSync(dirName, { recursive: true });
}
fs.writeFileSync(params.file_path, fileContent, 'utf8');
// Generate diff for display result
const fileName = path.basename(params.file_path);
// If there was a readError, originalContent in correctedContentResult is '',
// but for the diff, we want to show the original content as it was before the write if possible.
// However, if it was unreadable, currentContentForDiff will be empty.
const currentContentForDiff = correctedContentResult.error
? '' // Or some indicator of unreadable content
: originalContent;
const fileDiff = Diff.createPatch(
fileName,
currentContentForDiff,
fileContent,
'Original',
'Written',
DEFAULT_DIFF_OPTIONS,
);
const llmSuccessMessageParts = [
isNewFile
? `Successfully created and wrote to new file: ${params.file_path}.`
: `Successfully overwrote file: ${params.file_path}.`,
];
if (params.modified_by_user) {
llmSuccessMessageParts.push(
`User modified the \`content\` to be: ${params.content}`,
);
}
const displayResult: FileDiff = { fileDiff, fileName };
const lines = fileContent.split('\n').length;
const mimetype = getSpecificMimeType(params.file_path);
const extension = path.extname(params.file_path); // Get extension
if (isNewFile) {
recordFileOperationMetric(
this.config,
FileOperation.CREATE,
lines,
mimetype,
extension,
);
} else {
recordFileOperationMetric(
this.config,
FileOperation.UPDATE,
lines,
mimetype,
extension,
);
}
return {
llmContent: llmSuccessMessageParts.join(' '),
returnDisplay: displayResult,
};
} catch (error) {
const errorMsg = `Error writing to file: ${error instanceof Error ? error.message : String(error)}`;
return {
llmContent: `Error writing to file ${params.file_path}: ${errorMsg}`,
returnDisplay: `Error: ${errorMsg}`,
};
}
}