plannotator-tui 0.15.1

Annotate Markdown in the terminal - standalone, and as a Herdr plugin.
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
//! Posting a pull request review's notes to GitHub, against the simulated GitHub of
//! `pull_flow`: the `gh` stand-in answers `gh pr view` from `view.json` and records every
//! `gh api` call (its arguments, and the JSON on its stdin) instead of reaching GitHub.

use plannotator_tui_review::CodeAnnotation;
use ratatui::crossterm::event::KeyModifiers;

use super::inline_flow::set_notes;
use super::pull_flow::{Pull, URL, git_in};
use super::*;
use crate::config::review::Notes;
use crate::review::Mode;

const REVIEW_URL: &str = "https://github.com/o/app/pull/7#pullrequestreview-42";

impl Pull {
    /// Make the `gh` stand-in answer `gh api` with `stdout`, `stderr` and `exit`, recording
    /// each call's arguments in `api-args` and its stdin as one line of `api-requests.jsonl`.
    fn answer_api(&self, stdout: &str, stderr: &str, exit: i32) {
        let dir = self.dir.display().to_string();
        std::fs::write(self.dir.join("api-stdout"), stdout).expect("stdout");
        std::fs::write(self.dir.join("api-stderr"), stderr).expect("stderr");
        let script = format!(
            "#!/bin/sh\nif [ \"$1\" = api ]; then\n  printf '%s\\n' \"$@\" >> '{dir}/api-args'\n  cat >> '{dir}/api-requests.jsonl'\n  echo >> '{dir}/api-requests.jsonl'\n  cat '{dir}/api-stdout'\n  cat '{dir}/api-stderr' >&2\n  exit {exit}\nfi\ncat '{dir}/view.json'\n"
        );
        crate::test_support::write_script(&self.dir.join("gh"), &script);
    }

    fn answer_created(&self) {
        let reply = serde_json::json!({"id": 42, "html_url": REVIEW_URL, "state": "COMMENTED"});
        self.answer_api(&reply.to_string(), "", 0);
    }

    /// Every review `gh api` was handed, in order.
    fn requests(&self) -> Vec<serde_json::Value> {
        std::fs::read_to_string(self.dir.join("api-requests.jsonl"))
            .unwrap_or_default()
            .lines()
            .filter(|l| !l.trim().is_empty())
            .map(|l| serde_json::from_str(l).expect("JSON"))
            .collect()
    }
}

fn ctrl_g(screen: &mut Screen) {
    screen.handle_event(Event::Key(KeyEvent::new(KeyCode::Char('g'), KeyModifiers::CONTROL))).expect("key");
}

/// Tick until `done` holds of the summary, as the event loop would.
fn tick_until(screen: &mut Screen, done: impl Fn(&crate::review::post::Confirm) -> bool) {
    let started = Instant::now();
    loop {
        screen.tick().expect("tick");
        match &screen.mode {
            Mode::Post(confirm) if !done(confirm) => {}
            _ => return,
        }
        assert!(started.elapsed() < Duration::from_secs(10), "gh never answered");
        std::thread::sleep(Duration::from_millis(5));
    }
}

/// `ctrl+g`, the PR checked, and the summary drawn: what the person sees before `Enter`.
fn summary(screen: &mut Screen) -> Vec<String> {
    ctrl_g(screen);
    tick_until(screen, |c| c.head != crate::review::post::Head::Checking);
    frame(screen, 120, 40)
}

/// `Enter` on the summary, then GitHub's answer.
fn post_it(screen: &mut Screen) {
    press(screen, KeyCode::Enter);
    tick_until(screen, |c| !c.posting);
}

fn comment_on(screen: &mut Screen, side: Side, line: u32, text: &str) {
    screen.diff.reveal("app.py", side, line).expect("in the diff");
    keys(screen, "c");
    type_and_save(screen, text);
}

/// A line comment, a range, an old-side comment, a suggestion, a file note, a whole-change
/// note and a note outside the diff.
fn every_kind_of_note(screen: &mut Screen) {
    comment_on(screen, Side::New, 5, "say hello properly");
    at(screen, 9);
    keys(screen, "vjv");
    keys(screen, "c");
    type_and_save(screen, "name the total");
    comment_on(screen, Side::Old, 10, "why drop the default?");
    at(screen, 14);
    keys(screen, "s");
    press(screen, KeyCode::End);
    type_and_save(screen, "  # from argv");
    keys(screen, "C");
    type_and_save(screen, "split this file");
    keys(screen, "M");
    type_and_save(screen, "please add a test");
    let outside = CodeAnnotation::outside_diff_comment(
        "app.py",
        15,
        15,
        "    print(add(1, 2))".into(),
        "is this still needed?".into(),
        &screen.capture.patch_key,
    );
    screen.store.add(outside).expect("adds");
}

#[test]
fn ctrl_g_shows_a_summary_and_posts_one_review_only_on_enter() {
    let pull = Pull::new("post");
    pull.answer_created();
    let mut screen = pull.open();
    every_kind_of_note(&mut screen);
    let head = git_in(&pull.work(), &["rev-parse", "feature"]);

    let rows = summary(&mut screen);
    assert!(matches!(screen.mode, Mode::Post(_)), "{:?}", screen.status);
    if let Some(dir) = std::env::var_os("POST_GH_PROOF_DIR") {
        std::fs::create_dir_all(&dir).expect("proof dir");
        std::fs::write(PathBuf::from(dir).join("summary.txt"), rows.join("\n")).expect("proof");
    }
    row_with(&rows, "post to GitHub");
    assert!(row_with(&rows, "o/app#7").contains("feat: greet from argv"));
    row_with(&rows, &format!("anchored to {}, the commit you reviewed", &head[..7]));
    row_with(&rows, "4 inline comments");
    row_with(&rows, "3 in the review body:");
    row_with(&rows, "  1 whole-change note");
    row_with(&rows, "  1 file note");
    row_with(&rows, "  1 note outside the diff, quoted with a link");
    assert!(row_with(&rows, "verdict").contains("(\u{2022}) Comment"));
    row_with(&rows, "enter posts");
    assert_eq!(pull.requests().len(), 0, "nothing leaves before Enter");

    press(&mut screen, KeyCode::Enter);
    row_with(&frame(&mut screen, 120, 40), "Posting to GitHub\u{2026}");
    tick_until(&mut screen, |c| !c.posting);
    assert_eq!(screen.mode, Mode::Browse);
    let [request] = pull.requests().try_into().expect("one request");
    let args = read(&pull.dir.join("api-args"));
    assert_eq!(args, "api\n--method\nPOST\nrepos/o/app/pulls/7/reviews\n--input\n-\n");
    assert_eq!(request["commit_id"], head.as_str());
    assert_eq!(request["event"], "COMMENT");
    assert_eq!(
        request["comments"],
        serde_json::json!([
            {"path": "app.py", "line": 5, "side": "RIGHT", "body": "say hello properly"},
            {"path": "app.py", "line": 10, "side": "RIGHT", "start_line": 9, "start_side": "RIGHT", "body": "name the total"},
            {"path": "app.py", "line": 10, "side": "LEFT", "body": "why drop the default?"},
            {"path": "app.py", "line": 14, "side": "RIGHT", "body": "```suggestion\n    greet(sys.argv[1])  # from argv\n```"},
        ])
    );
    let body = request["body"].as_str().expect("a body");
    assert!(
        body.starts_with(
            "**app.py:** split this file\n\nplease add a test\n\n**Comments outside the diff**\n\n"
        ),
        "{body}"
    );
    assert!(body.contains(&format!("[app.py (L15)]({URL}/blob/{head}/app.py#L15)")), "{body}");

    let status = screen.status.clone().unwrap_or_default();
    assert_eq!(status, format!("posted to GitHub: 4 inline, 3 in the body \u{b7} {REVIEW_URL}"));
    open_notes(&mut screen);
    let rows = frame(&mut screen, 120, 40);
    assert!(rows[39].contains(REVIEW_URL) || rows[38].contains(REVIEW_URL), "the footer shows the link");
    row_with(&rows, "5 new \u{b7} posted");
    let record: serde_json::Value = serde_json::from_str(&read(screen.store.path())).expect("JSON");
    assert_eq!(record["posted"][0]["url"], REVIEW_URL);
    assert_eq!(record["posted"][0]["commitId"], head.as_str());
    assert_eq!(record["posted"][0]["annotationIds"].as_array().map(Vec::len), Some(7));
    assert_eq!(pull.agent.sent.borrow().len(), 0, "posting is not sending to the agent");
}

#[test]
fn esc_on_the_summary_posts_nothing() {
    let pull = Pull::new("post-esc");
    pull.answer_created();
    let mut screen = pull.open();
    comment_on(&mut screen, Side::New, 9, "name the total");
    ctrl_g(&mut screen);
    keys(&mut screen, "l");
    let Mode::Post(confirm) = &screen.mode else { panic!("the summary") };
    assert_eq!(confirm.event, plannotator_tui_review::Event::Approve, "an explicit choice");
    press(&mut screen, KeyCode::Esc);
    assert_eq!(screen.mode, Mode::Browse);
    assert_eq!(pull.requests().len(), 0);
    assert_eq!(screen.status.as_deref(), Some("nothing posted to GitHub"));
    assert!(!screen.store.is_posted(&screen.store.annotations()[0]));
}

#[test]
fn a_later_post_carries_only_new_and_edited_notes() {
    let pull = Pull::new("post-again");
    pull.answer_created();
    let mut screen = pull.open();
    comment_on(&mut screen, Side::New, 5, "say hello properly");
    comment_on(&mut screen, Side::New, 9, "name the total");
    summary(&mut screen);
    post_it(&mut screen);
    ctrl_g(&mut screen);
    assert_eq!(screen.mode, Mode::Browse);
    assert_eq!(screen.status.as_deref(), Some("nothing new to post to GitHub (2 already posted)"));

    // Edit the note on line 9 and add one on line 14.
    let edited = screen.store.annotations().iter().find(|n| n.line_start == 9).expect("note").id.clone();
    screen
        .store
        .edit(&edited, |n| {
            n.text = Some("call it total".into());
            true
        })
        .expect("edits");
    comment_on(&mut screen, Side::New, 14, "check argv");
    let rows = summary(&mut screen);
    row_with(&rows, "2 inline comments");
    row_with(&rows, "1 edited since posted: posted again as new comments");
    row_with(&rows, "skipped: 1 already posted");
    post_it(&mut screen);
    let requests = pull.requests();
    let [_, second] = requests.as_slice() else { panic!("two posts: {requests:?}") };
    let bodies: Vec<&str> =
        second["comments"].as_array().expect("comments").iter().filter_map(|c| c["body"].as_str()).collect();
    assert_eq!(bodies, ["call it total", "check argv"]);
}

#[test]
fn a_refused_post_posts_nothing_and_names_the_comments() {
    let pull = Pull::new("post-refused");
    pull.answer_api(
        r#"{"message":"Unprocessable Entity","errors":["Line could not be resolved"],"status":"422"}"#,
        "gh: Unprocessable Entity (HTTP 422)\n",
        1,
    );
    let mut screen = pull.open();
    comment_on(&mut screen, Side::New, 9, "name the total");
    comment_on(&mut screen, Side::Old, 10, "why drop the default?");
    summary(&mut screen);
    post_it(&mut screen);
    let Mode::Post(confirm) = &screen.mode else { panic!("the summary stays open") };
    let failed = confirm.failed.clone().expect("a reason");
    assert_eq!(
        failed,
        "Nothing was posted: GitHub refused the place of an inline comment (Unprocessable Entity: Line could \
         not be resolved). The inline comments, each checked against the diff you reviewed, were on app.py:9 \
         new, app.py:10 old."
    );
    let rows = frame(&mut screen, 120, 40);
    row_with(&rows, "Nothing was posted");
    assert_eq!(screen.store.posts(), []);
    assert!(screen.store.annotations().iter().all(|n| !screen.store.is_posted(n)));
    assert_eq!(screen.status.as_deref(), Some("nothing posted to GitHub: GitHub refused a comment's place"));
}

#[test]
fn gh_errors_are_named_and_post_nothing() {
    let cases = [
        ("", "To get started with GitHub CLI, please run:  gh auth login\n", "gh is not logged in to GitHub"),
        (
            r#"{"message":"Resource not accessible by integration"}"#,
            "gh: Resource not accessible by integration (HTTP 403)\n",
            "your GitHub login cannot review this pull request",
        ),
        (
            r#"{"message":"API rate limit exceeded for user ID 1."}"#,
            "gh: API rate limit exceeded for user ID 1. (HTTP 403)\n",
            "GitHub's rate limit was reached",
        ),
        ("", "error connecting to api.github.com\n", "could not reach GitHub"),
    ];
    for (stdout, stderr, says) in cases {
        let pull = Pull::new("post-errors");
        pull.answer_api(stdout, stderr, 1);
        let mut screen = pull.open();
        comment_on(&mut screen, Side::New, 9, "name the total");
        summary(&mut screen);
        post_it(&mut screen);
        let Mode::Post(confirm) = &screen.mode else { panic!("the summary stays open") };
        let failed = confirm.failed.clone().unwrap_or_default();
        assert!(failed.starts_with(&format!("Nothing was posted: {says}")), "{failed}");
        assert_eq!(screen.store.posts(), []);
    }
}

#[test]
fn when_the_pr_moved_on_the_summary_says_so_and_comments_stay_on_the_reviewed_commit() {
    let pull = Pull::new("post-moved");
    pull.answer_created();
    let mut screen = pull.open();
    let reviewed = git_in(&pull.work(), &["rev-parse", "feature"]);
    comment_on(&mut screen, Side::New, 9, "name the total");
    pull.push_head(&format!("# greeter\n{AFTER}"));
    let now = git_in(&pull.work(), &["rev-parse", "feature"]);
    let rows = summary(&mut screen);
    let moved = rows.iter().find(|r| r.contains("The PR moved on")).expect("the warning");
    assert!(moved.contains(&now[..7]), "{moved}");
    post_it(&mut screen);
    let [request] = pull.requests().try_into().expect("one request");
    assert_eq!(request["commit_id"], reviewed.as_str());
    assert_eq!(request["comments"][0]["line"], 9);
}

#[test]
fn the_review_menu_offers_it_and_outside_a_pr_it_says_why_not() {
    let pull = Pull::new("post-menu");
    pull.answer_created();
    let mut screen = pull.open();
    comment_on(&mut screen, Side::New, 9, "name the total");
    keys(&mut screen, "m");
    let rows = frame(&mut screen, 120, 40);
    assert!(row_with(&rows, "Post to GitHub\u{2026} \u{b7} 1 new").contains("ctrl+g"));
    keys(&mut screen, "j");
    press(&mut screen, KeyCode::Enter);
    assert!(matches!(screen.mode, Mode::Post(_)));

    let fixture = Fixture::new("post-local");
    let mut local = fixture.open();
    keys(&mut local, "m");
    let rows = frame(&mut local, 120, 40);
    row_with(&rows, "Post to GitHub\u{2026} \u{b7} pull requests only");
    press(&mut local, KeyCode::Esc);
    ctrl_g(&mut local);
    assert_eq!(local.mode, Mode::Browse);
    assert_eq!(
        local.status.as_deref(),
        Some(
            "Post to GitHub needs a pull request review (plannotator-tui review <PR>); this one is Uncommitted"
        )
    );
}

#[test]
fn a_note_both_sent_and_posted_says_so_even_when_its_title_has_no_room() {
    let pull = Pull::new("post-both");
    pull.answer_created();
    let mut screen = pull.open();
    let outside = CodeAnnotation::outside_diff_comment(
        "app.py",
        14,
        15,
        "    greet(sys.argv[1])\n    print(add(1, 2))".into(),
        "both lines?".into(),
        &screen.capture.patch_key,
    );
    screen.store.add(outside).expect("adds");
    keys(&mut screen, "E");
    summary(&mut screen);
    post_it(&mut screen);
    open_notes(&mut screen);
    let rows = frame(&mut screen, 120, 40);
    let title = row_with(&rows, "app.py 14-15 new");
    assert!(title.trim_end().ends_with('\u{256e}'), "the border is whole: {title}");
    let below = rows.iter().position(|r| r.contains("app.py 14-15 new")).map(|i| &rows[i + 1]).expect("row");
    assert!(below.contains("sent \u{b7} posted"), "{rows:#?}");
}

/// Notes drawn in the diff (the inline setting) say they were posted, as the rail does.
#[test]
fn an_inline_box_says_its_note_was_posted() {
    let pull = Pull::new("post-inline");
    pull.answer_created();
    let mut screen = pull.open();
    set_notes(&mut screen, Notes::Inline);
    comment_on(&mut screen, Side::New, 5, "say hello properly");
    let rows = frame(&mut screen, 120, 40);
    assert!(!row_with(&rows, "comment \u{b7} L5").contains("posted"), "{rows:#?}");
    summary(&mut screen);
    post_it(&mut screen);
    let rows = frame(&mut screen, 120, 40);
    assert!(row_with(&rows, "comment \u{b7} L5").contains("\u{b7} posted"), "{rows:#?}");
}

/// GitHub takes a review on a closed or merged PR (it did on a real one), so the summary says
/// which before Enter.
#[test]
fn the_summary_says_when_the_pr_is_merged() {
    let pull = Pull::new("post-merged");
    pull.answer_created();
    let mut screen = pull.open();
    comment_on(&mut screen, Side::New, 5, "say hello properly");
    let path = pull.dir.join("view.json");
    let mut view: serde_json::Value = serde_json::from_str(&read(&path)).expect("JSON");
    view["state"] = "MERGED".into();
    std::fs::write(&path, view.to_string()).expect("view.json");
    let rows = summary(&mut screen);
    row_with(&rows, "The PR is merged. GitHub still takes a review on it.");
    post_it(&mut screen);
    assert_eq!(pull.requests().len(), 1, "it still posts");
}

/// The summary is what the person says yes to: an `Enter` that came before it was on screen
/// (typed ahead while GitHub was asked about the PR, or a double press) posts nothing.
#[test]
fn enter_before_the_summary_is_on_screen_posts_nothing() {
    let pull = Pull::new("post-early");
    pull.answer_created();
    let mut screen = pull.open();
    comment_on(&mut screen, Side::New, 9, "name the total");
    ctrl_g(&mut screen);
    press(&mut screen, KeyCode::Enter);
    tick_until(&mut screen, |c| c.head != crate::review::post::Head::Checking);
    press(&mut screen, KeyCode::Enter);
    // The menu, with Enter pressed twice in a row.
    press(&mut screen, KeyCode::Esc);
    keys(&mut screen, "mj");
    press(&mut screen, KeyCode::Enter);
    press(&mut screen, KeyCode::Enter);
    tick_until(&mut screen, |c| c.head != crate::review::post::Head::Checking);
    press(&mut screen, KeyCode::Enter);
    assert_eq!(pull.requests().len(), 0, "no frame showed the summary: nothing posted");
    let Mode::Post(confirm) = &screen.mode else { panic!("the summary waits") };
    assert!(!confirm.shown && !confirm.posting);
    // Drawn once: the keys waiting are dropped, and the next Enter posts.
    let _ = frame(&mut screen, 120, 40);
    assert!(!screen.after_draw(), "only the first frame drops the waiting keys");
    post_it(&mut screen);
    assert_eq!(pull.requests().len(), 1);
}

/// A post whose answer never came back may exist on GitHub: say so, and mark nothing posted.
#[test]
fn a_post_with_no_clear_answer_may_have_been_posted() {
    let pull = Pull::new("post-unsure");
    pull.answer_api("", "gh: Bad Gateway (HTTP 502)\n", 1);
    let mut screen = pull.open();
    comment_on(&mut screen, Side::New, 9, "name the total");
    summary(&mut screen);
    post_it(&mut screen);
    let Mode::Post(confirm) = &screen.mode else { panic!("the summary stays open") };
    let failed = confirm.failed.clone().unwrap_or_default();
    assert!(failed.starts_with("This may have been posted: GitHub's answer did not come back"), "{failed}");
    assert!(failed.ends_with(&format!("before you post again: {URL}/pull/7")), "{failed}");
    assert_eq!(screen.status.as_deref(), Some("may have been posted to GitHub: check the pull request"));
    assert_eq!(screen.store.posts(), []);
    // An Enter typed while it was posting does not answer a message not yet drawn.
    press(&mut screen, KeyCode::Enter);
    assert_eq!(pull.requests().len(), 1, "the message was not on screen: no second post");
    let _ = frame(&mut screen, 120, 40);
    post_it(&mut screen);
    assert_eq!(pull.requests().len(), 2, "read, then Enter: the person chose to post again");
}

/// A note longer than GitHub takes is named in the summary, before Enter, and nothing goes.
#[test]
fn a_note_too_long_for_github_is_named_before_posting() {
    let pull = Pull::new("post-long");
    pull.answer_created();
    let mut screen = pull.open();
    comment_on(&mut screen, Side::New, 5, "short for now");
    let id = screen.store.annotations()[0].id.clone();
    let long = "x".repeat(plannotator_tui_review::post::MAX_BODY_CHARS + 1);
    screen
        .store
        .edit(&id, |n| {
            n.text = Some(long.clone());
            true
        })
        .expect("edits");
    let rows = summary(&mut screen);
    row_with(&rows, "The note on app.py:5 new is 65537 characters; GitHub takes");
    post_it(&mut screen);
    assert_eq!(pull.requests().len(), 0);
    let Mode::Post(confirm) = &screen.mode else { panic!("the summary stays open") };
    assert_eq!(confirm.failed.as_deref(), Some("Nothing was posted: shorten the notes named above first."));
}