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
#![deny(rust_2018_idioms)]

macro_rules! dir {
    (| $x:ident | $($input:tt)*) => {
        DIRS.as_ref()
            .map(|$x| $($input)*)
            .map_err(|e| e.clone())
    }
}

#[cfg(any(feature = "android", target_os = "android"))]
pub mod android;
#[cfg(any(feature = "ios", target_os = "ios"))]
pub mod ios;
#[cfg(any(feature = "linux", target_os = "linux"))]
pub mod linux;
#[cfg(any(feature = "macos", target_os = "macos", target_os = "ios"))]
pub mod macos;
#[cfg(any(feature = "windows", target_os = "windows"))]
pub mod windows;
#[cfg(any(unix, feature = "xdg"))]
pub mod xdg;

#[cfg(target_os = "android")]
pub use android::system;
#[cfg(target_os = "ios")]
pub use ios::system;
#[cfg(target_os = "linux")]
pub use linux::system;
#[cfg(target_os = "macos")]
pub use macos::system;
#[cfg(windows)]
pub use windows::system;

#[cfg(target_os = "android")]
pub use android::user;
#[cfg(target_os = "ios")]
pub use ios::user;
#[cfg(target_os = "linux")]
pub use linux::user;
#[cfg(target_os = "macos")]
pub use macos::user;
#[cfg(windows)]
pub use windows::user;

use iref::IriBuf;
use os_str_bytes::{OsStrBytes, OsStringBytes};
use percent_encoding::{percent_decode_str, percent_encode, NON_ALPHANUMERIC};
use std::{
    borrow::Cow,
    ffi::{OsStr, OsString},
    iter::once,
    path::{Component, Path, PathBuf, Prefix},
};

#[derive(Debug, thiserror::Error)]
pub enum ResolveError {
    #[error("IRI does not have a supported scheme. Got: '{0}', Supported: {1:?}")]
    InvalidScheme(String, &'static [&'static str]),

    #[error("IRI is empty")]
    EmptyIri,

    #[error("Failed to convert path to IRI.")]
    ConversionFailed(#[from] IriError),

    #[error("Error")]
    Error(#[from] Error),
}

#[derive(Clone, Debug, thiserror::Error)]
pub enum IriError {
    #[error("Could not convert path component to UTF-8 representation.")]
    InvalidUtf8(#[from] std::string::FromUtf8Error),

    #[error("Path must not contain parent or current directory components (e.g. `.` or `..`)")]
    InvalidComponent,

    #[error("Unsupported prefix.")]
    UnsupportedPrefix,

    #[error("Failed to parse input as an IRI.")]
    InvalidIri(iref::Error),
}

#[derive(Clone, Debug, thiserror::Error)]
pub enum Error {
    #[error("No home directory found!")]
    NoHomeDirectory,

    #[error("Failed to create directory for path: '{}'", .1.display())]
    CreateDirectoryFailed(#[source] eieio::Error, PathBuf),

    #[error("Failed to convert path to IRI")]
    IriConversionFailed(#[from] IriError),
}

#[inline(always)]
fn os_str_to_cow_str<'a>(os_str: &'a OsStr) -> Cow<'a, str> {
    match os_str.to_str() {
        Some(v) => Cow::Borrowed(v),
        None => {
            let bytes = os_str.to_bytes();
            let mut iter = percent_encode(&bytes, NON_ALPHANUMERIC);
            match iter.next() {
                None => "".into(),
                Some(first) => match iter.next() {
                    None => unreachable!(),
                    Some(second) => {
                        let mut string = first.to_owned();
                        string.push_str(second);
                        string.extend(iter);
                        string.into()
                    }
                },
            }
        }
    }
}

#[inline]
fn resolve_file_iri(iri: &IriBuf) -> Result<PathBuf, ResolveError> {
    if iri.path().first().is_some() {
        let mut segments = iri.path().into_iter().map(|segment| -> OsString {
            let bytes: Cow<'_, [u8]> = percent_decode_str(segment.as_str()).into();
            // This should never panic, and according to the documentation,
            // panicking here is the correct behaviour if it _does_ break an invariant and fail.
            OsString::from_bytes(bytes)
                .expect("Invariant failed to be upheld: invalid OS string data")
        });
        let start = segments.next().unwrap();
        Ok(segments
            .fold(start, |mut acc: OsString, cur: OsString| {
                acc.push(cur);
                acc
            })
            .into())
    } else {
        Err(ResolveError::EmptyIri)
    }
}

#[inline]
#[cfg(any(
    feature = "android",
    target_os = "android",
    feature = "ios",
    target_os = "ios",
))]
fn resolve_container_iri(prefix: PathBuf, iri: &IriBuf) -> Result<PathBuf, ResolveError> {
    let segments = iri.path().into_iter().map(|segment| -> OsString {
        let bytes: Cow<'_, [u8]> = percent_decode_str(segment.as_str()).into();
        // This should never panic, and according to the documentation,
        // panicking here is the correct behaviour if it _does_ break an invariant and fail.
        OsString::from_bytes(bytes).expect("Invariant failed to be upheld: invalid OS string data")
    });
    Ok(segments
        .fold(prefix, |mut acc: PathBuf, cur: OsString| {
            acc.push(cur);
            acc
        })
        .into())
}

pub fn file_path<P: AsRef<Path>>(path: P) -> Result<IriBuf, IriError> {
    let input = once(Ok(Cow::Borrowed("file:///")))
        .chain(path.as_ref().components().map(|c| {
            Ok(match c {
                Component::Prefix(prefix) => match prefix.kind() {
                    Prefix::Verbatim(verbatim) => os_str_to_cow_str(verbatim),
                    Prefix::VerbatimUNC(server, share) => Cow::Owned(format!(
                        "{}/{}",
                        os_str_to_cow_str(server),
                        os_str_to_cow_str(share)
                    )),
                    Prefix::VerbatimDisk(disk) => {
                        Cow::Owned(unsafe { std::str::from_utf8_unchecked(&[disk]) }.to_string())
                    }
                    Prefix::DeviceNS(_) => return Err(IriError::UnsupportedPrefix),
                    Prefix::UNC(server, share) => Cow::Owned(format!(
                        "{}/{}",
                        os_str_to_cow_str(server),
                        os_str_to_cow_str(share)
                    )),
                    Prefix::Disk(disk) => {
                        Cow::Owned(unsafe { std::str::from_utf8_unchecked(&[disk]) }.to_string())
                    }
                },
                Component::RootDir => Cow::Borrowed(""),
                Component::CurDir => return Err(IriError::InvalidComponent),
                Component::ParentDir => return Err(IriError::InvalidComponent),
                Component::Normal(value) => os_str_to_cow_str(value),
            })
        }))
        .collect::<Result<Vec<_>, _>>()?
        .join("/");
    IriBuf::new(&input).map_err(IriError::InvalidIri)
}

pub trait AppDirs: Sized {
    fn new<P>(prefix: P) -> Result<Self, Error>
    where
        P: Into<PathBuf>;
    fn create(&self) -> Result<(), Error>;
    fn data_dir(&self) -> &Path;
    fn config_dir(&self) -> &Path;
    fn cache_dir(&self) -> &Path;
    fn log_dir(&self) -> &Path;
    fn temporary_dir(&self) -> &Path;
}

pub trait UserDirs: Sized {
    fn new() -> Result<Self, Error>;
    fn home_dir(&self) -> &Path;
    fn data_dir(&self) -> &Path;
    fn cache_dir(&self) -> &Path;
}