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