diffler 0.20.0

Standalone magit-style git TUI and code reviewer, on its own or with your coding agent
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
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
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
//! Opening a pull request from the TUI: check the branch is in a state a
//! forge will accept, fill the fields from the commits the branch carries,
//! and let the human correct any of it before it goes out.

use diffler_core::vcs::{LogEntry, NetworkOp};

use super::App;
use crate::ci::NewPullRequest;

/// What the cursor sits on in the create form. The buttons are rows like the
/// fields, so the pointer and `j`/`k` reach them the same way.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PrField {
    Base,
    Title,
    Body,
    Draft,
    Create,
    Cancel,
}

impl PrField {
    pub(crate) const ORDER: [Self; 6] = [
        Self::Base,
        Self::Title,
        Self::Body,
        Self::Draft,
        Self::Create,
        Self::Cancel,
    ];

    pub(crate) fn step(self, down: bool) -> Self {
        let at = Self::ORDER.iter().position(|f| *f == self).unwrap_or(0);
        let next = if down {
            (at + 1).min(Self::ORDER.len() - 1)
        } else {
            at.saturating_sub(1)
        };
        Self::ORDER.get(next).copied().unwrap_or(Self::Title)
    }

    pub(crate) fn as_text(self) -> Option<PrTextField> {
        match self {
            Self::Title => Some(PrTextField::Title),
            Self::Body => Some(PrTextField::Body),
            Self::Base | Self::Draft | Self::Create | Self::Cancel => None,
        }
    }
}

/// The [`PrField`] rows that hold text.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PrTextField {
    Title,
    Body,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PrDraft {
    pub base: String,
    pub head: String,
    pub title: String,
    pub body: String,
    pub draft: bool,
    /// Commits `head` carries over `base`, for the form's summary line.
    pub commits: usize,
    /// The remote lacks this branch at the local commit, so creating pushes first.
    pub needs_push: bool,
    pub field: PrField,
}

impl PrDraft {
    pub(crate) fn request(&self) -> NewPullRequest {
        NewPullRequest {
            base: self.base.clone(),
            head: self.head.clone(),
            title: self.title.clone(),
            body: self.body.clone(),
            draft: self.draft,
        }
    }
}

/// Title and body the way `gh` and `glab` build them.
fn defaults_from(commits: &[LogEntry], branch: &str) -> (String, String) {
    if let [only] = commits {
        (only.subject.clone(), String::new())
    } else {
        let title = humanize(branch);
        let body = commits.iter().rev().fold(String::new(), |mut acc, c| {
            use std::fmt::Write as _;
            let _ = writeln!(acc, "- {}", c.subject);
            acc
        });
        (title, body)
    }
}

/// A branch name as prose: `feat/pr-create` reads `pr create`.
fn humanize(branch: &str) -> String {
    let tail = branch.rsplit('/').next().unwrap_or(branch);
    tail.replace(['-', '_'], " ")
}

impl App {
    /// Label of the push a pending create waits on. Dedicated, because
    /// `git_finished` must not let an unrelated push consume the slot.
    pub(crate) const PR_CREATE_PUSH: &'static str = "push for the pull request";

    pub(crate) fn create_pr_start(&mut self) {
        let Some(remote) = self.ci_remotes().first().cloned() else {
            self.info("no forge detected for this repo");
            return;
        };
        let Some(head) = self.head.branch.clone() else {
            self.error("HEAD is detached; check out a branch to open a pull request");
            return;
        };
        let base = match self.review.vcs.default_branch(&remote.name) {
            Ok(Some(base)) => base,
            Ok(None) => {
                self.error(format!("no default branch on {}", remote.name));
                return;
            }
            Err(err) => {
                self.error(err.to_string());
                return;
            }
        };
        if base == head {
            self.info(format!("already on {base}; branch first"));
            return;
        }
        // the pull request merges into the remote's branch, so the commits it
        // carries count from there; a local branch of the same name can be
        // stale, or missing entirely once it has been pruned
        let base_rev = self.remote_rev(&remote.name, &base);
        let commits = match self.review.vcs.commits_between(&base_rev, &head) {
            Ok(commits) => commits,
            Err(err) => {
                self.error(err.to_string());
                return;
            }
        };
        if commits.is_empty() {
            self.info(format!("{head} has nothing {base} doesn't"));
            return;
        }
        let (title, body) = defaults_from(&commits, &head);
        let needs_push = !self.branch_is_on_remote(&remote.name, &head);
        self.modal = Some(super::Modal::CreatePr {
            draft: Box::new(PrDraft {
                base,
                head,
                title,
                body,
                draft: false,
                commits: commits.len(),
                needs_push,
                field: PrField::Title,
            }),
        });
    }

    /// `branch` as the remote holds it, falling back to the bare name when
    /// there is no tracking ref to read.
    fn remote_rev(&self, remote: &str, branch: &str) -> String {
        let tracking = format!("refs/remotes/{remote}/{branch}");
        if self.review.vcs.resolve(&tracking).is_ok() {
            tracking
        } else {
            branch.to_owned()
        }
    }

    /// `git checkout -b` inherits the parent's upstream, so the tracking ref
    /// itself has to exist and match the local commit.
    fn branch_is_on_remote(&self, remote: &str, branch: &str) -> bool {
        let there = self
            .review
            .vcs
            .resolve(&format!("refs/remotes/{remote}/{branch}"));
        match (there, self.review.vcs.resolve(branch)) {
            (Ok(there), Ok(here)) => there == here,
            _ => false,
        }
    }

    /// Send the composed pull request, pushing the branch first when the forge
    /// has never seen it.
    pub(crate) fn create_pr_submit(&mut self) {
        let Some(super::Modal::CreatePr { draft }) = self.modal.take() else {
            return;
        };
        if draft.title.trim().is_empty() {
            self.info("a pull request needs a title");
            self.modal = Some(super::Modal::CreatePr { draft });
            return;
        }
        let request = draft.request();
        if !draft.needs_push {
            self.queue_pr_create(request);
            return;
        }
        let Some(remote) = self.ci_remotes().first().map(|r| r.name.clone()) else {
            self.error("no remote to push the branch to");
            return;
        };
        if !self.review.vcs.has_index() {
            self.error("push the bookmark with P p, then open the pull request");
            return;
        }
        // arm the slot and queue the push it waits on together: a slot armed
        // ahead of a dialog stays armed when the dialog is declined, and the
        // next push of any kind would then open a pull request nobody asked for
        self.pending_pr_create = Some(Box::new(request));
        self.queue_network_op(Self::PR_CREATE_PUSH, NetworkOp::PushSetUpstream { remote });
    }

    pub(crate) fn queue_pr_create(&mut self, request: NewPullRequest) {
        self.info(format!("opening {} → {}…", request.head, request.base));
        self.pending_ci = Some(super::CiRequest::CreatePr(Box::new(request)));
    }

    /// The push a create waited on finished, so we send the pull request.
    pub(crate) fn pr_create_after_push(&mut self) {
        if let Some(request) = self.pending_pr_create.take() {
            self.queue_pr_create(*request);
        }
    }

    pub(crate) fn on_pr_created(&mut self, result: Result<crate::ci::PullRequest, String>) {
        match result {
            Ok(pr) => {
                self.info(format!("opened #{}: {}", pr.number, pr.title));
                // we resolve the branch's PR once per branch, so we seat the
                // new one here or the band stays empty until a checkout
                self.seat_branch_pr(pr.clone());
                // reviewing needs the head commit, which some providers omit
                if pr.head_oid.is_empty() {
                    return;
                }
                self.open_pr_review_for(pr);
            }
            Err(err) => self.error(err),
        }
    }
}

#[cfg(test)]
mod tests {
    use crossterm::event::KeyCode;

    use super::*;

    fn entry(subject: &str) -> LogEntry {
        LogEntry {
            oid: "0".repeat(40),
            oid7: "0000000".to_owned(),
            refs: Vec::new(),
            parents: Vec::new(),
            subject: subject.to_owned(),
            author: "reviewer".to_owned(),
            time_unix: 0,
            change_id: None,
        }
    }

    #[test]
    fn a_lone_commit_titles_the_pull_request() {
        let (title, body) = defaults_from(&[entry("fix: stop dropping the reply")], "fix/reply");
        assert_eq!(title, "fix: stop dropping the reply");
        assert!(body.is_empty(), "one commit needs no summary of itself");
    }

    #[test]
    fn a_series_is_titled_by_its_branch_and_listed_oldest_first() {
        let commits = [entry("second"), entry("first")];
        let (title, body) = defaults_from(&commits, "feat/pr-create");
        assert_eq!(title, "pr create");
        assert_eq!(body, "- first\n- second\n");
    }

    #[test]
    fn fields_stop_at_both_ends() {
        assert_eq!(PrField::Base.step(false), PrField::Base);
        assert_eq!(PrField::Base.step(true), PrField::Title);
        assert_eq!(PrField::Draft.step(true), PrField::Create);
        assert_eq!(PrField::Create.step(true), PrField::Cancel);
        assert_eq!(PrField::Cancel.step(true), PrField::Cancel);
        assert_eq!(PrField::Create.step(false), PrField::Draft);
    }

    #[test]
    fn a_branch_with_no_tracking_ref_still_needs_a_push() {
        let fixture = crate::test_support::standard_fixture();
        fixture.commit_all("base");
        let app = App::new(fixture.review(), crate::config::LoadedConfig::default());
        assert!(
            !app.branch_is_on_remote("origin", "main"),
            "no remote-tracking ref means the branch still has to be pushed"
        );
    }

    #[test]
    fn composing_without_a_forge_is_refused() {
        let fixture = crate::test_support::standard_fixture();
        fixture.commit_all("base");
        let mut app = App::new(fixture.review(), crate::config::LoadedConfig::default());
        app.create_pr_start();
        assert!(app.modal.is_none(), "no forge, no form");
    }

    #[test]
    fn an_unpushed_branch_pushes_before_the_forge_call() {
        let fixture = crate::test_support::standard_fixture();
        fixture.remote("origin", "https://github.com/acme/widgets.git");
        let mut app = App::new(fixture.review(), crate::config::LoadedConfig::default());
        app.modal = Some(super::super::Modal::CreatePr {
            draft: Box::new(PrDraft {
                base: "main".to_owned(),
                head: "feat/x".to_owned(),
                title: "a title".to_owned(),
                body: String::new(),
                draft: false,
                commits: 1,
                needs_push: true,
                field: PrField::Title,
            }),
        });
        app.create_pr_submit();
        assert!(app.pending_pr_create.is_some(), "the request waits");
        assert!(
            !matches!(app.pending_ci, Some(super::super::CiRequest::CreatePr(_))),
            "nothing reaches the forge before the branch does"
        );
        assert_eq!(
            app.pending_git.as_ref().map(|op| op.label.as_str()),
            Some(App::PR_CREATE_PUSH),
        );
    }

    /// We address the forge call against the pushed head, which only the
    /// refresh after the push knows.
    #[test]
    fn the_forge_call_waits_for_the_refresh_the_finished_push_queues() {
        let fixture = crate::test_support::standard_fixture();
        let mut app = App::new(fixture.review(), crate::config::LoadedConfig::default());
        app.pending_pr_create = Some(Box::new(NewPullRequest {
            base: "main".to_owned(),
            head: "feat/x".to_owned(),
            title: "a title".to_owned(),
            body: String::new(),
            draft: false,
        }));
        app.handle(crate::event::AppEvent::GitDone {
            label: App::PR_CREATE_PUSH.to_owned(),
            ok: true,
            output: String::new(),
        });
        assert!(app.pending_ci.is_none(), "the create holds for the refresh");
        app.settle_refresh();
        assert!(matches!(
            app.pending_ci,
            Some(super::super::CiRequest::CreatePr(_))
        ));
    }

    #[test]
    fn a_title_left_empty_keeps_the_form_open() {
        let fixture = crate::test_support::standard_fixture();
        let mut app = App::new(fixture.review(), crate::config::LoadedConfig::default());
        app.modal = Some(super::super::Modal::CreatePr {
            draft: Box::new(PrDraft {
                base: "main".to_owned(),
                head: "feat/x".to_owned(),
                title: "   ".to_owned(),
                body: String::new(),
                draft: false,
                commits: 1,
                needs_push: false,
                field: PrField::Title,
            }),
        });
        app.create_pr_submit();
        assert!(
            matches!(app.modal, Some(super::super::Modal::CreatePr { .. })),
            "the form stays up so the title can be filled in"
        );
        assert!(app.pending_ci.is_none());
    }

    /// A draft parked on the base field, as the form hands it to the picker.
    fn on_base(head: &str) -> PrDraft {
        PrDraft {
            base: "main".to_owned(),
            head: head.to_owned(),
            title: "a title".to_owned(),
            body: String::new(),
            draft: false,
            commits: 1,
            needs_push: false,
            field: PrField::Base,
        }
    }

    #[test]
    fn the_base_field_picks_from_the_remotes_branches() {
        let fixture = crate::test_support::standard_fixture();
        fixture.remote("origin", "https://github.com/acme/widgets.git");
        fixture.track("main", "HEAD");
        fixture.branch("feat/x");
        fixture.track("feat/x", "HEAD");
        let mut app = App::new(fixture.review(), crate::config::LoadedConfig::default());

        app.open_pr_base_list(Box::new(on_base("feat/x")));

        let Some(super::super::Modal::PrBase { names, .. }) = &app.modal else {
            panic!(
                "the base field opens a picker, not a text field: {:?}",
                app.modal
            );
        };
        assert_eq!(names.first().map(String::as_str), Some("main"), "{names:?}");
        assert!(
            !names.iter().any(|name| name == "feat/x"),
            "a branch cannot merge into itself: {names:?}"
        );
    }

    #[test]
    fn picking_a_base_returns_to_the_form_with_it() {
        let fixture = crate::test_support::standard_fixture();
        fixture.remote("origin", "https://github.com/acme/widgets.git");
        fixture.track("main", "HEAD");
        fixture.branch("release");
        fixture.track("release", "HEAD");
        let mut app = App::new(fixture.review(), crate::config::LoadedConfig::default());
        app.open_pr_base_list(Box::new(on_base("feat/x")));

        let Some(super::super::Modal::PrBase { names, list, .. }) = &mut app.modal else {
            panic!("picker open");
        };
        let at = names
            .iter()
            .position(|name| name == "release")
            .expect("the other branch is offered");
        list.selected = list
            .matches
            .iter()
            .position(|index| *index == at)
            .expect("it is in the ranked matches");
        app.handle_modal_key(&key(KeyCode::Enter));

        let Some(super::super::Modal::CreatePr { draft }) = &app.modal else {
            panic!("the form comes back: {:?}", app.modal);
        };
        assert_eq!(draft.base, "release");
    }

    #[test]
    fn leaving_the_picker_keeps_the_form_and_its_base() {
        let fixture = crate::test_support::standard_fixture();
        fixture.remote("origin", "https://github.com/acme/widgets.git");
        fixture.track("main", "HEAD");
        let mut app = App::new(fixture.review(), crate::config::LoadedConfig::default());
        app.open_pr_base_list(Box::new(on_base("feat/x")));
        app.handle_modal_key(&key(KeyCode::Esc));

        let Some(super::super::Modal::CreatePr { draft }) = &app.modal else {
            panic!("the form comes back: {:?}", app.modal);
        };
        assert_eq!(draft.base, "main", "an abandoned pick changes nothing");
    }

    fn key(code: KeyCode) -> crossterm::event::KeyEvent {
        crossterm::event::KeyEvent::new(code, crossterm::event::KeyModifiers::NONE)
    }

    fn click(row: u16) -> crossterm::event::MouseEvent {
        crossterm::event::MouseEvent {
            kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
            column: 4,
            row,
            modifiers: crossterm::event::KeyModifiers::NONE,
        }
    }

    #[test]
    fn a_click_lands_on_the_row_under_the_pointer() {
        let fixture = crate::test_support::standard_fixture();
        fixture.remote("origin", "https://github.com/acme/widgets.git");
        fixture.track("main", "HEAD");
        fixture.branch("release");
        fixture.track("release", "HEAD");
        let mut app = App::new(fixture.review(), crate::config::LoadedConfig::default());
        app.open_pr_base_list(Box::new(on_base("feat/x")));
        // the renderer publishes where the rows went; stand in for a frame
        app.modal_hits = Some(crate::ui::popup::ListHits {
            first_row: 10,
            rows: 4,
            first_index: 0,
        });

        app.handle_modal_mouse(click(11));
        let Some(super::super::Modal::PrBase { list, .. }) = &app.modal else {
            panic!("picker open");
        };
        assert_eq!(list.selected, 1, "the second row is under row 11");

        // clicking it again takes it, the way Enter would
        app.handle_modal_mouse(click(11));
        assert!(
            matches!(app.modal, Some(super::super::Modal::CreatePr { .. })),
            "a second click on the selected row activates: {:?}",
            app.modal
        );
    }

    #[test]
    fn the_wheel_walks_the_create_form() {
        let fixture = crate::test_support::standard_fixture();
        let mut app = App::new(fixture.review(), crate::config::LoadedConfig::default());
        app.modal = Some(super::super::Modal::CreatePr {
            draft: Box::new(on_base("feat/x")),
        });
        app.handle_modal_mouse(crossterm::event::MouseEvent {
            kind: crossterm::event::MouseEventKind::ScrollDown,
            column: 4,
            row: 12,
            modifiers: crossterm::event::KeyModifiers::NONE,
        });
        let Some(super::super::Modal::CreatePr { draft }) = &app.modal else {
            panic!("form open");
        };
        assert_eq!(draft.field, PrField::Title, "the wheel steps the field");
    }
}

#[cfg(test)]
mod form_tests {
    use crossterm::event::{KeyCode, KeyEvent, MouseButton, MouseEvent, MouseEventKind};

    use super::PrField;
    use crate::app::{App, Modal};
    use crate::config::LoadedConfig;
    use crate::test_support::standard_fixture;

    fn press(code: KeyCode) -> KeyEvent {
        KeyEvent::new(code, crossterm::event::KeyModifiers::NONE)
    }

    fn click(row: u16) -> MouseEvent {
        MouseEvent {
            kind: MouseEventKind::Down(MouseButton::Left),
            column: 4,
            row,
            modifiers: crossterm::event::KeyModifiers::NONE,
        }
    }

    /// The fixture owns the temp repo, so it has to outlive the app: a dropped
    /// one takes `.git` with it and every editor write fails.
    fn form(field: PrField) -> (crate::test_support::Fixture, App) {
        let fixture = standard_fixture();
        let mut app = App::new(fixture.review(), LoadedConfig::default());
        app.modal = Some(Modal::CreatePr {
            draft: Box::new(super::PrDraft {
                base: "main".to_owned(),
                head: "feat/x".to_owned(),
                title: "a title".to_owned(),
                body: "a body".to_owned(),
                draft: false,
                commits: 1,
                needs_push: false,
                field,
            }),
        });
        (fixture, app)
    }

    fn open_field(app: &App) -> Option<PrField> {
        match app.modal.as_ref()? {
            Modal::CreatePr { draft } => Some(draft.field),
            _ => None,
        }
    }

    #[test]
    fn the_body_opens_the_inline_editor() {
        let (_fixture, mut app) = form(PrField::Body);
        app.handle_modal_key(&press(KeyCode::Enter));
        assert!(
            matches!(app.modal, Some(Modal::Input { ref title, .. }) if title == "Body"),
            "{:?}",
            app.modal
        );
        assert!(app.pending_editor.is_none(), "no editor was launched");
    }

    #[test]
    fn an_emptied_body_sticks_but_an_emptied_title_does_not() {
        let (_fixture, mut app) = form(PrField::Body);
        app.handle_modal_key(&press(KeyCode::Enter));
        if let Some(Modal::Input { buffer, cursor, .. }) = app.modal.as_mut() {
            buffer.clear();
            *cursor = 0;
        }
        app.handle_modal_key(&press(KeyCode::Enter));
        let Some(Modal::CreatePr { draft }) = app.modal.as_ref() else {
            panic!("back on the form: {:?}", app.modal);
        };
        assert_eq!(draft.body, "");
        assert_eq!(draft.title, "a title", "the title is untouched");
    }

    #[test]
    fn e_hands_the_body_to_the_editor() {
        let (_fixture, mut app) = form(PrField::Body);
        app.handle_modal_key(&press(KeyCode::Char('e')));
        assert!(app.pending_editor.is_some(), "an editor was queued");
    }

    #[test]
    fn e_writes_a_scratch_file_removed_after_the_round_trip() {
        let (_fixture, mut app) = form(PrField::Body);
        app.handle_modal_key(&press(KeyCode::Char('e')));
        let request = app.pending_editor.take().expect("editor queued");
        let crate::editor::EditorPurpose::PrBody { msg_path, .. } = &request.purpose else {
            panic!("expected a PrBody purpose, got {:?}", request.purpose);
        };
        assert!(
            msg_path.starts_with(std::env::temp_dir()),
            "{}",
            msg_path.display()
        );
        assert_eq!(std::fs::read_to_string(msg_path).unwrap(), "a body");
        let path = msg_path.clone();
        app.editor_finished(request.purpose, Ok(true));
        assert!(!path.exists(), "the scratch file is removed");
    }

    #[test]
    fn e_on_the_title_lands_in_the_title_not_the_body() {
        let (_fixture, mut app) = form(PrField::Title);
        app.handle_modal_key(&press(KeyCode::Char('e')));
        let request = app.pending_editor.take().expect("editor queued");
        let crate::editor::EditorPurpose::PrBody { msg_path, .. } = &request.purpose else {
            panic!("expected a PrBody purpose, got {:?}", request.purpose);
        };
        std::fs::write(msg_path, "a new title").unwrap();
        app.editor_finished(request.purpose, Ok(true));
        let Some(Modal::CreatePr { draft }) = app.modal.as_ref() else {
            panic!("back on the form: {:?}", app.modal);
        };
        assert_eq!(draft.title, "a new title");
        assert_eq!(draft.body, "a body", "the body is untouched");
    }

    #[test]
    fn a_cancelled_body_edit_keeps_the_body() {
        let (_fixture, mut app) = form(PrField::Body);
        app.handle_modal_key(&press(KeyCode::Char('e')));
        let request = app.pending_editor.take().expect("editor queued");
        let crate::editor::EditorPurpose::PrBody { msg_path, .. } = &request.purpose else {
            panic!("expected a PrBody purpose, got {:?}", request.purpose);
        };
        std::fs::write(msg_path, "an edit the editor never saved").unwrap();
        let path = msg_path.clone();
        app.editor_finished(request.purpose, Ok(false));
        assert!(!path.exists(), "the scratch file is removed regardless");
        let Some(Modal::CreatePr { draft }) = app.modal.as_ref() else {
            panic!("back on the form: {:?}", app.modal);
        };
        assert_eq!(draft.body, "a body", "the cancelled edit changed nothing");
    }

    #[test]
    fn e_on_a_non_text_field_says_so() {
        let (_fixture, mut app) = form(PrField::Draft);
        app.handle_modal_key(&press(KeyCode::Char('e')));
        assert!(app.pending_editor.is_none());
        assert_eq!(open_field(&app), Some(PrField::Draft), "the form stays up");
    }

    #[test]
    fn the_cancel_button_closes_the_form() {
        let (_fixture, mut app) = form(PrField::Cancel);
        app.handle_modal_key(&press(KeyCode::Enter));
        assert!(app.modal.is_none());
    }

    #[test]
    fn the_create_button_submits() {
        let (_fixture, mut app) = form(PrField::Create);
        app.handle_modal_key(&press(KeyCode::Enter));
        // the fixture has no forge, so the submit only reports
        assert!(app.modal.is_none() || app.pending_git.is_some());
    }

    #[test]
    fn clicking_the_cancel_button_closes_the_form() {
        let (_fixture, mut app) = form(PrField::Base);
        app.modal_hits = Some(crate::ui::popup::ListHits {
            first_row: 3,
            rows: PrField::ORDER.len() as u16,
            first_index: 0,
        });
        let cancel_row = 3 + PrField::ORDER.len() as u16 - 1;
        app.handle_modal_mouse(click(cancel_row));
        assert_eq!(
            open_field(&app),
            Some(PrField::Cancel),
            "first click selects"
        );
        app.handle_modal_mouse(click(cancel_row));
        assert!(app.modal.is_none(), "second click takes it");
    }
}