Skip to main content

mars_agents/
types.rs

1use serde::{Deserialize, Serialize};
2use std::borrow::Borrow;
3use std::fmt;
4use std::hash::{Hash, Hasher};
5use std::ops::Deref;
6use std::path::{Path, PathBuf};
7
8macro_rules! string_newtype {
9    ($(#[$meta:meta])* $name:ident) => {
10        $(#[$meta])*
11        #[derive(
12            Serialize, Deserialize, Hash, Eq, PartialEq, Clone, Debug, Ord, PartialOrd,
13        )]
14        #[serde(transparent)]
15        pub struct $name(String);
16
17        impl $name {
18            pub fn new(value: impl Into<String>) -> Self {
19                Self(value.into())
20            }
21
22            pub fn as_str(&self) -> &str {
23                &self.0
24            }
25
26            pub fn into_inner(self) -> String {
27                self.0
28            }
29        }
30
31        impl From<String> for $name {
32            fn from(value: String) -> Self {
33                Self(value)
34            }
35        }
36
37        impl From<&str> for $name {
38            fn from(value: &str) -> Self {
39                Self(value.to_owned())
40            }
41        }
42
43        impl AsRef<str> for $name {
44            fn as_ref(&self) -> &str {
45                &self.0
46            }
47        }
48
49        impl Borrow<str> for $name {
50            fn borrow(&self) -> &str {
51                &self.0
52            }
53        }
54
55        impl Deref for $name {
56            type Target = str;
57
58            fn deref(&self) -> &Self::Target {
59                &self.0
60            }
61        }
62
63        impl From<$name> for String {
64            fn from(value: $name) -> Self {
65                value.0
66            }
67        }
68
69        impl fmt::Display for $name {
70            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
71                f.write_str(&self.0)
72            }
73        }
74
75        impl PartialEq<str> for $name {
76            fn eq(&self, other: &str) -> bool {
77                self.0 == other
78            }
79        }
80
81        impl PartialEq<&str> for $name {
82            fn eq(&self, other: &&str) -> bool {
83                self.0 == *other
84            }
85        }
86
87        impl PartialEq<String> for $name {
88            fn eq(&self, other: &String) -> bool {
89                self.0 == *other
90            }
91        }
92
93        impl PartialEq<$name> for String {
94            fn eq(&self, other: &$name) -> bool {
95                *self == other.0
96            }
97        }
98    };
99}
100
101string_newtype!(SourceName);
102string_newtype!(ItemName);
103string_newtype!(SourceUrl);
104string_newtype!(CommitHash);
105string_newtype!(ContentHash);
106
107/// Relative path under the install root (`.agents/` / project root).
108#[derive(Eq, PartialEq, Clone, Debug, Ord, PartialOrd)]
109pub struct DestPath(PathBuf);
110
111impl DestPath {
112    pub fn new(value: impl Into<PathBuf>) -> Self {
113        Self(value.into())
114    }
115
116    pub fn as_path(&self) -> &Path {
117        &self.0
118    }
119
120    pub fn into_inner(self) -> PathBuf {
121        self.0
122    }
123
124    /// Resolve this relative path under a root path.
125    pub fn resolve(&self, root: &Path) -> PathBuf {
126        root.join(&self.0)
127    }
128}
129
130impl From<PathBuf> for DestPath {
131    fn from(value: PathBuf) -> Self {
132        Self(value)
133    }
134}
135
136impl From<&Path> for DestPath {
137    fn from(value: &Path) -> Self {
138        Self(value.to_path_buf())
139    }
140}
141
142impl From<&str> for DestPath {
143    fn from(value: &str) -> Self {
144        Self(PathBuf::from(value))
145    }
146}
147
148impl From<String> for DestPath {
149    fn from(value: String) -> Self {
150        Self(PathBuf::from(value))
151    }
152}
153
154impl AsRef<Path> for DestPath {
155    fn as_ref(&self) -> &Path {
156        &self.0
157    }
158}
159
160impl Borrow<Path> for DestPath {
161    fn borrow(&self) -> &Path {
162        &self.0
163    }
164}
165
166impl Borrow<str> for DestPath {
167    fn borrow(&self) -> &str {
168        self.0.to_str().expect("DestPath must be valid UTF-8")
169    }
170}
171
172impl Hash for DestPath {
173    fn hash<H: Hasher>(&self, state: &mut H) {
174        self.0.to_string_lossy().hash(state);
175    }
176}
177
178impl Deref for DestPath {
179    type Target = Path;
180
181    fn deref(&self) -> &Self::Target {
182        &self.0
183    }
184}
185
186impl fmt::Display for DestPath {
187    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
188        write!(f, "{}", self.0.display())
189    }
190}
191
192impl Serialize for DestPath {
193    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
194        self.0.to_string_lossy().serialize(serializer)
195    }
196}
197
198impl<'de> Deserialize<'de> for DestPath {
199    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
200        String::deserialize(deserializer).map(|s| Self(PathBuf::from(s)))
201    }
202}
203
204/// Stable source identity used for resolver deduplication.
205#[derive(Hash, Eq, PartialEq, Clone, Debug, Ord, PartialOrd)]
206pub enum SourceId {
207    Git { url: SourceUrl },
208    Path { canonical: PathBuf },
209}
210
211impl SourceId {
212    pub fn git(url: SourceUrl) -> Self {
213        Self::Git { url }
214    }
215
216    pub fn path(base: &Path, relative_or_absolute: &Path) -> std::io::Result<Self> {
217        let candidate = if relative_or_absolute.is_absolute() {
218            relative_or_absolute.to_path_buf()
219        } else {
220            base.join(relative_or_absolute)
221        };
222        let canonical = candidate.canonicalize()?;
223        Ok(Self::Path { canonical })
224    }
225}
226
227impl fmt::Display for SourceId {
228    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
229        match self {
230            Self::Git { url } => write!(f, "git:{url}"),
231            Self::Path { canonical } => write!(f, "path:{}", canonical.display()),
232        }
233    }
234}
235
236#[derive(Debug, Clone, PartialEq, Eq)]
237pub struct RenameRule {
238    pub from: ItemName,
239    pub to: ItemName,
240}
241
242/// Ordered rename rules, serialized as TOML inline table/map for compatibility.
243#[derive(Debug, Clone, Default, PartialEq, Eq)]
244pub struct RenameMap(Vec<RenameRule>);
245
246impl RenameMap {
247    pub fn new() -> Self {
248        Self(Vec::new())
249    }
250
251    pub fn insert(&mut self, from: ItemName, to: ItemName) {
252        if let Some(existing) = self.0.iter_mut().find(|r| r.from == from) {
253            existing.to = to;
254            return;
255        }
256        self.0.push(RenameRule { from, to });
257    }
258
259    pub fn push(&mut self, rule: RenameRule) {
260        self.insert(rule.from, rule.to);
261    }
262
263    pub fn get(&self, from: &str) -> Option<&ItemName> {
264        self.0.iter().find(|r| r.from == from).map(|r| &r.to)
265    }
266
267    pub fn iter(&self) -> impl Iterator<Item = &RenameRule> {
268        self.0.iter()
269    }
270
271    pub fn is_empty(&self) -> bool {
272        self.0.is_empty()
273    }
274
275    pub fn len(&self) -> usize {
276        self.0.len()
277    }
278}
279
280impl Serialize for RenameMap {
281    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
282        use serde::ser::SerializeMap;
283        let mut map = serializer.serialize_map(Some(self.0.len()))?;
284        for rule in &self.0 {
285            map.serialize_entry(rule.from.as_str(), rule.to.as_str())?;
286        }
287        map.end()
288    }
289}
290
291impl<'de> Deserialize<'de> for RenameMap {
292    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
293        let map = indexmap::IndexMap::<String, String>::deserialize(deserializer)?;
294        Ok(Self(
295            map.into_iter()
296                .map(|(from, to)| RenameRule {
297                    from: ItemName::from(from),
298                    to: ItemName::from(to),
299                })
300                .collect(),
301        ))
302    }
303}
304
305#[cfg(test)]
306mod tests {
307    use super::*;
308    use serde::{Deserialize, Serialize};
309
310    #[derive(Debug, Serialize, Deserialize, PartialEq)]
311    struct Wrapper<T> {
312        value: T,
313    }
314
315    #[test]
316    fn dest_path_roundtrip() {
317        let v = Wrapper {
318            value: DestPath::from("agents/coder.md"),
319        };
320        let s = toml::to_string(&v).unwrap();
321        let out: Wrapper<DestPath> = toml::from_str(&s).unwrap();
322        assert_eq!(v, out);
323    }
324
325    #[test]
326    fn rename_map_toml_roundtrip_compat() {
327        #[derive(Debug, Serialize, Deserialize, PartialEq, Eq)]
328        struct RenameWrapper {
329            rename: RenameMap,
330        }
331
332        let input = r#"rename = { "coder" = "cool-coder" }"#;
333        let parsed: RenameWrapper = toml::from_str(input).unwrap();
334        assert_eq!(
335            parsed.rename.get("coder").map(|v| v.as_str()),
336            Some("cool-coder")
337        );
338
339        let serialized = toml::to_string(&parsed).unwrap();
340        let reparsed: RenameWrapper = toml::from_str(&serialized).unwrap();
341        assert_eq!(parsed, reparsed);
342    }
343}