croft-software 0.2.132

VSCode-style TUI written in Rust
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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
//! The write side of PR review in the editor (#366): reply to a thread,
//! resolve or unresolve it, and submit a review with the comments written
//! in croft. Each is a `gh` call run off the frame loop; [`run`] does the
//! work and returns what the app should show.

use crate::review_threads::{PendingComment, ReviewEvent};
use std::io::Write as _;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};

/// What a posted export settles once it lands: navigator notes to remove
/// and sticky notes to mark resolved. It rides the job and comes back in
/// its outcome, so only the submission that carried them can settle them.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Settles {
    pub notes: Vec<u64>,
    pub sticky: Vec<String>,
    /// The pending comments this submission posted: only these leave the
    /// pending list, so one written while it ran is kept.
    pub pending: Vec<PendingComment>,
}

#[derive(Clone, Debug)]
pub enum Job {
    Reply {
        number: String,
        thread: u64,
        text: String,
    },
    Resolve {
        thread: u64,
        node: String,
        resolve: bool,
    },
    Submit {
        number: String,
        event: ReviewEvent,
        summary: String,
        pending: Vec<PendingComment>,
        settles: Settles,
    },
    /// Find the branch's PR and read `rel`'s review threads with their
    /// resolution (#366). `path` rides along so the threads land on the file
    /// they were read for.
    LoadThreads { path: PathBuf, rel: String },
    /// Find the branch's PR and count which of `comments` GitHub will take
    /// inline, for the export preview (#368).
    ExportPreview {
        comments: Vec<PendingComment>,
        notes: Vec<u64>,
    },
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Outcome {
    Replied {
        thread: u64,
        text: String,
    },
    Resolved {
        thread: u64,
        resolved: bool,
    },
    Submitted {
        inline: usize,
        folded: usize,
        settles: Settles,
    },
    Threads {
        root: PathBuf,
        number: String,
        path: PathBuf,
        rel: String,
        threads: Vec<crate::review_threads::Thread>,
        /// Thread id to (GraphQL node id, resolved).
        states: std::collections::HashMap<u64, (String, bool)>,
    },
    ExportReady {
        root: PathBuf,
        number: String,
        comments: Vec<PendingComment>,
        notes: Vec<u64>,
        inline: usize,
    },
    /// No PR for the branch; the status says so.
    NoPr,
    /// A submission failed: the next one may go.
    SubmitFailed(String),
    /// Any other job failed; nothing was in flight on its account.
    Failed(String),
}

/// `gh api --paginate` prints each page's JSON array back to back
/// (`[...][...]`), which no JSON parser reads as one value: join the pages
/// into one array. A single page comes back as it was.
fn flatten_pages(json: &str) -> String {
    let mut all = Vec::new();
    for page in serde_json::Deserializer::from_str(json).into_iter::<serde_json::Value>() {
        match page {
            Ok(serde_json::Value::Array(items)) => all.extend(items),
            _ => return json.to_string(),
        }
    }
    serde_json::Value::Array(all).to_string()
}

/// The PR number for the branch checked out in `root`, if it has one; or
/// why gh could not tell (#917).
fn pr_number(program: &str, root: &Path) -> Result<Option<String>, String> {
    match gh(
        program,
        root,
        &["pr", "view", "--json", "number", "--jq", ".number"],
        None,
    ) {
        Ok(n) => Ok(Some(n.trim().to_string()).filter(|n| !n.is_empty())),
        Err(why) if crate::gh::unusable(&why) => {
            Err(format!("Could not find this branch's PR: {why}"))
        }
        Err(_) => Ok(None),
    }
}

/// gh's first stderr line, which names the problem (scope, rate limit, a
/// line outside the diff) better than anything croft could say; or that
/// gh has no account signed in (#917).
fn gh_error(out: &std::process::Output) -> String {
    if crate::gh::signed_out(out.status) {
        return String::from(crate::gh::SIGNED_OUT);
    }
    let err = String::from_utf8_lossy(&out.stderr);
    err.trim().lines().next().unwrap_or("gh failed").to_string()
}

/// Spawn `cmd`, trying again for a moment while its program is "Text file
/// busy" (ETXTBSY). A file just written is busy while any process forked
/// meanwhile still holds the write descriptor, until that child execs,
/// which takes microseconds. A freshly installed or updated `gh` can hit it,
/// and a test's stand-in script hits it whenever another test forks.
pub(crate) fn spawn_retrying_busy(cmd: &mut Command) -> std::io::Result<std::process::Child> {
    retry_while_busy(|| cmd.spawn(), |r| r.as_ref().is_err_and(text_file_busy))
}

/// [`Command::output`] through [`spawn_retrying_busy`]: stdin closed, stdout
/// and stderr captured, waiting out a moment of "Text file busy".
pub(crate) fn output_retrying_busy(cmd: &mut Command) -> std::io::Result<std::process::Output> {
    cmd.stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped());
    spawn_retrying_busy(cmd)?.wait_with_output()
}

/// Whether a spawn failed because its program is "Text file busy" (ETXTBSY).
pub(crate) fn text_file_busy(e: &std::io::Error) -> bool {
    const ETXTBSY: i32 = 26;
    e.raw_os_error() == Some(ETXTBSY)
}

/// Call `attempt` again, 10 ms apart and at most 50 more times, while `busy`
/// says its result is a moment of "Text file busy". Nothing `attempt` takes
/// is held across the pause, so a caller that spawns under a lock lets
/// others in between tries.
pub(crate) fn retry_while_busy<R>(mut attempt: impl FnMut() -> R, busy: impl Fn(&R) -> bool) -> R {
    let mut tries = 0;
    loop {
        let result = attempt();
        if tries >= 50 || !busy(&result) {
            return result;
        }
        tries += 1;
        std::thread::sleep(std::time::Duration::from_millis(10));
    }
}

fn gh(program: &str, root: &Path, args: &[&str], stdin: Option<&str>) -> Result<String, String> {
    let mut cmd = Command::new(program);
    cmd.args(args)
        .current_dir(root)
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .stdin(if stdin.is_some() {
            Stdio::piped()
        } else {
            Stdio::null()
        });
    let mut child =
        spawn_retrying_busy(&mut cmd).map_err(|e| crate::gh::spawn_error(&e, Some(root)))?;
    if let (Some(input), Some(mut pipe)) = (stdin, child.stdin.take()) {
        let _ = pipe.write_all(input.as_bytes());
    }
    let out = child
        .wait_with_output()
        .map_err(|e| format!("gh failed: {e}"))?;
    if out.status.success() {
        Ok(String::from_utf8_lossy(&out.stdout).into_owned())
    } else {
        Err(gh_error(&out))
    }
}

/// Carry out `job` with `program` (normally `gh`) in `root`.
pub fn run(program: &str, root: &Path, job: Job) -> Outcome {
    match job {
        Job::Reply {
            number,
            thread,
            text,
        } => {
            let endpoint =
                format!("repos/{{owner}}/{{repo}}/pulls/{number}/comments/{thread}/replies");
            let body = format!("body={text}");
            match gh(
                program,
                root,
                &["api", "-X", "POST", &endpoint, "-f", &body],
                None,
            ) {
                Ok(_) => Outcome::Replied { thread, text },
                Err(e) => Outcome::Failed(format!("Reply failed: {e}")),
            }
        }
        Job::Resolve {
            thread,
            node,
            resolve,
        } => {
            let query = format!("query={}", crate::review_threads::resolve_mutation(resolve));
            let id = format!("id={node}");
            match gh(
                program,
                root,
                &["api", "graphql", "-f", &query, "-f", &id],
                None,
            ) {
                Ok(_) => Outcome::Resolved {
                    thread,
                    resolved: resolve,
                },
                Err(e) => Outcome::Failed(format!("Could not change the thread: {e}")),
            }
        }
        Job::Submit {
            number,
            event,
            summary,
            pending,
            settles,
        } => {
            // The diff decides which comments GitHub will take inline; a
            // failure to read it folds every comment into the summary rather
            // than risking a refused review.
            let diff = gh(program, root, &["pr", "diff", &number], None).unwrap_or_default();
            let mut lines: std::collections::HashMap<String, std::collections::HashSet<usize>> =
                std::collections::HashMap::new();
            for c in &pending {
                lines
                    .entry(c.path.clone())
                    .or_insert_with(|| crate::review_threads::commentable_lines(&diff, &c.path));
            }
            let commentable =
                |path: &str, line: usize| lines.get(path).is_some_and(|s| s.contains(&line));
            let payload =
                crate::review_threads::review_payload(event, &summary, &pending, &commentable);
            let inline = payload["comments"].as_array().map_or(0, Vec::len);
            let endpoint = format!("repos/{{owner}}/{{repo}}/pulls/{number}/reviews");
            match gh(
                program,
                root,
                &["api", "-X", "POST", &endpoint, "--input", "-"],
                Some(&payload.to_string()),
            ) {
                Ok(_) => Outcome::Submitted {
                    inline,
                    folded: pending.len() - inline,
                    settles,
                },
                Err(e) => Outcome::SubmitFailed(format!("Review not submitted: {e}")),
            }
        }
        Job::LoadThreads { path, rel } => {
            let number = match pr_number(program, root) {
                Ok(Some(number)) => number,
                Ok(None) => return Outcome::NoPr,
                Err(why) => return Outcome::Failed(why),
            };
            let endpoint = format!("repos/{{owner}}/{{repo}}/pulls/{number}/comments");
            let json = match gh(program, root, &["api", &endpoint, "--paginate"], None) {
                Ok(j) => j,
                Err(e) => return Outcome::Failed(format!("Could not read the PR's comments: {e}")),
            };
            let threads: Vec<_> = crate::review_threads::parse_threads(&flatten_pages(&json))
                .into_iter()
                .filter(|t| t.path == rel)
                .collect();
            // Resolution and the node id Resolve needs live only in GraphQL.
            // Best effort: without it every thread reads as unresolved, the
            // safe default. Every page: past 100 threads the rest would
            // otherwise lack the id Resolve needs.
            let mut states = std::collections::HashMap::new();
            let mut after: Option<String> = None;
            loop {
                let mut args = vec![
                    String::from("api"),
                    String::from("graphql"),
                    String::from("-F"),
                    String::from("owner={owner}"),
                    String::from("-F"),
                    String::from("repo={repo}"),
                    String::from("-F"),
                    format!("number={number}"),
                    String::from("-f"),
                    format!("query={}", crate::review_threads::THREADS_QUERY),
                ];
                if let Some(cursor) = &after {
                    args.push(String::from("-f"));
                    args.push(format!("after={cursor}"));
                }
                let args: Vec<&str> = args.iter().map(String::as_str).collect();
                let Ok(page) = gh(program, root, &args, None) else {
                    break;
                };
                states.extend(crate::review_threads::parse_thread_states(&page));
                match crate::review_threads::next_page(&page) {
                    Some(cursor) if after.as_deref() != Some(cursor.as_str()) => {
                        after = Some(cursor);
                    }
                    _ => break,
                }
            }
            Outcome::Threads {
                root: root.to_path_buf(),
                number,
                path,
                rel,
                threads,
                states,
            }
        }
        Job::ExportPreview { comments, notes } => {
            let number = match pr_number(program, root) {
                Ok(Some(number)) => number,
                Ok(None) => return Outcome::NoPr,
                Err(why) => return Outcome::Failed(why),
            };
            // Which comments GitHub will take inline, so one folded into the
            // summary is no surprise after posting.
            let diff = gh(program, root, &["pr", "diff", &number], None).unwrap_or_default();
            let inline = comments
                .iter()
                .filter(|c| {
                    crate::review_threads::commentable_lines(&diff, &c.path).contains(&(c.line + 1))
                })
                .count();
            Outcome::ExportReady {
                root: root.to_path_buf(),
                number,
                comments,
                notes,
                inline,
            }
        }
    }
}

/// Run `job` on a thread; the outcome arrives on `tx`.
pub fn spawn(program: String, root: PathBuf, job: Job, tx: std::sync::mpsc::Sender<Outcome>) {
    std::thread::spawn(move || {
        let _ = tx.send(run(&program, &root, job));
    });
}

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

    #[test]
    fn paginated_comment_pages_join_into_one_array() {
        let joined: serde_json::Value =
            serde_json::from_str(&flatten_pages("[{\"id\":1}]\n[{\"id\":2}]")).unwrap();
        assert_eq!(joined.as_array().map(Vec::len), Some(2));
        assert_eq!(flatten_pages("[]"), "[]");
    }

    /// A fake `gh` that logs its arguments and stdin, answers `pr diff`
    /// with a one-hunk diff, and fails when told to.
    fn fake_gh(dir: &Path, fail: bool) -> String {
        let path = dir.join("gh");
        let script = format!(
            "#!/bin/sh\necho \"$@\" >> '{log}'\nif [ \"$1\" = pr ]; then printf 'diff --git a/a.rs b/a.rs\\n--- a/a.rs\\n+++ b/a.rs\\n@@ -1,1 +1,2 @@\\n x\\n+y\\n'; exit 0; fi\n{fail}cat > '{stdin}' 2>/dev/null\necho '{{}}'\n",
            log = dir.join("log").display(),
            stdin = dir.join("stdin").display(),
            fail = if fail {
                "echo 'HTTP 422: Unprocessable' >&2; exit 1\n"
            } else {
                ""
            },
        );
        std::fs::write(&path, script).unwrap();
        use std::os::unix::fs::PermissionsExt as _;
        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
        path.display().to_string()
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn a_program_still_open_for_writing_is_run_once_it_is_released() {
        // Exec of a file open for writing fails with ETXTBSY, as it does
        // for a stand-in script while a forked sibling holds its descriptor.
        use std::os::unix::fs::PermissionsExt as _;
        let tmp = tempfile::tempdir().unwrap();
        let path = tmp.path().join("busy");
        std::fs::write(&path, "#!/bin/sh\necho ran\n").unwrap();
        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
        let writer = std::fs::OpenOptions::new()
            .append(true)
            .open(&path)
            .unwrap();
        let busy = Command::new(&path).output().unwrap_err();
        assert_eq!(busy.raw_os_error(), Some(26), "{busy}");
        let release = std::thread::spawn(move || {
            std::thread::sleep(std::time::Duration::from_millis(50));
            drop(writer);
        });
        let mut cmd = Command::new(&path);
        cmd.stdout(Stdio::piped());
        let out = spawn_retrying_busy(&mut cmd)
            .unwrap()
            .wait_with_output()
            .unwrap();
        release.join().unwrap();
        assert_eq!(String::from_utf8_lossy(&out.stdout), "ran\n");
    }

    #[test]
    fn a_reply_posts_to_the_threads_replies_endpoint() {
        let tmp = tempfile::tempdir().unwrap();
        let gh = fake_gh(tmp.path(), false);
        let out = run(
            &gh,
            tmp.path(),
            Job::Reply {
                number: "7".into(),
                thread: 42,
                text: "fixed".into(),
            },
        );
        assert_eq!(
            out,
            Outcome::Replied {
                thread: 42,
                text: "fixed".into()
            }
        );
        let log = std::fs::read_to_string(tmp.path().join("log")).unwrap();
        assert!(
            log.contains(
                "api -X POST repos/{owner}/{repo}/pulls/7/comments/42/replies -f body=fixed"
            ),
            "{log}"
        );
    }

    #[test]
    fn a_submitted_review_sends_inline_and_folded_comments_and_the_verdict() {
        let tmp = tempfile::tempdir().unwrap();
        let gh = fake_gh(tmp.path(), false);
        let out = run(
            &gh,
            tmp.path(),
            Job::Submit {
                number: "7".into(),
                event: ReviewEvent::Approve,
                summary: "LGTM".into(),
                pending: vec![
                    PendingComment {
                        path: "a.rs".into(),
                        line: 1,
                        body: "nice".into(),
                    },
                    PendingComment {
                        path: "a.rs".into(),
                        line: 30,
                        body: "later".into(),
                    },
                ],
                settles: Settles::default(),
            },
        );
        assert_eq!(
            out,
            Outcome::Submitted {
                inline: 1,
                folded: 1,
                settles: Settles::default(),
            }
        );
        let sent: serde_json::Value =
            serde_json::from_str(&std::fs::read_to_string(tmp.path().join("stdin")).unwrap())
                .unwrap();
        assert_eq!(sent["event"], "APPROVE");
        assert_eq!(sent["comments"][0]["line"], 2);
        assert!(sent["body"].as_str().unwrap().contains("a.rs:31"));
    }

    #[test]
    fn a_refusal_reports_ghs_own_reason() {
        let tmp = tempfile::tempdir().unwrap();
        let gh = fake_gh(tmp.path(), true);
        let out = run(
            &gh,
            tmp.path(),
            Job::Resolve {
                thread: 1,
                node: "PRRT_x".into(),
                resolve: true,
            },
        );
        assert_eq!(
            out,
            Outcome::Failed("Could not change the thread: HTTP 422: Unprocessable".into())
        );
    }

    /// #917: a missing or signed-out gh is named as such, not reported as
    /// a branch without a PR or as "No such file or directory".
    #[test]
    fn a_missing_or_signed_out_gh_says_how_to_fix_it() {
        use std::os::unix::fs::PermissionsExt as _;
        let tmp = tempfile::tempdir().unwrap();
        let signed_out = tmp.path().join("signed-out-gh");
        std::fs::write(&signed_out, "#!/bin/sh\necho 'gh auth login' >&2\nexit 4\n").unwrap();
        std::fs::set_permissions(&signed_out, std::fs::Permissions::from_mode(0o755)).unwrap();
        for (gh, why) in [
            (tmp.path().join("gh"), crate::gh::MISSING),
            (signed_out, crate::gh::SIGNED_OUT),
        ] {
            let gh = gh.display().to_string();
            let load = Job::LoadThreads {
                path: tmp.path().join("a.rs"),
                rel: "a.rs".into(),
            };
            assert_eq!(
                run(&gh, tmp.path(), load),
                Outcome::Failed(format!("Could not find this branch's PR: {why}"))
            );
            let reply = Job::Reply {
                number: "7".into(),
                thread: 42,
                text: "fixed".into(),
            };
            assert_eq!(
                run(&gh, tmp.path(), reply),
                Outcome::Failed(format!("Reply failed: {why}"))
            );
        }
    }
}