Skip to main content

gitfox_client/models/
repository.rs

1use serde::{Deserialize, Serialize};
2
3/// A repository.
4///
5/// This is the CLI's own model, not the raw API DTO: the serde attributes are
6/// the translation layer, so an upstream rename is absorbed with an `alias`
7/// instead of breaking the JSON schema agents depend on.
8///
9/// GitFox returns two shapes here. `GET /repos/{repo_ref}` and
10/// `GET /spaces/{space_ref}/repos` answer with `RepoRepositoryOutput`, which
11/// carries `is_public` and `importing`; the instance-wide `GET /repos` answers
12/// with `TypesRepository`, which does not. Both decode into this one struct,
13/// and the fields the narrower shape lacks stay `None` — a repository whose
14/// visibility is simply unknown, rather than one wrongly reported as private.
15#[derive(Debug, Clone, Default, Serialize, Deserialize)]
16pub struct Repository {
17    #[serde(default)]
18    pub id: Option<i64>,
19    /// The repository name on its own, e.g. `backend`.
20    #[serde(default)]
21    pub identifier: Option<String>,
22    /// The full space path, e.g. `ai/backend`.
23    #[serde(default)]
24    pub path: Option<String>,
25    #[serde(default)]
26    pub description: Option<String>,
27    #[serde(default)]
28    pub default_branch: Option<String>,
29    /// `None` when the endpoint that produced this does not report visibility.
30    #[serde(default)]
31    pub is_public: Option<bool>,
32    #[serde(default)]
33    pub importing: Option<bool>,
34    #[serde(default)]
35    pub git_url: Option<String>,
36    #[serde(default)]
37    pub git_ssh_url: Option<String>,
38    #[serde(default)]
39    pub is_empty: Option<bool>,
40    #[serde(default)]
41    pub num_open_pulls: Option<i64>,
42    #[serde(default)]
43    pub num_pulls: Option<i64>,
44    #[serde(default)]
45    pub num_forks: Option<i64>,
46    /// Size in KiB, as GitFox reports it.
47    #[serde(default)]
48    pub size: Option<i64>,
49    #[serde(default)]
50    pub created: Option<i64>,
51    #[serde(default)]
52    pub updated: Option<i64>,
53    /// The repository this one was forked from; `0` or absent for a source
54    /// repository.
55    #[serde(default)]
56    pub fork_id: Option<i64>,
57    /// The id of the space the repository lives in.
58    #[serde(default)]
59    pub parent_id: Option<i64>,
60    #[serde(default)]
61    pub mirror: Option<bool>,
62    #[serde(default)]
63    pub num_closed_pulls: Option<i64>,
64    #[serde(default)]
65    pub num_merged_pulls: Option<i64>,
66}
67
68/// The body of `POST /api/v1/repos`.
69#[derive(Debug, Clone, Default, Serialize)]
70pub struct CreateRepository {
71    pub identifier: String,
72    /// The space to create it in.
73    pub parent_ref: String,
74    #[serde(skip_serializing_if = "Option::is_none")]
75    pub description: Option<String>,
76    #[serde(skip_serializing_if = "Option::is_none")]
77    pub default_branch: Option<String>,
78    pub is_public: bool,
79    #[serde(skip_serializing_if = "std::ops::Not::not")]
80    pub readme: bool,
81    #[serde(skip_serializing_if = "Option::is_none")]
82    pub license: Option<String>,
83    #[serde(skip_serializing_if = "Option::is_none")]
84    pub git_ignore: Option<String>,
85    /// Makes the new repository a fork of the repository with this id.
86    #[serde(skip_serializing_if = "Option::is_none")]
87    pub fork_id: Option<i64>,
88}
89
90impl Repository {
91    /// Whether this repository is a fork of another.
92    pub fn is_fork(&self) -> bool {
93        self.fork_id.is_some_and(|id| id > 0)
94    }
95
96    /// `ai/backend` — the reference a user would type back into `-R`.
97    pub fn reference(&self) -> String {
98        self.path
99            .clone()
100            .or_else(|| self.identifier.clone())
101            .unwrap_or_default()
102    }
103
104    /// `public`, `private`, or `None` when the endpoint did not say.
105    pub fn visibility(&self) -> Option<&'static str> {
106        self.is_public.map(|p| if p { "public" } else { "private" })
107    }
108
109    /// The URL `git clone` should be given.
110    pub fn clone_url(&self, ssh: bool) -> Option<&str> {
111        let (first, second) = if ssh {
112            (&self.git_ssh_url, &self.git_url)
113        } else {
114            (&self.git_url, &self.git_ssh_url)
115        };
116        first
117            .as_deref()
118            .filter(|u| !u.is_empty())
119            .or_else(|| second.as_deref().filter(|u| !u.is_empty()))
120    }
121}
122
123#[cfg(test)]
124mod tests {
125    use super::*;
126    use serde_json::json;
127
128    #[test]
129    fn the_narrow_list_shape_decodes_with_visibility_unknown() {
130        // `GET /repos` answers with TypesRepository, which has no is_public.
131        let repo: Repository = serde_json::from_value(json!({
132            "identifier": "backend", "path": "ai/backend", "default_branch": "main"
133        }))
134        .unwrap();
135        assert_eq!(repo.reference(), "ai/backend");
136        // Unknown, not "private" — the difference matters in a listing.
137        assert_eq!(repo.visibility(), None);
138    }
139
140    #[test]
141    fn the_wide_shape_reports_visibility() {
142        let public: Repository =
143            serde_json::from_value(json!({ "identifier": "x", "is_public": true })).unwrap();
144        assert_eq!(public.visibility(), Some("public"));
145        let private: Repository =
146            serde_json::from_value(json!({ "identifier": "x", "is_public": false })).unwrap();
147        assert_eq!(private.visibility(), Some("private"));
148    }
149
150    #[test]
151    fn clone_url_honours_the_requested_protocol_and_falls_back() {
152        let both = Repository {
153            git_url: Some("http://h:3000/git/ai/backend.git".into()),
154            git_ssh_url: Some("git@h:ai/backend.git".into()),
155            ..Default::default()
156        };
157        assert_eq!(
158            both.clone_url(false),
159            Some("http://h:3000/git/ai/backend.git")
160        );
161        assert_eq!(both.clone_url(true), Some("git@h:ai/backend.git"));
162
163        // An instance with SSH disabled still clones over HTTP.
164        let http_only = Repository {
165            git_url: Some("http://h:3000/git/ai/backend.git".into()),
166            git_ssh_url: Some(String::new()),
167            ..Default::default()
168        };
169        assert_eq!(
170            http_only.clone_url(true),
171            Some("http://h:3000/git/ai/backend.git")
172        );
173        assert_eq!(Repository::default().clone_url(false), None);
174    }
175
176    #[test]
177    fn reference_falls_back_to_the_identifier() {
178        let repo = Repository {
179            identifier: Some("backend".into()),
180            ..Default::default()
181        };
182        assert_eq!(repo.reference(), "backend");
183    }
184}