xsd_parser/parser/resolver/
file_resolver.rs

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
use std::env::current_dir;
use std::fs::File;
use std::io::{BufReader, Error, ErrorKind};
use std::path::{Path, PathBuf};

use url::Url;

use super::{ResolveRequest, Resolver};

/// Implements a [`Resolver`] that can be used to load local files.
#[must_use]
#[derive(Debug)]
pub struct FileResolver {
    search_paths: Vec<PathBuf>,
    use_current_path: bool,
}

impl FileResolver {
    /// Create a new [`FileResolver`] instance.
    pub fn new() -> Self {
        Self {
            search_paths: Vec::new(),
            use_current_path: false,
        }
    }

    /// Wether to use the path of the current schema as base path to resolve
    /// other schema files or not.
    pub fn use_current_path(mut self, value: bool) -> Self {
        self.use_current_path = value;

        self
    }

    /// Add an additional search path to the resolver.
    pub fn add_search_path<P>(mut self, path: P) -> Self
    where
        PathBuf: From<P>,
    {
        self.search_paths.push(PathBuf::from(path));

        self
    }

    /// Add additional search paths to the resolver.
    pub fn add_search_paths<P>(mut self, paths: P) -> Self
    where
        P: IntoIterator,
        PathBuf: From<P::Item>,
    {
        self.search_paths
            .extend(paths.into_iter().map(PathBuf::from));

        self
    }
}

impl Default for FileResolver {
    fn default() -> Self {
        Self::new()
            .use_current_path(true)
            .add_search_paths(current_dir().ok())
    }
}

impl Resolver for FileResolver {
    type Buffer = BufReader<File>;
    type Error = Error;

    fn resolve(
        &mut self,
        req: &ResolveRequest,
    ) -> Result<Option<(Url, Self::Buffer)>, Self::Error> {
        macro_rules! try_resolve {
            ($path:expr) => {{
                let path = $path;
                tracing::trace!("Try to resolve \"file://{}\"", path.display());

                if let Ok(path) = path.canonicalize() {
                    let location = format!("file://{}", path.display());
                    let location = Url::parse(&location).map_err(|err| {
                        Error::new(
                            ErrorKind::InvalidInput,
                            format!("Invalid URL: {location} ({err})"),
                        )
                    })?;
                    let file = File::open(&path)?;
                    let buffer = BufReader::new(file);

                    return Ok(Some((location, buffer)));
                }
            }};
        }

        if req.requested_location.scheme() != "file" {
            return Ok(None);
        }

        /* HACK:
         *   Relative paths are not supported by url.
         *   It is interpreted as host, so we join it manually
         */
        let location = match (req.requested_location.host(), req.requested_location.path()) {
            (Some(host), path) => format!("{host}{path}"),
            (None, path) => path.to_string(),
        };
        let location = Path::new(&location);

        if location.is_absolute() {
            try_resolve!(location);
        }

        if let Some(path) = self
            .use_current_path
            .then_some(())
            .and(req.current_location.as_ref())
            .filter(|url| url.scheme() == "file")
            .map(Url::path)
            .and_then(|path| Path::new(path).parent())
            .map(|dir| dir.join(location))
        {
            try_resolve!(path);
        }

        for dir in &self.search_paths {
            try_resolve!(dir.join(location));
        }

        Ok(None)
    }
}