use crate::{
git::{self, Opts},
model::Config,
modes,
modes::guide,
repo_state::{self, EntryKind, Head, InProgress, RepoState},
screen, ui,
};
use anyhow::Result;
pub fn run(config: &mut Config) -> Result<()> {
let mut index = 0usize;
loop {
let state = repo_state::load()?;
let mut header = summary_lines(&state);
if let Some(l) = last_commit() {
header.push(format!("Last commit: {l}"));
}
if let Some(op) = state.op {
header.push(screen::warning(format!(
"In progress: {}. Finish or abort it (see Conflicts).",
op_label(op)
)));
}
if let Some(top) = guide::next_steps(&state).first() {
header.push(screen::accent(format!("Next step: {}", top.title)));
}
let rows_spec = rows(&state);
let labels: Vec<String> = rows_spec.iter().map(|(l, _)| l.to_string()).collect();
let keys = [ui::Key {
key: 'r',
label: "Refresh",
}];
match ui::action_list("Status", &header, &labels, &keys, &mut index)? {
ui::Choice::Back => return Ok(()),
ui::Choice::Action(_, _) => {}
ui::Choice::Open(i) => {
if let Some((_, mode)) = rows_spec.get(i) {
modes::open(mode, config)?;
}
}
}
}
}
fn rows(state: &RepoState) -> Vec<(&'static str, &'static str)> {
let mut v = vec![
("Stage changes", "stage"),
("Commit", "commit"),
("Branches", "branch"),
("Sync (pull / push)", "sync"),
("Stash", "stash"),
("Log", "log"),
];
if state.op.is_some() || state.entries.iter().any(|e| e.conflicted()) {
v.push(("Conflicts", "conflicts"));
}
v.push(("Undo", "undo"));
v
}
fn op_label(op: InProgress) -> &'static str {
match op {
InProgress::Merge => "merge",
InProgress::Rebase => "rebase",
InProgress::CherryPick => "cherry-pick",
InProgress::Revert => "revert",
InProgress::Am => "patch apply (am)",
InProgress::Bisect => "bisect",
}
}
fn last_commit() -> Option<String> {
let out = git::git_ok(&["log", "-1", "--format=%h %s (%cr)"], &Opts::default()).ok()?;
let out = out.trim();
(!out.is_empty()).then(|| out.to_string())
}
fn head_line(head: &Head) -> String {
match head {
Head::Branch { name, .. } => format!("Branch: {name}"),
Head::Unborn { name } => format!("Branch: {name} (no commits yet)"),
Head::Detached { oid } => {
format!(
"Branch: detached at {}",
oid.chars().take(7).collect::<String>()
)
}
}
}
fn upstream_line(state: &RepoState) -> String {
let b = &state.branch;
match &b.upstream {
None => "Upstream: no upstream".into(),
Some(u) if b.upstream_gone => format!("Upstream: {u} (upstream gone)"),
Some(u) => format!("Upstream: {u} (ahead {}, behind {})", b.ahead, b.behind),
}
}
fn counts_line(state: &RepoState) -> String {
let e = &state.entries;
let staged = e.iter().filter(|x| x.staged()).count();
let unstaged = e.iter().filter(|x| x.unstaged()).count();
let untracked = e.iter().filter(|x| x.kind == EntryKind::Untracked).count();
let conflicted = e.iter().filter(|x| x.conflicted()).count();
format!(
"Changes: {staged} staged, {unstaged} unstaged, {untracked} untracked, {conflicted} conflicted"
)
}
fn summary_lines(state: &RepoState) -> Vec<String> {
vec![
head_line(&state.branch.head),
upstream_line(state),
counts_line(state),
format!("Stashes: {}", state.branch.stash_count),
]
}
#[cfg(test)]
mod tests {
use super::*;
use crate::repo_state::{BranchInfo, Entry};
use crate::testutil::TempRepo;
use std::path::PathBuf;
fn state(head: Head) -> RepoState {
RepoState {
branch: BranchInfo {
head,
upstream: None,
ahead: 0,
behind: 0,
stash_count: 2,
upstream_gone: false,
},
entries: vec![],
op: None,
git_dir: PathBuf::new(),
workdir: PathBuf::new(),
}
}
fn ent(x: char, y: char, kind: EntryKind) -> Entry {
Entry {
path: "f".into(),
orig_path: None,
x,
y,
kind,
}
}
#[test]
fn head_lines() {
let oid = "0123456789abcdef".to_string();
assert_eq!(
head_line(&Head::Branch {
name: "main".into(),
oid: oid.clone()
}),
"Branch: main"
);
assert_eq!(
head_line(&Head::Detached { oid }),
"Branch: detached at 0123456"
);
assert_eq!(
head_line(&Head::Unborn {
name: "main".into()
}),
"Branch: main (no commits yet)"
);
}
#[test]
fn upstream_lines() {
let mut s = state(Head::Unborn { name: "m".into() });
assert_eq!(upstream_line(&s), "Upstream: no upstream");
s.branch.upstream = Some("origin/m".into());
s.branch.ahead = 2;
s.branch.behind = 1;
assert_eq!(upstream_line(&s), "Upstream: origin/m (ahead 2, behind 1)");
s.branch.upstream_gone = true;
assert_eq!(upstream_line(&s), "Upstream: origin/m (upstream gone)");
}
#[test]
fn counts_and_summary() {
let mut s = state(Head::Unborn { name: "m".into() });
s.entries = vec![
ent('M', 'M', EntryKind::Ordinary),
ent('.', 'M', EntryKind::Ordinary),
ent('?', '?', EntryKind::Untracked),
ent('U', 'U', EntryKind::Unmerged),
];
assert_eq!(
counts_line(&s),
"Changes: 1 staged, 2 unstaged, 1 untracked, 1 conflicted"
);
assert_eq!(summary_lines(&s).len(), 4);
assert_eq!(summary_lines(&s)[3], "Stashes: 2");
}
#[test]
fn conflicts_row_only_when_relevant() {
let mut s = state(Head::Unborn { name: "m".into() });
assert!(!rows(&s).iter().any(|r| r.1 == "conflicts"));
s.op = Some(InProgress::Merge);
assert!(rows(&s).iter().any(|r| r.1 == "conflicts"));
}
#[test]
fn last_commit_on_repo_and_unborn() {
let repo = TempRepo::new(2);
let l = repo.run(last_commit).expect("last");
assert!(l.contains("commit 2"), "{l}");
let empty = TempRepo::new(0);
assert!(empty.run(last_commit).is_none());
}
#[test]
fn load_unborn_repo_summary() {
let repo = TempRepo::new(0);
let st = repo.run(repo_state::load).expect("load");
assert!(summary_lines(&st)[0].contains("no commits yet"));
}
}