atomwrite 0.1.14

Atomic file operations CLI for LLM agents — read, write, edit, search, replace with NDJSON output
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
// SPDX-License-Identifier: MIT OR Apache-2.0

mod common;

#[test]
fn batch_write_creates_file() {
    let dir = tempfile::tempdir().expect("tempdir");
    let target = dir.path().join("batch_out.txt");

    let manifest = common::manifest(&[serde_json::json!({
        "op": "write",
        "target": target.to_string_lossy(),
        "content": "hello batch",
    })]);

    let output = common::atomwrite()
        .args(["--workspace", dir.path().to_str().unwrap(), "batch"])
        .write_stdin(manifest)
        .output()
        .expect("run");

    assert!(
        output.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let events = common::parse_ndjson(&output.stdout);

    let op = events
        .iter()
        .find(|e| e["type"] == "batch_op")
        .expect("batch_op event");
    assert_eq!(op["op"], "write");
    assert_eq!(op["status"], "ok");

    let summary = events
        .iter()
        .find(|e| e["type"] == "summary")
        .expect("summary");
    assert_eq!(summary["operations"], 1);
    assert_eq!(summary["succeeded"], 1);
    assert_eq!(summary["failed"], 0);

    let content = std::fs::read_to_string(&target).expect("read");
    assert_eq!(content, "hello batch");
}

#[test]
fn batch_replace_modifies_file() {
    let dir = tempfile::tempdir().expect("tempdir");
    let target = dir.path().join("replace_me.txt");
    std::fs::write(&target, "old_value here\n").expect("write");

    let manifest = common::manifest(&[serde_json::json!({
        "op": "replace",
        "target": target.to_string_lossy(),
        "pattern": "old_value",
        "replacement": "new_value",
    })]);

    let output = common::atomwrite()
        .args(["--workspace", dir.path().to_str().unwrap(), "batch"])
        .write_stdin(manifest)
        .output()
        .expect("run");

    assert!(output.status.success());

    let content = std::fs::read_to_string(&target).expect("read");
    assert!(content.contains("new_value"));
    assert!(!content.contains("old_value"));
}

#[test]
fn batch_delete_removes_file() {
    let dir = tempfile::tempdir().expect("tempdir");
    let target = dir.path().join("to_delete.txt");
    std::fs::write(&target, "delete me\n").expect("write");

    let manifest = common::manifest(&[serde_json::json!({
        "op": "delete",
        "target": target.to_string_lossy(),
    })]);

    let output = common::atomwrite()
        .args(["--workspace", dir.path().to_str().unwrap(), "batch"])
        .write_stdin(manifest)
        .output()
        .expect("run");

    assert!(output.status.success());
    assert!(!target.exists());
}

#[test]
fn batch_dry_run_does_not_modify() {
    let dir = tempfile::tempdir().expect("tempdir");
    let target = dir.path().join("keep.txt");
    let original = "keep me\n";
    std::fs::write(&target, original).expect("write");

    let manifest = common::manifest(&[serde_json::json!({
        "op": "replace",
        "target": target.to_string_lossy(),
        "pattern": "keep",
        "replacement": "gone",
    })]);

    let output = common::atomwrite()
        .args([
            "--workspace",
            dir.path().to_str().unwrap(),
            "batch",
            "--dry-run",
        ])
        .write_stdin(manifest)
        .output()
        .expect("run");

    assert!(output.status.success());
    let content = std::fs::read_to_string(&target).expect("read");
    assert_eq!(content, original);
}

#[test]
fn batch_multiple_operations() {
    let dir = tempfile::tempdir().expect("tempdir");
    let file_a = dir.path().join("a.txt");
    let file_b = dir.path().join("b.txt");
    std::fs::write(&file_b, "original_b\n").expect("write");

    let manifest = common::manifest(&[
        serde_json::json!({
            "op": "write",
            "target": file_a.to_string_lossy(),
            "content": "content_a",
        }),
        serde_json::json!({
            "op": "replace",
            "target": file_b.to_string_lossy(),
            "pattern": "original_b",
            "replacement": "modified_b",
        }),
    ]);

    let output = common::atomwrite()
        .args(["--workspace", dir.path().to_str().unwrap(), "batch"])
        .write_stdin(manifest)
        .output()
        .expect("run");

    assert!(output.status.success());
    let events = common::parse_ndjson(&output.stdout);

    let summary = events
        .iter()
        .find(|e| e["type"] == "summary")
        .expect("summary");
    assert_eq!(summary["operations"], 2);
    assert_eq!(summary["succeeded"], 2);

    assert_eq!(std::fs::read_to_string(&file_a).expect("a"), "content_a");
    assert!(
        std::fs::read_to_string(&file_b)
            .expect("b")
            .contains("modified_b")
    );
}

#[test]
fn batch_invalid_op_fails() {
    let dir = tempfile::tempdir().expect("tempdir");

    let manifest = r#"{"op":"nonexistent","target":"foo.txt"}"#;

    let output = common::atomwrite()
        .args(["--workspace", dir.path().to_str().unwrap(), "batch"])
        .write_stdin(manifest)
        .output()
        .expect("run");

    assert!(!output.status.success());
    let events = common::parse_ndjson(&output.stdout);
    let op = events
        .iter()
        .find(|e| e["type"] == "batch_op")
        .expect("batch_op");
    assert_eq!(op["status"], "failed");
}

#[test]
fn batch_empty_manifest_fails() {
    let dir = tempfile::tempdir().expect("tempdir");

    let output = common::atomwrite()
        .args(["--workspace", dir.path().to_str().unwrap(), "batch"])
        .write_stdin("")
        .output()
        .expect("run");

    assert!(!output.status.success());
}

// --- GAP 03: campo source com aliases ---

#[test]
fn batch_move_with_source_target() {
    let dir = tempfile::tempdir().expect("tempdir");
    let src = common::create_test_file(dir.path(), "origin.txt", "move me\n");
    let dest = dir.path().join("destination.txt");

    let manifest = common::manifest(&[serde_json::json!({
        "op": "move",
        "source": src.to_string_lossy(),
        "target": dest.to_string_lossy(),
    })]);

    let output = common::atomwrite()
        .args(["--workspace", dir.path().to_str().unwrap(), "batch"])
        .write_stdin(manifest)
        .output()
        .expect("run");

    assert!(
        output.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert!(!src.exists(), "source should be removed after move");
    assert!(dest.exists(), "destination should exist after move");
    assert_eq!(std::fs::read_to_string(&dest).unwrap(), "move me\n");
}

#[test]
fn batch_copy_with_source_target() {
    let dir = tempfile::tempdir().expect("tempdir");
    let src = common::create_test_file(dir.path(), "src_copy.txt", "copy me\n");
    let dest = dir.path().join("dst_copy.txt");

    let manifest = common::manifest(&[serde_json::json!({
        "op": "copy",
        "source": src.to_string_lossy(),
        "target": dest.to_string_lossy(),
    })]);

    let output = common::atomwrite()
        .args(["--workspace", dir.path().to_str().unwrap(), "batch"])
        .write_stdin(manifest)
        .output()
        .expect("run");

    assert!(
        output.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert!(src.exists(), "source should still exist after copy");
    assert!(dest.exists(), "destination should exist after copy");
    assert_eq!(std::fs::read_to_string(&dest).unwrap(), "copy me\n");
}

#[test]
fn batch_move_with_from_alias() {
    let dir = tempfile::tempdir().expect("tempdir");
    let src = common::create_test_file(dir.path(), "from_file.txt", "alias test\n");
    let dest = dir.path().join("to_file.txt");

    let manifest = common::manifest(&[serde_json::json!({
        "op": "move",
        "from": src.to_string_lossy(),
        "target": dest.to_string_lossy(),
    })]);

    let output = common::atomwrite()
        .args(["--workspace", dir.path().to_str().unwrap(), "batch"])
        .write_stdin(manifest)
        .output()
        .expect("run");

    assert!(
        output.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert!(!src.exists());
    assert_eq!(std::fs::read_to_string(&dest).unwrap(), "alias test\n");
}

// --- GAP 04: path como alias de target ---

#[test]
fn batch_write_with_path_alias() {
    let dir = tempfile::tempdir().expect("tempdir");
    let target = dir.path().join("path_alias.txt");

    let manifest = common::manifest(&[serde_json::json!({
        "op": "write",
        "path": target.to_string_lossy(),
        "content": "via path field",
    })]);

    let output = common::atomwrite()
        .args(["--workspace", dir.path().to_str().unwrap(), "batch"])
        .write_stdin(manifest)
        .output()
        .expect("run");

    assert!(
        output.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert_eq!(std::fs::read_to_string(&target).unwrap(), "via path field");
}

#[test]
fn batch_delete_with_path_alias() {
    let dir = tempfile::tempdir().expect("tempdir");
    let target = common::create_test_file(dir.path(), "to_del.txt", "del me\n");

    let manifest = common::manifest(&[serde_json::json!({
        "op": "delete",
        "path": target.to_string_lossy(),
    })]);

    let output = common::atomwrite()
        .args(["--workspace", dir.path().to_str().unwrap(), "batch"])
        .write_stdin(manifest)
        .output()
        .expect("run");

    assert!(
        output.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert!(!target.exists(), "file should be deleted via path alias");
}

#[test]
fn batch_move_legacy_compat() {
    let dir = tempfile::tempdir().expect("tempdir");
    let src = common::create_test_file(dir.path(), "legacy_src.txt", "legacy\n");
    let dest = dir.path().join("legacy_dst.txt");

    // Legacy workaround: path=source (via fallback), target=destination
    // Since resolve: source.or(path) for source, target for destination
    // But legacy used target=source, path=destination — this should still work
    // because the new code reads source first, falls back to path
    // If source is absent and path is present, path becomes source
    // and target becomes destination. This is the NEW correct behavior.
    let manifest = common::manifest(&[serde_json::json!({
        "op": "move",
        "path": src.to_string_lossy(),
        "target": dest.to_string_lossy(),
    })]);

    let output = common::atomwrite()
        .args(["--workspace", dir.path().to_str().unwrap(), "batch"])
        .write_stdin(manifest)
        .output()
        .expect("run");

    assert!(
        output.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
}

// Known limitation: batch --transaction rollback does NOT remove files
// CREATED during the transaction. This test documents the behavior.
#[test]
fn batch_transaction_rollback_preserves_created_files() {
    let dir = tempfile::tempdir().expect("tempdir");
    let created = dir.path().join("created_in_tx.txt");
    let existing = common::create_test_file(dir.path(), "existing.txt", "original\n");

    // First op creates a new file (succeeds), second op targets nonexistent
    // file for replace (fails) — triggering transaction rollback.
    let manifest = common::manifest(&[
        serde_json::json!({
            "op": "write",
            "target": created.to_string_lossy(),
            "content": "new file",
        }),
        serde_json::json!({
            "op": "replace",
            "target": dir.path().join("does_not_exist.txt").to_string_lossy(),
            "pattern": "nonexistent_pattern_xyz",
            "replacement": "x",
        }),
    ]);

    let _output = common::atomwrite()
        .args([
            "--workspace",
            dir.path().to_str().unwrap(),
            "batch",
            "--transaction",
        ])
        .write_stdin(manifest)
        .output()
        .expect("run");

    // Transaction may or may not fail depending on how replace handles
    // nonexistent files. The key assertion is about the created file.
    let existing_content = std::fs::read_to_string(&existing).expect("read existing");
    assert_eq!(
        existing_content, "original\n",
        "existing file should be restored by rollback"
    );

    // Known limitation: created_in_tx.txt may still exist after rollback
    // because the transaction rollback mechanism only restores pre-existing
    // files from backup, it does not track and remove newly created files.
    if created.exists() {
        eprintln!(
            "NOTE: known limitation — file created during transaction persists after rollback"
        );
    }
}

// --- GAP 23: regression for Windows path backslash in JSON manifests ---

/// Regression test that catches the Windows backslash-in-JSON bug on any
/// platform. Builds a manifest whose target path string contains a literal
/// backslash (the kind Windows paths contain natively), and confirms the
/// batch command parses it without error. Before the fix, this test fails
/// on every platform because the handcrafted `format!` + `display()`
/// pattern does not escape backslashes inside JSON strings.
#[test]
fn batch_write_escapes_backslash_in_target_path() {
    let dir = tempfile::tempdir().expect("tempdir");
    // Force a backslash into the path string even on non-Windows platforms.
    let target = format!("{}/with\\backslash.txt", dir.path().display());

    let manifest = common::manifest(&[serde_json::json!({
        "op": "write",
        "target": target,
        "content": "backslash ok",
    })]);

    let output = common::atomwrite()
        .args(["--workspace", dir.path().to_str().unwrap(), "batch"])
        .write_stdin(manifest)
        .output()
        .expect("run");

    assert!(
        output.status.success(),
        "backslash in target path must be JSON-escaped; stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let events = common::parse_ndjson(&output.stdout);
    let op = events
        .iter()
        .find(|e| e["type"] == "batch_op")
        .expect("batch_op event");
    assert_eq!(op["status"], "ok");
}