patchloom 0.7.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
/*! Search operations for the public library API. */

use std::path::{Path, PathBuf};

use anyhow::{Context, bail};

use crate::ops;

// ---------------------------------------------------------------------------
// Search operations
// ---------------------------------------------------------------------------

/// A single search match.
#[derive(Debug, Clone)]
pub struct SearchMatch {
    /// 1-based line number.
    pub line_number: usize,
    /// The matched line content.
    pub line: String,
}

/// Search for a pattern in a file, returning all matching lines.
///
/// This is a read-only operation. For richer results with column/context use
/// `search_file` (the one taking SearchOptions) or the low-level `search_one_file`.
pub fn search(
    path: &Path,
    pattern: &str,
    regex: bool,
    case_insensitive: bool,
) -> anyhow::Result<Vec<SearchMatch>> {
    let content = std::fs::read_to_string(path)
        .with_context(|| format!("failed to read {}", path.display()))?;

    if pattern.is_empty() {
        bail!("search pattern must not be empty");
    }

    let compiled_re = if regex || case_insensitive {
        Some(ops::replace::compile_replace_regex(
            pattern,
            regex,
            case_insensitive,
            false,
            false,
        )?)
    } else {
        None
    };

    let mut matches = Vec::new();
    for (i, line) in content.lines().enumerate() {
        let matched = match &compiled_re {
            Some(Some(re)) => re.is_match(line),
            _ => line.contains(pattern),
        };
        if matched {
            matches.push(SearchMatch {
                line_number: i + 1,
                line: line.to_string(),
            });
        }
    }
    Ok(matches)
}

/// Search a single file with full `SearchOptions` support (context, regex, literal, etc).
///
/// Returns rich `SearchResult` entries (with column + context when requested).
/// This is the recommended per-file primitive for library/agent hosts (#812).
/// For callers that do their own walking (custom ignores, limits, etc.) see
/// [`search_one_file`].
pub fn search_file(
    path: &Path,
    pattern: &str,
    opts: &SearchOptions,
) -> anyhow::Result<Vec<SearchResult>> {
    // Delegate to search_directory (handles file root case + full rich logic with correct column/context).
    // This ensures parity and reuses the complete one-file impl (#812/#815).
    search_directory(path, pattern, opts)
}

/// Options for full directory search (for library consumers).
///
/// Supports customization for advanced ignore behavior (e.g. blineignore)
/// via `exclude_patterns` and `custom_ignore_filenames`. The underlying
/// `ignore::WalkBuilder` is used when the "files" feature is enabled, so
/// standard .gitignore is respected by default.
#[derive(Debug, Clone, Default)]
pub struct SearchOptions {
    /// Treat pattern as literal string (not regex).
    pub literal: bool,
    /// Treat as regex (default false, use with literal=false).
    pub regex: bool,
    /// Case insensitive match.
    pub case_insensitive: bool,
    /// Context lines around matches (symmetric). Overridden by
    /// `before_context` / `after_context` when those are set.
    pub context: Option<usize>,
    /// Lines of context before each match. Takes precedence over `context`.
    pub before_context: Option<usize>,
    /// Lines of context after each match. Takes precedence over `context`.
    pub after_context: Option<usize>,
    /// Show lines that do NOT match the pattern.
    pub invert_match: bool,
    /// Enable multiline matching (dot matches newlines in regex mode).
    pub multiline: bool,
    /// Glob patterns to include (e.g. "*.rs").
    pub globs: Vec<String>,
    /// Max number of results (0 for unlimited).
    pub max_results: usize,
    /// Additional gitignore-style patterns to *exclude* (e.g. from a .blineignore).
    /// These are applied in addition to any .gitignore respected by the walker.
    pub exclude_patterns: Vec<String>,
    /// Custom ignore filenames to respect in addition to .gitignore / .ignore
    /// (e.g. `vec![".blineignore".to_string()]`).
    pub custom_ignore_filenames: Vec<String>,
}

/// Result of a search match with optional context.
#[derive(Debug, Clone)]
pub struct SearchResult {
    pub path: PathBuf,
    pub line_number: usize,
    pub line: String,
    pub column: usize,
    pub context_before: Vec<String>,
    pub context_after: Vec<String>,
}

/// Helper to build context slices for a match line. DRY for search impls (library + CLI).
///
/// Exposed for downstreams that want consistent context extraction (#815).
///
/// Accepts asymmetric context sizes (`before_ctx`, `after_ctx`). For symmetric
/// context pass the same value for both.
pub fn build_context_lines(
    all_lines: &[&str],
    match_idx: usize,
    before_ctx: usize,
    after_ctx: usize,
) -> (Vec<String>, Vec<String>) {
    let before = if before_ctx == 0 {
        vec![]
    } else {
        let start = match_idx.saturating_sub(before_ctx);
        all_lines[start..match_idx]
            .iter()
            .map(|s| s.to_string())
            .collect()
    };
    let after = if after_ctx == 0 {
        vec![]
    } else {
        let end = (match_idx + 1 + after_ctx).min(all_lines.len());
        all_lines[match_idx + 1..end]
            .iter()
            .map(|s| s.to_string())
            .collect()
    };
    (before, after)
}

/// Search a directory (or file) recursively for pattern.
/// Respects globs and custom ignores (via `SearchOptions`) if "files" feature enabled.
/// Uses parallel processing when available.
/// This provides the full power of the CLI search for library use (see #773, #796).
/// See `SearchOptions` for `exclude_patterns` and `custom_ignore_filenames` (blineignore etc.).
///
/// For callers that already have a list of files (custom walker), see [`search_one_file`].
///
/// Example for custom ignore (bline style):
/// ```ignore
/// let opts = SearchOptions {
///     custom_ignore_filenames: vec![".blineignore".into()],
///     exclude_patterns: vec!["*.tmp".into()],
///     ..Default::default()
/// };
/// let hits = search_directory(Path::new("."), "TODO", &opts)?;
/// ```
pub fn search_directory(
    root: &Path,
    pattern: &str,
    opts: &SearchOptions,
) -> anyhow::Result<Vec<SearchResult>> {
    if pattern.is_empty() {
        bail!("search pattern must not be empty");
    }

    #[cfg(any(feature = "cli", feature = "files"))]
    {
        use crate::files::{build_glob_matcher, par_process_files};
        let glob_matcher = build_glob_matcher(&opts.globs)?;
        let glob_roots = vec![root.to_path_buf()];

        // Delegate to shared helper for identical multi-source ignore precedence (#813).
        let file_paths = crate::files::collect_file_paths_with_ignores(
            root,
            &opts.custom_ignore_filenames,
            &opts.exclude_patterns,
            false, // search typically does not traverse hidden unless requested via other means
        )?;

        let limit = if opts.max_results > 0 {
            opts.max_results
        } else {
            usize::MAX
        };

        let file_result_groups: Vec<Vec<SearchResult>> =
            par_process_files(&file_paths, glob_matcher.as_ref(), &glob_roots, |path| {
                let v = search_one_file(path, pattern, opts, root);
                if v.is_empty() { None } else { Some(v) }
            });

        let mut res: Vec<SearchResult> = file_result_groups.into_iter().flatten().collect();
        if limit < usize::MAX {
            res.truncate(limit);
        }
        Ok(res)
    }

    #[cfg(not(any(feature = "cli", feature = "files")))]
    {
        if opts.multiline {
            bail!("multiline search requires the 'cli' or 'files' feature");
        }
        if opts.invert_match {
            bail!("invert_match search requires the 'cli' or 'files' feature");
        }
        // fallback to single file search (multi-match supported via basic search)
        if root.is_file() {
            let basic = search(root, pattern, opts.regex, opts.case_insensitive)?;
            let display = root.to_path_buf();
            let ctx_b = opts.before_context.or(opts.context).unwrap_or(0);
            let ctx_a = opts.after_context.or(opts.context).unwrap_or(0);
            // read once for both content and context lines (fallback is rare / no "files" feature)
            let content = std::fs::read_to_string(root)
                .with_context(|| format!("failed to read {}", root.display()))?;
            let all_lines: Vec<&str> = content.lines().collect();
            let results: Vec<SearchResult> = basic
                .into_iter()
                .map(|m| {
                    let i = m.line_number - 1;
                    let (context_before, context_after) =
                        build_context_lines(&all_lines, i, ctx_b, ctx_a);
                    // column not tracked in basic fallback search (always 1; full impl behind "files" feature)
                    let column = 1;
                    SearchResult {
                        path: display.clone(),
                        line_number: m.line_number,
                        line: m.line,
                        column,
                        context_before,
                        context_after,
                    }
                })
                .collect();
            Ok(results)
        } else {
            bail!(
                "search_directory requires the 'files' feature to be enabled (for pure-library recursive search with ignores/parallelism)"
            );
        }
    }
}

#[cfg(any(feature = "cli", feature = "files"))]
/// Low-level single-file matcher for callers that already selected the files.
///
/// Returns rich [`SearchResult`]s (including `column` and context when requested
/// via [`SearchOptions`]). Intended for advanced library users (e.g. custom
/// `WalkBuilder` with extra ignores, size caps, depth limits, custom truncation)
/// who then want to apply patchloom's matching logic.
///
/// Prefer [`search_file`] for simple per-file use and [`search_directory`] for
/// full directory walking with built-in ignore support.
pub fn search_one_file(
    path: &Path,
    pattern: &str,
    opts: &SearchOptions,
    root: &Path,
) -> Vec<SearchResult> {
    let content = match crate::files::read_text_file(path) {
        Some(c) => c,
        None => return vec![],
    };
    let display = crate::files::relative_display(path, root);
    let pat = if opts.literal || (opts.multiline && !opts.regex) {
        // Auto-escape when literal is set, or when multiline mode is used
        // without regex (the pattern must go through RegexBuilder but the
        // user expects literal matching).
        regex::escape(pattern)
    } else {
        pattern.to_string()
    };
    let re = if opts.regex || opts.case_insensitive || opts.multiline {
        match regex::RegexBuilder::new(&pat)
            .case_insensitive(opts.case_insensitive)
            .multi_line(true)
            .dot_matches_new_line(opts.multiline)
            .build()
        {
            Ok(r) => Some(r),
            Err(_) => return vec![],
        }
    } else {
        None
    };

    let ctx_before = opts.before_context.or(opts.context).unwrap_or(0);
    let ctx_after = opts.after_context.or(opts.context).unwrap_or(0);

    // Multiline mode: match against full content, report the start line of each match
    if opts.multiline {
        // `re` is always Some here: multiline triggers the regex path above,
        // and invalid patterns return early with an empty vec.
        let re = re.as_ref().expect("multiline always builds regex");
        let mut results = Vec::new();
        let all_lines: Vec<&str> = content.lines().collect();
        for m in re.find_iter(&content) {
            let start_byte = m.start();
            let line_num = content[..start_byte].matches('\n').count();
            let line_text = all_lines.get(line_num).unwrap_or(&"").to_string();
            let (context_before, context_after) =
                build_context_lines(&all_lines, line_num, ctx_before, ctx_after);
            results.push(SearchResult {
                path: display.to_path_buf(),
                line_number: line_num + 1,
                line: line_text,
                column: 1,
                context_before,
                context_after,
            });
        }
        return results;
    }

    let mut results = Vec::new();
    let all_lines: Vec<&str> = content.lines().collect();
    for (i, line) in all_lines.iter().enumerate() {
        let found = if let Some(re) = &re {
            re.is_match(line)
        } else {
            line.contains(pattern)
        };
        let is_match = if opts.invert_match { !found } else { found };
        if is_match {
            let (context_before, context_after) =
                build_context_lines(&all_lines, i, ctx_before, ctx_after);
            let column = if !opts.invert_match {
                if let Some(re) = &re {
                    re.find(line).map_or(1, |m| m.start() + 1)
                } else {
                    line.find(pattern).map_or(1, |p| p + 1)
                }
            } else {
                1
            };
            results.push(SearchResult {
                path: display.to_path_buf(),
                line_number: i + 1,
                line: line.to_string(),
                column,
                context_before,
                context_after,
            });
        }
    }
    results
}

/// Format `SearchResult`s for display (human text or JSON).
///
/// Library / agent hosts can use this for consistent output with CLI search (#812).
pub fn format_search_results(results: &[SearchResult], as_json: bool) -> String {
    use std::fmt::Write;
    let mut out = String::new();
    if as_json {
        let payload: Vec<_> = results
            .iter()
            .map(|r| {
                serde_json::json!({
                    "path": r.path,
                    "line": r.line_number,
                    "text": r.line,
                    "column": r.column,
                    "context_before": r.context_before,
                    "context_after": r.context_after,
                })
            })
            .collect();
        if let Ok(s) = serde_json::to_string_pretty(&payload) {
            out = s;
            out.push('\n');
        }
    } else {
        for r in results {
            for ctx in &r.context_before {
                let _ = writeln!(out, "  {}", ctx);
            }
            let _ = writeln!(out, "{}:{}: {}", r.path.display(), r.line_number, r.line);
            for ctx in &r.context_after {
                let _ = writeln!(out, "  {}", ctx);
            }
        }
    }
    out
}