ironpath 0.1.1

An iron-hard crate for handling filesystem paths
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
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
use env_logger;
use tempfile;

use super::*;
use std::env;
use std::fs;

#[test]
fn relative_accepts_empty_path() {
    let _ = env_logger::try_init();

    let actual = Relative::new("").expect("Could not parse empty path");

    let expected = path::Path::new("");

    assert_eq!(actual.0, expected);
}

fn create_cookie_at<P: AsRef<path::Path>>(path: P) -> String {
    use std::io::Write;

    // Generate a string that should be different for every run of the test
    // suite.
    let res = format!(
        "pid: {} time: {:?}",
        std::process::id(),
        std::time::Instant::now(),
    );

    // Write our string to the given path
    println!("Creating cookie at {:?}", path.as_ref());
    let mut handle = fs::File::create(path).expect("Could not create file?");
    handle
        .write_all(res.as_bytes())
        .expect("Could not write message?");

    res
}

fn check_cookie_at<P: AsRef<path::Path>>(expected: &str, path: P) {
    // Read our string back through the cleaned-up path.
    let actual = {
        use std::io::Read;

        println!("Checking cookie at {:?}", path.as_ref());
        let mut handle = fs::File::open(path).expect("Could not open file?");
        let mut res = String::new();

        handle
            .read_to_string(&mut res)
            .expect("Could not read message?");

        res
    };

    // Our message should have round-tripped correctly.
    assert_eq!(actual, expected);
}

#[cfg(windows)]
fn symlink_dir<P, Q>(src: P, dst: Q)
where
    P: AsRef<path::Path>,
    Q: AsRef<path::Path>,
{
    use std::os::windows::fs;

    let dst = dst.as_ref();

    fs::symlink_dir(src, &dst).expect(
        "Could not create symbolic link? \
         Run as Administrator, or on Windows 10 in Developer Mode",
    );
    dst.symlink_metadata().expect(
        "Link creation succeeded, but can't read link? \
         If you're using Wine, see bug 44948",
    );
}

#[cfg(unix)]
fn symlink_dir<P, Q>(src: P, dst: Q)
where
    P: AsRef<path::Path>,
    Q: AsRef<path::Path>,
{
    use std::os::unix::fs;

    fs::symlink(src, dst).expect("Could not create symbolic link?");
}

#[test]
fn simple_absolute_path_works_after_cleaning() {
    let _ = env_logger::try_init();

    let temp =
        tempfile::tempdir().expect("Could not make temporary directory.");

    let normal_path = temp.path().join("foo.txt");

    let cookie = create_cookie_at(&normal_path);
    check_cookie_at(
        &cookie,
        Absolute::new(normal_path).expect("Could not clean absolute path?"),
    );
}

#[test]
fn absolute_path_with_single_dot_works_after_cleaning() {
    let _ = env_logger::try_init();

    let temp =
        tempfile::tempdir().expect("Could not make temporary directory.");

    let normal_path = temp.path().join("./././foo.txt");

    let cookie = create_cookie_at(&normal_path);
    check_cookie_at(
        &cookie,
        Absolute::new(normal_path)
            .expect("Could not clean path with single dots?"),
    );
}

#[test]
fn absolute_path_with_double_dot_from_existing_dir_works_after_cleaning() {
    let _ = env_logger::try_init();

    let temp =
        tempfile::tempdir().expect("Could not make temporary directory.");

    let parent = temp.path().join("parent");
    fs::create_dir_all(&parent).expect("Could not create parent dir?");

    let normal_path = parent.join("../foo.txt");

    let cookie = create_cookie_at(&normal_path);
    check_cookie_at(
        &cookie,
        Absolute::new(normal_path)
            .expect("Could not clean path with double dots?"),
    );
}

#[test]
fn double_dot_after_relative_symlink_works_as_expected() {
    let _ = env_logger::try_init();

    let temp =
        tempfile::tempdir().expect("Could not make temporary directory.");

    fs::create_dir_all(temp.path().join("apple/ant"))
        .expect("Could not create apple/ant dir?");

    fs::create_dir_all(temp.path().join("banana"))
        .expect("Could not create banana dir?");

    symlink_dir("../apple/ant", temp.path().join("banana/bat"));

    // On POSIX, "banana/bat/../foo.txt" is "apple/foo.txt".
    // On Windows, it's "banana/foo.txt".
    // We don't mind which we use,
    // as long as we match the platform we're running on.
    let normal_path = temp.path().join("banana/bat/../foo.txt");
    let cookie = create_cookie_at(&normal_path);
    check_cookie_at(
        &cookie,
        Absolute::new(normal_path)
            .expect("Could not clean path through a symlink?"),
    );
}

#[test]
fn double_dot_after_absolute_symlink_works_as_expected() {
    let _ = env_logger::try_init();

    let temp =
        tempfile::tempdir().expect("Could not make temporary directory.");

    fs::create_dir_all(temp.path().join("apple/ant"))
        .expect("Could not create apple/ant dir?");

    fs::create_dir_all(temp.path().join("banana"))
        .expect("Could not create banana dir?");

    symlink_dir(
        temp.path().join("apple/ant"),
        temp.path().join("banana/bat"),
    );

    // On POSIX, "banana/bat/../foo.txt" is "apple/foo.txt".
    // On Windows, it's "banana/foo.txt".
    // We don't mind which we use,
    // as long as we match the platform we're running on.
    let normal_path = temp.path().join("banana/bat/../foo.txt");
    let cookie = create_cookie_at(&normal_path);
    check_cookie_at(
        &cookie,
        Absolute::new(normal_path)
            .expect("Could not clean path through a symlink?"),
    );
}

#[test]
fn cleaning_is_idempotent() {
    let _ = env_logger::try_init();

    let temp =
        tempfile::tempdir().expect("Could not make temporary directory.");

    let first =
        Absolute::new(temp.path()).expect("Could not clean sensible path?");

    let second =
        Absolute::new(&first).expect("Could not re-clean sensible path?");

    assert_eq!(first, second);
}

#[cfg(windows)]
mod windows {
    use super::*;
    #[test]
    fn absolute_path_with_double_dot_from_missing_dir_works_after_cleaning() {
        let _ = env_logger::try_init();

        let temp =
            tempfile::tempdir().expect("Could not make temporary directory.");

        let normal_path = temp.path().join("foo/../bar.txt");

        let cookie = create_cookie_at(&normal_path);
        check_cookie_at(
            &cookie,
            Absolute::new(normal_path)
                .expect("Could not clean path with double dots?"),
        );
    }

    #[test]
    fn absolute_path_gets_canonical_prefix() {
        let _ = env_logger::try_init();

        let path = Absolute::new("C:\\foo\\bar")
            .expect("Could not handle an absolute path");

        assert_eq!(path.0, path::Path::new("\\\\?\\C:\\foo\\bar"));
    }

    #[test]
    fn missing_absolute_path_with_double_dot_is_normalized() {
        let _ = env_logger::try_init();

        let path = Absolute::new("C:\\foo\\..\\bar")
            .expect("Could not handle an absolute path");

        assert_eq!(path.0, path::Path::new("\\\\?\\C:\\bar"));
    }

    #[test]
    fn absolute_path_with_single_dot_is_dropped() {
        let _ = env_logger::try_init();

        let path = Absolute::new("C:\\foo\\.\\bar")
            .expect("Could not handle an absolute path");

        assert_eq!(path.0, path::Path::new("\\\\?\\C:\\foo\\bar"));
    }

    #[test]
    fn absolute_path_with_slashes_is_normalized() {
        let _ = env_logger::try_init();

        let path = Absolute::new("C:/foo/bar")
            .expect("Could not handle an absolute path");

        assert_eq!(path.0, path::Path::new("\\\\?\\C:\\foo\\bar"));
    }

    #[test]
    fn relative_path_is_relative_to_current_directory() {
        let _ = env_logger::try_init();

        let path =
            Absolute::new("foo").expect("Could not handle a relative path");

        let current_dir = env::current_dir()
            .expect("Could not read current directory.")
            .canonicalize()
            .expect("Could not canonicalize current directory.");

        let expected = current_dir.join("foo");

        assert_eq!(path.0, expected);
    }

    #[test]
    fn leading_double_dot_in_relative_path() {
        let _ = env_logger::try_init();

        let path =
            Absolute::new("..\\foo").expect("Could not handle a relative path");

        let current_dir = env::current_dir()
            .expect("Could not read current directory.")
            .canonicalize()
            .expect("Could not canonicalize current directory.");

        let expected = current_dir
            .parent()
            .unwrap_or(path::Path::new("/"))
            .join("foo");

        assert_eq!(path.0, expected);
    }

    #[test]
    fn skip_leading_dot_in_relative_path() {
        let _ = env_logger::try_init();

        let path =
            Absolute::new(".\\foo").expect("Could not handle a relative path");

        let current_dir = env::current_dir()
            .expect("Could not read current directory.")
            .canonicalize()
            .expect("Could not canonicalize current directory.");

        let expected = current_dir.join("foo");

        assert_eq!(path.0, expected);
    }

    #[test]
    fn prefix_relative_path_is_relative_to_current_drive() {
        let _ = env_logger::try_init();

        let actual = Absolute::new("\\foo")
            .expect("Could not handle a prefix-relative path");

        let expected = env::current_dir()
            .expect("Could not read current directory.")
            .canonicalize()
            .expect("Could not canonicalize current directory?")
            .join("\\foo");

        assert_eq!(actual.0, expected);
    }

    /*

    This test can't work without having more than one valid drive letter,
    which we can't possibly guarantee.

    #[test]
    fn drive_relative_path_is_relative_to_drive_directory() {
        let _ = env_logger::try_init();

        // Save the current directory on the current drive.
        let original_dir =
            env::current_dir().expect("Could not read current directory.");

        // Remember which drive that's on.
        let original_drive = original_dir
            .components()
            .next()
            .expect("Current directory is an empty path?")
            .as_os_str();

        // Switch to a different drive.
        assert_ne!(original_drive, "A:");
        env::set_current_dir("A:\\")
            .expect("Could not set current directory to A:\\");
    }
    */

    #[test]
    fn drive_relative_path_uses_drive_current_path() {
        let _ = env_logger::try_init();

        let current_drive = env::current_dir()
            .expect("Could not read current directory")
            .components()
            .next()
            .expect("Current directory is an empty path?")
            .as_os_str()
            .to_os_string();

        // input == "C:foo" assuming C: is the current drive.
        let mut input = current_drive.clone();
        input.push("foo");

        let actual = Absolute::new(input)
            .expect("Could not handle a drive-relative path");

        let expected = env::current_dir()
            .expect("Could not read current directory.")
            .canonicalize()
            .expect("Could not canonicalize current directory.")
            .join("foo");

        assert_eq!(actual.0, expected);
    }

    #[test]
    fn do_not_resolve_every_symlink() {
        let _ = env_logger::try_init();

        let temp =
            tempfile::tempdir().expect("Could not make temporary directory.");

        let target_path = temp.path().join("target");
        let link_path = temp.path().join("link");

        // Create an empty file as the target.
        println!("Creating target path: {:?}", target_path);
        fs::OpenOptions::new()
            .create(true)
            .write(true)
            .open(&target_path)
            .expect("Could not create target");
        assert_eq!(target_path.exists(), true);

        println!("Creating link path: {:?}", link_path);
        symlink_dir(&target_path, &link_path);

        println!("Absolutizing symlink path");
        let actual =
            Absolute::new(&link_path).expect("Could not handle symlink path");
        println!("Actual: {:?}", actual.0);

        let expected = temp
            .path()
            .canonicalize()
            .expect("Could not canonicalize symlink path")
            .join("link");

        assert_eq!(actual.0, expected);
    }

    #[test]
    fn cannot_go_up_from_root_directory() {
        let _ = env_logger::try_init();

        let actual = Absolute::new("C:\\..\\foo")
            .expect("Could not handle going up from the root directory");

        let expected = fs::canonicalize("C:\\")
            .expect("No C:\\ directory?")
            .join("foo");

        assert_eq!(actual.0, expected);
    }

    #[test]
    fn do_not_resolve_absolute_symlinks() {
        let _ = env_logger::try_init();

        let temp = tempfile::tempdir()
            .expect("Could not make temporary directory.")
            .into_path();

        let link_path = temp.join("link");

        debug!("Creating link at: {:?}", link_path);

        symlink_dir("C:\\does\\not\\exist", &link_path);

        let actual = Absolute::new(link_path.join("..\\bar"))
            .expect("Could not handle symlink with absolute target");

        let expected = link_path
            .parent()
            .expect("Temporary directory is rooot?")
            .canonicalize()
            .expect("Could not canonicalize?")
            .join("bar");

        assert_eq!(actual.0, expected);
    }

    #[test]
    fn absolute_accepts_dereferencing_cyclic_symlinks() {
        let _ = env_logger::try_init();

        let temp =
            tempfile::tempdir().expect("Could not make temporary directory.");

        symlink_dir("a", temp.path().join("b"));
        symlink_dir("b", temp.path().join("a"));

        let actual = Absolute::new(temp.path().join("a/../tail"))
            .expect("Could not handle cyclic symlinks?");

        let expected = temp
            .path()
            .canonicalize()
            .expect("Could not canonicalize temp path?")
            .join("tail");

        assert_eq!(actual.0, expected);
    }

    #[test]
    fn absolute_accepts_navigating_cyclic_symlinks() {
        let _ = env_logger::try_init();

        let temp =
            tempfile::tempdir().expect("Could not make temporary directory.");

        symlink_dir(".", temp.path().join("cur"));

        let actual = Absolute::new(temp.path().join("cur/cur/cur/cur/cur/a"))
            .expect("Could not handle cyclic path.");

        let expected = temp
            .path()
            .canonicalize()
            .expect("Could not canonicalize temp dir")
            .join("cur\\cur\\cur\\cur\\cur\\a");

        assert_eq!(actual.0, expected);
    }

    #[test]
    fn absolute_rejects_invalid_prefix() {
        let _ = env_logger::try_init();

        let err = Absolute::new("\\\\?**?\\bogus\\path\\")
            .map(|p| {
                panic!("Parsing bogus path should have failed! {:?}", p);
            })
            .err()
            .unwrap();

        match err {
            Error::IoError { err, at } => {
                assert_eq!(err.kind(), io::ErrorKind::Other);
                assert_eq!(at, path::Path::new("\\\\?**?\\bogus"));
            }
            e => panic!("Got unexpected error {:?}", e),
        }
    }

    #[test]
    fn relative_accepts_monotonic_path() {
        let _ = env_logger::try_init();

        let actual = Relative::new("does\\not\\exist")
            .expect("Could not parse monotonic path");

        let expected = path::Path::new("does\\not\\exist");

        assert_eq!(actual.0, expected);
    }

    #[test]
    fn relative_normalises_slashes() {
        let _ = env_logger::try_init();

        let actual = Relative::new("does/not/exist")
            .expect("Could not parse path with slashes");

        let expected = path::Path::new("does\\not\\exist");

        assert_eq!(actual.0, expected);
    }

    #[test]
    fn relative_normalises_single_dots() {
        let _ = env_logger::try_init();

        let actual = Relative::new("does\\.\\not\\.\\exist")
            .expect("Could not parse path with CurrentDir components");

        let expected = path::Path::new("does\\not\\exist");

        assert_eq!(actual.0, expected);
    }

    #[test]
    fn relative_normalises_inner_double_dots() {
        let _ = env_logger::try_init();

        let actual = Relative::new("does\\..\\not\\exist")
            .expect("Could not parse path with ParentDir component");

        let expected = path::Path::new("not\\exist");

        assert_eq!(actual.0, expected);
    }

    #[test]
    fn relative_rejects_leading_double_dots() {
        let _ = env_logger::try_init();

        let err = Relative::new("..\\does\\not\\exist")
            .err()
            .expect("Parsing leading '..' should have failed!");

        match err {
            Error::RelativePathEscapesPrefix(p) => {
                assert_eq!(p, path::Path::new("..\\does\\not\\exist"))
            }
            e => panic!("Got unexpected error {:?}", e),
        }
    }

    #[test]
    fn relative_rejects_fully_absolute_path() {
        let _ = env_logger::try_init();

        let err = Relative::new("C:\\absolute\\path")
            .err()
            .expect("Parsing an absolute path should have failed!");

        match err {
            Error::PathIsAbsolute(p) => {
                assert_eq!(p, path::Path::new("C:\\absolute\\path"))
            }
            e => panic!("Got unexpected error {:?}", e),
        }
    }

    #[test]
    fn relative_rejects_prefix_relative_path() {
        let _ = env_logger::try_init();

        let err = Relative::new("\\relative\\path")
            .err()
            .expect("Parsing prefix-relative path should have failed!");

        match err {
            Error::PathIsAbsolute(p) => {
                assert_eq!(p, path::Path::new("\\relative\\path"))
            }
            e => panic!("Got unexpected error {:?}", e),
        }
    }

    #[test]
    fn relative_rejects_drive_relative_path() {
        let _ = env_logger::try_init();

        let err = Relative::new("C:relative\\path")
            .err()
            .expect("Parsing drive-relative path should have failed!");

        match err {
            Error::PathIsAbsolute(p) => {
                assert_eq!(p, path::Path::new("C:relative\\path"))
            }
            e => panic!("Got unexpected error {:?}", e),
        }
    }

    #[test]
    fn relative_rejects_relative_path_escaping_prefix() {
        let _ = env_logger::try_init();

        let err = Relative::new("inside\\..\\..\\outside")
            .err()
            .expect("Parsing escaping path should have failed!");

        match err {
            Error::RelativePathEscapesPrefix(p) => {
                assert_eq!(p, path::Path::new("inside\\..\\..\\outside"))
            }
            e => panic!("Got unexpected error {:?}", e),
        }
    }
}

#[cfg(unix)]
mod unix {
    use super::*;
    use std::os::unix::fs as unixfs;

    #[test]
    fn missing_absolute_path_is_unchanged() {
        let _ = env_logger::try_init();

        let expected = path::Path::new("/some/absolute/path");

        let path = Absolute::new(&expected)
            .expect("Could not handle an absolute path");

        assert_eq!(path.0, expected);
    }

    #[test]
    fn missing_absolute_path_with_double_dot_is_normalized() {
        let _ = env_logger::try_init();

        let actual = Absolute::new("/some/absolute/../path")
            .expect("Could not handle an absolute path");
        let expected = path::Path::new("/some/path");

        assert_eq!(actual.0, expected);
    }

    #[test]
    fn existing_path_with_double_dot_is_normalized() {
        let _ = env_logger::try_init();

        let temp =
            tempfile::tempdir().expect("Could not make temporary directory.");

        fs::create_dir_all(temp.path().join("apple"))
            .expect("Could not create apple directory.");
        fs::create_dir_all(temp.path().join("banana"))
            .expect("Could not create apple directory.");

        let actual = Absolute::new(temp.path().join("banana/../apple"))
            .expect("Could not resolve existing directories.");

        let expected = temp.path().join("apple");

        assert_eq!(actual.0, expected);
    }

    #[test]
    fn missing_relative_path_is_relative_to_current_directory() {
        let _ = env_logger::try_init();

        let actual = Absolute::new("does/not/exist")
            .expect("Could not handle a missing relative path");

        let expected = env::current_dir()
            .expect("Could not get current directory")
            .join("does/not/exist");

        assert_eq!(actual.0, expected);
    }

    #[test]
    fn skip_leading_dots() {
        let _ = env_logger::try_init();

        let actual = Absolute::new("/some/./missing/./path")
            .expect("Could not handle a path with dot components");

        let expected = path::Path::new("/some/missing/path");

        assert_eq!(actual.0, expected);
    }

    #[test]
    fn leading_double_dot_in_relative_path() {
        let _ = env_logger::try_init();

        let actual = Absolute::new("../does/not/exist")
            .expect("Could not handle a relative path");

        let expected = env::current_dir()
            .expect("Could not get current directory")
            .parent()
            .unwrap_or_else(|| path::Path::new("/"))
            .join("does/not/exist");

        assert_eq!(actual.0, expected);
    }

    #[test]
    fn do_not_resolve_every_symlink() {
        let _ = env_logger::try_init();

        let temp =
            tempfile::tempdir().expect("Could not make temporary directory.");

        let target_path = temp.path().join("target");
        let link_path = temp.path().join("link");

        // Create an empty file as the target.
        fs::OpenOptions::new()
            .create(true)
            .write(true)
            .open(&target_path)
            .expect("Could not create target");

        unixfs::symlink(&target_path, &link_path)
            .expect("Could not create symbolic link.");

        let actual =
            Absolute::new(&link_path).expect("Could not handle symlink path");

        assert_eq!(actual.0, link_path);
    }

    #[test]
    fn cannot_go_up_from_root_directory() {
        let _ = env_logger::try_init();

        let actual = Absolute::new("/../foo")
            .expect("Could not handle going up from the root directory");
        let expected = path::Path::new("/foo");

        assert_eq!(actual.0, expected);
    }

    #[test]
    fn resolve_absolute_symlinks() {
        let _ = env_logger::try_init();

        let temp =
            tempfile::tempdir().expect("Could not make temporary directory.");

        unixfs::symlink("/does/not/exist", temp.path().join("link"))
            .expect("Could not create symlink");

        let actual = Absolute::new(temp.path().join("link/../bar"))
            .expect("Could not handle symlink with absolute target");

        let expected = path::Path::new("/does/not/bar");

        assert_eq!(actual.0, expected);
    }

    #[test]
    fn absolute_rejects_dereferencing_cyclic_symlinks() {
        let _ = env_logger::try_init();

        let temp =
            tempfile::tempdir().expect("Could not make temporary directory.");

        unixfs::symlink("a", temp.path().join("b"))
            .expect("Could not create symlink b->a");
        unixfs::symlink("b", temp.path().join("a"))
            .expect("Could not create symlink a->b");

        let err = Absolute::new(temp.path().join("a/../tail"))
            .expect_err("Cyclic symlinks dereferenced?");

        match err {
            // This is what we expected.
            Error::SymlinkLoops(_) => (),
            // Uh oh.
            e => panic!("Got unexpected error: {:?}", e),
        }
    }

    #[test]
    fn absolute_accepts_navigating_cyclic_symlinks() {
        let _ = env_logger::try_init();

        let temp =
            tempfile::tempdir().expect("Could not make temporary directory.");

        unixfs::symlink("a", temp.path().join("b"))
            .expect("Could not create symlink b->a");
        unixfs::symlink("b", temp.path().join("a"))
            .expect("Could not create symlink a->b");

        let expected = temp.path().join("a/tail");

        let actual =
            Absolute::new(&expected).expect("Could not handle cyclic path.");

        assert_eq!(actual.0, expected);
    }

    #[test]
    fn absolute_reports_permission_error() {
        let _ = env_logger::try_init();

        let temp =
            tempfile::tempdir().expect("Could not make temporary directory.");

        fs::create_dir_all(temp.path().join("dir/secret"))
            .expect("Could not create directory");

        // Make "dir" unreadable.
        use self::unixfs::PermissionsExt;
        fs::set_permissions(
            temp.path().join("dir"),
            fs::Permissions::from_mode(0),
        )
        .expect("Could not set permissions");

        // Now, trying to stat 'secret' should give permission denied.
        let err = Absolute::new(temp.path().join("dir/secret/.."))
            .map(|p| {
                panic!("Getting absolute path should have failed: {:?}", p);
            })
            .err()
            .unwrap();

        match err {
            Error::IoError { err, at } => {
                assert_eq!(err.kind(), io::ErrorKind::PermissionDenied);
                assert_eq!(at, temp.path().join("dir/secret"));
            }
            e => panic!("Got unexpected error: {:?}", e),
        }
    }

    #[test]
    fn relative_accepts_monotonic_path() {
        let actual = Relative::new("does/not/exist")
            .expect("Could not parse monotonic path");

        let expected = path::Path::new("does/not/exist");

        assert_eq!(actual.0, expected);
    }

    #[test]
    fn relative_normalises_single_dots() {
        let actual = Relative::new("does/./not/./exist")
            .expect("Could not parse path with CurrentDir components");

        let expected = path::Path::new("does/not/exist");

        assert_eq!(actual.0, expected);
    }

    #[test]
    fn relative_normalises_inner_double_dots() {
        let actual = Relative::new("does/../not/exist")
            .expect("Could not parse path with ParentDir component");

        let expected = path::Path::new("not/exist");

        assert_eq!(actual.0, expected);
    }

    #[test]
    fn relative_rejects_leading_double_dots() {
        let err = Relative::new("../does/not/exist")
            .err()
            .expect("Parsing leading '..' should have failed!");

        match err {
            Error::RelativePathEscapesPrefix(p) => {
                assert_eq!(p, path::Path::new("../does/not/exist"))
            }
            e => panic!("Got unexpected error {:?}", e),
        }
    }

    #[test]
    fn relative_rejects_relative_path_escaping_prefix() {
        let err = Relative::new("inside/../../outside")
            .err()
            .expect("Parsing escaping path should have failed!");

        match err {
            Error::RelativePathEscapesPrefix(p) => {
                assert_eq!(p, path::Path::new("inside/../../outside"))
            }
            e => panic!("Got unexpected error {:?}", e),
        }
    }

    #[test]
    fn relative_rejects_fully_absolute_path() {
        let err = Relative::new("/absolute/path")
            .err()
            .expect("Parsing an absolute path should have failed!");

        match err {
            Error::PathIsAbsolute(p) => {
                assert_eq!(p, path::Path::new("/absolute/path"))
            }
            e => panic!("Got unexpected error {:?}", e),
        }
    }
}