aboutsummaryrefslogtreecommitdiffstats
path: root/pkgs/populate/src/rsync.rs
blob: 011c021ff688a9553c70f9872c3e725cdfcedfe7 (plain)
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
//! Transferring with rsync, from the deploying machine to the target.

use crate::run::{self, Context, Failure, Result};
use crate::sh;
use serde_json::{Map, Value};
use std::collections::{BTreeMap, BTreeSet};
use std::path::Path;
use std::process::Command;

/// What a transfer excludes and filters, and how it compares files.
pub struct Config {
    pub use_checksum: bool,
    pub exclude: Vec<String>,
    /// Filter rules, as rsync's option without the dashes and its pattern.
    pub filters: Vec<(String, String)>,
    pub delete_excluded: bool,
    /// What to do about .rsync-filter files rsync can't read: fail if None,
    /// make rsync read them anyway if true, sync without them if false.
    pub insecure_links: Option<bool>,
    /// Whether .rsync-filter files apply.
    pub filter_files: bool,
}

impl Default for Config {
    fn default() -> Config {
        Config {
            use_checksum: false,
            exclude: Vec::new(),
            filters: Vec::new(),
            delete_excluded: true,
            insecure_links: None,
            filter_files: true,
        }
    }
}

impl Config {
    /// The defaults, with what a file source's settings say instead.
    pub fn from_settings(settings: &Map<String, Value>) -> Config {
        let mut config = Config::default();
        if let Some(Value::Bool(b)) = settings.get("useChecksum") {
            config.use_checksum = *b;
        }
        if let Some(Value::Array(patterns)) = settings.get("exclude") {
            config.exclude = patterns
                .iter()
                .filter_map(|p| p.as_str().map(String::from))
                .collect();
        }
        if let Some(Value::Array(filters)) = settings.get("filters") {
            config.filters = filters
                .iter()
                .filter_map(|f| {
                    let kind = f.get("type")?.as_str()?;
                    let pattern = f.get("pattern")?.as_str()?;
                    Some((kind.to_string(), pattern.to_string()))
                })
                .collect();
        }
        if let Some(Value::Bool(b)) = settings.get("deleteExcluded") {
            config.delete_excluded = *b;
        }
        if let Some(Value::Bool(b)) = settings.get("insecureLinks") {
            config.insecure_links = Some(*b);
        }
        config
    }

    /// rsync's arguments for what the transfer excludes and filters,
    /// followed by -F, which applies .rsync-filter files, unless the config
    /// turns that off.
    fn filter_args(&self) -> Vec<String> {
        let mut args = Vec::new();
        for pattern in &self.exclude {
            args.extend(["--exclude".to_string(), pattern.clone()]);
        }
        for (kind, pattern) in &self.filters {
            args.extend([format!("--{kind}"), pattern.clone()]);
        }
        if self.filter_files {
            args.push("-F".to_string());
        }
        args
    }
}

/// What the deploying machine finds out about a transfer before it runs,
/// see prepare.
pub struct Prepared {
    /// source_path as rsync gets it: a directory's with a trailing slash,
    /// so rsync transfers its contents.
    source: String,
    /// Whether rsync needs --insecure-links, see insecure_links.
    insecure_links: bool,
    /// What rsync would transfer, if asked for, and populate can tell.
    pub listing: Option<Listing>,
}

/// Checks the .rsync-filter files that apply to source_path, see
/// insecure_links, and, if listing, lists what rsync would transfer of it:
/// with find, if nothing excludes or filters anything, else with rsync
/// --list-only, which the check uses itself, if it runs rsync.  Not when
/// rsync needs --insecure-links, nor for what isn't a directory.
pub fn prepare(config: &Config, source_path: &str, listing: bool) -> Result<Prepared> {
    let directory = Path::new(source_path).is_dir();
    let mut source = source_path.to_string();
    if directory {
        source.push('/');
    }
    // Also with older versions of rsync, so a source that's missing, or
    // that contains a directory find can't read, fails before rsync runs.
    let filtered = config.filter_files && filtered(&source)?;
    let (insecure_links, log) = if filtered {
        insecure_links(config, &source)?
    } else {
        (false, None)
    };
    let listing = if !listing || !directory || insecure_links {
        None
    } else if let Some(log) = log {
        listed(&log)
    } else if !filtered && config.exclude.is_empty() && config.filters.is_empty() {
        found_locally(&source)
    } else {
        list_only(config, &source)
    };
    Ok(Prepared {
        source,
        insecure_links,
        listing,
    })
}

/// What rsync --list-only prints for source, with the config's filters,
/// in UTC, and paths as they are, or None if it fails.
fn list_only(config: &Config, source: &str) -> Option<Listing> {
    let output = Command::new("rsync")
        .env("TZ", "UTC0")
        .args(["-8", "--list-only"])
        .args(config.filter_args())
        .arg("-rlptD")
        .arg(source)
        .stdin(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .output()
        .ok()
        .filter(|output| output.status.success())?;
    listed(&String::from_utf8_lossy(&output.stdout))
}

/// Transfers source_path, a directory's contents or a file, to path on the
/// target, returning the paths, relative to path, of what that changed
/// there.
pub fn transfer(
    context: &Context,
    config: &Config,
    source_path: &str,
    path: &str,
) -> Result<Vec<String>> {
    let prepared = prepare(config, source_path, false)?;
    transfer_prepared(context, config, &prepared, path)
}

/// Transfers what prepare prepared, like transfer.
pub fn transfer_prepared(
    context: &Context,
    config: &Config,
    prepared: &Prepared,
    path: &str,
) -> Result<Vec<String>> {
    context.run(&sh::break_hard_links(), &[path, &context.name(path)])?;
    let source = &prepared.source;
    let insecure_links = prepared.insecure_links;
    let mut command = Command::new("rsync");
    if config.use_checksum {
        command.arg("--checksum");
    }
    // The remote shell runs it as a command.
    let sudo = if context.target.sudo { "sudo " } else { "" };
    match context.path() {
        Some(path) => command.arg(format!(
            "--rsync-path={sudo}env PATH={path}:\"$PATH\" rsync"
        )),
        None if context.target.sudo => command.arg("--rsync-path=sudo rsync"),
        None => &mut command,
    };
    command.arg("-e").arg(&context.ssh).arg("--protect-args");
    if insecure_links {
        command.arg("--insecure-links");
    }
    // Each item gets logged with what changed about it, and its size, as
    // transferred and in total, in units of 1024, which three apostrophes
    // ask for.
    command
        .arg("--itemize-changes")
        .arg("--out-format=%i %n%L %'''b/%'''l")
        .arg("--info=backup,del,copy,misc,mount,name,nonreg,remove,skip,symsafe")
        // Nothing relies on the times of directories and symlinks, and
        // keeping them would log a line for each directory changed.
        .arg("--omit-dir-times")
        .arg("--omit-link-times")
        .args(config.filter_args())
        .arg("-rlptD");
    if config.delete_excluded {
        command.arg("--delete-excluded");
    }
    command.arg(source).arg(context.rsync_destination(path));
    let mut changed = Vec::new();
    run::lines(&mut command, |line| {
        changed.extend(changed_path(line));
        eprintln!("{line}");
    })?;
    Ok(changed)
}

/// The path of what a line rsync prints itemizes a change of: what
/// --itemize-changes prints for an item, eleven characters, the second the
/// type of the item, or *deleting, followed by a blank, and the path, which
/// the sizes follow for items, and a symlink's target, after ->.
fn changed_path(line: &str) -> Option<String> {
    let (item, rest) = line.split_once(' ')?;
    if item == "*deleting" {
        return Some(rest.trim_start().to_string());
    }
    if item.len() != 11 || !matches!(item.as_bytes()[1], b'f' | b'd' | b'L' | b'D' | b'S') {
        return None;
    }
    let (path, _sizes) = rest.rsplit_once(' ')?;
    let path = if item.as_bytes()[1] == b'L' {
        path.split_once(" -> ").map_or(path, |(path, _)| path)
    } else {
        path
    };
    Some(path.to_string())
}

/// rsync 3.5.0 and later open .rsync-filter files with a stricter walk than
/// the files they transfer, and treat the ones that walk can't open as
/// missing, without saying so.  It fails, e.g., for a directory on the way
/// that the user may enter but not read, like a home directory with mode
/// 711, or a symlink that neither root nor the user owns.  So rsync, when
/// asked, tells which .rsync-filter files it reads for source: the ones
/// therein, and the ones in the directories above it, which apply as well.
/// If it reports ones as missing that exist and that the user may read, the
/// config's insecure_links decides: populate fails with an error if it's
/// None, syncs without them if it's false, and makes rsync open them like
/// the files it transfers with --insecure-links if it's true, both with a
/// warning.  Returns whether rsync needs --insecure-links, and, if it
/// asked rsync, what rsync --list-only printed: the listing of what it
/// would transfer, see listed, in UTC, and its debugging lines.
fn insecure_links(config: &Config, source: &str) -> Result<(bool, Option<String>)> {
    let version = rsync_version()?;
    if !version_at_least(&version, "3.5.0") {
        return Ok((false, None));
    }
    // Listing what the transfer would send, as far as filtering goes.
    let log = run::output(
        Command::new(run::SH)
            .env("TZ", "UTC0")
            .arg("-c")
            .arg(r#"rsync "$@" 2>&1 || :"#)
            .arg("sh")
            .args(["-8", "--list-only", "--debug=FILTER2"])
            .args(config.filter_args())
            .arg("-rlptD")
            .arg(source),
    )?;
    let mut parsed = false;
    let mut ignored = None;
    for line in log.lines() {
        let Some(rest) = line.strip_prefix("[sender] parse_filter_file(") else {
            continue;
        };
        parsed = true;
        let Some(rest) = rest.strip_suffix(") [not found]") else {
            continue;
        };
        // What precedes the last two comma-separated fields.
        let Some(file) = rest.rsplitn(3, ',').nth(2) else {
            continue;
        };
        let file = unescape(file);
        let shown = file.display().to_string();
        let readable = std::fs::File::open(&file).is_ok();
        if Path::new(&file).exists() && readable {
            ignored = Some(shown);
            break;
        }
    }
    if !parsed {
        eprintln!(
            "warning: rsync {version} doesn't tell which .rsync-filter files it reads, so it may sync {source} without some of them unnoticed."
        );
    }
    let Some(ignored) = ignored else {
        return Ok((false, Some(log)));
    };
    match config.insecure_links {
        None => Err(Failure::Message(format!(
            "error: rsync {version} can't read {ignored}, so it would sync {source} without it.  This happens, e.g., if a directory on the way isn't readable, or if a symlink on the way belongs to neither root nor the user running rsync.  Set the source's insecureLinks to true to make rsync read it anyway, or to false to sync without it."
        ))),
        Some(true) => {
            eprintln!(
                "warning: rsync {version} can't read {ignored}; it reads it with --insecure-links anyway, because insecureLinks is true."
            );
            Ok((true, Some(log)))
        }
        Some(false) => {
            eprintln!(
                "warning: rsync {version} can't read {ignored}, so it syncs {source} without it, because insecureLinks is false."
            );
            Ok((false, Some(log)))
        }
    }
}

/// Whether a .rsync-filter file applies to source: one therein, or in a
/// directory above it.  Fails, with find's message, if find fails.
fn filtered(source: &str) -> Result<bool> {
    let found = run::output(Command::new("find").arg(source).args([
        "-name",
        ".rsync-filter",
        "-print",
        "-quit",
    ]))?;
    if !found.is_empty() {
        return Ok(true);
    }
    let mut above = parent(source);
    loop {
        if Path::new(&above).join(".rsync-filter").exists() {
            return Ok(true);
        }
        if above == "/" || above == "." {
            return Ok(false);
        }
        above = parent(&above);
    }
}

/// Like dirname.
fn parent(path: &str) -> String {
    let trimmed = path.trim_end_matches('/');
    if trimmed.is_empty() {
        return "/".to_string();
    }
    match trimmed.rfind('/') {
        None => ".".to_string(),
        Some(i) => {
            let parent = trimmed[..i].trim_end_matches('/');
            if parent.is_empty() { "/" } else { parent }.to_string()
        }
    }
}

/// The version of the rsync in PATH, from rsync --version, which runs once
/// per run, not once for each source.
fn rsync_version() -> Result<String> {
    static VERSION: std::sync::OnceLock<String> = std::sync::OnceLock::new();
    if let Some(version) = VERSION.get() {
        return Ok(version.clone());
    }
    let output = run::output(Command::new("rsync").arg("--version"))?;
    let version = output
        .lines()
        .next()
        .and_then(|line| line.split_whitespace().nth(2))
        .unwrap_or("")
        .to_string();
    Ok(VERSION.get_or_init(|| version).clone())
}

/// Like sort -V: whether version is at least minimum.
fn version_at_least(version: &str, minimum: &str) -> bool {
    let parts = |v: &str| -> Vec<u64> {
        v.split('.')
            .map(|p| {
                p.chars()
                    .take_while(char::is_ascii_digit)
                    .collect::<String>()
            })
            .map(|p| p.parse().unwrap_or(0))
            .collect()
    };
    parts(version) >= parts(minimum)
}

/// rsync prints bytes it takes for unprintable, which depends on the
/// locale, as \#ooo.
fn unescape(escaped: &str) -> std::path::PathBuf {
    use std::os::unix::ffi::OsStringExt;
    let bytes = escaped.as_bytes();
    let mut out = Vec::with_capacity(bytes.len());
    let mut i = 0;
    while i < bytes.len() {
        let octal = bytes
            .get(i + 2..i + 5)
            .filter(|d| d.iter().all(|b| (b'0'..=b'7').contains(b)));
        let escape = bytes[i] == b'\\' && bytes.get(i + 1) == Some(&b'#');
        if let (true, Some(digits)) = (escape, octal) {
            let value = digits
                .iter()
                .fold(0u32, |acc, d| acc * 8 + u32::from(d - b'0'));
            out.push(value as u8);
            i += 5;
        } else {
            out.push(bytes[i]);
            i += 1;
        }
    }
    std::ffi::OsString::from_vec(out).into()
}

/// A listing of a directory: an entry for each thing in it, and for the
/// directory itself, as ".", in a form that is the same for both sides of a
/// transfer exactly if rsync's quick check finds nothing to do between them:
/// the mode and the path, and, for files, also the size and the
/// modification time in whole seconds, and, for symlinks, the target.
/// rsync doesn't keep the times of directories and symlinks
/// (--omit-dir-times, --omit-link-times), nor owners (-rlptD).
pub type Listing = BTreeSet<String>;

/// Whether populate can't compare an entry's path or link target: one that
/// rsync --list-only escapes, with control characters, or that isn't
/// UTF-8, which reading it as UTF-8 replaced.
fn incomparable(text: &str) -> bool {
    text.chars()
        .any(|c| c.is_control() || c == '\u{fffd}' || c == '\\')
}

/// The canonical form of an entry that rsync --list-only, with -8 and in
/// UTC, prints as MODE SIZE DATE TIME PATH, with " -> TARGET" for a
/// symlink, or None if it's something else, or something populate doesn't
/// compare: devices, FIFOs, sockets, and paths it can't compare.
fn canonical_listed(line: &str) -> Option<String> {
    let (mode, rest) = line.split_once(' ')?;
    let (size, rest) = rest.trim_start().split_once(' ')?;
    let (date, rest) = rest.split_once(' ')?;
    let (time, path) = rest.split_once(' ')?;
    if mode.len() != 10 || incomparable(path) {
        return None;
    }
    match mode.as_bytes()[0] {
        b'd' | b'l' => Some(format!("{mode} {path}")),
        b'-' => Some(format!(
            "{mode} {} {date} {time} {path}",
            size.replace(',', "")
        )),
        _ => None,
    }
}

/// The canonical form of an entry find prints in sh::LISTINGS: its mode,
/// size, modification time in seconds since the epoch, path relative to
/// where find started, empty for that, and symlink target, or None, like
/// canonical_listed.
fn canonical_found(mode: &str, size: &str, time: &str, path: &str, target: &str) -> Option<String> {
    let path = if path.is_empty() { "." } else { path };
    if mode.len() != 10 || incomparable(path) || incomparable(target) {
        return None;
    }
    match mode.as_bytes()[0] {
        b'd' => Some(format!("{mode} {path}")),
        b'l' => Some(format!("{mode} {path} -> {target}")),
        b'-' => {
            let seconds: f64 = time.parse().ok()?;
            if seconds < 0.0 {
                return None;
            }
            // Like 2026/11/30 13:57:55, as rsync prints it.
            let stamp = crate::record::timestamp(seconds as u64);
            let (date, time) = stamp.trim_end_matches('Z').split_once('T')?;
            Some(format!(
                "{mode} {size} {} {time} {path}",
                date.replace('-', "/")
            ))
        }
        _ => None,
    }
}

/// The listing in what rsync --list-only printed, skipping its debugging
/// lines, which start with [, or None if a line is anything else, e.g. an
/// error, or an entry populate doesn't compare.
fn listed(output: &str) -> Option<Listing> {
    output
        .lines()
        .filter(|line| !line.starts_with('['))
        .map(canonical_listed)
        .collect()
}

/// The listings of the paths in what sh::LISTINGS printed, by path: None
/// for a path where find failed, or that has an entry populate doesn't
/// compare.
pub fn found(output: &str) -> BTreeMap<String, Option<Listing>> {
    let mut listings = BTreeMap::new();
    let mut fields = output.split('\0');
    let mut current: Option<(String, Option<Listing>)> = None;
    while let Some(field) = fields.next() {
        match field {
            "P" => {
                current = fields
                    .next()
                    .map(|path| (path.to_string(), Some(Listing::new())))
            }
            "E" => {
                let entry: Vec<&str> = fields.by_ref().take(5).collect();
                if let Some((_, listing)) = &mut current {
                    let canonical = match entry[..] {
                        [mode, size, time, path, target] => {
                            canonical_found(mode, size, time, path, target)
                        }
                        _ => None,
                    };
                    match (listing.as_mut(), canonical) {
                        (Some(entries), Some(entry)) => {
                            entries.insert(entry);
                        }
                        _ => *listing = None,
                    }
                }
            }
            "S" => {
                let status = fields.next();
                if let Some((path, listing)) = current.take() {
                    let ok = status == Some("0");
                    listings.insert(path, listing.filter(|_| ok));
                }
            }
            _ => {}
        }
    }
    listings
}

/// The listing of source on the deploying machine, with find, as
/// sh::LISTINGS prints it for the target, or None.
fn found_locally(source: &str) -> Option<Listing> {
    let output = run::output(
        Command::new(run::SH)
            .arg("-c")
            .arg(sh::LISTINGS)
            .arg("sh")
            .arg(source),
    )
    .ok()?;
    found(&output).remove(source).flatten()
}

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

    // What rsync --list-only and find print for the same directory, with a
    // directory, a file, and a symlink, as in the test of the listings.
    const LISTED: &str = "\
[sender] parse_filter_file(/src/.rsync-filter,c00,4)
drwxr-xr-x          4,096 2026/11/30 17:52:48 .
lrwxrwxrwx              6 2026/11/30 17:52:48 link -> a/keep
drwxr-x---          4,096 2026/11/30 17:52:48 a
-rw-r--r--          1,234 2026/11/30 17:52:48 a/keep
";

    fn found_output(path: &str, entries: &[[&str; 5]], status: &str) -> String {
        let mut output = format!("P\0{path}\0");
        for entry in entries {
            output.push_str("E\0");
            for field in entry {
                output.push_str(field);
                output.push('\0');
            }
        }
        output + &format!("S\0{status}\0")
    }

    const FOUND: [[&str; 5]; 4] = [
        ["drwxr-xr-x", "4096", "1796060000.1", "", ""],
        ["lrwxrwxrwx", "6", "1796060001.2", "link", "a/keep"],
        ["drwxr-x---", "4096", "1796060002.3", "a", ""],
        ["-rw-r--r--", "1234", "1796060000.9", "a/keep", ""],
    ];

    #[test]
    fn listings() {
        // 1796060000 is 2026/11/30 17:33:20 in UTC.
        let expected = listed(&LISTED.replace("17:52:48", "17:33:20")).expect("listed");
        let all = found(&found_output("/t/x", &FOUND, "0"));
        assert_eq!(all.get("/t/x"), Some(&Some(expected.clone())));
        // A file's time, size, or mode, or a link's target, makes a
        // difference, directories' and links' times don't.
        let differs = |i: usize, field: usize, value: &str| {
            let mut entries = FOUND;
            entries[i][field] = value;
            found(&found_output("/t/x", &entries, "0"))["/t/x"] != Some(expected.clone())
        };
        assert!(differs(3, 2, "1796060001.0"));
        assert!(differs(3, 1, "1235"));
        assert!(differs(3, 0, "-rw-------"));
        assert!(differs(1, 4, "a"));
        assert!(differs(0, 0, "drwx------"));
        assert!(!differs(0, 2, "1"));
        assert!(!differs(1, 2, "1"));
        // A missing entry, a failing find, and paths populate doesn't
        // compare.
        assert_ne!(
            found(&found_output("/t/x", &FOUND[..3], "0"))["/t/x"],
            Some(expected.clone())
        );
        assert_eq!(found(&found_output("/t/x", &FOUND, "1"))["/t/x"], None);
        let mut entries = FOUND;
        entries[3][3] = "a/new\nline";
        assert_eq!(found(&found_output("/t/x", &entries, "0"))["/t/x"], None);
        assert_eq!(listed("rsync: [sender] change_dir failed\n"), None);
        assert_eq!(
            listed("crw-r--r--          1,3 2026/11/30 17:33:20 null\n"),
            None
        );
        assert_eq!(
            listed("-rw-r--r--              1 2026/11/30 17:33:20 a\\#012b\n"),
            None
        );
    }

    #[test]
    fn changed_paths() {
        let path = |line| changed_path(line);
        assert_eq!(
            path(">f.st...... flake.nix 82/39").as_deref(),
            Some("flake.nix")
        );
        assert_eq!(path("cd+++++++++ a b/ 0/4.00K").as_deref(), Some("a b/"));
        assert_eq!(path(".f..t...... x 0/1").as_deref(), Some("x"));
        assert_eq!(path("cL+++++++++ l -> t 0/0").as_deref(), Some("l"));
        assert_eq!(path("*deleting   old").as_deref(), Some("old"));
        assert_eq!(path("skipping non-regular file \"x\""), None);
        assert_eq!(path("sent 10 bytes"), None);
    }

    #[test]
    fn versions() {
        assert!(version_at_least("3.5.0", "3.5.0"));
        assert!(version_at_least("3.10.1", "3.5.0"));
        assert!(!version_at_least("3.4.1", "3.5.0"));
    }

    #[test]
    fn parents() {
        assert_eq!(parent("/a/b/"), "/a");
        assert_eq!(parent("/a"), "/");
        assert_eq!(parent("a"), ".");
        assert_eq!(parent("/"), "/");
    }

    #[test]
    fn unescaping() {
        assert_eq!(unescape(r"a\#012b"), std::path::PathBuf::from("a\nb"));
        assert_eq!(unescape(r"a\#9b"), std::path::PathBuf::from(r"a\#9b"));
    }
}