applyTextEditsToFile applies LSP text edits to a file on disk
(filePath string, edits []lspTextEdit)
| 1402 | |
| 1403 | // applyTextEditsToFile applies LSP text edits to a file on disk |
| 1404 | func applyTextEditsToFile(filePath string, edits []lspTextEdit) error { |
| 1405 | content, err := os.ReadFile(filePath) |
| 1406 | if err != nil { |
| 1407 | return fmt.Errorf("failed to read file: %w", err) |
| 1408 | } |
| 1409 | |
| 1410 | lines := strings.Split(string(content), "\n") |
| 1411 | |
| 1412 | sortedEdits := make([]lspTextEdit, len(edits)) |
| 1413 | copy(sortedEdits, edits) |
| 1414 | slices.SortFunc(sortedEdits, func(a, b lspTextEdit) int { |
| 1415 | if a.Range.Start.Line != b.Range.Start.Line { |
| 1416 | return cmp.Compare(b.Range.Start.Line, a.Range.Start.Line) |
| 1417 | } |
| 1418 | return cmp.Compare(b.Range.Start.Character, a.Range.Start.Character) |
| 1419 | }) |
| 1420 | |
| 1421 | for _, edit := range sortedEdits { |
| 1422 | lines = applyTextEdit(lines, edit) |
| 1423 | } |
| 1424 | |
| 1425 | newContent := strings.Join(lines, "\n") |
| 1426 | if err := os.WriteFile(filePath, []byte(newContent), 0o644); err != nil { //nolint:gosec // file pre-exists; mode is only applied on creation |
| 1427 | return fmt.Errorf("failed to write file: %w", err) |
| 1428 | } |
| 1429 | |
| 1430 | return nil |
| 1431 | } |
| 1432 | |
| 1433 | func applyTextEdit(lines []string, edit lspTextEdit) []string { |
| 1434 | startLine := edit.Range.Start.Line |
no test coverage detected