git-custom-cli 2.4.0

Fast, keyboard-driven terminal UI for dated Git commits
//! Hub: a launcher listing the modes by group. Enter opens one; when it returns you are back
//! here. Tab switches between the basic modes and all modes. Esc/Q (or Ctrl+C) in the hub quits
//! gct. A cancel (Esc in the commit menu, Ctrl+C) inside a mode returns to the hub.

use super::{not_a_repo, run_mode, show_result, Group, Mode, Tier};
use crate::{
    input::{self, Input},
    model::{Config, Level},
    repo_state::{EntryKind, Head, RepoState},
    screen,
};
use anyhow::{bail, Result};
use crossterm::event::KeyCode;

const HUB_HINT: &str =
    "Up/Down move  ·  Enter or click open  ·  Tab basic/all  ·  Esc/Q quit  ·  Ctrl+C quit";

enum Row {
    Header(Group),
    Mode(Mode),
}

/// The hub rows: each non-empty group's header followed by its modes (the hub itself hidden).
fn rows(all: bool) -> Vec<Row> {
    let mut rows = Vec::new();
    for group in Group::ALL {
        let modes: Vec<Mode> = Mode::all()
            .filter(|m| m.info().group == group && m.name() != "hub")
            .filter(|m| all || m.info().tier == Tier::Basic)
            .collect();
        if !modes.is_empty() {
            rows.push(Row::Header(group));
            rows.extend(modes.into_iter().map(Row::Mode));
        }
    }
    rows
}

/// "<branch> · clean|N changes", or a hint outside a repository.
fn repo_line(state: Option<&RepoState>) -> String {
    let Some(state) = state else {
        return "Not in a git repository".into();
    };
    let branch = match &state.branch.head {
        Head::Branch { name, .. } | Head::Unborn { name } => name.clone(),
        Head::Detached { oid } => format!("detached at {}", &oid[..oid.len().min(7)]),
    };
    let changes = state
        .entries
        .iter()
        .filter(|e| e.kind != EntryKind::Ignored)
        .count();
    if changes == 0 {
        format!("{branch} · clean")
    } else {
        let plural = if changes == 1 { "" } else { "s" };
        format!("{branch} · {changes} change{plural}")
    }
}

fn load_line() -> String {
    let state = if crate::repo_state::in_repo() {
        crate::repo_state::load().ok()
    } else {
        None
    };
    repo_line(state.as_ref())
}

/// Row position of the selectable row after/before `from` (wrapping), skipping headers.
fn next_mode(rows: &[Row], from: usize, forward: bool) -> usize {
    let len = rows.len();
    (1..=len)
        .map(|k| {
            if forward {
                (from + k) % len
            } else {
                (from + len - k % len) % len
            }
        })
        .find(|i| matches!(rows[*i], Row::Mode(_)))
        .unwrap_or(from)
}

pub fn run(config: &mut Config) -> Result<()> {
    let mut all = config.level() == Level::Pro;
    let mut list = rows(all);
    let mut index = next_mode(&list, 0, true);
    let mut offset = 0usize;
    let mut repo = load_line();
    loop {
        screen::set_mood(crate::mascot::Mood::Idle);
        let scope = if all { "all modes" } else { "basic modes" };
        let mut body = vec![
            screen::accent(format!("GCT HUB  ·  choose a mode  ·  {scope}")),
            screen::muted(&repo),
        ];
        body.extend(crate::ui::explain(
            config,
            &["A mode is one screen for one job. Pick one with Enter; Esc there brings you back."],
        ));
        body.push(String::new());
        let top = body.len();
        let visible = screen::body_rows().saturating_sub(top).max(1);
        offset = ui_scroll(index, offset, visible);
        body.extend(
            list.iter()
                .enumerate()
                .skip(offset)
                .take(visible)
                .map(|(i, row)| match row {
                    Row::Header(group) => screen::muted(format!("  ── {}", group.title())),
                    Row::Mode(mode) => input::styled_menu_line(
                        i == index,
                        &format!("{:<12}  {}", mode.title(), mode.description()),
                    ),
                }),
        );
        screen::draw(&body, HUB_HINT, None)?;

        let mut open = None;
        match input::read_input()? {
            None => {}
            Some(Input::Scroll(lines)) => {
                for _ in 0..lines.unsigned_abs() {
                    index = next_mode(&list, index, lines > 0);
                }
            }
            Some(Input::Click(line)) => {
                if let Some(i) = line.checked_sub(top).map(|row| row + offset) {
                    if let Some(Row::Mode(mode)) = list.get(i) {
                        index = i;
                        open = Some(*mode);
                    }
                }
            }
            Some(Input::Key(key)) => {
                if input::is_interrupt(&key) {
                    bail!(input::CANCELLED);
                }
                match input::mapped_code(&key) {
                    KeyCode::Up | KeyCode::Char('w' | 'W') => {
                        index = next_mode(&list, index, false)
                    }
                    KeyCode::Down | KeyCode::Char('s' | 'S') => {
                        index = next_mode(&list, index, true)
                    }
                    KeyCode::Home => index = next_mode(&list, list.len() - 1, true),
                    KeyCode::End => index = next_mode(&list, 0, false),
                    KeyCode::Tab | KeyCode::BackTab => {
                        let current = match &list[index] {
                            Row::Mode(mode) => Some(*mode),
                            Row::Header(_) => None,
                        };
                        all = !all;
                        list = rows(all);
                        index = list
                            .iter()
                            .position(|row| matches!(row, Row::Mode(m) if Some(*m) == current))
                            .unwrap_or_else(|| next_mode(&list, 0, true));
                    }
                    KeyCode::Enter | KeyCode::Char(' ') => {
                        if let Row::Mode(mode) = &list[index] {
                            open = Some(*mode);
                        }
                    }
                    KeyCode::Esc | KeyCode::Char('q' | 'Q') => return Ok(()),
                    _ => {}
                }
            }
        }
        if let Some(mode) = open {
            if needs_repo_notice(mode, crate::repo_state::in_repo()) {
                not_a_repo(mode)?;
            } else {
                let result = run_mode(mode, config);
                show_result(mode, result)?;
            }
            // Only reload after a mode returns (it may have changed the repository).
            repo = load_line();
        }
    }
}

/// The commit flow is not a repository mode (plain `gct` keeps its own error), but from the hub
/// a missing repository gets the same neutral notice as the repository modes.
fn needs_repo_notice(mode: Mode, in_repo: bool) -> bool {
    !in_repo && mode.name() == "commit"
}

/// Keeps row `index` visible.
fn ui_scroll(index: usize, offset: usize, visible: usize) -> usize {
    // Show the group header too when the first mode of a group is selected at the top.
    let wanted = index.saturating_sub(1);
    if wanted < offset {
        wanted
    } else if index >= offset + visible {
        index + 1 - visible
    } else {
        offset
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::repo_state::{BranchInfo, Entry};

    fn names(rows: &[Row]) -> Vec<String> {
        rows.iter()
            .map(|row| match row {
                Row::Header(group) => format!("[{}]", group.title()),
                Row::Mode(mode) => mode.name().to_string(),
            })
            .collect()
    }

    #[test]
    fn basic_and_all_rows() {
        let basic = names(&rows(false));
        assert_eq!(basic[0], "[Start]");
        assert!(!basic.contains(&"hub".to_string()));
        assert!(!basic.contains(&"stash".to_string()));
        assert!(basic.contains(&"commit".to_string()));
        assert!(
            !basic.contains(&"[Release]".to_string()),
            "tag is advanced: {basic:?}"
        );
        let all = names(&rows(true));
        assert!(all.contains(&"stash".to_string()) && all.contains(&"[Release]".to_string()));
        assert_eq!(all.iter().filter(|n| !n.starts_with('[')).count(), 20);
        let list = rows(false);
        assert_eq!(next_mode(&list, 0, true), 1);
        assert_eq!(next_mode(&list, 1, false), list.len() - 1);
        assert!(matches!(
            list[next_mode(&list, list.len() - 1, true)],
            Row::Mode(_)
        ));
    }

    #[test]
    fn commit_outside_repo_gets_the_neutral_notice() {
        let commit = Mode::parse("commit").unwrap();
        assert!(needs_repo_notice(commit, false));
        assert!(!needs_repo_notice(commit, true));
        // Repository modes get the notice from run_mode; the others never need a repo.
        for name in ["stage", "settings", "account", "start", "guide"] {
            assert!(
                !needs_repo_notice(Mode::parse(name).unwrap(), false),
                "{name}"
            );
        }
    }

    #[test]
    fn scroll_shows_the_group_header() {
        assert_eq!(ui_scroll(1, 0, 5), 0);
        assert_eq!(ui_scroll(1, 3, 5), 0, "moving up shows the header above");
        assert_eq!(ui_scroll(9, 0, 5), 5);
        assert_eq!(ui_scroll(4, 2, 5), 2);
        assert_eq!(ui_scroll(0, 0, 1), 0);
    }

    #[test]
    fn repo_line_text() {
        assert_eq!(repo_line(None), "Not in a git repository");
        let mut state = RepoState {
            branch: BranchInfo {
                head: Head::Branch {
                    name: "main".into(),
                    oid: "abc".into(),
                },
                upstream: None,
                ahead: 0,
                behind: 0,
                stash_count: 0,
                upstream_gone: false,
            },
            entries: vec![],
            op: None,
            git_dir: Default::default(),
            workdir: Default::default(),
        };
        assert_eq!(repo_line(Some(&state)), "main · clean");
        state.entries.push(Entry {
            path: "a".into(),
            orig_path: None,
            x: '?',
            y: '?',
            kind: EntryKind::Untracked,
        });
        assert_eq!(repo_line(Some(&state)), "main · 1 change");
        state.branch.head = Head::Detached {
            oid: "1234567890".into(),
        };
        assert_eq!(repo_line(Some(&state)), "detached at 1234567 · 1 change");
    }
}