include_graph/dependencies/
path_mapper.rs

1use std::path::{Path, PathBuf};
2
3#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4pub struct PathMapping {
5    pub from: PathBuf,
6    pub to: String,
7}
8
9/// Maps path buffers into actual strings
10#[derive(Default, Debug, Clone)]
11pub struct PathMapper {
12    mappings: Vec<PathMapping>,
13}
14
15impl PathMapper {
16    pub fn add_mapping(&mut self, mapping: PathMapping) {
17        self.mappings.push(mapping);
18    }
19
20    pub fn try_invert(&self, p: &str) -> Option<PathBuf> {
21        self.mappings
22            .iter()
23            .filter_map(|m| {
24                p.strip_prefix(&m.to).map(|tail| {
25                    let mut p = m.from.clone();
26                    p.push(PathBuf::from(tail));
27                    p
28                })
29            })
30            .next()
31    }
32
33    /// Map the given input path into a final name string
34    ///
35    /// Returns the mapped String if a mapping exists, otherwise
36    /// it returns None
37    pub fn try_map(&self, p: &Path) -> Option<String> {
38        for mapping in self.mappings.iter() {
39            if let Ok(rest) = p.strip_prefix(&mapping.from) {
40                return Some(mapping.to.clone() + &rest.to_string_lossy());
41            }
42        }
43        None
44    }
45}