( config: Config, filePath: string, proposedContent: string, abortSignal: AbortSignal, )
| 71 | } |
| 72 | |
| 73 | export async function getCorrectedFileContent( |
| 74 | config: Config, |
| 75 | filePath: string, |
| 76 | proposedContent: string, |
| 77 | abortSignal: AbortSignal, |
| 78 | ): Promise<GetCorrectedFileContentResult> { |
| 79 | let originalContent = ''; |
| 80 | let fileExists = false; |
| 81 | let correctedContent = proposedContent; |
| 82 | |
| 83 | try { |
| 84 | originalContent = fs.readFileSync(filePath, 'utf8'); |
| 85 | fileExists = true; // File exists and was read |
| 86 | } catch (err) { |
| 87 | if (isNodeError(err) && err.code === 'ENOENT') { |
| 88 | fileExists = false; |
| 89 | originalContent = ''; |
| 90 | } else { |
| 91 | // File exists but could not be read (permissions, etc.) |
| 92 | fileExists = true; // Mark as existing but problematic |
| 93 | originalContent = ''; // Can't use its content |
| 94 | const error = { |
| 95 | message: getErrorMessage(err), |
| 96 | code: isNodeError(err) ? err.code : undefined, |
| 97 | }; |
| 98 | // Return early as we can't proceed with content correction meaningfully |
| 99 | return { originalContent, correctedContent, fileExists, error }; |
| 100 | } |
| 101 | } |
| 102 | |
| 103 | // If readError is set, we have returned. |
| 104 | // So, file was either read successfully (fileExists=true, originalContent set) |
| 105 | // or it was ENOENT (fileExists=false, originalContent=''). |
| 106 | |
| 107 | if (fileExists) { |
| 108 | // This implies originalContent is available |
| 109 | const { params: correctedParams } = await ensureCorrectEdit( |
| 110 | filePath, |
| 111 | originalContent, |
| 112 | { |
| 113 | old_string: originalContent, // Treat entire current content as old_string |
| 114 | new_string: proposedContent, |
| 115 | file_path: filePath, |
| 116 | }, |
| 117 | config.getAnusClient(), |
| 118 | abortSignal, |
| 119 | ); |
| 120 | correctedContent = correctedParams.new_string; |
| 121 | } else { |
| 122 | // This implies new file (ENOENT) |
| 123 | correctedContent = await ensureCorrectFileContent( |
| 124 | proposedContent, |
| 125 | config.getAnusClient(), |
| 126 | abortSignal, |
| 127 | ); |
| 128 | } |
| 129 | return { originalContent, correctedContent, fileExists }; |
| 130 | } |
no test coverage detected