patchloom 0.33.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
//! `tidy fix`: parallel dirty-file scan, stage via engine, finalize_report.

use crate::cli::global::GlobalFlags;
use crate::diff::render_diffs_colored;
use crate::exit;
use crate::plan::Operation;
use crate::tx::engine::{ExecutionResult, WriteSource};
use crate::write::{apply_policy, policy_from_flags};
use serde::Serialize;
use std::path::Path;

/// Per-file result for tidy fix structured output.
#[derive(Debug, Clone, Serialize)]
pub(super) struct TidyFixFileResult {
    pub path: String,
}

/// JSON wrapper for tidy fix output.
#[derive(Debug, Serialize)]
struct TidyFixOutput {
    ok: bool,
    files_changed: usize,
    files: Vec<TidyFixFileResult>,
    #[serde(skip_serializing_if = "Option::is_none")]
    diff: Option<String>,
    /// Whether bytes were written (#1812). `false` for preview/`--check`.
    #[serde(skip_serializing_if = "Option::is_none")]
    applied: Option<bool>,
    /// Backup session id after a successful apply (#1802).
    #[serde(skip_serializing_if = "Option::is_none")]
    backup_session: Option<String>,
    /// Paths from `--files-from` that were missing (agent honesty; #1756 class).
    #[serde(skip_serializing_if = "Option::is_none")]
    skipped: Option<Vec<String>>,
    /// Explicit multi-path co-targets soft-skipped (e.g. binary). Directory walks omit.
    #[serde(skip_serializing_if = "Option::is_none")]
    refused: Option<Vec<crate::ops::file::PathRefused>>,
}

/// Convert `EolMode` to the string format expected by `Operation::TidyFix`.
pub(super) fn eol_mode_to_str(mode: crate::cli::global::EolMode) -> &'static str {
    match mode {
        crate::cli::global::EolMode::Lf => "lf",
        crate::cli::global::EolMode::Crlf => "crlf",
        crate::cli::global::EolMode::Cr => "cr",
        crate::cli::global::EolMode::Keep => "keep",
    }
}

/// Handle output rendering and commit/check/preview for tidy fix via the engine.
///
/// Mode/exit owned by [`crate::cmd::write_mode::finalize_report`].
pub(super) fn tidy_fix_output(
    global: &GlobalFlags,
    result: ExecutionResult,
    dirty_rel_paths: &[String],
    cwd: &Path,
    skipped: Option<Vec<String>>,
    refused: Option<Vec<crate::ops::file::PathRefused>>,
) -> anyhow::Result<u8> {
    use crate::cmd::write_mode::{FinalizeCallbacks, finalize_report};

    let fix_files: Vec<TidyFixFileResult> = dirty_rel_paths
        .iter()
        .map(|p| TidyFixFileResult { path: p.clone() })
        .collect();
    let n_files = dirty_rel_paths.len();

    finalize_report(
        global,
        cwd,
        result,
        true,
        FinalizeCallbacks {
            on_check: |g: &GlobalFlags, _has: bool, _diffs: &[crate::diff::FileDiff]| {
                emit_tidy_fix_output(
                    g,
                    &fix_files,
                    None,
                    Some(false),
                    None,
                    skipped.clone(),
                    refused.clone(),
                )?;
                if !g.quiet && !g.json && !g.jsonl {
                    for p in dirty_rel_paths {
                        println!("{p}");
                    }
                }
                Ok(())
            },
            on_apply: |g: &GlobalFlags,
                       has: bool,
                       _diffs: &[crate::diff::FileDiff],
                       diff_text: Option<String>,
                       backup: Option<String>| {
                emit_tidy_fix_output(
                    g,
                    &fix_files,
                    diff_text,
                    Some(has),
                    backup,
                    skipped.clone(),
                    refused.clone(),
                )?;
                Ok(())
            },
            on_preview: |g: &GlobalFlags,
                         _has: bool,
                         diffs: &[crate::diff::FileDiff],
                         diff_text: Option<String>| {
                emit_tidy_fix_output(
                    g,
                    &fix_files,
                    diff_text,
                    Some(false),
                    None,
                    skipped.clone(),
                    refused.clone(),
                )?;
                if !g.json && !g.jsonl && !g.quiet && !diffs.is_empty() {
                    print!("{}", render_diffs_colored(diffs, g.should_color()));
                }
                Ok(())
            },
            after_preview_emit: |g: &GlobalFlags| {
                if g.show_status() {
                    eprintln!("{n_files} file(s) changed");
                }
            },
            after_preview_apply: |_: &GlobalFlags| {},
        },
    )
}

/// Emit structured JSON/JSONL output for tidy fix.
///
/// Propagates serialize failures (`?`) so agents never see empty stdout under
/// `--json`/`--jsonl` while the command still returns a soft success code
/// (same fail-closed class as #1651 / `json_emit`).
fn emit_tidy_fix_output(
    global: &GlobalFlags,
    fix_files: &[TidyFixFileResult],
    diff_text: Option<String>,
    applied: Option<bool>,
    backup_session: Option<String>,
    skipped: Option<Vec<String>>,
    refused: Option<Vec<crate::ops::file::PathRefused>>,
) -> anyhow::Result<()> {
    if global.json {
        let output = TidyFixOutput {
            ok: true,
            files_changed: fix_files.len(),
            files: fix_files.to_vec(),
            diff: diff_text,
            applied,
            backup_session,
            skipped,
            refused,
        };
        global.emit_json(&output)?;
    } else if global.jsonl {
        // Stream per-file rows, then a summary trailer so agents using --jsonl
        // still get applied / backup_session / skipped / refused (parity JSON).
        global.emit_json_items(fix_files)?;
        global.emit_json(&serde_json::json!({
            "type": "summary",
            "ok": true,
            "files_changed": fix_files.len(),
            "applied": applied,
            "backup_session": backup_session,
            "skipped": skipped,
            "refused": refused,
            "diff": diff_text,
        }))?;
    }
    Ok(())
}

/// Write-policy fields for `tidy fix` after applying check-parity defaults.
struct TidyFixPolicy {
    ensure_final_newline: bool,
    trim_trailing_whitespace: bool,
    normalize_eol: Option<crate::cli::global::EolMode>,
    collapse_blanks: bool,
}

/// When the user did not pass any write-policy flag and is not only
/// indenting/dedenting, enable the same normalizations that `tidy check`
/// always reports (final newline + trailing whitespace). Otherwise
/// `tidy fix --apply` is a silent no-op while `tidy check` still fails
/// (fixrealloop feature gap).
fn effective_tidy_fix_policy(
    global: &GlobalFlags,
    dedent: Option<&str>,
    indent: Option<&str>,
) -> TidyFixPolicy {
    // EditorConfig opt-in is also "explicit policy": do not force check-parity
    // defaults on top of per-file EditorConfig rules.
    let any_explicit_policy = global.ensure_final_newline
        || global.trim_trailing_whitespace
        || global.normalize_eol.is_some()
        || global.collapse_blanks
        || global.respect_editorconfig
        || dedent.is_some()
        || indent.is_some();
    if any_explicit_policy {
        return TidyFixPolicy {
            ensure_final_newline: global.ensure_final_newline,
            trim_trailing_whitespace: global.trim_trailing_whitespace,
            normalize_eol: global.normalize_eol,
            collapse_blanks: global.collapse_blanks,
        };
    }
    TidyFixPolicy {
        ensure_final_newline: true,
        trim_trailing_whitespace: true,
        normalize_eol: None,
        collapse_blanks: false,
    }
}

/// Run `tidy fix` for the given paths and optional dedent/indent/lines.
pub(super) fn run_fix(
    paths: Vec<String>,
    dedent: Option<String>,
    indent: Option<String>,
    lines: Option<String>,
    global: &GlobalFlags,
) -> anyhow::Result<u8> {
    crate::verbose!("tidy: fixing {} path(s)", paths.len());
    if dedent.is_some() && indent.is_some() {
        let msg = "--dedent and --indent cannot both be set";
        global.emit_error_json_kind(Some("invalid_input"), msg)?;
        return Ok(crate::exit::FAILURE);
    }

    let policy_flags = effective_tidy_fix_policy(global, dedent.as_deref(), indent.as_deref());

    let cwd = global.resolve_cwd()?;
    global.check_paths_contained(&cwd, &paths)?;
    // Read --files-from once (including stdin `-`); do not re-read empty stdin.
    let files_from_list = global.read_files_from()?;
    let charset_paths = files_from_list.as_deref().unwrap_or(&paths);
    if let Some(name) =
        super::check::first_unsupported_editorconfig_charset(charset_paths, global, &cwd)
    {
        let msg = format!("editorconfig charset '{name}' is not supported; use utf-8 or utf-8-bom");
        global.emit_error_json_kind(Some("invalid_input"), &msg)?;
        return Ok(exit::FAILURE);
    }
    if let Some(err) =
        crate::ops::file::sole_explicit_non_text_for_scan(&paths, files_from_list.as_deref(), &cwd)
    {
        {
            let kind = crate::fallback::error_kind_str(&err).unwrap_or("invalid_input");
            let msg = crate::exit::agent_error_message(&err);
            global.emit_error_json_kind(Some(kind), &msg)?;
        }
        return Ok(crate::exit::FAILURE);
    }
    let skipped = if files_from_list.is_some() {
        files_from_list
            .as_ref()
            .and_then(|files| crate::files::explicit_paths_missing_entries(&cwd, files))
    } else {
        crate::files::scan_missing_entries(global, &cwd, &paths)?
    };
    let glob_matcher = crate::build_glob_matcher_from_global(global)?;
    let fix_file_paths = crate::files::collect_file_paths_opts_with_list(
        &paths,
        global,
        true,
        Some(&cwd),
        files_from_list.as_deref(),
        None,
    )?;
    // Empty --files-from is invalid_input, not a successful no-op (#1796).
    crate::files::ensure_files_from_nonempty(global, &fix_file_paths)?;
    let glob_roots = crate::collect_glob_roots_from_global(&paths, global, Some(&cwd))?;

    let line_range = lines
        .as_deref()
        .map(crate::ops::read::parse_line_range)
        .transpose()?;

    let quiet = global.quiet || global.json || global.jsonl;
    let dedent_ref = dedent.as_deref();
    let indent_ref = indent.as_deref();
    // policy_from_flags reads ensure/trim/eol from GlobalFlags. Overlay the
    // effective tidy defaults (and keep editorconfig opt-in from the caller).
    let policy_global = GlobalFlags {
        ensure_final_newline: policy_flags.ensure_final_newline,
        trim_trailing_whitespace: policy_flags.trim_trailing_whitespace,
        normalize_eol: policy_flags.normalize_eol,
        collapse_blanks: policy_flags.collapse_blanks,
        respect_editorconfig: global.respect_editorconfig,
        quiet: global.quiet,
        ..GlobalFlags::default()
    };

    let charset_err = std::sync::Mutex::new(None::<&'static str>);
    let dirty_rel_paths: Vec<String> = crate::par_process_files(
        &fix_file_paths,
        glob_matcher.as_ref(),
        &glob_roots,
        |file_path| {
            let mut policy = policy_from_flags(&policy_global, Some(file_path));
            if let Some(name) = policy.unsupported_charset() {
                *charset_err.lock().unwrap_or_else(|e| e.into_inner()) = Some(name);
                return None;
            }
            let original = match crate::files::read_text_file_logged(file_path, "tidy", quiet) {
                Some(text) => text,
                None => return None,
            };
            let charset = policy.charset;
            policy.charset = crate::write::CharsetMode::Keep;
            let mut fixed = apply_policy(&original, &policy).into_owned();
            if let Some(spec) = dedent_ref {
                fixed = crate::write::dedent_content(&fixed, spec, line_range);
            }
            if let Some(spec) = indent_ref {
                fixed = crate::write::indent_content(&fixed, spec, line_range);
            }
            fixed = crate::write::apply_charset(&fixed, charset).into_owned();
            if fixed == *original {
                return None;
            }
            let rel_path = file_path
                .strip_prefix(&cwd)
                .unwrap_or(file_path)
                .to_string_lossy()
                .to_string();
            Some(rel_path)
        },
    );

    crate::verbose!("tidy: {} file(s) need fixing", dirty_rel_paths.len());
    if let Some(name) = charset_err.into_inner().unwrap_or_else(|e| e.into_inner()) {
        let msg = format!("editorconfig charset '{name}' is not supported; use utf-8 or utf-8-bom");
        global.emit_error_json_kind(Some("invalid_input"), &msg)?;
        return Ok(crate::exit::FAILURE);
    }
    if dirty_rel_paths.is_empty() {
        let all_missing = if let Some(ref files) = files_from_list {
            crate::files::all_explicit_paths_missing(files, Some(&cwd))
        } else {
            crate::files::all_scan_targets_missing(global, &paths, Some(&cwd))?
        };
        if all_missing {
            let msg = format!(
                "no such file or directory: {}",
                global.path_scope_description(&paths)
            );
            global.emit_error_json_kind(Some("not_found"), &msg)?;
            return Ok(exit::FAILURE);
        }
        // Sole re-check after scan (covers rare races); files_from already above.
        if let Some(err) = crate::ops::file::sole_explicit_non_text_for_scan(
            &paths,
            files_from_list.as_deref(),
            &cwd,
        ) {
            {
                let kind = crate::fallback::error_kind_str(&err).unwrap_or("invalid_input");
                let msg = crate::exit::agent_error_message(&err);
                global.emit_error_json_kind(Some(kind), &msg)?;
            }
            return Ok(exit::FAILURE);
        }
        // Dir walk: unreadable must not look like "already tidy".
        if let Some(err) = crate::ops::file::empty_scan_masked_by_unreadable(&fix_file_paths, &cwd)
        {
            global.emit_error_json_kind(Some("invalid_input"), &err.msg)?;
            return Ok(exit::FAILURE);
        }
        let refuse_paths: &[String] = files_from_list.as_deref().unwrap_or(&paths);
        let refused = crate::ops::file::explicit_multi_path_non_text_refused(refuse_paths, &cwd);
        emit_tidy_fix_output(global, &[], None, Some(false), None, skipped, refused)?;
        return Ok(exit::SUCCESS);
    }

    let eol_str = policy_flags.normalize_eol.map(eol_mode_to_str);
    let collapse = if policy_flags.collapse_blanks {
        Some(true)
    } else {
        None
    };
    let ops: Vec<Operation> = dirty_rel_paths
        .iter()
        .map(|rel_path| Operation::TidyFix {
            path: rel_path.clone(),
            ensure_final_newline: Some(policy_flags.ensure_final_newline),
            trim_trailing_whitespace: Some(policy_flags.trim_trailing_whitespace),
            normalize_eol: eol_str.map(String::from),
            collapse_blanks: collapse,
            dedent: dedent.clone(),
            indent: indent.clone(),
            lines: lines.clone(),
        })
        .collect();

    // Mode/apply still come from the caller's global flags; only the
    // write-policy fields use the effective check-parity defaults above.
    let (cwd, result) = crate::cmd::output::stage_for_write(WriteSource::Operations(ops), global)?;

    let refuse_paths: &[String] = files_from_list.as_deref().unwrap_or(&paths);
    let refused = crate::ops::file::explicit_multi_path_non_text_refused(refuse_paths, &cwd);
    tidy_fix_output(global, result, &dirty_rel_paths, &cwd, skipped, refused)
}