path_abs/
lib.rs

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
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
/* Copyright (c) 2018 Garrett Berg, vitiral@gmail.com
 *
 * Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
 * http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
 * http://opensource.org/licenses/MIT>, at your option. This file may not be
 * copied, modified, or distributed except according to those terms.
 */
//! Ergonomic paths and files in rust.
//!
//! This library aims to provide ergonomic path and file operations to rust with reasonable
//! performance.
//!
//! This includes:
//!
//! - Improved methods for the `std` path types using [`PathInfo`] [`PathMut`] and [`PathOps`]
//! - Cleaner _absolute_ paths (which is distinct from canonicalized paths).
//! - Improved error messages, see the [Better Errors](#better-errors) section.
//! - Improved type safety. The types specify that a file/dir _once_ existed and was _once_ a
//!   certain type. Obviously a file/dir can be deleted/changed by another process.
//! - More stringent mutability requirements. See the
//!   [Differing Method Signatures](#differing-method-signatures) section.
//! - Cheap cloning: all path types are `Arc`, which a cheap operation compared to filesystem
//!   operations and allows more flexibility and ergonomics in the library for relatively low cost.
//!
//! ## Better Errors
//!
//! All errors include the **path** and **action** which caused the error, as well as the unaltered
//! `std::io::Error` message. Errors are convertable into `std::io::Error`, giving almost complete
//! compatibility with existing code.
//!
//! ### `set_len` (i.e. truncate a file):
//!
//! - [`/* */ std::fs::File::set_len(0)`][file_set_len]: `Invalid argument (os error 22)`
//! - [`path_abs::FileWrite::set_len(0)`][path_set_len]: `Invalid argument (os error 22) when setting
//!   len for /path/to/example/foo.txt`
//!
//! > The above error is actually impossible because `FileWrite` is always writeable, and
//! > `FileRead` does not implement `set_len`. However, it is kept for demonstration.
//!
//! ### `open_read` (open file for reading):
//!
//! - [`/**/ std::fs::File::read(path)`][file_read]: `No such file or directory (os error 2)`
//! - [`path_abs::FileRead::open(path)`][path_read]: `No such file or directory (os error 2) when
//!   opening example/foo.txt`
//!
//! And every other method has similarily improved errors. If a method does not have pretty error
//! messages please open a ticket.
//!
//! [file_set_len]: https://doc.rust-lang.org/std/fs/struct.File.html#method.set_len
//! [file_read]: https://doc.rust-lang.org/std/fs/struct.File.html#method.read
//! [path_set_len]: struct.FileWrite.html#method.set_len
//! [path_read]: struct.FileRead.html#method.open
//!
//!
//! ## Exported Path Types
//!
//! These are the exported Path types. All of them are absolute.
//!
//! - [`PathAbs`](struct.PathAbs.html): a reference counted absolute (_not necessarily_
//!   canonicalized) path that is not necessarily guaranteed to exist.
//! - [`PathFile`](struct.PathFile.html): a `PathAbs` that is guaranteed (at instantiation) to
//!   exist and be a file, with associated methods.
//! - [`PathDir`](struct.PathDir.html): a `PathAbs` that is guaranteed (at instantiation) to exist
//!   and be a directory, with associated methods.
//! - [`PathType`](struct.PathType.html): an enum containing either a PathFile or a PathDir.
//!   Returned by [`PathDir::list`][dir_list]
//!
//! In addition, all paths are serializable through serde (even on windows!) by using the crate
//! [`stfu8`](https://crates.io/crates/stfu8) to encode/decode, allowing ill-formed UTF-16. See
//! that crate for more details on how the resulting encoding can be edited (by hand) even in the
//! case of what *would be* ill-formed UTF-16.
//!
//! [dir_list]: struct.PathDir.html#method.list
//!
//!
//! ## Exported File Types
//!
//! All File types provide _type safe_ access to their relevant traits. For instance, you can't
//! `read` with a `FileWrite` and you can't `write` with a `FileRead`.
//!
//! - [`FileRead`](struct.FileRead.html): a read-only file handle with `path()` attached and
//!   improved error messages. Contains only the methods and trait implementations which are
//!   allowed by a read-only file.
//! - [`FileWrite`](struct.FileWrite.html): a write-only file handle with `path()` attached and
//!   improved error messages. Contains only the methods and trait implementations which are
//!   allowed by a write-only file.
//! - [`FileEdit`](struct.FileEdit.html): a read/write file handle with `path()` attached and
//!   improved error messages. Contains methods and trait implements for both readable _and_
//!   writeable files.
//!
//! ### Differing Method Signatures
//!
//! The type signatures of the `File*` types regarding `read`, `write` and other methods is
//! slightly different than `std::fs::File` -- they all take `&mut` instead of `&`. This is to
//! avoid a [common possible footgun](https://github.com/rust-lang/rust/issues/47708).
//!
//! To demonstrate, imagine the following scenario:
//!
//! - You pass your open `&File` to a method, which puts it in a thread. This thread constantly
//!   calls `seek(SeekFrom::Start(10))`
//! - You periodically read from a file expecting new data, but are always getting the same data.
//!
//! Yes, this is actually allowed by the rust compiler since `seek` is implemented for
//! [`&File`](https://doc.rust-lang.org/std/fs/struct.File.html#impl-Seek-1). Technically this is
//! still _memory safe_ since the operating system will handle any contention, however many would
//! argue that it isn't _expected_ that an immutable reference passed to another
//! function can affect the seek position of a file.
//!
//!
//! # Examples
//! Recreating `Cargo.init` in `example/`
//!
//! ```rust
//! # extern crate path_abs;
//! # extern crate tempdir;
//! use std::path::Path;
//! use std::collections::HashSet;
//! use path_abs::{
//!     PathAbs,   // absolute path
//!     PathDir,   // absolute path to a directory
//!     PathFile,  // absolute path to a file
//!     PathType,  // enum of Dir or File
//!     PathInfo,  // trait for query methods
//!     PathOps,   // trait for methods that make new paths
//!     FileRead,  // Open read-only file handler
//!     FileWrite, // Open write-only file handler
//!     FileEdit,  // Open read/write file handler
//! };
//!
//! # fn try_main() -> ::std::io::Result<()> {
//! let example = Path::new("example");
//! # let tmp = tempdir::TempDir::new("ex")?;
//! # let example = &tmp.path().join(example);
//!
//! // Create your paths
//! let project = PathDir::create_all(example)?;
//! let src = PathDir::create(project.concat("src")?)?;
//! let lib = PathFile::create(src.concat("lib.rs")?)?;
//! let cargo = PathFile::create(project.concat("Cargo.toml")?)?;
//!
//! // Write the templates
//! lib.write_str(r#"
//! #[cfg(test)]
//! mod tests {
//!     #[test]
//!     fn it_works() {
//!         assert_eq!(2 + 2, 4);
//!     }
//! }"#)?;
//!
//! cargo.write_str(r#"
//! [package]
//! name = "example"
//! version = "0.1.0"
//! authors = ["Garrett Berg <vitiral@gmail.com>"]
//!
//! [dependencies]
//! "#)?;
//!
//! // Put our result into a HashMap so we can assert it
//! let mut result = HashSet::new();
//! for p in project.list()? {
//!     result.insert(p?);
//! }
//!
//! // Create our expected value
//! let mut expected = HashSet::new();
//! expected.insert(PathType::Dir(src));
//! expected.insert(PathType::File(cargo));
//!
//! assert_eq!(expected, result);
//!
//! // ----------------------------------
//! // Creating types from existing paths
//!
//! // Creating a generic path
//! let lib_path = example.join("src").join("lib.rs");
//! let abs = PathAbs::new(&lib_path)?;
//!
//! // Or a path with a known type
//! let file = PathType::new(&lib_path)
//!     ?
//!     .unwrap_file();
//!
//! assert!(abs.is_file());
//! assert!(file.is_file());
//!
//! // ----------------------------------
//! // Opening a File
//!
//! // open read-only using the PathFile method
//! let read = file.open_read()?;
//!
//! // Or use the type directly: open for appending
//! let write = FileWrite::open_append(&file)?;
//!
//! // Open for read/write editing.
//! let edit = file.open_edit()?;
//! # Ok(()) } fn main() { try_main().unwrap() }
//! ```
//!
//! [`PathInfo`]: trait.PathInfo.html
//! [`PathOps`]: trait.PathOps.html
//! [`PathMut`]: trait.PathMut.html

#![cfg_attr(target_os = "wasi",
            feature(wasi_ext))]

#[cfg(feature = "serialize")]
extern crate serde;
#[macro_use]
#[cfg(feature = "serialize")]
extern crate serde_derive;

#[cfg(feature = "serialize")]
extern crate stfu8;

#[macro_use]
#[cfg(test)]
extern crate pretty_assertions;
#[cfg(test)]
extern crate regex;
#[cfg(test)]
extern crate serde_json;
#[cfg(test)]
extern crate tempdir;

use std::error;
use std::ffi;
use std::fmt;
use std::fs;
use std::io;
use std::path::{self, Component, Components};
use std_prelude::*;

mod abs;
mod dir;
mod edit;
mod file;
pub mod open;
mod read;
#[cfg(feature = "serialize")]
pub mod ser;
mod ty;
mod write;

pub use crate::abs::PathAbs;
pub use crate::dir::{ListDir, PathDir};
pub use crate::file::PathFile;
#[cfg(feature = "serialize")]
pub use crate::ser::PathSer;
pub use crate::ty::PathType;

pub use crate::edit::FileEdit;
pub use crate::read::FileRead;
pub use crate::write::FileWrite;

pub type Result<T> = ::std::result::Result<T, Error>;

/// An error produced by performing an filesystem operation on a `Path`.
///
/// This error type is a light wrapper around [`std::io::Error`]. In particular, it adds the
/// following information:
///
/// - The action being performed when the error occured
/// - The path associated with the IO error.
///
/// To maintain good ergonomics, this type has a `impl From<Error> for std::io::Error` defined so
/// that you may use an [`io::Result`] with methods in this crate if you don't care about accessing
/// the underlying error data in a structured form (the pretty format will be preserved however).
///
/// [`std::io::Error`]: https://doc.rust-lang.org/stable/std/io/struct.Error.html
/// [`io::Result`]: https://doc.rust-lang.org/stable/std/io/type.Result.html
///
/// # Examples
/// ```rust
/// use path_abs::Error as PathError;
/// use path_abs::PathFile;
///
/// /// main function, note that you can use `io::Error`
/// fn try_main() -> Result<(), ::std::io::Error> {
///     let lib = PathFile::new("src/lib.rs")?;
///     Ok(())
/// }
///
/// ```
pub struct Error {
    io_err: io::Error,
    action: String,
    path: Arc<PathBuf>,
}

impl Error {
    /// Create a new error when the path and action are known.
    pub fn new(io_err: io::Error, action: &str, path: Arc<PathBuf>) -> Error {
        Error {
            io_err,
            action: action.into(),
            path,
        }
    }
}

impl fmt::Debug for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Error<{}>", self)
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{} when {} {}",
            self.io_err,
            self.action,
            self.path.display()
        )
    }
}

impl Error {
    /// Returns the path associated with this error.
    pub fn path(&self) -> &Path {
        self.path.as_ref()
    }

    /// Returns the `std::io::Error` associated with this errors.
    pub fn io_error(&self) -> &io::Error {
        &self.io_err
    }

    /// Returns the action being performed when this error occured.
    pub fn action(&self) -> &str {
        &self.action
    }
}

impl error::Error for Error {
    fn description(&self) -> &str {
        self.io_err.description()
    }

    fn cause(&self) -> Option<&dyn error::Error> {
        Some(&self.io_err)
    }
}

impl From<Error> for io::Error {
    fn from(err: Error) -> io::Error {
        io::Error::new(err.io_err.kind(), err)
    }
}

/// Methods that return information about a path.
///
/// This trait provides the familiar methods from `std::path::Path`
/// for the `Path*` types. These methods take the same parameters and return
/// the same types as the originals in the standard library, except where
/// noted.
///
/// As a general rule, methods that can return an error will return a rich
/// [`path_abs::Error`] instead of a [`std::io::Error`] (although it will
/// automatically convert into a `std::io::Error` with `?` if needed).
///
/// [`path_abs::Error`]: struct.Error.html
/// [`std::io::Error`]: https://doc.rust-lang.org/stable/std/io/struct.Error.html
pub trait PathInfo {
    fn as_path(&self) -> &Path;

    fn to_arc_pathbuf(&self) -> Arc<PathBuf>;

    fn as_os_str(&self) -> &ffi::OsStr {
        Path::as_os_str(self.as_path())
    }

    fn to_str(&self) -> Option<&str> {
        Path::to_str(self.as_path())
    }

    fn to_string_lossy(&self) -> Cow<'_, str> {
        Path::to_string_lossy(self.as_path())
    }

    fn is_absolute(&self) -> bool {
        Path::is_absolute(self.as_path())
    }

    fn is_relative(&self) -> bool {
        Path::is_relative(self.as_path())
    }

    fn has_root(&self) -> bool {
        Path::has_root(self.as_path())
    }

    fn ancestors(&self) -> path::Ancestors<'_> {
        Path::ancestors(self.as_path())
    }

    fn file_name(&self) -> Option<&ffi::OsStr> {
        Path::file_name(self.as_path())
    }

    fn strip_prefix<P>(&self, base: P) -> std::result::Result<&Path, path::StripPrefixError>
    where
        P: AsRef<Path>,
    {
        Path::strip_prefix(self.as_path(), base)
    }

    fn starts_with<P: AsRef<Path>>(&self, base: P) -> bool {
        Path::starts_with(self.as_path(), base)
    }

    fn ends_with<P: AsRef<Path>>(&self, base: P) -> bool {
        Path::ends_with(self.as_path(), base)
    }

    fn file_stem(&self) -> Option<&ffi::OsStr> {
        Path::file_stem(self.as_path())
    }

    fn extension(&self) -> Option<&ffi::OsStr> {
        Path::extension(self.as_path())
    }

    fn components(&self) -> Components<'_> {
        Path::components(self.as_path())
    }

    fn iter(&self) -> path::Iter<'_> {
        Path::iter(self.as_path())
    }

    fn display(&self) -> path::Display<'_> {
        Path::display(self.as_path())
    }

    /// Queries the file system to get information about a file, directory, etc.
    ///
    /// The same as [`std::path::Path::metadata()`], except that it returns a
    /// rich [`path_abs::Error`] when a problem is encountered.
    ///
    /// [`path_abs::Error`]: struct.Error.html
    /// [`std::path::Path::metadata()`]: https://doc.rust-lang.org/stable/std/path/struct.Path.html#method.metadata
    fn metadata(&self) -> Result<fs::Metadata> {
        Path::metadata(self.as_path())
            .map_err(|err| Error::new(err, "getting metadata of", self.to_arc_pathbuf()))
    }

    /// Queries the metadata about a file without following symlinks.
    ///
    /// The same as [`std::path::Path::symlink_metadata()`], except that it
    /// returns a rich [`path_abs::Error`] when a problem is encountered.
    ///
    /// [`path_abs::Error`]: struct.Error.html
    /// [`std::path::Path::symlink_metadata()`]: https://doc.rust-lang.org/stable/std/path/struct.Path.html#method.symlink_metadata
    fn symlink_metadata(&self) -> Result<fs::Metadata> {
        Path::symlink_metadata(self.as_path())
            .map_err(|err| Error::new(err, "getting symlink metadata of", self.to_arc_pathbuf()))
    }

    fn exists(&self) -> bool {
        Path::exists(self.as_path())
    }

    fn is_file(&self) -> bool {
        Path::is_file(self.as_path())
    }

    fn is_dir(&self) -> bool {
        Path::is_dir(self.as_path())
    }

    /// Reads a symbolic link, returning the path that the link points to.
    ///
    /// The same as [`std::path::Path::read_link()`], except that it returns a
    /// rich [`path_abs::Error`] when a problem is encountered.
    ///
    /// [`path_abs::Error`]: struct.Error.html
    /// [`std::path::Pathdoc.rust-lang.org/stable/std/path/struct.Path.html#method.read_link
    fn read_link(&self) -> Result<PathBuf> {
        Path::read_link(self.as_path())
            .map_err(|err| Error::new(err, "reading link target of", self.to_arc_pathbuf()))
    }

    /// Returns the canonical, absolute form of the path with all intermediate
    /// components normalized and symbolic links resolved.
    ///
    /// The same as [`std::path::Path::canonicalize()`],
    ///   - On success, returns a `path_abs::PathAbs` instead of a `PathBuf`
    ///   - returns a rich [`path_abs::Error`] when a problem is encountered
    ///
    /// [`path_abs::Error`]: struct.Error.html
    /// [`std::path::Path::canonicalize()`]: https://doc.rust-lang.org/stable/std/path/struct.Path.html#method.canonicalize
    fn canonicalize(&self) -> Result<PathAbs> {
        Path::canonicalize(self.as_path())
            .map(|path| PathAbs(path.into()))
            .map_err(|err| Error::new(err, "canonicalizing", self.to_arc_pathbuf()))
    }

    /// Returns the path without its final component, if there is one.
    ///
    /// The same as [`std::path::Path::parent()`], except that it returns a
    /// `Result` with a rich [`path_abs::Error`] when a problem is encountered.
    ///
    /// [`path_abs::Error`]: struct.Error.html
    /// [`std::path::Path::parent()`]: https://doc.rust-lang.org/stable/std/path/struct.Path.html#method.parent
    fn parent(&self) -> Result<&Path> {
        let parent_path = Path::parent(self.as_path());
        if let Some(p) = parent_path {
            Ok(p)
        } else {
            Err(Error::new(
                io::Error::new(io::ErrorKind::NotFound, "path has no parent"),
                "truncating to parent",
                self.to_arc_pathbuf(),
            ))
        }
    }
}

// TODO: I would like to be able to do this.
// impl<T> PathInfo for T
// where
//     T: AsRef<Path>
// {
//     fn as_path(&self) -> &Path {
//         PathBuf::as_path(self.borrow())
//     }
//     fn to_arc_pathbuf(&self) -> Arc<PathBuf> {
//         self.clone().into()
//     }
// }

impl<T> PathInfo for T
where
    T: Clone + Borrow<PathBuf> + Into<Arc<PathBuf>>,
{
    fn as_path(&self) -> &Path {
        PathBuf::as_path(self.borrow())
    }
    fn to_arc_pathbuf(&self) -> Arc<PathBuf> {
        self.clone().into()
    }
}

impl PathInfo for Path {
    fn as_path(&self) -> &Path {
        &self
    }
    fn to_arc_pathbuf(&self) -> Arc<PathBuf> {
        self.to_path_buf().into()
    }
}

/// Methods that modify a path.
///
/// These methods are not implemented for all `path_abs` types because they
/// may break the type's invariant. For example, if you could call
/// `pop_up()` on a `PathFile`, it would no longer be the path to
/// a file, but the path to a directory.
///
/// As a general rule, methods that can return an error will return a rich
/// [`path_abs::Error`] instead of a [`std::io::Error`] (although it will
/// automatically convert into a `std::io::Error` with `?` if needed).
pub trait PathMut: PathInfo {
    /// Appends `path` to this path.
    ///
    /// Note that this method represents pure concatenation, not "adjoinment"
    /// like [`PathBuf::push`], so absolute paths won't wholly replace the
    /// current path.
    ///
    /// `..` components are resolved using [`pop_up`], which can consume components
    /// on `self`
    ///
    /// # Errors
    ///
    /// This method returns an error if the result would try to go outside a filesystem root,
    /// like `/` on Unix or `C:\` on Windows.
    ///
    /// # Example
    ///
    /// ```rust
    /// use std::path::PathBuf;
    /// use path_abs::PathMut;
    ///
    /// let mut somepath = PathBuf::from("foo");
    /// somepath.append("bar");
    ///
    /// assert_eq!(somepath, PathBuf::from("foo/bar"));
    /// ```
    ///
    /// [`pop_up`]: trait.PathMut.html#method.pop_up
    /// [`PathBuf::push`]: https://doc.rust-lang.org/stable/std/path/struct.PathBuf.html#method.push
    fn append<P: AsRef<Path>>(&mut self, path: P) -> Result<()>;

    /// Go "up" one directory.
    ///
    /// This removes the last component of this path. It also resolves any `..` that exist at the
    /// _end_ of the path until a real item can be truncated. If the path is relative, and no
    /// items remain then a `..` is appended to the path.
    ///
    /// # Errors
    ///
    /// This method returns an error if the result would try to go outside a filesystem root,
    /// like `/` on Unix or `C:\` on Windows.
    ///
    /// # Example
    ///
    /// ```rust
    /// # fn example() -> Result<(), path_abs::Error> {
    /// use std::path::Path;
    /// use path_abs::PathMut;
    ///
    /// let executable = Path::new("/usr/loca/bin/myapp");
    /// let mut install_path = executable.to_path_buf();
    /// install_path.pop_up()?;
    ///
    /// assert_eq!(install_path.as_path(), Path::new("/usr/local/bin"));
    /// # Ok(()) }
    /// ```
    ///
    /// Example handling weird relative paths
    ///
    /// ```rust
    /// # fn example() -> Result<(), path_abs::Error> {
    /// use std::path::Path;
    /// use path_abs::PathMut;
    ///
    /// let executable = Path::new("../../weird/../relative/path/../../");
    /// let mut install_path = executable.to_path_buf();
    /// install_path.pop_up()?;
    ///
    /// assert_eq!(install_path.as_path(), Path::new("../../../"));
    /// # Ok(()) }
    /// ```
    ///
    /// Error use case
    ///
    /// ```rust
    /// # fn example() -> Result<(), path_abs::Error> {
    /// use std::path::Path;
    /// use path_abs::PathMut;
    ///
    /// let tmp = Path::new("/tmp");
    /// let mut relative = tmp.to_path_buf();
    /// relative.pop_up()?;
    /// assert!(relative.pop_up().is_err());
    /// # Ok(()) }
    /// ```
    fn pop_up(&mut self) -> Result<()>;

    /// Removes all components after the root, if any.
    ///
    /// This is mostly useful on Windows, since it preserves the prefix before
    /// the root.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use std::path::PathBuf;
    /// use path_abs::PathMut;
    ///
    /// let mut somepath = PathBuf::from(r"C:\foo\bar");
    /// somepath.truncate_to_root();
    ///
    /// assert_eq!(somepath, PathBuf::from(r"C:\"));
    /// ```
    fn truncate_to_root(&mut self);

    fn set_file_name<S: AsRef<ffi::OsStr>>(&mut self, file_name: S);

    fn set_extension<S: AsRef<ffi::OsStr>>(&mut self, extension: S) -> bool;
}

impl PathMut for PathBuf {
    fn append<P: AsRef<Path>>(&mut self, path: P) -> Result<()> {
        for each in path.as_ref().components() {
            match each {
                Component::Normal(c) => self.push(c),
                Component::CurDir => (), // "." does nothing
                Component::Prefix(_) => {
                    return Err(Error::new(
                        io::Error::new(io::ErrorKind::Other, "appended path has a prefix"),
                        "appending path",
                        path.as_ref().to_path_buf().into(),
                    ));
                }
                Component::RootDir => (), // leading "/" does nothing
                Component::ParentDir => self.pop_up()?,
            }
        }

        Ok(())
    }

    fn pop_up(&mut self) -> Result<()> {
        /// Pop off the parent components and return how
        /// many were removed.
        fn pop_parent_components(p: &mut PathBuf) -> usize {
            let mut cur_dirs: usize = 0;
            let mut parents: usize = 0;
            let mut components = p.components();
            while let Some(c) = components.next_back() {
                match c {
                    Component::CurDir => cur_dirs += 1,
                    Component::ParentDir => parents += 1,
                    _ => break,
                }
            }
            for _ in 0..(cur_dirs + parents) {
                p.pop();
            }
            parents
        }

        let mut ending_parents = 0;
        loop {
            ending_parents += pop_parent_components(self);
            if ending_parents == 0 || self.file_name().is_none() {
                break;
            } else {
                // we have at least one "parent" to consume
                self.pop();
                ending_parents -= 1;
            }
        }

        if self.pop() {
            // do nothing, success
        } else if self.has_root() {
            // We tried to pop off the root
            return Err(Error::new(
                io::Error::new(io::ErrorKind::NotFound, "cannot get parent of root path"),
                "truncating to parent",
                self.clone().into(),
            ));
        } else {
            // we are creating a relative path, `"../"`
            self.push("..")
        }

        // Put all unhandled parents back, creating a relative path.
        for _ in 0..ending_parents {
            self.push("..")
        }

        Ok(())
    }

    fn truncate_to_root(&mut self) {
        let mut res = PathBuf::new();
        for component in self.components().take(2) {
            match component {
                // We want to keep prefix and RootDir components of this path
                Component::Prefix(_) | Component::RootDir => res.push(component),
                // We want to discard all other components.
                _ => break,
            }
        }

        // Clobber ourselves with the new value.
        *self = res;
    }

    fn set_file_name<S: AsRef<ffi::OsStr>>(&mut self, file_name: S) {
        self.set_file_name(file_name)
    }

    fn set_extension<S: AsRef<ffi::OsStr>>(&mut self, extension: S) -> bool {
        self.set_extension(extension)
    }
}

impl PathMut for Arc<PathBuf> {
    fn append<P: AsRef<Path>>(&mut self, path: P) -> Result<()> {
        Arc::make_mut(self).append(path)
    }
    fn pop_up(&mut self) -> Result<()> {
        Arc::make_mut(self).pop_up()
    }
    fn truncate_to_root(&mut self) {
        Arc::make_mut(self).truncate_to_root()
    }
    fn set_file_name<S: AsRef<ffi::OsStr>>(&mut self, file_name: S) {
        Arc::make_mut(self).set_file_name(file_name)
    }
    fn set_extension<S: AsRef<ffi::OsStr>>(&mut self, extension: S) -> bool {
        Arc::make_mut(self).set_extension(extension)
    }
}

/// Methods that return new path-like objects.
///
/// Like the methods of [`PathInfo`] and [`PathMut`], these methods are similar
/// to ones from the standard library's [`PathBuf`] but may return a rich
/// [`path_abs::Error`] instead of a [`std::io::Error`] (although it will
/// automatically convert into a `std::io::Error` with `?` if needed).
///
/// Unlike the methods of [`PathInfo`] and [`PathMut`], different types that
/// implement this trait may have different return types.
///
/// [`PathInfo`]: trait.PathInfo.html
/// [`PathMut`]: trait.PathMut.html
/// [`PathBuf`]: https://doc.rust-lang.org/stable/std/path/struct.PathBuf.html
/// [`path_abs::Error`]: struct.Error.html
/// [`std::io::Error`]: https://doc.rust-lang.org/stable/std/io/struct.Error.html
pub trait PathOps: PathInfo {
    type Output: PathOps;

    /// Returns a new value representing the concatenation of two paths.
    ///
    /// Note that this method represents pure concatenation, not "adjoinment"
    /// like [`PathBuf::join`], so absolute paths won't wholly replace the
    /// current path. See [`append`] for more information about how it works.
    ///
    /// # Errors
    ///
    /// This method returns an error if the result would try to go outside a filesystem root,
    /// like `/` on Unix or `C:\` on Windows.
    ///
    /// # Example
    ///
    /// ```rust
    /// use path_abs::{PathInfo, PathOps, Result};
    ///
    /// fn find_config_file<P: PathOps>(
    ///     search_path: &[P],
    ///     file_name: &str,
    /// ) -> Option<<P as PathOps>::Output> {
    ///     for each in search_path.iter() {
    ///         if let Ok(maybe_config) = each.concat(file_name) {
    ///             if maybe_config.is_file() { return Some(maybe_config); }
    ///         }
    ///     }
    ///
    ///     None
    /// }
    /// ```
    ///
    /// [`append`]: trait.PathMut.html#method.append
    /// [`PathBuf::join`]: https://doc.rust-lang.org/stable/std/path/struct.PathBuf.html#method.join
    fn concat<P: AsRef<Path>>(&self, path: P) -> Result<Self::Output>;

    /// An exact replica of `std::path::Path::join` with all of its gotchas and pitfalls,, except
    /// returns a more relevant type.
    ///
    /// In general, prefer [`concat`]
    ///
    /// [`concat`]: trait.PathOps.html#method.concat
    fn join<P: AsRef<Path>>(&self, path: P) -> Self::Output;

    /// Creates a new path object like `self` but with the given file name.
    ///
    /// The same as [`std::path::Path::with_file_name()`], except that the
    /// return type depends on the trait implementation.
    ///
    /// [`std::path::Path::with_file_name()`]: https://doc.rust-lang.org/stable/std/path/struct.Path.html#method.with_file_name
    fn with_file_name<S: AsRef<ffi::OsStr>>(&self, file_name: S) -> Self::Output;

    /// Creates a new path object like `self` but with the given extension.
    ///
    /// The same as [`std::path::Path::with_extension()`], except that the
    /// return type depends on the trait implementation.
    ///
    /// [`std::path::Path::with_extension()`]: https://doc.rust-lang.org/stable/std/path/struct.Path.html#method.with_extension
    fn with_extension<S: AsRef<ffi::OsStr>>(&self, extension: S) -> Self::Output;
}

// impl<T> PathOps for T
// where
//     T: PathInfo
//
// {
//     type Output = PathBuf;
//
//     fn concat<P: AsRef<Path>>(&self, path: P) -> Result<Self::Output> {
//         let mut res = self.as_ref().to_owned();
//         res.append(path)?;
//         Ok(res)
//     }
//
//     fn with_file_name<S: AsRef<ffi::OsStr>>(&self, file_name: S) -> Self::Output {
//         let mut res = self.as_ref().to_owned();
//         res.set_file_name(file_name);
//         res
//     }
//
//     fn with_extension<S: AsRef<ffi::OsStr>>(&self, extension: S) -> Self::Output {
//         let mut res = self.as_ref().to_owned();
//         res.set_extension(extension);
//         res
//     }
// }

impl PathOps for Path {
    type Output = PathBuf;

    fn concat<P: AsRef<Path>>(&self, path: P) -> Result<Self::Output> {
        let mut res = self.to_owned();
        res.append(path)?;
        Ok(res)
    }

    fn join<P: AsRef<Path>>(&self, path: P) -> Self::Output {
        Path::join(self, path)
    }

    fn with_file_name<S: AsRef<ffi::OsStr>>(&self, file_name: S) -> Self::Output {
        let mut res = self.to_owned();
        res.set_file_name(file_name);
        res
    }

    fn with_extension<S: AsRef<ffi::OsStr>>(&self, extension: S) -> Self::Output {
        let mut res = self.to_owned();
        res.set_extension(extension);
        res
    }
}

impl PathOps for PathBuf {
    type Output = PathBuf;

    fn concat<P: AsRef<Path>>(&self, path: P) -> Result<Self::Output> {
        self.as_path().concat(path)
    }

    fn join<P: AsRef<Path>>(&self, path: P) -> Self::Output {
        Path::join(self, path)
    }

    fn with_file_name<S: AsRef<ffi::OsStr>>(&self, file_name: S) -> Self::Output {
        self.as_path().with_file_name(file_name)
    }

    fn with_extension<S: AsRef<ffi::OsStr>>(&self, extension: S) -> Self::Output {
        self.as_path().with_extension(extension)
    }
}

impl PathOps for Arc<PathBuf> {
    type Output = Arc<PathBuf>;

    fn concat<P: AsRef<Path>>(&self, path: P) -> Result<Self::Output> {
        let mut res = self.clone();
        Arc::make_mut(&mut res).append(path)?;
        Ok(res)
    }

    fn join<P: AsRef<Path>>(&self, path: P) -> Self::Output {
        let buf = Path::join(self, path);
        Arc::new(buf)
    }

    fn with_file_name<S: AsRef<ffi::OsStr>>(&self, file_name: S) -> Self::Output {
        let mut res = self.clone();
        Arc::make_mut(&mut res).set_file_name(file_name);
        res
    }

    fn with_extension<S: AsRef<ffi::OsStr>>(&self, extension: S) -> Self::Output {
        let mut res = self.clone();
        Arc::make_mut(&mut res).set_extension(extension);
        res
    }
}

#[cfg(test)]
mod tests {
    use regex::{self, Regex};
    use tempdir::TempDir;

    use super::*;

    macro_rules! assert_match {
        ($re: expr, $err: expr) => {{
            let re = Regex::new(&$re).unwrap();
            let err = $err.to_string();
            assert!(
                re.is_match(&err),
                "\nGot Err         : {:?}\nMatching against: {:?}",
                err.to_string(),
                $re
            );
        }};
    }

    fn escape<P: AsRef<Path>>(path: P) -> String {
        regex::escape(&format!("{}", path.as_ref().display()))
    }

    #[test]
    /// Tests to make sure the error messages look like we expect.
    fn sanity_errors() {
        let tmp_dir = TempDir::new("example").expect("create temp dir");
        let tmp_abs = PathDir::new(tmp_dir.path()).expect("tmp_abs");

        {
            let foo_path = tmp_abs.concat("foo.txt").expect("path foo.txt");
            let foo = PathFile::create(foo_path).expect("create foo.txt");
            foo.clone().remove().unwrap();
            let pat = if cfg!(unix) {
                format!(
                    r"No such file or directory \(os error \d+\) when opening {}",
                    escape(&foo)
                )
            } else {
                format!(
                    r"The system cannot find the file specified. \(os error \d+\) when opening {}",
                    escape(&foo)
                )
            };
            assert_match!(pat, foo.open_edit().unwrap_err())
        }
    }

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

        #[cfg_attr(windows, test)]
        fn _test_pathinfo_parent() {
            let p = PathBuf::from(r"C:\foo\bar");

            let actual = <PathBuf as PathInfo>::parent(&p).expect("could not find parent?");
            let expected = PathBuf::from(r"C:\foo");
            assert_eq!(actual, expected);

            let p = PathBuf::from(r"C:\");
            let actual = <PathBuf as PathInfo>::parent(&p).expect_err("root has a parent?");
            assert_eq!(actual.io_error().kind(), io::ErrorKind::NotFound);
            assert_eq!(actual.action(), "truncating to parent");
            assert_eq!(actual.path(), Path::new(r"C:\"));
        }

        #[cfg_attr(windows, test)]
        fn _test_pathinfo_starts_with() {
            let p = PathBuf::from(r"foo\bar");

            assert_eq!(
                <PathBuf as PathInfo>::starts_with(&p, Path::new("foo")),
                true,
            );
            assert_eq!(
                <PathBuf as PathInfo>::starts_with(&p, Path::new("bar")),
                false,
            );
        }

        #[cfg_attr(windows, test)]
        fn _test_pathinfo_ends_with() {
            let p = PathBuf::from(r"foo\bar");

            assert_eq!(
                <PathBuf as PathInfo>::ends_with(&p, Path::new("foo")),
                false,
            );
            assert_eq!(<PathBuf as PathInfo>::ends_with(&p, Path::new("bar")), true,);
        }

        #[cfg_attr(windows, test)]
        fn _test_pathops_concat() {
            let actual = Path::new("foo")
                .concat(Path::new("bar"))
                .expect("Could not concat paths?");
            let expected = PathBuf::from(r"foo\bar");
            assert_eq!(actual, expected);

            let actual = Path::new("foo")
                .concat(Path::new(r"bar\..\baz"))
                .expect("Could not concat path with ..?");
            let expected = PathBuf::from(r"foo\baz");
            assert_eq!(actual, expected);

            let actual = Path::new("foo")
                .concat("..")
                .expect("Could not cancel path with ..?");
            let expected = PathBuf::from(r"");
            assert_eq!(actual, expected);

            let actual = Path::new("foo")
                .concat(r"..\..")
                .expect("Could not escape prefix with ..?");
            let expected = PathBuf::from("../");
            assert_eq!(actual, expected);

            let actual = Path::new(r"C:\foo")
                .concat(r"..\..")
                .expect_err("Could escape root with ..?");
            assert_eq!(actual.io_error().kind(), io::ErrorKind::NotFound);
            assert_eq!(actual.action(), "truncating to parent");
            assert_eq!(actual.path(), Path::new(r"C:\"));

            let actual = Path::new("foo")
                .concat(Path::new(r"\windows\system32"))
                .expect("Could not concat path with RootDir?");
            let expected = PathBuf::from(r"foo\windows\system32");
            assert_eq!(actual, expected);

            let actual = Path::new("foo")
                .concat(Path::new(r"C:bar"))
                .expect_err("Could concat path with prefix?");
            assert_eq!(actual.io_error().kind(), io::ErrorKind::Other);
            assert_eq!(actual.action(), "appending path");
            assert_eq!(actual.path(), Path::new(r"C:bar"));
        }

        #[cfg_attr(windows, test)]
        fn _test_pathmut_append() {
            let mut actual = PathBuf::from("foo");
            actual
                .append(Path::new("bar"))
                .expect("Could not append paths?");
            let expected = PathBuf::from(r"foo\bar");
            assert_eq!(actual, expected);

            let mut actual = PathBuf::from("foo");
            actual
                .append(Path::new(r"bar\..\baz"))
                .expect("Could not append path with ..?");
            let expected = PathBuf::from(r"foo\baz");
            assert_eq!(actual, expected);

            let mut actual = PathBuf::from("foo");
            actual.append("..").expect("Could not cancel path with ..?");
            let expected = PathBuf::from(r"");
            assert_eq!(actual, expected);

            let mut actual = PathBuf::from("foo");
            actual
                .append(r"..\..")
                .expect("Could not escape prefix with ..?");
            let expected = PathBuf::from("../");
            assert_eq!(actual, expected);

            let actual = PathBuf::from(r"C:\foo")
                .append(r"..\..")
                .expect_err("Could escape root with ..?");

            assert_eq!(actual.io_error().kind(), io::ErrorKind::NotFound);
            assert_eq!(actual.action(), "truncating to parent");
            assert_eq!(actual.path(), Path::new(r"C:\"));

            let mut actual = PathBuf::from("foo");
            actual
                .append(Path::new(r"\windows\system32"))
                .expect("Could not append RootDir to path?");
            let expected = PathBuf::from(r"foo\windows\system32");
            assert_eq!(actual, expected);

            let actual = PathBuf::from("foo")
                .append(Path::new(r"C:bar"))
                .expect_err("Could append prefix to path?");
            assert_eq!(actual.io_error().kind(), io::ErrorKind::Other);
            assert_eq!(actual.action(), "appending path");
            assert_eq!(actual.path(), Path::new(r"C:bar"));
        }

        #[cfg_attr(windows, test)]
        fn _test_pathmut_pop_up() {
            let mut p = PathBuf::from(r"C:\foo\bar");
            p.pop_up().expect("could not find parent?");
            assert_eq!(p.as_path(), Path::new(r"C:\foo"));

            let mut p = PathBuf::from(r"C:\");
            let actual = p.pop_up().expect_err("root has a parent?");
            assert_eq!(actual.io_error().kind(), io::ErrorKind::NotFound);
            assert_eq!(actual.action(), "truncating to parent");
            assert_eq!(actual.path(), Path::new(r"C:\"));
        }

        #[cfg_attr(windows, test)]
        fn _test_pathmut_truncate_to_root() {
            let mut p = PathBuf::from(r"C:\foo\bar");
            p.truncate_to_root();
            assert_eq!(p.as_path(), Path::new(r"C:\"));

            let mut p = PathBuf::from(r"C:foo");
            p.truncate_to_root();
            assert_eq!(p.as_path(), Path::new(r"C:"));

            let mut p = PathBuf::from(r"\foo");
            p.truncate_to_root();
            assert_eq!(p.as_path(), Path::new(r"\"));

            let mut p = PathBuf::from(r"foo");
            p.truncate_to_root();
            assert_eq!(p.as_path(), Path::new(r""));
        }
    }

    mod any {
        use super::*;

        #[test]
        fn test_pathinfo_is_absolute() {
            let p = PathBuf::from("/foo/bar");

            let expected = !cfg!(windows);
            assert_eq!(<PathBuf as PathInfo>::is_absolute(&p), expected);
        }

        #[test]
        fn test_pathinfo_parent() {
            let p = PathBuf::from("/foo/bar");

            let actual = <PathBuf as PathInfo>::parent(&p).expect("could not find parent?");
            let expected = PathBuf::from("/foo");

            assert_eq!(actual, expected);

            let p = PathBuf::from("/");

            let actual = <PathBuf as PathInfo>::parent(&p).expect_err("root has a parent?");

            assert_eq!(actual.io_error().kind(), io::ErrorKind::NotFound);
            assert_eq!(actual.action(), "truncating to parent");
            assert_eq!(actual.path(), Path::new("/"));
        }

        #[test]
        fn test_pathinfo_starts_with() {
            let p = PathBuf::from("foo/bar");

            assert_eq!(
                <PathBuf as PathInfo>::starts_with(&p, Path::new("foo")),
                true,
            );
            assert_eq!(
                <PathBuf as PathInfo>::starts_with(&p, Path::new("bar")),
                false,
            );
        }

        #[test]
        fn test_pathinfo_ends_with() {
            let p = PathBuf::from("foo/bar");

            assert_eq!(
                <PathBuf as PathInfo>::ends_with(&p, Path::new("foo")),
                false,
            );
            assert_eq!(<PathBuf as PathInfo>::ends_with(&p, Path::new("bar")), true,);
        }

        #[test]
        fn test_pathops_concat() {
            let actual = Path::new("foo")
                .concat(Path::new("bar"))
                .expect("Could not concat paths?");
            let expected = PathBuf::from("foo/bar");

            assert_eq!(actual, expected);

            let actual = Path::new("foo")
                .concat(Path::new("bar/../baz"))
                .expect("Could not concat path with ..?");
            let expected = PathBuf::from("foo/baz");

            assert_eq!(actual, expected);

            let actual = Path::new("foo")
                .concat("..")
                .expect("Could not cancel path with ..?");
            let expected = PathBuf::from(r"");

            assert_eq!(actual, expected);

            let actual = Path::new("foo")
                .concat("../..")
                .expect("Could not prefix with ..?");
            let expected = PathBuf::from(r"../");
            assert_eq!(actual, expected);

            let actual = Path::new("/foo")
                .concat("../..")
                .expect_err("Could escape root with ..?");

            assert_eq!(actual.io_error().kind(), io::ErrorKind::NotFound);
            assert_eq!(actual.action(), "truncating to parent");
            assert_eq!(actual.path(), Path::new("/"));

            let actual = Path::new("foo")
                .concat(Path::new("/etc/passwd"))
                .expect("Could not concat RootDir to path?");
            let expected: PathBuf = PathBuf::from("foo/etc/passwd");

            assert_eq!(actual, expected);
        }

        #[test]
        fn test_pathops_concat_relative() {
            let actual = Path::new("../foo")
                .concat("bar")
                .expect("Could not create relative path with concat");
            let expected = PathBuf::from(r"../foo/bar");
            assert_eq!(actual, expected);

            let actual = Path::new("../foo")
                .concat("..")
                .expect("Could not create relative path with concat");
            let expected = PathBuf::from(r"..");
            assert_eq!(actual, expected);

            let actual = Path::new("../foo")
                .concat("../..")
                .expect("Could not create relative path with concat");
            let expected = PathBuf::from(r"../..");
            assert_eq!(actual, expected);

            let actual = Path::new("../foo/../bar")
                .concat("../..")
                .expect("Could not create relative path with concat");
            let expected = PathBuf::from(r"../..");
            assert_eq!(actual, expected);

            let actual = Path::new("../foo/../bar/..")
                .concat("../..")
                .expect("Could not create relative path with concat");
            let expected = PathBuf::from(r"../../..");
            assert_eq!(actual, expected);

            let actual = PathBuf::from("../foo/..")
                .concat("../../baz")
                .expect("Could not create relative path with concat");
            let expected = PathBuf::from(r"../../../baz");
            assert_eq!(actual, expected);
        }

        #[test]
        fn test_pathops_concat_cur() {
            // just check that pahts don't normalize...
            let actual = Path::new("foo/././..").as_os_str();
            let expected = ffi::OsStr::new("foo/././..");
            assert_eq!(actual, expected);

            let actual = PathBuf::from("././foo/././..")
                .concat("../bar")
                .expect("Could not create relative path with concat");
            let expected = PathBuf::from(r"../bar");
            assert_eq!(actual, expected);
        }

        #[test]
        fn test_pathops_concat_consume() {
            let actual = Path::new("foo")
                .concat("../../bar")
                .expect("Could not create relative path with concat");
            let expected = PathBuf::from(r"../bar");
            assert_eq!(actual, expected);
        }

        #[test]
        fn test_pathmut_append() {
            let mut actual = PathBuf::from("foo");
            actual
                .append(Path::new("bar"))
                .expect("Could not append paths?");
            let expected = PathBuf::from("foo/bar");
            assert_eq!(actual, expected);

            let mut actual = PathBuf::from("foo");
            actual
                .append(Path::new("bar/../baz"))
                .expect("Could not append path with ..?");
            let expected = PathBuf::from("foo/baz");
            assert_eq!(actual, expected);

            let mut actual = PathBuf::from("foo");
            actual.append("..").expect("Could not cancel path with ..?");
            let expected = PathBuf::from(r"");
            assert_eq!(actual, expected);

            let mut actual = PathBuf::from("foo");
            actual
                .append("../..")
                .expect("Could not escape prefix with ..?");
            let expected = PathBuf::from("../");
            assert_eq!(actual, expected);

            let actual = PathBuf::from("/foo")
                .append("../..")
                .expect_err("Could escape root with ..?");
            assert_eq!(actual.io_error().kind(), io::ErrorKind::NotFound);
            assert_eq!(actual.action(), "truncating to parent");
            assert_eq!(actual.path(), Path::new("/"));

            let mut actual = PathBuf::from("foo");
            actual
                .append(Path::new("/etc/passwd"))
                .expect("Could not append RootDir to path?");
            let expected: PathBuf = PathBuf::from("foo/etc/passwd");

            assert_eq!(actual, expected);
        }

        #[test]
        fn test_pathmut_pop_up() {
            let mut p = PathBuf::from("/foo/bar");
            p.pop_up().expect("could not find parent?");

            assert_eq!(p.as_path(), Path::new("/foo"));

            let mut p = PathBuf::from("/");
            let actual = p.pop_up().expect_err("root has a parent?");

            assert_eq!(actual.io_error().kind(), io::ErrorKind::NotFound);
            assert_eq!(actual.action(), "truncating to parent");
            assert_eq!(actual.path(), Path::new("/"));
        }

        #[test]
        fn test_pathmut_truncate_to_root() {
            let mut p = PathBuf::from("/foo/bar");
            p.truncate_to_root();
            assert_eq!(p.as_path(), Path::new("/"));

            let mut p = PathBuf::from("foo/bar");
            p.truncate_to_root();
            assert_eq!(p.as_path(), Path::new(""));
        }
    }
}