1use serde_json::json;
22
23use crate::client::{GitFoxClient, Method, Query};
24use crate::error::Result;
25use crate::models::{
26 CreatePullRequest, FileDiff, MergePullRequest, MergeResult, PullRequest, PullRequestChecks,
27 PullRequestState, RepoRef,
28};
29
30#[derive(Debug, Clone)]
35pub struct PullRequestFilter {
36 pub state: Vec<PullRequestState>,
37 pub author_id: Option<i64>,
38 pub source_branch: Option<String>,
39 pub target_branch: Option<String>,
40 pub query: Option<String>,
41 pub page: u32,
42 pub limit: u32,
43}
44
45impl Default for PullRequestFilter {
46 fn default() -> Self {
47 Self {
48 state: vec![PullRequestState::Open],
49 author_id: None,
50 source_branch: None,
51 target_branch: None,
52 query: None,
53 page: 1,
54 limit: 30,
55 }
56 }
57}
58
59impl PullRequestFilter {
60 fn to_query(&self) -> Query {
61 let mut q = Query::new();
62 q.extend("state", self.state.iter().map(|s| s.as_str()))
63 .push_opt("author_id", self.author_id)
64 .push_opt("source_branch", self.source_branch.as_deref())
65 .push_opt("target_branch", self.target_branch.as_deref())
66 .push_opt("query", self.query.as_deref())
67 .push("page", self.page)
68 .push("limit", self.limit);
69 q
70 }
71}
72
73pub struct PullRequestsApi<'a> {
74 client: &'a GitFoxClient,
75}
76
77impl<'a> PullRequestsApi<'a> {
78 pub(crate) fn new(client: &'a GitFoxClient) -> Self {
79 Self { client }
80 }
81
82 pub async fn list(
84 &self,
85 repo: &RepoRef,
86 filter: &PullRequestFilter,
87 ) -> Result<Vec<PullRequest>> {
88 let path = format!("/api/v1/repos/{}/pullreq", repo.encoded());
89 self.client.get_json(&filter.to_query().apply(&path)).await
90 }
91
92 pub async fn get(&self, repo: &RepoRef, number: u64) -> Result<PullRequest> {
94 self.client
95 .get_json(&format!(
96 "/api/v1/repos/{}/pullreq/{number}",
97 repo.encoded()
98 ))
99 .await
100 }
101
102 pub async fn find_for_branch(
107 &self,
108 repo: &RepoRef,
109 branch: &str,
110 ) -> Result<Option<PullRequest>> {
111 let filter = PullRequestFilter {
112 source_branch: Some(branch.to_string()),
113 limit: 2,
114 ..Default::default()
115 };
116 Ok(self.list(repo, &filter).await?.into_iter().next())
117 }
118
119 pub async fn create(&self, repo: &RepoRef, input: &CreatePullRequest) -> Result<PullRequest> {
121 let body = serde_json::to_value(input).map_err(|e| crate::Error::Decode(e.to_string()))?;
122 self.client
123 .request(
124 Method::POST,
125 &format!("/api/v1/repos/{}/pullreq", repo.encoded()),
126 Some(&body),
127 &[],
128 )
129 .await?
130 .deserialize()
131 }
132
133 pub async fn merge(
135 &self,
136 repo: &RepoRef,
137 number: u64,
138 input: &MergePullRequest,
139 ) -> Result<MergeResult> {
140 let body = serde_json::to_value(input).map_err(|e| crate::Error::Decode(e.to_string()))?;
141 self.client
142 .request(
143 Method::POST,
144 &format!("/api/v1/repos/{}/pullreq/{number}/merge", repo.encoded()),
145 Some(&body),
146 &[],
147 )
148 .await?
149 .deserialize()
150 }
151
152 pub async fn delete_source_branch(&self, repo: &RepoRef, number: u64) -> Result<()> {
157 self.client
158 .request(
159 Method::DELETE,
160 &format!("/api/v1/repos/{}/pullreq/{number}/branch", repo.encoded()),
161 None,
162 &[],
163 )
164 .await
165 .map(|_| ())
166 }
167
168 pub async fn diff_files(&self, repo: &RepoRef, number: u64) -> Result<Vec<FileDiff>> {
173 self.client
174 .get_json(&format!(
175 "/api/v1/repos/{}/pullreq/{number}/diff",
176 repo.encoded()
177 ))
178 .await
179 }
180
181 pub async fn diff_text(&self, repo: &RepoRef, number: u64) -> Result<String> {
183 let response = self
184 .client
185 .request(
186 Method::GET,
187 &format!("/api/v1/repos/{}/pullreq/{number}/diff", repo.encoded()),
188 None,
189 &[("Accept".to_string(), "text/plain".to_string())],
190 )
191 .await?;
192 Ok(response.text)
193 }
194
195 pub async fn checks(&self, repo: &RepoRef, number: u64) -> Result<PullRequestChecks> {
197 self.client
198 .get_json(&format!(
199 "/api/v1/repos/{}/pullreq/{number}/checks",
200 repo.encoded()
201 ))
202 .await
203 }
204
205 pub async fn set_state(
207 &self,
208 repo: &RepoRef,
209 number: u64,
210 state: PullRequestState,
211 ) -> Result<PullRequest> {
212 let body = json!({ "state": state.as_str() });
213 self.client
214 .request(
215 Method::POST,
216 &format!("/api/v1/repos/{}/pullreq/{number}/state", repo.encoded()),
217 Some(&body),
218 &[],
219 )
220 .await?
221 .deserialize()
222 }
223}
224
225#[cfg(test)]
226mod tests {
227 use super::*;
228
229 #[test]
230 fn the_default_filter_asks_for_open_pull_requests_only() {
231 let q = PullRequestFilter::default().to_query();
232 assert_eq!(q.apply("/p"), "/p?state=open&page=1&limit=30");
233 }
234
235 #[test]
236 fn several_states_become_repeated_parameters() {
237 let filter = PullRequestFilter {
238 state: vec![PullRequestState::Open, PullRequestState::Merged],
239 ..Default::default()
240 };
241 assert!(
242 filter
243 .to_query()
244 .encode()
245 .contains("state=open&state=merged")
246 );
247 }
248
249 #[test]
250 fn unset_filters_are_left_out_entirely() {
251 let encoded = PullRequestFilter::default().to_query().encode();
252 for absent in ["author_id", "source_branch", "target_branch", "query"] {
253 assert!(
254 !encoded.contains(absent),
255 "{absent} should be absent: {encoded}"
256 );
257 }
258 }
259}