1use 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 pub async fn gitignore_templates(&self) -> Result<Vec<String>> {
236 self.client.get_json("/api/v1/resources/gitignore").await
237 }
238
239 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
267pub 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#[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}