Skip to content

Commit 57d37ac

Browse files
committed
Merge remote-tracking branch 'origin/v2/main' into v2/chore/1149-windows-ci
Signed-off-by: cliffhall <[email protected]>
2 parents 4393f9b + 87a395a commit 57d37ac

5 files changed

Lines changed: 117 additions & 6 deletions

File tree

‎.changeset/filesystem-in-place-write.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,4 +2,4 @@
22
"@modelcontextprotocol/server-filesystem": patch
33
---
44

5-
`write_file` and `edit_file` now overwrite an existing file in place instead of renaming a temp file over it, so the file keeps its inode, creation time (birthtime), hard links and permission bits (#4512), and an overwrite no longer fails with `EPERM` on Windows when another process holds the file open (#3199). A symlink swapped in after the path was validated is still refused rather than written through, now by an `O_NOFOLLOW` open (on POSIX) and a check that the opened file is the one validated (on every platform). The overwrite is no longer crash-atomic.
5+
`write_file` and `edit_file` now overwrite an existing file in place instead of renaming a temp file over it, so the file keeps its inode, creation time (birthtime), hard links and permission bits (#4512), and an overwrite no longer fails with `EPERM` on Windows when another process holds the file open (#3199). A symlink swapped in after the path was validated is still refused rather than written through, now by an `O_NOFOLLOW` open (on POSIX) and a check that the opened file is the one validated (on every platform). The overwrite is no longer crash-atomic. A read-only file is now refused (`EACCES`, or `EPERM` on Windows) instead of being replaced, since writing in place opens the file itself for writing.

‎src/filesystem/README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,7 @@ The server's directory access control follows this flow:
100100
- An existing file is overwritten in place, so it keeps its inode, creation
101101
time, hard links and permissions (`edit_file` writes the same way). The
102102
overwrite is not crash-atomic: a crash mid-write can leave the file partly
103-
written
103+
written. A read-only file is refused rather than replaced
104104

105105
- **edit_file**
106106
- Make selective edits using advanced pattern matching and formatting

‎src/filesystem/__tests__/path-validation.test.ts‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1279,8 +1279,11 @@ describe("Path Validation", () => {
12791279
const realPath = await fs.realpath(legitFile);
12801280
expect(isPathWithinAllowedDirectories(realPath, allowed)).toBe(false);
12811281

1282-
// The server's write path refuses a symlink rather than following it
1283-
// (lstat, O_NOFOLLOW and an inode check in lib.ts's overwriteInPlace)
1282+
// So validatePath, which checks the realpath, refuses this
1283+
// outside-pointing symlink before any write is attempted. A symlink
1284+
// swapped in after validation is refused by the write itself (lstat,
1285+
// O_NOFOLLOW and an inode check in lib.ts's overwriteInPlace), which
1286+
// server-tools.test.ts covers.
12841287

12851288
// Verify content remains unchanged
12861289
const targetContent = await fs.readFile(targetFile, "utf-8");

‎src/filesystem/__tests__/server-tools.test.ts‎

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -556,6 +556,30 @@ describe("write_file", () => {
556556
expect(await fs.readFile(hardLink, "utf-8")).toBe("changed");
557557
});
558558

559+
// Writing in place opens the existing file for writing, so a read-only file
560+
// is refused rather than replaced; the old rename only got past the mode
561+
// bits because it rewrote the directory entry instead of the file. Root
562+
// ignores mode bits, so the refusal cannot be observed there.
563+
it.skipIf(process.getuid?.() === 0)(
564+
"refuses to overwrite a read-only file and leaves it unchanged",
565+
async () => {
566+
const file = path.join(dir, "readonly.txt");
567+
await fs.writeFile(file, "keep me");
568+
await fs.chmod(file, 0o444);
569+
try {
570+
const result = await call(client, "write_file", {
571+
path: file,
572+
content: "replaced",
573+
});
574+
expect(result.isError).toBe(true);
575+
expect(textOf(result)).toMatch(/EACCES|EPERM/);
576+
expect(await fs.readFile(file, "utf-8")).toBe("keep me");
577+
} finally {
578+
await fs.chmod(file, 0o644);
579+
}
580+
},
581+
);
582+
559583
it("truncates the old content when the new content is shorter", async () => {
560584
const file = path.join(dir, "existing.txt");
561585
await fs.writeFile(file, "a much longer original");
@@ -842,6 +866,41 @@ describe("edit_file", () => {
842866
);
843867
});
844868

869+
it("dedents a tab-indented file by levels when the edit indents with spaces", async () => {
870+
await fs.writeFile(file, "\tif (a) {\n\t\tb();\n\t}\n");
871+
await call(client, "edit_file", {
872+
path: file,
873+
edits: [{ oldText: " b();", newText: " c();" }],
874+
});
875+
// The edit dedents b() by one 2-space level; in the file that is one
876+
// tab, not two characters (which would strip both tabs).
877+
expect(await fs.readFile(file, "utf-8")).toBe(
878+
"\tif (a) {\n\tc();\n\t}\n",
879+
);
880+
});
881+
882+
it("indents a tab-indented file by levels when the edit indents with spaces", async () => {
883+
await fs.writeFile(file, "\tif (a) {\n\t\tb();\n\t}\n");
884+
await call(client, "edit_file", {
885+
path: file,
886+
edits: [{ oldText: "if (a) {\n b();", newText: "if (a) {\n c();" }],
887+
});
888+
expect(await fs.readFile(file, "utf-8")).toBe(
889+
"\tif (a) {\n\t\t\tc();\n\t}\n",
890+
);
891+
});
892+
893+
it("indents a space-indented file by levels when the edit indents with tabs", async () => {
894+
await fs.writeFile(file, " if (a) {\n b();\n }\n");
895+
await call(client, "edit_file", {
896+
path: file,
897+
edits: [{ oldText: "if (a) {\n\tb();", newText: "if (a) {\n\t\tc();" }],
898+
});
899+
expect(await fs.readFile(file, "utf-8")).toBe(
900+
" if (a) {\n c();\n }\n",
901+
);
902+
});
903+
845904
it("keeps the file's indentation when oldText indents with a different width", async () => {
846905
await fs.writeFile(file, " if (a) {\n b();\n }\n");
847906
await call(client, "edit_file", {

‎src/filesystem/lib.ts‎

Lines changed: 51 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -403,19 +403,57 @@ function leadingWhitespace(line: string): string {
403403
return line.slice(0, line.length - line.trimStart().length);
404404
}
405405

406+
/**
407+
* The indentation unit of some lines: a tab when any indented line starts
408+
* with one, otherwise the narrowest run of leading spaces, or "" when no line
409+
* is indented.
410+
*/
411+
function indentUnit(lines: string[]): string {
412+
let narrowest = Infinity;
413+
for (const line of lines) {
414+
const indent = leadingWhitespace(line);
415+
if (indent === "" || line.trim() === "") continue;
416+
if (indent.includes("\t")) return "\t";
417+
narrowest = Math.min(narrowest, indent.length);
418+
}
419+
return narrowest === Infinity ? "" : " ".repeat(narrowest);
420+
}
421+
406422
/**
407423
* Reindents one replacement line for the whitespace-tolerant matcher: it gets
408424
* the indentation of `fileLine` (the file line it replaces), plus or minus the
409425
* difference between its own indentation and `oldLine`'s (the oldText line
410426
* that matched `fileLine`). A dedent never goes below no indentation. A blank
411427
* line is kept as given.
428+
*
429+
* When the edit and the file indent with different characters (tabs in one,
430+
* spaces in the other), the difference is counted in indent levels of the
431+
* edit's unit and applied in the file's unit, so four spaces of extra
432+
* indent in the edit become one tab in a tab-indented file.
412433
*/
413-
function reindentLine(line: string, fileLine: string, oldLine: string): string {
434+
function reindentLine(
435+
line: string,
436+
fileLine: string,
437+
oldLine: string,
438+
editUnit: string,
439+
fileUnit: string,
440+
): string {
414441
const body = line.trimStart();
415442
if (body === "") return line;
416443
const fileIndent = leadingWhitespace(fileLine);
417444
const newIndent = leadingWhitespace(line);
418445
const delta = newIndent.length - leadingWhitespace(oldLine).length;
446+
if (editUnit && fileUnit && (editUnit === "\t") !== (fileUnit === "\t")) {
447+
const levels = Math.trunc(delta / editUnit.length);
448+
const indent =
449+
levels >= 0
450+
? fileIndent + fileUnit.repeat(levels)
451+
: fileIndent.slice(
452+
0,
453+
Math.max(0, fileIndent.length + levels * fileUnit.length),
454+
);
455+
return indent + body;
456+
}
419457
const indent =
420458
delta >= 0
421459
? fileIndent + newIndent.slice(newIndent.length - delta)
@@ -468,9 +506,20 @@ export async function applyFileEdits(
468506
// replaces, shifted by however much the edit indents or dedents it
469507
// relative to the matching oldText line (#4990). Lines beyond
470508
// oldText's length are placed relative to its last line.
509+
const editUnit = indentUnit([
510+
...oldLines,
511+
...normalizedNew.split("\n"),
512+
]);
513+
const fileUnit = indentUnit(contentLines);
471514
const newLines = normalizedNew.split("\n").map((line, j) => {
472515
const k = Math.min(j, oldLines.length - 1);
473-
return reindentLine(line, potentialMatch[k], oldLines[k]);
516+
return reindentLine(
517+
line,
518+
potentialMatch[k],
519+
oldLines[k],
520+
editUnit,
521+
fileUnit,
522+
);
474523
});
475524

476525
contentLines.splice(i, oldLines.length, ...newLines);

0 commit comments

Comments
 (0)