Skip to main content

gitfox_client/models/
repo_ref.rs

1use std::fmt;
2use std::str::FromStr;
3
4use crate::error::{Error, Result};
5
6/// A reference to a repository, e.g. `ai/backend`.
7///
8/// GitFox spaces can be nested (`org/team/repo`), so everything before the last
9/// segment is treated as the space path.
10#[derive(Debug, Clone, PartialEq, Eq, Hash)]
11pub struct RepoRef {
12    space: String,
13    name: String,
14}
15
16impl RepoRef {
17    pub fn parse(input: &str) -> Result<Self> {
18        let trimmed = input.trim().trim_matches('/');
19        let Some((space, name)) = trimmed.rsplit_once('/') else {
20            return Err(Error::InvalidUrl(format!(
21                "repository reference must be `space/name`, got `{input}`"
22            )));
23        };
24        if space.is_empty() || name.is_empty() || space.split('/').any(str::is_empty) {
25            return Err(Error::InvalidUrl(format!(
26                "repository reference must be `space/name`, got `{input}`"
27            )));
28        }
29        Ok(Self {
30            space: space.to_string(),
31            name: name.to_string(),
32        })
33    }
34
35    /// The space path (everything before the repository name).
36    pub fn space(&self) -> &str {
37        &self.space
38    }
39
40    /// The repository name (the last segment).
41    pub fn name(&self) -> &str {
42        &self.name
43    }
44
45    /// `space/name`, as a user would type it.
46    pub fn full(&self) -> String {
47        format!("{}/{}", self.space, self.name)
48    }
49
50    /// `space%2Fname`, as GitFox expects it inside a URL path segment.
51    pub fn encoded(&self) -> String {
52        self.full().replace('/', "%2F")
53    }
54}
55
56impl FromStr for RepoRef {
57    type Err = Error;
58
59    fn from_str(s: &str) -> Result<Self> {
60        Self::parse(s)
61    }
62}
63
64impl fmt::Display for RepoRef {
65    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
66        f.write_str(&self.full())
67    }
68}
69
70#[cfg(test)]
71mod tests {
72    use super::*;
73
74    #[test]
75    fn parses_simple_reference() {
76        let r = RepoRef::parse("ai/backend").unwrap();
77        assert_eq!(r.space(), "ai");
78        assert_eq!(r.name(), "backend");
79        assert_eq!(r.full(), "ai/backend");
80        assert_eq!(r.encoded(), "ai%2Fbackend");
81    }
82
83    #[test]
84    fn parses_nested_space() {
85        let r = RepoRef::parse("org/team/backend").unwrap();
86        assert_eq!(r.space(), "org/team");
87        assert_eq!(r.name(), "backend");
88        assert_eq!(r.encoded(), "org%2Fteam%2Fbackend");
89    }
90
91    #[test]
92    fn tolerates_surrounding_slashes_and_space() {
93        assert_eq!(
94            RepoRef::parse("  /ai/backend/ ").unwrap().full(),
95            "ai/backend"
96        );
97    }
98
99    #[test]
100    fn rejects_references_without_a_space() {
101        for bad in ["backend", "", "/", "ai//backend", "ai/"] {
102            assert!(
103                RepoRef::parse(bad).is_err(),
104                "expected `{bad}` to be rejected"
105            );
106        }
107    }
108}