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
//! Cleaned-up cross-platform path handling
//!
//! Most operating systems accept a complex syntax for specifying filesystem
//! paths, including special notation for things like "the current directory"
//! and "the parent directory" that make path-handling code intricate. If
//! filesystem paths always described a straight-line path from the root to
//! the file or directory in question, path-handling code could be much simpler.
//!
//! This module contains types representing exactly those kinds of paths.
//!
//! # Examples
//!
//! ```rust
//! # fn foo() -> Result<(), Box<std::error::Error>> {
//! # use ironpath::*;
//! let install_structure = vec![
//!     Relative::new("bin")?,
//!     Relative::new("lib")?,
//!     Relative::new("share/applications")?,
//!     Relative::new("share/icons")?,
//!     Relative::new("share/man")?,
//! ];
//!
//! let raw_install_path = std::env::args_os().next().ok_or("missing arg")?;
//! let install_path = Absolute::new(raw_install_path)?;
//!
//! for each in install_structure.iter() {
//!     std::fs::create_dir_all(install_path.join_relative(each))?;
//! }
//! # Ok(())
//! # }
//! ```
#[macro_use]
extern crate log;

use std::collections;
use std::error;
use std::ffi;
use std::fmt;
use std::io;
use std::path;

/// An error encountered during path handling.
#[derive(Debug)]
pub enum Error {
    /// An error returned by the operating system.
    ///
    /// `err` is the underlying error returned by the operating system.
    ///
    /// `at` is the path that provoked the error.
    IoError { err: io::Error, at: path::PathBuf },

    /// Returned by [`Absolute::new()`] when given a path that involves a
    /// symlink loop.
    ///
    /// [`Absolute::new()`]: struct.Absolute.html#method.new
    SymlinkLoops(path::PathBuf),

    /// Returned by [`Relative::new()`] when given a (partially or fully) absolute
    /// path.
    ///
    /// [`Relative::new()`]: struct.Relative.html#method.new
    PathIsAbsolute(path::PathBuf),

    /// Returned by [`Relative::new()`] when given a path with enough `/../`
    /// components to escape whatever prefix it's joined to.
    ///
    /// [`Relative::new()`]: struct.Relative.html#method.new
    RelativePathEscapesPrefix(path::PathBuf),

    #[doc(hidden)]
    __NonExhaustive,
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
        match self {
            Error::IoError { err, at } => write!(f, "{}: {:?}", err, at),
            Error::SymlinkLoops(p) => {
                write!(f, "Found an infinite symlink loop: {:?}", p)
            }
            Error::PathIsAbsolute(p) => write!(
                f,
                "Tried to make a relative path from absolute path {:?}",
                p
            ),
            Error::RelativePathEscapesPrefix(p) => write!(
                f,
                "Tried to make a relative path with leading '..': {:?}",
                p
            ),
            _ => write!(f, "Unknown error"),
        }
    }
}

impl error::Error for Error {
    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
        match self {
            Error::IoError { ref err, .. } => Some(err),
            _ => None,
        }
    }
}

/// Splits a path into a head and a tail.
///
/// The "head" is the safe, known-to-exist parts of the path.
/// If the path starts with Prefix or RootDir components,
/// the head is those components.
/// If the path doesn't contain Prefix or RootDir components,
/// the "head" is the current working directory.
/// Either way, it is always in fully canonicalized form.
///
/// The "tail" consists of all the other components that follow the head.
/// These parts may or may not exist, and need to be checked.
///
/// # Errors
///
/// Returns [`Error::IoError`] if the head cannot be canonicalized.
/// For example, if the process' current working directory has been deleted,
/// or the given path includes a syntactically invalid prefix.
///
/// [`Error::IoError`]: struct.Error.html#variant.IoError
fn split_head_and_tail<P: AsRef<path::Path>>(
    path: P,
) -> Result<(path::PathBuf, collections::VecDeque<ffi::OsString>), Error> {
    let path = path.as_ref();

    debug!("Splitting head and tail of {:?}", path);

    // If `path` is in any way relative, it's relative to the current working
    // directory, so let's get a copy of that in canonical form to use as a
    // base.
    let mut head =
        path::Path::new(".")
            .canonicalize()
            .map_err(|err| Error::IoError {
                err: err,
                at: path.into(),
            })?;

    let mut tail = collections::VecDeque::new();

    debug!("Initial head: {:?} tail: {:?}", head, tail);

    for each in path.components() {
        debug!("Component: {:?}", each);
        match each {
            // This is a prefix component, like `C:` or `\\server\share`.
            // This basically replaces all of our existing head, but we
            // may need to canonicalize it first.
            path::Component::Prefix(prefix) => {
                match prefix.kind() {
                    // This is already canonicalized,
                    // nothing to do here.
                    path::Prefix::Verbatim(..)
                    | path::Prefix::VerbatimUNC(..)
                    | path::Prefix::VerbatimDisk(..)
                    | path::Prefix::DeviceNS(..) => head.push(each),

                    // A legacy DOS/Windows syntax,
                    // we need to canonicalize it.
                    _ => {
                        let path_prefix: &path::Path = each.as_ref();
                        let path_prefix =
                            path_prefix.canonicalize().map_err(|err| {
                                Error::IoError {
                                    err,
                                    at: path_prefix.into(),
                                }
                            })?;
                        head.push(path_prefix)
                    }
                }
            }

            // On POSIX, this replaces all of our existing head.
            // On Windows, this replaces all but the prefix.
            path::Component::RootDir => head.push(each),

            // Everything else gets put in the tail,
            // to be checked later.
            _ => tail.push_back(each.as_os_str().to_os_string()),
        }
        debug!("Current head: {:?} tail: {:?}", head, tail);
    }

    debug!("Head: {:?}, tail: {:?}", head, tail);
    Ok((head, tail))
}

/// Returns the target of the symlink at `path`, if it exists and is one.
///
/// If `path` is a symlink and we can read the target, returns
/// `Ok(Some(target))`.
/// If `path` is not a symlink, returns `Ok(None)`.
/// If `path` does not exist, it's still not a symlink and this function
/// returns `Ok(None)`.
/// Otherwise, returns the relevant error.
#[cfg(unix)]
fn read_link_if_exists<P: AsRef<path::Path>>(
    path: P,
) -> Result<Option<path::PathBuf>, Error> {
    let path = path.as_ref();

    // In theory, we could just call .read_link() directly and handle the error
    // result, but:
    //
    // - on Windows, the "can't read this because it isn't a symlink"
    //   error is returned as an io::ErrorKind::Other rather than
    //   io::ErrorKind::InvalidInput.
    // - on Windows, some not-smart filesystems (like VirtualBox's shared
    //   folders) don't understand the API call, and just return "invalid
    //   operation".
    //
    // Therefore, we'll check if the thing is a symlink before trying to read
    // it.
    path.symlink_metadata()
        // If we successfully got metadata, check if it's a symlink.
        .map(|metadata| metadata.file_type().is_symlink())
        // If we failed to get metadata...
        .or_else(|err| {
            if err.kind() == io::ErrorKind::NotFound {
                // ...and we failed because the path doesn't exist, by
                // definition it cannot be a symlink.
                debug!("{:?} does not exist, it's not a symlink", path,);
                Ok(false)
            } else {
                // Any other error we can return as-is.
                error!("Could not check {:?}", path);
                Err(err)
            }
        })
        // If we know for sure whether this is a symlink...
        .and_then(|is_symlink| {
            // ...and it *is* a symlink...
            if is_symlink {
                // ...let's read it to find the target.
                debug!("{:?} exists and is a symlink", path);
                Ok(Some(path.read_link()?))

            // ...and it *isn't* a symlink...
            } else {
                // ...then obviously we don't have a target.
                debug!("{:?} exists and isn't a symlink", path);
                Ok(None)
            }
        })
        .map_err(|err| Error::IoError {
            err: err,
            at: path.into(),
        })
}

/// An absolute path that may or may not exist.
///
/// This path obeys the following invariants:
///
/// - It is absolute, having a prefix (on Windows) and a root directory
///   component.
/// - It contains only named path components, no `/./` or `/../` ones.
/// - It uses the platform-native path-component separator (`/` on POSIX,
///   `\` on Windows).
///
/// Therefore:
///
/// - It's always reasonably straight-forward for humans to understand.
/// - On Windows, it uses [extended-length path syntax], so cross-platform
///   applications don't need to worry about most traditional Windows path
///   limitations.
/// - You can join more named path components on the end without having to
///   check the filesystem or re-normalize the path.
///
/// Since this type implements `AsRef<Path>`, it can be used with almost any
/// standard library function that expects a path.
///
/// [extended-length path syntax]: https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx#maxpath
///
/// # Examples
///
/// ```rust
/// # fn example() -> Result<(), Box<std::error::Error>> {
/// # use ironpath::*;
/// use std::fs;
/// use std::io::Write;
///
/// let log_storage = Absolute::new("/var/log/myapp")?;
///
/// let current_log = log_storage.join("events")?;
/// let previous_log = log_storage.join("events.old")?;
///
/// fs::rename(&current_log, previous_log)?;
///
/// let mut log_file = fs::OpenOptions::new()
///     .write(true)
///     .create(true)
///     .open(current_log)?;
///
/// write!(&mut log_file, "Log rotated.")?;
///
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Absolute(path::PathBuf);

impl Absolute {
    #[cfg(unix)]
    fn from_path<P: AsRef<path::Path>>(path: P) -> Result<Absolute, Error> {
        // This function steps through the components of path, checking each one
        // for monotonicity and building up a proper monotonic path in `res`.
        // `tail` contains the path components we've yet to check and clean up.
        let (mut res, mut tail) = split_head_and_tail(path)?;

        let mut seen_paths = collections::BTreeSet::new();

        // While there's still components left to check...
        while !tail.is_empty() {
            debug!("Monotonic path: {:?}, to check: {:?}", res, tail);

            // Grab the component at the front of the tail, so we can check it.
            let current =
                tail.pop_front().expect("len() > 0 but vec is empty?");

            if &current == "." {
                // A "." component can be ignored.
                //
                //    blah/./blah -> blah/blah

            } else if &current == ".." {
                // If we get a ParentDir component, the component at the end of
                // `res` might be a symlink. in which case we'll have to splice
                // the target path in at the beginning of `tail` so we have the
                // full, monotonic path.
                //
                // If `foo` is not a symlink:
                //
                //    blah/foo/../blah -> blah/blah
                //
                // If `foo` is a symlink to `relative/target`:
                //
                //    blah/symlink/../blah -> blah/relative/target/../blah
                //
                // If `foo` is a symlink to `/absolute/target`:
                //
                //    blah/symlink/../blah -> /absolute/target/../blah
                //

                // But first, let's check for symlink loops. If we've already
                // dereferenced this symlink before, we've hit a loop and we
                // will never find a suitable answer.
                if seen_paths.contains(&res) {
                    return Err(Error::SymlinkLoops(res));
                }

                // This is the first time we've dereferenced this symlink, note
                // it down.
                seen_paths.insert(res.clone());

                match read_link_if_exists(&res)? {
                    // The component before the ParentDir component was not
                    // a symlink, so we don't need to do anything to `tail`.
                    None => (),

                    // The component before the ParentDir component *was* a
                    // symlink, so we need to add it to tail so we'll get around
                    // to checking it.
                    Some(target) => {
                        debug!("Symlink target: {:?}", target);

                        // We'll re-check this ".." component once we've
                        // checked all the components from target. Since we're
                        // pushing to the front, we're pushing components in
                        // reverse order, and so we have to push this first.
                        tail.push_front("..".into());

                        // If the target is an absolute path, then the target's
                        // head replaces our current result. Conveniently,
                        // Windows will only create symlinks with fully-relative
                        // or fully-absolute targets, not root-relative
                        // (`\\foo`) or drive-relative (`C:foo`) paths, so we
                        // don't need to handle those cases.
                        let target = if target.is_absolute() {
                            debug!("Target is absolute");
                            let (new_head, new_target) =
                                split_head_and_tail(target)?;
                            res.push(new_head);

                            new_target

                        // The target is relative, so we can use it as-is.
                        } else {
                            debug!("Target is relative");
                            target
                                .components()
                                .map(|each| each.as_os_str().to_os_string())
                                .collect::<collections::VecDeque<_>>()
                        };

                        // Push all the components of target in reverse order
                        // so we'll check them the next time through the loop.
                        for each in target.into_iter().rev() {
                            tail.push_front(each);
                        }
                    }
                }

                // If the component at the end of `res` is a symlink, its
                // target has been pushed to the front of `tail` and will
                // be processed in due course. If it's not a symlink, this
                // ParentDir component nullifies it. Either way, we don't want
                // the last component of `res` anymore.
                res.pop();
            } else {
                // This component is a normal name. We'll trust it... for now.
                res.push(current);
            }
        }

        Ok(Absolute(res))
    }

    #[cfg(windows)]
    fn from_path<P: AsRef<path::Path>>(path: P) -> Result<Absolute, Error> {
        // Windows always resolves `..` lexically, without regard to the
        // filesystem, so we can get away with just dropping `.` components
        // and eating components followed by `..`.
        let (mut res, mut tail) = split_head_and_tail(path)?;
        // While there's still components left to check...
        while !tail.is_empty() {
            debug!("Monotonic path: {:?}, to check: {:?}", res, tail);
            // Grab the component at the front of the tail, so we can check it.
            let current =
                tail.pop_front().expect("len() > 0 but vec is empty?");

            if &current == "." {
                // A "." component can be ignored.
                //
                //    blah/./blah -> blah/blah

            } else if &current == ".." {
                // If we get a ParentDir component, we can just pop the last
                // component off head.
                //
                //    blah/foo/../blah -> blah/blah
                //
                res.pop();
            } else {
                // For any other component, we can just use it as-is.
                res.push(current);
            }
        }

        Ok(Absolute(res))
    }

    /// Convert an arbitrary path to follow the rules for an `Absolute` path.
    ///
    /// - If the path is relative, it is interpreted relative to the process'
    ///   current working directory.
    /// - Any `/./` components in the path are removed.
    /// - If a component that refers to an existing, readable symlink is
    ///   followed by a `/../` component, it will be resolved in the same way as
    ///   the operating system would (see "Platform-specific behaviour" below).
    /// - If a component that does not exist in the filesystem, or which refers
    ///   to an ordinary file or directory, is followed by a `/../` component,
    ///   they cancel each other out and both are removed.
    /// - Other components are left alone.
    ///
    /// # Performance
    ///
    /// In the best-case, the given path already follows the rules, and
    /// we only call [`canonicalize()`] on the head (the prefix and root
    /// directory, if any) to convert it to canonical syntax.
    ///
    /// If the platform requires it, we will call [`symlink_metadata()`] on
    /// every component preceding a `/../` component, and (if it turns out to be
    /// a symlink) [`read_link()`]. The process repeats if the symlink target
    /// includes any `/../` components of its own.
    ///
    /// [`canonicalize()`]: https://doc.rust-lang.org/stable/std/fs/fn.canonicalize.html
    /// [`symlink_metadata()`]: https://doc.rust-lang.org/stable/std/fs/fn.symlink_metadata.html
    /// [`read_link()`]: https://doc.rust-lang.org/stable/std/fs/fn.read_link.html
    ///
    /// # Platform-specific behaviour
    ///
    /// On Windows, when a path component that refers to a symlink is followed
    /// by `/../`, the symlink component is removed, because that's how the
    /// Windows kernel does it.
    ///
    /// On Unix, when a path component that refers to a symlink is followed
    /// by `/../`, the symlink component is resolved recursively before the `/../` is applied, because that's how the Unix kernel does it.
    ///
    /// On Windows, this method correctly handles partially-absolute paths like
    /// `D:foo\bar.txt` that are relative to a path other than the current
    /// working directory.
    ///
    /// On Windows, the resulting path uses [extended-length path syntax], so
    /// it may confuse other applications not designed to handle such paths.
    /// For example, if you pass such a path on another application's command
    /// line, or write it to a configuration file.
    ///
    /// [extended-length path syntax]: https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx#maxpath
    ///
    /// # Errors
    ///
    /// Returns [`Error::IoError`] if the head of the given path cannot be
    /// canonicalized. For example, if the process' current working directory
    /// has been deleted, or the given path includes a syntactically invalid
    /// prefix.
    ///
    /// The same variant is returned if a problem is encountered while checking
    /// if a given path is a symlink, or while trying to read a symlink. For
    /// example, if the current user does not have permission to read the
    /// directory containing it, or the path is on a network-mounted filesystem
    /// that stopped responding.
    ///
    /// Returns [`Error::SymlinkLoops`] if resolving a symlink takes us back
    /// to a previously-resolved symlink. For example, if `/example/path/a`
    /// is a symlink to `/example/path/b`, and `b` is a symlink back to `a`,
    /// then giving this method a path like `/example/path/a/../c` will return
    /// this error. It's like the POSIX `ELOOP` error, but cross-platform.
    ///
    /// Note that "does not exist" is *not* a fatal error for this function;
    /// path components that do not exist by definition are not symlinks, and
    /// are treated the same way as every other component that is not a symlink.
    ///
    /// [`Error::IoError`]: struct.Error.html#variant.IoError
    /// [`Error::SymlinkLoops`]: struct.Error.html#variant.SymlinkLoops
    ///
    /// # Examples
    ///
    /// ```rust
    /// # fn example() -> Result<(), Box<std::error::Error>> {
    /// # use ironpath::*;
    /// let real_current_directory = Absolute::new(std::env::current_dir()?)?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn new<P: AsRef<path::Path>>(path: P) -> Result<Absolute, Error> {
        Absolute::from_path(path)
    }

    /// Clone this path, attempting to add an arbitrary relative path on the
    /// end.
    ///
    /// # Performance
    ///
    /// An expression like:
    ///
    /// ```rust
    /// # fn example() -> Result<(), Box<std::error::Error>> {
    /// # let absolute_path = ironpath::Absolute::new(".").unwrap();
    /// # let path = std::path::Path::new("foo");
    /// absolute_path.join(path)?
    /// # ;Ok(())
    /// # }
    /// ```
    ///
    /// ...is the same as doing:
    ///
    /// ```rust
    /// # fn example() -> Result<(), Box<std::error::Error>> {
    /// # use ironpath::*;
    /// # let absolute_path = Absolute::new(".").unwrap();
    /// # let path = std::path::Path::new("foo");
    /// absolute_path.join_relative(&Relative::new(path)?)
    /// # ;Ok(())
    /// # }
    /// ```
    ///
    /// ...and therefore involves the same allocation and other costs as
    /// calling [`Relative::new()`] yourself.
    ///
    /// If you plan on joining the same relative path to many `Absolute` paths,
    /// it's more efficient to call `Relative::new()` once yourself then use
    /// [`.join_relative()`] each time.
    ///
    /// [`Relative::new()`]: struct.Relative.html#method.new
    /// [`.join_relative()`]: #method.join_relative
    ///
    /// # Errors
    ///
    /// Returns the same errors as [`Relative::new()`].
    ///
    /// # Examples
    ///
    /// ```rust
    /// # fn example() -> Result<(), Box<std::error::Error>> {
    /// # let extraction_path = ironpath::Absolute::new(".")?;
    /// let metadata_path = extraction_path.join("META-INF/MANIFEST.MF")?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn join<P: AsRef<path::Path>>(
        &self,
        path: P,
    ) -> Result<Absolute, Error> {
        Ok(self.join_relative(&Relative::new(path)?))
    }

    /// Clone this path, adding the given [`Relative`] path on the end.
    ///
    /// If the thing you want to join isn't already a `Relative`, you may find
    /// it more ergonomic to call [`.join()`] instead.
    ///
    /// [`.join()`]: #method.join
    ///
    /// # Performance
    ///
    /// Since a `Relative` is guaranteed to follow the rules for `Absolute`
    /// paths (except for being absolute), no additional checks or processing
    /// need to be done, just straight concatenation.
    ///
    /// [`Relative`]: struct.Relative.html
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use ironpath::*;
    /// # fn example() -> Result<Absolute, Error> {
    /// let search_path = vec![
    ///     Absolute::new("/usr/local/bin")?,
    ///     Absolute::new("/bin")?,
    ///     Absolute::new("/usr/bin")?,
    ///     Absolute::new("/sbin")?,
    ///     Absolute::new("/usr/sbin")?,
    /// ];
    ///
    /// let binary = Relative::new("cargo")?;
    ///
    /// for prefix in search_path {
    ///     let guess = prefix.join_relative(&binary);
    ///
    ///     if guess.as_path().is_file() {
    ///         return Ok(guess)
    ///     }
    /// }
    ///
    /// # Ok(Absolute::new(".").unwrap())
    /// # }
    /// ```
    pub fn join_relative(&self, tail: &Relative) -> Absolute {
        Absolute(self.0.join(tail))
    }

    /// Coerces to a [`Path`] slice.
    ///
    /// Since `Absolute` implements `AsRef<Path>`, this method is not needed
    /// very often—you can often just pass it directly to the thing that needs
    /// a [`Path`].
    ///
    /// [`Path`]: https://doc.rust-lang.org/stable/std/path/struct.Path.html
    ///
    /// # Examples
    ///
    /// If you really, really need to convert an `Absolute` to a [`PathBuf`]:
    ///
    /// ```rust
    /// # use ironpath::*;
    /// # let absolute_path = Absolute::new(".").unwrap();
    /// let owned_path: std::path::PathBuf = absolute_path.as_path().into();
    /// ```
    ///
    /// [`PathBuf`]: https://doc.rust-lang.org/stable/std/path/struct.PathBuf.html
    pub fn as_path(&self) -> &path::Path {
        <Self as AsRef<path::Path>>::as_ref(self)
    }

    /// Coerces to an [`OsStr`] slice.
    ///
    /// Since `Absolute` implements `AsRef<OsStr>`, this method is not needed
    /// very often—you can often just pass it directly to the thing that needs
    /// an [`OsStr`].
    ///
    /// [`OsStr`]: https://doc.rust-lang.org/stable/std/ffi/struct.OsStr.html
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use ironpath::*;
    /// let install_path = std::env::args_os()
    ///     .next()
    ///     .expect("Specify the installation path on the command line.");
    ///
    /// let windows_path = Absolute::new("C:\\windows").unwrap();
    ///
    /// if windows_path.as_os_str() == install_path {
    ///     panic!("No, you can't install to the Windows path.");
    /// }
    /// ```
    pub fn as_os_str(&self) -> &ffi::OsStr {
        <Self as AsRef<ffi::OsStr>>::as_ref(self)
    }
}

impl AsRef<path::Path> for Absolute {
    fn as_ref(&self) -> &path::Path {
        self.0.as_path()
    }
}

impl AsRef<ffi::OsStr> for Absolute {
    fn as_ref(&self) -> &ffi::OsStr {
        self.0.as_os_str()
    }
}

/// A relative path that may be joined to an absolute path.
///
/// This path obeys the following invariants:
///
/// - It is relative, containing no prefix or root directory components.
/// - It contains only named path components, no `/./` or `/../` ones.
/// - It uses the platform-native path-component separator (`/` on POSIX,
///   `\` on Windows).
///
/// Therefore:
///
/// - It's always reasonably straight-forward for humans to understand.
/// - It can safely be appended to an [`Absolute`] path or another
///   `Relative` path without having to revalidatet the invariants.
/// - Joining a `Relative` to an `Absolute` will always produce a path that
///   refers to a child of the `Absolute`, unless the directory named by the
///   `Absolute` contains a symilnk to a directory outside it.
///
/// Since this type implements `AsRef<Path>`, it can be used with almost any
/// standard library function that expects a path, but you probably only want
/// to join it to an `Absolute` path.
///
/// [`Absolute`]: struct.Absolute.html
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Relative(path::PathBuf);

impl Relative {
    /// Convert an arbitrary path to follow the rules for a `Relative` path.
    ///
    /// - Any `/./` components in the path are removed.
    /// - If a named component is followed by a `/../` component, they cancel
    ///   each other out and both are removed. We cannot resolve symlinks here
    ///   since we do not know what absolute path this path is relative to.
    ///
    /// # Performance
    ///
    /// This validation is performed entirely in memory, with no reference to
    /// the filesystem.
    ///
    /// # Errors
    ///
    /// Returns [`Error::PathIsAbsolute`] if the given path contains prefix or
    /// root directory components, like `/usr/share` or `C:file.txt`.
    ///
    /// Returns [`Error::RelativePathEscapesPrefix`] if any `/../` components
    /// cannot be normalized away, like `a/b/../../../c`.
    ///
    /// [`Error::PathIsAbsolute`]: enum.Error.html#variant.PathIsAbsolute
    /// [`Error::RelativePathEscapesPrefix`]: enum.Error.html#variant.RelativePathEscapesPrefix
    ///
    pub fn new<P: AsRef<path::Path>>(path: P) -> Result<Relative, Error> {
        let components = path.as_ref().components();
        let mut res = path::PathBuf::new();

        for each in components {
            match each {
                path::Component::Prefix(_) | path::Component::RootDir => {
                    return Err(Error::PathIsAbsolute(path.as_ref().into()));
                }
                path::Component::Normal(name) => res.push(name),
                path::Component::ParentDir => {
                    if res.as_os_str() == "" {
                        return Err(Error::RelativePathEscapesPrefix(
                            path.as_ref().into(),
                        ));
                    }

                    res.pop();
                }
                path::Component::CurDir => (),
            }
        }

        Ok(Relative(res))
    }

    /// Clone this path, attempting to add an arbitrary relative path on the
    /// end.
    ///
    /// # Performance
    ///
    /// An expression like:
    ///
    /// ```rust
    /// # fn example() -> Result<(), Box<std::error::Error>> {
    /// # let other_relative_path = ironpath::Relative::new(".").unwrap();
    /// # let path = std::path::Path::new("foo");
    /// other_relative_path.join(path)?
    /// # ;Ok(())
    /// # }
    /// ```
    ///
    /// ...is the same as doing:
    ///
    /// ```rust
    /// # fn example() -> Result<(), Box<std::error::Error>> {
    /// # use ironpath::*;
    /// # let other_relative_path = Relative::new(".").unwrap();
    /// # let path = std::path::Path::new("foo");
    /// other_relative_path.join_relative(&Relative::new(path)?)
    /// # ;Ok(())
    /// # }
    /// ```
    ///
    /// ...and therefore involves the same allocation and other costs as
    /// calling [`Relative::new()`] yourself.
    ///
    /// If you plan on joining the same relative path to many other `Relative`
    /// paths, it's more efficient to call `Relative::new()` once yourself and
    /// call [`.join_relative()`] each time.
    ///
    /// [`Relative::new()`]: struct.Relative.html#method.new
    /// [`.join_relative()`]: #method.join_relative
    ///
    /// # Errors
    ///
    /// Returns the same errors as [`Relative::new()`].
    ///
    /// # Examples
    ///
    /// ```rust
    /// # fn example() -> Result<(), Box<std::error::Error>> {
    /// # use ironpath::*;
    /// let config_base = Relative::new("SuperSoftwareCo/MyCoolApp")?;
    ///
    /// let video_config = config_base.join("video.cfg")?;
    /// let audio_config = config_base.join("audio.cfg")?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn join<P: AsRef<path::Path>>(
        &self,
        path: P,
    ) -> Result<Relative, Error> {
        Ok(self.join_relative(&Relative::new(path)?))
    }

    /// Clone this path, adding the given `Relative` path on the end.
    ///
    /// [`.join()`]: #method.join
    ///
    /// # Performance
    ///
    /// Since `Relative` paths all have the same invariants, no additional
    /// checks or processing need to be done, just straight concatenation.
    ///
    pub fn join_relative(&self, tail: &Relative) -> Relative {
        Relative(self.0.join(tail))
    }

    /// Coerces to a [`Path`] slice.
    ///
    /// Since `Relative` implements `AsRef<Path>`, this method is not needed
    /// very often—you can often just pass it directly to the thing that needs
    /// a [`Path`].
    ///
    /// [`Path`]: https://doc.rust-lang.org/stable/std/path/struct.Path.html
    ///
    /// # Examples
    ///
    /// If you really, really need to convert a `Relative` to a [`PathBuf`]:
    ///
    /// ```rust
    /// # let relative = ironpath::Relative::new("foo").unwrap();
    /// let owned_path: std::path::PathBuf = relative.as_path().into();
    /// ```
    ///
    /// [`PathBuf`]: https://doc.rust-lang.org/stable/std/path/struct.PathBuf.html
    pub fn as_path(&self) -> &path::Path {
        <Self as AsRef<path::Path>>::as_ref(self)
    }

    /// Coerces to an [`OsStr`] slice.
    ///
    /// Since `Relative` implements `AsRef<OsStr>`, this method is not needed
    /// very often—you can often just pass it directly to the thing that needs
    /// an [`OsStr`].
    ///
    /// [`OsStr`]: https://doc.rust-lang.org/stable/std/ffi/struct.OsStr.html
    ///
    /// # Examples
    ///
    /// If you really, really need to convert a `Relative` to a [`OsString`]:
    ///
    /// ```rust
    /// # let relative = ironpath::Relative::new("foo").unwrap();
    /// let owned_string: std::ffi::OsString = relative.as_os_str().into();
    /// ```
    ///
    /// [`OsString`]: https://doc.rust-lang.org/stable/std/ffi/struct.OsString.html
    pub fn as_os_str(&self) -> &ffi::OsStr {
        <Self as AsRef<ffi::OsStr>>::as_ref(self)
    }
}

impl AsRef<path::Path> for Relative {
    fn as_ref(&self) -> &path::Path {
        self.0.as_path()
    }
}

impl AsRef<ffi::OsStr> for Relative {
    fn as_ref(&self) -> &ffi::OsStr {
        self.0.as_os_str()
    }
}

#[cfg(test)]
mod tests;