artifactize_core/scope/
argument.rs1use super::{ScopeError, logical_path};
4use serde::{Deserialize, Serialize};
5
6#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
8pub enum LogicalTarget {
9 Root,
10 Suffix(LogicalSuffix),
11}
12
13#[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#[derive(Debug, Clone, PartialEq, Eq)]
91pub enum Argument {
92 Literal(String),
93 Reference {
94 prefix: String,
95 name: crate::config::ReferenceName,
96 path: LogicalTarget,
97 },
98}
99
100pub(crate) const PATH_SLOT: &str = "@{path ";
102
103impl Argument {
104 pub fn literal(&self) -> Option<&str> {
106 match self {
107 Self::Literal(text) => Some(text),
108 Self::Reference { .. } => None,
109 }
110 }
111}
112
113impl std::str::FromStr for Argument {
114 type Err = ScopeError;
115 fn from_str(argument: &str) -> Result<Self, Self::Err> {
116 let mut text = String::new();
117 let mut rest = argument;
118 let mut slot = None;
119 while let Some(at) = rest.find("@{").map(|index| {
120 if index > 0 && rest.as_bytes()[index - 1] == b'@' {
122 index - 1
123 } else {
124 index
125 }
126 }) {
127 text.push_str(&rest[..at]);
128 if rest[at..].starts_with("@@{") {
129 text.push_str("@{");
130 rest = &rest[at + 3..];
131 continue;
132 }
133 if slot.is_some() || !rest[at..].starts_with(PATH_SLOT) {
134 return Err(ScopeError(
135 "An argument holds one `@{path NAME[/sub]}` slot, or `@@{` for a literal `@{`."
136 .into(),
137 ));
138 }
139 let close = rest[at..]
140 .find('}')
141 .ok_or_else(|| ScopeError("This `@{path …}` slot has no closing `}`.".into()))?;
142 slot = Some((
143 text.clone(),
144 rest[at + PATH_SLOT.len()..at + close].trim().to_owned(),
145 ));
146 rest = &rest[at + close + 1..];
147 if !rest.is_empty() {
148 return Err(ScopeError(
149 "An argument's `@{path …}` slot ends it; write the path inside the slot."
150 .into(),
151 ));
152 }
153 }
154 text.push_str(rest);
155 let Some((prefix, target)) = slot else {
156 return Ok(Self::Literal(text));
157 };
158 let flag = prefix
159 .strip_prefix("--")
160 .and_then(|flag| flag.strip_suffix('='))
161 .is_some_and(|flag| {
162 !flag.is_empty()
163 && flag
164 .bytes()
165 .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_'))
166 });
167 if !prefix.is_empty() && !flag {
168 return Err(ScopeError(
169 "An Artifact argument is `@{path NAME[/sub]}` or `--flag=@{path NAME[/sub]}`."
170 .into(),
171 ));
172 }
173 let (name, path) = target.split_once('/').unwrap_or((&target, ""));
174 if target.contains('/') && path.is_empty() {
175 return Err(ScopeError(
176 "Artifact argument suffix must be a nonempty /path.".into(),
177 ));
178 }
179 logical_path(path)?;
180 Ok(Self::Reference {
181 prefix,
182 name: name
183 .parse()
184 .map_err(|_| ScopeError(format!("`@{{path {target}}}` names no Artifact.")))?,
185 path: path.parse()?,
186 })
187 }
188}
189
190impl std::fmt::Display for Argument {
191 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
192 match self {
193 Self::Literal(text) => f.write_str(&text.replace("@{", "@@{")),
194 Self::Reference { prefix, name, path } => {
195 write!(f, "{}{PATH_SLOT}{name}", prefix.replace("@{", "@@{"))?;
196 if !path.is_empty() {
197 write!(f, "/{path}")?;
198 }
199 f.write_str("}")
200 }
201 }
202 }
203}
204
205impl TryFrom<String> for Argument {
206 type Error = ScopeError;
207 fn try_from(value: String) -> Result<Self, Self::Error> {
208 value.parse()
209 }
210}
211
212impl From<Argument> for String {
213 fn from(argument: Argument) -> Self {
214 argument.to_string()
215 }
216}
217
218impl Serialize for Argument {
219 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
220 serializer.serialize_str(&self.to_string())
221 }
222}
223
224impl<'de> serde::Deserialize<'de> for Argument {
225 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
226 use serde::de::Error;
227 String::deserialize(deserializer)?
228 .parse()
229 .map_err(|failure: ScopeError| D::Error::custom(failure.0))
230 }
231}
232
233impl From<&str> for Argument {
235 fn from(value: &str) -> Self {
236 value.parse().expect("a valid declared argument")
237 }
238}
239
240impl PartialEq<str> for Argument {
243 fn eq(&self, other: &str) -> bool {
244 other.parse::<Self>().is_ok_and(|parsed| *self == parsed)
245 }
246}
247impl PartialEq<&str> for Argument {
248 fn eq(&self, other: &&str) -> bool {
249 self == *other
250 }
251}
252impl PartialEq<Argument> for str {
253 fn eq(&self, other: &Argument) -> bool {
254 other == self
255 }
256}
257impl PartialEq<Argument> for String {
258 fn eq(&self, other: &Argument) -> bool {
259 other == self.as_str()
260 }
261}
262impl PartialEq<String> for Argument {
263 fn eq(&self, other: &String) -> bool {
264 self == other.as_str()
265 }
266}
267
268#[cfg(test)]
269mod tests;