Skip to main content

cargo/context/
path.rs

1use std::path::PathBuf;
2
3use regex::Regex;
4
5use super::{ConfigRelativePath, GlobalContext};
6
7/// Resolves configuration-relative paths using the global context.
8pub trait ConfigRelativePathResolveExt {
9    /// Resolves this configuration-relative path to an absolute path.
10    ///
11    /// This will always return an absolute path where it's relative to the
12    /// location for configuration for this value.
13    fn resolve_path(&self, gctx: &GlobalContext) -> PathBuf;
14
15    /// Same as [`Self::resolve_path`] but will make string replacements
16    /// before resolving the path.
17    ///
18    /// `replacements` should be an [`IntoIterator`] of tuples with the "from" and "to" for the
19    /// string replacement.
20    fn resolve_templated_path(
21        &self,
22        gctx: &GlobalContext,
23        replacements: impl IntoIterator<Item = (impl AsRef<str>, impl AsRef<str>)>,
24    ) -> Result<PathBuf, ResolveTemplateError>;
25
26    /// Resolves this configuration-relative path to either an absolute path or
27    /// something appropriate to execute from `PATH`.
28    ///
29    /// Values which don't look like a filesystem path (don't contain `/` or
30    /// `\`) will be returned as-is, and everything else will fall through to an
31    /// absolute path.
32    fn resolve_program(&self, gctx: &GlobalContext) -> PathBuf;
33}
34
35impl ConfigRelativePathResolveExt for ConfigRelativePath {
36    fn resolve_path(&self, gctx: &GlobalContext) -> PathBuf {
37        let value = self.as_value();
38        value.definition.root(gctx.cwd()).join(&value.val)
39    }
40
41    fn resolve_templated_path(
42        &self,
43        gctx: &GlobalContext,
44        replacements: impl IntoIterator<Item = (impl AsRef<str>, impl AsRef<str>)>,
45    ) -> Result<PathBuf, ResolveTemplateError> {
46        let path = self.as_value();
47        let mut value = path.val.clone();
48
49        for (from, to) in replacements {
50            value = value.replace(from.as_ref(), to.as_ref());
51        }
52
53        // Check for expected variables
54        let re = Regex::new(r"\{(.*)\}").unwrap();
55        if let Some(caps) = re.captures(&value) {
56            return Err(ResolveTemplateError::UnexpectedVariable {
57                variable: caps[1].to_string(),
58                raw_template: path.val.clone(),
59            });
60        };
61
62        if value.contains("{") {
63            return Err(ResolveTemplateError::UnexpectedBracket {
64                bracket_type: BracketType::Opening,
65                raw_template: path.val.clone(),
66            });
67        }
68
69        if value.contains("}") {
70            return Err(ResolveTemplateError::UnexpectedBracket {
71                bracket_type: BracketType::Closing,
72                raw_template: path.val.clone(),
73            });
74        }
75
76        Ok(path.definition.root(gctx.cwd()).join(&value))
77    }
78
79    fn resolve_program(&self, gctx: &GlobalContext) -> PathBuf {
80        let value = self.as_value();
81        gctx.string_to_path(&value.val, &value.definition)
82    }
83}
84
85#[derive(Debug)]
86pub enum ResolveTemplateError {
87    UnexpectedVariable {
88        variable: String,
89        raw_template: String,
90    },
91    UnexpectedBracket {
92        bracket_type: BracketType,
93        raw_template: String,
94    },
95}
96
97#[derive(Debug)]
98pub enum BracketType {
99    Opening,
100    Closing,
101}