use crate::{
model::{Config, Level},
modes,
repo_state::{self, EntryKind, Head, InProgress, RepoState},
screen, ui,
};
use anyhow::Result;
pub fn run(config: &mut Config) -> Result<()> {
if !repo_state::in_repo() {
let lines = vec![
"This folder is not a git repository yet.".to_string(),
"Start mode can create one here or clone an existing project.".to_string(),
];
ui::notice("Not a git repository", &lines)?;
if ui::choose("Open Start mode?", &[], &["Yes, open Start", "No"])? == Some(0) {
modes::open("start", config)?;
}
return Ok(());
}
let mut index = 0usize;
loop {
let state = repo_state::load()?;
let steps = next_steps(&state);
let mut header = vec![screen::muted("Suggested next steps, most important first.")];
if config.level() == Level::Beginner {
if let Some(top) = steps.first() {
header.push(top.why.clone());
}
header.extend(ui::explain(
config,
&["Pick a step and press Enter to open the tool that does it."],
));
}
let rows: Vec<String> = steps
.iter()
.map(|s| format!("{} - {}", s.title, s.why))
.collect();
let keys = [ui::Key {
key: 'r',
label: "Refresh",
}];
match ui::action_list("Guide", &header, &rows, &keys, &mut index)? {
ui::Choice::Back => return Ok(()),
ui::Choice::Action(_, _) => {}
ui::Choice::Open(i) => {
if let Some(mode) = steps.get(i).and_then(|s| s.mode) {
modes::open(mode, config)?;
}
}
}
}
}
pub struct Step {
pub title: String,
pub why: String,
pub mode: Option<&'static str>,
}
fn step(title: &str, why: &str, mode: Option<&'static str>) -> Step {
Step {
title: title.into(),
why: why.into(),
mode,
}
}
fn op_name(op: InProgress) -> &'static str {
match op {
InProgress::Merge => "merge",
InProgress::Rebase => "rebase",
InProgress::CherryPick => "cherry-pick",
InProgress::Revert => "revert",
InProgress::Am => "patch apply",
InProgress::Bisect => "bisect",
}
}
pub fn next_steps(state: &RepoState) -> Vec<Step> {
let b = &state.branch;
let mut out = Vec::new();
let conflicted = state.entries.iter().any(|e| e.conflicted());
let staged = state.entries.iter().filter(|e| e.staged()).count();
let unstaged = state.entries.iter().filter(|e| e.unstaged()).count();
let untracked = state
.entries
.iter()
.filter(|e| e.kind == EntryKind::Untracked)
.count();
if state.op.is_some() || conflicted {
let name = state.op.map_or("conflict", op_name);
out.push(step(
&format!("Finish or abort the {name}"),
"An operation is half done; finish it or abort to get back to a clean state.",
Some("conflicts"),
));
}
if matches!(b.head, Head::Detached { .. }) {
out.push(step(
"Create a branch here so your work is not lost",
"You are on a detached HEAD; commits made here are easy to lose.",
Some("branch"),
));
}
let has_commits = !matches!(b.head, Head::Unborn { .. });
if !has_commits {
out.push(step(
"Make your first commit",
"This branch has no commits yet.",
Some("commit"),
));
if staged == 0 {
out.push(step(
"Set up this repo",
"Nothing is tracked yet; add files or a .gitignore first.",
Some("start"),
));
}
}
if b.behind > 0 && b.ahead > 0 {
out.push(step(
"Your branch diverged: pull (rebase or merge)",
"You and the remote both have new commits; combine them before pushing.",
Some("sync"),
));
}
if staged > 0 {
out.push(step(
"Commit your staged changes",
"Staged changes are ready to be saved as a commit.",
Some("commit"),
));
}
if unstaged > 0 {
out.push(step(
"Stage your changes",
"You edited files; choose which edits go into the next commit.",
Some("stage"),
));
}
if untracked > 0 {
out.push(step(
"Stage or ignore new files",
"Git does not track these new files yet.",
Some("stage"),
));
}
if b.ahead > 0 {
out.push(step(
"Push your commits",
"You have commits the remote does not have yet.",
Some("sync"),
));
}
if has_commits && b.upstream.is_none() {
out.push(step(
"Publish this branch",
"This branch has no upstream; push it to share it and track it.",
Some("sync"),
));
}
if b.behind > 0 && b.ahead == 0 {
out.push(step(
"Pull the latest changes",
"The remote has commits you do not have yet.",
Some("sync"),
));
}
if out.is_empty() {
out.push(step(
"All good: nothing to do",
"Everything is committed and in sync.",
None,
));
}
out
}
#[cfg(test)]
mod tests {
use super::*;
use crate::repo_state::{BranchInfo, Entry};
use crate::testutil::TempRepo;
use std::path::PathBuf;
fn base() -> RepoState {
RepoState {
branch: BranchInfo {
head: Head::Branch {
name: "main".into(),
oid: "abc".into(),
},
upstream: Some("origin/main".into()),
ahead: 0,
behind: 0,
stash_count: 0,
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,
}
}
fn titles(s: &RepoState) -> Vec<String> {
next_steps(s).into_iter().map(|s| s.title).collect()
}
#[test]
fn clean_repo_is_all_good() {
let steps = next_steps(&base());
assert_eq!(steps.len(), 1);
assert_eq!(steps[0].title, "All good: nothing to do");
assert_eq!(steps[0].mode, None);
}
#[test]
fn each_rule_table() {
let mut cases: Vec<(RepoState, &str, &str)> = Vec::new();
let mut s = base();
s.op = Some(InProgress::Merge);
cases.push((s, "Finish or abort the merge", "conflicts"));
let mut s = base();
s.entries = vec![ent('U', 'U', EntryKind::Unmerged)];
cases.push((s, "Finish or abort the conflict", "conflicts"));
let mut s = base();
s.branch.head = Head::Detached { oid: "abc".into() };
cases.push((s, "Create a branch here so your work is not lost", "branch"));
let mut s = base();
s.branch.head = Head::Unborn {
name: "main".into(),
};
s.branch.upstream = None;
cases.push((s, "Make your first commit", "commit"));
let mut s = base();
s.branch.ahead = 1;
s.branch.behind = 1;
cases.push((s, "Your branch diverged: pull (rebase or merge)", "sync"));
let mut s = base();
s.entries = vec![ent('M', '.', EntryKind::Ordinary)];
cases.push((s, "Commit your staged changes", "commit"));
let mut s = base();
s.entries = vec![ent('.', 'M', EntryKind::Ordinary)];
cases.push((s, "Stage your changes", "stage"));
let mut s = base();
s.entries = vec![ent('?', '?', EntryKind::Untracked)];
cases.push((s, "Stage or ignore new files", "stage"));
let mut s = base();
s.branch.ahead = 2;
cases.push((s, "Push your commits", "sync"));
let mut s = base();
s.branch.upstream = None;
cases.push((s, "Publish this branch", "sync"));
let mut s = base();
s.branch.behind = 3;
cases.push((s, "Pull the latest changes", "sync"));
for (state, title, mode) in cases {
let steps = next_steps(&state);
assert_eq!(steps[0].title, title);
assert_eq!(steps[0].mode, Some(mode));
assert!(!steps[0].why.is_empty());
}
}
#[test]
fn unborn_untracked_offers_start() {
let mut s = base();
s.branch.head = Head::Unborn {
name: "main".into(),
};
s.branch.upstream = None;
assert_eq!(titles(&s), ["Make your first commit", "Set up this repo"]);
s.entries = vec![ent('A', '.', EntryKind::Ordinary)];
assert_eq!(
titles(&s),
["Make your first commit", "Commit your staged changes"]
);
}
#[test]
fn priority_ordering() {
let mut s = base();
s.op = Some(InProgress::Rebase);
s.branch.head = Head::Detached { oid: "abc".into() };
s.branch.ahead = 1;
s.branch.behind = 1;
s.entries = vec![
ent('M', 'M', EntryKind::Ordinary),
ent('?', '?', EntryKind::Untracked),
];
assert_eq!(
titles(&s),
[
"Finish or abort the rebase",
"Create a branch here so your work is not lost",
"Your branch diverged: pull (rebase or merge)",
"Commit your staged changes",
"Stage your changes",
"Stage or ignore new files",
"Push your commits",
]
);
}
#[test]
fn fresh_repo_with_untracked_file() {
let repo = TempRepo::new(1).with_remote();
repo.git(&["push", "-q", "-u", "origin", "main"]);
repo.write("new.txt", "x");
let state = repo.run(repo_state::load).expect("load");
let steps = next_steps(&state);
assert_eq!(steps[0].title, "Stage or ignore new files");
}
}