Skip to content

Commit 31a6437

Browse files
fix(filesystem): strip trailing whitespace on write and edits
Fixes modelcontextprotocol#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 2e3e4c7 commit 31a6437

2 files changed

Lines changed: 127 additions & 3 deletions

File tree

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

Lines changed: 106 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,
@@ -377,6 +378,57 @@ describe('Lib Functions', () => {
377378
await expect(writeFileContent('/test/script.sh', 'new content')).resolves.toBeUndefined();
378379
expect(mockFs.unlink).not.toHaveBeenCalled();
379380
});
381+
382+
it('strips trailing whitespace from each line before writing', async () => {
383+
mockFs.writeFile.mockResolvedValueOnce(undefined);
384+
385+
await writeFileContent('/test/file.txt', 'line1 \nline2\t\nline3');
386+
387+
expect(mockFs.writeFile).toHaveBeenCalledWith(
388+
'/test/file.txt',
389+
'line1\nline2\nline3',
390+
{ encoding: "utf-8", flag: 'wx' }
391+
);
392+
});
393+
394+
it('strips trailing whitespace on the EEXIST/atomic-rename fallback path too', async () => {
395+
const eexistError = Object.assign(new Error('exists'), { code: 'EEXIST' });
396+
mockFs.writeFile.mockRejectedValueOnce(eexistError);
397+
mockFs.stat.mockResolvedValueOnce({ mode: 0o100644 });
398+
mockFs.writeFile.mockResolvedValueOnce(undefined);
399+
mockFs.rename.mockResolvedValueOnce(undefined);
400+
mockFs.chmod.mockResolvedValueOnce(undefined);
401+
402+
await writeFileContent('/test/file.txt', 'line1 \nline2 ');
403+
404+
expect(mockFs.writeFile).toHaveBeenLastCalledWith(
405+
expect.stringContaining('/test/file.txt.'),
406+
'line1\nline2',
407+
'utf-8'
408+
);
409+
});
410+
});
411+
412+
describe('stripTrailingWhitespace', () => {
413+
it('removes trailing spaces and tabs from each line', () => {
414+
const input = 'line1 \nline2\t\t\nline3';
415+
expect(stripTrailingWhitespace(input)).toBe('line1\nline2\nline3');
416+
});
417+
418+
it('leaves leading whitespace untouched', () => {
419+
const input = ' indented line \n\tmixed indent\t';
420+
expect(stripTrailingWhitespace(input)).toBe(' indented line\n\tmixed indent');
421+
});
422+
423+
it('does not change content with no trailing whitespace', () => {
424+
const input = 'line1\nline2\nline3';
425+
expect(stripTrailingWhitespace(input)).toBe(input);
426+
});
427+
428+
it('preserves blank lines and trailing newline', () => {
429+
const input = 'line1 \n\nline3 \n';
430+
expect(stripTrailingWhitespace(input)).toBe('line1\n\nline3\n');
431+
});
380432
});
381433

382434
describe('moveFile', () => {
@@ -604,6 +656,60 @@ describe('Lib Functions', () => {
604656
);
605657
});
606658

659+
it('strips trailing whitespace from the new text of an edit', async () => {
660+
const edits = [
661+
{ oldText: 'line2', newText: 'modified line2 \t' }
662+
];
663+
664+
mockFs.rename.mockResolvedValueOnce(undefined);
665+
666+
await applyFileEdits('/test/file.txt', edits, false);
667+
668+
expect(mockFs.writeFile).toHaveBeenCalledWith(
669+
expect.stringMatching(/\/test\/file\.txt\.[a-f0-9]+\.tmp$/),
670+
'line1\nmodified line2\nline3\n',
671+
'utf-8'
672+
);
673+
});
674+
675+
it('does not touch trailing whitespace on lines outside the edit', async () => {
676+
// line3 has trailing spaces but is never targeted by an edit
677+
mockFs.readFile.mockResolvedValue('line1\nline2\nline3 \n');
678+
679+
const edits = [
680+
{ oldText: 'line1', newText: 'first line' }
681+
];
682+
683+
mockFs.rename.mockResolvedValueOnce(undefined);
684+
685+
await applyFileEdits('/test/file.txt', edits, false);
686+
687+
expect(mockFs.writeFile).toHaveBeenCalledWith(
688+
expect.stringMatching(/\/test\/file\.txt\.[a-f0-9]+\.tmp$/),
689+
'first line\nline2\nline3 \n',
690+
'utf-8'
691+
);
692+
});
693+
694+
it('strips trailing whitespace from multi-line replacement text', async () => {
695+
const edits = [
696+
{
697+
oldText: 'line1\nline2',
698+
newText: 'first line \nsecond line\t'
699+
}
700+
];
701+
702+
mockFs.rename.mockResolvedValueOnce(undefined);
703+
704+
await applyFileEdits('/test/file.txt', edits, false);
705+
706+
expect(mockFs.writeFile).toHaveBeenCalledWith(
707+
expect.stringMatching(/\/test\/file\.txt\.[a-f0-9]+\.tmp$/),
708+
'first line\nsecond line\nline3\n',
709+
'utf-8'
710+
);
711+
});
712+
607713
it('preserves file permissions after applying edits', async () => {
608714
mockFs.stat.mockResolvedValue({ mode: 0o100755 });
609715
const edits = [

‎src/filesystem/lib.ts‎

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

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

205216
export async function writeFileContent(filePath: string, content: string): Promise<void> {
217+
// Strip trailing whitespace from every line before writing. This is the
218+
// content the caller is asking us to write, so cleaning it here avoids
219+
// the trailing-whitespace/lint churn reported in #1590.
220+
const cleanedContent = stripTrailingWhitespace(content);
206221
try {
207222
// Security: 'wx' flag ensures exclusive creation - fails if file/symlink exists,
208223
// preventing writes through pre-existing symlinks
209-
await fs.writeFile(filePath, content, { encoding: "utf-8", flag: 'wx' });
224+
await fs.writeFile(filePath, cleanedContent, { encoding: "utf-8", flag: 'wx' });
210225
} catch (error) {
211226
if ((error as NodeJS.ErrnoException).code === 'EEXIST') {
212227
// Security: Use atomic rename to prevent race conditions where symlinks
@@ -215,7 +230,7 @@ export async function writeFileContent(filePath: string, content: string): Promi
215230
const origStats = await fs.stat(filePath);
216231
const tempPath = `${filePath}.${randomBytes(16).toString('hex')}.tmp`;
217232
try {
218-
await fs.writeFile(tempPath, content, 'utf-8');
233+
await fs.writeFile(tempPath, cleanedContent, 'utf-8');
219234
await fs.rename(tempPath, filePath);
220235
} catch (renameError) {
221236
try {
@@ -274,7 +289,10 @@ export async function applyFileEdits(
274289
let modifiedContent = content;
275290
for (const edit of edits) {
276291
const normalizedOld = normalizeLineEndings(edit.oldText);
277-
const normalizedNew = normalizeLineEndings(edit.newText);
292+
// Strip trailing whitespace from the incoming replacement text only -
293+
// this is the content the edit is introducing, so it's safe to clean
294+
// without touching whitespace on unrelated lines elsewhere in the file.
295+
const normalizedNew = stripTrailingWhitespace(normalizeLineEndings(edit.newText));
278296

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

0 commit comments

Comments
 (0)