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

use crate::{Resolver, ResolverResult};

impl Resolver {
    pub fn normalize_alias(&self, target: String) -> Option<String> {
        match self
            .options
            .alias
            .iter()
            .find(|&(key, _)| target.starts_with(key))
        {
            Some((from, to)) => to.as_ref().map(|to| target.replacen(from, to, 1)),
            None => Some(target),
        }
    }

    pub fn normalize_path(
        &self,
        path: Option<PathBuf>,
        query: &str,
        fragment: &str,
    ) -> ResolverResult {
        if let Some(path) = path {
            if self.options.symlinks {
                Path::canonicalize(&path)
                    .map_err(|_| "Path normalized failed".to_string())
                    .map(|result| {
                        Some(PathBuf::from(format!(
                            "{}{}{}",
                            result.to_str().unwrap(),
                            query,
                            fragment
                        )))
                    })
            } else {
                let result = path
                    .components()
                    .fold(PathBuf::new(), |mut acc, path_component| {
                        match path_component {
                            Component::Prefix(prefix) => acc.push(prefix.as_os_str()),
                            Component::Normal(name) => acc.push(name),
                            Component::RootDir => acc.push("/"),
                            Component::CurDir => {}
                            Component::ParentDir => {
                                acc.pop();
                            }
                        }
                        acc
                    });
                Ok(Some(PathBuf::from(format!(
                    "{}{}{}",
                    result.to_str().unwrap(),
                    query,
                    fragment
                ))))
            }
        } else {
            Ok(None)
        }
    }
}