rs-rich-ext 0.0.21

Extensions for the `rich` Rust port: diagnostics, structured data, clap and tracing integration, diffs, workflow renderables and a plugin registry
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
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
//! File operations as a file manager runs them: copy, move, link, delete
//! and trash, reporting progress as they go and stopping when cancelled, with
//! Yazi's rules for names that are taken (a copy gets `_1`, `_2`… before
//! its extension) and for directories pasted into themselves (refused).
//!
//! Not a port of anything upstream: an rs-rich addition, with no
//! dependencies. [`run`] blocks; call it on a worker thread and send the
//! [`Progress`] it reports wherever it is shown (intuiTUIve's `files`
//! tasks do, with a task panel).
//!
//! ```
//! use rich_ext::cancel::CancelToken;
//! use rich_ext::file_ops::{run, Conflict, Op};
//!
//! let base = std::env::temp_dir().join(format!("rich-ext-ops-doc-{}", std::process::id()));
//! std::fs::create_dir_all(base.join("into")).unwrap();
//! std::fs::write(base.join("a.txt"), "hello").unwrap();
//!
//! let op = Op::Copy { from: vec![base.join("a.txt")], into: base.join("into"), conflict: Conflict::Rename };
//! let mut seen = 0;
//! let report = run(&op, &CancelToken::new(), &mut |p| seen = p.bytes);
//! assert!(report.errors.is_empty());
//! assert_eq!(seen, 5);
//! assert_eq!(std::fs::read_to_string(base.join("into/a.txt")).unwrap(), "hello");
//! // Again: the name is taken, so the copy is a_1.txt.
//! run(&op, &CancelToken::new(), &mut |_| {});
//! assert!(base.join("into/a_1.txt").exists());
//! # std::fs::remove_dir_all(&base).ok();
//! ```

use std::io::{self, Read, Write};
use std::path::{Component, Path, PathBuf};

use crate::cancel::CancelToken;

/// What to do when the target's name is taken.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum Conflict {
    /// Take a free name: `name_1.ext`, `name_2.ext`… (Yazi's default).
    #[default]
    Rename,
    /// Replace what is there (Yazi's `paste --force`).
    Overwrite,
    /// Leave it, and skip this one.
    Skip,
}

/// What kind of link [`Op::Link`] makes.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum LinkKind {
    /// A symbolic link to the file: to its absolute path (Yazi's `-`), or
    /// with `relative`, to its path from the link's directory (`_`), so the
    /// two can move together.
    Symbolic { relative: bool },
    /// A hard link (Yazi's Ctrl+-): another name for the same file. A
    /// directory is made again with hard links to the files in it, as
    /// directories cannot be hard linked; a symbolic link is copied as a
    /// link.
    Hard,
}

/// A file operation over some paths.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum Op {
    /// Copy each of `from` into the directory `into`: files, links as
    /// links, directories with everything in them.
    Copy {
        from: Vec<PathBuf>,
        into: PathBuf,
        conflict: Conflict,
    },
    /// Move each of `from` into `into`: a rename where it can be, else a
    /// copy and a delete (across file systems).
    Move {
        from: Vec<PathBuf>,
        into: PathBuf,
        conflict: Conflict,
    },
    /// Delete for good: a link itself (never what it points to), a file,
    /// a directory and everything in it.
    Delete(Vec<PathBuf>),
    /// Move to the platform's trash ([`crate::trash::send`]): the
    /// FreeDesktop trash, the Finder's, the Recycle Bin.
    Trash(Vec<PathBuf>),
    /// Link each of `from` into the directory `into`, under its own name,
    /// as `kind` says (Yazi's `-`, `_` and Ctrl+- on the files yanked). A
    /// name that is taken is treated as `conflict` says.
    Link {
        from: Vec<PathBuf>,
        into: PathBuf,
        kind: LinkKind,
        conflict: Conflict,
    },
}

impl Op {
    /// What it does, for a task list: `Copy 3 items to docs`.
    pub fn title(&self) -> String {
        let count = |paths: &[PathBuf]| match paths {
            [one] => one.file_name().map_or_else(
                || one.display().to_string(),
                |n| n.to_string_lossy().into_owned(),
            ),
            many => format!("{} items", many.len()),
        };
        let name = |dir: &Path| {
            dir.file_name().map_or_else(
                || dir.display().to_string(),
                |n| n.to_string_lossy().into_owned(),
            )
        };
        match self {
            Op::Copy { from, into, .. } => format!("Copy {} to {}", count(from), name(into)),
            Op::Move { from, into, .. } => format!("Move {} to {}", count(from), name(into)),
            Op::Delete(paths) => format!("Delete {}", count(paths)),
            Op::Trash(paths) => format!("Trash {}", count(paths)),
            Op::Link {
                from, into, kind, ..
            } => {
                let what = match kind {
                    LinkKind::Symbolic { .. } => "Link",
                    LinkKind::Hard => "Hard link",
                };
                format!("{what} {} in {}", count(from), name(into))
            }
        }
    }

    /// The paths it works on.
    pub fn paths(&self) -> &[PathBuf] {
        match self {
            Op::Copy { from, .. } | Op::Move { from, .. } | Op::Link { from, .. } => from,
            Op::Delete(paths) | Op::Trash(paths) => paths,
        }
    }
}

/// How far an operation has got. Totals are counted before it starts.
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
pub struct Progress {
    /// Bytes copied (copies and moves across file systems).
    pub bytes: u64,
    pub total_bytes: u64,
    /// Files, links and directories done.
    pub items: usize,
    pub total_items: usize,
    /// What it is working on.
    pub current: Option<PathBuf>,
}

impl Progress {
    /// Done, from 0 to 1: by bytes when there are any, else by items.
    pub fn fraction(&self) -> f64 {
        if self.total_bytes > 0 {
            self.bytes as f64 / self.total_bytes as f64
        } else if self.total_items > 0 {
            self.items as f64 / self.total_items as f64
        } else {
            1.0
        }
    }
}

/// How an operation ended.
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
pub struct Report {
    /// What it made: each copy or moved item at its new path.
    pub made: Vec<PathBuf>,
    /// What went wrong, one line each (`name: error`).
    pub errors: Vec<String>,
    /// It was cancelled before the end. A file half copied is removed;
    /// what was done before stays.
    pub cancelled: bool,
}

/// Bytes copied a read.
const CHUNK: usize = 256 * 1024;

/// Run `op`, calling `progress` as it goes (after each chunk of 256 KiB
/// and each item), and stopping at the next of those when `cancel` is
/// cancelled. Blocks until done.
pub fn run(op: &Op, cancel: &CancelToken, progress: &mut dyn FnMut(&Progress)) -> Report {
    let mut runner = Runner {
        cancel,
        progress: Progress::default(),
        emit: progress,
        report: Report::default(),
    };
    for path in op.paths() {
        let (items, bytes) = match op {
            Op::Trash(_)
            | Op::Link {
                kind: LinkKind::Symbolic { .. },
                ..
            } => (1, 0),
            Op::Delete(_) | Op::Link { .. } => (count(path).0, 0),
            _ => count(path),
        };
        runner.progress.total_items += items;
        runner.progress.total_bytes += bytes;
    }
    runner.tell();
    for path in op.paths() {
        if runner.stopped() {
            break;
        }
        let name = path.file_name().map_or_else(
            || path.display().to_string(),
            |n| n.to_string_lossy().into_owned(),
        );
        let done = match op {
            Op::Copy { into, conflict, .. } => runner.paste(path, into, *conflict, false),
            Op::Move { into, conflict, .. } => runner.paste(path, into, *conflict, true),
            Op::Delete(_) => runner.delete(path),
            Op::Trash(_) => crate::trash::send(path).map(|_| {
                runner.progress.items += 1;
                runner.tell();
            }),
            Op::Link {
                into,
                kind,
                conflict,
                ..
            } => runner.link(path, into, *kind, *conflict),
        };
        if let Err(error) = done
            && error.kind() != io::ErrorKind::Interrupted
        {
            runner.report.errors.push(format!("{name}: {error}"));
        }
    }
    runner.progress.current = None;
    runner.tell();
    runner.report
}

/// Files, links and directories at `path`, and their bytes (files only).
fn count(path: &Path) -> (usize, u64) {
    let Ok(meta) = std::fs::symlink_metadata(path) else {
        return (0, 0);
    };
    if !meta.is_dir() {
        return (1, if meta.is_file() { meta.len() } else { 0 });
    }
    let mut total = (1, 0);
    if let Ok(read) = std::fs::read_dir(path) {
        for entry in read.filter_map(Result::ok) {
            let (items, bytes) = count(&entry.path());
            total.0 += items;
            total.1 += bytes;
        }
    }
    total
}

struct Runner<'a> {
    cancel: &'a CancelToken,
    progress: Progress,
    emit: &'a mut dyn FnMut(&Progress),
    report: Report,
}

fn interrupted() -> io::Error {
    io::Error::new(io::ErrorKind::Interrupted, "cancelled")
}

impl Runner<'_> {
    fn tell(&mut self) {
        (self.emit)(&self.progress);
    }

    fn stopped(&mut self) -> bool {
        if self.cancel.is_cancelled() {
            self.report.cancelled = true;
        }
        self.report.cancelled
    }

    /// Copy or move `from` into the directory `into`.
    fn paste(&mut self, from: &Path, into: &Path, conflict: Conflict, cut: bool) -> io::Result<()> {
        let Some(name) = from.file_name() else {
            return Ok(());
        };
        let meta = std::fs::symlink_metadata(from)?;
        if meta.is_dir() && into.starts_with(from) {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                "can't go inside itself",
            ));
        }
        let mut target = into.join(name);
        if target == from {
            if cut {
                // A cut pasted where it is: nothing to do.
                let (items, bytes) = count(from);
                self.progress.items += items;
                self.progress.bytes += bytes;
                self.tell();
                return Ok(());
            }
            target = unique(&target);
        } else if std::fs::symlink_metadata(&target).is_ok() {
            match conflict {
                Conflict::Rename => target = unique(&target),
                Conflict::Skip => {
                    let (items, bytes) = count(from);
                    self.progress.items += items;
                    self.progress.bytes += bytes;
                    self.tell();
                    return Ok(());
                }
                Conflict::Overwrite => remove_all(&target)?,
            }
        }
        if cut && std::fs::rename(from, &target).is_ok() {
            let (items, bytes) = count(&target);
            self.progress.items += items;
            self.progress.bytes += bytes;
            self.tell();
            self.report.made.push(target);
            return Ok(());
        }
        self.copy(from, &target)?;
        if cut {
            remove_all(from)?;
        }
        self.report.made.push(target);
        Ok(())
    }

    fn copy(&mut self, from: &Path, to: &Path) -> io::Result<()> {
        if self.stopped() {
            return Err(interrupted());
        }
        self.progress.current = Some(from.to_path_buf());
        let meta = std::fs::symlink_metadata(from)?;
        if meta.file_type().is_symlink() {
            #[cfg(unix)]
            std::os::unix::fs::symlink(std::fs::read_link(from)?, to)?;
            #[cfg(not(unix))]
            std::fs::copy(from, to)?;
        } else if meta.is_dir() {
            std::fs::create_dir(to)?;
            let mut names: Vec<_> = std::fs::read_dir(from)?
                .filter_map(Result::ok)
                .map(|e| e.file_name())
                .collect();
            names.sort();
            self.progress.items += 1;
            self.tell();
            for name in names {
                self.copy(&from.join(&name), &to.join(&name))?;
            }
            std::fs::set_permissions(to, meta.permissions())?;
            return Ok(());
        } else {
            self.copy_file(from, to, &meta)?;
        }
        self.progress.items += 1;
        self.tell();
        Ok(())
    }

    fn copy_file(&mut self, from: &Path, to: &Path, meta: &std::fs::Metadata) -> io::Result<()> {
        let mut reader = std::fs::File::open(from)?;
        let mut writer = std::fs::OpenOptions::new()
            .write(true)
            .create_new(true)
            .open(to)?;
        let mut buffer = vec![0u8; CHUNK];
        let copied = (|| -> io::Result<()> {
            loop {
                if self.stopped() {
                    return Err(interrupted());
                }
                let n = reader.read(&mut buffer)?;
                if n == 0 {
                    return Ok(());
                }
                writer.write_all(&buffer[..n])?;
                self.progress.bytes += n as u64;
                self.tell();
            }
        })();
        drop(writer);
        if let Err(error) = copied {
            let _ = std::fs::remove_file(to);
            return Err(error);
        }
        std::fs::set_permissions(to, meta.permissions())?;
        if let Ok(modified) = meta.modified() {
            let _ = std::fs::File::options()
                .write(true)
                .open(to)
                .and_then(|f| f.set_modified(modified));
        }
        Ok(())
    }

    /// Link `from` into the directory `into`.
    fn link(
        &mut self,
        from: &Path,
        into: &Path,
        kind: LinkKind,
        conflict: Conflict,
    ) -> io::Result<()> {
        let Some(name) = from.file_name() else {
            return Ok(());
        };
        let meta = std::fs::symlink_metadata(from)?;
        let mut target = into.join(name);
        if std::fs::symlink_metadata(&target).is_ok() {
            match conflict {
                Conflict::Rename => target = unique(&target),
                Conflict::Skip => {
                    self.progress.items += match kind {
                        LinkKind::Symbolic { .. } => 1,
                        LinkKind::Hard => count(from).0,
                    };
                    self.tell();
                    return Ok(());
                }
                Conflict::Overwrite => {
                    if target == from {
                        return Err(io::Error::new(
                            io::ErrorKind::InvalidInput,
                            "can't link a file over itself",
                        ));
                    }
                    remove_all(&target)?;
                }
            }
        }
        match kind {
            LinkKind::Symbolic { relative } => {
                let from = absolute(from)?;
                let to = if relative {
                    relative_to(&from, &absolute(into)?)
                } else {
                    from.clone()
                };
                symlink(&to, &target, meta.is_dir())?;
                self.progress.items += 1;
                self.tell();
            }
            LinkKind::Hard => {
                if meta.is_dir() && into.starts_with(from) {
                    return Err(io::Error::new(
                        io::ErrorKind::InvalidInput,
                        "can't go inside itself",
                    ));
                }
                self.hard_link(from, &target)?;
            }
        }
        self.report.made.push(target);
        Ok(())
    }

    /// Hard link `from` at `to`: a directory made again, its files hard
    /// linked; a symbolic link copied as a link.
    fn hard_link(&mut self, from: &Path, to: &Path) -> io::Result<()> {
        if self.stopped() {
            return Err(interrupted());
        }
        self.progress.current = Some(from.to_path_buf());
        let meta = std::fs::symlink_metadata(from)?;
        if meta.file_type().is_symlink() {
            let points = std::fs::read_link(from)?;
            let dir = std::fs::metadata(from).is_ok_and(|m| m.is_dir());
            symlink(&points, to, dir)?;
        } else if meta.is_dir() {
            std::fs::create_dir(to)?;
            let mut names: Vec<_> = std::fs::read_dir(from)?
                .filter_map(Result::ok)
                .map(|e| e.file_name())
                .collect();
            names.sort();
            self.progress.items += 1;
            self.tell();
            for name in names {
                self.hard_link(&from.join(&name), &to.join(&name))?;
            }
            std::fs::set_permissions(to, meta.permissions())?;
            return Ok(());
        } else {
            std::fs::hard_link(from, to)?;
        }
        self.progress.items += 1;
        self.tell();
        Ok(())
    }

    fn delete(&mut self, path: &Path) -> io::Result<()> {
        if self.stopped() {
            return Err(interrupted());
        }
        self.progress.current = Some(path.to_path_buf());
        let meta = std::fs::symlink_metadata(path)?;
        if meta.is_dir() {
            for entry in std::fs::read_dir(path)? {
                self.delete(&entry?.path())?;
            }
            std::fs::remove_dir(path)?;
        } else {
            std::fs::remove_file(path)?;
        }
        self.progress.items += 1;
        self.tell();
        Ok(())
    }
}

/// A symbolic link at `link` to `to` (a directory's link on Windows).
fn symlink(to: &Path, link: &Path, dir: bool) -> io::Result<()> {
    #[cfg(unix)]
    {
        let _ = dir;
        std::os::unix::fs::symlink(to, link)
    }
    #[cfg(windows)]
    {
        if dir {
            std::os::windows::fs::symlink_dir(to, link)
        } else {
            std::os::windows::fs::symlink_file(to, link)
        }
    }
    #[cfg(not(any(unix, windows)))]
    {
        let _ = (to, link, dir);
        Err(io::Error::new(
            io::ErrorKind::Unsupported,
            "symbolic links are not supported here",
        ))
    }
}

/// `path` made absolute against the working directory, `.` and `..`
/// resolved by name (links are not followed: a link's path is linked to,
/// as Yazi does).
fn absolute(path: &Path) -> io::Result<PathBuf> {
    let joined = if path.is_absolute() {
        path.to_path_buf()
    } else {
        std::env::current_dir()?.join(path)
    };
    let mut out = PathBuf::new();
    for part in joined.components() {
        match part {
            Component::ParentDir => {
                out.pop();
            }
            Component::CurDir => {}
            other => out.push(other),
        }
    }
    Ok(out)
}

/// The path from the directory `base` to `path`, both absolute:
/// `../docs/a.txt`. Where they share no root (two drives), `path` itself.
///
/// ```
/// use std::path::Path;
/// use rich_ext::file_ops::relative_to;
///
/// assert_eq!(relative_to(Path::new("/home/a/docs/x.md"), Path::new("/home/a/links")), Path::new("../docs/x.md"));
/// assert_eq!(relative_to(Path::new("/home/a/x.md"), Path::new("/home/a")), Path::new("x.md"));
/// ```
pub fn relative_to(path: &Path, base: &Path) -> PathBuf {
    let (path_parts, base_parts): (Vec<_>, Vec<_>) =
        (path.components().collect(), base.components().collect());
    let shared = path_parts
        .iter()
        .zip(&base_parts)
        .take_while(|(a, b)| a == b)
        .count();
    let rooted = |parts: &[Component]| {
        parts
            .first()
            .is_some_and(|c| matches!(c, Component::Prefix(_) | Component::RootDir))
    };
    if shared == 0 && (rooted(&path_parts) || rooted(&base_parts)) {
        return path.to_path_buf();
    }
    let mut out = PathBuf::new();
    for _ in shared..base_parts.len() {
        out.push("..");
    }
    for part in &path_parts[shared..] {
        out.push(part);
    }
    out
}

/// Remove `path`: a link itself (never what it points to), a file, or a
/// directory and everything in it.
pub fn remove_all(path: &Path) -> io::Result<()> {
    let meta = std::fs::symlink_metadata(path)?;
    if meta.is_dir() {
        std::fs::remove_dir_all(path)
    } else {
        std::fs::remove_file(path)
    }
}

/// `path`, or `path` with `_1`, `_2`… before its extension, whichever does
/// not exist yet: how Yazi pastes over a name that is taken.
pub fn unique(path: &Path) -> PathBuf {
    if std::fs::symlink_metadata(path).is_err() {
        return path.to_path_buf();
    }
    let stem = path
        .file_stem()
        .map(|s| s.to_string_lossy().into_owned())
        .unwrap_or_default();
    let ext = path
        .extension()
        .map(|e| format!(".{}", e.to_string_lossy()))
        .unwrap_or_default();
    (1..)
        .map(|n| path.with_file_name(format!("{stem}_{n}{ext}")))
        .find(|p| std::fs::symlink_metadata(p).is_err())
        .expect("a free name")
}

/// A name typed into a prompt as a path under `dir`: relative, never
/// climbing out of it (`..`, a root or a drive), trailing slashes dropped.
///
/// ```
/// use std::path::Path;
/// use rich_ext::file_ops::under;
///
/// assert_eq!(under(Path::new("/home/a"), "notes/new.md").unwrap(), Path::new("/home/a/notes/new.md"));
/// assert!(under(Path::new("/home/a"), "../b").is_err());
/// assert!(under(Path::new("/home/a"), "/etc/passwd").is_err());
/// ```
pub fn under(dir: &Path, typed: &str) -> Result<PathBuf, String> {
    let typed = typed.trim_end_matches(['/', '\\']);
    let rel = Path::new(typed);
    if typed.is_empty() {
        return Err("No name given".into());
    }
    if rel
        .components()
        .any(|c| !matches!(c, Component::Normal(_) | Component::CurDir))
    {
        return Err(format!("{typed:?} must stay inside this directory"));
    }
    Ok(dir.join(rel))
}

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

    fn base(name: &str) -> PathBuf {
        let dir = std::env::temp_dir().join(format!("rich-ext-ops-{name}-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(dir.join("src/inner")).unwrap();
        std::fs::create_dir_all(dir.join("dst")).unwrap();
        std::fs::write(dir.join("src/a.txt"), "aaaa").unwrap();
        std::fs::write(dir.join("src/inner/b.txt"), "bb").unwrap();
        dir
    }

    fn quiet(op: &Op) -> Report {
        run(op, &CancelToken::new(), &mut |_| {})
    }

    #[test]
    fn copies_trees_and_counts_progress() {
        let dir = base("copy");
        let op = Op::Copy {
            from: vec![dir.join("src")],
            into: dir.join("dst"),
            conflict: Conflict::Rename,
        };
        let mut last = Progress::default();
        let report = run(&op, &CancelToken::new(), &mut |p| last = p.clone());
        assert!(report.errors.is_empty(), "{report:?}");
        assert_eq!(report.made, [dir.join("dst/src")]);
        assert_eq!((last.items, last.total_items), (4, 4));
        assert_eq!((last.bytes, last.total_bytes), (6, 6));
        assert_eq!(last.fraction(), 1.0);
        assert_eq!(
            std::fs::read_to_string(dir.join("dst/src/inner/b.txt")).unwrap(),
            "bb"
        );
        // Copied again: a free name.
        quiet(&op);
        assert!(dir.join("dst/src_1/a.txt").exists());
        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn conflicts_skip_overwrite_and_never_into_itself() {
        let dir = base("conflict");
        std::fs::write(dir.join("dst/a.txt"), "old").unwrap();
        let op = |conflict| Op::Copy {
            from: vec![dir.join("src/a.txt")],
            into: dir.join("dst"),
            conflict,
        };
        quiet(&op(Conflict::Skip));
        assert_eq!(
            std::fs::read_to_string(dir.join("dst/a.txt")).unwrap(),
            "old"
        );
        quiet(&op(Conflict::Overwrite));
        assert_eq!(
            std::fs::read_to_string(dir.join("dst/a.txt")).unwrap(),
            "aaaa"
        );
        let into_itself = quiet(&Op::Copy {
            from: vec![dir.join("src")],
            into: dir.join("src/inner"),
            conflict: Conflict::Rename,
        });
        assert_eq!(into_itself.errors, ["src: can't go inside itself"]);
        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn moves_and_deletes() {
        let dir = base("move");
        let report = quiet(&Op::Move {
            from: vec![dir.join("src/inner")],
            into: dir.join("dst"),
            conflict: Conflict::Rename,
        });
        assert!(report.errors.is_empty(), "{report:?}");
        assert!(!dir.join("src/inner").exists());
        assert!(dir.join("dst/inner/b.txt").exists());
        // A cut pasted where it already is stays.
        quiet(&Op::Move {
            from: vec![dir.join("dst/inner")],
            into: dir.join("dst"),
            conflict: Conflict::Rename,
        });
        assert!(dir.join("dst/inner/b.txt").exists());
        let mut items = 0;
        let report = run(
            &Op::Delete(vec![dir.join("dst")]),
            &CancelToken::new(),
            &mut |p| items = p.items,
        );
        assert!(report.errors.is_empty());
        assert_eq!(items, 3);
        assert!(!dir.join("dst").exists());
        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn cancelling_stops_and_removes_the_half_copied_file() {
        let dir = base("cancel");
        std::fs::write(dir.join("src/big.bin"), vec![7u8; CHUNK * 3]).unwrap();
        let cancel = CancelToken::new();
        let stop = cancel.clone();
        let report = run(
            &Op::Copy {
                from: vec![dir.join("src/big.bin")],
                into: dir.join("dst"),
                conflict: Conflict::Rename,
            },
            &cancel,
            &mut |p| {
                if p.bytes >= CHUNK as u64 {
                    stop.cancel();
                }
            },
        );
        assert!(report.cancelled);
        assert!(report.errors.is_empty(), "{report:?}");
        assert!(!dir.join("dst/big.bin").exists());
        std::fs::remove_dir_all(&dir).ok();
    }

    #[cfg(unix)]
    #[test]
    fn links_absolute_relative_and_hard() {
        let dir = base("link");
        let link = |kind| {
            quiet(&Op::Link {
                from: vec![dir.join("src/a.txt"), dir.join("src/inner")],
                into: dir.join("dst"),
                kind,
                conflict: Conflict::Rename,
            })
        };
        let report = link(LinkKind::Symbolic { relative: false });
        assert!(report.errors.is_empty(), "{report:?}");
        assert_eq!(report.made, [dir.join("dst/a.txt"), dir.join("dst/inner")]);
        assert_eq!(
            std::fs::read_link(dir.join("dst/a.txt")).unwrap(),
            dir.join("src/a.txt")
        );
        assert_eq!(
            std::fs::read_to_string(dir.join("dst/inner/b.txt")).unwrap(),
            "bb"
        );
        // Again, relative: the names are taken, so a_1.txt and inner_1.
        let report = link(LinkKind::Symbolic { relative: true });
        assert!(report.errors.is_empty(), "{report:?}");
        assert_eq!(
            std::fs::read_link(dir.join("dst/a_1.txt")).unwrap(),
            Path::new("../src/a.txt")
        );
        assert_eq!(
            std::fs::read_link(dir.join("dst/inner_1")).unwrap(),
            Path::new("../src/inner")
        );
        // Hard links: the same file, a directory made again.
        std::fs::remove_dir_all(dir.join("dst")).unwrap();
        std::fs::create_dir(dir.join("dst")).unwrap();
        let mut last = Progress::default();
        let report = run(
            &Op::Link {
                from: vec![dir.join("src")],
                into: dir.join("dst"),
                kind: LinkKind::Hard,
                conflict: Conflict::Rename,
            },
            &CancelToken::new(),
            &mut |p| last = p.clone(),
        );
        assert!(report.errors.is_empty(), "{report:?}");
        assert_eq!((last.items, last.total_items), (4, 4));
        let meta = std::fs::symlink_metadata(dir.join("dst/src/inner/b.txt")).unwrap();
        assert!(meta.is_file());
        std::fs::write(dir.join("src/inner/b.txt"), "changed").unwrap();
        assert_eq!(
            std::fs::read_to_string(dir.join("dst/src/inner/b.txt")).unwrap(),
            "changed"
        );
        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn relative_paths_climb_to_what_they_share() {
        assert_eq!(
            relative_to(Path::new("/a/b/c.txt"), Path::new("/a/d/e")),
            Path::new("../../b/c.txt")
        );
        assert_eq!(relative_to(Path::new("/a"), Path::new("/a")), Path::new(""));
    }

    #[test]
    fn titles() {
        let op = Op::Copy {
            from: vec![PathBuf::from("/a/x.txt")],
            into: PathBuf::from("/b/docs"),
            conflict: Conflict::Rename,
        };
        assert_eq!(op.title(), "Copy x.txt to docs");
        assert_eq!(
            Op::Delete(vec![PathBuf::from("a"), PathBuf::from("b")]).title(),
            "Delete 2 items"
        );
        let link = |kind| Op::Link {
            from: vec![PathBuf::from("/a/x.txt")],
            into: PathBuf::from("/b/docs"),
            kind,
            conflict: Conflict::Rename,
        };
        assert_eq!(link(LinkKind::Hard).title(), "Hard link x.txt in docs");
        assert_eq!(
            link(LinkKind::Symbolic { relative: true }).title(),
            "Link x.txt in docs"
        );
    }
}