Edit 实现 BackendProtocol.Edit
(ctx context.Context, path, oldStr, newStr string, replaceAll bool)
| 176 | |
| 177 | // Edit 实现 BackendProtocol.Edit |
| 178 | func (b *StateBackend) Edit(ctx context.Context, path, oldStr, newStr string, replaceAll bool) (*EditResult, error) { |
| 179 | b.mu.Lock() |
| 180 | defer b.mu.Unlock() |
| 181 | |
| 182 | data, exists := b.files[path] |
| 183 | if !exists { |
| 184 | return &EditResult{ |
| 185 | Error: "file not found: " + path, |
| 186 | Path: path, |
| 187 | }, nil |
| 188 | } |
| 189 | |
| 190 | // 读取当前内容 |
| 191 | content := strings.Join(data.Lines, "\n") |
| 192 | |
| 193 | // 执行替换 |
| 194 | var newContent string |
| 195 | var count int |
| 196 | |
| 197 | if replaceAll { |
| 198 | count = strings.Count(content, oldStr) |
| 199 | newContent = strings.ReplaceAll(content, oldStr, newStr) |
| 200 | } else { |
| 201 | if strings.Contains(content, oldStr) { |
| 202 | newContent = strings.Replace(content, oldStr, newStr, 1) |
| 203 | count = 1 |
| 204 | } else { |
| 205 | newContent = content |
| 206 | count = 0 |
| 207 | } |
| 208 | } |
| 209 | |
| 210 | // 更新文件数据 |
| 211 | if count > 0 { |
| 212 | data.Lines = strings.Split(newContent, "\n") |
| 213 | data.ModifiedAt = time.Now() |
| 214 | } |
| 215 | |
| 216 | return &EditResult{ |
| 217 | Error: "", // 空字符串表示成功 |
| 218 | Path: path, |
| 219 | ReplacementsMade: count, |
| 220 | }, nil |
| 221 | } |
| 222 | |
| 223 | // GrepRaw 实现 BackendProtocol.GrepRaw |
| 224 | func (b *StateBackend) GrepRaw(ctx context.Context, pattern, path, glob string) ([]GrepMatch, error) { |