1use serde::de::{Deserialize, Deserializer};
2use serde_derive::Serialize;
3use std::borrow::Cow;
4use std::env;
5use std::ffi::OsString;
6use std::io;
7use std::path::{Path, PathBuf};
8
9#[derive(Clone, Debug, Serialize)]
10#[serde(transparent)]
11pub struct Directory {
12 path: PathBuf,
13}
14
15impl 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
43impl From<OsString> for Directory {
44 fn from(os_string: OsString) -> Self {
45 Directory::new(PathBuf::from(os_string))
46 }
47}
48
49impl AsRef<Path> for Directory {
50 fn as_ref(&self) -> &Path {
51 &self.path
52 }
53}
54
55impl<'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