git-custom-cli 2.4.0

Fast, keyboard-driven terminal UI for dated Git commits
//! Commands mode: every git command gct ran in this session (newest first), with exit code and
//! duration. Enter shows one command in full. Secrets are masked by `cmdlog`.

use crate::{
    cmdlog::{self, Entry},
    model::Config,
    screen,
    ui::{self, Choice},
};
use anyhow::Result;

pub fn run(config: &mut Config) -> Result<()> {
    let _ = config;
    let mut index = 0usize;
    loop {
        let entries = cmdlog::entries();
        let header = vec![screen::muted(if entries.is_empty() {
            "No git commands have run yet in this session.".to_string()
        } else {
            format!(
                "{} commands, newest first. Enter shows one in full.",
                entries.len()
            )
        })];
        let rows: Vec<String> = entries.iter().map(row).collect();
        match ui::action_list("GIT COMMANDS", &header, &rows, &[], &mut index)? {
            Choice::Open(i) if i < entries.len() => {
                ui::pager("Git command", &detail(&entries[i]), "")?;
            }
            Choice::Open(_) | Choice::Action(..) => {}
            Choice::Back => return Ok(()),
        }
    }
}

fn status(code: Option<i32>) -> String {
    match code {
        Some(0) => screen::success("ok"),
        Some(code) => screen::danger(format!("exit {code}")),
        None => screen::warning("stopped"),
    }
}

fn row(entry: &Entry) -> String {
    format!(
        "{}  {:>6}  {}  git {}",
        screen::muted(&entry.at),
        format!("{}ms", entry.ms),
        status(entry.code),
        crate::model::preview(&entry.args, 90)
    )
}

fn detail(entry: &Entry) -> Vec<String> {
    vec![
        format!("$ git {}", entry.args),
        String::new(),
        format!("Result:   {}", status(entry.code)),
        format!("Duration: {} ms", entry.ms),
        format!("At:       {}", entry.at),
    ]
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn rows_and_details() {
        let entry = Entry {
            args: "status --short".into(),
            code: Some(1),
            ms: 12,
            at: "10:00:00".into(),
        };
        let line = row(&entry);
        assert!(line.contains("git status --short") && line.contains("12ms"));
        assert!(line.contains("exit 1"));
        assert_eq!(detail(&entry)[0], "$ git status --short");
        assert!(status(None).contains("stopped"));
    }
}