Skip to content

Commit 2a9174d

Browse files
ampagentPierrunoYT
andcommitted
1 parent 99f24ec commit 2a9174d

2 files changed

Lines changed: 113 additions & 7 deletions

File tree

‎internal/tools/write_file.go‎

Lines changed: 29 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -23,9 +23,11 @@ func NewScopedWriteFileTool(workspaceRoot string, scope PathScope) Tool {
2323
parameters: Schema{
2424
Type: "object",
2525
Properties: map[string]PropertySchema{
26-
"path": {Type: "string", Description: "Absolute or relative path of the file to write."},
27-
"content": {Type: "string", Description: "Full file contents to write."},
28-
"overwrite": {Type: "boolean", Description: "Whether to allow overwriting an existing file.", Default: false},
26+
"path": {Type: "string", Description: "Absolute or relative path of the file to write."},
27+
"content": {Type: "string", Description: "Full file contents to write."},
28+
"overwrite": {Type: "boolean", Description: "Whether to allow overwriting an existing file.", Default: false},
29+
"bom": {Type: "string", Enum: []string{"auto", "add", "remove"}, Default: "auto", Description: "Existing-file overwrites only: auto preserves an existing or supplied UTF-8 BOM; add/remove explicitly sets its presence. New files retain content bytes. Applied before optional formatting."},
30+
"line_endings": {Type: "string", Enum: []string{"auto", "lf", "crlf"}, Default: "auto", Description: "Existing-file overwrites only: auto preserves dominant existing endings (or supplied dominant CRLF); lf/crlf explicitly selects endings, independently of bom. New files retain content bytes. Applied before optional formatting."},
2931
},
3032
Required: []string{"path", "content"},
3133
AdditionalProperties: false,
@@ -55,6 +57,20 @@ func (tool writeFileTool) RunWithOptions(ctx context.Context, args map[string]an
5557
if err != nil {
5658
return errorResult("Error: Invalid arguments for write_file: " + err.Error())
5759
}
60+
bom, err := stringArg(args, "bom", "auto", false)
61+
if err != nil {
62+
return errorResult("Error: Invalid arguments for write_file: " + err.Error())
63+
}
64+
if bom != "auto" && bom != "add" && bom != "remove" {
65+
return errorResult("Error: Invalid arguments for write_file: bom must be auto, add, or remove")
66+
}
67+
lineEndings, err := stringArg(args, "line_endings", "auto", false)
68+
if err != nil {
69+
return errorResult("Error: Invalid arguments for write_file: " + err.Error())
70+
}
71+
if lineEndings != "auto" && lineEndings != "lf" && lineEndings != "crlf" {
72+
return errorResult("Error: Invalid arguments for write_file: line_endings must be auto, lf, or crlf")
73+
}
5874

5975
absolutePath, relativePath, err := resolveScopedTargetPath(tool.workspaceRoot, tool.scope, requestedPath)
6076
if err != nil {
@@ -108,7 +124,7 @@ func (tool writeFileTool) RunWithOptions(ctx context.Context, args map[string]an
108124
return errorResult("Error writing file " + relativePath + ": cannot read the existing file to preserve its line endings and BOM: " + rerr.Error())
109125
}
110126
priorContent = string(prev)
111-
content = preserveWriteFileEncoding(prev, content)
127+
content = preserveWriteFileEncoding(prev, content, bom, lineEndings)
112128
}
113129
modelEquivalentContent := content
114130

@@ -162,10 +178,13 @@ var utf8BOM = []byte{0xef, 0xbb, 0xbf}
162178
// preserveWriteFileEncoding restores byte-level features hidden by read_file's
163179
// normalized text view. It keeps line endings consistent with the existing
164180
// file, while still allowing an LF file to be explicitly replaced with
165-
// consistently CRLF content.
166-
func preserveWriteFileEncoding(existing []byte, content string) string {
181+
// consistently CRLF content. Explicit BOM and line-ending intent independently
182+
// overrides this automatic behavior, before optional formatting.
183+
func preserveWriteFileEncoding(existing []byte, content, bom, lineEndings string) string {
167184
updated := []byte(content)
168-
if bytes.HasPrefix(existing, utf8BOM) && !bytes.HasPrefix(updated, utf8BOM) {
185+
if bom == "remove" {
186+
updated = bytes.TrimPrefix(updated, utf8BOM)
187+
} else if (bom == "add" || bytes.HasPrefix(existing, utf8BOM)) && !bytes.HasPrefix(updated, utf8BOM) {
169188
updated = append(append([]byte(nil), utf8BOM...), updated...)
170189
}
171190

@@ -177,6 +196,9 @@ func preserveWriteFileEncoding(existing []byte, content string) string {
177196
// unambiguous request to change an LF file's convention.
178197
useCRLF = true
179198
}
199+
if lineEndings != "auto" {
200+
useCRLF = lineEndings == "crlf"
201+
}
180202
updated = bytes.ReplaceAll(updated, []byte("\r\n"), []byte("\n"))
181203
if useCRLF {
182204
updated = bytes.ReplaceAll(updated, []byte("\n"), []byte("\r\n"))

‎internal/tools/write_tools_test.go‎

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -181,6 +181,89 @@ func TestWriteFileToolOverwritePreservesExistingEncoding(t *testing.T) {
181181
}
182182
}
183183

184+
func TestWriteFileToolExplicitEncodingIntent(t *testing.T) {
185+
t.Setenv("ZERO_FORMAT_ON_WRITE", "")
186+
// Explicit intent wins independently; omitted intent retains automatic
187+
// restoration. Every case also exercises a second tracked overwrite.
188+
for _, tt := range []struct {
189+
name, existing, content, bom, endings, want string
190+
}{
191+
{"default both", "\ufeffold\r\n", "new\n", "", "", "\ufeffnew\r\n"},
192+
{"remove BOM retain CRLF", "\ufeffold\r\n", "new\n", "remove", "", "new\r\n"},
193+
{"LF retain BOM", "\ufeffold\r\n", "new\n", "", "lf", "\ufeffnew\n"},
194+
{"LF without BOM", "old\r\n", "new\n", "", "lf", "new\n"},
195+
{"remove and LF", "\ufeffold\r\n", "\ufeffnew\r\n", "remove", "lf", "new\n"},
196+
{"add BOM retain LF", "old\n", "new\n", "add", "", "\ufeffnew\n"},
197+
{"CRLF retain BOM", "\ufeffold\n", "new\n", "", "crlf", "\ufeffnew\r\n"},
198+
{"CRLF without BOM", "old\n", "new\n", "", "crlf", "new\r\n"},
199+
{"add and CRLF", "old\n", "new\n", "add", "crlf", "\ufeffnew\r\n"},
200+
{"empty remove BOM", "\ufeffold\r\n", "", "remove", "", ""},
201+
{"empty default", "\ufeffold\r\n", "", "", "", "\ufeff"},
202+
} {
203+
t.Run(tt.name, func(t *testing.T) {
204+
root := t.TempDir()
205+
path := filepath.Join(root, "example.txt")
206+
if err := os.WriteFile(path, []byte(tt.existing), 0o644); err != nil {
207+
t.Fatal(err)
208+
}
209+
path, err := filepath.EvalSymlinks(path)
210+
if err != nil {
211+
t.Fatal(err)
212+
}
213+
options := RunOptions{FileTracker: NewFileTracker()}
214+
read := NewScopedReadFileTool(root, nil).(optionsAwareTool).RunWithOptions(context.Background(), map[string]any{"path": path}, options)
215+
if read.Status != StatusOK {
216+
t.Fatal(read.Output)
217+
}
218+
args := map[string]any{"path": path, "content": tt.content, "overwrite": true}
219+
if tt.bom != "" {
220+
args["bom"] = tt.bom
221+
}
222+
if tt.endings != "" {
223+
args["line_endings"] = tt.endings
224+
}
225+
for i := 0; i < 2; i++ {
226+
result := NewScopedWriteFileTool(root, nil).(optionsAwareTool).RunWithOptions(context.Background(), args, options)
227+
if result.Status != StatusOK {
228+
t.Fatal(result.Output)
229+
}
230+
got, err := os.ReadFile(path)
231+
if err != nil {
232+
t.Fatal(err)
233+
}
234+
if string(got) != tt.want {
235+
t.Fatalf("written bytes = %q, want %q", got, tt.want)
236+
}
237+
if !options.FileTracker.SeenWhole(path) {
238+
t.Fatal("encoding intent discarded whole-file observation")
239+
}
240+
}
241+
})
242+
}
243+
}
244+
245+
func TestWriteFileToolRejectsInvalidEncodingIntent(t *testing.T) {
246+
for _, key := range []string{"bom", "line_endings"} {
247+
for _, value := range []any{"invalid", true} {
248+
root := t.TempDir()
249+
path := filepath.Join(root, "example.txt")
250+
if err := os.WriteFile(path, []byte("original"), 0o644); err != nil {
251+
t.Fatal(err)
252+
}
253+
result := NewScopedWriteFileTool(root, nil).Run(context.Background(), map[string]any{
254+
"path": path, "content": "replacement", "overwrite": true, key: value,
255+
})
256+
if result.Status != StatusError {
257+
t.Fatalf("accepted %s=%v", key, value)
258+
}
259+
got, err := os.ReadFile(path)
260+
if err != nil || string(got) != "original" {
261+
t.Fatalf("invalid intent changed target: %q, %v", got, err)
262+
}
263+
}
264+
}
265+
}
266+
184267
func TestWriteFileToolEncodingPreservationKeepsWholeFileObservation(t *testing.T) {
185268
t.Setenv("ZERO_FORMAT_ON_WRITE", "")
186269
tests := []struct {
@@ -233,6 +316,7 @@ func TestWriteFileToolNewFileRetainsCallerBytes(t *testing.T) {
233316
want := []byte("\xef\xbb\xbfnew\r\ntext\n")
234317
result := NewScopedWriteFileTool(root, nil).Run(context.Background(), map[string]any{
235318
"path": "example.txt", "content": string(want),
319+
"bom": "remove", "line_endings": "lf",
236320
})
237321
if result.Status != StatusOK {
238322
t.Fatalf("write failed: %s", result.Output)

0 commit comments

Comments
 (0)