use super::*;
#[derive(Debug, PartialEq)]
pub enum Request {
Nothing,
Close,
Hide,
Load,
Copy(String, String),
Type(String),
OpenFile(PathBuf, u32),
OpenUrl(String),
Approve(PathBuf, u64, String),
Merge(PathBuf, u64, String, Method),
Create(Box<Proposal>),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum Tab {
#[default]
Guide,
Findings,
Description,
}
impl Tab {
pub const ALL: [Tab; 3] = [Tab::Guide, Tab::Findings, Tab::Description];
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Thing {
File(usize),
Item(usize),
}
#[derive(Clone, Debug, PartialEq)]
pub enum Click {
GitRow(usize),
GitAction(workspace::Control),
Close,
Back,
Reload,
Tab(Tab),
Stage(usize),
Continue,
Step(usize),
Verdict(Verdict),
Clear,
Prev,
Next,
EditNote,
Copy(String),
Type(String),
File(String, u32),
Url(String),
Finding(usize),
ChangedFile(usize),
Seen(usize),
Approve,
Merge(Method),
Propose,
CopyResults,
Reset,
Choose(usize),
Menu,
MenuRow(usize),
Inert,
Hide,
Create(create::Press),
}
#[derive(Default)]
pub enum Pulls {
#[default]
Loading,
Done(&'static str, Vec<Entry>),
Failed(String),
}
#[derive(Default)]
pub struct Picker {
pub local: Option<Result<Local, String>>,
pub pulls: Pulls,
pub filter: String,
pub selected: usize,
pub want: Option<String>,
}
pub(super) const NEW_PULL: &str = "new-pull-request";
pub enum Row {
Heading(String),
Note(String),
Entry(Entry),
}
impl Picker {
pub fn rows(&self) -> Vec<Row> {
let words: Vec<String> = self.filter.split_whitespace().map(str::to_lowercase).collect();
let matches = |e: &Entry| {
let text = format!("{} {}", e.title, e.detail).to_lowercase();
words.iter().all(|w| text.contains(w))
};
let mut rows = Vec::new();
let section = |rows: &mut Vec<Row>, name: &str, entries: &[Entry]| {
let found: Vec<Entry> = entries.iter().filter(|e| matches(e)).cloned().collect();
if !found.is_empty() {
rows.push(Row::Heading(name.to_string()));
rows.extend(found.into_iter().map(Row::Entry));
}
};
let typed = self.filter.trim();
if !typed.is_empty() {
rows.push(Row::Entry(Entry {
target: typed.to_string(),
title: format!("Review \u{201c}{typed}\u{201d}"),
detail: "a pull request number or address, a branch, or a commit".into(),
}));
}
match &self.pulls {
Pulls::Loading => {
rows.push(Row::Heading("Pull requests".into()));
rows.push(Row::Note("asking the host\u{2026}".into()));
}
Pulls::Failed(why) => {
rows.push(Row::Heading("Pull requests".into()));
rows.push(Row::Note(why.clone()));
}
Pulls::Done(host, list) if list.is_empty() => {
rows.push(Row::Heading(format!("Pull requests on {host}")));
rows.push(Row::Note("none are open".into()));
}
Pulls::Done(host, list) => section(&mut rows, &format!("Pull requests on {host}"), list),
}
if matches!(self.local, Some(Ok(_))) {
let new = Entry {
target: NEW_PULL.into(),
title: "+ New pull request".into(),
detail: "propose the current branch\u{2019}s commits".into(),
};
section(&mut rows, "Create", &[new]);
}
match &self.local {
None => rows.push(Row::Note("reading the repository\u{2026}".into())),
Some(Err(why)) => rows.push(Row::Note(why.clone())),
Some(Ok(l)) => {
section(&mut rows, "Work in progress", &l.work);
section(&mut rows, "Branches", &l.branches);
section(&mut rows, "Recent commits", &l.commits);
}
}
let demo = Entry {
target: "demo".into(),
title: "Demo pull request".into(),
detail: "a made-up change to try this on".into(),
};
section(&mut rows, "Try it", &[demo]);
rows
}
pub(super) fn select_wanted(&mut self) -> bool {
let Some(wanted) = &self.want else { return false };
let found = self.entries().iter().position(|e| &e.target == wanted);
if let Some(i) = found {
self.selected = i;
}
found.is_some()
}
pub fn entries(&self) -> Vec<Entry> {
self.rows().into_iter().filter_map(|r| if let Row::Entry(e) = r { Some(e) } else { None }).collect()
}
}
pub struct Opened {
pub change: Box<Change>,
pub items: Vec<Item>,
pub session: Session,
pub stages: Vec<Stage>,
pub stage: usize,
pub cursor: usize,
pub step: usize,
pub tab: Tab,
pub finding: usize,
pub unfolded: bool,
pub note: Option<String>,
pub confirm_reset: bool,
pub file: usize,
pub file_open: bool,
pub confirm_approve: bool,
pub approving: bool,
pub confirm_merge: Option<Method>,
pub merging: bool,
pub menu: Option<Menu>,
pub merged: bool,
}
impl Opened {
pub fn new(change: Box<Change>, results: Option<&Path>) -> Opened {
let items = session::items(&change.report);
let session = Session::open(results, &change.root, &change.id, &change.revision);
let stages = guide::build(&change.files, &change.report.findings, &items);
let mut o = Opened {
change,
items,
session,
stages,
stage: 0,
cursor: 0,
step: 0,
tab: Tab::Guide,
finding: 0,
unfolded: true,
note: None,
confirm_reset: false,
file: 0,
file_open: true,
confirm_approve: false,
approving: false,
confirm_merge: None,
merging: false,
menu: None,
merged: false,
};
let started = (0..o.stages.len()).any(|s| o.things(s).iter().any(|&t| o.done(t)));
let stage =
if started { (0..o.stages.len()).find(|&s| !o.stage_done(s)).unwrap_or(o.stages.len() - 1) } else { 0 };
let cursor = o.things(stage).iter().position(|&t| !o.done(t)).unwrap_or(0);
o.focus(stage, cursor);
o
}
pub fn current(&self) -> Option<&Item> {
match self.thing() {
Some(Thing::Item(i)) => self.items.get(i),
_ => None,
}
}
pub fn things(&self, stage: usize) -> Vec<Thing> {
let Some(s) = self.stages.get(stage) else { return Vec::new() };
s.files.iter().map(|&f| Thing::File(f)).chain(s.items.iter().map(|&i| Thing::Item(i))).collect()
}
pub fn thing(&self) -> Option<Thing> {
self.things(self.stage).get(self.cursor).copied()
}
pub fn done(&self, t: Thing) -> bool {
match t {
Thing::File(f) => self.change.files.get(f).is_some_and(|f| self.session.seen(f) == Seen::Yes),
Thing::Item(i) => self.items.get(i).is_some_and(|i| matches!(self.session.state(&i.id), State::Done(_))),
}
}
pub fn stage_counts(&self, stage: usize) -> (usize, usize) {
let things = self.things(stage);
(things.iter().filter(|&&t| self.done(t)).count(), things.len())
}
pub fn stage_done(&self, stage: usize) -> bool {
let (done, total) = self.stage_counts(stage);
done == total
}
pub fn focus(&mut self, stage: usize, cursor: usize) {
self.stage = stage.min(self.stages.len().saturating_sub(1));
self.cursor = cursor.min(self.things(self.stage).len().saturating_sub(1));
self.note = None;
match self.thing() {
Some(Thing::Item(i)) => self.step = i,
Some(Thing::File(f)) => {
self.file = f;
self.file_open = true;
}
None => {}
}
}
pub fn locate(&self, t: Thing) -> Option<(usize, usize)> {
(0..self.stages.len()).find_map(|s| self.things(s).iter().position(|&x| x == t).map(|c| (s, c)))
}
pub fn next_undone(&self) -> Option<usize> {
let things = self.things(self.stage);
(1..=things.len()).map(|k| (self.cursor + k) % things.len()).find(|&c| !self.done(things[c]))
}
pub fn file(&self, rel: &str) -> Option<PathBuf> {
let rel = Path::new(rel);
let inside = rel.components().all(|c| matches!(c, Component::Normal(_)));
let path = self.change.root.join(rel);
(inside && !rel.as_os_str().to_string_lossy().contains('"') && path.is_file()).then_some(path)
}
pub(super) fn current_place(&self) -> Option<(String, u32)> {
let report = &self.change.report;
let of = |i: &usize| report.findings.get(*i)?.span.as_ref().map(|s| (s.file.clone(), s.line));
match (self.tab, self.thing()) {
(Tab::Findings, _) => of(&self.finding),
(_, Some(Thing::File(f))) => {
let file = self.change.files.get(f)?;
let line =
file.lines().find(|l| l.kind != Kind::Context).and_then(|l| l.new_no.or(l.old_no)).unwrap_or(1);
Some((file.path.clone(), line))
}
_ => self.current()?.findings.iter().find_map(of),
}
}
pub fn findings_in(&self, path: &str) -> Vec<usize> {
let findings = &self.change.report.findings;
(0..findings.len()).filter(|&i| findings[i].span.as_ref().is_some_and(|s| s.file == path)).collect()
}
pub fn still_open(&self) -> Vec<String> {
let mut open = Vec::new();
let unread = self.change.files.len() - self.session.seen_count(&self.change.files);
let left = |check: bool| {
self.items
.iter()
.filter(|i| i.check == check && !matches!(self.session.state(&i.id), State::Done(_)))
.count()
};
let (unchecked, untested) = (left(true), left(false));
let parts = [
(unread, "file unread", "files unread"),
(unchecked, "finding unchecked", "findings unchecked"),
(untested, "step untried", "steps untried"),
];
for (n, one, many) in parts {
if n > 0 {
open.push(format!("{n} {}", if n == 1 { one } else { many }));
}
}
open
}
}
pub enum Screen {
Git(Box<GitView>),
Create(Box<CreateView>),
Pick(Picker),
Loading(String),
Open(Box<Opened>),
Message {
text: String,
error: bool,
},
}