1use crate::client::{GitFoxClient, Query};
20use crate::error::Result;
21use crate::models::{RepoRef, Repository};
22
23pub struct ReposApi<'a> {
24 client: &'a GitFoxClient,
25}
26
27impl<'a> ReposApi<'a> {
28 pub(crate) fn new(client: &'a GitFoxClient) -> Self {
29 Self { client }
30 }
31
32 pub async fn get(&self, repo: &RepoRef) -> Result<Repository> {
34 self.client
35 .get_json(&format!("/api/v1/repos/{}", repo.encoded()))
36 .await
37 }
38
39 pub async fn list(
44 &self,
45 query: Option<&str>,
46 sort: RepoSort,
47 page: u32,
48 limit: u32,
49 ) -> Result<Vec<Repository>> {
50 self.client
51 .get_json(&list_query(query, sort, page, limit).apply("/api/v1/repos"))
52 .await
53 }
54
55 pub async fn list_in_space(
57 &self,
58 space: &str,
59 query: Option<&str>,
60 sort: RepoSort,
61 page: u32,
62 limit: u32,
63 ) -> Result<Vec<Repository>> {
64 let space = space.replace('/', "%2F");
65 self.client
66 .get_json(
67 &list_query(query, sort, page, limit)
68 .apply(&format!("/api/v1/spaces/{space}/repos")),
69 )
70 .await
71 }
72}
73
74fn list_query(query: Option<&str>, sort: RepoSort, page: u32, limit: u32) -> Query {
75 let mut q = Query::new();
76 q.push_opt("query", query)
77 .push("sort", sort.as_str())
78 .push("order", sort.order())
79 .push("page", page)
80 .push("limit", limit);
81 q
82}
83
84#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
88pub enum RepoSort {
89 #[default]
90 Name,
91 Created,
92 Updated,
93}
94
95impl RepoSort {
96 pub fn as_str(self) -> &'static str {
97 match self {
98 Self::Name => "identifier",
99 Self::Created => "created",
100 Self::Updated => "updated",
101 }
102 }
103
104 pub fn order(self) -> &'static str {
105 match self {
106 Self::Name => "asc",
107 Self::Created | Self::Updated => "desc",
108 }
109 }
110}
111
112#[cfg(test)]
113mod tests {
114 use super::*;
115
116 #[test]
117 fn listings_are_ordered_the_way_each_sort_key_is_read() {
118 assert_eq!(RepoSort::Name.as_str(), "identifier");
119 assert_eq!(RepoSort::Name.order(), "asc");
120 assert_eq!(RepoSort::Updated.as_str(), "updated");
121 assert_eq!(RepoSort::Updated.order(), "desc");
122 }
123
124 #[test]
125 fn the_space_listing_encodes_a_nested_space_as_one_segment() {
126 let q = list_query(None, RepoSort::Name, 1, 30);
127 assert_eq!(
128 q.apply("/api/v1/spaces/org%2Fteam/repos"),
129 "/api/v1/spaces/org%2Fteam/repos?sort=identifier&order=asc&page=1&limit=30"
130 );
131 }
132
133 #[test]
134 fn a_search_term_is_escaped_not_concatenated() {
135 let q = list_query(Some("back end"), RepoSort::Name, 1, 30);
136 assert!(q.encode().contains("query=back+end"), "{}", q.encode());
137 }
138}