feat(tools/file): edit_file atomic + preserve existing mode

This commit is contained in:
sausheong committed 2026-06-13 00:51:57 +08:00
1 parent 7ae944f0eb
commit 87f77c76ba
2 files changed
+39 -1

No files matched your search

+5 -1
View File
@@ -91,7 +91,11 @@ func (t *EditFileTool) Execute(_ context.Context, input json.RawMessage) (tool.T
newContent := strings.Replace(content, in.OldString, in.NewString, 1)
if err := os.WriteFile(in.Path, []byte(newContent), 0o644); err != nil {
mode := os.FileMode(0o600)
if info, statErr := os.Stat(in.Path); statErr == nil {
mode = info.Mode().Perm()
}
if err := tool.WriteFileAtomic(in.Path, []byte(newContent), mode); err != nil {
return tool.ToolResult{Error: fmt.Sprintf("failed to write file: %v", err)}, nil
}
+34
View File
@@ -0,0 +1,34 @@
package file
import (
"context"
"encoding/json"
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/require"
)
func TestEditFilePreservesMode(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "code.txt")
require.NoError(t, os.WriteFile(path, []byte("alpha beta"), 0o640))
tool := &EditFileTool{WorkDir: dir}
in, _ := json.Marshal(map[string]string{
"path": path,
"old_string": "alpha",
"new_string": "gamma",
})
res, err := tool.Execute(context.Background(), in)
require.NoError(t, err)
require.Empty(t, res.Error)
data, _ := os.ReadFile(path)
require.Equal(t, "gamma beta", string(data))
info, err := os.Stat(path)
require.NoError(t, err)
require.Equal(t, os.FileMode(0o640), info.Mode().Perm())
}