patchloom 0.37.6

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
use crate::cli::global::GlobalFlags;
use crate::cmd::output::execute_via_engine;
use crate::plan::Operation;
use clap::Args;
use serde::Serialize;

#[derive(Debug, Args)]
#[command(after_help = "\
EXAMPLES:
  patchloom append tests/integration.rs --content 'fn new_test() {}' --apply
  echo 'new content' | patchloom append tests/integration.rs --stdin --apply

NOTES:
  If the file does not already end with a newline, append inserts the file's
  line ending before --content so the new text starts on its own line.")]
pub struct AppendArgs {
    /// Path of the file to append to.
    pub file: String,
    /// Content to append (alternative to --stdin).
    /// If the file does not already end with a newline, the file's line ending
    /// is inserted first.
    #[arg(long)]
    pub content: Option<String>,
    /// Read content from stdin.
    #[arg(long)]
    pub stdin: bool,
    #[command(flatten)]
    pub write: crate::cli::global::WriteFlags,
}

pub fn run(args: AppendArgs, global: &GlobalFlags) -> anyhow::Result<u8> {
    run_content_inject(
        &args.file,
        args.content.as_deref(),
        args.stdin,
        ContentPosition::Append,
        global,
    )
}

// ---------------------------------------------------------------------------
// Shared append/prepend implementation
// ---------------------------------------------------------------------------

pub(crate) enum ContentPosition {
    Append,
    Prepend,
}

#[derive(Debug, Serialize)]
struct ContentInjectOutput {
    ok: bool,
    path: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    diff: Option<String>,
    #[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>,
}

pub(crate) fn run_content_inject(
    file: &str,
    content: Option<&str>,
    stdin: bool,
    position: ContentPosition,
    global: &GlobalFlags,
) -> anyhow::Result<u8> {
    let verb = match position {
        ContentPosition::Append => "append",
        ContentPosition::Prepend => "prepend",
    };

    crate::verbose!("{verb}: file={file}");
    if content.is_some() && stdin {
        let msg = "--content and --stdin cannot be combined";
        global.emit_error_json_kind(Some("invalid_input"), msg)?;
        return Ok(crate::exit::FAILURE);
    }

    let inject_content = if let Some(c) = content {
        c.to_string()
    } else if stdin {
        std::io::read_to_string(std::io::stdin())?
    } else {
        let msg = "either --content or --stdin must be provided";
        global.emit_error_json_kind(Some("invalid_input"), msg)?;
        return Ok(crate::exit::FAILURE);
    };

    let cwd = global.resolve_cwd()?;
    // Containment + absolute-path rewrite before existence checks (#1931).
    let file = global.rewrite_user_path_arg(&cwd, file)?;
    let file = file.as_str();
    let path = cwd.join(file);
    // Entry presence (not Path::exists follow): dangling symlink is present
    // like create/delete/rename (#2087 dual-path), not not_found.
    use crate::ops::file::{
        PathEntryKind, classify_path_entry, is_followed_content_file, path_entry_exists,
    };
    if !path_entry_exists(&path) {
        let msg = format!("file does not exist: {file}");
        global.emit_error_json_kind(Some("not_found"), &msg)?;
        return Ok(crate::exit::FAILURE);
    }
    match classify_path_entry(&path) {
        PathEntryKind::RegularFile => {}
        PathEntryKind::Missing => {
            let msg = format!("file does not exist: {file}");
            global.emit_error_json_kind(Some("not_found"), &msg)?;
            return Ok(crate::exit::FAILURE);
        }
        PathEntryKind::Special if is_followed_content_file(&path) => {}
        _ => {
            // Dangling/symlink-to-dir/FIFO/dir: content ops need a regular file.
            let msg = format!("target is not a file: {file}");
            global.emit_error_json_kind(Some("invalid_input"), &msg)?;
            return Ok(crate::exit::FAILURE);
        }
    }
    // Fail before the engine so --json gets error_kind and binaries are not
    // rewritten as text (NUL is valid UTF-8).
    if let Err(e) = crate::ops::file::ensure_not_binary_file(&path, file) {
        global.emit_error_json_kind(Some("binary"), &e.msg)?;
        return Ok(crate::exit::FAILURE);
    }

    let op = match position {
        ContentPosition::Append => Operation::FileAppend {
            path: file.to_string(),
            content: inject_content,
        },
        ContentPosition::Prepend => Operation::FilePrepend {
            path: file.to_string(),
            content: inject_content,
        },
    };

    let check_msg = format!("would {verb} to {file}");
    let apply_msg = format!("{verb}ed to {file}");
    let file_owned = file.to_string();

    execute_via_engine(
        op,
        global,
        |phase, diff, _backup| ContentInjectOutput {
            ok: true,
            path: file_owned.clone(),
            diff,
            applied: phase.applied_flag(),
            backup_session: _backup,
        },
        &check_msg,
        &apply_msg,
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::exit;
    use std::fs;
    use tempfile::TempDir;

    #[test]
    fn append_adds_content_to_existing_file() {
        let dir = TempDir::new().unwrap();
        let file = dir.path().join("test.txt");
        fs::write(&file, "line one\n").unwrap();

        let args = AppendArgs {
            file: file.to_string_lossy().into_owned(),
            content: Some("line two\n".to_string()),
            stdin: false,
            write: Default::default(),
        };
        let global = GlobalFlags::test_apply();

        let code = run(args, &global).unwrap();
        assert_eq!(code, exit::SUCCESS);

        let content = fs::read_to_string(&file).unwrap();
        assert_eq!(content, "line one\nline two\n");
    }

    #[test]
    fn append_help_mentions_separator_newline() {
        use clap::CommandFactory;
        let cmd = crate::cli::Cli::command();
        let append = cmd.find_subcommand("append").expect("append");
        let mut buf = Vec::new();
        append.clone().write_long_help(&mut buf).unwrap();
        let help = String::from_utf8(buf).unwrap();
        assert!(
            help.contains("line ending") && help.contains("newline"),
            "append --help must mention the separator newline (#2199):\n{help}"
        );
    }

    #[test]
    fn append_inserts_newline_if_file_lacks_trailing_newline() {
        let dir = TempDir::new().unwrap();
        let file = dir.path().join("test.txt");
        fs::write(&file, "no trailing newline").unwrap();

        let args = AppendArgs {
            file: file.to_string_lossy().into_owned(),
            content: Some("appended\n".to_string()),
            stdin: false,
            write: Default::default(),
        };
        let global = GlobalFlags::test_apply();

        let code = run(args, &global).unwrap();
        assert_eq!(code, exit::SUCCESS);

        let content = fs::read_to_string(&file).unwrap();
        assert_eq!(content, "no trailing newline\nappended\n");
    }

    #[test]
    fn append_fails_if_file_does_not_exist() {
        let dir = TempDir::new().unwrap();
        let file = dir.path().join("missing.txt");

        let args = AppendArgs {
            file: file.to_string_lossy().into_owned(),
            content: Some("content\n".to_string()),
            stdin: false,
            write: Default::default(),
        };

        let code = run(args, &GlobalFlags::default()).unwrap();
        assert_eq!(code, exit::FAILURE);
    }

    #[test]
    fn append_check_returns_exit_2() {
        let dir = TempDir::new().unwrap();
        let file = dir.path().join("test.txt");
        fs::write(&file, "existing\n").unwrap();

        let args = AppendArgs {
            file: file.to_string_lossy().into_owned(),
            content: Some("new\n".to_string()),
            stdin: false,
            write: Default::default(),
        };
        let mut global = GlobalFlags::test_default();
        global.check = true;

        let code = run(args, &global).unwrap();
        assert_eq!(code, exit::CHANGES_DETECTED);

        // File should be unchanged.
        assert_eq!(fs::read_to_string(&file).unwrap(), "existing\n");
    }

    #[test]
    fn append_rejects_content_and_stdin_together() {
        let dir = TempDir::new().unwrap();
        let file = dir.path().join("test.txt");
        fs::write(&file, "existing\n").unwrap();

        let args = AppendArgs {
            file: file.to_string_lossy().into_owned(),
            content: Some("inline\n".to_string()),
            stdin: true,
            write: Default::default(),
        };

        let code = run(args, &GlobalFlags::default()).unwrap();
        assert_eq!(code, exit::FAILURE);
    }

    #[test]
    fn append_requires_content_or_stdin() {
        let dir = TempDir::new().unwrap();
        let file = dir.path().join("test.txt");
        fs::write(&file, "existing\n").unwrap();

        let args = AppendArgs {
            file: file.to_string_lossy().into_owned(),
            content: None,
            stdin: false,
            write: Default::default(),
        };

        let code = run(args, &GlobalFlags::default()).unwrap();
        assert_eq!(code, exit::FAILURE);
    }

    #[test]
    fn append_rejects_directory_target() {
        let dir = TempDir::new().unwrap();
        let target = dir.path().join("folder");
        fs::create_dir(&target).unwrap();

        let args = AppendArgs {
            file: target.to_string_lossy().into_owned(),
            content: Some("content\n".to_string()),
            stdin: false,
            write: Default::default(),
        };

        let code = run(args, &GlobalFlags::default()).unwrap();
        assert_eq!(code, exit::FAILURE);
    }

    #[cfg(unix)]
    #[test]
    fn append_rejects_dangling_symlink_as_invalid_input() {
        let dir = TempDir::new().unwrap();
        let link = dir.path().join("dangling.txt");
        std::os::unix::fs::symlink(dir.path().join("missing-target"), &link).unwrap();

        let args = AppendArgs {
            file: link.to_string_lossy().into_owned(),
            content: Some("content\n".to_string()),
            stdin: false,
            write: Default::default(),
        };
        let mut global = GlobalFlags::test_with_cwd(dir.path());
        global.json = true;

        let code = run(args, &global).unwrap();
        assert_eq!(code, exit::FAILURE);
        // Dangling is present: invalid_input, not not_found (matches create/delete).
        assert!(crate::ops::file::path_entry_exists(&link));
    }

    #[test]
    fn append_rejects_binary_file() {
        let dir = TempDir::new().unwrap();
        let file = dir.path().join("data.bin");
        fs::write(&file, b"hello\x00world").unwrap();

        let args = AppendArgs {
            file: file.to_string_lossy().into_owned(),
            content: Some("evil\n".into()),
            stdin: false,
            write: Default::default(),
        };
        let mut global = GlobalFlags::test_with_cwd(dir.path());
        global.apply = true;

        let code = run(args, &global).unwrap();
        assert_eq!(code, exit::FAILURE);
        assert_eq!(fs::read(&file).unwrap(), b"hello\x00world");
    }

    #[cfg(unix)]
    #[test]
    fn append_symlink_to_text_apply_writes_target() {
        let dir = TempDir::new().unwrap();
        let real = dir.path().join("real.txt");
        fs::write(&real, "hello\n").unwrap();
        let link = dir.path().join("link.txt");
        std::os::unix::fs::symlink(&real, &link).unwrap();

        let args = AppendArgs {
            file: link.to_string_lossy().into_owned(),
            content: Some("X\n".to_string()),
            stdin: false,
            write: Default::default(),
        };
        let mut global = GlobalFlags::test_with_cwd(dir.path());
        global.apply = true;

        let code = run(args, &global).unwrap();
        assert_eq!(code, exit::SUCCESS);
        let text = fs::read_to_string(&real).unwrap();
        assert!(text.contains("hello"), "target must keep hello: {text}");
        assert!(text.contains('X'), "target must contain X: {text}");
        assert_eq!(text, "hello\nX\n");
        assert!(
            link.symlink_metadata().unwrap().file_type().is_symlink(),
            "link must still be a symlink"
        );
    }

    #[cfg(unix)]
    #[test]
    fn append_symlink_to_text_preview_leaves_target() {
        let dir = TempDir::new().unwrap();
        let real = dir.path().join("real.txt");
        fs::write(&real, "hello\n").unwrap();
        let link = dir.path().join("link.txt");
        std::os::unix::fs::symlink(&real, &link).unwrap();

        let args = AppendArgs {
            file: link.to_string_lossy().into_owned(),
            content: Some("X\n".to_string()),
            stdin: false,
            write: Default::default(),
        };
        let global = GlobalFlags::test_with_cwd(dir.path());

        let code = run(args, &global).unwrap();
        assert_eq!(code, exit::CHANGES_DETECTED);
        assert_eq!(fs::read(&real).unwrap(), b"hello\n");
        assert!(link.symlink_metadata().unwrap().file_type().is_symlink());
    }

    #[cfg(unix)]
    #[test]
    fn append_symlink_to_binary_apply_leaves_target() {
        let dir = TempDir::new().unwrap();
        let real = dir.path().join("real.bin");
        fs::write(&real, b"hello\x00world").unwrap();
        let link = dir.path().join("link.bin");
        std::os::unix::fs::symlink(&real, &link).unwrap();

        let args = AppendArgs {
            file: link.to_string_lossy().into_owned(),
            content: Some("Z\n".to_string()),
            stdin: false,
            write: Default::default(),
        };
        let mut global = GlobalFlags::test_with_cwd(dir.path());
        global.apply = true;

        let code = run(args, &global).unwrap();
        assert_eq!(code, exit::FAILURE);
        assert_eq!(fs::read(&real).unwrap(), b"hello\x00world");
        assert!(link.symlink_metadata().unwrap().file_type().is_symlink());
    }

    #[test]
    fn prepend_rejects_binary_file() {
        let dir = TempDir::new().unwrap();
        let file = dir.path().join("data.bin");
        fs::write(&file, b"hello\x00world").unwrap();

        let code = run_content_inject(
            &file.to_string_lossy(),
            Some("evil\n"),
            false,
            ContentPosition::Prepend,
            &GlobalFlags {
                apply: true,
                ..GlobalFlags::test_with_cwd(dir.path())
            },
        )
        .unwrap();
        assert_eq!(code, exit::FAILURE);
        assert_eq!(fs::read(&file).unwrap(), b"hello\x00world");
    }
}