patchloom 0.37.2

Structured file editing library and CLI for AI agents: parser-backed JSON/YAML/TOML edits, AST-aware code operations, multi-file batching, markdown operations, and MCP server
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
//! Symbol-scoped replacement: replace text only within a specific symbol's body.

use std::path::Path;

use super::Language;
use super::insert::indent_content;
use super::symbols::{
    SymbolDef, extract_symbols_or_timeout, find_symbol, full_symbol_span, try_extract_symbols,
};

/// Result of a symbol-scoped replacement.
#[derive(Debug)]
pub struct ScopedReplaceResult {
    /// The full file content after replacement.
    pub content: String,
    /// Number of replacements made within the symbol.
    pub replacements: usize,
    /// 1-based start line of the symbol.
    pub start_line: usize,
    /// 1-based end line of the symbol.
    pub end_line: usize,
}

/// Replace text only within the body of a specific symbol.
pub fn replace_in_symbol(
    source: &str,
    symbol_name: &str,
    from: &str,
    to: &str,
    regex: bool,
    lang: Language,
) -> anyhow::Result<Option<ScopedReplaceResult>> {
    if from.is_empty() {
        return Err(anyhow::Error::new(crate::exit::InvalidInputError {
            msg: "ast replace pattern must not be empty".into(),
        }));
    }
    let symbols = match try_extract_symbols(source, lang) {
        Ok(s) => s,
        Err(crate::ast::ParseFailure::DeadlineExceeded) => {
            return Err(crate::exit::ParseTimeoutError {
                msg: format!("parse deadline exceeded for {lang}"),
            }
            .into());
        }
        Err(crate::ast::ParseFailure::NoGrammar) => return Ok(None),
    };
    replace_in_symbol_from_symbols(source, &symbols, symbol_name, from, to, regex, lang)
}

/// Like [`replace_in_symbol`] using a pre-extracted symbol list (tx tree cache).
pub(crate) fn replace_in_symbol_from_symbols(
    source: &str,
    symbols: &[SymbolDef],
    symbol_name: &str,
    from: &str,
    to: &str,
    regex: bool,
    _lang: Language,
) -> anyhow::Result<Option<ScopedReplaceResult>> {
    if from.is_empty() {
        return Err(anyhow::Error::new(crate::exit::InvalidInputError {
            msg: "ast replace pattern must not be empty".into(),
        }));
    }
    let sym = match find_symbol(symbols, symbol_name) {
        Some(s) => s,
        None => return Ok(None),
    };

    // Use canonical majority-vote detection, consistent with all other AST modules.
    let eol = crate::write::detect_eol(source);
    let lines: Vec<&str> = crate::ops::file::text_lines(source).collect();
    let start_idx = sym.start_line.saturating_sub(1);
    let end_idx = sym.end_line.min(lines.len());

    let body: String = lines[start_idx..end_idx]
        .iter()
        .map(|l| format!("{l}{eol}"))
        .collect();

    // Perform replacement within the body
    let (new_body, count) = if regex {
        let re = crate::bounded_regex_build(crate::bounded_regex_builder(from).multi_line(true))?;
        let body_len = body.len();
        // Filter out phantom zero-length matches at EOF (same as replace_content).
        let count = re
            .find_iter(&body)
            .filter(|m| !(m.start() == body_len && m.end() == body_len))
            .count();
        let new = re
            .replace_all(&body, |caps: &regex::Captures| {
                if let Some(m) = caps.get(0)
                    && m.start() == body_len
                    && m.end() == body_len
                {
                    return String::new();
                }
                let mut expanded = String::new();
                caps.expand(to, &mut expanded);
                expanded
            })
            .into_owned();
        (new, count)
    } else {
        let count = body.matches(from).count();
        let new = body.replace(from, to);
        (new, count)
    };

    if count == 0 {
        return Ok(Some(ScopedReplaceResult {
            content: source.to_string(),
            replacements: 0,
            start_line: sym.start_line,
            end_line: sym.end_line,
        }));
    }

    // Reconstruct the full file: prefix + new body + suffix
    let mut result = String::new();
    for line in &lines[..start_idx] {
        result.push_str(line);
        result.push_str(eol);
    }
    result.push_str(&new_body);
    // new_body already has trailing line endings; add suffix
    for line in &lines[end_idx..] {
        result.push_str(line);
        result.push_str(eol);
    }

    // Preserve original trailing newline behavior
    let ends_with_eol = source.ends_with('\n') || source.ends_with('\r');
    if !ends_with_eol && result.ends_with(eol) {
        result.truncate(result.len() - eol.len());
    }

    Ok(Some(ScopedReplaceResult {
        content: result,
        replacements: count,
        start_line: sym.start_line,
        end_line: sym.end_line,
    }))
}

/// Replace text within a symbol in a file.
pub fn replace_in_symbol_file(
    path: &Path,
    symbol_name: &str,
    from: &str,
    to: &str,
    regex: bool,
    lang_hint: Option<Language>,
) -> anyhow::Result<Option<ScopedReplaceResult>> {
    let lang = lang_hint.unwrap_or_else(|| Language::from_path(path));
    if !lang.has_grammar() {
        return Ok(None);
    }
    // Strict sole-path (#1894): binary / invalid UTF-8 → Binary / InvalidEncoding.
    let source = crate::files::load_text_strict(path, &path.display().to_string())?;
    replace_in_symbol(&source, symbol_name, from, to, regex, lang)
}

fn reject_empty_symbol_name(symbol_name: &str, op: &str) -> anyhow::Result<()> {
    if symbol_name.trim().is_empty() {
        return Err(anyhow::Error::new(crate::exit::InvalidInputError {
            msg: format!("{op} symbol must not be empty"),
        }));
    }
    Ok(())
}

struct ResolvedSymbolSpan<'a> {
    lines: Vec<&'a str>,
    start_0: usize,
    end_0: usize,
    indent: String,
    eol: &'a str,
}

fn resolve_symbol_span<'a>(
    source: &'a str,
    symbol_name: &str,
    lang: Language,
    op: &str,
) -> anyhow::Result<ResolvedSymbolSpan<'a>> {
    reject_empty_symbol_name(symbol_name, op)?;
    let symbols = extract_symbols_or_timeout(source, lang)?;
    resolve_symbol_span_from(source, &symbols, symbol_name, lang, op)
}

fn resolve_symbol_span_from<'a>(
    source: &'a str,
    symbols: &[SymbolDef],
    symbol_name: &str,
    lang: Language,
    op: &str,
) -> anyhow::Result<ResolvedSymbolSpan<'a>> {
    reject_empty_symbol_name(symbol_name, op)?;
    let sym = find_symbol(symbols, symbol_name).ok_or_else(|| {
        anyhow::Error::new(crate::exit::NoMatchError {
            msg: format!("symbol '{symbol_name}' not found"),
        })
    })?;
    let (full_start, full_end) = full_symbol_span(source, sym, lang);
    let lines: Vec<&str> = crate::ops::file::text_lines(source).collect();
    let start_0 = full_start.saturating_sub(1);
    let end_0 = full_end.min(lines.len());
    let indent = symbol_column_indent(&lines, sym.start_line.saturating_sub(1));
    Ok(ResolvedSymbolSpan {
        lines,
        start_0,
        end_0,
        indent,
        eol: crate::write::detect_eol(source),
    })
}

fn symbol_column_indent(lines: &[&str], start_idx: usize) -> String {
    if start_idx < lines.len() {
        let line = lines[start_idx];
        let trimmed = line.trim_start();
        line[..line.len() - trimmed.len()].to_string()
    } else {
        String::new()
    }
}

fn join_source_lines(lines: &[String], eol: &str, source: &str) -> String {
    let mut out = lines.join(eol);
    if (source.ends_with('\n') || source.ends_with('\r')) && !out.ends_with(eol) {
        out.push_str(eol);
    }
    out
}

/// After removing a span at `hole`, keep at most one surrounding blank line.
fn collapse_surrounding_blanks(lines: &mut Vec<String>, hole: usize) {
    let mut before = 0usize;
    while hole > before && lines[hole - 1 - before].trim().is_empty() {
        before += 1;
    }
    let mut after = 0usize;
    while hole + after < lines.len() && lines[hole + after].trim().is_empty() {
        after += 1;
    }
    let total = before.saturating_add(after);
    if total > 1 {
        let blank_start = hole - before;
        lines.drain(blank_start + 1..blank_start + total);
    }
}

/// Replace a whole symbol span, including leading docs and attributes.
///
/// `content` is re-indented to the symbol's column. A missing symbol is
/// [`crate::exit::NoMatchError`].
pub fn replace_symbol(
    source: &str,
    symbol_name: &str,
    content: &str,
    lang: Language,
) -> anyhow::Result<String> {
    let span = resolve_symbol_span(source, symbol_name, lang, "ast.replace_symbol")?;
    replace_symbol_span(source, span, content)
}

/// Like [`replace_symbol`] using a pre-extracted symbol list (tx tree cache).
pub(crate) fn replace_symbol_from_symbols(
    source: &str,
    symbols: &[SymbolDef],
    symbol_name: &str,
    content: &str,
    lang: Language,
) -> anyhow::Result<String> {
    let span = resolve_symbol_span_from(source, symbols, symbol_name, lang, "ast.replace_symbol")?;
    replace_symbol_span(source, span, content)
}

fn replace_symbol_span(
    source: &str,
    span: ResolvedSymbolSpan<'_>,
    content: &str,
) -> anyhow::Result<String> {
    let mut lines: Vec<String> = span.lines.iter().map(|l| (*l).to_string()).collect();
    lines.drain(span.start_0..span.end_0);
    if content.is_empty() {
        collapse_surrounding_blanks(&mut lines, span.start_0);
    } else {
        let adjusted = indent_content(content, &span.indent, span.eol);
        let new_lines: Vec<String> = crate::ops::file::text_lines(&adjusted)
            .map(str::to_string)
            .collect();
        for (i, line) in new_lines.into_iter().enumerate() {
            lines.insert(span.start_0 + i, line);
        }
    }
    Ok(join_source_lines(&lines, span.eol, source))
}

/// Delete a whole symbol span, including leading docs and attributes.
///
/// Surrounding blank lines collapse to at most one. A missing symbol is
/// [`crate::exit::NoMatchError`].
pub fn delete_symbol(source: &str, symbol_name: &str, lang: Language) -> anyhow::Result<String> {
    let span = resolve_symbol_span(source, symbol_name, lang, "ast.delete_symbol")?;
    delete_symbol_span(source, span)
}

/// Like [`delete_symbol`] using a pre-extracted symbol list (tx tree cache).
pub(crate) fn delete_symbol_from_symbols(
    source: &str,
    symbols: &[SymbolDef],
    symbol_name: &str,
    lang: Language,
) -> anyhow::Result<String> {
    let span = resolve_symbol_span_from(source, symbols, symbol_name, lang, "ast.delete_symbol")?;
    delete_symbol_span(source, span)
}

fn delete_symbol_span(source: &str, span: ResolvedSymbolSpan<'_>) -> anyhow::Result<String> {
    let mut lines: Vec<String> = span.lines.iter().map(|l| (*l).to_string()).collect();
    lines.drain(span.start_0..span.end_0);
    collapse_surrounding_blanks(&mut lines, span.start_0);
    Ok(join_source_lines(&lines, span.eol, source))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn replace_empty_pattern_is_invalid_input() {
        let err = replace_in_symbol(
            "fn foo() { let x = 1; }\n",
            "foo",
            "",
            "y",
            false,
            Language::Rust,
        )
        .expect_err("empty from must fail");
        assert!(
            crate::exit::is_invalid_input(&err),
            "empty from must be invalid_input, got {err}"
        );
        replace_in_symbol(
            "fn foo() { let x = 1; }\n",
            "foo",
            "x",
            "",
            false,
            Language::Rust,
        )
        .expect("empty to is a delete, not invalid_input")
        .expect("symbol exists");
    }

    #[test]
    fn replace_within_function() {
        let source = r#"fn foo() {
    let x = 1;
    let y = 1;
}

fn bar() {
    let x = 1;
}
"#;
        let result = replace_in_symbol(source, "foo", "1", "42", false, Language::Rust)
            .unwrap()
            .unwrap();
        assert_eq!(result.replacements, 2);
        // foo's body should have 42, bar's should still have 1
        assert!(result.content.contains("fn foo()"));
        assert!(result.content.contains("let x = 42"));
        let bar_section: &str = result.content.split("fn bar()").nth(1).unwrap();
        assert!(bar_section.contains("let x = 1"));
    }

    #[test]
    fn replace_with_regex() {
        let source = "fn run() {\n    exit::FAILURE\n    exit::NO_MATCHES\n}\n";
        let result = replace_in_symbol(
            source,
            "run",
            r"exit::\w+",
            "exit::SUCCESS",
            true,
            Language::Rust,
        )
        .unwrap()
        .unwrap();
        assert_eq!(result.replacements, 2);
        assert!(result.content.contains("exit::SUCCESS"));
        assert!(!result.content.contains("exit::FAILURE"));
    }

    #[test]
    fn symbol_not_found_returns_none() {
        let source = "fn foo() {}\n";
        let result =
            replace_in_symbol(source, "nonexistent", "x", "y", false, Language::Rust).unwrap();
        assert!(result.is_none());
    }

    #[test]
    fn replace_preserves_crlf_line_endings() {
        let source = "fn foo() {\r\n    let x = 1;\r\n    let y = 1;\r\n}\r\n\r\nfn bar() {\r\n    let x = 1;\r\n}\r\n";
        let result = replace_in_symbol(source, "foo", "1", "42", false, Language::Rust)
            .unwrap()
            .unwrap();
        assert_eq!(result.replacements, 2);
        // All CRLF line endings must be preserved
        assert!(result.content.contains("\r\n"), "CRLF should be preserved");
        assert!(!result.content.contains("\r\n\n"), "no mixed line endings");
        // Verify no bare LF where CRLF was expected
        let without_cr = result.content.replace("\r\n", "");
        assert!(!without_cr.contains('\n'), "no bare LF in CRLF content");
    }

    #[test]
    fn replace_in_symbol_cr_only_second_fn() {
        let source = "fn one() { let x = 1; }\rfn two() { let y = 2; }\r";
        let result = replace_in_symbol(
            source,
            "two",
            "let y = 2;",
            "let y = 3;",
            false,
            Language::Rust,
        )
        .unwrap()
        .unwrap();
        assert_eq!(result.replacements, 1);
        assert!(
            result.content.contains("let y = 3;"),
            "content={}",
            result.content
        );
        assert!(result.content.contains("let x = 1;"));
        assert!(!result.content.contains("let y = 2;"));
    }

    /// Regression: a majority-LF file with one stray CRLF must stay LF,
    /// not be converted to all-CRLF by the inline `contains("\r\n")` check.
    #[test]
    fn replace_majority_lf_with_stray_crlf_preserves_lf() {
        // 3 LF lines + 1 CRLF line: majority is LF.
        let source = "fn foo() {\n    let x = 1;\r\n    let y = 2;\n}\n";
        let result = replace_in_symbol(source, "foo", "1", "42", false, Language::Rust)
            .unwrap()
            .unwrap();
        assert_eq!(result.replacements, 1);
        // The output should use LF (majority vote), not CRLF.
        let lines: Vec<&str> = result.content.split('\n').collect();
        let crlf_count = result.content.matches("\r\n").count();
        let lf_count = lines.len().saturating_sub(1).saturating_sub(crlf_count);
        assert!(
            lf_count > crlf_count,
            "majority-LF file should stay LF after replace, got {crlf_count} CRLF vs {lf_count} LF"
        );
    }

    #[test]
    fn no_match_returns_zero_replacements() {
        let source = "fn foo() {\n    let x = 1;\n}\n";
        let result = replace_in_symbol(source, "foo", "zzz", "yyy", false, Language::Rust)
            .unwrap()
            .unwrap();
        assert_eq!(result.replacements, 0);
    }

    #[test]
    fn replace_symbol_rewrites_function_span() {
        let source = "fn keep() {}\n\nfn victim() {\n    let x = 1;\n}\n\nfn other() {}\n";
        let out = replace_symbol(
            source,
            "victim",
            "fn victim() {\n    let x = 2;\n}",
            Language::Rust,
        )
        .unwrap();
        assert!(out.contains("fn victim() {\n    let x = 2;\n}"));
        assert!(!out.contains("let x = 1"));
        assert!(out.contains("fn keep() {}"));
        assert!(out.contains("fn other() {}"));
    }

    #[test]
    fn replace_symbol_includes_leading_docs_and_attrs() {
        let source = "/// old docs\n#[allow(dead_code)]\nfn victim() {}\n\nfn keep() {}\n";
        let out = replace_symbol(source, "victim", "fn victim() { 1 }", Language::Rust).unwrap();
        assert!(
            !out.contains("old docs") && !out.contains("allow(dead_code)"),
            "full span must include docs/attrs: {out}"
        );
        assert!(out.contains("fn victim() { 1 }"));
        assert!(out.contains("fn keep() {}"));
    }

    #[test]
    fn replace_symbol_reindents_to_symbol_column() {
        let source = "impl Foo {\n    fn victim() {\n        let x = 1;\n    }\n}\n";
        let out = replace_symbol(
            source,
            "victim",
            "fn victim() {\n    let x = 2;\n}",
            Language::Rust,
        )
        .unwrap();
        assert!(
            out.contains("    fn victim() {\n        let x = 2;\n    }"),
            "replacement must match impl column: {out}"
        );
    }

    #[test]
    fn delete_symbol_removes_function_and_collapses_blanks() {
        let source = "fn keep() {}\n\nfn victim() {\n    let x = 1;\n}\n\nfn other() {}\n";
        let out = delete_symbol(source, "victim", Language::Rust).unwrap();
        assert!(!out.contains("fn victim"));
        assert!(!out.contains("let x = 1"));
        assert!(out.contains("fn keep() {}"));
        assert!(out.contains("fn other() {}"));
        assert!(
            !out.contains("\n\n\n"),
            "surrounding blanks must collapse to one: {out:?}"
        );
        assert!(out.contains("fn keep() {}\n\nfn other() {}"));
    }

    #[test]
    fn missing_symbol_is_no_matches() {
        let source = "fn foo() {}\n";
        let err = replace_symbol(source, "missing", "fn missing() {}", Language::Rust).unwrap_err();
        assert!(
            crate::exit::is_no_match(&err),
            "replace missing symbol must be no_matches, got {err}"
        );
        let err = delete_symbol(source, "missing", Language::Rust).unwrap_err();
        assert!(
            crate::exit::is_no_match(&err),
            "delete missing symbol must be no_matches, got {err}"
        );
    }

    #[test]
    fn empty_symbol_name_is_invalid_input() {
        let source = "fn foo() {}\n";
        let err = replace_symbol(source, "  ", "fn x() {}", Language::Rust).unwrap_err();
        assert!(
            crate::exit::is_invalid_input(&err),
            "empty replace symbol must be invalid_input, got {err}"
        );
        let err = delete_symbol(source, "", Language::Rust).unwrap_err();
        assert!(
            crate::exit::is_invalid_input(&err),
            "empty delete symbol must be invalid_input, got {err}"
        );
    }
}