logmv 0.7.1

Logged atomic file move and trash with an append-only JSON-Lines audit trail
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
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
//! Logged atomic file move and trash with an append-only JSON-Lines audit trail.
//!
//! `logmv` renames a file, or moves it to a trash directory, and records the
//! operation as one compact JSON line per action so every change is auditable.
//! Moves are atomic renames only (never a copy fallback), never overwrite an
//! existing destination, and trash never unlinks. See [`run`] for the
//! orchestration and [`Op`] for the operations it performs.
//!
//! # Platform support
//!
//! logmv supports only macOS and Linux. The crate bakes in macOS/Linux-specific
//! assumptions: `EXDEV` == raw OS error 18, `'/'` path separators (see
//! `ends_with_sep`), and the `~/.Trash` move model (resolved in `main.rs`). Other
//! platforms differ on all three, so a non-macOS/Linux build is rejected at
//! compile time via `compile_error!` rather than silently misbehaving. The guard
//! lives here; the binary depends on the library, so it is guarded transitively.
//!
//! One further Linux-only divergence affects log fidelity, not the move itself.
//! The rename is byte-faithful: it uses the real `OsStr` bytes (see
//! `path_to_cstring`), so a non-UTF-8 filename is moved correctly. The log,
//! however, records `src` and `dst` via `to_string_lossy`, so on Linux each
//! invalid UTF-8 byte is written as U+FFFD (the Unicode replacement character);
//! JSON strings must be valid Unicode, so the raw bytes cannot be stored
//! verbatim. A log line whose `src` or `dst` contains U+FFFD is therefore not a
//! byte-exact record and is not reliably reversible. macOS (APFS/HFS+)
//! enforces UTF-8, so this case is unreachable there.

#![warn(missing_docs)]

#[cfg(not(any(target_os = "macos", target_os = "linux")))]
compile_error!("logmv supports only macOS and Linux");

use std::ffi::CString;
use std::ffi::OsStr;
use std::ffi::c_char;
use std::ffi::c_int;
use std::ffi::c_uint;
use std::fs;
use std::fs::OpenOptions;
use std::io;
use std::io::Write;
use std::path::Path;
use std::path::PathBuf;

use chrono::DateTime;
use chrono::FixedOffset;
use chrono::SecondsFormat;
use serde_json::Map;
use serde_json::Value;

/// EXDEV (cross-device link) is raw os error 18 on macOS and Linux.
const EXDEV: i32 = 18;

/// EEXIST (destination already exists) is raw os error 17 on macOS and Linux.
const EEXIST: i32 = 17;

/// The four keys `logmv` stamps itself; metadata pairs may never use them (AC13).
const CANONICAL_KEYS: [&str; 4] = ["ts", "act", "src", "dst"];

/// A file-system operation for logmv to perform.
pub enum Op {
    /// Move `src` to `dst` via an atomic rename, then log a `move` line.
    Move {
        /// Source path to move (canonicalized to absolute when logged).
        src: PathBuf,
        /// Destination path; an existing dir (or trailing `/`) means move *into* it.
        dst: PathBuf,
    },
    /// Move `path` into `trash_dir`, disambiguating on name collision, then log a `trash` line.
    Trash {
        /// Path to send to the trash.
        path: PathBuf,
        /// Trash directory to move `path` into (e.g. `~/.Trash`).
        trash_dir: PathBuf,
    },
}

/// Typed errors for logmv operations.
#[derive(Debug, thiserror::Error)]
pub enum Error {
    /// The resolved destination already exists; the move was refused (never overwrite).
    #[error("destination already exists: {0}")]
    DestinationExists(PathBuf),
    /// The rename crossed filesystems (`EXDEV`); logmv never falls back to a copy.
    #[error("cross-volume rename not supported (EXDEV)")]
    CrossVolume,
    /// The `rename` syscall failed for a reason other than a cross-volume move.
    #[error("rename failed: {0}")]
    Rename(#[source] io::Error),
    /// The move succeeded but the log append failed: filesystem and log may have drifted.
    #[error("move succeeded but log append failed: filesystem and log may have drifted: {0}")]
    DriftAfterMove(#[source] io::Error),
    /// A `--mkdir` directory creation failed; any partially created directories are unlogged.
    #[error("directory creation failed; any partially created directories are unlogged: {0}")]
    MkdirCreate(#[source] io::Error),
    /// A `--mkdir` directory was created but its log append failed: filesystem and log may have drifted.
    #[error("directories created but log append failed: filesystem and log may have drifted: {0}")]
    DriftAfterMkdir(#[source] io::Error),
    /// A `--rmdir` directory removal's log append failed: filesystem and log may have drifted.
    #[error(
        "directory removed but its log append failed: filesystem and log may have drifted: {0}"
    )]
    DriftAfterRmdir(#[source] io::Error),
    /// Resolving a path to its canonical absolute form failed.
    #[error("canonicalize failed: {0}")]
    Canonicalize(#[source] io::Error),
    /// A metadata key collided with a canonical key (`ts`/`act`/`src`/`dst`).
    #[error("metadata key collides with canonical key: {0}")]
    MetadataKeyCollision(String),
}

/// Assemble one compact JSON-Lines entry from the given fields.
///
/// `ts` is injected (not read from a clock) so this function is pure and
/// deterministically testable. `src`/`dst` must already be absolute strings.
/// For trash ops, `dst` is the canonical landing path under the trash dir
/// (the disambiguated target), just like move.
/// Refuses any pair whose key is a canonical key (ts/act/src/dst) via
/// `Error::MetadataKeyCollision` (AC13). Canonical four are written first,
/// then pairs in the given order, all values as JSON strings.
fn build_entry(
    ts: DateTime<FixedOffset>,
    act: &str,
    src: &str,
    dst: &str,
    pairs: &[(&str, &str)],
) -> Result<String, Error> {
    // Refuse before assembling anything: a colliding key must yield no line
    // (and, via `run`, no move and no log).
    if let Some(key) = first_colliding_key(pairs) {
        return Err(Error::MetadataKeyCollision(key.to_string()));
    }

    let mut map = Map::new();
    map.insert(
        "ts".to_string(),
        Value::String(ts.to_rfc3339_opts(SecondsFormat::Secs, false)),
    );
    map.insert("act".to_string(), Value::String(act.to_string()));
    map.insert("src".to_string(), Value::String(src.to_string()));
    map.insert("dst".to_string(), Value::String(dst.to_string()));
    // Pairs follow the canonical four in given order (serde_json `preserve_order`),
    // every value a JSON string; serde owns all key/value escaping (AC6).
    for (k, v) in pairs {
        map.insert((*k).to_string(), Value::String((*v).to_string()));
    }

    Ok(Value::Object(map).to_string())
}

/// Return the first metadata key that collides with a canonical key, if any.
/// Single source of truth for the collision guard: `build_entry` runs it before
/// assembling a line, and `run` runs it early so a bad pair aborts before any
/// `--mkdir` mutation (AC11).
fn first_colliding_key<'a>(pairs: &'a [(&str, &str)]) -> Option<&'a str> {
    pairs
        .iter()
        .find(|(k, _)| CANONICAL_KEYS.contains(k))
        .map(|(k, _)| *k)
}

/// Map an `io::Error` from `fs::rename` to a typed `Error`.
///
/// EXDEV (raw os error 18) → `Error::CrossVolume`.
/// Anything else → `Error::Rename`.
fn classify_rename_err(err: io::Error) -> Error {
    if err.raw_os_error() == Some(EXDEV) {
        Error::CrossVolume
    } else {
        Error::Rename(err)
    }
}

/// `AT_FDCWD`: resolve a relative `renameat2` path against the current working
/// directory, matching the relative-path semantics `fs::rename` has today.
#[cfg(target_os = "linux")]
const AT_FDCWD: c_int = -100;

/// `RENAME_NOREPLACE`: fail with `EEXIST` rather than clobbering an existing
/// destination entry (name-level; a symlink is not followed).
#[cfg(target_os = "linux")]
const RENAME_NOREPLACE: c_uint = 1;

/// `RENAME_EXCL`: macOS exclusive-create flag from `<sys/stdio.h>`
/// (`RENAME_SECLUDE 0x1`, `RENAME_SWAP 0x2`, `RENAME_EXCL 0x4`); fail with
/// `EEXIST` rather than clobbering an existing destination entry.
#[cfg(target_os = "macos")]
const RENAME_EXCL: c_uint = 0x0000_0004;

/// Convert a path to a NUL-terminated C string for the `renameat2`/`renamex_np`
/// FFI, via raw bytes (never a lossy `String`, so non-UTF-8 paths pass through
/// unchanged). An interior NUL yields a clean `InvalidInput` error rather than
/// an `unwrap`/`expect` on the write path.
fn path_to_cstring(p: &Path) -> io::Result<CString> {
    use std::os::unix::ffi::OsStrExt;
    CString::new(p.as_os_str().as_bytes())
        .map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))
}

/// Atomically rename `from` to `to`, refusing to clobber an existing destination
/// entry (name-level; a symlink is not followed).
///
/// Returns `Ok(())` on success, or `Err(io::Error::last_os_error())` carrying the
/// raw `errno` so callers can test `raw_os_error() == Some(EEXIST)` and still route
/// `EXDEV` and others through [`classify_rename_err`]. Classifies nothing itself,
/// mirroring today's `fs::rename(...).map_err(classify_rename_err)` split of
/// mechanism from policy.
#[cfg(target_os = "linux")]
fn rename_noclobber(from: &Path, to: &Path) -> io::Result<()> {
    // NOTE: libc renameat2 wrapper (glibc >=2.28); drop to a raw syscall() only
    // if a target without the wrapper (e.g. an old musl) is ever added to CI.
    unsafe extern "C" {
        fn renameat2(
            olddirfd: c_int,
            oldpath: *const c_char,
            newdirfd: c_int,
            newpath: *const c_char,
            flags: c_uint,
        ) -> c_int;
    }

    let from_c = path_to_cstring(from)?;
    let to_c = path_to_cstring(to)?;

    // SAFETY:
    // - `from_c`/`to_c` are `CString` locals that outlive the call; `.as_ptr()`
    //   yields non-null pointers to valid, readable, NUL-terminated bytes.
    // - `renameat2` only reads (never retains) the two `*const c_char` pointers;
    //   no Rust aliasing/mutability invariant is exposed (only `*const` passed).
    // - `AT_FDCWD` and `RENAME_NOREPLACE` are the documented kernel sentinel/flag.
    // - the return value is checked immediately and `errno` is read via
    //   `io::Error::last_os_error()` with no intervening libc call between.
    let rc = unsafe {
        renameat2(
            AT_FDCWD,
            from_c.as_ptr(),
            AT_FDCWD,
            to_c.as_ptr(),
            RENAME_NOREPLACE,
        )
    };
    if rc < 0 {
        return Err(io::Error::last_os_error());
    }
    Ok(())
}

/// Atomically rename `from` to `to`, refusing to clobber an existing destination
/// entry (name-level; a symlink is not followed).
///
/// Returns `Ok(())` on success, or `Err(io::Error::last_os_error())` carrying the
/// raw `errno` so callers can test `raw_os_error() == Some(EEXIST)` and still route
/// `EXDEV` and others through [`classify_rename_err`]. Classifies nothing itself,
/// mirroring today's `fs::rename(...).map_err(classify_rename_err)` split of
/// mechanism from policy.
#[cfg(target_os = "macos")]
fn rename_noclobber(from: &Path, to: &Path) -> io::Result<()> {
    unsafe extern "C" {
        fn renamex_np(from: *const c_char, to: *const c_char, flags: c_uint) -> c_int;
    }

    let from_c = path_to_cstring(from)?;
    let to_c = path_to_cstring(to)?;

    // SAFETY:
    // - `from_c`/`to_c` are `CString` locals that outlive the call; `.as_ptr()`
    //   yields non-null pointers to valid, readable, NUL-terminated bytes.
    // - `renamex_np` only reads (never retains) the two `*const c_char` pointers;
    //   no Rust aliasing/mutability invariant is exposed (only `*const` passed).
    // - `RENAME_EXCL` is the documented exclusive-create flag from `<sys/stdio.h>`.
    // - the return value is checked immediately and `errno` is read via
    //   `io::Error::last_os_error()` with no intervening libc call between.
    let rc = unsafe { renamex_np(from_c.as_ptr(), to_c.as_ptr(), RENAME_EXCL) };
    if rc < 0 {
        return Err(io::Error::last_os_error());
    }
    Ok(())
}

/// Canonicalize a destination path that must NOT yet exist: canonicalize the
/// parent directory (which does exist) and rejoin the file name.
fn canonicalize_new(dst: &Path) -> Result<PathBuf, Error> {
    let file_name = dst.file_name().ok_or_else(|| {
        Error::Canonicalize(io::Error::new(
            io::ErrorKind::InvalidInput,
            "destination has no file name",
        ))
    })?;
    let parent = match dst.parent() {
        Some(p) if !p.as_os_str().is_empty() => p,
        _ => Path::new("."),
    };
    let parent_abs = fs::canonicalize(parent).map_err(Error::Canonicalize)?;
    Ok(parent_abs.join(file_name))
}

/// Atomically move `path` into `trash_dir`, never clobbering an existing entry:
/// try `name` as-is, then `<stem>-<n>[.<ext>]` for n = 1,2,3,…, bumping `n` only
/// on `EEXIST` and returning the winning path on the first successful rename.
/// Any other errno is classified via [`classify_rename_err`]. The disambiguation
/// is driven by the atomic rename result (not a pre-scan), so the returned path is
/// exactly the candidate that won the rename.
fn rename_into_trash(path: &Path, trash_dir: &Path, name: &OsStr) -> Result<PathBuf, Error> {
    let first = trash_dir.join(name);
    match rename_noclobber(path, &first) {
        Ok(()) => return Ok(first),
        Err(e) if e.raw_os_error() == Some(EEXIST) => {}
        Err(e) => return Err(classify_rename_err(e)),
    }

    let as_path = Path::new(name);
    let stem = as_path
        .file_stem()
        .unwrap_or(name)
        .to_string_lossy()
        .into_owned();
    let ext = as_path
        .extension()
        .map(|e| e.to_string_lossy().into_owned());

    let mut n = 1u32;
    loop {
        let candidate_name = match &ext {
            Some(ext) => format!("{stem}-{n}.{ext}"),
            None => format!("{stem}-{n}"),
        };
        let candidate = trash_dir.join(candidate_name);
        match rename_noclobber(path, &candidate) {
            Ok(()) => return Ok(candidate),
            Err(e) if e.raw_os_error() == Some(EEXIST) => {}
            Err(e) => return Err(classify_rename_err(e)),
        }
        n += 1;
    }
}

/// Write `line` plus one trailing newline to `w` in a single `write` call, so a
/// log entry can never be split across two syscalls (which two concurrent runs
/// could interleave). Generic over `Write` so it is unit-testable.
fn write_log_line<W: Write>(w: &mut W, line: &str) -> io::Result<()> {
    w.write_all(format!("{line}\n").as_bytes())
}

/// Append exactly one line (with trailing newline) to `log`, creating it if absent,
/// then flush it to disk so the record is at least as durable as the event it logs.
fn append_log(log: &Path, line: &str) -> io::Result<()> {
    let mut file = OpenOptions::new().create(true).append(true).open(log)?;
    write_log_line(&mut file, line)?;
    // NOTE: unconditional sync_data; add --no-sync only if a batch caller measurably needs it.
    file.sync_data()
}

/// Does the path end with a directory separator (explicit directory intent)?
// NOTE: macOS/Linux `'/'` only, consistent with the hardcoded EXDEV const.
fn ends_with_sep(p: &Path) -> bool {
    p.to_string_lossy().ends_with('/')
}

/// Resolve the final move target. When `dst` is an existing directory (or ends
/// with a separator, signalling directory intent), move `src` *into* it keeping
/// its basename: `dst/basename(src)`. Otherwise `dst` is the full target path
/// (today's behavior).
fn resolve_move_target(src: &Path, dst: &Path) -> PathBuf {
    match (ends_with_sep(dst) || dst.is_dir(), src.file_name()) {
        (true, Some(name)) => dst.join(name),
        _ => dst.to_path_buf(),
    }
}

/// `--mkdir`: create the move destination's missing parent chain (`mkdir -p`) and
/// append one `mkdir` line per directory actually created, parent → child, before
/// the move line. A fully-present chain creates nothing and logs nothing (AC6).
/// `mkdir` line carries `src:"-"`, `dst:<created dir>` (Q1 directional sentinel).
fn mkdir_chain(parent: &Path, log: &Path, ts: DateTime<FixedOffset>) -> Result<(), Error> {
    // Missing ancestors, collected child → parent then reversed to parent → child.
    let mut missing: Vec<PathBuf> = Vec::new();
    let mut cur = Some(parent);
    while let Some(dir) = cur {
        if dir.as_os_str().is_empty() || dir.exists() {
            break;
        }
        missing.push(dir.to_path_buf());
        cur = dir.parent();
    }
    if missing.is_empty() {
        return Ok(());
    }
    missing.reverse();

    // create_dir_all is idempotent and never clobbers an existing dir (AC4). A
    // failure may leave partially-created, unlogged dirs, but the requested chain
    // is not confirmed present, so this is not post-create drift.
    fs::create_dir_all(parent).map_err(Error::MkdirCreate)?;

    for dir in &missing {
        // The dirs now exist but are not yet logged; a canonicalize failure here is
        // created-but-not-logged drift, not a generic path-resolution failure.
        let abs = fs::canonicalize(dir).map_err(Error::DriftAfterMkdir)?;
        let line = build_entry(ts, "mkdir", "-", &abs.to_string_lossy(), &[])?;
        // Logged only after the dir exists; an append failure here is real drift.
        append_log(log, &line).map_err(Error::DriftAfterMkdir)?;
    }
    Ok(())
}

/// `--rmdir`: after a successful, logged move/trash, remove the source's now-empty
/// parent and cascade upward, removing each now-empty ancestor and stopping at the
/// first non-empty one (`rmdir -p`). Truly-empty-only: a dir holding `.DS_Store`
/// (or anything) is left in place (AC9). `start` paths come from the canonicalized
/// `abs_src`, so the cascade walks real (non-symlink) ancestors only.
/// `rmdir` line carries `src:<removed dir>`, `dst:"-"` (Q1 directional sentinel).
fn rmdir_cascade(start: Option<&Path>, log: &Path, ts: DateTime<FixedOffset>) -> Result<(), Error> {
    let mut cur = start.map(Path::to_path_buf);
    while let Some(dir) = cur {
        if dir.as_os_str().is_empty() {
            break;
        }
        // Cascade boundary gate: stop at a non-empty (or unreadable) directory.
        match fs::read_dir(&dir) {
            Ok(mut entries) => {
                if entries.next().is_some() {
                    break;
                }
            }
            Err(_) => break,
        }
        // remove_dir is the atomic safety guard: it removes only empty dirs.
        match fs::remove_dir(&dir) {
            Ok(()) => {
                let line = build_entry(ts, "rmdir", &dir.to_string_lossy(), "-", &[])?;
                // Logged only after removal; an append failure here is real drift.
                append_log(log, &line).map_err(Error::DriftAfterRmdir)?;
                cur = dir.parent().map(Path::to_path_buf);
            }
            // NOTE: a remove_dir failure (race repopulation, EACCES) stops the
            // cascade silently; rmdir is best-effort cleanup after a logged move and
            // the dir simply remaining is safe. Upgrade to a stderr warning if
            // cleanup visibility ever matters.
            Err(_) => break,
        }
    }
    Ok(())
}

/// Orchestrate: resolve final dst → never-overwrite + pair-collision check →
/// `--mkdir` (create + log each) → atomic rename → log move/trash → `--rmdir`
/// (remove + log each, cascading).
///
/// `log` is the path to the JSON-Lines file to append to (created if absent).
/// `pairs` are free K/V metadata pairs inserted into the line after the canonical four.
/// `mkdir`/`rmdir` gate the directory-creation / cascading-removal behaviors.
///
/// # Errors
///
/// - [`Error::MetadataKeyCollision`] if any pair key is a canonical key
///   (`ts`/`act`/`src`/`dst`), checked before any mutation, so nothing moves.
/// - [`Error::DestinationExists`] if the resolved target already exists (never overwrite).
/// - [`Error::Canonicalize`] if a source or destination path cannot be resolved.
/// - [`Error::MkdirCreate`] if `--mkdir` fails to create the destination's parent
///   chain; any partially created directories are unlogged.
/// - [`Error::CrossVolume`] or [`Error::Rename`] if the atomic rename fails.
/// - [`Error::DriftAfterMove`], [`Error::DriftAfterMkdir`], or [`Error::DriftAfterRmdir`]
///   if the rename succeeded but a subsequent log append or directory operation
///   failed: the filesystem and the log have drifted, and the error is loud.
///
/// # Examples
///
/// ```no_run
/// use std::path::{Path, PathBuf};
/// use logmv::{run, Op};
///
/// let op = Op::Move {
///     src: PathBuf::from("report.txt"),
///     dst: PathBuf::from("archive.txt"),
/// };
/// run(op, Path::new("ops.log"), &[("by", "cc")], false, false)?;
/// # Ok::<(), logmv::Error>(())
/// ```
pub fn run(
    op: Op,
    log: &Path,
    pairs: &[(&str, &str)],
    mkdir: bool,
    rmdir: bool,
) -> Result<(), Error> {
    let ts = chrono::Local::now().fixed_offset();

    // Early pair-collision check: a colliding key must abort before any --mkdir
    // mutation and before the move (AC11). build_entry re-checks (idempotent).
    if let Some(key) = first_colliding_key(pairs) {
        return Err(Error::MetadataKeyCollision(key.to_string()));
    }

    // Each arm performs its own atomic no-clobber rename (move: once; trash: in a
    // retry loop), then yields the line to append and the canonical source path.
    let (line, abs_src) = match op {
        Op::Move { src, dst } => {
            let abs_src = fs::canonicalize(&src).map_err(Error::Canonicalize)?;
            // Resolve the final target: into an existing / trailing-slash directory.
            let target = resolve_move_target(&src, &dst);
            // --mkdir: create the destination's missing parent chain, logging each.
            // A colliding destination implies its parent exists, so mkdir_chain is a
            // no-op on collision and a refused move creates no orphan dirs (AC11).
            if mkdir {
                if let Some(parent) = target.parent() {
                    mkdir_chain(parent, log, ts)?;
                }
            }
            let abs_dst = canonicalize_new(&target)?;
            let line = build_entry(
                ts,
                "move",
                &abs_src.to_string_lossy(),
                &abs_dst.to_string_lossy(),
                pairs,
            )?;
            // Atomic no-clobber rename: EEXIST names the colliding target (never
            // overwrite); EXDEV and others keep CrossVolume/Rename. No log on refusal.
            rename_noclobber(&src, &target).map_err(|e| {
                if e.raw_os_error() == Some(EEXIST) {
                    Error::DestinationExists(target.clone())
                } else {
                    classify_rename_err(e)
                }
            })?;
            (line, abs_src)
        }
        Op::Trash { path, trash_dir } => {
            let abs_src = fs::canonicalize(&path).map_err(Error::Canonicalize)?;
            let name = path.file_name().ok_or_else(|| {
                Error::Canonicalize(io::Error::new(
                    io::ErrorKind::InvalidInput,
                    "trash source has no file name",
                ))
            })?;
            // never-overwrite for trash: disambiguate rather than clobber. The
            // winning candidate is chosen by the atomic rename, then logged.
            let winner = rename_into_trash(&path, &trash_dir, name)?;
            let abs_dst = canonicalize_new(&winner)?;
            let line = build_entry(
                ts,
                "trash",
                &abs_src.to_string_lossy(),
                &abs_dst.to_string_lossy(),
                pairs,
            )?;
            (line, abs_src)
        }
    };

    // Rename happened: an append failure now is real drift, reported loudly (AC9).
    append_log(log, &line).map_err(Error::DriftAfterMove)?;

    // --rmdir runs only after a successful move AND its log append (AC11), for both
    // move and trash; it walks the now-empty source parent upward, cascading.
    if rmdir {
        rmdir_cascade(abs_src.parent(), log, ts)?;
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// Unit tests: T1, T2, T3, T_pairs, T_collide_u, T4
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use chrono::TimeZone;
    use std::io;

    // Shared fixed timestamp for U tests: 2024-01-15T10:30:00+00:00
    fn fixed_ts() -> DateTime<FixedOffset> {
        FixedOffset::east_opt(0)
            .unwrap()
            .with_ymd_and_hms(2024, 1, 15, 10, 30, 0)
            .unwrap()
    }

    // T1: AC1, AC5
    // build_entry(move, empty pairs) → exact compact JSON line with ONLY the four
    // canonical keys ts/act/src/dst in that order, act="move", absolute src/dst,
    // ts ISO-8601 second-precision with offset. Parses as valid JSON.
    #[test]
    fn t1_build_entry_move_exact_line() {
        let ts = fixed_ts();
        let line = build_entry(ts, "move", "/abs/src/file.txt", "/abs/dst/file.txt", &[])
            .expect("build_entry must succeed with no pairs");

        // Must parse as valid JSON.
        let v: serde_json::Value =
            serde_json::from_str(&line).expect("build_entry output must be valid JSON");

        // Field values.
        assert_eq!(v["ts"], "2024-01-15T10:30:00+00:00");
        assert_eq!(v["act"], "move");
        assert_eq!(v["src"], "/abs/src/file.txt");
        assert_eq!(v["dst"], "/abs/dst/file.txt");

        // Exact compact line: only 4 keys, in order, no placeholders.
        let expected = r#"{"ts":"2024-01-15T10:30:00+00:00","act":"move","src":"/abs/src/file.txt","dst":"/abs/dst/file.txt"}"#;
        assert_eq!(line, expected);
    }

    // AC2: non-UTF-8 path converted the way run() converts it
    // (Path::to_string_lossy) is logged with each invalid byte as U+FFFD, and
    // the line stays valid JSON. Pins that a faithful undo of such a line is
    // impossible: the raw 0xFF byte is not recoverable from the log.
    #[cfg(unix)]
    #[test]
    fn t_non_utf8_path_logs_replacement_char() {
        use std::os::unix::ffi::OsStrExt;

        let ts = fixed_ts();
        let lossy = Path::new(OsStr::from_bytes(b"file\xFF.txt")).to_string_lossy();

        let line = build_entry(ts, "move", &lossy, "/abs/dst", &[])
            .expect("build_entry must succeed with a lossily-converted src");

        // Must parse as valid JSON.
        let v: serde_json::Value =
            serde_json::from_str(&line).expect("build_entry output must be valid JSON");

        // The invalid byte is recorded as U+FFFD, not the original byte.
        assert_eq!(v["src"], "file\u{FFFD}.txt");
    }

    // T3: AC6  [no-JSON-corruption invariant]
    // build_entry with a pair whose KEY AND VALUE each contain quote + backslash +
    // unicode → line is still valid JSON and both key and value round-trip
    // byte-exact (serde_json escapes object keys too).
    #[test]
    fn t3_build_entry_special_chars_in_key_and_value_round_trips() {
        let ts = fixed_ts();
        // Key and value each contain a double-quote, backslash, and unicode snowman.
        let tricky_key = r#"k"ey\ ☃"#;
        let tricky_val = r#"say "hello" \ ☃"#;

        let line = build_entry(
            ts,
            "move",
            "/abs/src",
            "/abs/dst",
            &[(tricky_key, tricky_val)],
        )
        .expect("build_entry must succeed with special-char pair");

        // Must parse as valid JSON (not corrupted).
        let v: serde_json::Value = serde_json::from_str(&line)
            .expect("line with special chars in key and value must still be valid JSON");

        // Both key and value must round-trip byte-exact.
        let obj = v.as_object().unwrap();
        assert_eq!(
            obj.get(tricky_key)
                .and_then(|v| v.as_str())
                .expect("tricky key must be present in JSON object"),
            tricky_val
        );
    }

    // T_pairs: AC5
    // build_entry with multiple pairs → pairs appear AFTER the canonical four,
    // in the given order; every value is a JSON string (even a numeric-looking one).
    #[test]
    fn t_pairs_appear_after_canonical_in_order_as_strings() {
        let ts = fixed_ts();
        let pairs: &[(&str, &str)] = &[("by", "cc"), ("ac", "p"), ("num", "42")];

        let line = build_entry(ts, "move", "/abs/src", "/abs/dst", pairs)
            .expect("build_entry must succeed with pairs");

        let v: serde_json::Value =
            serde_json::from_str(&line).expect("line with pairs must be valid JSON");

        let obj = v.as_object().unwrap();
        let keys: Vec<&str> = obj.keys().map(|k| k.as_str()).collect();

        // First four must be the canonical keys in order.
        assert_eq!(
            &keys[..4],
            &["ts", "act", "src", "dst"],
            "first four keys must be canonical in order, got: {keys:?}"
        );
        // Pairs follow in the given order.
        assert_eq!(
            &keys[4..],
            &["by", "ac", "num"],
            "pairs must follow canonical keys in given order, got: {keys:?}"
        );

        // Every value is a JSON string (not number, bool, etc.)
        assert_eq!(v["by"], serde_json::Value::String("cc".into()));
        assert_eq!(v["ac"], serde_json::Value::String("p".into()));
        // "42" must stay a string, not be coerced to a number.
        assert_eq!(v["num"], serde_json::Value::String("42".into()));
    }

    // T_collide_u: AC13  [canonical-unspoofable invariant]
    // build_entry with a pair key in {ts,act,src,dst} → Err(MetadataKeyCollision),
    // no line produced.
    #[test]
    fn t_collide_u_build_entry_refuses_canonical_key() {
        let ts = fixed_ts();

        for &canonical in &["ts", "act", "src", "dst"] {
            let result = build_entry(
                ts,
                "move",
                "/abs/src",
                "/abs/dst",
                &[(canonical, "spoofed")],
            );
            assert!(
                matches!(&result, Err(Error::MetadataKeyCollision(k)) if k == canonical),
                "expected MetadataKeyCollision({canonical}), got: {result:?}"
            );
        }
    }

    // T4: AC8  [atomic-only / no-copy-fallback]
    // classify_rename_err maps raw os error 18 (EXDEV) to Error::CrossVolume;
    // any other error maps to Error::Rename.
    // REUSE: behavior identical to old contract; stays green, no edit.
    #[test]
    fn t4_classify_rename_err_exdev_and_other() {
        // EXDEV is raw os error 18 on macOS and Linux.
        let exdev = io::Error::from_raw_os_error(18);
        let result = classify_rename_err(exdev);
        assert!(
            matches!(result, Error::CrossVolume),
            "os error 18 must map to CrossVolume, got: {result:?}"
        );

        // A different os error (e.g. EACCES = 13) maps to Rename.
        let other = io::Error::from_raw_os_error(13);
        let result2 = classify_rename_err(other);
        assert!(
            matches!(result2, Error::Rename(_)),
            "non-EXDEV error must map to Rename, got: {result2:?}"
        );
    }

    // T_write_log_line_single_write_call: AC1 + AC3
    // write_log_line must emit line + newline in a SINGLE Write::write call
    // (locks out any reintroduction of a two-piece writeln!-style write).
    #[derive(Default)]
    struct CountingWriter {
        writes: usize,
        buf: Vec<u8>,
    }

    impl io::Write for CountingWriter {
        fn write(&mut self, data: &[u8]) -> io::Result<usize> {
            self.writes += 1;
            self.buf.extend_from_slice(data);
            Ok(data.len())
        }

        fn flush(&mut self) -> io::Result<()> {
            Ok(())
        }
    }

    #[test]
    fn t_write_log_line_single_write_call() {
        let mut w = CountingWriter::default();
        let line = "{\"ts\":\"x\",\"act\":\"move\"}";

        let r = write_log_line(&mut w, line);

        assert!(r.is_ok());
        assert_eq!(
            w.writes, 1,
            "line + newline must be a single write, not two"
        );
        assert_eq!(w.buf, format!("{line}\n").into_bytes());
    }
}