Edit 实现 BackendProtocol.Edit
(ctx context.Context, path, oldStr, newStr string, replaceAll bool)
| 111 | |
| 112 | // Edit 实现 BackendProtocol.Edit |
| 113 | func (b *FilesystemBackend) Edit(ctx context.Context, path, oldStr, newStr string, replaceAll bool) (*EditResult, error) { |
| 114 | // 读取文件内容 |
| 115 | content, err := b.fs.Read(ctx, path) |
| 116 | if err != nil { |
| 117 | return &EditResult{ |
| 118 | Error: fmt.Sprintf("failed to read file: %v", err), |
| 119 | Path: path, |
| 120 | }, nil |
| 121 | } |
| 122 | |
| 123 | // 执行替换 |
| 124 | var newContent string |
| 125 | var count int |
| 126 | |
| 127 | if replaceAll { |
| 128 | count = strings.Count(content, oldStr) |
| 129 | newContent = strings.ReplaceAll(content, oldStr, newStr) |
| 130 | } else { |
| 131 | if strings.Contains(content, oldStr) { |
| 132 | newContent = strings.Replace(content, oldStr, newStr, 1) |
| 133 | count = 1 |
| 134 | } else { |
| 135 | newContent = content |
| 136 | count = 0 |
| 137 | } |
| 138 | } |
| 139 | |
| 140 | // 写回文件 |
| 141 | if count > 0 { |
| 142 | if err := b.fs.Write(ctx, path, newContent); err != nil { |
| 143 | return &EditResult{ |
| 144 | Error: fmt.Sprintf("failed to write file: %v", err), |
| 145 | Path: path, |
| 146 | }, nil |
| 147 | } |
| 148 | } |
| 149 | |
| 150 | return &EditResult{ |
| 151 | Error: "", // 空字符串表示成功 |
| 152 | Path: path, |
| 153 | ReplacementsMade: count, |
| 154 | }, nil |
| 155 | } |
| 156 | |
| 157 | // GrepRaw 实现 BackendProtocol.GrepRaw |
| 158 | func (b *FilesystemBackend) GrepRaw(ctx context.Context, pattern, path, glob string) ([]GrepMatch, error) { |