Skip to content

Commit

Permalink
fix: cleanup stdout output
Browse files Browse the repository at this point in the history
  • Loading branch information
gmickel committed Aug 8, 2024
1 parent d646b46 commit 9a1f351
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 24 deletions.
23 changes: 10 additions & 13 deletions src/ai/apply-changes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,8 @@ async function applyFileChange(
const fullPath = path.join(basePath, file.path);
const tempPath = path.join(tmpdir(), `codewhisper-${uuidv4()}`);

console.log(`Processing file: ${file.path}`);
console.log(`File status: ${file.status}`);
console.log(chalk.cyan(`Processing file: ${file.path}`));
console.log(chalk.cyan(`File status: ${file.status}`));

try {
switch (file.status) {
Expand Down Expand Up @@ -78,35 +78,36 @@ async function applyFileChange(
let currentContent: string;
try {
currentContent = await fs.readFile(fullPath, 'utf-8');
console.log(`Current content length: ${currentContent.length}`);
} catch (error) {
console.error(chalk.red(`Error reading file ${file.path}:`, error));
throw error;
}

// Write current content to temp file first
await fs.writeFile(tempPath, currentContent);
console.log(`Wrote original content to temp file: ${tempPath}`);
console.log(
chalk.cyan(`Wrote original content to temp file: ${tempPath}`),
);

let updatedContent: string;

if (file.changes && file.changes.length > 0) {
console.log(`Applying ${file.changes.length} changes in diff mode`);
console.log(
chalk.cyan(
`Applying ${file.changes.length} changes in diff mode`,
),
);
updatedContent = applySearchReplace(currentContent, file.changes);
if (updatedContent === currentContent) {
console.log(chalk.yellow(`No changes applied to: ${file.path}`));
await fs.remove(tempPath);
return;
}
console.log(
`Updated content length after changes: ${updatedContent.length}`,
);
// Write updated content to temp file
await fs.writeFile(tempPath, updatedContent);
} else if (file.content) {
console.log('Applying whole file edit');
updatedContent = file.content;
console.log(`New content length: ${updatedContent.length}`);
// Write new content to temp file
await fs.writeFile(tempPath, updatedContent);
} else {
Expand All @@ -118,10 +119,6 @@ async function applyFileChange(
// Move temp file to overwrite original file
await fs.move(tempPath, fullPath, { overwrite: true });
console.log(chalk.green(`Modified file: ${file.path}`));

// Verify final content
const finalContent = await fs.readFile(fullPath, 'utf-8');
console.log(`Final content length: ${finalContent.length}`);
}
break;
case 'deleted':
Expand Down
19 changes: 9 additions & 10 deletions src/ai/parsers/search-replace-parser.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import chalk from 'chalk';
import { detectLanguage } from '../../core/file-worker';
import type { AIFileChange, AIFileInfo } from '../../types';
import getLogger from '../../utils/logger';
Expand Down Expand Up @@ -42,8 +43,8 @@ export function parseSearchReplaceFiles(response: string): AIFileInfo[] {
? explanationMatch[1].trim()
: undefined;

console.log(`Parsing file: ${path}`);
console.log(`Status: ${status}`);
console.log(chalk.cyan(`Parsing file: ${path}`));
console.log(chalk.cyan(`Status: ${status}`));

const fileInfo: AIFileInfo = {
path,
Expand Down Expand Up @@ -78,7 +79,7 @@ export function parseSearchReplaceFiles(response: string): AIFileInfo[] {
* @returns An array of AIFileChange objects representing the parsed search/replace blocks.
*/
function parseSearchReplaceBlocks(content: string): AIFileChange[] {
console.log('Parsing search/replace blocks. Content:', content);
console.log(chalk.cyan('Parsing search/replace blocks.'));

const blockRegex =
/<<<<<<< SEARCH([\s\S]*?)=======([\s\S]*?)>>>>>>> REPLACE/g;
Expand All @@ -93,11 +94,11 @@ function parseSearchReplaceBlocks(content: string): AIFileChange[] {
if (search && replace) {
changes.push({ search, replace });
} else {
console.log('Invalid block structure');
console.log(chalk.red('Invalid block structure'));
}
}

console.log(`Found ${changes.length} valid changes`);
console.log(chalk.cyan(`Found ${changes.length} valid changes`));
return changes;
}

Expand All @@ -118,10 +119,6 @@ export function applySearchReplace(
const matchResult = flexibleMatch(result, block.search, block.replace);
if (matchResult) {
result = matchResult;
} else {
console.warn(
`Failed to apply change:\n${block.search}\n=====\n${block.replace}`,
);
}
}

Expand Down Expand Up @@ -154,7 +151,7 @@ function flexibleMatch(
}

// If nothing else, log the failure so the user can manually fix it
console.warn(generateMatchFailureReport(content, searchBlock));
console.warn(chalk.yellow(generateMatchFailureReport(content, searchBlock)));
logger.info(
generateMatchFailureReport(
'Match Failure:',
Expand Down Expand Up @@ -243,6 +240,8 @@ function generateMatchFailureReport(
const similarLines = findSimilarLines(searchLines, contentLines);
errorMessage += similarLines;

errorMessage += '\n\nThis diff will have to be applied manually.\n\n';

return errorMessage;
}

Expand Down
2 changes: 1 addition & 1 deletion tests/unit/apply-changes.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ describe('applyChanges', () => {

expect(fs.ensureDir).toHaveBeenCalledTimes(1);
expect(fs.writeFile).toHaveBeenCalledTimes(3);
expect(fs.readFile).toHaveBeenCalledTimes(2);
expect(fs.readFile).toHaveBeenCalledTimes(1);
expect(fs.remove).toHaveBeenCalledTimes(1);
expect(applySearchReplace).toHaveBeenCalledTimes(1);

Expand Down

0 comments on commit 9a1f351

Please sign in to comment.