git-custom-cli 1.0.0

Fast, keyboard-driven terminal UI for dated Git commits
use anyhow::{anyhow, bail, Context, Result};
use crossterm::event::{self, Event, KeyCode, KeyEventKind, KeyModifiers};
use std::{
    fs,
    process::{Command, Stdio},
};

use crate::{
    model::{current_year, truncate, valid_date, valid_time, Values},
    screen,
};

pub fn menu(values: &Values) -> Result<String> {
    let mode = match (values.amend, values.dry_run) {
        (true, true) => "amend, dry-run",
        (true, false) => "amend",
        (false, true) => "dry-run",
        _ => "normal",
    };
    let message = if values.message.is_empty() {
        "[not set]".into()
    } else {
        truncate(&values.message, 40)
    };
    let choices = [
        format!(
            "Edit date     : {}",
            if values.date.is_empty() {
                "[not set]"
            } else {
                &values.date
            }
        ),
        format!(
            "Edit time     : {}",
            if values.time.is_empty() {
                "[not set]"
            } else {
                &values.time
            }
        ),
        format!(
            "Edit branch   : {}",
            if values.branch.is_empty() {
                "[not set]"
            } else {
                &values.branch
            }
        ),
        format!("Edit message  : {message}"),
        format!("Edit msg (editor): {message}"),
        format!("Edit options  : {mode}"),
        "------------".into(),
        "Finalize & commit".into(),
    ];
    let ready = [
        !values.date.is_empty(),
        !values.time.is_empty(),
        !values.branch.is_empty(),
        !values.message.trim().is_empty(),
    ]
    .into_iter()
    .filter(|ready| *ready)
    .count();
    let mut index = 7usize;
    loop {
        let mut lines = vec![
            screen::accent(format!("MISSION CONTROL  [{ready}/4 FIELDS READY]")),
            screen::muted("Navigate with arrows or W/S  ยท  Enter to select"),
            String::new(),
        ];
        for (position, choice) in choices.iter().enumerate() {
            if position == 6 {
                lines.push("  \x1b[90m------------\x1b[0m".into());
            } else {
                lines.push(styled_menu_line(position == index, choice));
            }
        }
        screen::draw(&lines, None)?;
        if let Event::Key(key) = event::read()? {
            if key.kind != KeyEventKind::Press {
                continue;
            }
            match key.code {
                KeyCode::Up | KeyCode::Char('w') => index = previous_choice(index),
                KeyCode::Down | KeyCode::Char('s') => index = next_choice(index),
                KeyCode::Enter | KeyCode::Char(' ') => {
                    return Ok(match index {
                        0 => "date",
                        1 => "time",
                        2 => "branch",
                        3 => "message",
                        4 => "editor",
                        5 => "options",
                        _ => "finalize",
                    }
                    .into())
                }
                KeyCode::Esc | KeyCode::Char('q') => bail!("Cancelled"),
                _ => {}
            }
        }
    }
}

fn styled_menu_line(active: bool, text: &str) -> String {
    if active {
        screen::selected(format!("  โ–ถ {text}"))
    } else {
        format!("  {}", screen::muted(format!("โ—‡ {text}")))
    }
}

fn previous_choice(index: usize) -> usize {
    if index <= 1 {
        7
    } else if index == 7 {
        5
    } else {
        index - 1
    }
}

fn next_choice(index: usize) -> usize {
    if index >= 5 {
        0
    } else {
        index + 1
    }
}

pub fn read_line(prompt: &str, initial: &str, multiline: bool) -> Result<String> {
    let mut value = initial.to_string();
    let mut cursor_pos = value.len();
    loop {
        let mut lines = vec![prompt.to_string()];
        if multiline {
            lines.push("  Ctrl+S to save  ยท  Esc to cancel".into());
        }
        lines.extend(value.lines().map(str::to_owned));
        if value.is_empty() {
            lines.push(String::new());
        }
        screen::draw(
            &lines,
            Some((if multiline { 2 } else { 0 }, cursor_pos as u16)),
        )?;
        if let Event::Key(key) = event::read()? {
            if key.kind != KeyEventKind::Press {
                continue;
            }
            if key.modifiers.contains(KeyModifiers::CONTROL)
                && (key.code == KeyCode::Char('s') || key.code == KeyCode::Enter)
            {
                if value.trim().is_empty() {
                    screen::error("Message is required")?;
                    continue;
                }
                return Ok(value.trim().into());
            }
            match key.code {
                KeyCode::Esc => return Ok(initial.into()),
                KeyCode::Enter if multiline => value.insert(cursor_pos, '\n'),
                KeyCode::Enter => {
                    if value.trim().is_empty() {
                        screen::error("Value is required")?;
                        continue;
                    }
                    return Ok(value.trim().into());
                }
                KeyCode::Backspace if cursor_pos > 0 => {
                    value.remove(cursor_pos - 1);
                    cursor_pos -= 1;
                }
                KeyCode::Left if cursor_pos > 0 => cursor_pos -= 1,
                KeyCode::Right if cursor_pos < value.len() => cursor_pos += 1,
                KeyCode::Home => cursor_pos = 0,
                KeyCode::End => cursor_pos = value.len(),
                KeyCode::Char(ch) if !key.modifiers.contains(KeyModifiers::CONTROL) => {
                    value.insert(cursor_pos, ch);
                    cursor_pos += ch.len_utf8();
                }
                _ => {}
            }
        }
    }
}

pub fn masked(prompt: &str, initial: &str, date: bool) -> Result<String> {
    let template = if date { "YYYY-MM-DD" } else { "hh:mm:ss" };
    let fallback = if date {
        format!("{}-__-__", current_year())
    } else {
        "00:__:__".into()
    };
    let initial_is_valid = (date && valid_date(initial)) || (!date && valid_time(initial));
    let mut chars: Vec<char> = if initial_is_valid {
        initial.chars().collect()
    } else {
        fallback.chars().collect()
    };
    let slots: Vec<usize> = chars
        .iter()
        .enumerate()
        .filter_map(|(index, value)| {
            (*value == '_'
                || template.chars().nth(index).is_some_and(|token| {
                    token == 'Y'
                        || token == 'M'
                        || token == 'D'
                        || token == 'h'
                        || token == 'm'
                        || token == 's'
                }))
            .then_some(index)
        })
        .collect();
    let mut slot = 0usize;
    loop {
        let rendered: String = chars
            .iter()
            .enumerate()
            .map(|(index, value)| {
                if slots[slot] == index {
                    format!("\x1b[7;36m{value}\x1b[0m")
                } else {
                    value.to_string()
                }
            })
            .collect();
        let column = prompt.chars().count() as u16 + 1 + slots[slot] as u16;
        screen::draw(&[format!("{prompt} {rendered}")], Some((0, column)))?;
        if let Event::Key(key) = event::read()? {
            if key.kind != KeyEventKind::Press {
                continue;
            }
            match key.code {
                KeyCode::Char(ch) if ch.is_ascii_digit() => {
                    chars[slots[slot]] = ch;
                    if slot + 1 < slots.len() {
                        slot += 1;
                    }
                }
                KeyCode::Left => slot = slot.saturating_sub(1),
                KeyCode::Right => slot = (slot + 1).min(slots.len() - 1),
                KeyCode::Home => slot = 0,
                KeyCode::End => slot = slots.len() - 1,
                KeyCode::Backspace => {
                    chars[slots[slot]] = '_';
                    slot = slot.saturating_sub(1);
                }
                KeyCode::Delete => chars[slots[slot]] = '_',
                KeyCode::Esc => return Ok(initial.into()),
                KeyCode::Char('c') if key.modifiers.contains(KeyModifiers::CONTROL) => {
                    bail!("Cancelled")
                }
                KeyCode::Enter => {
                    let result: String = chars.iter().collect();
                    if result.contains('_') {
                        screen::error("Complete all fields before continuing")?;
                        continue;
                    }
                    if (date && !valid_date(&result)) || (!date && !valid_time(&result)) {
                        screen::error(if date {
                            "Not a valid calendar date"
                        } else {
                            "Time out of range (00:00:00 - 23:59:59)"
                        })?;
                        continue;
                    }
                    return Ok(result);
                }
                _ => {}
            }
        }
    }
}

pub fn external_editor(initial: &str) -> Result<String> {
    let path = std::env::temp_dir().join(format!("git-cc-{}.txt", std::process::id()));
    fs::write(&path, initial)?;
    let editor = std::env::var("VISUAL")
        .or_else(|_| std::env::var("EDITOR"))
        .unwrap_or_else(|_| {
            if cfg!(windows) {
                "notepad".into()
            } else {
                "vi".into()
            }
        });
    let mut parts = editor.split_whitespace();
    let program = parts.next().context("editor command is empty")?;
    let status = Command::new(program)
        .args(parts)
        .arg(&path)
        .stdin(Stdio::inherit())
        .stdout(Stdio::inherit())
        .stderr(Stdio::inherit())
        .status();
    let result = match status {
        Ok(status) if status.success() => {
            fs::read_to_string(&path).context("could not read editor output")
        }
        Ok(status) => Err(anyhow!("editor exited with status {status}")),
        Err(error) => Err(error.into()),
    };
    let _ = fs::remove_file(&path);
    let message = result?;
    if message.trim().is_empty() {
        bail!("Commit message is required");
    }
    Ok(message.trim().into())
}

pub fn options(values: &mut Values) -> Result<()> {
    values.amend = confirm(
        "Amend the last commit instead of creating a new one?",
        false,
    )?;
    values.dry_run = confirm("Preview only (dry run, do not commit/push)?", false)?;
    Ok(())
}

pub fn confirm(prompt: &str, default: bool) -> Result<bool> {
    loop {
        screen::draw(
            &[format!(
                "{prompt} ({})",
                if default { "Y/n" } else { "y/N" }
            )],
            None,
        )?;
        if let Event::Key(key) = event::read()? {
            if key.kind != KeyEventKind::Press {
                continue;
            }
            match key.code {
                KeyCode::Enter => return Ok(default),
                KeyCode::Char('y') | KeyCode::Char('Y') => return Ok(true),
                KeyCode::Char('n') | KeyCode::Char('N') => return Ok(false),
                KeyCode::Char('c') if key.modifiers.contains(KeyModifiers::CONTROL) => {
                    bail!("Cancelled")
                }
                _ => {}
            }
        }
    }
}