quinjet 0.0.48

A fast, live, keyboard-first Git source-control interface for the terminal
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
use std::ffi::OsString;
use std::path::{Path, PathBuf};

use anyhow::{Context, Result, bail};
use serde::Deserialize;
use serde_json::{Map, Value, json};

use super::{MAX_GH_METADATA_BYTES, PullRequest, Repository, bounded_command_error};

mod model;
mod query;

pub(crate) use model::*;

#[derive(Deserialize)]
struct GraphqlEnvelope {
    data: Option<Value>,
    #[serde(default)]
    errors: Vec<GraphqlError>,
}

#[derive(Deserialize)]
struct GraphqlError {
    message: String,
}

impl Repository {
    pub(crate) fn perform_pull_request_review_operation(
        &self,
        pull_request: &PullRequest,
        operation: &PullRequestReviewOperation,
    ) -> Result<String> {
        match operation {
            PullRequestReviewOperation::AddThread {
                body,
                path,
                line,
                side,
                start_line,
                start_side,
                subject,
            } => self.add_review_thread(
                pull_request,
                &ReviewThreadDraft {
                    body,
                    path,
                    line: *line,
                    side: *side,
                    start_line: *start_line,
                    start_side: *start_side,
                    subject: *subject,
                },
            ),
            PullRequestReviewOperation::Reply { thread_id, body } => {
                self.reply_review_thread(pull_request, thread_id, body)
            }
            PullRequestReviewOperation::UpdateComment { comment_id, body } => self
                .review_mutation(
                    pull_request,
                    "mutation($input: UpdatePullRequestReviewCommentInput!) { updatePullRequestReviewComment(input: $input) { pullRequestReviewComment { id } } }",
                    &json!({ "input": { "pullRequestReviewCommentId": comment_id, "body": body } }),
                    "unable to update the review comment",
                    "Updated review comment",
                ),
            PullRequestReviewOperation::DeleteComment { comment_id } => self.review_mutation(
                pull_request,
                "mutation($input: DeletePullRequestReviewCommentInput!) { deletePullRequestReviewComment(input: $input) { pullRequestReview { id } } }",
                &json!({ "input": { "id": comment_id } }),
                "unable to delete the review comment",
                "Deleted review comment",
            ),
            PullRequestReviewOperation::Submit { body, decision } => {
                self.submit_review(pull_request, body, *decision)
            }
            PullRequestReviewOperation::Discard => self.discard_review(pull_request),
            PullRequestReviewOperation::Resolve { thread_id } => self.review_mutation(
                pull_request,
                "mutation($input: ResolveReviewThreadInput!) { resolveReviewThread(input: $input) { thread { id } } }",
                &json!({ "input": { "threadId": thread_id } }),
                "unable to resolve the review thread",
                "Resolved review thread",
            ),
            PullRequestReviewOperation::Unresolve { thread_id } => self.review_mutation(
                pull_request,
                "mutation($input: UnresolveReviewThreadInput!) { unresolveReviewThread(input: $input) { thread { id } } }",
                &json!({ "input": { "threadId": thread_id } }),
                "unable to reopen the review thread",
                "Reopened review thread",
            ),
        }
    }

    fn add_review_thread(
        &self,
        pull_request: &PullRequest,
        draft: &ReviewThreadDraft<'_>,
    ) -> Result<String> {
        let snapshot = self.pull_request_review(pull_request)?;
        ensure_current_pending_review(&snapshot)?;
        let pending = match snapshot.pending_review {
            Some(pending) => pending,
            None => self.create_pending_review(pull_request, &snapshot)?,
        };
        let mut input = review_thread_input(draft)?;
        drop(input.insert("pullRequestReviewId".to_owned(), Value::String(pending.id)));
        self.review_mutation(
            pull_request,
            "mutation($input: AddPullRequestReviewThreadInput!) { addPullRequestReviewThread(input: $input) { thread { id } } }",
            &json!({ "input": input }),
            "unable to add the review comment",
            "Added pending review comment",
        )
    }

    fn reply_review_thread(
        &self,
        pull_request: &PullRequest,
        thread_id: &str,
        body: &str,
    ) -> Result<String> {
        let snapshot = self.pull_request_review(pull_request)?;
        ensure_current_pending_review(&snapshot)?;
        let pending = match snapshot.pending_review {
            Some(pending) => pending,
            None => self.create_pending_review(pull_request, &snapshot)?,
        };
        self.review_mutation(
            pull_request,
            "mutation($input: AddPullRequestReviewThreadReplyInput!) { addPullRequestReviewThreadReply(input: $input) { comment { id } } }",
            &json!({
                "input": {
                    "pullRequestReviewThreadId": thread_id,
                    "pullRequestReviewId": pending.id,
                    "body": body,
                }
            }),
            "unable to reply to the review thread",
            "Added pending review reply",
        )
    }

    fn create_pending_review(
        &self,
        pull_request: &PullRequest,
        snapshot: &PullRequestReviewSnapshot,
    ) -> Result<PullRequestPendingReview> {
        let data = self.graphql_value(
            pull_request,
            "mutation($input: AddPullRequestReviewInput!) { addPullRequestReview(input: $input) { pullRequestReview { id body commit { oid } } } }",
            &json!({
                "input": {
                    "pullRequestId": snapshot.pull_request_id,
                    "commitOID": snapshot.head_oid,
                }
            }),
            "unable to start the pull-request review",
        )?;
        let review = data
            .pointer("/addPullRequestReview/pullRequestReview")
            .context("GitHub did not return the pending review")?;
        Ok(PullRequestPendingReview {
            id: string_field(review, "id")?,
            body: review
                .get("body")
                .and_then(Value::as_str)
                .unwrap_or_default()
                .to_owned(),
            commit_oid: review
                .pointer("/commit/oid")
                .and_then(Value::as_str)
                .unwrap_or_default()
                .to_owned(),
        })
    }

    fn submit_review(
        &self,
        pull_request: &PullRequest,
        body: &str,
        decision: PullRequestReviewDecision,
    ) -> Result<String> {
        let snapshot = self.pull_request_review(pull_request)?;
        ensure_current_pending_review(&snapshot)?;
        let input = snapshot.pending_review.map_or_else(
            || {
                json!({
                    "pullRequestId": snapshot.pull_request_id,
                    "commitOID": snapshot.head_oid,
                    "body": body,
                    "event": decision.graphql(),
                })
            },
            |pending| {
                json!({
                    "pullRequestReviewId": pending.id,
                    "body": body,
                    "event": decision.graphql(),
                })
            },
        );
        let (query, context) = if input.get("pullRequestReviewId").is_some() {
            (
                "mutation($input: SubmitPullRequestReviewInput!) { submitPullRequestReview(input: $input) { pullRequestReview { id } } }",
                "unable to submit the pending review",
            )
        } else {
            (
                "mutation($input: AddPullRequestReviewInput!) { addPullRequestReview(input: $input) { pullRequestReview { id } } }",
                "unable to submit the pull-request review",
            )
        };
        self.review_mutation(
            pull_request,
            query,
            &json!({ "input": input }),
            context,
            &format!("Submitted review: {}", decision.label()),
        )
    }

    fn discard_review(&self, pull_request: &PullRequest) -> Result<String> {
        let snapshot = self.pull_request_review(pull_request)?;
        let pending = snapshot
            .pending_review
            .context("there is no pending review to discard")?;
        self.review_mutation(
            pull_request,
            "mutation($input: DeletePullRequestReviewInput!) { deletePullRequestReview(input: $input) { pullRequestReview { id } } }",
            &json!({ "input": { "pullRequestReviewId": pending.id } }),
            "unable to discard the pending review",
            "Discarded pending review",
        )
    }

    fn review_mutation(
        &self,
        pull_request: &PullRequest,
        query: &str,
        variables: &Value,
        context: &str,
        message: &str,
    ) -> Result<String> {
        let _data = self.graphql_value(pull_request, query, variables, context)?;
        Ok(message.to_owned())
    }

    fn graphql<T: for<'de> Deserialize<'de>>(
        &self,
        pull_request: &PullRequest,
        query: &str,
        variables: &Value,
        context: &str,
    ) -> Result<T> {
        serde_json::from_value(self.graphql_value(pull_request, query, variables, context)?)
            .with_context(|| format!("{context}: GitHub returned an unexpected response"))
    }

    fn graphql_value(
        &self,
        pull_request: &PullRequest,
        query: &str,
        variables: &Value,
        context: &str,
    ) -> Result<Value> {
        let payload = serde_json::to_vec(&json!({ "query": query, "variables": variables }))?;
        let mut args = vec![OsString::from("api"), OsString::from("graphql")];
        let host = pull_request.base_repository.host();
        if !host.is_empty() {
            args.push(OsString::from("--hostname"));
            args.push(OsString::from(host));
        }
        args.push(OsString::from("--input"));
        args.push(OsString::from("-"));
        let output = self.run_gh_with_input(args, &payload, MAX_GH_METADATA_BYTES)?;
        if !output.status.success() {
            bail!("{}", bounded_command_error(context, &output));
        }
        if output.stdout_truncated {
            bail!("{context}: GitHub response exceeded the metadata limit");
        }
        let envelope: GraphqlEnvelope = serde_json::from_slice(&output.stdout)
            .with_context(|| format!("{context}: GitHub returned invalid JSON"))?;
        if !envelope.errors.is_empty() {
            bail!(
                "{context}: {}",
                envelope
                    .errors
                    .into_iter()
                    .map(|error| error.message)
                    .collect::<Vec<_>>()
                    .join("; ")
            );
        }
        envelope
            .data
            .with_context(|| format!("{context}: GitHub returned no data"))
    }
}

fn repository_parts(pull_request: &PullRequest) -> Result<(&str, &str)> {
    pull_request
        .base_repository
        .name_with_owner
        .split_once('/')
        .context("the pull request repository is not in owner/name form")
}

fn ensure_current_pending_review(snapshot: &PullRequestReviewSnapshot) -> Result<()> {
    if let Some(pending) = &snapshot.pending_review
        && !pending.commit_oid.is_empty()
        && pending.commit_oid != snapshot.head_oid
    {
        bail!(
            "the pending review targets an older head commit; submit or discard it before adding more comments"
        );
    }
    Ok(())
}

struct ReviewThreadDraft<'a> {
    body: &'a str,
    path: &'a Path,
    line: Option<usize>,
    side: Option<PullRequestReviewSide>,
    start_line: Option<usize>,
    start_side: Option<PullRequestReviewSide>,
    subject: PullRequestReviewThreadSubject,
}

fn review_thread_input(draft: &ReviewThreadDraft<'_>) -> Result<Map<String, Value>> {
    if draft.body.trim().is_empty() {
        bail!("a review comment cannot be empty");
    }
    let mut input = Map::new();
    drop(input.insert("body".to_owned(), Value::String(draft.body.to_owned())));
    drop(input.insert(
        "path".to_owned(),
        Value::String(draft.path.to_string_lossy().into_owned()),
    ));
    drop(input.insert(
        "subjectType".to_owned(),
        Value::String(draft.subject.graphql().to_owned()),
    ));
    if draft.subject == PullRequestReviewThreadSubject::Line {
        let line = draft
            .line
            .context("a line-level review comment needs a line")?;
        let side = draft
            .side
            .context("a line-level review comment needs a diff side")?;
        drop(input.insert("line".to_owned(), json!(line)));
        drop(input.insert("side".to_owned(), Value::String(side.graphql().to_owned())));
        if let Some(start_line) = draft.start_line {
            drop(input.insert("startLine".to_owned(), json!(start_line)));
            drop(input.insert(
                "startSide".to_owned(),
                Value::String(draft.start_side.unwrap_or(side).graphql().to_owned()),
            ));
        }
    }
    Ok(input)
}

fn string_field(value: &Value, field: &str) -> Result<String> {
    value
        .get(field)
        .and_then(Value::as_str)
        .map(str::to_owned)
        .with_context(|| format!("GitHub did not return `{field}`"))
}

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

    #[test]
    fn line_thread_input_uses_blob_coordinates() {
        let input = review_thread_input(&ReviewThreadDraft {
            body: "Fix this",
            path: Path::new("src/main.rs"),
            line: Some(42),
            side: Some(PullRequestReviewSide::Right),
            start_line: Some(40),
            start_side: Some(PullRequestReviewSide::Right),
            subject: PullRequestReviewThreadSubject::Line,
        })
        .unwrap();
        assert_eq!(input.get("line"), Some(&json!(42)));
        assert_eq!(input.get("side"), Some(&json!("RIGHT")));
        assert_eq!(input.get("startLine"), Some(&json!(40)));
    }

    #[test]
    fn file_thread_input_omits_line_coordinates() {
        let input = review_thread_input(&ReviewThreadDraft {
            body: "Consider splitting this file",
            path: Path::new("src/main.rs"),
            line: None,
            side: None,
            start_line: None,
            start_side: None,
            subject: PullRequestReviewThreadSubject::File,
        })
        .unwrap();
        assert!(!input.contains_key("line"));
        assert_eq!(input.get("subjectType"), Some(&json!("FILE")));
    }
}

#[cfg(test)]
mod transport_tests;