rustimal 0.7.0

A minimal, GPU-rendered terminal for Windows that runs Git Bash, with animated split panes and a glass look
//! Walks the panel the way a person would: open the demo, test its steps, come back later.

use super::*;
use crate::review::forge::Method;
use crate::review::testutil::Scratch;

fn text(s: &str) -> Input {
    Input::Text(s.to_string())
}

/// A panel with the demo change loaded, saving results into `results`.
fn demo_view(results: &Path) -> ReviewView {
    let job = Job::Open(vec!["demo".to_string()]);
    let mut view = ReviewView::new(std::env::temp_dir(), job.clone(), Some(results.to_path_buf()));
    let (tx, rx) = std::sync::mpsc::channel();
    spawn(job, std::env::temp_dir(), view.number, move |m| tx.send(m).unwrap());
    view.receive(rx.recv_timeout(std::time::Duration::from_secs(60)).unwrap());
    if let Screen::Message { text, .. } = &view.screen {
        panic!("{text}");
    }
    view
}

fn state(view: &mut ReviewView, step: usize) -> State {
    let o = view.opened().unwrap();
    o.session.state(&o.items[step].id)
}

/// The stage with this title.
fn stage_named(view: &mut ReviewView, title: &str) -> usize {
    view.opened().unwrap().stages.iter().position(|s| s.title == title).unwrap_or_else(|| panic!("no stage {title}"))
}

#[test]
fn walking_through_the_demo_stage_by_stage() {
    let s = Scratch::new("panel");
    let mut view = demo_view(&s.0);
    assert!(view.wide, "a change opens over the whole window");
    let o = view.opened().unwrap();
    assert!(o.change.checked_out && o.tab == Tab::Guide && (o.stage, o.cursor) == (0, 0));
    assert_eq!(o.stages[0].title, "What it claims");
    // Things to look at come before steps to try.
    let first = o.current().unwrap();
    assert!(first.check, "{}", first.text);
    let in_overview = o.things(0).len();

    // Enter: looked at, and on to the next.
    view.input(Input::Enter);
    let o = view.opened().unwrap();
    assert_eq!(o.session.state(&o.items[o.stages[0].items[0]].id), State::Done(Verdict::Passed));
    assert_eq!(o.cursor, 1);

    // Backspace flags a problem; while typing its note it deletes text normally.
    view.input(Input::Backspace);
    let o = view.opened().unwrap();
    assert_eq!(o.session.state(&o.current().unwrap().id), State::Done(Verdict::Failed));
    assert_eq!(o.note.as_deref(), Some(""));
    view.input(text("x"));
    view.input(Input::Backspace);
    for t in ["p", "d", "f"] {
        view.input(text(t));
    }
    view.input(Input::Space);
    view.input(text("is blank"));
    view.input(Input::Enter);
    let o = view.opened().unwrap();
    let failed = o.stages[0].items[1];
    assert_eq!(o.session.record(&o.items[failed].id).unwrap().note, "pdf is blank");
    assert_eq!(o.cursor, 2);

    // Skipping the rest finishes the stage; it says so, and stays.
    for _ in 2..in_overview {
        view.input(text("s"));
    }
    let o = view.opened().unwrap();
    assert!(o.stage_done(0) && o.stage == 0);
    assert!(view.status.as_ref().unwrap().0.contains("Get it running"), "{:?}", view.status);

    // Enter goes on: the next stage starts with its file.
    view.input(Input::Enter);
    let o = view.opened().unwrap();
    assert_eq!(o.stages[o.stage].title, "Get it running");
    let Some(Thing::File(f)) = o.thing() else { panic!("{:?}", o.thing()) };
    assert_eq!(o.change.files[f].path, "config/billing.php");
    view.input(Input::Enter);
    let o = view.opened().unwrap();
    assert!(matches!(o.thing(), Some(Thing::Item(_))), "reading a file moves on to what is left");
    let step = o.current().unwrap().id.clone();
    view.input(Input::Enter);
    assert_eq!(view.opened().unwrap().session.state(&step), State::Done(Verdict::Passed));

    // Arrows move between stages; a click goes straight to one.
    view.input(Input::Right);
    let o = view.opened().unwrap();
    assert_eq!(o.stages[o.stage].title, "Database");
    view.input(Input::Left);
    let invoice = stage_named(&mut view, "Invoice");
    view.activate(Click::Stage(invoice));
    let o = view.opened().unwrap();
    assert_eq!((o.stage, o.cursor), (invoice, 0));
    assert!(matches!(o.thing(), Some(Thing::File(_))));

    let Request::Copy(markdown, _) = view.activate(Click::CopyResults) else { panic!() };
    assert!(markdown.contains("**FAILED**") && markdown.contains("> pdf is blank") && markdown.contains("Looked at in the code"), "{markdown}");

    // A later look carries on at the first stage with something left.
    let mut again = demo_view(&s.0);
    let o = again.opened().unwrap();
    assert_eq!(o.stages[o.stage].title, "Database");
    assert!(matches!(o.thing(), Some(Thing::File(_))));

    // Reset takes two presses, and starts over.
    again.activate(Click::Reset);
    assert!(again.opened().unwrap().stage_done(0));
    again.activate(Click::Reset);
    let o = again.opened().unwrap();
    assert!(!o.stage_done(0) && (o.stage, o.cursor) == (0, 0));
    assert_eq!(o.session.seen_count(&o.change.files), 0);
}

#[test]
fn tabs_findings_and_what_is_asked_of_the_app() {
    let s = Scratch::new("panel-tabs");
    let mut view = demo_view(&s.0);
    view.input(Input::Tab);
    assert_eq!(view.opened().unwrap().tab, Tab::Findings);
    view.input(text("p"));
    assert_eq!(state(&mut view, 0), State::Untested, "no judging from another tab");
    view.input(Input::Down);
    assert_eq!(view.opened().unwrap().finding, 1);
    view.input(Input::Enter);
    assert!(!view.opened().unwrap().unfolded);

    // A finding's file opens from the demo repository, but nothing outside it.
    let Request::OpenFile(path, line) = view.input(text("o")) else { panic!("{:?}", view.status) };
    assert!(path.is_file() && line > 0);
    for outside in ["../x", "C:/Windows/win.ini", "/etc/passwd", "nope.rs"] {
        assert_eq!(view.activate(Click::File(outside.into(), 1)), Request::Nothing, "{outside}");
        assert!(view.status.as_ref().is_some_and(|(_, problem)| *problem));
    }

    // A command is typed without anything that could run it.
    let typed = view.activate(Click::Type("php artisan test\r\n".into()));
    assert_eq!(typed, Request::Type("php artisan test".into()));

    // Choosing a step from anywhere goes to it on the guide.
    view.activate(Click::Step(0));
    let o = view.opened().unwrap();
    assert_eq!((o.tab, o.current().map(|i| i.id.clone())), (Tab::Guide, Some(o.items[0].id.clone())));

    assert_eq!(view.input(Input::Escape), Request::Unfocus);
    // Side by side lasts until a new review is opened.
    assert_eq!(view.input(text("w")), Request::Nothing);
    assert!(!view.wide);
    view.start(Job::Open(vec!["demo".into()]));
    assert!(view.wide);
    assert_eq!(view.activate(Click::Close), Request::Close);
}

#[test]
fn the_picker_lists_filters_and_opens() {
    let mut view = ReviewView::new(PathBuf::from("."), Job::List, None);
    let number = view.number;
    let entry = |t: &str, title: &str| Entry { target: t.into(), title: title.into(), detail: String::new() };
    view.receive(Message::Local(number, Ok(Local { branches: vec![entry("invoices", "invoices"), entry("main", "main")], ..Default::default() })));
    let titles = |v: &ReviewView| match &v.screen {
        Screen::Pick(p) => p.entries().into_iter().map(|e| e.target).collect::<Vec<_>>(),
        _ => panic!(),
    };
    assert_eq!(titles(&view), ["new-pull-request", "invoices", "main", "demo"]);
    view.input(Input::Down);

    // Pull requests arrive later, above the rest; the selection stays on its row.
    view.input(Input::Down);
    let pr = PullRequest { number: 7, title: "Fix totals".into(), ..Default::default() };
    view.receive(Message::Pulls(number, Ok(("GitHub", vec![pr]))));
    assert_eq!(titles(&view), ["#7", "new-pull-request", "invoices", "main", "demo"]);
    let Screen::Pick(p) = &view.screen else { panic!() };
    assert_eq!(p.entries()[p.selected].target, "main");

    // Typing narrows, and what was typed can itself be opened.
    for t in ["t", "o", "t"] {
        view.input(text(t));
    }
    assert_eq!(titles(&view), ["tot", "#7"]);
    view.input(Input::Down);
    assert_eq!(view.input(Input::Enter), Request::Load);
    assert_eq!(view.job, Job::Open(vec!["#7".into()]));

    // Answers meant for an earlier screen are ignored.
    view.receive(Message::Local(number, Err("old".into())));
    assert!(matches!(view.screen, Screen::Loading(_)));
    view.receive(Message::Loaded(view.number, Err("no such thing".into())));
    assert!(matches!(&view.screen, Screen::Message { error: true, .. }));
    assert_eq!(view.input(Input::Escape), Request::Load);
    assert!(matches!(view.screen, Screen::Pick(_)));
    assert_eq!(view.input(Input::Escape), Request::Close);

    // The entry for a new pull request starts one.
    view.start(Job::List);
    view.receive(Message::Local(view.number, Ok(Local::default())));
    assert_eq!(view.input(Input::Enter), Request::Load);
    assert_eq!(view.job, Job::Propose(None));
    assert!(matches!(view.screen, Screen::Create(_)));
}

#[test]
fn a_reviewed_branch_can_be_proposed_from_the_review() {
    let s = Scratch::new("panel-propose");
    crate::review::git::testing::init(&s.0);
    std::fs::write(s.0.join("file"), "1\n").unwrap();
    crate::review::git::testing::commit(&s.0, "one");
    crate::review::git::testing::run(&s.0, &["switch", "--quiet", "-c", "topic"]);
    std::fs::write(s.0.join("file"), "2\n").unwrap();
    crate::review::git::testing::commit(&s.0, "two");
    crate::review::git::testing::run(&s.0, &["switch", "--quiet", "main"]);

    // Looking at a branch that is not checked out.
    let review = Job::Open(vec!["topic".into(), "--base".into(), "main".into()]);
    let mut view = ReviewView::new(s.0.clone(), review.clone(), None);
    // Read it the way the panel's own worker does.
    let load = |args: &[String]| match parse_args(args) {
        Ok(Parsed::Review(o)) => source::load(&s.0, &o),
        _ => panic!("{args:?}"),
    };
    let Job::Open(args) = &review else { unreachable!() };
    view.receive(Message::Loaded(view.number, load(args)));
    let of = view.opened().unwrap().change.branch.clone().expect("a branch");
    assert_eq!((of.name.as_str(), of.base.as_deref()), ("refs/heads/topic", Some("main")));

    assert_eq!(view.input(text("m")), Request::Load);
    assert_eq!(view.job, Job::Propose(Some(of)));
    // Leaving goes back to the review it came from, not to the list.
    assert_eq!(view.input(Input::Escape), Request::Load);
    assert_eq!(view.job, review);

    // A single commit is not something to open a pull request for.
    let commit = crate::review::git::commit_id(&s.0, "topic").unwrap();
    view.receive(Message::Loaded(view.number, load(&[commit])));
    assert_eq!(view.opened().unwrap().change.branch, None);
    assert_eq!(view.input(text("m")), Request::Nothing);
}

/// The demo, dressed up as pull request #7.
fn a_pull_request() -> ReviewView {
    let mut view = ReviewView::new(PathBuf::from("."), Job::Open(vec!["demo".into()]), None);
    let options = match parse_args(&["demo".to_string()]) {
        Ok(Parsed::Review(o)) => o,
        _ => unreachable!(),
    };
    view.receive(Message::Loaded(view.number, source::load(&PathBuf::from("."), &options)));
    view.opened().unwrap().change.pull = Some((7, "abc1234".into()));
    view
}

#[test]
fn merging_takes_two_presses_of_the_same_kind() {
    let mut view = a_pull_request();
    assert_eq!(view.input(text("q")), Request::Nothing, "the first press only asks");
    let (asked, warns) = view.status.clone().unwrap();
    assert!(warns && asked.contains("you have not approved it") && asked.contains("squash and merge #7 into"), "{asked}");
    // The other kind asks for itself, and any other key disarms.
    assert_eq!(view.input(text("g")), Request::Nothing);
    assert_eq!(view.input(text("q")), Request::Nothing);
    view.input(Input::Down);
    assert_eq!(view.input(text("q")), Request::Nothing);
    assert_eq!(view.input(Input::Escape), Request::Unfocus);
    assert_eq!(view.input(text("q")), Request::Nothing, "leaving the panel disarms too");
    assert!(view.ignores_repeat(&text("q")) && view.ignores_repeat(&text("a")));
    assert!(!view.ignores_repeat(&text("j")));

    let Request::Merge(_, number, head, how) = view.input(text("q")) else { panic!("the second press merges") };
    assert_eq!((number, head.as_str(), how), (7, "abc1234", Method::Squash));
    assert_eq!(view.input(text("q")), Request::Nothing, "only once");
    assert_eq!(view.activate(Click::Merge(Method::Commit)), Request::Nothing);

    view.receive(Message::Merged(view.number, Err("Bitbucket refused to merge it (400)".into())));
    assert!(!view.opened().unwrap().merged);
    assert_eq!(view.activate(Click::Merge(Method::Commit)), Request::Nothing, "asks again after a refusal");
    assert!(matches!(view.activate(Click::Merge(Method::Commit)), Request::Merge(.., Method::Commit)));
    view.receive(Message::Merged(view.number, Ok(("Bitbucket", true))));
    assert!(view.opened().unwrap().merged);
    assert_eq!(view.status.clone().unwrap().0, "Merged #7 on Bitbucket. Fetch to update your branches");
    assert_eq!(view.input(text("q")), Request::Nothing);
    assert_eq!(view.input(text("q")), Request::Nothing, "never twice");
}

#[test]
fn a_failed_step_stops_a_merge_and_so_does_not_being_a_pull_request() {
    let mut view = a_pull_request();
    view.activate(Click::Step(0));
    view.activate(Click::Verdict(Verdict::Failed));
    view.input(Input::Escape);
    for _ in 0..2 {
        assert_eq!(view.activate(Click::Merge(Method::Squash)), Request::Nothing);
    }
    assert!(view.status.clone().unwrap().0.contains("cannot be merged"));
    view.opened().unwrap().change.pull = None;
    assert_eq!(view.activate(Click::Merge(Method::Squash)), Request::Nothing);
    assert!(view.status.clone().unwrap().0.starts_with("Only a pull request"));
}

#[test]
fn reading_files_and_approving() {
    let s = Scratch::new("panel-files");
    let mut view = demo_view(&s.0);
    let invoice = stage_named(&mut view, "Invoice");
    view.activate(Click::Stage(invoice));
    let (first, second) = {
        let o = view.opened().unwrap();
        (o.stages[invoice].files[0], o.stages[invoice].files[1])
    };

    // Space ticks the file and moves on to the next unread one; o opens it at its change.
    view.input(Input::Space);
    let o = view.opened().unwrap();
    assert_eq!((o.thing(), o.session.seen_count(&o.change.files)), (Some(Thing::File(second)), 1));
    // Revisiting a read file and accepting it keeps its tick, then moves on.
    view.input(Input::Up);
    view.input(Input::Enter);
    let o = view.opened().unwrap();
    assert_eq!((o.thing(), o.session.seen_count(&o.change.files)), (Some(Thing::File(second)), 1));
    let Request::OpenFile(path, line) = view.input(text("o")) else { panic!("{:?}", view.status) };
    assert!(path.is_file() && line > 0);
    // A click on the tick of the first file takes it off again, and stays where it is.
    view.activate(Click::Seen(first));
    let o = view.opened().unwrap();
    assert_eq!((o.thing(), o.session.seen_count(&o.change.files)), (Some(Thing::File(second)), 0));
    assert!(o.still_open().iter().any(|s| s.ends_with("files unread")), "{:?}", o.still_open());

    // The demo is no pull request, so there is nothing to approve.
    assert_eq!(view.input(text("a")), Request::Nothing);
    assert!(view.status.as_ref().is_some_and(|(_, problem)| *problem));

    // As one: the first press says what is open, the second asks the app.
    let root = {
        let o = view.opened().unwrap();
        o.change.pull = Some((7, "abc1234".into()));
        o.change.root.clone()
    };
    assert_eq!(view.input(text("a")), Request::Nothing);
    assert!(view.status.as_ref().unwrap().0.starts_with("Still open:"), "{:?}", view.status);
    assert_eq!(view.input(text("a")), Request::Approve(root.clone(), 7, "abc1234".into()));
    assert_eq!(view.input(text("a")), Request::Nothing, "not twice while it is on its way");
    let number = view.number;
    view.receive(Message::Approved(number, Err("Bitbucket refused the approval (403)".into())));
    assert!(view.status.as_ref().is_some_and(|(m, problem)| *problem && m.contains("403")));
    view.input(text("a"));
    view.input(text("a"));
    view.receive(Message::Approved(number, Ok("Bitbucket")));
    assert!(view.opened().unwrap().session.approved());
    assert_eq!(view.status, Some(("Approved #7 on Bitbucket".into(), false)));

    // Anything else in between means asking again.
    view.input(text("a"));
    view.activate(Click::Tab(Tab::Findings));
    assert!(!view.opened().unwrap().confirm_approve);

    // A failed step stops an approval.
    let other = Scratch::new("panel-failed");
    let mut view = demo_view(&other.0);
    view.opened().unwrap().change.pull = Some((7, "abc1234".into()));
    view.input(text("f"));
    view.input(Input::Escape);
    for _ in 0..2 {
        assert_eq!(view.input(text("a")), Request::Nothing);
        assert!(view.status.as_ref().is_some_and(|(m, problem)| *problem && m.contains("failed")), "{:?}", view.status);
    }
}