patchloom 0.4.0

Structured file editing library and CLI for AI agents: parser-backed JSON/YAML/TOML edits, AST-aware code operations via tree-sitter, 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
#[cfg(feature = "cli")]
use clap::Args;
use std::io::BufRead;

/// Color mode for terminal output.
#[derive(Debug, Clone, Copy, Default)]
#[cfg_attr(feature = "cli", derive(clap::ValueEnum))]
pub enum ColorMode {
    /// Auto-detect: color when stdout is a terminal.
    #[default]
    Auto,
    /// Always emit ANSI color codes.
    Always,
    /// Never emit ANSI color codes.
    Never,
}

/// Write policy for EOL normalization. Re-exported from `write` so that
/// CLI code can continue to use `crate::cli::global::EolMode`.
pub use crate::write::EolMode;

/// Flags available to all subcommands (read and write).
///
/// Write-only flags are `#[clap(skip)]` here so they don't appear in
/// read-only subcommand help. Write commands flatten [`WriteFlags`]
/// separately and the dispatcher merges them via [`GlobalFlags::merge_write`].
#[derive(Debug, Default)]
#[cfg_attr(feature = "cli", derive(Args))]
pub struct GlobalFlags {
    /// Emit machine-readable JSON output.
    #[cfg_attr(feature = "cli", arg(long, global = true))]
    pub json: bool,

    /// Emit one JSON object per result line.
    #[cfg_attr(feature = "cli", arg(long, global = true))]
    pub jsonl: bool,

    /// Suppress non-JSON human-readable output.
    #[cfg_attr(feature = "cli", arg(long, short = 'q', global = true))]
    pub quiet: bool,

    /// Enable verbose diagnostic output on stderr for debugging.
    /// Can also be enabled via the PATCHLOOM_LOG environment variable.
    #[cfg_attr(feature = "cli", arg(long, global = true))]
    pub verbose: bool,

    /// Set working directory.
    #[cfg_attr(feature = "cli", arg(long, global = true))]
    pub cwd: Option<String>,

    /// Restrict target files by glob pattern (may be repeated).
    #[cfg_attr(feature = "cli", arg(long, global = true, action = clap::ArgAction::Append))]
    pub glob: Vec<String>,

    /// Read file list from a file or stdin (`-`), one path per line.
    #[cfg_attr(feature = "cli", arg(long, global = true))]
    pub files_from: Option<String>,

    /// When to use color: auto (default), always, or never.
    #[cfg_attr(
        feature = "cli",
        arg(long, global = true, value_enum, default_value = "auto")
    )]
    pub color: ColorMode,

    // -- Write-only flags (populated via merge_write in dispatch) -----------
    #[cfg_attr(feature = "cli", clap(skip))]
    pub diff: bool,
    #[cfg_attr(feature = "cli", clap(skip))]
    pub apply: bool,
    #[cfg_attr(feature = "cli", clap(skip))]
    pub check: bool,
    #[cfg_attr(feature = "cli", clap(skip))]
    pub ensure_final_newline: bool,
    #[cfg_attr(feature = "cli", clap(skip))]
    pub normalize_eol: Option<EolMode>,
    #[cfg_attr(feature = "cli", clap(skip))]
    pub trim_trailing_whitespace: bool,
    #[cfg_attr(feature = "cli", clap(skip))]
    pub respect_editorconfig: bool,
    #[cfg_attr(feature = "cli", clap(skip))]
    pub collapse_blanks: bool,
    #[cfg_attr(feature = "cli", clap(skip))]
    pub confirm: bool,
    #[cfg_attr(feature = "cli", clap(skip))]
    pub format: Option<String>,
    #[cfg_attr(feature = "cli", clap(skip))]
    pub format_timeout: Option<u64>,
}

/// Write-only flags exposed in subcommands that mutate files.
///
/// Use `global = true` so these propagate into nested subcommands
/// (e.g. `doc set`, `patch apply`). They only appear in help when
/// the parent command flattens this struct.
#[derive(Debug, Default)]
#[cfg_attr(feature = "cli", derive(Args))]
pub struct WriteFlags {
    /// Print unified diff for any write operation.
    #[cfg_attr(feature = "cli", arg(long, global = true))]
    pub diff: bool,

    /// Actually mutate files.
    #[cfg_attr(feature = "cli", arg(long, global = true, conflicts_with = "check"))]
    pub apply: bool,

    /// Compute and report changes without writing.
    #[cfg_attr(feature = "cli", arg(long, global = true, conflicts_with = "apply"))]
    pub check: bool,

    /// Ensure non-empty written files end with a newline.
    #[cfg_attr(feature = "cli", arg(long, global = true))]
    pub ensure_final_newline: bool,

    /// Normalize line endings after write.
    #[cfg_attr(feature = "cli", arg(long, global = true, value_enum))]
    pub normalize_eol: Option<EolMode>,

    /// Remove trailing whitespace on touched lines.
    #[cfg_attr(feature = "cli", arg(long, global = true))]
    pub trim_trailing_whitespace: bool,

    /// Read write policy from .editorconfig when present.
    #[cfg_attr(feature = "cli", arg(long, global = true))]
    pub respect_editorconfig: bool,

    /// Collapse consecutive blank lines into a single blank line after writing.
    #[cfg_attr(feature = "cli", arg(long, global = true))]
    pub collapse_blanks: bool,

    /// Show diff then prompt before applying. Implies --apply on confirmation.
    #[cfg_attr(feature = "cli", arg(long, global = true, conflicts_with_all = ["apply", "check"]))]
    pub confirm: bool,

    /// Run a shell command after successful --apply (e.g. "cargo fmt --all").
    /// Ignored in --diff and --check modes.
    #[cfg_attr(feature = "cli", arg(long, global = true))]
    pub format: Option<String>,

    /// Timeout in seconds for the --format command (default: 30).
    #[cfg_attr(feature = "cli", arg(long, global = true, default_value = "30"))]
    pub format_timeout: Option<u64>,
}

pub(crate) fn confirm_prompt(prompt: &str) -> bool {
    // Flush stdout before the prompt writes to stderr, otherwise the diff
    // output may remain buffered and invisible in a PTY.
    use std::io::Write;
    let _ = std::io::stdout().flush();
    let is_tty = std::io::IsTerminal::is_terminal(&std::io::stdin());
    confirm_prompt_interactive(prompt, is_tty, &mut std::io::stdin().lock())
}

/// Prompt for confirmation when stdin is an interactive TTY.
///
/// Returns `false` immediately when `is_tty` is false (safe fallback for
/// pipes, CI, and `cargo test` without a pseudo-TTY).
pub(crate) fn confirm_prompt_interactive(
    prompt: &str,
    is_tty: bool,
    reader: &mut impl BufRead,
) -> bool {
    if !is_tty {
        return false;
    }
    eprint!("{prompt} [Y/n] ");
    let mut buf = String::new();
    match reader.read_line(&mut buf) {
        Ok(0) | Err(_) => false,
        Ok(_) => {
            let answer = buf.trim().to_lowercase();
            answer.is_empty() || answer == "y" || answer == "yes"
        }
    }
}

impl GlobalFlags {
    /// Copy write-only flags from a [`WriteFlags`] into this struct.
    pub fn merge_write(&mut self, w: &WriteFlags) {
        self.diff = w.diff;
        self.apply = w.apply;
        self.check = w.check;
        self.confirm = w.confirm;
        self.ensure_final_newline = w.ensure_final_newline;
        self.normalize_eol = w.normalize_eol;
        self.trim_trailing_whitespace = w.trim_trailing_whitespace;
        self.respect_editorconfig = w.respect_editorconfig;
        self.collapse_blanks = w.collapse_blanks;
        self.format = w.format.clone();
        self.format_timeout = w.format_timeout;
    }

    /// Whether to proceed with the write after optional confirmation.
    ///
    /// Returns `true` when `--apply` is set, or when `--confirm` is set and
    /// the user answers yes at the interactive prompt. When `--confirm` is
    /// used but stdin is not a TTY, returns `false` (safe fallback).
    pub fn should_apply(&self) -> bool {
        if self.apply {
            return true;
        }
        self.confirm && confirm_prompt("Apply?")
    }

    /// Whether to emit ANSI color codes to stdout.
    ///
    /// Respects `--color`, the `NO_COLOR` env var, and TTY detection.
    pub fn should_color(&self) -> bool {
        match self.color {
            ColorMode::Always => true,
            ColorMode::Never => false,
            ColorMode::Auto => {
                // Respect NO_COLOR (https://no-color.org)
                if std::env::var_os("NO_COLOR").is_some() {
                    return false;
                }
                #[cfg(feature = "cli")]
                {
                    anstream::stdout().is_terminal()
                }
                #[cfg(not(feature = "cli"))]
                {
                    false
                }
            }
        }
    }

    /// Whether to show human-friendly status messages on stderr.
    ///
    /// Returns true when stderr is a TTY and `--quiet`/`--json`/`--jsonl` are
    /// not set. This lets commands print brief summaries for humans without
    /// interfering with machine-readable stdout.
    pub fn show_status(&self) -> bool {
        !self.quiet && !self.json && !self.jsonl && {
            #[cfg(feature = "cli")]
            {
                anstream::stderr().is_terminal()
            }
            #[cfg(not(feature = "cli"))]
            {
                false
            }
        }
    }

    /// Resolve the working directory from `--cwd`, defaulting to the process
    /// current directory.
    pub fn resolve_cwd(&self) -> anyhow::Result<std::path::PathBuf> {
        if let Some(ref cwd) = self.cwd {
            let path = std::path::PathBuf::from(cwd);
            if !path.exists() {
                anyhow::bail!("--cwd directory does not exist: {cwd}");
            }
            if !path.is_dir() {
                anyhow::bail!("--cwd is not a directory: {cwd}");
            }
            Ok(path)
        } else {
            std::env::current_dir().map_err(Into::into)
        }
    }

    /// Emit a serializable value to stdout in structured format.
    ///
    /// If `--json` is set, pretty-prints. If `--jsonl` is set, prints compact.
    /// Returns `true` if structured output was emitted, `false` if the caller
    /// should handle text-mode output (respecting `--quiet`).
    pub fn emit_json<T: serde::Serialize>(&self, value: &T) -> anyhow::Result<bool> {
        if self.json {
            println!("{}", serde_json::to_string_pretty(value)?);
            Ok(true)
        } else if self.jsonl {
            println!("{}", serde_json::to_string(value)?);
            Ok(true)
        } else {
            Ok(false)
        }
    }

    /// Read file paths from `--files-from`. Returns `None` if the flag is not set.
    /// When the value is `-`, reads from stdin (one path per line).
    pub fn read_files_from(&self) -> anyhow::Result<Option<Vec<String>>> {
        let source = match self.files_from.as_deref() {
            Some(s) => s,
            None => return Ok(None),
        };
        let lines: Vec<String> = if source == "-" {
            std::io::stdin()
                .lock()
                .lines()
                .map_while(Result::ok)
                .filter(|l| !l.is_empty())
                .collect()
        } else {
            std::fs::read_to_string(source)
                .map_err(|e| anyhow::anyhow!("failed to read --files-from '{}': {e}", source))?
                .lines()
                .filter(|l| !l.is_empty())
                .map(String::from)
                .collect()
        };
        Ok(Some(lines))
    }
}

#[cfg(test)]
impl GlobalFlags {
    /// Test helper returning GlobalFlags with color=Never for deterministic
    /// test output (avoids TTY/NO_COLOR variance).
    pub fn test_default() -> Self {
        GlobalFlags {
            color: ColorMode::Never,
            ..GlobalFlags::default()
        }
    }

    /// Test helper with cwd set (simulates --cwd for cmd unit tests).
    pub fn test_with_cwd(dir: &std::path::Path) -> Self {
        GlobalFlags {
            cwd: Some(dir.to_string_lossy().into_owned()),
            color: ColorMode::Never,
            ..GlobalFlags::default()
        }
    }

    /// Test helper with apply=true (for write cmd tests that want mutation).
    pub fn test_apply() -> Self {
        let mut g = Self::test_default();
        g.apply = true;
        g
    }
}

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

    #[test]
    fn should_apply_returns_true_when_apply_set() {
        let g = GlobalFlags {
            apply: true,
            ..GlobalFlags::default()
        };
        assert!(g.should_apply());
    }

    #[test]
    fn should_apply_returns_false_by_default() {
        let g = GlobalFlags::default();
        assert!(!g.should_apply());
    }

    #[test]
    fn confirm_prompt_non_tty_returns_false() {
        let mut reader = std::io::Cursor::new(b"y\n");
        assert!(!confirm_prompt_interactive("Apply?", false, &mut reader));
    }

    #[test]
    fn confirm_prompt_tty_accepts_default_yes() {
        let mut reader = std::io::Cursor::new(b"\n");
        assert!(confirm_prompt_interactive("Apply?", true, &mut reader));
    }

    #[test]
    fn should_apply_confirm_non_tty_returns_false() {
        if std::io::IsTerminal::is_terminal(&std::io::stdin()) {
            // Docker and devcontainers often allocate a pseudo-TTY on stdin.
            // Non-TTY behavior is covered by confirm_prompt_non_tty_returns_false.
            return;
        }
        let g = GlobalFlags {
            confirm: true,
            ..GlobalFlags::default()
        };
        assert!(!g.should_apply());
    }

    #[test]
    fn merge_write_copies_confirm() {
        let w = WriteFlags {
            confirm: true,
            ..WriteFlags::default()
        };
        let mut g = GlobalFlags::default();
        g.merge_write(&w);
        assert!(g.confirm);
    }

    #[test]
    fn verbose_flag_defaults_to_false() {
        let g = GlobalFlags::default();
        assert!(!g.verbose);
    }

    #[test]
    fn resolve_cwd_nonexistent_errors() {
        let g = GlobalFlags {
            cwd: Some("/nonexistent/path/that/does/not/exist".into()),
            ..GlobalFlags::default()
        };
        let err = g.resolve_cwd().unwrap_err().to_string();
        assert!(err.contains("does not exist"), "unexpected: {err}");
    }

    #[test]
    fn resolve_cwd_not_a_directory_errors() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("file.txt");
        std::fs::write(&file, "x").unwrap();
        let g = GlobalFlags {
            cwd: Some(file.to_string_lossy().into_owned()),
            ..GlobalFlags::default()
        };
        let err = g.resolve_cwd().unwrap_err().to_string();
        assert!(err.contains("not a directory"), "unexpected: {err}");
    }
}