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
use std::{
    path::{Path, PathBuf},
    mem
};

use mail_core::{IRI, Resource};
use failure::{Fail, Context};

#[derive(Fail, Debug)]
#[fail(display = "unsupported path, only paths with following constraint are allowed: {}", _0)]
pub struct UnsupportedPathError(Context<&'static str>);

impl UnsupportedPathError {
    pub fn new(violated_constraint: &'static str) -> Self {
        UnsupportedPathError(Context::new(violated_constraint))
    }
}

pub trait PathRebaseable {
    /// Prefixes path in the type with `base_dir`.
    ///
    /// # Error
    ///
    /// Some implementors might not support all paths.
    /// For example a implementor requiring rust string
    /// compatible paths might return a
    /// `Err(UnsupportedPathError::new("utf-8"))`.
    fn rebase_to_include_base_dir(&mut self, base_dir: impl AsRef<Path>)
        -> Result<(), UnsupportedPathError>;

    /// Removes the `base_dir` prefix.
    ///
    /// # Error
    ///
    /// Some implementors might not support all paths.
    /// For example a implementor requiring rust string
    /// compatible paths might return a
    /// `Err(UnsupportedPathError::new("utf-8"))`.
    fn rebase_to_exclude_base_dir(&mut self, base_dir: impl AsRef<Path>)
        -> Result<(), UnsupportedPathError>;
}

impl PathRebaseable for PathBuf {
    fn rebase_to_include_base_dir(&mut self, base_dir: impl AsRef<Path>)
        -> Result<(), UnsupportedPathError>
    {
        let new_path;
        if self.is_relative() {
            new_path = base_dir.as_ref().join(&self);
        } else {
            return Ok(());
        }
        mem::replace(self, new_path);
        Ok(())
    }

    fn rebase_to_exclude_base_dir(&mut self, base_dir: impl AsRef<Path>)
        -> Result<(), UnsupportedPathError>
    {
        let new_path;
        if let Ok(path) = self.strip_prefix(base_dir) {
            new_path = path.to_owned();
        } else {
            return Ok(());
        }
        mem::replace(self, new_path);
        Ok(())
    }
}

impl PathRebaseable for IRI {
    fn rebase_to_include_base_dir(&mut self, base_dir: impl AsRef<Path>)
        -> Result<(), UnsupportedPathError>
    {
        if self.scheme() != "path" {
            return Ok(());
        }

        let new_tail = {
            let path = Path::new(self.tail());
            if path.is_relative() {
                base_dir.as_ref().join(path)
            } else {
                return Ok(());
            }
        };

        let new_tail = new_tail.to_str()
            .ok_or_else(|| UnsupportedPathError::new("utf-8"))?;

        let new_iri = self.with_tail(new_tail);
        mem::replace(self, new_iri);
        Ok(())
    }

    fn rebase_to_exclude_base_dir(&mut self, base_dir: impl AsRef<Path>)
        -> Result<(), UnsupportedPathError>
    {
        if self.scheme() != "path" {
            return Ok(());
        }

        let new_iri = {
            let path = Path::new(self.tail());

            if let Ok(path) = path.strip_prefix(base_dir) {
                //UNWRAP_SAFE: we just striped some parts, this can
                // not make it lose it's string-ness
                let new_tail = path.to_str().unwrap();
                self.with_tail(new_tail)
            } else {
                return Ok(());
            }
        };

        mem::replace(self, new_iri);
        Ok(())
    }
}

impl PathRebaseable for Resource {
    fn rebase_to_include_base_dir(&mut self, base_dir: impl AsRef<Path>)
        -> Result<(), UnsupportedPathError>
    {
        if let &mut Resource::Source(ref mut source) = self {
            source.iri.rebase_to_include_base_dir(base_dir)?;
        }
        Ok(())
    }

    fn rebase_to_exclude_base_dir(&mut self, base_dir: impl AsRef<Path>)
        -> Result<(), UnsupportedPathError>
    {
        if let &mut Resource::Source(ref mut source) = self {
            source.iri.rebase_to_exclude_base_dir(base_dir)?;
        }
        Ok(())
    }

}



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

    #[test]
    fn rebase_on_path() {
        let mut path = Path::new("/prefix/suffix.yup").to_owned();
        path.rebase_to_exclude_base_dir("/prefix").unwrap();
        assert_eq!(path, Path::new("suffix.yup"));
        path.rebase_to_include_base_dir("./nfix").unwrap();
        path.rebase_to_include_base_dir("/mfix").unwrap();
        assert_eq!(path, Path::new("/mfix/nfix/suffix.yup"));
        path.rebase_to_exclude_base_dir("/wrong").unwrap();
        assert_eq!(path, Path::new("/mfix/nfix/suffix.yup"));
    }

    #[test]
    fn rebase_on_iri() {
        let mut iri: IRI = "path:/prefix/suffix.yup".parse().unwrap();
        iri.rebase_to_exclude_base_dir("/prefix").unwrap();
        assert_eq!(iri.as_str(), "path:suffix.yup");
        iri.rebase_to_include_base_dir("nfix").unwrap();
        iri.rebase_to_include_base_dir("/mfix").unwrap();
        assert_eq!(iri.as_str(), "path:/mfix/nfix/suffix.yup");
        iri.rebase_to_exclude_base_dir("/wrong").unwrap();
        assert_eq!(iri.as_str(), "path:/mfix/nfix/suffix.yup");
    }

    #[test]
    fn rebase_on_resource() {
        let mut resource = Resource::Source(Source {
            iri: "path:abc/def".parse().unwrap(),
            use_media_type: Default::default(),
            use_file_name: Default::default()
        });

        resource.rebase_to_include_base_dir("./abc").unwrap();
        resource.rebase_to_include_base_dir("/pre").unwrap();
        resource.rebase_to_exclude_base_dir("/pre").unwrap();
        resource.rebase_to_exclude_base_dir("abc").unwrap();
        resource.rebase_to_include_base_dir("abc").unwrap();

        if let Resource::Source(Source { iri, ..}) = resource {
            assert_eq!(iri.as_str(), "path:abc/abc/def");
        } else { unreachable!() }
    }
}