Skip to main content

artifactize_core/scope/
argument.rs

1//! Validated declared argv references and their exact authored string form.
2
3use super::{ScopeError, instruction, logical_path};
4use serde::Serialize;
5
6/// An Artifact root has no suffix; non-root suffixes are validated logical paths.
7#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
8pub enum LogicalTarget {
9    Root,
10    Suffix(LogicalSuffix),
11}
12
13/// A nonempty relative logical path. Its private storage cannot bypass validation.
14#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
15pub struct LogicalSuffix(String);
16
17impl std::str::FromStr for LogicalSuffix {
18    type Err = ScopeError;
19    fn from_str(path: &str) -> Result<Self, Self::Err> {
20        logical_path(path)?;
21        if path.is_empty() {
22            return Err(ScopeError(
23                "Artifact argument suffix must be nonempty.".into(),
24            ));
25        }
26        Ok(Self(path.to_owned()))
27    }
28}
29
30impl std::str::FromStr for LogicalTarget {
31    type Err = ScopeError;
32    fn from_str(path: &str) -> Result<Self, Self::Err> {
33        if path.is_empty() {
34            Ok(Self::Root)
35        } else {
36            path.parse().map(Self::Suffix)
37        }
38    }
39}
40
41impl std::ops::Deref for LogicalTarget {
42    type Target = str;
43    fn deref(&self) -> &str {
44        match self {
45            Self::Root => "",
46            Self::Suffix(path) => &path.0,
47        }
48    }
49}
50
51impl LogicalTarget {
52    pub fn as_str(&self) -> &str {
53        self
54    }
55}
56
57impl AsRef<std::path::Path> for LogicalTarget {
58    fn as_ref(&self) -> &std::path::Path {
59        std::path::Path::new(self.as_str())
60    }
61}
62
63impl std::fmt::Display for LogicalTarget {
64    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
65        formatter.write_str(self)
66    }
67}
68
69/// A declared argument, parsed once when its declaration loads: either a plain literal, or a
70/// `{name}[/path]` / `--flag={name}[/path]` Artifact reference. Parsing here only checks shape
71/// (a single well-formed reference, a valid path suffix); whether `name` names a real Artifact
72/// is a separate, config-wide check ([`reference_target`]) run once every declaration is loaded.
73/// [`std::fmt::Display`] reconstructs the exact original text, so round-tripping through the
74/// saved `Vec<String>` forms (`StoredProfile`, Views) changes no byte and no reuse key.
75#[derive(Debug, Clone, PartialEq, Eq)]
76pub enum Argument {
77    Literal(String),
78    Reference {
79        prefix: String,
80        name: crate::config::ReferenceName,
81        path: LogicalTarget,
82    },
83}
84
85impl std::str::FromStr for Argument {
86    type Err = ScopeError;
87    fn from_str(argument: &str) -> Result<Self, Self::Err> {
88        let references = instruction::references(argument);
89        let Some(reference) = references.first() else {
90            return Ok(Self::Literal(argument.to_owned()));
91        };
92        let prefix = &argument[..reference.start];
93        let flag = prefix
94            .strip_prefix("--")
95            .and_then(|flag| flag.strip_suffix('='))
96            .is_some_and(|flag| {
97                !flag.is_empty()
98                    && flag
99                        .bytes()
100                        .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_'))
101            });
102        if references.len() != 1 || (!prefix.is_empty() && !flag) {
103            return Err(ScopeError(
104                "Artifact arguments must be {name}[/path] or --flag={name}[/path].".into(),
105            ));
106        }
107        let suffix = &argument[reference.end..];
108        let path = if suffix.is_empty() {
109            ""
110        } else {
111            suffix
112                .strip_prefix('/')
113                .filter(|path| !path.is_empty())
114                .ok_or_else(|| {
115                    ScopeError("Artifact argument suffix must be a nonempty /path.".into())
116                })?
117        };
118        logical_path(path)?;
119        Ok(Self::Reference {
120            prefix: prefix.to_owned(),
121            name: reference.name.clone(),
122            path: path.parse()?,
123        })
124    }
125}
126
127impl std::fmt::Display for Argument {
128    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
129        match self {
130            Self::Literal(text) => f.write_str(text),
131            Self::Reference { prefix, name, path } => {
132                write!(f, "{prefix}{{{name}}}")?;
133                if !path.is_empty() {
134                    write!(f, "/{path}")?;
135                }
136                Ok(())
137            }
138        }
139    }
140}
141
142impl TryFrom<String> for Argument {
143    type Error = ScopeError;
144    fn try_from(value: String) -> Result<Self, Self::Error> {
145        value.parse()
146    }
147}
148
149impl From<Argument> for String {
150    fn from(argument: Argument) -> Self {
151        argument.to_string()
152    }
153}
154
155impl Serialize for Argument {
156    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
157        serializer.serialize_str(&self.to_string())
158    }
159}
160
161impl<'de> serde::Deserialize<'de> for Argument {
162    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
163        use serde::de::Error;
164        String::deserialize(deserializer)?
165            .parse()
166            .map_err(|failure: ScopeError| D::Error::custom(failure.0))
167    }
168}
169
170/// For fixtures: a trusted literal string, as declarations and test tables already spell it.
171impl From<&str> for Argument {
172    fn from(value: &str) -> Self {
173        value.parse().expect("a valid declared argument")
174    }
175}
176
177/// Equal iff `other`, spelled as a declared argument, is the same literal or reference: not a
178/// mere prefix/suffix match, and never panics on a malformed `other` (it is just unequal).
179impl PartialEq<str> for Argument {
180    fn eq(&self, other: &str) -> bool {
181        other.parse::<Self>().is_ok_and(|parsed| *self == parsed)
182    }
183}
184impl PartialEq<&str> for Argument {
185    fn eq(&self, other: &&str) -> bool {
186        self == *other
187    }
188}
189impl PartialEq<Argument> for str {
190    fn eq(&self, other: &Argument) -> bool {
191        other == self
192    }
193}
194impl PartialEq<Argument> for String {
195    fn eq(&self, other: &Argument) -> bool {
196        other == self.as_str()
197    }
198}
199impl PartialEq<String> for Argument {
200    fn eq(&self, other: &String) -> bool {
201        self == other.as_str()
202    }
203}
204
205#[cfg(test)]
206mod tests {
207    use super::*;
208
209    #[test]
210    fn reference_suffix_boundary_preserves_root_and_rejects_unsafe_paths() {
211        for text in [
212            "{owner}",
213            "{owner}/folder/file",
214            "--input={owner}/folder/file",
215        ] {
216            let argument: Argument = serde_json::from_value(serde_json::json!(text)).unwrap();
217            assert_eq!(
218                serde_json::to_value(argument).unwrap(),
219                serde_json::json!(text)
220            );
221        }
222        let root: LogicalTarget = "".parse().unwrap();
223        assert_eq!(root, LogicalTarget::Root);
224        for invalid in ["", ".", "../outside", "a//b", "a/../b", "a\\b", "a\0b"] {
225            assert!(invalid.parse::<LogicalSuffix>().is_err(), "{invalid:?}");
226        }
227        for invalid in [
228            "{owner}/",
229            "{owner}/../outside",
230            "{owner}/a//b",
231            "{owner}/.",
232        ] {
233            assert!(serde_json::from_value::<Argument>(serde_json::json!(invalid)).is_err());
234        }
235    }
236}