Skip to content

Commit 4683a27

Browse files
fix(filesystem): strip trailing whitespace on write and edits
Fixes #1590. writeFileContent and applyFileEdits now strip trailing horizontal whitespace from content before writing. Scoped narrowly: writeFileContent cleans the full content being written, while applyFileEdits only cleans the newText an edit introduces, leaving untouched lines elsewhere in the file unaffected.
1 parent 76d64c8 commit 4683a27

2 files changed

Lines changed: 125 additions & 3 deletions

File tree

‎src/filesystem/__tests__/lib.test.ts‎

Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import {
66
// Pure utility functions
77
formatSize,
88
normalizeLineEndings,
9+
stripTrailingWhitespace,
910
createUnifiedDiff,
1011
// Security & validation functions
1112
validatePath,
@@ -308,6 +309,55 @@ describe('Lib Functions', () => {
308309

309310
expect(mockFs.writeFile).toHaveBeenCalledWith('/test/file.txt', 'new content', { encoding: "utf-8", flag: 'wx' });
310311
});
312+
313+
it('strips trailing whitespace from each line before writing', async () => {
314+
mockFs.writeFile.mockResolvedValueOnce(undefined);
315+
316+
await writeFileContent('/test/file.txt', 'line1 \nline2\t\nline3');
317+
318+
expect(mockFs.writeFile).toHaveBeenCalledWith(
319+
'/test/file.txt',
320+
'line1\nline2\nline3',
321+
{ encoding: "utf-8", flag: 'wx' }
322+
);
323+
});
324+
325+
it('strips trailing whitespace on the EEXIST/atomic-rename fallback path too', async () => {
326+
const eexistError = Object.assign(new Error('exists'), { code: 'EEXIST' });
327+
mockFs.writeFile.mockRejectedValueOnce(eexistError);
328+
mockFs.writeFile.mockResolvedValueOnce(undefined);
329+
mockFs.rename.mockResolvedValueOnce(undefined);
330+
331+
await writeFileContent('/test/file.txt', 'line1 \nline2 ');
332+
333+
expect(mockFs.writeFile).toHaveBeenLastCalledWith(
334+
expect.stringContaining('/test/file.txt.'),
335+
'line1\nline2',
336+
'utf-8'
337+
);
338+
});
339+
});
340+
341+
describe('stripTrailingWhitespace', () => {
342+
it('removes trailing spaces and tabs from each line', () => {
343+
const input = 'line1 \nline2\t\t\nline3';
344+
expect(stripTrailingWhitespace(input)).toBe('line1\nline2\nline3');
345+
});
346+
347+
it('leaves leading whitespace untouched', () => {
348+
const input = ' indented line \n\tmixed indent\t';
349+
expect(stripTrailingWhitespace(input)).toBe(' indented line\n\tmixed indent');
350+
});
351+
352+
it('does not change content with no trailing whitespace', () => {
353+
const input = 'line1\nline2\nline3';
354+
expect(stripTrailingWhitespace(input)).toBe(input);
355+
});
356+
357+
it('preserves blank lines and trailing newline', () => {
358+
const input = 'line1 \n\nline3 \n';
359+
expect(stripTrailingWhitespace(input)).toBe('line1\n\nline3\n');
360+
});
311361
});
312362

313363
});
@@ -510,6 +560,60 @@ describe('Lib Functions', () => {
510560
);
511561
});
512562

563+
it('strips trailing whitespace from the new text of an edit', async () => {
564+
const edits = [
565+
{ oldText: 'line2', newText: 'modified line2 \t' }
566+
];
567+
568+
mockFs.rename.mockResolvedValueOnce(undefined);
569+
570+
await applyFileEdits('/test/file.txt', edits, false);
571+
572+
expect(mockFs.writeFile).toHaveBeenCalledWith(
573+
expect.stringMatching(/\/test\/file\.txt\.[a-f0-9]+\.tmp$/),
574+
'line1\nmodified line2\nline3\n',
575+
'utf-8'
576+
);
577+
});
578+
579+
it('does not touch trailing whitespace on lines outside the edit', async () => {
580+
// line3 has trailing spaces but is never targeted by an edit
581+
mockFs.readFile.mockResolvedValue('line1\nline2\nline3 \n');
582+
583+
const edits = [
584+
{ oldText: 'line1', newText: 'first line' }
585+
];
586+
587+
mockFs.rename.mockResolvedValueOnce(undefined);
588+
589+
await applyFileEdits('/test/file.txt', edits, false);
590+
591+
expect(mockFs.writeFile).toHaveBeenCalledWith(
592+
expect.stringMatching(/\/test\/file\.txt\.[a-f0-9]+\.tmp$/),
593+
'first line\nline2\nline3 \n',
594+
'utf-8'
595+
);
596+
});
597+
598+
it('strips trailing whitespace from multi-line replacement text', async () => {
599+
const edits = [
600+
{
601+
oldText: 'line1\nline2',
602+
newText: 'first line \nsecond line\t'
603+
}
604+
];
605+
606+
mockFs.rename.mockResolvedValueOnce(undefined);
607+
608+
await applyFileEdits('/test/file.txt', edits, false);
609+
610+
expect(mockFs.writeFile).toHaveBeenCalledWith(
611+
expect.stringMatching(/\/test\/file\.txt\.[a-f0-9]+\.tmp$/),
612+
'first line\nsecond line\nline3\n',
613+
'utf-8'
614+
);
615+
});
616+
513617
it('throws error for non-matching edits', async () => {
514618
const edits = [
515619
{ oldText: 'nonexistent line', newText: 'replacement' }

‎src/filesystem/lib.ts‎

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,17 @@ export function normalizeLineEndings(text: string): string {
5757
return text.replace(/\r\n/g, '\n');
5858
}
5959

60+
// Strips trailing horizontal whitespace (spaces/tabs) from every line.
61+
// Applied only to content that is actually being written, so callers
62+
// that pass already-clean content see no behavioral change, and edits
63+
// never touch whitespace on lines outside the edit itself.
64+
export function stripTrailingWhitespace(text: string): string {
65+
return text
66+
.split('\n')
67+
.map(line => line.replace(/[ \t]+$/, ''))
68+
.join('\n');
69+
}
70+
6071
export function createUnifiedDiff(originalContent: string, newContent: string, filepath: string = 'file'): string {
6172
// Ensure consistent line endings for diff
6273
const normalizedOriginal = normalizeLineEndings(originalContent);
@@ -159,18 +170,22 @@ export async function readFileContent(filePath: string, encoding: string = 'utf-
159170
}
160171

161172
export async function writeFileContent(filePath: string, content: string): Promise<void> {
173+
// Strip trailing whitespace from every line before writing. This is the
174+
// content the caller is asking us to write, so cleaning it here avoids
175+
// the trailing-whitespace/lint churn reported in #1590.
176+
const cleanedContent = stripTrailingWhitespace(content);
162177
try {
163178
// Security: 'wx' flag ensures exclusive creation - fails if file/symlink exists,
164179
// preventing writes through pre-existing symlinks
165-
await fs.writeFile(filePath, content, { encoding: "utf-8", flag: 'wx' });
180+
await fs.writeFile(filePath, cleanedContent, { encoding: "utf-8", flag: 'wx' });
166181
} catch (error) {
167182
if ((error as NodeJS.ErrnoException).code === 'EEXIST') {
168183
// Security: Use atomic rename to prevent race conditions where symlinks
169184
// could be created between validation and write. Rename operations
170185
// replace the target file atomically and don't follow symlinks.
171186
const tempPath = `${filePath}.${randomBytes(16).toString('hex')}.tmp`;
172187
try {
173-
await fs.writeFile(tempPath, content, 'utf-8');
188+
await fs.writeFile(tempPath, cleanedContent, 'utf-8');
174189
await fs.rename(tempPath, filePath);
175190
} catch (renameError) {
176191
try {
@@ -203,7 +218,10 @@ export async function applyFileEdits(
203218
let modifiedContent = content;
204219
for (const edit of edits) {
205220
const normalizedOld = normalizeLineEndings(edit.oldText);
206-
const normalizedNew = normalizeLineEndings(edit.newText);
221+
// Strip trailing whitespace from the incoming replacement text only -
222+
// this is the content the edit is introducing, so it's safe to clean
223+
// without touching whitespace on unrelated lines elsewhere in the file.
224+
const normalizedNew = stripTrailingWhitespace(normalizeLineEndings(edit.newText));
207225

208226
// If exact match exists, use it
209227
if (modifiedContent.includes(normalizedOld)) {

0 commit comments

Comments
 (0)