1 | use serde::de::{Deserialize, Deserializer}; |
2 | use serde_derive::Serialize; |
3 | use std::borrow::Cow; |
4 | use std::env; |
5 | use std::ffi::OsString; |
6 | use std::io; |
7 | use std::path::{Path, PathBuf}; |
8 | |
9 | #[derive(Clone, Debug, Serialize)] |
10 | #[serde(transparent)] |
11 | pub struct Directory { |
12 | path: PathBuf, |
13 | } |
14 | |
15 | impl Directory { |
16 | pub fn new<P: Into<PathBuf>>(path: P) -> Self { |
17 | let mut path = path.into(); |
18 | path.push("" ); |
19 | Directory { path } |
20 | } |
21 | |
22 | pub fn current() -> io::Result<Self> { |
23 | env::current_dir().map(Directory::new) |
24 | } |
25 | |
26 | pub fn to_string_lossy(&self) -> Cow<str> { |
27 | self.path.to_string_lossy() |
28 | } |
29 | |
30 | pub fn join<P: AsRef<Path>>(&self, tail: P) -> PathBuf { |
31 | self.path.join(tail) |
32 | } |
33 | |
34 | pub fn parent(&self) -> Option<Self> { |
35 | self.path.parent().map(Directory::new) |
36 | } |
37 | |
38 | pub fn canonicalize(&self) -> io::Result<Self> { |
39 | self.path.canonicalize().map(Directory::new) |
40 | } |
41 | } |
42 | |
43 | impl From<OsString> for Directory { |
44 | fn from(os_string: OsString) -> Self { |
45 | Directory::new(PathBuf::from(os_string)) |
46 | } |
47 | } |
48 | |
49 | impl AsRef<Path> for Directory { |
50 | fn as_ref(&self) -> &Path { |
51 | &self.path |
52 | } |
53 | } |
54 | |
55 | impl<'de> Deserialize<'de> for Directory { |
56 | fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> |
57 | where |
58 | D: Deserializer<'de>, |
59 | { |
60 | PathBuf::deserialize(deserializer).map(Directory::new) |
61 | } |
62 | } |
63 | |