plannotator-tui 0.15.1

Annotate Markdown in the terminal - standalone, and as a Herdr plugin.
//! Marked commits: `mark-commit` (Space) marks the commit under the cursor or unmarks it,
//! and Enter then reviews every commit from the newest mark to the oldest, the rows between
//! included, as one review ([`Scope::Range`]). One mark is that commit alone. Marks are kept
//! by commit id, so they stay where they were through `r` and older pages; a marked commit
//! not listed (after `r` with new commits on top, or the ends of a range the picker opens
//! over) has older pages listed until it is, at most [`REACH_PAGES`] of them, and is
//! unmarked, with a word in the footer, when it is not found. The footer counts a range's
//! commits as its review will (`git rev-list --count`, in the background), not the rows
//! between the marks, which can differ across merges.

use plannotator_tui_review::Scope;

use super::rows::{Kind, Row};
use super::source::Job;
use super::{More, Picker, REACH_PAGES};

#[derive(Debug, Default, Clone)]
pub(super) struct Marks(Vec<String>);

/// The commit id of a commit row.
fn sha(row: &Row) -> Option<&str> {
    match &row.kind {
        Kind::Commit(commit) => Some(&commit.sha),
        _ => None,
    }
}

impl Marks {
    pub(super) fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    pub(super) fn clear(&mut self) {
        self.0.clear();
    }

    /// Mark `row`'s commit, or unmark it. False when the row is not a commit.
    pub(super) fn toggle(&mut self, row: &Row) -> bool {
        let Some(sha) = sha(row) else { return false };
        if let Some(at) = self.0.iter().position(|marked| marked == sha) {
            self.0.remove(at);
        } else {
            self.0.push(sha.to_owned());
        }
        true
    }

    pub(super) fn has(&self, row: &Row) -> bool {
        sha(row).is_some_and(|sha| self.0.iter().any(|marked| marked == sha))
    }

    /// Mark exactly `shas`.
    fn set(&mut self, shas: Vec<String>) {
        self.0 = shas;
    }

    /// The marked commits no row lists.
    fn missing(&self, rows: &[Row]) -> Vec<String> {
        self.0
            .iter()
            .filter(|marked| !rows.iter().any(|row| sha(row) == Some(marked.as_str())))
            .cloned()
            .collect()
    }

    /// The rows from the newest mark to the oldest, as `(first, last)` indexes into `rows`
    /// (newest first, so `first <= last`); `None` with no mark listed.
    pub(super) fn span(&self, rows: &[Row]) -> Option<(usize, usize)> {
        let mut marked = rows.iter().enumerate().filter(|(_, row)| self.has(row)).map(|(i, _)| i);
        let first = marked.next()?;
        Some((first, marked.next_back().unwrap_or(first)))
    }

    /// Whether `index` is in the span, between the marks or on one.
    pub(super) fn covers(&self, rows: &[Row], index: usize) -> bool {
        self.span(rows).is_some_and(|(first, last)| (first..=last).contains(&index))
    }

    /// The range Enter reviews when two or more commits are marked: from the oldest marked
    /// (the last row) to the newest (the first).
    pub(super) fn range(&self, rows: &[Row]) -> Option<Scope> {
        let (first, last) = self.span(rows)?;
        if first == last {
            return None;
        }
        let to = rows.get(first).and_then(sha)?.to_owned();
        let from = rows.get(last).and_then(sha)?.to_owned();
        Some(Scope::Range { from, to })
    }
}

impl Picker {
    /// Start on `scope`'s row: for a range, show it marked (its marks are not the person's
    /// until Space, see [`Picker::confirm`]) and start on its newest commit. Any other scope
    /// takes away a range shown before.
    pub(super) fn aim(&mut self, scope: Scope) {
        if self.aimed.take().is_some() {
            self.marks.clear();
        }
        self.keep = Some(match scope {
            Scope::Range { from, to } => {
                self.marks.set(vec![to.clone(), from.clone()]);
                self.aimed = Some(Scope::Range { from, to: to.clone() });
                Scope::Commit { sha: to }
            }
            scope => scope,
        });
    }

    /// After a page is listed: list the next one while a marked commit is not listed yet,
    /// up to [`REACH_PAGES`]; past that, or at the end of the history, unmark it and say so.
    pub(super) fn reach_marks(&mut self) {
        let missing = self.marks.missing(&self.rows);
        if missing.is_empty() {
            self.reached = 0;
            return;
        }
        if self.more == More::Ready && self.reached < REACH_PAGES {
            self.reached += 1;
            self.list_more();
            return;
        }
        self.reached = 0;
        if self.aimed.take().is_some() {
            // Half a range shown would read as one commit marked: show none, and Enter opens
            // the row under the cursor.
            self.marks.clear();
        } else {
            self.marks.0.retain(|marked| !missing.contains(marked));
        }
        let shorts: Vec<&str> = missing.iter().map(|sha| sha.get(..7).unwrap_or(sha)).collect();
        self.status = Some(match shorts.as_slice() {
            [one] => format!("commit {one} is not in the list, so it is not marked"),
            many => format!("commits {} are not in the list, so they are not marked", many.join(", ")),
        });
    }

    /// Count the commits of the marked range in the background, once per range.
    pub(super) fn ask_count(&mut self) {
        let Some(scope) = self.marks.range(&self.rows) else { return };
        let busy = self.opening.is_some() || self.opened.is_some();
        if busy || self.counting.as_ref() == Some(&scope) || self.count_of(&scope).is_some() {
            return;
        }
        self.counting = Some(scope.clone());
        if !self.ask(Job::Count { scope }) {
            self.counting = None;
        }
    }

    /// Forget the counts that failed, so a range is asked again once the marks come back to
    /// it: what failed (a git that was stopped, say) may not fail twice.
    pub(super) fn forget_failed_counts(&mut self) {
        self.counts.retain(|(_, count)| count.is_ok());
    }

    pub(super) fn take_count(&mut self, scope: Scope, count: Result<usize, String>) {
        if self.counting.as_ref() == Some(&scope) {
            self.counting = None;
        }
        self.counts.retain(|(known, _)| *known != scope);
        self.counts.push((scope, count));
    }

    /// The commits `scope` holds, or why it cannot open, once counted.
    pub(super) fn count_of(&self, scope: &Scope) -> Option<&Result<usize, String>> {
        self.counts.iter().find(|(known, _)| known == scope).map(|(_, count)| count)
    }
}