kaish-vfs 0.17.0

kaish VFS contract: the Filesystem trait and the LocalFs/MemoryFs backends
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
//! Cross-backend symlink conformance cases.
//!
//! Each case gets a fresh, empty writable root and exercises one symlink
//! behavior against the [`Filesystem`] trait. An embedder runs the whole
//! suite against its own backend via [`run_all`], supplying an adapter
//! that builds a fresh root per case.

use crate::Filesystem;
use std::future::Future;
use std::path::Path;
use std::pin::Pin;

/// One conformance case: an empty writable root in, pass/fail out.
pub type Case = for<'a> fn(
    &'a dyn Filesystem,
) -> Pin<Box<dyn Future<Output = Result<(), String>> + Send + 'a>>;

pub async fn lstat_reports_the_link_itself(fs: &dyn Filesystem) -> Result<(), String> {
    fs.write(Path::new("target"), b"TARGET")
        .await
        .map_err(|e| format!("write target: {e}"))?;
    fs.symlink(Path::new("target"), Path::new("link"))
        .await
        .map_err(|e| format!("symlink: {e}"))?;

    let lstat_entry = fs
        .lstat(Path::new("link"))
        .await
        .map_err(|e| format!("lstat(link): {e}"))?;
    if !lstat_entry.is_symlink() {
        return Err(format!(
            "expected lstat(link) to report symlink kind, got {:?}",
            lstat_entry.kind
        ));
    }

    let stat_entry = fs
        .stat(Path::new("link"))
        .await
        .map_err(|e| format!("stat(link): {e}"))?;
    if !stat_entry.is_file() {
        return Err(format!(
            "expected stat(link) to report a regular file, got {:?}",
            stat_entry.kind
        ));
    }
    Ok(())
}

pub async fn read_link_returns_the_target_verbatim(fs: &dyn Filesystem) -> Result<(), String> {
    fs.symlink(Path::new("target"), Path::new("link"))
        .await
        .map_err(|e| format!("symlink: {e}"))?;

    let target = fs
        .read_link(Path::new("link"))
        .await
        .map_err(|e| format!("read_link(link): {e}"))?;
    if target != Path::new("target") {
        return Err(format!(
            "expected read_link(link) == \"target\", got {}",
            target.display()
        ));
    }
    Ok(())
}

pub async fn relative_target_resolves_from_the_link_directory(
    fs: &dyn Filesystem,
) -> Result<(), String> {
    fs.write(Path::new("target"), b"ROOT")
        .await
        .map_err(|e| format!("write root target: {e}"))?;
    fs.mkdir(Path::new("d"))
        .await
        .map_err(|e| format!("mkdir d: {e}"))?;
    fs.write(Path::new("d/target"), b"D")
        .await
        .map_err(|e| format!("write d/target: {e}"))?;
    fs.symlink(Path::new("target"), Path::new("d/link"))
        .await
        .map_err(|e| format!("symlink d/link -> target: {e}"))?;

    let data = fs
        .read(Path::new("d/link"))
        .await
        .map_err(|e| format!("read(d/link): {e}"))?;
    if data != b"D" {
        return Err(format!(
            "expected read(d/link) == b\"D\" (resolved from d/), got {:?}",
            String::from_utf8_lossy(&data)
        ));
    }

    let entry = fs
        .stat(Path::new("d/link"))
        .await
        .map_err(|e| format!("stat(d/link): {e}"))?;
    if !entry.is_file() {
        return Err(format!(
            "expected stat(d/link) to be a regular file, got {:?}",
            entry.kind
        ));
    }
    Ok(())
}

pub async fn dangling_link_is_visible_to_lstat_but_not_stat(
    fs: &dyn Filesystem,
) -> Result<(), String> {
    fs.symlink(Path::new("nowhere"), Path::new("link"))
        .await
        .map_err(|e| format!("symlink: {e}"))?;

    let lstat_entry = fs
        .lstat(Path::new("link"))
        .await
        .map_err(|e| format!("lstat(link): {e}"))?;
    if !lstat_entry.is_symlink() {
        return Err(format!(
            "expected lstat(link) to report symlink kind, got {:?}",
            lstat_entry.kind
        ));
    }

    match fs.stat(Path::new("link")).await {
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
        Err(e) => {
            return Err(format!(
                "expected stat(link) to be Err(NotFound), got a different error: {e}"
            ))
        }
        Ok(entry) => {
            return Err(format!(
                "expected stat(link) to be Err(NotFound), got Ok({:?})",
                entry.kind
            ))
        }
    }

    if fs.exists(Path::new("link")).await {
        return Err("expected exists(link) == false for a dangling link".to_string());
    }

    let target = fs
        .read_link(Path::new("link"))
        .await
        .map_err(|e| format!("read_link(link): {e}"))?;
    if target != Path::new("nowhere") {
        return Err(format!(
            "expected read_link(link) == \"nowhere\", got {}",
            target.display()
        ));
    }
    Ok(())
}

pub async fn remove_unlinks_the_link_and_keeps_the_file(
    fs: &dyn Filesystem,
) -> Result<(), String> {
    fs.write(Path::new("target"), b"TARGET")
        .await
        .map_err(|e| format!("write target: {e}"))?;
    fs.symlink(Path::new("target"), Path::new("link"))
        .await
        .map_err(|e| format!("symlink: {e}"))?;
    fs.remove(Path::new("link"))
        .await
        .map_err(|e| format!("remove(link): {e}"))?;

    if let Ok(entry) = fs.lstat(Path::new("link")).await {
        return Err(format!(
            "expected lstat(link) to be Err after remove, got Ok({:?})",
            entry.kind
        ));
    }

    let data = fs
        .read(Path::new("target"))
        .await
        .map_err(|e| format!("read(target): {e}"))?;
    if data != b"TARGET" {
        return Err(format!(
            "expected read(target) == b\"TARGET\" after removing the link, got {:?}",
            String::from_utf8_lossy(&data)
        ));
    }
    Ok(())
}

pub async fn remove_unlinks_a_link_to_a_directory(fs: &dyn Filesystem) -> Result<(), String> {
    fs.mkdir(Path::new("dir"))
        .await
        .map_err(|e| format!("mkdir dir: {e}"))?;
    fs.write(Path::new("dir/inner"), b"INNER")
        .await
        .map_err(|e| format!("write dir/inner: {e}"))?;
    fs.symlink(Path::new("dir"), Path::new("link"))
        .await
        .map_err(|e| format!("symlink: {e}"))?;
    fs.remove(Path::new("link"))
        .await
        .map_err(|e| format!("remove(link): {e}"))?;

    if let Ok(entry) = fs.lstat(Path::new("link")).await {
        return Err(format!(
            "expected lstat(link) to be Err after remove, got Ok({:?})",
            entry.kind
        ));
    }

    let dir_entry = fs
        .stat(Path::new("dir"))
        .await
        .map_err(|e| format!("stat(dir): {e}"))?;
    if !dir_entry.is_dir() {
        return Err(format!(
            "expected dir to still be a directory, got {:?}",
            dir_entry.kind
        ));
    }

    let data = fs
        .read(Path::new("dir/inner"))
        .await
        .map_err(|e| format!("read(dir/inner): {e}"))?;
    if data != b"INNER" {
        return Err(format!(
            "expected read(dir/inner) == b\"INNER\", got {:?}",
            String::from_utf8_lossy(&data)
        ));
    }
    Ok(())
}

pub async fn rename_moves_the_link_not_the_target(fs: &dyn Filesystem) -> Result<(), String> {
    fs.write(Path::new("target"), b"TARGET")
        .await
        .map_err(|e| format!("write target: {e}"))?;
    fs.symlink(Path::new("target"), Path::new("link"))
        .await
        .map_err(|e| format!("symlink: {e}"))?;
    fs.rename(Path::new("link"), Path::new("link2"))
        .await
        .map_err(|e| format!("rename(link, link2): {e}"))?;

    if let Ok(entry) = fs.lstat(Path::new("link")).await {
        return Err(format!(
            "expected lstat(link) to be Err after rename, got Ok({:?})",
            entry.kind
        ));
    }

    let link2_entry = fs
        .lstat(Path::new("link2"))
        .await
        .map_err(|e| format!("lstat(link2): {e}"))?;
    if !link2_entry.is_symlink() {
        return Err(format!(
            "expected lstat(link2) to report symlink kind, got {:?}",
            link2_entry.kind
        ));
    }

    let target = fs
        .read_link(Path::new("link2"))
        .await
        .map_err(|e| format!("read_link(link2): {e}"))?;
    if target != Path::new("target") {
        return Err(format!(
            "expected read_link(link2) == \"target\", got {}",
            target.display()
        ));
    }

    let target_data = fs
        .read(Path::new("target"))
        .await
        .map_err(|e| format!("read(target): {e}"))?;
    if target_data != b"TARGET" {
        return Err(format!(
            "expected read(target) == b\"TARGET\", got {:?}",
            String::from_utf8_lossy(&target_data)
        ));
    }

    let link2_data = fs
        .read(Path::new("link2"))
        .await
        .map_err(|e| format!("read(link2): {e}"))?;
    if link2_data != b"TARGET" {
        return Err(format!(
            "expected read(link2) == b\"TARGET\", got {:?}",
            String::from_utf8_lossy(&link2_data)
        ));
    }
    Ok(())
}

pub async fn rename_onto_a_file_link_replaces_the_link(
    fs: &dyn Filesystem,
) -> Result<(), String> {
    fs.write(Path::new("src"), b"NEW")
        .await
        .map_err(|e| format!("write src: {e}"))?;
    fs.write(Path::new("target"), b"TARGET")
        .await
        .map_err(|e| format!("write target: {e}"))?;
    fs.symlink(Path::new("target"), Path::new("link"))
        .await
        .map_err(|e| format!("symlink: {e}"))?;
    fs.rename(Path::new("src"), Path::new("link"))
        .await
        .map_err(|e| format!("rename(src, link): {e}"))?;

    let link_entry = fs
        .lstat(Path::new("link"))
        .await
        .map_err(|e| format!("lstat(link): {e}"))?;
    if !link_entry.is_file() {
        return Err(format!(
            "expected lstat(link) to be a regular file after rename onto it, got {:?}",
            link_entry.kind
        ));
    }

    let link_data = fs
        .read(Path::new("link"))
        .await
        .map_err(|e| format!("read(link): {e}"))?;
    if link_data != b"NEW" {
        return Err(format!(
            "expected read(link) == b\"NEW\", got {:?}",
            String::from_utf8_lossy(&link_data)
        ));
    }

    let target_data = fs
        .read(Path::new("target"))
        .await
        .map_err(|e| format!("read(target): {e}"))?;
    if target_data != b"TARGET" {
        return Err(format!(
            "expected read(target) unchanged == b\"TARGET\" (rename must not write through the link), got {:?}",
            String::from_utf8_lossy(&target_data)
        ));
    }

    if let Ok(entry) = fs.lstat(Path::new("src")).await {
        return Err(format!(
            "expected lstat(src) to be Err after rename, got Ok({:?})",
            entry.kind
        ));
    }
    Ok(())
}

pub async fn rename_onto_a_dangling_link_replaces_the_link(
    fs: &dyn Filesystem,
) -> Result<(), String> {
    fs.write(Path::new("src"), b"NEW")
        .await
        .map_err(|e| format!("write src: {e}"))?;
    fs.symlink(Path::new("nowhere"), Path::new("link"))
        .await
        .map_err(|e| format!("symlink: {e}"))?;
    fs.rename(Path::new("src"), Path::new("link"))
        .await
        .map_err(|e| format!("rename(src, link): {e}"))?;

    let link_entry = fs
        .lstat(Path::new("link"))
        .await
        .map_err(|e| format!("lstat(link): {e}"))?;
    if !link_entry.is_file() {
        return Err(format!(
            "expected lstat(link) to be a regular file after rename onto it, got {:?}",
            link_entry.kind
        ));
    }

    let link_data = fs
        .read(Path::new("link"))
        .await
        .map_err(|e| format!("read(link): {e}"))?;
    if link_data != b"NEW" {
        return Err(format!(
            "expected read(link) == b\"NEW\", got {:?}",
            String::from_utf8_lossy(&link_data)
        ));
    }
    Ok(())
}

pub async fn rename_onto_a_directory_link_replaces_the_link(
    fs: &dyn Filesystem,
) -> Result<(), String> {
    fs.write(Path::new("src"), b"NEW")
        .await
        .map_err(|e| format!("write src: {e}"))?;
    fs.mkdir(Path::new("dir"))
        .await
        .map_err(|e| format!("mkdir dir: {e}"))?;
    fs.symlink(Path::new("dir"), Path::new("link"))
        .await
        .map_err(|e| format!("symlink: {e}"))?;
    fs.rename(Path::new("src"), Path::new("link"))
        .await
        .map_err(|e| format!("rename(src, link): {e}"))?;

    let link_entry = fs
        .lstat(Path::new("link"))
        .await
        .map_err(|e| format!("lstat(link): {e}"))?;
    if !link_entry.is_file() {
        return Err(format!(
            "expected lstat(link) to be a regular file after rename onto it (POSIX rename does not follow the destination), got {:?}",
            link_entry.kind
        ));
    }

    let link_data = fs
        .read(Path::new("link"))
        .await
        .map_err(|e| format!("read(link): {e}"))?;
    if link_data != b"NEW" {
        return Err(format!(
            "expected read(link) == b\"NEW\", got {:?}",
            String::from_utf8_lossy(&link_data)
        ));
    }

    let dir_entry = fs
        .stat(Path::new("dir"))
        .await
        .map_err(|e| format!("stat(dir): {e}"))?;
    if !dir_entry.is_dir() {
        return Err(format!(
            "expected dir to still exist as a directory, got {:?}",
            dir_entry.kind
        ));
    }

    let listing = fs
        .list(Path::new("dir"))
        .await
        .map_err(|e| format!("list(dir): {e}"))?;
    if !listing.is_empty() {
        return Err(format!(
            "expected dir to remain empty (nothing moved into it), got {} entries",
            listing.len()
        ));
    }
    Ok(())
}

pub async fn write_through_a_file_link_updates_the_target(
    fs: &dyn Filesystem,
) -> Result<(), String> {
    fs.write(Path::new("target"), b"TARGET")
        .await
        .map_err(|e| format!("write target: {e}"))?;
    fs.symlink(Path::new("target"), Path::new("link"))
        .await
        .map_err(|e| format!("symlink: {e}"))?;
    fs.write(Path::new("link"), b"VIA LINK")
        .await
        .map_err(|e| format!("write(link): {e}"))?;

    let target_data = fs
        .read(Path::new("target"))
        .await
        .map_err(|e| format!("read(target): {e}"))?;
    if target_data != b"VIA LINK" {
        return Err(format!(
            "expected read(target) == b\"VIA LINK\" (write follows the link), got {:?}",
            String::from_utf8_lossy(&target_data)
        ));
    }

    let link_entry = fs
        .lstat(Path::new("link"))
        .await
        .map_err(|e| format!("lstat(link): {e}"))?;
    if !link_entry.is_symlink() {
        return Err(format!(
            "expected lstat(link) to still report symlink kind after write, got {:?}",
            link_entry.kind
        ));
    }
    Ok(())
}

pub async fn stat_on_a_link_loop_errors_instead_of_hanging(
    fs: &dyn Filesystem,
) -> Result<(), String> {
    fs.symlink(Path::new("b"), Path::new("a"))
        .await
        .map_err(|e| format!("symlink a -> b: {e}"))?;
    fs.symlink(Path::new("a"), Path::new("b"))
        .await
        .map_err(|e| format!("symlink b -> a: {e}"))?;

    match tokio::time::timeout(std::time::Duration::from_secs(2), fs.stat(Path::new("a"))).await {
        Ok(Ok(entry)) => Err(format!(
            "expected stat(a) to error on a symlink loop, got Ok({:?})",
            entry.kind
        )),
        Ok(Err(_)) => Ok(()),
        Err(_) => Err("stat(a) hung on a symlink loop instead of erroring".to_string()),
    }
}

pub async fn list_shows_a_link_as_a_link(fs: &dyn Filesystem) -> Result<(), String> {
    fs.write(Path::new("target"), b"TARGET")
        .await
        .map_err(|e| format!("write target: {e}"))?;
    fs.symlink(Path::new("target"), Path::new("link"))
        .await
        .map_err(|e| format!("symlink: {e}"))?;

    let entries = fs
        .list(Path::new(""))
        .await
        .map_err(|e| format!("list(\"\"): {e}"))?;
    let names: Vec<&str> = entries.iter().map(|e| e.name.as_str()).collect();

    let link_entry = entries
        .iter()
        .find(|e| e.name == "link")
        .ok_or_else(|| format!("expected an entry named \"link\" in list(\"\"), got {names:?}"))?;
    if !link_entry.is_symlink() {
        return Err(format!(
            "expected the \"link\" entry to be symlink kind, got {:?}",
            link_entry.kind
        ));
    }

    let target_entry = entries
        .iter()
        .find(|e| e.name == "target")
        .ok_or_else(|| {
            format!("expected an entry named \"target\" in list(\"\"), got {names:?}")
        })?;
    if !target_entry.is_file() {
        return Err(format!(
            "expected the \"target\" entry to be file kind, got {:?}",
            target_entry.kind
        ));
    }
    Ok(())
}

pub async fn symlink_refuses_an_absolute_target(fs: &dyn Filesystem) -> Result<(), String> {
    fs.write(Path::new("target"), b"TARGET")
        .await
        .map_err(|e| format!("write target: {e}"))?;

    match fs.symlink(Path::new("/target"), Path::new("link")).await {
        Err(e) if e.kind() == std::io::ErrorKind::InvalidInput => {}
        Err(e) => {
            return Err(format!(
                "expected symlink(\"/target\") to be Err(InvalidInput), got a different error: {e}"
            ))
        }
        Ok(()) => return Err("expected symlink(\"/target\") to be refused, got Ok".to_string()),
    }
    if let Ok(entry) = fs.lstat(Path::new("link")).await {
        return Err(format!(
            "expected nothing at link after the refusal, got {:?}",
            entry.kind
        ));
    }
    Ok(())
}

pub async fn list_through_a_link_to_a_directory(fs: &dyn Filesystem) -> Result<(), String> {
    fs.mkdir(Path::new("dir"))
        .await
        .map_err(|e| format!("mkdir dir: {e}"))?;
    fs.write(Path::new("dir/inner"), b"I")
        .await
        .map_err(|e| format!("write dir/inner: {e}"))?;
    fs.symlink(Path::new("dir"), Path::new("link"))
        .await
        .map_err(|e| format!("symlink: {e}"))?;

    let entries = fs
        .list(Path::new("link"))
        .await
        .map_err(|e| format!("list(link) must follow the link: {e}"))?;
    let names: Vec<&str> = entries.iter().map(|e| e.name.as_str()).collect();
    if names != ["inner"] {
        return Err(format!("expected list(link) == [\"inner\"], got {names:?}"));
    }
    Ok(())
}

pub async fn set_mtime_through_a_link_touches_the_target(
    fs: &dyn Filesystem,
) -> Result<(), String> {
    fs.write(Path::new("target"), b"TARGET")
        .await
        .map_err(|e| format!("write target: {e}"))?;
    fs.symlink(Path::new("target"), Path::new("link"))
        .await
        .map_err(|e| format!("symlink: {e}"))?;

    let stamp = std::time::UNIX_EPOCH + std::time::Duration::from_secs(1_000_000);
    fs.set_mtime(Path::new("link"), stamp)
        .await
        .map_err(|e| format!("set_mtime(link) must follow the link: {e}"))?;

    let entry = fs
        .stat(Path::new("target"))
        .await
        .map_err(|e| format!("stat(target): {e}"))?;
    if entry.modified != Some(stamp) {
        return Err(format!(
            "expected the target's mtime to be the stamp, got {:?}",
            entry.modified
        ));
    }
    let link_entry = fs
        .lstat(Path::new("link"))
        .await
        .map_err(|e| format!("lstat(link): {e}"))?;
    if !link_entry.is_symlink() {
        return Err(format!("expected link to still be a symlink, got {:?}", link_entry.kind));
    }
    Ok(())
}

pub async fn rename_to_itself_keeps_the_file(fs: &dyn Filesystem) -> Result<(), String> {
    fs.write(Path::new("file"), b"KEEP")
        .await
        .map_err(|e| format!("write file: {e}"))?;
    fs.rename(Path::new("file"), Path::new("file"))
        .await
        .map_err(|e| format!("rename(file, file): {e}"))?;
    let data = fs
        .read(Path::new("file"))
        .await
        .map_err(|e| format!("read(file) after identity rename: {e}"))?;
    if data != b"KEEP" {
        return Err(format!("expected b\"KEEP\", got {:?}", String::from_utf8_lossy(&data)));
    }
    Ok(())
}

pub async fn rename_to_itself_spelled_with_dotdot_keeps_the_file(
    fs: &dyn Filesystem,
) -> Result<(), String> {
    fs.mkdir(Path::new("d"))
        .await
        .map_err(|e| format!("mkdir d: {e}"))?;
    fs.write(Path::new("d/file"), b"KEEP")
        .await
        .map_err(|e| format!("write d/file: {e}"))?;
    fs.rename(Path::new("d/../d/file"), Path::new("d/file"))
        .await
        .map_err(|e| format!("rename(d/../d/file, d/file): {e}"))?;
    let data = fs
        .read(Path::new("d/file"))
        .await
        .map_err(|e| format!("read(d/file) after identity rename: {e}"))?;
    if data != b"KEEP" {
        return Err(format!("expected b\"KEEP\", got {:?}", String::from_utf8_lossy(&data)));
    }
    Ok(())
}

pub async fn remove_refuses_the_root(fs: &dyn Filesystem) -> Result<(), String> {
    // The root is empty here, so "not empty" cannot be the reason.
    for spelling in ["", "/", ".", "./", "a/.."] {
        if fs.remove(Path::new(spelling)).await.is_ok() {
            return Err(format!("remove({spelling:?}) removed the empty mount root"));
        }
    }
    fs.write(Path::new("keep"), b"K")
        .await
        .map_err(|e| format!("write keep after the refusals (root gone?): {e}"))?;
    if fs.remove(Path::new("")).await.is_ok() {
        return Err("remove(\"\") removed the mount root".to_string());
    }
    fs.read(Path::new("keep"))
        .await
        .map_err(|e| format!("read(keep): {e}"))?;
    Ok(())
}

pub async fn rename_refuses_the_root(fs: &dyn Filesystem) -> Result<(), String> {
    fs.write(Path::new("keep"), b"K")
        .await
        .map_err(|e| format!("write keep: {e}"))?;
    if fs.rename(Path::new(""), Path::new("moved")).await.is_ok() {
        return Err("rename(\"\", moved) moved the mount root".to_string());
    }
    if fs.rename(Path::new("keep"), Path::new("")).await.is_ok() {
        return Err("rename(keep, \"\") replaced the mount root".to_string());
    }
    fs.read(Path::new("keep"))
        .await
        .map_err(|e| format!("read(keep) after the refusals: {e}"))?;
    if fs.lstat(Path::new("moved")).await.is_ok() {
        return Err("a path named moved appeared".to_string());
    }
    Ok(())
}

// Adapts an async case fn to the boxed-future `Case` fn-pointer shape. The
// local `adapt` fn is a fresh item per invocation, so names never collide.
macro_rules! case {
    ($name:ident) => {{
        fn adapt(
            fs: &dyn Filesystem,
        ) -> Pin<Box<dyn Future<Output = Result<(), String>> + Send + '_>> {
            Box::pin($name(fs))
        }
        (stringify!($name), adapt as Case)
    }};
}

pub const CASES: &[(&str, Case)] = &[
    case!(lstat_reports_the_link_itself),
    case!(read_link_returns_the_target_verbatim),
    case!(relative_target_resolves_from_the_link_directory),
    case!(dangling_link_is_visible_to_lstat_but_not_stat),
    case!(remove_unlinks_the_link_and_keeps_the_file),
    case!(remove_unlinks_a_link_to_a_directory),
    case!(rename_moves_the_link_not_the_target),
    case!(rename_onto_a_file_link_replaces_the_link),
    case!(rename_onto_a_dangling_link_replaces_the_link),
    case!(rename_onto_a_directory_link_replaces_the_link),
    case!(write_through_a_file_link_updates_the_target),
    case!(stat_on_a_link_loop_errors_instead_of_hanging),
    case!(list_shows_a_link_as_a_link),
    case!(symlink_refuses_an_absolute_target),
    case!(list_through_a_link_to_a_directory),
    case!(set_mtime_through_a_link_touches_the_target),
    case!(rename_to_itself_keeps_the_file),
    case!(rename_to_itself_spelled_with_dotdot_keeps_the_file),
    case!(remove_refuses_the_root),
    case!(rename_refuses_the_root),
];

/// Runs every case, each against its own fresh root from `make_root`.
pub async fn run_all<F, Fut>(make_root: F) -> Vec<(&'static str, Result<(), String>)>
where
    F: Fn() -> Fut,
    Fut: Future<Output = Box<dyn Filesystem>>,
{
    let mut results = Vec::with_capacity(CASES.len());
    for (name, case) in CASES {
        let root = make_root().await;
        results.push((*name, case(root.as_ref()).await));
    }
    results
}

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

    fn assert_no_failures(backend: &str, results: Vec<(&'static str, Result<(), String>)>) {
        let failures: Vec<String> = results
            .into_iter()
            .filter_map(|(name, outcome)| outcome.err().map(|msg| format!("{name}: {msg}")))
            .collect();
        if !failures.is_empty() {
            panic!(
                "{backend} conformance failures ({}):\n{}",
                failures.len(),
                failures.join("\n")
            );
        }
    }

    #[cfg(all(unix, feature = "localfs"))]
    #[tokio::test]
    async fn localfs_conformance() {
        use crate::local::LocalFs;

        // Hold every TempDir until the assertions run, so the roots are
        // removed on drop instead of leaking under /tmp.
        let kept = std::sync::Mutex::new(Vec::new());
        let results = run_all(|| async {
            let dir = tempfile::tempdir().expect("tempdir");
            let fs = LocalFs::new(dir.path());
            kept.lock().expect("tempdir list").push(dir);
            Box::new(fs) as Box<dyn Filesystem>
        })
        .await;
        assert_no_failures("LocalFs", results);
        drop(kept);
    }

    #[cfg(feature = "memory")]
    #[tokio::test]
    async fn memoryfs_conformance() {
        use crate::memory::MemoryFs;

        let results = run_all(|| async { Box::new(MemoryFs::new()) as Box<dyn Filesystem> }).await;
        assert_no_failures("MemoryFs", results);
    }

    #[cfg(all(feature = "overlay", feature = "memory"))]
    #[tokio::test]
    async fn overlayfs_conformance() {
        use crate::memory::MemoryFs;
        use crate::overlay::OverlayFs;
        use std::sync::Arc;

        let results = run_all(|| async {
            let lower: Arc<dyn Filesystem> = Arc::new(MemoryFs::new());
            Box::new(OverlayFs::over(lower)) as Box<dyn Filesystem>
        })
        .await;
        assert_no_failures("OverlayFs", results);
    }
}