quinjet 0.0.60

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
412
413
414
415
#[cfg_attr(not(test), expect(clippy::wildcard_imports, reason = "shared"))]
use super::*;

pub(super) struct ApiPage {
    pub(super) data: Vec<u8>,
    pub(super) truncated: bool,
    pub(super) has_next: bool,
    pub(super) last_page: Option<usize>,
}

impl Repository {
    fn github_command(&self) -> Command {
        if let Some(path) = &self.github_cli {
            return Command::new(path);
        }
        Command::new("gh")
    }

    pub(crate) fn perform_pull_request_operation(
        &self,
        pull_request: &PullRequest,
        operation: &PullRequestOperation,
    ) -> Result<String> {
        let args = pull_request_operation_args(pull_request, operation);
        let output = self.run_gh(args)?;
        if !output.status.success() {
            bail!(
                "{}",
                bounded_command_error("unable to update the pull request", &output)
            );
        }
        Ok(operation.success_message(pull_request))
    }

    pub(crate) fn perform_stack_operation(&self, operation: &StackOperation) -> Result<String> {
        let output = self.run_gh(operation.arguments())?;
        if !output.status.success() {
            bail!(
                "{}",
                bounded_command_error("unable to update the pull request stack", &output)
            );
        }
        if output.stdout_truncated || output.stderr_truncated {
            bail!("gh stack output exceeded the safety limit");
        }
        let stdout = text(&output.stdout);
        if !stdout.trim().is_empty() {
            return Ok(stdout.trim().to_owned());
        }
        let stderr = text(&output.stderr);
        if !stderr.trim().is_empty() {
            return Ok(stderr.trim().to_owned());
        }
        Ok(operation.success_message().to_owned())
    }

    #[doc = " One bounded page of a listing endpoint: its body trimmed to whole"]
    #[doc = " records, plus whether GitHub advertises another page after it."]
    pub(super) fn api_page(
        &self,
        endpoint: &str,
        jq: &str,
        page: usize,
        error_context: &str,
    ) -> Result<ApiPage> {
        let output = self.run_gh([
            OsString::from("api"),
            OsString::from("-i"),
            OsString::from(format!("{endpoint}&page={page}")),
            OsString::from("--jq"),
            OsString::from(jq),
        ])?;
        if !output.status.success() && !output.stdout_truncated {
            bail!("{}", bounded_command_error(error_context, &output));
        }
        let (head, body) = split_http_response(&output.stdout);
        let has_next = has_next_page(head.as_ref());
        let mut data = body.to_vec();
        if output.stdout_truncated {
            while data.last().is_some_and(|byte| *byte != b'\n') {
                let _ = data.pop();
            }
        }
        Ok(ApiPage {
            data,
            truncated: output.stdout_truncated,
            has_next,
            last_page: last_page(head.as_ref()),
        })
    }

    #[doc = " Per-file additions and deletions from the pull-request files endpoint."]
    #[doc = " In the blob-less disposable workspace a local `--numstat` would download"]
    #[doc = " every changed blob just to count lines; GitHub already knows the totals."]
    pub(super) fn pull_request_file_counts_from_api(
        &self,
        pull_request: &PullRequest,
    ) -> Option<HashMap<PathBuf, DiffLineCounts>> {
        let base = pull_request.base_oid.trim();
        let head = pull_request.head_oid.trim();
        let repository = &pull_request.base_repository;
        if !is_commit_oid(base) || !is_commit_oid(head) || repository.name_with_owner.is_empty() {
            return None;
        }
        let key = format!(
            "pr-file-counts-v3\n{}\n{}\n{base}\n{head}",
            repository.url.trim_end_matches('/'),
            pull_request.number
        );
        if let Some(data) = cache_read_bounded(&key, CacheLife::Immutable, MAX_PR_PATH_BYTES) {
            return Some(parse_api_file_counts(&data));
        }
        let endpoint = format!(
            "repos/{}/pulls/{}/files?per_page=100",
            repository.name_with_owner, pull_request.number
        );
        let jq = ".[] | [.filename, (.additions|tostring), (.deletions|tostring), .status] | @tsv";
        let mut collected: Vec<u8> = Vec::new();
        let mut complete = false;
        for page in 1..=MAX_FILE_COUNT_PAGES {
            let read = self
                .api_page(&endpoint, jq, page, "unable to list pull-request files")
                .ok()?;
            if read.truncated {
                return None;
            }
            collected.extend_from_slice(&read.data);
            if collected.last().is_some_and(|byte| *byte != b'\n') {
                collected.push(b'\n');
            }
            if !read.has_next {
                complete = true;
                break;
            }
        }
        if complete && collected.len() <= MAX_PR_PATH_BYTES {
            cache_write_bounded(&key, &collected, MAX_PR_PATH_BYTES);
        }
        Some(parse_api_file_counts(&collected))
    }

    #[doc = " Ask the GitHub compare API for the merge base of the two immutable PR"]
    #[doc = " commits. One metadata request replaces the deepening fetch ladder, which"]
    #[doc = " cannot reach a merge base thousands of commits behind either tip."]
    pub(super) fn merge_base_from_api(&self, pull_request: &PullRequest) -> Option<String> {
        let base = pull_request.base_oid.trim();
        let head = pull_request.head_oid.trim();
        let repository = &pull_request.base_repository;
        if !is_commit_oid(base) || !is_commit_oid(head) || repository.name_with_owner.is_empty() {
            return None;
        }
        let key = format!(
            "pr-merge-base-v1\n{}\n{base}\n{head}",
            repository.url.trim_end_matches('/')
        );
        if let Some(cached) = cache_read(&key, CacheLife::Immutable) {
            let cached = String::from_utf8_lossy(trim_ascii(&cached)).into_owned();
            if is_commit_oid(&cached) {
                return Some(cached);
            }
        }
        let output = self
            .run_gh([
                OsString::from("api"),
                OsString::from(format!(
                    "repos/{}/compare/{base}...{head}",
                    repository.name_with_owner
                )),
                OsString::from("--jq"),
                OsString::from(".merge_base_commit.sha"),
            ])
            .ok()?;
        if !output.status.success() || output.stdout_truncated {
            return None;
        }
        let sha = String::from_utf8_lossy(trim_ascii(&output.stdout)).into_owned();
        if !is_commit_oid(&sha) {
            return None;
        }
        cache_write(&key, sha.as_bytes());
        Some(sha)
    }

    pub(super) fn run_gh<I, S>(&self, args: I) -> Result<BoundedOutput>
    where
        I: IntoIterator<Item = S>,
        S: AsRef<OsStr>,
    {
        self.run_gh_bounded(args, MAX_GH_METADATA_BYTES)
    }

    #[doc = " Metadata responses are small and share one cap, but a check run log is"]
    #[doc = " arbitrarily large and needs its own."]
    pub(super) fn run_gh_bounded<I, S>(&self, args: I, stdout_limit: usize) -> Result<BoundedOutput>
    where
        I: IntoIterator<Item = S>,
        S: AsRef<OsStr>,
    {
        let mut command = self.github_command();
        let _ = command
            .current_dir(&self.root)
            .args(args)
            .env_remove("GH_FORCE_TTY")
            .env("GH_PROMPT_DISABLED", "1")
            .env("GH_PAGER", "cat")
            .env("GH_NO_UPDATE_NOTIFIER", "1")
            .env("NO_COLOR", "1")
            .env("GIT_TERMINAL_PROMPT", "0")
            .env("GIT_EDITOR", "true")
            .env("GIT_SEQUENCE_EDITOR", "true")
            .env("EDITOR", "true")
            .env("VISUAL", "true");
        run_bounded_command(&mut command, stdout_limit, MAX_GH_ERROR_BYTES).with_context(|| {
            format!(
                "failed to execute GitHub CLI (`gh`) in {}; install it and run `gh auth login`",
                self.root.display()
            )
        })
    }

    pub(super) fn run_gh_with_input<I, S>(
        &self,
        args: I,
        input: &[u8],
        stdout_limit: usize,
    ) -> Result<BoundedOutput>
    where
        I: IntoIterator<Item = S>,
        S: AsRef<OsStr>,
    {
        let mut command = self.github_command();
        let _ = command
            .current_dir(&self.root)
            .args(args)
            .env_remove("GH_FORCE_TTY")
            .env("GH_PROMPT_DISABLED", "1")
            .env("GH_PAGER", "cat")
            .env("GH_NO_UPDATE_NOTIFIER", "1")
            .env("NO_COLOR", "1")
            .env("GIT_TERMINAL_PROMPT", "0")
            .env("GIT_EDITOR", "true")
            .env("GIT_SEQUENCE_EDITOR", "true")
            .env("EDITOR", "true")
            .env("VISUAL", "true");
        process::run_bounded_command_with_input(
            &mut command,
            input,
            stdout_limit,
            MAX_GH_ERROR_BYTES,
        )
        .with_context(|| {
            format!(
                "failed to execute GitHub CLI (`gh`) in {}; install it and run `gh auth login`",
                self.root.display()
            )
        })
    }
}

#[expect(
    clippy::too_many_lines,
    reason = "the match is the exhaustive non-interactive GitHub argument mapping"
)]
pub(super) fn pull_request_operation_args(
    pull_request: &PullRequest,
    operation: &PullRequestOperation,
) -> Vec<OsString> {
    if matches!(operation, PullRequestOperation::Dequeue) {
        return pull_request_graphql_args(
            pull_request,
            "mutation($id:ID!){dequeuePullRequest(input:{id:$id}){mergeQueueEntry{id}}}",
        );
    }
    if let PullRequestOperation::Subscribe(subscribe) = operation {
        let mut args = pull_request_graphql_args(
            pull_request,
            "mutation($id:ID!,$state:SubscriptionState!){updateSubscription(input:{subscribableId:$id,state:$state}){subscribable{viewerSubscription}}}",
        );
        args.push(OsString::from("-f"));
        args.push(OsString::from(if *subscribe {
            "state=SUBSCRIBED"
        } else {
            "state=UNSUBSCRIBED"
        }));
        return args;
    }
    if let PullRequestOperation::SetMaintainerEdits(enabled) = operation {
        let mut args = pull_request_graphql_args(
            pull_request,
            "mutation($id:ID!,$enabled:Boolean!){updatePullRequest(input:{pullRequestId:$id,maintainerCanModify:$enabled}){pullRequest{maintainerCanModify}}}",
        );
        args.push(OsString::from("-F"));
        args.push(OsString::from(format!("enabled={enabled}")));
        return args;
    }
    let command = match operation {
        PullRequestOperation::Merge { .. } | PullRequestOperation::DisableAutoMerge => "merge",
        PullRequestOperation::SetDraft(_) => "ready",
        PullRequestOperation::Review { .. } => "review",
        PullRequestOperation::Comment { .. } => "comment",
        PullRequestOperation::Edit(_) => "edit",
        PullRequestOperation::UpdateBranch(_) => "update-branch",
        PullRequestOperation::Lock(_) => "lock",
        PullRequestOperation::Unlock => "unlock",
        PullRequestOperation::Revert { .. } => "revert",
        PullRequestOperation::Close => "close",
        PullRequestOperation::Reopen => "reopen",
        PullRequestOperation::Dequeue
        | PullRequestOperation::Subscribe(_)
        | PullRequestOperation::SetMaintainerEdits(_) => return Vec::new(),
    };
    let mut args = vec![
        OsString::from("pr"),
        OsString::from(command),
        OsString::from(pull_request.number.to_string()),
        OsString::from("--repo"),
        OsString::from(&pull_request.base_repository.url),
    ];
    match operation {
        PullRequestOperation::Merge {
            method,
            mode,
            delete_branch,
        } => {
            args.push(OsString::from(method.flag()));
            match mode {
                PullRequestMergeMode::Direct => {}
                PullRequestMergeMode::Auto => args.push(OsString::from("--auto")),
                PullRequestMergeMode::Admin => args.push(OsString::from("--admin")),
            }
            if !pull_request.head_oid.is_empty() {
                args.push(OsString::from("--match-head-commit"));
                args.push(OsString::from(&pull_request.head_oid));
            }
            if *delete_branch {
                args.push(OsString::from("--delete-branch"));
            }
        }
        PullRequestOperation::SetDraft(draft) => {
            if *draft {
                args.push(OsString::from("--undo"));
            }
        }
        PullRequestOperation::Review { kind, body } => {
            args.push(OsString::from(kind.flag()));
            if !body.is_empty() {
                args.push(OsString::from("--body"));
                args.push(OsString::from(body));
            }
        }
        PullRequestOperation::Comment { mode, body } => match mode {
            PullRequestCommentMode::Create => {
                args.push(OsString::from("--body"));
                args.push(OsString::from(body));
            }
            PullRequestCommentMode::EditLast => {
                args.push(OsString::from("--edit-last"));
                args.push(OsString::from("--body"));
                args.push(OsString::from(body));
            }
            PullRequestCommentMode::DeleteLast => {
                args.push(OsString::from("--delete-last"));
                args.push(OsString::from("--yes"));
            }
        },
        PullRequestOperation::Edit(edit) => edit.append_args(&mut args),
        PullRequestOperation::UpdateBranch(PullRequestUpdateMethod::Rebase) => {
            args.push(OsString::from("--rebase"));
        }
        PullRequestOperation::Lock(reason) => {
            if let Some(reason) = reason {
                args.push(OsString::from("--reason"));
                args.push(OsString::from(reason.flag()));
            }
        }
        PullRequestOperation::Revert { draft, title, body } => {
            if *draft {
                args.push(OsString::from("--draft"));
            }
            if !title.is_empty() {
                args.push(OsString::from("--title"));
                args.push(OsString::from(title));
            }
            if !body.is_empty() {
                args.push(OsString::from("--body"));
                args.push(OsString::from(body));
            }
        }
        PullRequestOperation::UpdateBranch(PullRequestUpdateMethod::Merge)
        | PullRequestOperation::DisableAutoMerge
        | PullRequestOperation::Unlock
        | PullRequestOperation::Close
        | PullRequestOperation::Reopen
        | PullRequestOperation::Dequeue
        | PullRequestOperation::Subscribe(_)
        | PullRequestOperation::SetMaintainerEdits(_) => {}
    }
    if matches!(operation, PullRequestOperation::DisableAutoMerge) {
        args.push(OsString::from("--disable-auto"));
    }
    args
}

fn pull_request_graphql_args(pull_request: &PullRequest, query: &str) -> Vec<OsString> {
    vec![
        OsString::from("api"),
        OsString::from("graphql"),
        OsString::from("--hostname"),
        OsString::from(pull_request.base_repository.host()),
        OsString::from("-f"),
        OsString::from(format!("id={}", pull_request.action_state.node_id)),
        OsString::from("-f"),
        OsString::from(format!("query={query}")),
    ]
}