gitfox-client 0.7.0

Rust client library for the GitFox API
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
use std::fmt;
use std::str::FromStr;

use serde::{Deserialize, Serialize};

use super::Principal;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum PullRequestState {
    Open,
    Closed,
    Merged,
}

impl PullRequestState {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Open => "open",
            Self::Closed => "closed",
            Self::Merged => "merged",
        }
    }
}

impl fmt::Display for PullRequestState {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// How a pull request is merged. The wire values are GitFox's, including the
/// hyphen in `fast-forward`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum MergeMethod {
    Merge,
    Squash,
    Rebase,
    FastForward,
}

impl MergeMethod {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Merge => "merge",
            Self::Squash => "squash",
            Self::Rebase => "rebase",
            Self::FastForward => "fast-forward",
        }
    }
}

impl fmt::Display for MergeMethod {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl FromStr for MergeMethod {
    type Err = ();

    fn from_str(s: &str) -> Result<Self, ()> {
        match s.trim().to_ascii_lowercase().replace('_', "-").as_str() {
            "merge" => Ok(Self::Merge),
            "squash" => Ok(Self::Squash),
            "rebase" => Ok(Self::Rebase),
            "fast-forward" | "fastforward" | "ff" => Ok(Self::FastForward),
            _ => Err(()),
        }
    }
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct PullRequestStats {
    #[serde(default)]
    pub commits: Option<i64>,
    #[serde(default)]
    pub files_changed: Option<i64>,
    #[serde(default)]
    pub additions: Option<i64>,
    #[serde(default)]
    pub deletions: Option<i64>,
    #[serde(default)]
    pub conversations: Option<i64>,
    #[serde(default)]
    pub unresolved_count: Option<i64>,
}

/// A pull request.
///
/// Timestamps stay as the raw epoch integers GitFox sends. Interpreting them is
/// a presentation concern, and keeping them raw means the JSON a machine reads
/// never depends on this crate's idea of a date format.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PullRequest {
    pub number: u64,
    #[serde(default)]
    pub title: String,
    #[serde(default)]
    pub description: String,
    pub state: PullRequestState,
    #[serde(default)]
    pub is_draft: bool,
    #[serde(default)]
    pub author: Option<Principal>,
    #[serde(default)]
    pub merger: Option<Principal>,
    #[serde(default)]
    pub source_branch: String,
    #[serde(default)]
    pub target_branch: String,
    /// Differs from `target_repo_id` when the pull request comes from a fork.
    #[serde(default)]
    pub source_repo_id: Option<i64>,
    #[serde(default)]
    pub target_repo_id: Option<i64>,
    #[serde(default)]
    pub created: Option<i64>,
    #[serde(default)]
    pub updated: Option<i64>,
    #[serde(default)]
    pub merged: Option<i64>,
    #[serde(default)]
    pub closed: Option<i64>,
    #[serde(default)]
    pub web_url: Option<String>,
    #[serde(default)]
    pub stats: Option<PullRequestStats>,
    #[serde(default)]
    pub merge_check_status: Option<String>,
    #[serde(default)]
    pub merge_conflicts: Vec<String>,
    #[serde(default)]
    pub merge_method: Option<MergeMethod>,
    /// The head commit of the source branch.
    #[serde(default)]
    pub source_sha: Option<String>,
    /// The target branch commit the merge check was computed against.
    #[serde(default)]
    pub merge_target_sha: Option<String>,
    #[serde(default)]
    pub merge_base_sha: Option<String>,
    #[serde(default)]
    pub edited: Option<i64>,
    #[serde(default)]
    pub labels: Vec<PullRequestLabel>,
    /// Present when the list was asked for with `include_checks=true`.
    #[serde(default)]
    pub check_summary: Option<CheckCountSummary>,
}

/// A label as it is attached to a pull request: the label's key and, for a
/// label with values, the value chosen.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
pub struct PullRequestLabel {
    #[serde(default)]
    pub id: Option<i64>,
    #[serde(default)]
    pub key: String,
    #[serde(default)]
    pub value: Option<String>,
    #[serde(default)]
    pub value_id: Option<i64>,
    #[serde(default)]
    pub color: Option<String>,
    #[serde(default)]
    pub value_color: Option<String>,
    #[serde(default)]
    pub scope: Option<i64>,
}

impl PullRequestLabel {
    /// `key`, or `key:value` for a label with a value — the spelling
    /// `--label` takes back.
    pub fn name(&self) -> String {
        match self.value.as_deref().filter(|v| !v.is_empty()) {
            Some(value) => format!("{}:{value}", self.key),
            None => self.key.clone(),
        }
    }
}

/// How many checks on the head commit are in each state.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
pub struct CheckCountSummary {
    #[serde(default)]
    pub error: i64,
    #[serde(default)]
    pub failure: i64,
    #[serde(default)]
    pub pending: i64,
    #[serde(default)]
    pub running: i64,
    #[serde(default)]
    pub success: i64,
}

impl PullRequest {
    /// `open`, `draft`, `merged` or `closed` — draft is a display state, not an
    /// API one, but it is the first thing a reviewer wants to know.
    pub fn display_state(&self) -> &'static str {
        if self.state == PullRequestState::Open && self.is_draft {
            "draft"
        } else {
            self.state.as_str()
        }
    }

    pub fn author_label(&self) -> String {
        self.author
            .as_ref()
            .map(Principal::label)
            .unwrap_or_default()
    }
}

/// The body of `POST /repos/{repo_ref}/pullreq`.
#[derive(Debug, Clone, Serialize)]
pub struct CreatePullRequest {
    pub title: String,
    pub description: String,
    pub source_branch: String,
    pub target_branch: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub source_repo_ref: Option<String>,
    pub is_draft: bool,
}

/// The body of `PATCH /repos/{repo_ref}/pullreq/{n}`. GitFox edits only the
/// title and the description here; everything else has its own endpoint.
#[derive(Debug, Clone, Default, Serialize)]
pub struct UpdatePullRequest {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
}

/// The body of `POST /repos/{repo_ref}/pullreq/{n}/merge`.
#[derive(Debug, Clone, Default, Serialize)]
pub struct MergePullRequest {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub method: Option<MergeMethod>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub message: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub source_sha: Option<String>,
    #[serde(skip_serializing_if = "std::ops::Not::not")]
    pub bypass_rules: bool,
    #[serde(skip_serializing_if = "std::ops::Not::not")]
    pub dry_run: bool,
}

/// The answer to a merge attempt.
///
/// A `dry_run` merge returns the same shape with `mergeable` telling you whether
/// the real thing would work — which is what `gf pr merge --dry-run` reports.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct MergeResult {
    #[serde(default)]
    pub sha: Option<String>,
    #[serde(default)]
    pub branch_deleted: Option<bool>,
    #[serde(default)]
    pub mergeable: Option<bool>,
    #[serde(default)]
    pub dry_run: Option<bool>,
    #[serde(default)]
    pub conflict_files: Vec<String>,
    #[serde(default)]
    pub allowed_methods: Vec<MergeMethod>,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn merge_methods_use_the_wire_spelling() {
        assert_eq!(MergeMethod::FastForward.as_str(), "fast-forward");
        assert_eq!(
            serde_json::to_string(&MergeMethod::FastForward).unwrap(),
            "\"fast-forward\""
        );
        assert_eq!("fast-forward".parse(), Ok(MergeMethod::FastForward));
        assert_eq!("FF".parse(), Ok(MergeMethod::FastForward));
        assert_eq!("nonsense".parse::<MergeMethod>(), Err(()));
    }

    #[test]
    fn a_draft_reads_as_draft_rather_than_open() {
        let mut pr: PullRequest = serde_json::from_value(serde_json::json!({
            "number": 12, "title": "Add OAuth", "state": "open", "is_draft": true
        }))
        .unwrap();
        assert_eq!(pr.display_state(), "draft");
        pr.is_draft = false;
        assert_eq!(pr.display_state(), "open");
        pr.state = PullRequestState::Merged;
        pr.is_draft = true;
        assert_eq!(pr.display_state(), "merged");
    }

    #[test]
    fn a_minimal_payload_still_decodes() {
        let pr: PullRequest =
            serde_json::from_value(serde_json::json!({ "number": 1, "state": "closed" })).unwrap();
        assert_eq!(pr.number, 1);
        assert!(pr.title.is_empty());
        assert!(pr.author.is_none());
        assert_eq!(pr.author_label(), "");
    }

    #[test]
    fn merge_body_omits_everything_unset() {
        let body = serde_json::to_value(MergePullRequest {
            method: Some(MergeMethod::Squash),
            ..Default::default()
        })
        .unwrap();
        assert_eq!(body, serde_json::json!({ "method": "squash" }));
    }
}

/// One file's worth of a pull request diff.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct FileDiff {
    #[serde(default)]
    pub path: String,
    /// Set when the file was renamed or copied.
    #[serde(default)]
    pub old_path: Option<String>,
    #[serde(default)]
    pub status: Option<String>,
    #[serde(default)]
    pub additions: Option<i64>,
    #[serde(default)]
    pub deletions: Option<i64>,
    #[serde(default)]
    pub changes: Option<i64>,
    #[serde(default)]
    pub is_binary: Option<bool>,
    #[serde(default)]
    pub is_submodule: Option<bool>,
    /// The unified diff for this file. Absent for binaries and submodules.
    #[serde(default)]
    pub patch: Option<String>,
    #[serde(default)]
    pub sha: Option<String>,
    #[serde(default)]
    pub old_sha: Option<String>,
}

/// A status check reported against a pull request's head commit.
///
/// Reuses [`crate::CiStatus`] — a check status is a CI status, and the same
/// open-set reasoning applies: GitFox lists `error`, `failure`, `pending`,
/// `running` and `success` today, and this keeps whichever word arrives.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Check {
    #[serde(default)]
    pub identifier: String,
    #[serde(default)]
    pub status: crate::CiStatus,
    #[serde(default)]
    pub summary: Option<String>,
    #[serde(default)]
    pub link: Option<String>,
    #[serde(default)]
    pub started: Option<i64>,
    #[serde(default)]
    pub ended: Option<i64>,
    #[serde(default)]
    pub reported_by: Option<super::Principal>,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct PullRequestCheck {
    /// Whether a merge is blocked while this check is not green.
    #[serde(default)]
    pub required: Option<bool>,
    #[serde(default)]
    pub bypassable: Option<bool>,
    #[serde(default)]
    pub check: Check,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct PullRequestChecks {
    /// The commit the checks were reported against.
    #[serde(default)]
    pub commit_sha: Option<String>,
    #[serde(default)]
    pub checks: Vec<PullRequestCheck>,
}

impl PullRequestChecks {
    /// Whether anything required is not green.
    ///
    /// A required check that is still running counts as blocking: the answer to
    /// "can this merge" is no, not yet.
    pub fn required_blocking(&self) -> Vec<&PullRequestCheck> {
        self.checks
            .iter()
            .filter(|c| c.required.unwrap_or(false) && !c.check.status.is_success())
            .collect()
    }

    pub fn any_failed(&self) -> bool {
        self.checks.iter().any(|c| c.check.status.is_failed())
    }
}