Skip to main content

gitfox_client/models/
pull_request.rs

1use std::fmt;
2use std::str::FromStr;
3
4use serde::{Deserialize, Serialize};
5
6use super::Principal;
7
8#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
9#[serde(rename_all = "lowercase")]
10pub enum PullRequestState {
11    Open,
12    Closed,
13    Merged,
14}
15
16impl PullRequestState {
17    pub fn as_str(self) -> &'static str {
18        match self {
19            Self::Open => "open",
20            Self::Closed => "closed",
21            Self::Merged => "merged",
22        }
23    }
24}
25
26impl fmt::Display for PullRequestState {
27    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
28        f.write_str(self.as_str())
29    }
30}
31
32/// How a pull request is merged. The wire values are GitFox's, including the
33/// hyphen in `fast-forward`.
34#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
35#[serde(rename_all = "kebab-case")]
36pub enum MergeMethod {
37    Merge,
38    Squash,
39    Rebase,
40    FastForward,
41}
42
43impl MergeMethod {
44    pub fn as_str(self) -> &'static str {
45        match self {
46            Self::Merge => "merge",
47            Self::Squash => "squash",
48            Self::Rebase => "rebase",
49            Self::FastForward => "fast-forward",
50        }
51    }
52}
53
54impl fmt::Display for MergeMethod {
55    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
56        f.write_str(self.as_str())
57    }
58}
59
60impl FromStr for MergeMethod {
61    type Err = ();
62
63    fn from_str(s: &str) -> Result<Self, ()> {
64        match s.trim().to_ascii_lowercase().replace('_', "-").as_str() {
65            "merge" => Ok(Self::Merge),
66            "squash" => Ok(Self::Squash),
67            "rebase" => Ok(Self::Rebase),
68            "fast-forward" | "fastforward" | "ff" => Ok(Self::FastForward),
69            _ => Err(()),
70        }
71    }
72}
73
74#[derive(Debug, Clone, Default, Serialize, Deserialize)]
75pub struct PullRequestStats {
76    #[serde(default)]
77    pub commits: Option<i64>,
78    #[serde(default)]
79    pub files_changed: Option<i64>,
80    #[serde(default)]
81    pub additions: Option<i64>,
82    #[serde(default)]
83    pub deletions: Option<i64>,
84    #[serde(default)]
85    pub conversations: Option<i64>,
86    #[serde(default)]
87    pub unresolved_count: Option<i64>,
88}
89
90/// A pull request.
91///
92/// Timestamps stay as the raw epoch integers GitFox sends. Interpreting them is
93/// a presentation concern, and keeping them raw means the JSON a machine reads
94/// never depends on this crate's idea of a date format.
95#[derive(Debug, Clone, Serialize, Deserialize)]
96pub struct PullRequest {
97    pub number: u64,
98    #[serde(default)]
99    pub title: String,
100    #[serde(default)]
101    pub description: String,
102    pub state: PullRequestState,
103    #[serde(default)]
104    pub is_draft: bool,
105    #[serde(default)]
106    pub author: Option<Principal>,
107    #[serde(default)]
108    pub merger: Option<Principal>,
109    #[serde(default)]
110    pub source_branch: String,
111    #[serde(default)]
112    pub target_branch: String,
113    /// Differs from `target_repo_id` when the pull request comes from a fork.
114    #[serde(default)]
115    pub source_repo_id: Option<i64>,
116    #[serde(default)]
117    pub target_repo_id: Option<i64>,
118    #[serde(default)]
119    pub created: Option<i64>,
120    #[serde(default)]
121    pub updated: Option<i64>,
122    #[serde(default)]
123    pub merged: Option<i64>,
124    #[serde(default)]
125    pub closed: Option<i64>,
126    #[serde(default)]
127    pub web_url: Option<String>,
128    #[serde(default)]
129    pub stats: Option<PullRequestStats>,
130    #[serde(default)]
131    pub merge_check_status: Option<String>,
132    #[serde(default)]
133    pub merge_conflicts: Vec<String>,
134    #[serde(default)]
135    pub merge_method: Option<MergeMethod>,
136    /// The head commit of the source branch.
137    #[serde(default)]
138    pub source_sha: Option<String>,
139    /// The target branch commit the merge check was computed against.
140    #[serde(default)]
141    pub merge_target_sha: Option<String>,
142    #[serde(default)]
143    pub merge_base_sha: Option<String>,
144    #[serde(default)]
145    pub edited: Option<i64>,
146    #[serde(default)]
147    pub labels: Vec<PullRequestLabel>,
148    /// Present when the list was asked for with `include_checks=true`.
149    #[serde(default)]
150    pub check_summary: Option<CheckCountSummary>,
151}
152
153/// A label as it is attached to a pull request: the label's key and, for a
154/// label with values, the value chosen.
155#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
156pub struct PullRequestLabel {
157    #[serde(default)]
158    pub id: Option<i64>,
159    #[serde(default)]
160    pub key: String,
161    #[serde(default)]
162    pub value: Option<String>,
163    #[serde(default)]
164    pub value_id: Option<i64>,
165    #[serde(default)]
166    pub color: Option<String>,
167    #[serde(default)]
168    pub value_color: Option<String>,
169    #[serde(default)]
170    pub scope: Option<i64>,
171}
172
173impl PullRequestLabel {
174    /// `key`, or `key:value` for a label with a value — the spelling
175    /// `--label` takes back.
176    pub fn name(&self) -> String {
177        match self.value.as_deref().filter(|v| !v.is_empty()) {
178            Some(value) => format!("{}:{value}", self.key),
179            None => self.key.clone(),
180        }
181    }
182}
183
184/// How many checks on the head commit are in each state.
185#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
186pub struct CheckCountSummary {
187    #[serde(default)]
188    pub error: i64,
189    #[serde(default)]
190    pub failure: i64,
191    #[serde(default)]
192    pub pending: i64,
193    #[serde(default)]
194    pub running: i64,
195    #[serde(default)]
196    pub success: i64,
197}
198
199impl PullRequest {
200    /// `open`, `draft`, `merged` or `closed` — draft is a display state, not an
201    /// API one, but it is the first thing a reviewer wants to know.
202    pub fn display_state(&self) -> &'static str {
203        if self.state == PullRequestState::Open && self.is_draft {
204            "draft"
205        } else {
206            self.state.as_str()
207        }
208    }
209
210    pub fn author_label(&self) -> String {
211        self.author
212            .as_ref()
213            .map(Principal::label)
214            .unwrap_or_default()
215    }
216}
217
218/// The body of `POST /repos/{repo_ref}/pullreq`.
219#[derive(Debug, Clone, Serialize)]
220pub struct CreatePullRequest {
221    pub title: String,
222    pub description: String,
223    pub source_branch: String,
224    pub target_branch: String,
225    #[serde(skip_serializing_if = "Option::is_none")]
226    pub source_repo_ref: Option<String>,
227    pub is_draft: bool,
228}
229
230/// The body of `PATCH /repos/{repo_ref}/pullreq/{n}`. GitFox edits only the
231/// title and the description here; everything else has its own endpoint.
232#[derive(Debug, Clone, Default, Serialize)]
233pub struct UpdatePullRequest {
234    #[serde(skip_serializing_if = "Option::is_none")]
235    pub title: Option<String>,
236    #[serde(skip_serializing_if = "Option::is_none")]
237    pub description: Option<String>,
238}
239
240/// The body of `POST /repos/{repo_ref}/pullreq/{n}/merge`.
241#[derive(Debug, Clone, Default, Serialize)]
242pub struct MergePullRequest {
243    #[serde(skip_serializing_if = "Option::is_none")]
244    pub method: Option<MergeMethod>,
245    #[serde(skip_serializing_if = "Option::is_none")]
246    pub title: Option<String>,
247    #[serde(skip_serializing_if = "Option::is_none")]
248    pub message: Option<String>,
249    #[serde(skip_serializing_if = "Option::is_none")]
250    pub source_sha: Option<String>,
251    #[serde(skip_serializing_if = "std::ops::Not::not")]
252    pub bypass_rules: bool,
253    #[serde(skip_serializing_if = "std::ops::Not::not")]
254    pub dry_run: bool,
255}
256
257/// The answer to a merge attempt.
258///
259/// A `dry_run` merge returns the same shape with `mergeable` telling you whether
260/// the real thing would work — which is what `gf pr merge --dry-run` reports.
261#[derive(Debug, Clone, Default, Serialize, Deserialize)]
262pub struct MergeResult {
263    #[serde(default)]
264    pub sha: Option<String>,
265    #[serde(default)]
266    pub branch_deleted: Option<bool>,
267    #[serde(default)]
268    pub mergeable: Option<bool>,
269    #[serde(default)]
270    pub dry_run: Option<bool>,
271    #[serde(default)]
272    pub conflict_files: Vec<String>,
273    #[serde(default)]
274    pub allowed_methods: Vec<MergeMethod>,
275}
276
277#[cfg(test)]
278mod tests {
279    use super::*;
280
281    #[test]
282    fn merge_methods_use_the_wire_spelling() {
283        assert_eq!(MergeMethod::FastForward.as_str(), "fast-forward");
284        assert_eq!(
285            serde_json::to_string(&MergeMethod::FastForward).unwrap(),
286            "\"fast-forward\""
287        );
288        assert_eq!("fast-forward".parse(), Ok(MergeMethod::FastForward));
289        assert_eq!("FF".parse(), Ok(MergeMethod::FastForward));
290        assert_eq!("nonsense".parse::<MergeMethod>(), Err(()));
291    }
292
293    #[test]
294    fn a_draft_reads_as_draft_rather_than_open() {
295        let mut pr: PullRequest = serde_json::from_value(serde_json::json!({
296            "number": 12, "title": "Add OAuth", "state": "open", "is_draft": true
297        }))
298        .unwrap();
299        assert_eq!(pr.display_state(), "draft");
300        pr.is_draft = false;
301        assert_eq!(pr.display_state(), "open");
302        pr.state = PullRequestState::Merged;
303        pr.is_draft = true;
304        assert_eq!(pr.display_state(), "merged");
305    }
306
307    #[test]
308    fn a_minimal_payload_still_decodes() {
309        let pr: PullRequest =
310            serde_json::from_value(serde_json::json!({ "number": 1, "state": "closed" })).unwrap();
311        assert_eq!(pr.number, 1);
312        assert!(pr.title.is_empty());
313        assert!(pr.author.is_none());
314        assert_eq!(pr.author_label(), "");
315    }
316
317    #[test]
318    fn merge_body_omits_everything_unset() {
319        let body = serde_json::to_value(MergePullRequest {
320            method: Some(MergeMethod::Squash),
321            ..Default::default()
322        })
323        .unwrap();
324        assert_eq!(body, serde_json::json!({ "method": "squash" }));
325    }
326}
327
328/// One file's worth of a pull request diff.
329#[derive(Debug, Clone, Default, Serialize, Deserialize)]
330pub struct FileDiff {
331    #[serde(default)]
332    pub path: String,
333    /// Set when the file was renamed or copied.
334    #[serde(default)]
335    pub old_path: Option<String>,
336    #[serde(default)]
337    pub status: Option<String>,
338    #[serde(default)]
339    pub additions: Option<i64>,
340    #[serde(default)]
341    pub deletions: Option<i64>,
342    #[serde(default)]
343    pub changes: Option<i64>,
344    #[serde(default)]
345    pub is_binary: Option<bool>,
346    #[serde(default)]
347    pub is_submodule: Option<bool>,
348    /// The unified diff for this file. Absent for binaries and submodules.
349    #[serde(default)]
350    pub patch: Option<String>,
351    #[serde(default)]
352    pub sha: Option<String>,
353    #[serde(default)]
354    pub old_sha: Option<String>,
355}
356
357/// A status check reported against a pull request's head commit.
358///
359/// Reuses [`crate::CiStatus`] — a check status is a CI status, and the same
360/// open-set reasoning applies: GitFox lists `error`, `failure`, `pending`,
361/// `running` and `success` today, and this keeps whichever word arrives.
362#[derive(Debug, Clone, Default, Serialize, Deserialize)]
363pub struct Check {
364    #[serde(default)]
365    pub identifier: String,
366    #[serde(default)]
367    pub status: crate::CiStatus,
368    #[serde(default)]
369    pub summary: Option<String>,
370    #[serde(default)]
371    pub link: Option<String>,
372    #[serde(default)]
373    pub started: Option<i64>,
374    #[serde(default)]
375    pub ended: Option<i64>,
376    #[serde(default)]
377    pub reported_by: Option<super::Principal>,
378}
379
380#[derive(Debug, Clone, Default, Serialize, Deserialize)]
381pub struct PullRequestCheck {
382    /// Whether a merge is blocked while this check is not green.
383    #[serde(default)]
384    pub required: Option<bool>,
385    #[serde(default)]
386    pub bypassable: Option<bool>,
387    #[serde(default)]
388    pub check: Check,
389}
390
391#[derive(Debug, Clone, Default, Serialize, Deserialize)]
392pub struct PullRequestChecks {
393    /// The commit the checks were reported against.
394    #[serde(default)]
395    pub commit_sha: Option<String>,
396    #[serde(default)]
397    pub checks: Vec<PullRequestCheck>,
398}
399
400impl PullRequestChecks {
401    /// Whether anything required is not green.
402    ///
403    /// A required check that is still running counts as blocking: the answer to
404    /// "can this merge" is no, not yet.
405    pub fn required_blocking(&self) -> Vec<&PullRequestCheck> {
406        self.checks
407            .iter()
408            .filter(|c| c.required.unwrap_or(false) && !c.check.status.is_success())
409            .collect()
410    }
411
412    pub fn any_failed(&self) -> bool {
413        self.checks.iter().any(|c| c.check.status.is_failed())
414    }
415}