git-custom-cli 2.4.0

Fast, keyboard-driven terminal UI for dated Git commits
//! Settings screen: default mode, default remote, destructive-action confirms, git command echo
//! and the theme. Left/Right cycle or toggle, Enter edits text (or toggles), Delete clears the
//! accent, Esc/Q saves and returns. Theme changes apply live.

use super::Mode;
use crate::{config, input, model::Config, screen, ui};
use anyhow::{bail, Result};
use crossterm::event::KeyCode;

const SETTINGS_HINT: &str =
    "Up/Down move  ·  Left/Right change  ·  Enter edit  ·  Del clear accent  ·  Esc/Q save & back";
const ROWS: usize = 10;
const EXPERIENCE: usize = 8;
const PROTECTED: usize = 9;
const LEVELS: [&str; 3] = ["beginner", "normal", "pro"];

/// Runs the screen, then saves the config even when the screen was cancelled.
pub fn run(config: &mut Config) -> Result<()> {
    let result = screen_loop(config);
    config::save(config)?;
    result
}

/// Modes offered as the default. Settings, Hub and Commands are not offered (Settings and
/// Commands are not sensible start screens; Hub is opened with `gct --hub`). Repository modes
/// are allowed: outside a repository plain `gct` then behaves like the commit default.
fn default_choices() -> Vec<Mode> {
    const EXCLUDED: [&str; 2] = ["settings", "commands"];
    Mode::all()
        .filter(|m| !EXCLUDED.contains(&m.name()))
        .collect()
}

/// Next experience level after `current`, `step` places away, wrapping (unknown = normal).
fn cycle_experience(current: &str, step: i32) -> &'static str {
    let at = LEVELS
        .iter()
        .position(|level| level.eq_ignore_ascii_case(current.trim()))
        .unwrap_or(1) as i32;
    LEVELS[(at + step).rem_euclid(LEVELS.len() as i32) as usize]
}

/// Sets the experience level. Switching TO beginner turns on the safety prompts and the git
/// command echo once; the user may turn them off again afterwards.
fn set_experience(config: &mut Config, level: &str) {
    let was_beginner = config.experience.trim().eq_ignore_ascii_case("beginner");
    config.experience = level.to_string();
    if level == "beginner" && !was_beginner {
        config.confirm_destructive = true;
        config.show_commands = true;
    }
}

/// "main, release/*" -> ["main", "release/*"]; blanks dropped, duplicates removed.
fn parse_protected(text: &str) -> Vec<String> {
    let mut out: Vec<String> = Vec::new();
    for name in text
        .split(',')
        .map(str::trim)
        .filter(|name| !name.is_empty())
    {
        if !out.iter().any(|existing| existing == name) {
            out.push(name.to_string());
        }
    }
    out
}

/// Next default mode name after `current`, `step` places away, wrapping around.
fn cycle_mode(current: &str, step: i32) -> String {
    let choices = default_choices();
    let at = choices
        .iter()
        .position(|m| *m == Mode::from_config(current))
        .unwrap_or(0) as i32;
    let next = (at + step).rem_euclid(choices.len() as i32) as usize;
    choices[next].name().to_string()
}

/// None when `value` is a valid `#RRGGBB` (or `RRGGBB`) accent.
fn accent_problem(value: &str) -> Option<&'static str> {
    let theme = crate::model::Theme {
        accent: Some(value.to_string()),
        ..crate::model::Theme::default()
    };
    theme
        .accent_rgb()
        .is_none()
        .then_some("Accent must look like #RRGGBB, e.g. #10b981")
}

fn on_off(value: bool) -> &'static str {
    if value {
        "on"
    } else {
        "off"
    }
}

fn rows(config: &Config) -> [(&'static str, String); ROWS] {
    let theme = &config.theme;
    [
        (
            "Default mode",
            Mode::from_config(&config.default_mode).name().to_string(),
        ),
        ("Default remote", config.default_remote.clone()),
        (
            "Confirm destructive",
            on_off(config.confirm_destructive).into(),
        ),
        ("Show git commands", on_off(config.show_commands).into()),
        (
            "Theme accent",
            theme
                .accent
                .clone()
                .filter(|a| !a.is_empty())
                .unwrap_or_else(|| "default".into()),
        ),
        ("Show header", on_off(theme.show_header).into()),
        ("Show mascot", on_off(theme.show_mascot).into()),
        ("Show subtitle", on_off(theme.show_subtitle).into()),
        ("Experience", cycle_experience(&config.experience, 0).into()),
        (
            "Protected branches",
            if config.protected_branches.is_empty() {
                "none".into()
            } else {
                config.protected_branches.join(", ")
            },
        ),
    ]
}

/// Flips a toggle row; returns false for rows that are not toggles.
fn toggle(config: &mut Config, row: usize) -> bool {
    let flag = match row {
        2 => &mut config.confirm_destructive,
        3 => &mut config.show_commands,
        5 => &mut config.theme.show_header,
        6 => &mut config.theme.show_mascot,
        7 => &mut config.theme.show_subtitle,
        _ => return false,
    };
    *flag = !*flag;
    true
}

fn screen_loop(config: &mut Config) -> Result<()> {
    let mut index = 0usize;
    let mut notice: Option<String> = None;
    loop {
        let mut body = vec![screen::accent("SETTINGS"), String::new()];
        for (row, (label, value)) in rows(config).iter().enumerate() {
            let value = if row == index && row != 1 && row != 4 && row != PROTECTED {
                format!("◀ {value} ▶")
            } else {
                value.clone()
            };
            body.push(input::styled_menu_line(
                row == index,
                &format!("{label:<20}: {value}"),
            ));
        }
        body.push(String::new());
        body.push(screen::muted(
            "Changes are saved when you leave this screen.",
        ));
        if let Some(message) = &notice {
            body.push(String::new());
            body.push(screen::danger(message));
        }
        screen::draw(&body, SETTINGS_HINT, None)?;

        let Some(key) = input::read_key()? else {
            continue;
        };
        notice = None;
        if input::is_interrupt(&key) {
            bail!(input::CANCELLED);
        }
        match input::mapped_code(&key) {
            KeyCode::Up | KeyCode::Char('w' | 'W') => index = (index + ROWS - 1) % ROWS,
            KeyCode::Down | KeyCode::Char('s' | 'S') => index = (index + 1) % ROWS,
            KeyCode::Home => index = 0,
            KeyCode::End => index = ROWS - 1,
            KeyCode::Esc | KeyCode::Char('q' | 'Q') => return Ok(()),
            code @ (KeyCode::Left | KeyCode::Right) => {
                let step = if code == KeyCode::Left { -1 } else { 1 };
                if index == 0 {
                    config.default_mode = cycle_mode(&config.default_mode, step);
                } else if index == EXPERIENCE {
                    let level = cycle_experience(&config.experience, step);
                    set_experience(config, level);
                } else {
                    toggle(config, index);
                }
            }
            KeyCode::Enter | KeyCode::Char(' ') => match index {
                0 => config.default_mode = cycle_mode(&config.default_mode, 1),
                1 => {
                    if let Some(remote) = ui::ask("Default remote:", &config.default_remote)? {
                        let remote = remote.trim();
                        if remote.contains(char::is_whitespace) {
                            notice = Some("A remote name cannot contain spaces".into());
                        } else {
                            config.default_remote = remote.to_string();
                        }
                    }
                }
                4 => {
                    let current = config.theme.accent.clone().unwrap_or_default();
                    if let Some(value) = ui::ask("Accent color (#RRGGBB):", &current)? {
                        let value = value.trim().to_string();
                        match accent_problem(&value) {
                            Some(problem) => notice = Some(problem.into()),
                            None => config.theme.accent = Some(value),
                        }
                    }
                }
                EXPERIENCE => {
                    let level = cycle_experience(&config.experience, 1);
                    set_experience(config, level);
                }
                PROTECTED => {
                    let current = config.protected_branches.join(", ");
                    let prompt = "Protected branches (comma-separated, prefix* allowed):";
                    if let Some(value) = ui::ask(prompt, &current)? {
                        let parsed = parse_protected(&value);
                        if parsed.is_empty() {
                            notice = Some("Keep at least one protected branch".into());
                        } else {
                            config.protected_branches = parsed;
                        }
                    }
                }
                _ => {
                    toggle(config, index);
                }
            },
            KeyCode::Delete | KeyCode::Backspace if index == PROTECTED => {
                config.protected_branches = Config::default().protected_branches
            }
            KeyCode::Delete | KeyCode::Backspace if index == 4 => config.theme.accent = None,
            KeyCode::Delete | KeyCode::Backspace if index == 1 => {
                config.default_remote = "origin".into()
            }
            _ => {}
        }
        crate::apply_theme(config);
    }
}

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

    #[test]
    fn default_mode_cycles_without_settings_and_commands() {
        assert_eq!(cycle_mode("commit", 1), "account");
        assert_eq!(cycle_mode("account", 1), "hub");
        assert_eq!(cycle_mode("hub", 1), "status");
        assert_eq!(cycle_mode("status", -1), "hub");
        // The last registered mode wraps to the first.
        assert_eq!(cycle_mode("commit", -1), "start");
        assert_eq!(cycle_mode("start", 1), "commit");
        assert_eq!(cycle_mode("tag", 1), "log");
        assert_eq!(cycle_mode("garbage", 1), "account");
        // A hand-edited default that is not offered (settings, commands) still moves to a valid choice.
        assert_eq!(cycle_mode("commands", 1), "account");
        let mut name = "commit".to_string();
        let mut seen = Vec::new();
        for _ in 0..default_choices().len() {
            name = cycle_mode(&name, 1);
            assert!(!["settings", "commands"].contains(&name.as_str()), "{name}");
            seen.push(name.clone());
        }
        assert_eq!(name, "commit", "a full cycle comes back");
        assert!(
            seen.contains(&"stage".to_string()),
            "repository modes stay allowed"
        );
    }

    #[test]
    fn rows_show_current_values() {
        let mut config = Config::default();
        let shown = rows(&config);
        assert_eq!(shown[0], ("Default mode", "commit".to_string()));
        assert_eq!(shown[1].1, "origin");
        assert_eq!(shown[4].1, "default");
        assert_eq!(shown[EXPERIENCE].1, cycle_experience(&config.experience, 0));
        config.default_mode = "RESCUE".into();
        config.theme.accent = Some(String::new());
        config.protected_branches.clear();
        config.experience = "junk".into();
        let shown = rows(&config);
        assert_eq!(shown[0].1, "undo");
        assert_eq!(shown[4].1, "default");
        assert_eq!(shown[EXPERIENCE].1, "normal");
        assert_eq!(shown[PROTECTED].1, "none");
        config.protected_branches = vec!["main".into(), "release/*".into()];
        assert_eq!(rows(&config)[PROTECTED].1, "main, release/*");
        assert_eq!(rows(&config).len(), ROWS);
    }

    #[test]
    fn accent_check_and_toggles() {
        assert!(accent_problem("#10b981").is_none());
        assert!(accent_problem("nope").is_some());
        let mut config = Config::default();
        assert!(toggle(&mut config, 2));
        assert!(!config.confirm_destructive);
        assert!(!toggle(&mut config, 0));
        assert!(!toggle(&mut config, 4));
        assert!(!toggle(&mut config, EXPERIENCE));
        assert!(!toggle(&mut config, PROTECTED));
    }

    #[test]
    fn experience_cycles_and_beginner_turns_on_safety_once() {
        assert_eq!(cycle_experience("normal", 1), "pro");
        assert_eq!(cycle_experience("pro", 1), "beginner");
        assert_eq!(cycle_experience("beginner", -1), "pro");
        assert_eq!(cycle_experience("junk", 0), "normal");
        let mut config = Config {
            confirm_destructive: false,
            show_commands: false,
            ..Config::default()
        };
        set_experience(&mut config, "beginner");
        assert!(config.confirm_destructive && config.show_commands);
        config.show_commands = false;
        set_experience(&mut config, "beginner");
        assert!(!config.show_commands, "only when switching to beginner");
        set_experience(&mut config, "pro");
        assert_eq!(config.experience, "pro");
        assert!(!config.show_commands);
    }

    #[test]
    fn protected_list_parsing() {
        assert_eq!(
            parse_protected(" main, release/* ,,main, dev "),
            ["main", "release/*", "dev"]
        );
        assert!(parse_protected(" , ").is_empty());
    }
}