Skip to main content

gitfox_client/
repo.rs

1//! Repository endpoints.
2//!
3//! Verified against the GitFox API v1.3.0 OpenAPI document (`GET /openapi.yaml`
4//! on any instance, no authentication required):
5//!
6//! | Operation | Endpoint |
7//! |---|---|
8//! | list repositories (all spaces) | `GET /api/v1/repos` |
9//! | list repositories in a space   | `GET /api/v1/spaces/{space_ref}/repos` |
10//! | get a repository               | `GET /api/v1/repos/{repo_ref}` |
11//! | create                         | `POST /api/v1/repos` (`fork_id` makes a fork) |
12//! | delete (soft)                  | `DELETE /api/v1/repos/{repo_ref}` |
13//! | edit description               | `PATCH /api/v1/repos/{repo_ref}` |
14//! | change visibility              | `POST …/public-access` |
15//! | change default branch          | `POST …/default-branch` |
16//! | rename                         | `POST …/move` |
17//! | sync a mirror or fork          | `POST …/sync` |
18//! | read a path                    | `GET …/content/{path}` |
19//! | rebase a branch                | `POST …/rebase` |
20//! | commit diff                    | `GET …/commits/{commit_sha}/diff` |
21//! | gitignore / license templates  | `GET /api/v1/resources/gitignore`, `…/license` |
22//!
23//! `{repo_ref}` is [`crate::RepoRef::encoded`] (`ai%2Fbackend`), or a numeric
24//! repository id — which is how a fork's parent is looked up.
25//!
26//! Note the two response shapes: `GET /repos/{repo_ref}` and the space-scoped
27//! listing carry `is_public`, the instance-wide `GET /repos` does not. See
28//! [`Repository`] for how that difference is represented.
29
30use serde_json::json;
31
32use crate::client::{GitFoxClient, Method, Query};
33use crate::error::Result;
34use crate::models::{Content, CreateRepository, LicenseTemplate, RepoRef, Repository};
35
36pub struct ReposApi<'a> {
37    client: &'a GitFoxClient,
38}
39
40impl<'a> ReposApi<'a> {
41    pub(crate) fn new(client: &'a GitFoxClient) -> Self {
42        Self { client }
43    }
44
45    /// `GET /api/v1/repos/{repo_ref}`
46    pub async fn get(&self, repo: &RepoRef) -> Result<Repository> {
47        self.client
48            .get_json(&format!("/api/v1/repos/{}", repo.encoded()))
49            .await
50    }
51
52    /// `GET /api/v1/repos/{id}` — the same endpoint, addressed by id.
53    pub async fn get_by_id(&self, id: i64) -> Result<Repository> {
54        self.client.get_json(&format!("/api/v1/repos/{id}")).await
55    }
56
57    /// `GET /api/v1/repos` — spans every space the caller can see.
58    ///
59    /// Answers with the narrower shape: [`Repository::is_public`] is `None`
60    /// here. Use [`Self::list_in_space`] when visibility matters.
61    pub async fn list(
62        &self,
63        query: Option<&str>,
64        sort: RepoSort,
65        page: u32,
66        limit: u32,
67    ) -> Result<Vec<Repository>> {
68        self.client
69            .get_json(&list_query(query, sort, page, limit).apply("/api/v1/repos"))
70            .await
71    }
72
73    /// `GET /api/v1/spaces/{space_ref}/repos` — includes visibility.
74    pub async fn list_in_space(
75        &self,
76        space: &str,
77        query: Option<&str>,
78        sort: RepoSort,
79        page: u32,
80        limit: u32,
81    ) -> Result<Vec<Repository>> {
82        let space = space.replace('/', "%2F");
83        self.client
84            .get_json(
85                &list_query(query, sort, page, limit)
86                    .apply(&format!("/api/v1/spaces/{space}/repos")),
87            )
88            .await
89    }
90
91    /// `POST /api/v1/repos`
92    pub async fn create(&self, input: &CreateRepository) -> Result<Repository> {
93        let body = serde_json::to_value(input).map_err(|e| crate::Error::Decode(e.to_string()))?;
94        self.client
95            .request(Method::POST, "/api/v1/repos", Some(&body), &[])
96            .await?
97            .deserialize()
98    }
99
100    /// `DELETE /api/v1/repos/{repo_ref}` — a soft delete GitFox can restore.
101    /// Returns when it was deleted, which is what a restore needs.
102    pub async fn delete(&self, repo: &RepoRef) -> Result<Option<i64>> {
103        let response = self
104            .client
105            .request(
106                Method::DELETE,
107                &format!("/api/v1/repos/{}", repo.encoded()),
108                None,
109                &[],
110            )
111            .await?;
112        Ok(response
113            .json
114            .as_ref()
115            .and_then(|v| v.get("deleted_at"))
116            .and_then(serde_json::Value::as_i64))
117    }
118
119    /// `PATCH /api/v1/repos/{repo_ref}` — the description is all it edits.
120    pub async fn update_description(
121        &self,
122        repo: &RepoRef,
123        description: &str,
124    ) -> Result<Repository> {
125        self.post_like(
126            Method::PATCH,
127            &format!("/api/v1/repos/{}", repo.encoded()),
128            json!({ "description": description }),
129        )
130        .await
131    }
132
133    /// `POST …/public-access`
134    pub async fn set_public(&self, repo: &RepoRef, is_public: bool) -> Result<Repository> {
135        self.post_like(
136            Method::POST,
137            &format!("/api/v1/repos/{}/public-access", repo.encoded()),
138            json!({ "is_public": is_public }),
139        )
140        .await
141    }
142
143    /// `POST …/default-branch`
144    pub async fn set_default_branch(&self, repo: &RepoRef, branch: &str) -> Result<Repository> {
145        self.post_like(
146            Method::POST,
147            &format!("/api/v1/repos/{}/default-branch", repo.encoded()),
148            json!({ "name": branch }),
149        )
150        .await
151    }
152
153    /// `POST …/move` with a new identifier: renames within the same space.
154    pub async fn rename(&self, repo: &RepoRef, identifier: &str) -> Result<Repository> {
155        self.post_like(
156            Method::POST,
157            &format!("/api/v1/repos/{}/move", repo.encoded()),
158            json!({ "identifier": identifier }),
159        )
160        .await
161    }
162
163    /// `POST …/sync` — pull the upstream of a mirror or a fork.
164    pub async fn sync(&self, repo: &RepoRef) -> Result<()> {
165        self.client
166            .request(
167                Method::POST,
168                &format!("/api/v1/repos/{}/sync", repo.encoded()),
169                None,
170                &[],
171            )
172            .await
173            .map(|_| ())
174    }
175
176    /// `GET …/content/{path}` at `git_ref`, or the default branch.
177    pub async fn content(
178        &self,
179        repo: &RepoRef,
180        path: &str,
181        git_ref: Option<&str>,
182    ) -> Result<Content> {
183        let mut q = Query::new();
184        q.push_opt("git_ref", git_ref)
185            .push("include_commit", "false");
186        let path = path.trim_matches('/');
187        self.client
188            .get_json(&q.apply(&format!(
189                "/api/v1/repos/{}/content/{}",
190                repo.encoded(),
191                encode_path(path)
192            )))
193            .await
194    }
195
196    /// `POST …/rebase` — rebase `head_branch` onto `base_branch`.
197    pub async fn rebase(
198        &self,
199        repo: &RepoRef,
200        base_branch: &str,
201        head_branch: &str,
202        head_commit_sha: Option<&str>,
203    ) -> Result<serde_json::Value> {
204        let mut body = json!({ "base_branch": base_branch, "head_branch": head_branch });
205        if let Some(sha) = head_commit_sha {
206            body["head_commit_sha"] = json!(sha);
207        }
208        Ok(self
209            .client
210            .request(
211                Method::POST,
212                &format!("/api/v1/repos/{}/rebase", repo.encoded()),
213                Some(&body),
214                &[],
215            )
216            .await?
217            .json_or_null())
218    }
219
220    /// `GET …/commits/{commit_sha}/diff` — a raw unified diff.
221    pub async fn commit_diff(&self, repo: &RepoRef, sha: &str) -> Result<String> {
222        Ok(self
223            .client
224            .request(
225                Method::GET,
226                &format!("/api/v1/repos/{}/commits/{sha}/diff", repo.encoded()),
227                None,
228                &[("Accept".to_string(), "text/plain".to_string())],
229            )
230            .await?
231            .text)
232    }
233
234    /// `GET /api/v1/resources/gitignore` — template names only.
235    pub async fn gitignore_templates(&self) -> Result<Vec<String>> {
236        self.client.get_json("/api/v1/resources/gitignore").await
237    }
238
239    /// `GET /api/v1/resources/license`
240    pub async fn license_templates(&self) -> Result<Vec<LicenseTemplate>> {
241        self.client.get_json("/api/v1/resources/license").await
242    }
243
244    async fn post_like(
245        &self,
246        method: Method,
247        path: &str,
248        body: serde_json::Value,
249    ) -> Result<Repository> {
250        self.client
251            .request(method, path, Some(&body), &[])
252            .await?
253            .deserialize()
254    }
255}
256
257fn list_query(query: Option<&str>, sort: RepoSort, page: u32, limit: u32) -> Query {
258    let mut q = Query::new();
259    q.push_opt("query", query)
260        .push("sort", sort.as_str())
261        .push("order", sort.order())
262        .push("page", page)
263        .push("limit", limit);
264    q
265}
266
267/// Percent-encode each segment of a repository path, keeping the slashes that
268/// separate them.
269pub fn encode_path(path: &str) -> String {
270    path.split('/')
271        .map(|segment| {
272            let mut out = String::with_capacity(segment.len());
273            for byte in segment.bytes() {
274                match byte {
275                    b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
276                        out.push(byte as char)
277                    }
278                    other => out.push_str(&format!("%{other:02X}")),
279                }
280            }
281            out
282        })
283        .collect::<Vec<_>>()
284        .join("/")
285}
286
287/// How a repository listing is ordered. GitFox sorts by `identifier`, `created`
288/// or `updated`; name goes ascending because an alphabetical list read backwards
289/// helps nobody, while the other two mean "most recent first".
290#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
291pub enum RepoSort {
292    #[default]
293    Name,
294    Created,
295    Updated,
296}
297
298impl RepoSort {
299    pub fn as_str(self) -> &'static str {
300        match self {
301            Self::Name => "identifier",
302            Self::Created => "created",
303            Self::Updated => "updated",
304        }
305    }
306
307    pub fn order(self) -> &'static str {
308        match self {
309            Self::Name => "asc",
310            Self::Created | Self::Updated => "desc",
311        }
312    }
313}
314
315#[cfg(test)]
316mod tests {
317    use super::*;
318
319    #[test]
320    fn listings_are_ordered_the_way_each_sort_key_is_read() {
321        assert_eq!(RepoSort::Name.as_str(), "identifier");
322        assert_eq!(RepoSort::Name.order(), "asc");
323        assert_eq!(RepoSort::Updated.as_str(), "updated");
324        assert_eq!(RepoSort::Updated.order(), "desc");
325    }
326
327    #[test]
328    fn the_space_listing_encodes_a_nested_space_as_one_segment() {
329        let q = list_query(None, RepoSort::Name, 1, 30);
330        assert_eq!(
331            q.apply("/api/v1/spaces/org%2Fteam/repos"),
332            "/api/v1/spaces/org%2Fteam/repos?sort=identifier&order=asc&page=1&limit=30"
333        );
334    }
335
336    #[test]
337    fn a_search_term_is_escaped_not_concatenated() {
338        let q = list_query(Some("back end"), RepoSort::Name, 1, 30);
339        assert!(q.encode().contains("query=back+end"), "{}", q.encode());
340    }
341
342    #[test]
343    fn a_content_path_keeps_its_slashes_and_escapes_the_rest() {
344        assert_eq!(encode_path("src/main.rs"), "src/main.rs");
345        assert_eq!(encode_path("docs/a b#c.md"), "docs/a%20b%23c.md");
346        assert_eq!(encode_path(""), "");
347    }
348}