patchloom 0.8.0

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
//! AST-aware symbol reordering within a file or scope.

use std::collections::HashMap;

use super::Language;
use super::symbols::{SymbolDef, SymbolKind, extract_symbols, find_symbol, full_symbol_span};

/// Strategy for reordering symbols.
#[derive(Debug, Clone)]
pub enum ReorderStrategy {
    /// Sort symbols alphabetically by name.
    Alphabetical,
    /// Sort symbols in reverse alphabetical order.
    Reverse,
    /// Types (structs, enums, traits, interfaces) first, then functions.
    KindFirst,
    /// Explicit ordering: symbols appear in the given order.
    Custom(Vec<String>),
}

/// Result of a reorder operation.
#[derive(Debug)]
pub struct ReorderResult {
    /// The full file content after reordering.
    pub content: String,
    /// Number of symbols that changed position.
    pub symbols_reordered: usize,
}

/// Reorder symbols within a file or a specific scope (module, impl block).
///
/// When `inside` is `Some`, only symbols inside that container are reordered;
/// the container itself and everything outside it remain in place.
pub fn reorder_symbols(
    source: &str,
    inside: Option<&str>,
    strategy: &ReorderStrategy,
    lang: Language,
) -> anyhow::Result<ReorderResult> {
    let eol = crate::write::detect_eol(source);
    let all_symbols = extract_symbols(source, lang);
    let lines: Vec<&str> = source.lines().collect();

    let (scope_symbols, scope_start_0, scope_end_0) = if let Some(container) = inside {
        let parent = find_symbol(&all_symbols, container)
            .ok_or_else(|| anyhow::anyhow!("symbol '{}' not found", container))?;
        // Find the opening brace line of the container
        let open_line_0 = find_opening_line(&lines, parent.start_line.saturating_sub(1));
        let close_line_0 = parent.end_line.min(lines.len()).saturating_sub(1);
        (&parent.children, open_line_0 + 1, close_line_0)
    } else {
        (&all_symbols as &Vec<SymbolDef>, 0usize, lines.len())
    };

    if scope_symbols.is_empty() {
        return Ok(ReorderResult {
            content: source.to_string(),
            symbols_reordered: 0,
        });
    }

    // Build spans for each symbol, including attrs/docs
    let mut spans: Vec<SymbolSpan> = scope_symbols
        .iter()
        .map(|sym| {
            let (full_start, full_end) = full_symbol_span(source, sym, lang);
            SymbolSpan {
                name: sym.name.clone(),
                kind: sym.kind,
                start_0: full_start.saturating_sub(1),
                end_0: full_end.min(lines.len()),
            }
        })
        .collect();

    // Sort according to strategy
    let original_order: Vec<String> = spans.iter().map(|s| s.name.clone()).collect();
    sort_spans(&mut spans, strategy)?;
    let new_order: Vec<String> = spans.iter().map(|s| s.name.clone()).collect();

    // Count how many changed position
    let symbols_reordered = original_order
        .iter()
        .zip(new_order.iter())
        .filter(|(a, b)| a != b)
        .count();

    if symbols_reordered == 0 {
        return Ok(ReorderResult {
            content: source.to_string(),
            symbols_reordered: 0,
        });
    }

    // Rebuild the scope section with symbols in the new order.
    // Collect the text of each symbol, including any inter-symbol content
    // (comments, blank lines) that follows it but precedes the next symbol.
    // This ensures inter-symbol content moves with its preceding symbol (#1111.2).

    // Build original-order spans sorted by position for gap detection
    let mut positional_spans: Vec<(usize, usize, &str)> = spans
        .iter()
        .map(|s| (s.start_0, s.end_0, s.name.as_str()))
        .collect();
    positional_spans.sort_by_key(|s| s.0);

    // Map each symbol name to its text (symbol + trailing inter-symbol gap)
    let mut sym_text_map: HashMap<&str, String> = HashMap::new();
    for (idx, &(start, _end, name)) in positional_spans.iter().enumerate() {
        // Include lines from this symbol's start up to (but not including)
        // the next symbol's start. The last symbol keeps only its own lines.
        let effective_end = positional_spans.get(idx + 1).map(|s| s.0).unwrap_or(_end);
        let text: String = lines[start..effective_end].join(eol);
        sym_text_map.insert(name, text);
    }

    let mut sym_texts: Vec<(&str, String)> = Vec::new();
    for span in &spans {
        let text = sym_text_map.remove(span.name.as_str()).unwrap_or_default();
        sym_texts.push((&span.name, text));
    }

    // Find the positional boundaries of all symbols (by line index).
    let first_sym_start = spans
        .iter()
        .map(|s| s.start_0)
        .min()
        .unwrap_or(scope_start_0)
        .max(scope_start_0);
    let last_sym_end = spans
        .iter()
        .map(|s| s.end_0)
        .max()
        .unwrap_or(scope_end_0)
        .min(scope_end_0);

    // Now rebuild: before-scope + scope-prefix + reordered symbols + scope-suffix + after-scope
    let mut result = String::new();

    // Lines before the scope (container preamble when using `inside`)
    for line in &lines[..scope_start_0] {
        result.push_str(line);
        result.push_str(eol);
    }

    // Scope prefix: non-symbol lines inside the scope before the first symbol
    // (use statements, module-level comments, extern crate, etc.)
    for line in &lines[scope_start_0..first_sym_start] {
        result.push_str(line);
        result.push_str(eol);
    }

    // Emit symbols in new order with blank line separators
    for (i, (_name, text)) in sym_texts.iter().enumerate() {
        if i > 0 {
            result.push_str(eol);
        }
        result.push_str(text);
        result.push_str(eol);
    }

    // Scope suffix: non-symbol lines inside the scope after the last symbol
    for line in &lines[last_sym_end..scope_end_0] {
        result.push_str(line);
        result.push_str(eol);
    }

    // Lines after the scope (closing brace, trailing content)
    for line in &lines[scope_end_0..] {
        result.push_str(line);
        result.push_str(eol);
    }

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

    Ok(ReorderResult {
        content: result,
        symbols_reordered,
    })
}

#[derive(Debug, Clone)]
struct SymbolSpan {
    name: String,
    kind: SymbolKind,
    start_0: usize, // 0-based line index
    end_0: usize,   // 0-based exclusive end
}

fn sort_spans(spans: &mut [SymbolSpan], strategy: &ReorderStrategy) -> anyhow::Result<()> {
    match strategy {
        ReorderStrategy::Alphabetical => {
            spans.sort_by_key(|a| a.name.to_lowercase());
        }
        ReorderStrategy::Reverse => {
            spans.sort_by_key(|b| std::cmp::Reverse(b.name.to_lowercase()));
        }
        ReorderStrategy::KindFirst => {
            spans.sort_by(|a, b| {
                let ka = kind_priority(a.kind);
                let kb = kind_priority(b.kind);
                ka.cmp(&kb)
                    .then_with(|| a.name.to_lowercase().cmp(&b.name.to_lowercase()))
            });
        }
        ReorderStrategy::Custom(order) => {
            spans.sort_by(|a, b| {
                let ia = order
                    .iter()
                    .position(|n| *n == a.name)
                    .unwrap_or(usize::MAX);
                let ib = order
                    .iter()
                    .position(|n| *n == b.name)
                    .unwrap_or(usize::MAX);
                ia.cmp(&ib)
            });
        }
    }
    Ok(())
}

/// Priority for kind-first ordering: types before functions.
fn kind_priority(kind: SymbolKind) -> u8 {
    match kind {
        SymbolKind::Struct => 0,
        SymbolKind::Enum => 1,
        SymbolKind::Trait | SymbolKind::Interface => 2,
        SymbolKind::Type => 3,
        SymbolKind::Const => 4,
        SymbolKind::Class => 5,
        SymbolKind::Impl => 6,
        SymbolKind::Module => 7,
        SymbolKind::Function => 8,
        SymbolKind::Method => 9,
    }
}

/// Find the line with the opening brace of a container (0-based index).
fn find_opening_line(lines: &[&str], start_0: usize) -> usize {
    for (i, line) in lines.iter().enumerate().skip(start_0) {
        let trimmed = line.trim();
        if trimmed.ends_with('{') || trimmed.ends_with(':') || trimmed.ends_with(":{") {
            return i;
        }
    }
    start_0
}

/// Parse a reorder strategy from a `serde_json::Value`.
///
/// - String `"alphabetical"`, `"reverse"`, `"kind-first"` -> named strategy
/// - Array of strings -> `Custom` order
pub fn parse_strategy(value: &serde_json::Value) -> anyhow::Result<ReorderStrategy> {
    match value {
        serde_json::Value::String(s) => match s.as_str() {
            "alphabetical" => Ok(ReorderStrategy::Alphabetical),
            "reverse" => Ok(ReorderStrategy::Reverse),
            "kind-first" | "kind_first" => Ok(ReorderStrategy::KindFirst),
            other => anyhow::bail!("unknown reorder strategy: '{other}'"),
        },
        serde_json::Value::Array(arr) => {
            let names: Result<Vec<String>, _> = arr
                .iter()
                .map(|v| {
                    v.as_str()
                        .map(String::from)
                        .ok_or_else(|| anyhow::anyhow!("custom order items must be strings"))
                })
                .collect();
            Ok(ReorderStrategy::Custom(names?))
        }
        _ => anyhow::bail!("'order' must be a string or array of strings"),
    }
}

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

    #[test]
    fn reorder_alphabetical() {
        let source = "fn charlie() {}\n\nfn alpha() {}\n\nfn bravo() {}\n";
        let result =
            reorder_symbols(source, None, &ReorderStrategy::Alphabetical, Language::Rust).unwrap();
        let alpha_pos = result.content.find("fn alpha").unwrap();
        let bravo_pos = result.content.find("fn bravo").unwrap();
        let charlie_pos = result.content.find("fn charlie").unwrap();
        assert!(alpha_pos < bravo_pos);
        assert!(bravo_pos < charlie_pos);
        assert_eq!(result.symbols_reordered, 3);
    }

    #[test]
    fn reorder_reverse() {
        let source = "fn alpha() {}\n\nfn bravo() {}\n\nfn charlie() {}\n";
        let result =
            reorder_symbols(source, None, &ReorderStrategy::Reverse, Language::Rust).unwrap();
        let alpha_pos = result.content.find("fn alpha").unwrap();
        let bravo_pos = result.content.find("fn bravo").unwrap();
        let charlie_pos = result.content.find("fn charlie").unwrap();
        assert!(charlie_pos < bravo_pos);
        assert!(bravo_pos < alpha_pos);
    }

    #[test]
    fn reorder_kind_first() {
        let source =
            "fn do_stuff() {}\n\nstruct Config {\n    x: i32,\n}\n\nenum Mode {\n    A,\n}\n";
        let result =
            reorder_symbols(source, None, &ReorderStrategy::KindFirst, Language::Rust).unwrap();
        let struct_pos = result.content.find("struct Config").unwrap();
        let enum_pos = result.content.find("enum Mode").unwrap();
        let fn_pos = result.content.find("fn do_stuff").unwrap();
        assert!(struct_pos < enum_pos);
        assert!(enum_pos < fn_pos);
    }

    #[test]
    fn reorder_custom() {
        let source = "fn charlie() {}\n\nfn alpha() {}\n\nfn bravo() {}\n";
        let order = vec!["bravo".into(), "charlie".into(), "alpha".into()];
        let result = reorder_symbols(
            source,
            None,
            &ReorderStrategy::Custom(order),
            Language::Rust,
        )
        .unwrap();
        let alpha_pos = result.content.find("fn alpha").unwrap();
        let bravo_pos = result.content.find("fn bravo").unwrap();
        let charlie_pos = result.content.find("fn charlie").unwrap();
        assert!(bravo_pos < charlie_pos);
        assert!(charlie_pos < alpha_pos);
    }

    #[test]
    fn reorder_inside_module() {
        let source = "fn outside() {}\n\nmod tests {\n    fn zebra() {}\n    fn apple() {}\n}\n";
        let result = reorder_symbols(
            source,
            Some("tests"),
            &ReorderStrategy::Alphabetical,
            Language::Rust,
        )
        .unwrap();
        assert!(result.content.contains("fn outside()")); // unchanged
        let apple_pos = result.content.find("fn apple").unwrap();
        let zebra_pos = result.content.find("fn zebra").unwrap();
        assert!(apple_pos < zebra_pos);
    }

    #[test]
    fn reorder_no_op_when_already_sorted() {
        let source = "fn alpha() {}\n\nfn bravo() {}\n\nfn charlie() {}\n";
        let result =
            reorder_symbols(source, None, &ReorderStrategy::Alphabetical, Language::Rust).unwrap();
        assert_eq!(result.symbols_reordered, 0);
        assert_eq!(result.content, source);
    }

    #[test]
    fn reorder_preserves_attributes() {
        let source = "#[test]\nfn zebra() {}\n\n/// Doc for alpha.\n#[cfg(test)]\nfn alpha() {}\n";
        let result =
            reorder_symbols(source, None, &ReorderStrategy::Alphabetical, Language::Rust).unwrap();
        // alpha (with its doc + cfg) should come first
        let alpha_pos = result.content.find("fn alpha").unwrap();
        let zebra_pos = result.content.find("fn zebra").unwrap();
        assert!(alpha_pos < zebra_pos);
        // attributes should still be present
        assert!(result.content.contains("/// Doc for alpha."));
        assert!(result.content.contains("#[cfg(test)]"));
        assert!(result.content.contains("#[test]"));
    }

    #[test]
    fn reorder_symbol_not_found_inside() {
        let source = "fn foo() {}\n";
        let result = reorder_symbols(
            source,
            Some("nonexistent"),
            &ReorderStrategy::Alphabetical,
            Language::Rust,
        );
        assert!(result.is_err());
    }

    #[test]
    fn parse_strategy_string() {
        let v = serde_json::json!("alphabetical");
        assert!(matches!(
            parse_strategy(&v).unwrap(),
            ReorderStrategy::Alphabetical
        ));
        let v = serde_json::json!("reverse");
        assert!(matches!(
            parse_strategy(&v).unwrap(),
            ReorderStrategy::Reverse
        ));
        let v = serde_json::json!("kind-first");
        assert!(matches!(
            parse_strategy(&v).unwrap(),
            ReorderStrategy::KindFirst
        ));
    }

    #[test]
    fn parse_strategy_array() {
        let v = serde_json::json!(["b", "a", "c"]);
        let strategy = parse_strategy(&v).unwrap();
        assert!(
            matches!(strategy, ReorderStrategy::Custom(ref names) if names == &["b", "a", "c"])
        );
    }

    #[test]
    fn parse_strategy_kind_first_underscore() {
        let v = serde_json::json!("kind_first");
        assert!(matches!(
            parse_strategy(&v).unwrap(),
            ReorderStrategy::KindFirst
        ));
    }

    #[test]
    fn parse_strategy_unknown_string() {
        let v = serde_json::json!("bogus");
        assert!(parse_strategy(&v).is_err());
    }

    #[test]
    fn parse_strategy_array_non_string_item() {
        let v = serde_json::json!(["a", 42, "c"]);
        assert!(parse_strategy(&v).is_err());
    }

    #[test]
    fn parse_strategy_invalid() {
        let v = serde_json::json!(42);
        assert!(parse_strategy(&v).is_err());
    }

    // Regression: reorder must preserve non-symbol content (use statements,
    // module-level comments) that appears before the first symbol.
    #[test]
    fn reorder_preserves_use_statements() {
        let source =
            "use std::collections::HashMap;\n\n// Module doc\nfn zebra() {}\n\nfn alpha() {}\n";
        let result =
            reorder_symbols(source, None, &ReorderStrategy::Alphabetical, Language::Rust).unwrap();
        assert!(
            result.content.contains("use std::collections::HashMap;"),
            "use statement should be preserved: {}",
            result.content
        );
        assert!(
            result.content.contains("// Module doc"),
            "module comment should be preserved: {}",
            result.content
        );
        let alpha_pos = result.content.find("fn alpha").unwrap();
        let zebra_pos = result.content.find("fn zebra").unwrap();
        assert!(alpha_pos < zebra_pos, "alpha should come before zebra");
        // use statement should come before any function
        let use_pos = result.content.find("use std").unwrap();
        assert!(
            use_pos < alpha_pos,
            "use statement should remain before symbols"
        );
    }

    #[test]
    fn reorder_preserves_crlf_line_endings() {
        let source = "fn charlie() {}\r\n\r\nfn alpha() {}\r\n\r\nfn bravo() {}\r\n";
        let result =
            reorder_symbols(source, None, &ReorderStrategy::Alphabetical, Language::Rust).unwrap();
        // All line endings in the output must be CRLF
        assert!(
            !result.content.contains("\n\n") || result.content.contains("\r\n"),
            "CRLF line endings should be preserved: {:?}",
            result.content
        );
        assert!(
            result.content.contains("\r\n"),
            "output should contain CRLF: {:?}",
            result.content
        );
        // Verify no bare LF (every \n must be preceded by \r)
        let bytes = result.content.as_bytes();
        for (i, &b) in bytes.iter().enumerate() {
            if b == b'\n' {
                assert!(
                    i > 0 && bytes[i - 1] == b'\r',
                    "bare LF at byte {i} in: {:?}",
                    result.content
                );
            }
        }
    }

    /// Regression: inter-symbol comments between functions must be preserved
    /// and move with the preceding symbol during reordering (#1111.2).
    #[test]
    fn reorder_preserves_inter_symbol_comments() {
        let source = "fn charlie() {}\n// charlie's note\n\nfn alpha() {}\n// alpha's note\n\nfn bravo() {}\n";
        let result =
            reorder_symbols(source, None, &ReorderStrategy::Alphabetical, Language::Rust).unwrap();
        // After reordering: alpha (with its trailing note), bravo, charlie (with its trailing note)
        let alpha_pos = result.content.find("fn alpha").unwrap();
        let bravo_pos = result.content.find("fn bravo").unwrap();
        let charlie_pos = result.content.find("fn charlie").unwrap();
        assert!(alpha_pos < bravo_pos, "alpha < bravo");
        assert!(bravo_pos < charlie_pos, "bravo < charlie");

        // Both comments should be preserved
        assert!(
            result.content.contains("// alpha's note"),
            "alpha's note should be preserved: {}",
            result.content
        );
        assert!(
            result.content.contains("// charlie's note"),
            "charlie's note should be preserved: {}",
            result.content
        );

        // alpha's note should be between alpha and bravo (it follows alpha)
        let alpha_note_pos = result.content.find("// alpha's note").unwrap();
        assert!(
            alpha_note_pos > alpha_pos && alpha_note_pos < bravo_pos,
            "alpha's note should follow alpha: {} < {} < {}",
            alpha_pos,
            alpha_note_pos,
            bravo_pos
        );
    }

    #[test]
    fn reorder_inside_single_line_container_no_panic() {
        // When children start on the same line as the container's opening brace,
        // first_sym_start could be < scope_start_0 causing a slice panic.
        let source = "mod m {\nfn b() {}\nfn a() {}\n}\n";
        let result = reorder_symbols(
            source,
            Some("m"),
            &ReorderStrategy::Alphabetical,
            Language::Rust,
        )
        .unwrap();
        let a_pos = result.content.find("fn a").unwrap();
        let b_pos = result.content.find("fn b").unwrap();
        assert!(a_pos < b_pos, "a should come before b: {}", result.content);
    }
}