unrspack_resolver/
context.rs

1use std::path::{Path, PathBuf};
2
3use crate::error::ResolveError;
4
5#[derive(Debug, Default, Clone)]
6pub struct ResolveContext {
7    pub fully_specified: bool,
8
9    pub query: Option<String>,
10
11    pub fragment: Option<String>,
12
13    /// Files that was found on file system
14    pub file_dependencies: Option<Vec<PathBuf>>,
15
16    /// Files that was found on file system
17    pub missing_dependencies: Option<Vec<PathBuf>>,
18
19    /// The current resolving alias for bailing recursion alias.
20    pub resolving_alias: Option<String>,
21
22    /// For avoiding infinite recursion, which will cause stack overflow.
23    depth: u8,
24}
25
26impl ResolveContext {
27    pub fn with_fully_specified(&mut self, yes: bool) {
28        self.fully_specified = yes;
29    }
30
31    pub fn with_query_fragment(&mut self, query: Option<&str>, fragment: Option<&str>) {
32        if let Some(query) = query {
33            self.query.replace(query.to_string());
34        }
35        if let Some(fragment) = fragment {
36            self.fragment.replace(fragment.to_string());
37        }
38    }
39
40    pub fn init_file_dependencies(&mut self) {
41        self.file_dependencies.replace(vec![]);
42        self.missing_dependencies.replace(vec![]);
43    }
44
45    pub fn add_file_dependency(&mut self, dep: &Path) {
46        if let Some(deps) = &mut self.file_dependencies {
47            deps.push(dep.to_path_buf());
48        }
49    }
50
51    pub fn add_missing_dependency(&mut self, dep: &Path) {
52        if let Some(deps) = &mut self.missing_dependencies {
53            deps.push(dep.to_path_buf());
54        }
55    }
56
57    pub fn with_resolving_alias(&mut self, alias: String) {
58        self.resolving_alias = Some(alias);
59    }
60
61    /// Increases the context's depth in order to detect recursion.
62    ///
63    /// ### Errors
64    ///
65    /// * [ResolveError::Recursion]
66    pub fn test_for_infinite_recursion(&mut self) -> Result<(), ResolveError> {
67        self.depth += 1;
68        // 64 should be more than enough for detecting infinite recursion.
69        if self.depth > 64 {
70            return Err(ResolveError::Recursion);
71        }
72        Ok(())
73    }
74}