Skip to main content

aft/
edit.rs

1//! Shared edit engine: byte-offset conversion, content replacement,
2//! syntax validation, and auto-backup orchestration.
3//!
4//! Used by `write`, `edit_symbol`, `edit_match`, and `batch` commands.
5
6use std::path::Path;
7
8use crate::config::Config;
9use crate::context::AppContext;
10use crate::error::AftError;
11use crate::format;
12use crate::parser::{detect_language, grammar_for, FileParser};
13
14/// Convert 0-indexed line/col to a byte offset within `source`.
15///
16/// Tree-sitter columns are byte-indexed within the line, so `col` is a byte
17/// offset from the start of the line (not a character offset).
18///
19/// Returns `source.len()` if line is beyond the end of the file.
20pub fn line_col_to_byte(source: &str, line: u32, col: u32) -> usize {
21    let mut byte = 0;
22    for (i, l) in source.lines().enumerate() {
23        if i == line as usize {
24            return byte + (col as usize).min(l.len());
25        }
26        byte += l.len() + 1; // +1 for the newline character
27    }
28    // If we run out of lines, clamp to source length.
29    source.len()
30}
31
32/// Replace bytes in `[start..end)` with `replacement`.
33///
34/// Panics if `start > end` or indices are out of bounds for the source.
35pub fn replace_byte_range(source: &str, start: usize, end: usize, replacement: &str) -> String {
36    let mut result = String::with_capacity(source.len() - (end - start) + replacement.len());
37    result.push_str(&source[..start]);
38    result.push_str(replacement);
39    result.push_str(&source[end..]);
40    result
41}
42
43/// Validate syntax of a file using a fresh FileParser (D023).
44///
45/// Returns `Ok(Some(true))` if syntax is valid, `Ok(Some(false))` if there are
46/// parse errors, and `Ok(None)` if the language is unsupported.
47pub fn validate_syntax(path: &Path) -> Result<Option<bool>, AftError> {
48    let mut parser = FileParser::new();
49    match parser.parse(path) {
50        Ok((tree, _lang)) => Ok(Some(!tree.root_node().has_error())),
51        Err(AftError::InvalidRequest { .. }) => {
52            // Unsupported language — not an error, just can't validate
53            Ok(None)
54        }
55        Err(e) => Err(e),
56    }
57}
58
59/// Validate syntax of an in-memory string without touching disk.
60///
61/// Uses `detect_language(path)` + `grammar_for(lang)` + `parser.parse()`
62/// to validate syntax of a proposed content string. Returns `None` for
63/// unsupported languages, `Some(true)` for valid, `Some(false)` for invalid.
64pub fn validate_syntax_str(content: &str, path: &Path) -> Option<bool> {
65    let lang = detect_language(path)?;
66    let grammar = grammar_for(lang);
67    let mut parser = tree_sitter::Parser::new();
68    if parser.set_language(&grammar).is_err() {
69        return None;
70    }
71    let tree = parser.parse(content.as_bytes(), None)?;
72    Some(!tree.root_node().has_error())
73}
74
75/// Result of a dry-run diff computation.
76pub struct DryRunResult {
77    /// Unified diff between original and proposed content.
78    pub diff: String,
79    /// Whether the proposed content has valid syntax. `None` for unsupported languages.
80    pub syntax_valid: Option<bool>,
81}
82
83/// Compute a unified diff between original and proposed content, plus syntax validation.
84///
85/// Returns a standard unified diff with `a/` and `b/` path prefixes and 3 lines of context.
86/// Also validates syntax of the proposed content via tree-sitter.
87pub fn dry_run_diff(original: &str, proposed: &str, path: &Path) -> DryRunResult {
88    let display_path = path.display().to_string();
89    let text_diff = similar::TextDiff::from_lines(original, proposed);
90    let diff = text_diff
91        .unified_diff()
92        .context_radius(3)
93        .header(
94            &format!("a/{}", display_path),
95            &format!("b/{}", display_path),
96        )
97        .to_string();
98    let syntax_valid = validate_syntax_str(proposed, path);
99    DryRunResult { diff, syntax_valid }
100}
101
102/// Extract the `dry_run` boolean from request params.
103///
104/// Returns `true` if `params["dry_run"]` is `true`, `false` otherwise.
105pub fn is_dry_run(params: &serde_json::Value) -> bool {
106    params
107        .get("dry_run")
108        .and_then(|v| v.as_bool())
109        .unwrap_or(false)
110}
111
112/// Check if the caller requested diff info in the response.
113pub fn wants_diff(params: &serde_json::Value) -> bool {
114    params
115        .get("include_diff")
116        .and_then(|v| v.as_bool())
117        .unwrap_or(false)
118}
119
120/// Compute diff info between before/after content for UI metadata.
121/// Returns a JSON value with before, after, additions, deletions.
122/// For files >512KB, omits full content and returns only counts.
123pub fn compute_diff_info(before: &str, after: &str) -> serde_json::Value {
124    let before_lines: Vec<&str> = before.lines().collect();
125    let after_lines: Vec<&str> = after.lines().collect();
126
127    let max_len = before_lines.len().max(after_lines.len());
128    let mut additions = 0usize;
129    let mut deletions = 0usize;
130    for i in 0..max_len {
131        let bl = before_lines.get(i).copied().unwrap_or("");
132        let al = after_lines.get(i).copied().unwrap_or("");
133        if bl != al {
134            if i < before_lines.len() {
135                deletions += 1;
136            }
137            if i < after_lines.len() {
138                additions += 1;
139            }
140        }
141    }
142
143    // For large files, skip sending full content to avoid bloating JSON
144    let size_limit = 512 * 1024; // 512KB
145    if before.len() > size_limit || after.len() > size_limit {
146        serde_json::json!({
147            "additions": additions,
148            "deletions": deletions,
149            "truncated": true,
150        })
151    } else {
152        serde_json::json!({
153            "before": before,
154            "after": after,
155            "additions": additions,
156            "deletions": deletions,
157        })
158    }
159}
160
161/// Snapshot the file into the backup store before mutation.
162///
163/// Returns `Ok(Some(backup_id))` if the file existed and was backed up,
164/// `Ok(None)` if the file doesn't exist (new file creation).
165///
166/// Drops the RefCell borrow before returning (D029).
167pub fn auto_backup(
168    ctx: &AppContext,
169    path: &Path,
170    description: &str,
171) -> Result<Option<String>, AftError> {
172    if !path.exists() {
173        return Ok(None);
174    }
175    let backup_id = {
176        let mut store = ctx.backup().borrow_mut();
177        store.snapshot(path, description)?
178    }; // borrow dropped here
179    Ok(Some(backup_id))
180}
181
182/// Result of the write → format → validate pipeline.
183///
184/// Returned by `write_format_validate` to give callers a single struct
185/// with all post-write signals for the response JSON.
186pub struct WriteResult {
187    /// Whether tree-sitter syntax validation passed. `None` if unsupported language.
188    pub syntax_valid: Option<bool>,
189    /// Whether the file was auto-formatted.
190    pub formatted: bool,
191    /// Why formatting was skipped, if it was. Values: "not_found", "timeout", "error", "unsupported_language".
192    pub format_skipped_reason: Option<String>,
193    /// Whether full validation was requested (controls whether validation_errors is included in response).
194    pub validate_requested: bool,
195    /// Structured type-checker errors (only populated when validate:"full" is requested).
196    pub validation_errors: Vec<format::ValidationError>,
197    /// Why validation was skipped, if it was. Values: "not_found", "timeout", "error", "unsupported_language".
198    pub validate_skipped_reason: Option<String>,
199    /// LSP diagnostics for the edited file. Only populated when `diagnostics: true` is
200    /// passed in the edit request AND a language server is available.
201    pub lsp_diagnostics: Vec<crate::lsp::diagnostics::StoredDiagnostic>,
202}
203
204impl WriteResult {
205    /// Append LSP diagnostics to a response JSON object.
206    /// Only adds the field when diagnostics were requested and collected.
207    pub fn append_lsp_diagnostics_to(&self, result: &mut serde_json::Value) {
208        if !self.lsp_diagnostics.is_empty() {
209            result["lsp_diagnostics"] = serde_json::json!(self
210                .lsp_diagnostics
211                .iter()
212                .map(|d| {
213                    serde_json::json!({
214                        "file": d.file.display().to_string(),
215                        "line": d.line,
216                        "column": d.column,
217                        "end_line": d.end_line,
218                        "end_column": d.end_column,
219                        "severity": d.severity.as_str(),
220                        "message": d.message,
221                        "code": d.code,
222                        "source": d.source,
223                    })
224                })
225                .collect::<Vec<_>>());
226        }
227    }
228}
229
230/// Write content to disk, auto-format, then validate syntax.
231///
232/// This is the shared tail for all mutation commands. The pipeline order is:
233/// 1. `fs::write` — persist content
234/// 2. `auto_format` — run the project formatter (reads the written file, writes back)
235/// 3. `validate_syntax` — parse the (potentially formatted) file
236/// 4. `validate_full` — run type checker if `params.validate == "full"`
237///
238/// The `params` argument carries the original request parameters. When it
239/// contains `"validate": "full"`, the project's type checker is invoked after
240/// syntax validation and the results are included in `WriteResult`.
241pub fn write_format_validate(
242    path: &Path,
243    content: &str,
244    config: &Config,
245    params: &serde_json::Value,
246) -> Result<WriteResult, AftError> {
247    // Step 1: Write
248    std::fs::write(path, content).map_err(|e| AftError::InvalidRequest {
249        message: format!("failed to write file: {}", e),
250    })?;
251
252    // Step 2: Format (before validate so we validate the formatted content)
253    let (formatted, format_skipped_reason) = format::auto_format(path, config);
254
255    // Step 3: Validate syntax
256    let syntax_valid = match validate_syntax(path) {
257        Ok(sv) => sv,
258        Err(_) => None,
259    };
260
261    // Step 4: Full validation (type checker) — only when requested
262    let validate_requested = params.get("validate").and_then(|v| v.as_str()) == Some("full");
263    let (validation_errors, validate_skipped_reason) = if validate_requested {
264        format::validate_full(path, config)
265    } else {
266        (Vec::new(), None)
267    };
268
269    Ok(WriteResult {
270        syntax_valid,
271        formatted,
272        format_skipped_reason,
273        validate_requested,
274        validation_errors,
275        validate_skipped_reason,
276        lsp_diagnostics: Vec::new(),
277    })
278}
279
280#[cfg(test)]
281mod tests {
282    use super::*;
283
284    // --- line_col_to_byte ---
285
286    #[test]
287    fn line_col_to_byte_empty_string() {
288        assert_eq!(line_col_to_byte("", 0, 0), 0);
289    }
290
291    #[test]
292    fn line_col_to_byte_single_line() {
293        let source = "hello";
294        assert_eq!(line_col_to_byte(source, 0, 0), 0);
295        assert_eq!(line_col_to_byte(source, 0, 3), 3);
296        assert_eq!(line_col_to_byte(source, 0, 5), 5); // end of line
297    }
298
299    #[test]
300    fn line_col_to_byte_multi_line() {
301        let source = "abc\ndef\nghi\n";
302        // line 0: "abc" at bytes 0..3, newline at 3
303        assert_eq!(line_col_to_byte(source, 0, 0), 0);
304        assert_eq!(line_col_to_byte(source, 0, 2), 2);
305        // line 1: "def" at bytes 4..7, newline at 7
306        assert_eq!(line_col_to_byte(source, 1, 0), 4);
307        assert_eq!(line_col_to_byte(source, 1, 3), 7);
308        // line 2: "ghi" at bytes 8..11, newline at 11
309        assert_eq!(line_col_to_byte(source, 2, 0), 8);
310        assert_eq!(line_col_to_byte(source, 2, 2), 10);
311    }
312
313    #[test]
314    fn line_col_to_byte_last_line_no_trailing_newline() {
315        let source = "abc\ndef";
316        // line 1: "def" at bytes 4..7, no trailing newline
317        assert_eq!(line_col_to_byte(source, 1, 0), 4);
318        assert_eq!(line_col_to_byte(source, 1, 3), 7); // end
319    }
320
321    #[test]
322    fn line_col_to_byte_multi_byte_utf8() {
323        // "é" is 2 bytes in UTF-8
324        let source = "café\nbar";
325        // line 0: "café" is 5 bytes (c=1, a=1, f=1, é=2)
326        assert_eq!(line_col_to_byte(source, 0, 0), 0);
327        assert_eq!(line_col_to_byte(source, 0, 5), 5); // end of "café"
328                                                       // line 1: "bar" starts at byte 6
329        assert_eq!(line_col_to_byte(source, 1, 0), 6);
330        assert_eq!(line_col_to_byte(source, 1, 2), 8);
331    }
332
333    #[test]
334    fn line_col_to_byte_beyond_end() {
335        let source = "abc";
336        // Line beyond file returns source.len()
337        assert_eq!(line_col_to_byte(source, 5, 0), source.len());
338    }
339
340    #[test]
341    fn line_col_to_byte_col_clamped_to_line_length() {
342        let source = "ab\ncd";
343        // col=10 on a 2-char line should clamp to 2
344        assert_eq!(line_col_to_byte(source, 0, 10), 2);
345    }
346
347    // --- replace_byte_range ---
348
349    #[test]
350    fn replace_byte_range_basic() {
351        let source = "hello world";
352        let result = replace_byte_range(source, 6, 11, "rust");
353        assert_eq!(result, "hello rust");
354    }
355
356    #[test]
357    fn replace_byte_range_delete() {
358        let source = "hello world";
359        let result = replace_byte_range(source, 5, 11, "");
360        assert_eq!(result, "hello");
361    }
362
363    #[test]
364    fn replace_byte_range_insert_at_same_position() {
365        let source = "helloworld";
366        let result = replace_byte_range(source, 5, 5, " ");
367        assert_eq!(result, "hello world");
368    }
369
370    #[test]
371    fn replace_byte_range_replace_entire_string() {
372        let source = "old content";
373        let result = replace_byte_range(source, 0, source.len(), "new content");
374        assert_eq!(result, "new content");
375    }
376}