use anyhow::{anyhow, bail, Context, Result};
use crossterm::event::{
self, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers, MouseButton, MouseEventKind,
};
use std::{
fs,
process::{Command, Stdio},
};
use crate::{
accounts::{self, invalidate_logins, Account},
git, gitconfig,
model::{
adjust, current_year, extra_keys, preset_date, preset_time, preview, valid_date, valid_time, Config,
Values,
},
screen,
};
pub const CANCELLED: &str = "Cancelled";
const MENU_HINT: &str = "Up/Down move · Left/Right change · Enter or click select · Esc/Q quit · Ctrl+C quit";
const MENU_HINT_SHORT: &str = "Up/Down Left/Right change Enter Esc quit";
const TREE_HINT: &str =
"Up/Down or W/S scroll · PgUp/PgDn · Home/End · Esc/Q back · Ctrl+C quit";
const CONFIRM_HINT: &str = "Y yes · N no · Enter default · Ctrl+C quit";
const LINE_HINT: &str = "Enter save · Esc cancel · Ctrl+C quit";
const MESSAGE_HINT: &str =
"Click Save & go back · Tab+Enter or Ctrl+Enter save · Esc leave without saving · Enter new line";
const MASK_HINT: &str =
"Digits type · n/y/-/+ presets · Left/Right move · Backspace clear · Enter save · Esc cancel";
const HISTORY_HINT: &str =
"Tab switch · Up/Down or W/S scroll · PgUp/PgDn · Home/End · Esc/Q back · Ctrl+C quit";
const PICK_HINT: &str = "Up/Down or W/S move · Enter select · Esc/Q cancel · Ctrl+C quit";
const ACCOUNTS_HINT: &str = "Up/Down or W/S move · Enter/Space set active · A add · E edit · D delete · L sign in · R refresh · Esc/Q back · Ctrl+C quit";
enum Input {
Key(KeyEvent),
Click(usize),
}
fn read_input() -> Result<Option<Input>> {
loop {
match event::read()? {
Event::Key(key) if key.kind == KeyEventKind::Press => return Ok(Some(Input::Key(key))),
Event::Mouse(mouse) if mouse.kind == MouseEventKind::Down(MouseButton::Left) => {
if let Some(line) = screen::body_line(mouse.row) {
return Ok(Some(Input::Click(line)));
}
}
Event::Mouse(mouse) if screen::track_pointer(mouse.column) => return Ok(None),
Event::Resize(..) => {
screen::invalidate();
return Ok(None);
}
_ => {}
}
}
}
fn read_key() -> Result<Option<KeyEvent>> {
loop {
match read_input()? {
Some(Input::Key(key)) => return Ok(Some(key)),
Some(Input::Click(_)) => {}
None => return Ok(None),
}
}
}
fn is_interrupt(key: &KeyEvent) -> bool {
key.code == KeyCode::Char('c') && key.modifiers.contains(KeyModifiers::CONTROL)
}
pub fn is_cancel(error: &anyhow::Error) -> bool {
error.to_string() == CANCELLED
}
pub fn wait_key(body: &[String], footer: &str) -> Result<()> {
loop {
screen::draw(body, footer, None)?;
if read_key()?.is_some() {
return Ok(());
}
}
}
pub fn menu(
context: &[String],
values: &mut Values,
notice: Option<&str>,
index: &mut usize,
active: &str,
branches: &[String],
) -> Result<String> {
loop {
let choices = menu_choices(values, active, *index);
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 body = context.to_vec();
body.push(String::new());
body.push(screen::accent(format!(
"MISSION CONTROL [{ready}/4 FIELDS READY]"
)));
for (position, choice) in choices.iter().enumerate() {
body.push(if position == SEPARATOR {
screen::muted(" ------------")
} else {
styled_menu_line(position == *index, choice)
});
}
if let Some(notice) = notice {
body.push(String::new());
body.push(screen::danger(notice));
}
let selected_line = context.len() + 2 + *index;
let offset = selected_line.saturating_sub(screen::body_rows().saturating_sub(1));
let narrow = crossterm::terminal::size()
.is_ok_and(|(width, _)| (width as usize) < MENU_HINT.chars().count() + 6);
let hint = if narrow { MENU_HINT_SHORT } else { MENU_HINT };
screen::draw(&body[offset.min(body.len())..], hint, None)?;
let key = match read_input()? {
None => continue,
Some(Input::Key(key)) => key,
Some(Input::Click(line)) if (2..context.len()).contains(&(line + offset)) => {
return Ok("tree".into())
}
Some(Input::Click(line)) => {
let line = line + offset;
match line.checked_sub(context.len() + 2) {
Some(position) if position < choices.len() && position != SEPARATOR => {
*index = position;
return Ok(choice_name(position).into());
}
_ => continue,
}
}
};
if is_interrupt(&key) {
bail!(CANCELLED);
}
let mut code = key.code;
if let KeyCode::Char(ch) = code {
if !key.modifiers.contains(KeyModifiers::CONTROL)
&& !matches!(ch, 'w' | 'W' | 's' | 'S' | 'q' | 'Q' | ' ')
{
let has = |action: &str| extra_keys(action).contains(&ch);
if has("up") {
code = KeyCode::Up;
} else if has("down") {
code = KeyCode::Down;
} else if has("select") {
code = KeyCode::Enter;
} else if has("quit") {
code = KeyCode::Esc;
} else if has("first") {
code = KeyCode::Home;
} else if has("last") {
code = KeyCode::End;
}
}
}
match code {
KeyCode::Up | KeyCode::BackTab | KeyCode::Char('w' | 'W') => {
*index = previous_choice(*index)
}
KeyCode::Down | KeyCode::Tab | KeyCode::Char('s' | 'S') => {
*index = next_choice(*index)
}
KeyCode::Home | KeyCode::PageUp => *index = 0,
KeyCode::End | KeyCode::PageDown => *index = FINALIZE,
KeyCode::Left | KeyCode::Right => {
let delta = if code == KeyCode::Left { -1 } else { 1 };
match *index {
0 | 1 | 2 | 5 => {
adjust(values, *index, delta, branches);
}
8 => {
return Ok(if delta < 0 {
"account-prev"
} else {
"account-next"
}
.into())
}
_ => {}
}
}
KeyCode::Enter | KeyCode::Char(' ') => return Ok(choice_name(*index).into()),
KeyCode::Esc | KeyCode::Char('q' | 'Q') => bail!(CANCELLED),
_ => {}
}
}
}
fn menu_choices(values: &Values, active: &str, index: usize) -> Vec<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 {
preview(&values.message, 40)
};
let shown = |value: &str| {
if value.is_empty() {
"[not set]".to_string()
} else {
value.to_string()
}
};
let arrows = |row: usize, value: String| {
if row == index {
format!("◀ {value} ▶")
} else {
value
}
};
vec![
format!("Edit date : {}", arrows(0, shown(&values.date))),
format!("Edit time : {}", arrows(1, shown(&values.time))),
format!("Edit branch : {}", arrows(2, shown(&values.branch))),
format!("Edit message : {message}"),
format!("Edit msg (editor): {message}"),
format!("Edit options : {}", arrows(5, mode.to_string())),
"View history".into(),
"View working tree".into(),
format!("Account: {}", arrows(8, active.to_string())),
"Push only".into(),
"------------".into(),
"Finalize & commit".into(),
]
}
const SEPARATOR: usize = 10;
const FINALIZE: usize = 11;
fn choice_name(index: usize) -> &'static str {
match index {
0 => "date",
1 => "time",
2 => "branch",
3 => "message",
4 => "editor",
5 => "options",
6 => "history",
7 => "tree",
8 => "account",
9 => "push",
_ => "finalize",
}
}
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 {
match index {
0 => FINALIZE,
FINALIZE => 9,
_ => index - 1,
}
}
fn next_choice(index: usize) -> usize {
match index {
9 => FINALIZE,
FINALIZE => 0,
_ => index + 1,
}
}
pub fn working_tree() -> Result<()> {
let rows = match git::status_lines() {
Ok(lines) => lines,
Err(error) => vec![screen::danger(format!("Could not read status: {error}"))],
};
let title = if rows == ["(clean working tree)"] {
screen::success("Working tree clean")
} else {
screen::warning(format!(
"Working tree: {} changes (all are staged by commit)",
rows.len()
))
};
let mut offset = 0usize;
loop {
let visible = screen::body_rows().saturating_sub(1);
offset = offset.min(rows.len().saturating_sub(visible));
let mut body = vec![title.clone()];
body.extend(rows.iter().skip(offset).take(visible).cloned());
screen::draw(&body, TREE_HINT, None)?;
let Some(key) = read_key()? else { continue };
if is_interrupt(&key) {
bail!(CANCELLED);
}
match key.code {
KeyCode::Up | KeyCode::Char('w' | 'W') => offset = offset.saturating_sub(1),
KeyCode::Down | KeyCode::Char('s' | 'S') => offset = offset.saturating_add(1),
KeyCode::PageUp => offset = offset.saturating_sub(visible),
KeyCode::PageDown => offset = offset.saturating_add(visible),
KeyCode::Home => offset = 0,
KeyCode::End => offset = usize::MAX,
KeyCode::Esc | KeyCode::Char('q' | 'Q') => return Ok(()),
_ => {}
}
}
}
pub fn history() -> Result<()> {
let head = match git::current_branch() {
Ok(name) if name == "HEAD" => "detached HEAD".to_string(),
Ok(name) => match git::upstream(&name) {
Ok(Some(upstream)) => format!("{name} -> {upstream}"),
_ => format!("{name} (no upstream)"),
},
Err(error) => format!("Branch unknown: {error}"),
};
let commits: Vec<String> = match git::recent_commits(200) {
Ok(list) if list.is_empty() => vec![screen::muted("No commits yet")],
Ok(list) => list
.iter()
.map(|commit| {
let refs = if commit.refs.is_empty() {
String::new()
} else {
format!(" ({})", commit.refs)
};
format!("{} {}{refs} {}", commit.hash, commit.date, commit.subject)
})
.collect(),
Err(error) => vec![screen::danger(format!("Could not read commits: {error}"))],
};
let branches: Vec<String> = match git::remote_branches() {
Ok(list) if list.is_empty() => vec![screen::muted("No remote branches")],
Ok(list) => list,
Err(error) => vec![screen::danger(format!("Could not read branches: {error}"))],
};
let lists = [commits, branches];
let mut tab = 0usize;
let mut offset = 0usize;
loop {
let visible = screen::body_rows().saturating_sub(2);
let rows = &lists[tab];
offset = offset.min(rows.len().saturating_sub(visible));
let tabs: Vec<String> = ["Recent commits", "Remote branches"]
.iter()
.enumerate()
.map(|(index, name)| {
if index == tab {
screen::selected(format!("[{name}]"))
} else {
screen::muted(name)
}
})
.collect();
let mut body = vec![screen::accent(&head), tabs.join(" ")];
body.extend(rows.iter().skip(offset).take(visible).cloned());
screen::draw(&body, HISTORY_HINT, None)?;
let Some(key) = read_key()? else { continue };
if is_interrupt(&key) {
bail!(CANCELLED);
}
match key.code {
KeyCode::Tab => {
tab = 1 - tab;
offset = 0;
}
KeyCode::Up | KeyCode::Char('w' | 'W') => offset = offset.saturating_sub(1),
KeyCode::Down | KeyCode::Char('s' | 'S') => offset = offset.saturating_add(1),
KeyCode::PageUp => offset = offset.saturating_sub(visible),
KeyCode::PageDown => offset = offset.saturating_add(visible),
KeyCode::Home => offset = 0,
KeyCode::End => offset = usize::MAX,
KeyCode::Esc | KeyCode::Char('q' | 'Q') => return Ok(()),
_ => {}
}
}
}
pub fn read_line(prompt: &str, initial: &str, multiline: bool) -> Result<String> {
text_input(prompt, initial, multiline, false)
}
struct BlinkingBar;
impl BlinkingBar {
fn set() -> Self {
let _ = crossterm::execute!(
std::io::stdout(),
crossterm::cursor::SetCursorStyle::BlinkingBar
);
Self
}
}
impl Drop for BlinkingBar {
fn drop(&mut self) {
let _ = crossterm::execute!(
std::io::stdout(),
crossterm::cursor::SetCursorStyle::DefaultUserShape
);
}
}
fn line_start(chars: &[char], cursor: usize) -> usize {
chars[..cursor].iter().rposition(|c| *c == '\n').map_or(0, |i| i + 1)
}
fn line_end(chars: &[char], cursor: usize) -> usize {
chars[cursor..].iter().position(|c| *c == '\n').map_or(chars.len(), |i| cursor + i)
}
fn move_vertical(chars: &[char], cursor: usize, down: bool) -> usize {
let start = line_start(chars, cursor);
let column = cursor - start;
if down {
let end = line_end(chars, cursor);
if end >= chars.len() {
return cursor;
}
let next = end + 1;
next + column.min(line_end(chars, next) - next)
} else {
if start == 0 {
return cursor;
}
let prev_end = start - 1;
let prev = line_start(chars, prev_end);
prev + column.min(prev_end - prev)
}
}
fn word_left(chars: &[char], cursor: usize) -> usize {
let mut i = cursor;
while i > 0 && chars[i - 1].is_whitespace() {
i -= 1;
}
while i > 0 && !chars[i - 1].is_whitespace() {
i -= 1;
}
i
}
fn word_right(chars: &[char], cursor: usize) -> usize {
let mut i = cursor;
while i < chars.len() && !chars[i].is_whitespace() {
i += 1;
}
while i < chars.len() && chars[i].is_whitespace() {
i += 1;
}
i
}
fn editor_layout(body_rows: usize, has_notice: bool) -> (usize, usize) {
let notice = usize::from(has_notice);
let visible = body_rows.saturating_sub(2 + notice).max(1);
(visible, 1 + visible + notice)
}
fn text_input(prompt: &str, initial: &str, multiline: bool, optional: bool) -> Result<String> {
let _cursor_style = BlinkingBar::set();
let mut chars: Vec<char> = initial.chars().collect();
let mut cursor = chars.len();
let mut notice: Option<&str> = None;
let mut on_button = false;
let mut top = 0usize;
let hint = if multiline { MESSAGE_HINT } else { LINE_HINT };
loop {
let text: String = chars.iter().collect();
let line = chars[..cursor].iter().filter(|c| **c == '\n').count();
let column = cursor - line_start(&chars, cursor);
let (visible, button_row) = if multiline {
editor_layout(screen::body_rows(), notice.is_some())
} else {
(
screen::body_rows()
.saturating_sub(1 + if notice.is_some() { 2 } else { 0 })
.max(1),
0,
)
};
if line < top {
top = line;
} else if line >= top + visible {
top = line + 1 - visible;
}
let mut body = vec![prompt.to_string()];
body.extend(text.split('\n').skip(top).take(visible).map(str::to_owned));
if multiline {
body.resize(1 + visible, String::new());
if let Some(message) = notice {
body.push(screen::danger(message));
}
body.push(if on_button {
screen::selected("Save & go back")
} else {
screen::tag("Save & go back")
});
} else if let Some(message) = notice {
body.push(String::new());
body.push(screen::danger(message));
}
let cursor_at = (!on_button).then_some(((1 + line - top) as u16, column as u16));
screen::draw(&body, hint, cursor_at)?;
let mut submit = false;
let input = if multiline { read_input()? } else { read_key()?.map(Input::Key) };
let key = match input {
None => continue,
Some(Input::Click(row)) => {
if row == button_row {
submit = true;
}
None
}
Some(Input::Key(key)) => Some(key),
};
notice = None;
let mut ctrl = false;
if let Some(key) = key {
if is_interrupt(&key) {
bail!(CANCELLED);
}
let alt = key.modifiers.contains(KeyModifiers::ALT);
ctrl = key.modifiers.contains(KeyModifiers::CONTROL) && !alt;
if multiline && on_button {
on_button = false;
if key.code == KeyCode::Enter {
submit = true;
} else if key.code == KeyCode::Tab {
continue;
}
} else if multiline && key.code == KeyCode::Tab {
on_button = true;
continue;
}
if key.code == KeyCode::Enter && (ctrl || !multiline) {
submit = true;
}
}
if submit {
let value = text.trim();
if value.is_empty() && !optional {
notice = Some(if multiline { "Message is required" } else { "Value is required" });
continue;
}
return Ok(value.to_string());
}
let Some(key) = key else { continue };
match key.code {
KeyCode::Esc => return Ok(initial.into()),
KeyCode::Enter => {
chars.insert(cursor, '\n');
cursor += 1;
}
KeyCode::Backspace => {
let from = cursor.saturating_sub(1);
chars.drain(from..cursor);
cursor = from;
}
KeyCode::Delete if cursor < chars.len() => {
chars.remove(cursor);
}
KeyCode::Left if ctrl => cursor = word_left(&chars, cursor),
KeyCode::Right if ctrl => cursor = word_right(&chars, cursor),
KeyCode::Left => cursor = cursor.saturating_sub(1),
KeyCode::Right => cursor = (cursor + 1).min(chars.len()),
KeyCode::Up if multiline => cursor = move_vertical(&chars, cursor, false),
KeyCode::Down if multiline => cursor = move_vertical(&chars, cursor, true),
KeyCode::PageUp if multiline => {
for _ in 0..visible {
cursor = move_vertical(&chars, cursor, false);
}
}
KeyCode::PageDown if multiline => {
for _ in 0..visible {
cursor = move_vertical(&chars, cursor, true);
}
}
KeyCode::Home if ctrl => cursor = 0,
KeyCode::End if ctrl => cursor = chars.len(),
KeyCode::Home => cursor = line_start(&chars, cursor),
KeyCode::End => cursor = line_end(&chars, cursor),
KeyCode::Char(ch) if !ctrl => {
chars.insert(cursor, ch);
cursor += 1;
}
_ => {}
}
}
}
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;
let mut notice: Option<&str> = None;
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;
let mut body = vec![format!("{prompt} {rendered}")];
if let Some(message) = notice {
body.push(String::new());
body.push(screen::danger(message));
}
screen::draw(&body, MASK_HINT, Some((0, column)))?;
let Some(key) = read_key()? else { continue };
notice = None;
if is_interrupt(&key) {
bail!(CANCELLED);
}
let preset_key = match key.code {
KeyCode::Char(ch)
if !key.modifiers.contains(KeyModifiers::CONTROL)
&& ((if date {
matches!(ch.to_ascii_lowercase(), 'n' | 'y')
} else {
matches!(ch.to_ascii_lowercase(), 'n' | 'r')
}) || (matches!(ch, '-' | '+') && !chars.contains(&'_'))) =>
{
Some(ch.to_ascii_lowercase())
}
_ => None,
};
if let Some(ch) = preset_key {
let current: String = chars.iter().collect();
let preset = if date {
preset_date(ch, ¤t)
} else {
preset_time(ch, ¤t)
};
if let Some(filled) = preset {
if filled.chars().count() == chars.len() {
chars = filled.chars().collect();
}
}
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::Enter => {
let result: String = chars.iter().collect();
if result.contains('_') {
notice = Some("Complete all fields before continuing");
} else if (date && !valid_date(&result)) || (!date && !valid_time(&result)) {
notice = Some(if date {
"Not a valid calendar date"
} else {
"Time out of range (00:00:00 - 23:59:59)"
});
} else {
return Ok(result);
}
}
_ => {}
}
}
}
pub fn external_editor(initial: &str) -> Result<String> {
let nanos = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |elapsed| elapsed.as_nanos());
let path = std::env::temp_dir().join(format!("git-cc-{}-{nanos}.txt", std::process::id()));
{
use std::io::Write;
let mut file = fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&path)
.context("could not create temp file for the editor")?;
file.write_all(initial.as_bytes())?;
}
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 = split_command(&editor).into_iter();
let Some(program) = parts.next() else {
let _ = fs::remove_file(&path);
bail!("editor command is empty");
};
screen::suspend();
let status = Command::new(program)
.args(parts)
.arg(&path)
.stdin(Stdio::inherit())
.stdout(Stdio::inherit())
.stderr(Stdio::inherit())
.status();
let resumed = screen::resume();
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);
resumed?;
let message = result?;
if message.trim().is_empty() {
bail!("Commit message is required");
}
Ok(message.trim().into())
}
fn split_command(command: &str) -> Vec<String> {
let mut parts = Vec::new();
let mut current = String::new();
let mut started = false;
let mut quote: Option<char> = None;
for ch in command.chars() {
match quote {
Some(open) if ch == open => quote = None,
Some(_) => current.push(ch),
None if !started && (ch == '"' || ch == '\'') => {
quote = Some(ch);
started = true;
}
None if ch.is_whitespace() => {
if started {
parts.push(std::mem::take(&mut current));
started = false;
}
}
None => {
current.push(ch);
started = true;
}
}
}
if started {
parts.push(current);
}
parts
}
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(context: &[String], prompt: &str, default: bool) -> Result<bool> {
let mut body = context.to_vec();
if !body.is_empty() {
body.push(String::new());
}
body.push(format!(
"{prompt} ({})",
if default { "Y/n" } else { "y/N" }
));
loop {
screen::draw(&body, CONFIRM_HINT, None)?;
let Some(key) = read_key()? else { continue };
if is_interrupt(&key) {
bail!(CANCELLED);
}
match key.code {
KeyCode::Enter => return Ok(default),
KeyCode::Char('y' | 'Y') => return Ok(true),
KeyCode::Char('n' | 'N') => return Ok(false),
_ => {}
}
}
}
#[derive(Debug, PartialEq)]
pub enum Pick {
Account(String),
GitDefault,
}
pub fn pick_account(accounts: &[Account], active: Option<&str>) -> Result<Option<Pick>> {
accounts::invalidate_logins();
let mut index = 0usize;
let logins = accounts::stored_logins();
loop {
let mut body = vec![screen::accent("SELECT ACCOUNT"), String::new()];
body.extend(account_rows(accounts, active, &logins, index));
if accounts.is_empty() {
body.push(String::new());
body.push(screen::muted(
"No accounts yet. Use gct --account to add one.",
));
}
screen::draw(&body, PICK_HINT, None)?;
let Some(key) = read_key()? else { continue };
if is_interrupt(&key) {
bail!(CANCELLED);
}
let count = accounts.len() + 1;
match key.code {
KeyCode::Up | KeyCode::Char('w' | 'W') => index = (index + count - 1) % count,
KeyCode::Down | KeyCode::Char('s' | 'S') => index = (index + 1) % count,
KeyCode::Enter | KeyCode::Char(' ') => {
return Ok(Some(if index == 0 {
Pick::GitDefault
} else {
Pick::Account(accounts[index - 1].label.clone())
}))
}
KeyCode::Esc | KeyCode::Char('q' | 'Q') => return Ok(None),
_ => {}
}
}
}
pub fn accounts_screen(config: &mut Config) -> Result<()> {
let mut index = 0usize;
let mut notice: Option<String> = None;
let mut logins = accounts::stored_logins();
let mut identity = gitconfig::read();
loop {
index = index.min(config.accounts.len());
let mut body = vec![
screen::accent("ACCOUNTS"),
format!("Active in git: {}", identity_text(&identity)),
screen::muted("Press A to add a GitHub account; a browser window opens to sign in."),
String::new(),
];
if let Some(message) = ¬ice {
body.push(screen::danger(message));
body.push(String::new());
}
body.extend(account_rows(
&config.accounts,
config.active_account.as_deref(),
&logins,
index,
));
if config.accounts.is_empty() {
body.push(String::new());
body.push(screen::muted(
"No accounts yet. Press A, give it a label, and sign in with GitHub.",
));
}
screen::draw(&body, ACCOUNTS_HINT, None)?;
let Some(key) = read_key()? else { continue };
notice = None;
if is_interrupt(&key) {
bail!(CANCELLED);
}
let count = config.accounts.len() + 1;
match key.code {
KeyCode::Up | KeyCode::Char('w' | 'W') => index = (index + count - 1) % count,
KeyCode::Down | KeyCode::Char('s' | 'S') => index = (index + 1) % count,
KeyCode::Enter | KeyCode::Char(' ') => {
let result = if index == 0 {
accounts::deactivate(config)
} else {
let label = config.accounts[index - 1].label.clone();
accounts::activate(config, &label)
};
if let Err(error) = result {
notice = Some(error.to_string());
}
}
KeyCode::Char('a' | 'A') => {
notice = Some(match add_form(&config.accounts)? {
Some(label) => {
let mut username = String::new();
if ask("GitHub username:", &mut username)? {
match suspended(|| accounts::sign_in_new(&label, &username))? {
Ok(account) => {
let message = format!(
"Added {label}, signed in to GitHub as @{}",
account.github_username
);
config.accounts.push(account);
index = config.accounts.len();
message
}
Err(error) => error.to_string(),
}
} else {
"Cancelled, no account saved".into()
}
}
None => "Cancelled, no account saved".into(),
});
invalidate_logins();
logins = accounts::stored_logins();
}
KeyCode::Char('l' | 'L') if index > 0 => {
notice = Some(
update_account(config, index - 1, true)
.unwrap_or_else(|error| error.to_string()),
);
invalidate_logins();
logins = accounts::stored_logins();
}
KeyCode::Char('r' | 'R') if index > 0 => {
notice = Some(
update_account(config, index - 1, false)
.unwrap_or_else(|error| error.to_string()),
);
invalidate_logins();
logins = accounts::stored_logins();
}
KeyCode::Char('e' | 'E') if index > 0 => {
notice = Some(match edit_form(&config.accounts, index - 1)? {
Some(edited) => {
let label = edited.label.clone();
let old = config.accounts[index - 1].clone();
let old_active = config.active_account.clone();
match replace_account(config, index - 1, edited) {
Ok(()) => format!("Saved {label}"),
Err(error) => {
config.accounts[index - 1] = old;
config.active_account = old_active;
error.to_string()
}
}
}
None => "Cancelled, account unchanged".into(),
});
}
KeyCode::Char('d' | 'D') if index > 0 => {
let label = config.accounts[index - 1].label.clone();
let prompt = format!(
"Delete account '{label}'? Its GitHub sign-in stays saved in Git Credential Manager."
);
if confirm(&[], &prompt, false)? {
let was_active = config.active_account.as_deref() == Some(label.as_str());
let deactivated = if was_active {
accounts::deactivate(config)
} else {
Ok(())
};
match deactivated {
Ok(()) => {
config.accounts.remove(index - 1);
}
Err(error) => notice = Some(error.to_string()),
}
}
}
KeyCode::Esc | KeyCode::Char('q' | 'Q') => return Ok(()),
_ => {}
}
if matches!(
key.code,
KeyCode::Enter
| KeyCode::Char(' ' | 'a' | 'A' | 'l' | 'L' | 'r' | 'R' | 'e' | 'E' | 'd' | 'D')
) {
identity = gitconfig::read();
}
}
}
fn suspended<T>(work: impl FnOnce() -> Result<T>) -> Result<Result<T>> {
screen::suspend();
let result = work();
screen::resume()?;
Ok(result)
}
fn update_account(config: &mut Config, position: usize, sign_in: bool) -> Result<String> {
let account = config.accounts[position].clone();
let username = account.github_username.clone();
let fresh = suspended(|| {
if sign_in {
accounts::login(&username)?;
}
let mut fresh = account;
accounts::refresh(&mut fresh)?;
Ok(fresh)
})??;
let label = fresh.label.clone();
replace_account(config, position, fresh)?;
Ok(if sign_in {
format!("Signed in to GitHub as @{username}, {label} updated")
} else {
format!("Refreshed {label} from GitHub")
})
}
fn replace_account(config: &mut Config, position: usize, account: Account) -> Result<()> {
let was_active =
config.active_account.as_deref() == Some(config.accounts[position].label.as_str());
let label = account.label.clone();
let old_label = config.accounts[position].label.clone();
let old = std::mem::replace(&mut config.accounts[position], account);
if was_active {
config.active_account = Some(label.clone());
if let Err(error) = accounts::activate(config, &label) {
config.accounts[position] = old;
config.active_account = Some(old_label);
return Err(error);
}
}
Ok(())
}
fn identity_text(identity: &gitconfig::Identity) -> String {
match (identity.name.as_deref(), identity.email.as_deref()) {
(Some(name), Some(email)) => format!("{name} <{email}>"),
(Some(name), None) => name.into(),
(None, Some(email)) => email.into(),
(None, None) => "not set".into(),
}
}
fn account_rows(
accounts: &[Account],
active: Option<&str>,
logins: &[String],
index: usize,
) -> Vec<String> {
let mut rows = vec![styled_menu_line(
index == 0,
&marked("git default", active.is_none()),
)];
for (position, account) in accounts.iter().enumerate() {
let is_active = active == Some(account.label.as_str());
let signed_in = logins
.iter()
.any(|login| login.eq_ignore_ascii_case(&account.github_username));
rows.push(styled_menu_line(
index == position + 1,
&account_line(account, is_active, signed_in),
));
}
rows
}
fn account_line(account: &Account, active: bool, signed_in: bool) -> String {
let mut parts = vec![format!("{:<10}", account.label)];
if account.name.trim().is_empty() {
parts.push(account.email.clone());
} else {
parts.push(account.name.clone());
parts.push(format!("<{}>", account.email));
}
parts.push(format!("@{}", account.github_username));
parts.push(
if signed_in {
"[signed in]"
} else {
"[not signed in]"
}
.into(),
);
if active {
parts.push("(active)".into());
}
parts.join(" ")
}
fn marked(text: &str, active: bool) -> String {
if active {
format!("{text} (active)")
} else {
text.into()
}
}
fn ask(prompt: &str, value: &mut String) -> Result<bool> {
let answer = read_line(prompt, value.as_str(), false)?;
let filled = !answer.is_empty();
*value = answer;
Ok(filled)
}
fn add_form(accounts: &[Account]) -> Result<Option<String>> {
let mut label = (1..)
.map(|number| format!("account {number}"))
.find(|label| !accounts.iter().any(|account| account.label == *label))
.unwrap_or_default();
loop {
if !ask("Label (short name, e.g. work):", &mut label)? {
return Ok(None);
}
if accounts.iter().any(|account| account.label == label) {
wait_key(
&[screen::danger(format!("label {label} is already used"))],
"Press any key to fix the label",
)?;
continue;
}
return Ok(Some(label));
}
}
fn edit_form(accounts: &[Account], position: usize) -> Result<Option<Account>> {
let mut candidate = accounts[position].clone();
loop {
if !ask("Label (short name, e.g. work):", &mut candidate.label)? {
return Ok(None);
}
candidate.name = text_input(
"Display name (blank shows the email):",
&candidate.name,
false,
true,
)?;
let others: Vec<Account> = accounts
.iter()
.enumerate()
.filter(|(other, _)| *other != position)
.map(|(_, account)| account.clone())
.collect();
match accounts::problem(&candidate, &others) {
None => return Ok(Some(candidate)),
Some(message) => wait_key(
&[screen::danger(message)],
"Press any key to fix the values",
)?,
}
}
}
#[cfg(test)]
mod tests {
use super::split_command;
#[test]
fn splits_plain_command() {
assert_eq!(split_command("code --wait"), ["code", "--wait"]);
}
#[test]
fn keeps_quoted_path_with_spaces_and_args() {
assert_eq!(
split_command(r#""C:\Program Files\Vim\vim.exe" -f --nofork"#),
[r"C:\Program Files\Vim\vim.exe", "-f", "--nofork"]
);
}
#[test]
fn apostrophe_inside_token_is_literal() {
assert_eq!(
split_command(r"C:\Users\O'Brien\vim.exe -f"),
[r"C:\Users\O'Brien\vim.exe", "-f"]
);
}
}
#[cfg(test)]
mod editor_tests {
use super::*;
fn c(text: &str) -> Vec<char> {
text.chars().collect()
}
#[test]
fn vertical_moves_keep_column() {
let t = c("abcd\nef\nghij");
assert_eq!(move_vertical(&t, 3, true), 7); assert_eq!(move_vertical(&t, 7, true), 10); assert_eq!(move_vertical(&t, 10, false), 7);
assert_eq!(move_vertical(&t, 2, false), 2); assert_eq!(move_vertical(&t, 12, true), 12); }
#[test]
fn home_end_are_per_line() {
let t = c("ab\ncde");
assert_eq!((line_start(&t, 5), line_end(&t, 3)), (3, 6));
assert_eq!((line_start(&t, 1), line_end(&t, 1)), (0, 2));
}
#[test]
fn editor_layout_puts_button_last() {
assert_eq!(editor_layout(10, false), (8, 9));
assert_eq!(editor_layout(10, true), (7, 9));
assert_eq!(editor_layout(2, true), (1, 3)); }
#[test]
fn word_jumps() {
let t = c("one two three");
assert_eq!(word_right(&t, 0), 5);
assert_eq!(word_right(&t, 5), 9);
assert_eq!(word_left(&t, 14), 9);
assert_eq!(word_left(&t, 9), 5);
assert_eq!(word_left(&t, 0), 0);
}
}