use crate::{
git::{self, Opts},
model::Config,
policy::{self, Op},
repo_state::{self, Head, InProgress},
safety, screen, ui,
};
use anyhow::{bail, Result};
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Track {
pub ahead: u32,
pub behind: u32,
pub gone: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BranchRef {
pub name: String,
pub remote: bool,
pub oid: String,
pub upstream: String,
pub track: Track,
pub date: String,
pub current: bool,
}
pub const REF_FORMAT: &str = "--format=%(refname)%00%(objectname:short)%00%(upstream:short)%00%(upstream:track,nobracket)%00%(committerdate:relative)%00%(HEAD)";
pub fn parse_track(text: &str) -> Track {
let mut track = Track::default();
for part in text.split(',') {
let part = part.trim();
if part == "gone" {
track.gone = true;
} else if let Some(n) = part.strip_prefix("ahead ") {
track.ahead = n.trim().parse().unwrap_or(0);
} else if let Some(n) = part.strip_prefix("behind ") {
track.behind = n.trim().parse().unwrap_or(0);
}
}
track
}
pub fn parse_refs(text: &str) -> Vec<BranchRef> {
let mut out = Vec::new();
for line in text.lines() {
let line = line.trim_end_matches('\r');
let f: Vec<&str> = line.split('\0').collect();
if f.len() < 6 {
continue;
}
let (name, remote) = if let Some(n) = f[0].strip_prefix("refs/heads/") {
(n, false)
} else if let Some(n) = f[0].strip_prefix("refs/remotes/") {
(n, true)
} else {
continue;
};
if remote && (name.ends_with("/HEAD") || !name.contains('/')) {
continue;
}
out.push(BranchRef {
name: name.to_string(),
remote,
oid: f[1].to_string(),
upstream: f[2].to_string(),
track: parse_track(f[3]),
date: f[4].to_string(),
current: f[5].trim() == "*",
});
}
out
}
pub fn is_dirty_switch_error(stderr: &str) -> bool {
let s = stderr.to_ascii_lowercase();
s.contains("would be overwritten by checkout")
|| s.contains("would be overwritten by switch")
|| s.contains("commit your changes or stash them")
}
pub fn prune_candidates(
merged: &[String],
protected: &dyn Fn(&str) -> bool,
current: &str,
) -> Vec<String> {
merged
.iter()
.map(|b| b.trim().trim_start_matches("* ").to_string())
.filter(|b| !b.is_empty() && b != current && !b.starts_with('(') && !protected(b))
.collect()
}
fn split_remote(name: &str) -> Option<(&str, &str)> {
name.split_once('/')
}
pub fn switch_args(branch: &BranchRef, locals: &[String]) -> Vec<String> {
if !branch.remote {
return vec!["switch".into(), branch.name.clone()];
}
match split_remote(&branch.name) {
Some((_, local)) if locals.iter().any(|l| l == local) => {
vec!["switch".into(), local.to_string()]
}
_ => vec!["switch".into(), "--track".into(), branch.name.clone()],
}
}
pub fn name_problem(name: &str) -> Option<&'static str> {
if name.trim().is_empty() {
Some("The name is empty.")
} else if name.starts_with('-') {
Some("A branch name cannot start with '-'.")
} else if name.chars().any(char::is_whitespace) {
Some("A branch name cannot contain spaces.")
} else {
None
}
}
pub fn row_text(b: &BranchRef) -> String {
let mark = if b.current { "*" } else { " " };
let mut text = format!("{mark} {} {}", b.name, b.oid);
if b.track.gone {
text.push_str(" [gone]");
}
if b.track.ahead > 0 {
text.push_str(&format!(" ahead {}", b.track.ahead));
}
if b.track.behind > 0 {
text.push_str(&format!(" behind {}", b.track.behind));
}
if !b.upstream.is_empty() && !b.remote {
text.push_str(&format!(" -> {}", b.upstream));
}
if !b.date.is_empty() {
text.push_str(&format!(" {}", b.date));
}
text
}
pub fn list_refs() -> Result<Vec<BranchRef>> {
let out = git::git_ok(
&["for-each-ref", REF_FORMAT, "refs/heads", "refs/remotes"],
&Opts::default(),
)?;
Ok(parse_refs(&out))
}
pub fn validate_name(name: &str) -> Result<()> {
if let Some(problem) = name_problem(name) {
bail!("{problem}");
}
let out = git::git_raw(&["check-ref-format", "--branch", name], &Opts::default())?;
if !out.ok() {
bail!("'{name}' is not a valid branch name.");
}
Ok(())
}
#[derive(Debug, PartialEq, Eq)]
pub enum Attempt {
Done(String),
Dirty(String),
Failed(String),
}
fn attempt(args: &[&str]) -> Result<Attempt> {
let out = git::git_raw(args, &Opts::default())?;
if out.ok() {
return Ok(Attempt::Done(out.text()));
}
let err = out.stderr.trim().to_string();
Ok(if is_dirty_switch_error(&err) {
Attempt::Dirty(err)
} else {
Attempt::Failed(err)
})
}
fn refs(args: &[String]) -> Vec<&str> {
args.iter().map(String::as_str).collect()
}
pub fn stash_and_switch(args: &[String], target: &str) -> Result<Attempt> {
let message = format!("gct: before switch to {target}");
git::git_ok(&["stash", "push", "-u", "-m", &message], &Opts::default())?;
attempt(&refs(args))
}
pub fn backup_detached_commits() -> Result<Option<(usize, String)>> {
if git::git_raw(&["symbolic-ref", "--quiet", "HEAD"], &Opts::default())?.ok() {
return Ok(None);
}
let out = git::git_raw(
&[
"rev-list",
"--count",
"HEAD",
"--not",
"--branches",
"--tags",
"--remotes",
],
&Opts::default(),
)?;
let count: usize = if out.ok() {
out.text().trim().parse().unwrap_or(0)
} else {
0
};
if count == 0 {
return Ok(None);
}
Ok(Some((count, safety::backup("detached", "HEAD")?)))
}
pub fn rename_branch(old: &str, new: &str) -> Result<String> {
validate_name(new)?;
git::git_ok(&["branch", "-m", old, new], &Opts::default())
}
#[derive(Debug, PartialEq, Eq)]
pub enum Deleted {
Done,
NotMerged,
}
pub fn delete_merged(name: &str) -> Result<Deleted> {
let out = git::git_raw(&["branch", "-d", "--", name], &Opts::default())?;
if out.ok() {
return Ok(Deleted::Done);
}
if out.stderr.contains("not fully merged") {
return Ok(Deleted::NotMerged);
}
bail!("{}", out.stderr.trim())
}
pub fn force_delete(name: &str) -> Result<String> {
let full = format!("refs/heads/{name}");
let backup = safety::backup("branch-delete", &full)?;
git::git_ok(&["branch", "-D", "--", name], &Opts::default())?;
Ok(backup)
}
pub fn default_branch(cfg: &Config) -> Option<String> {
let head = format!("refs/remotes/{}/HEAD", cfg.default_remote);
if let Ok(full) = git::git_ok(&["symbolic-ref", "--short", &head], &Opts::default()) {
if let Some((_, b)) = split_remote(full.trim()) {
if local_exists(b) {
return Some(b.to_string());
}
}
}
["main", "master"]
.iter()
.find(|b| local_exists(b))
.map(|b| b.to_string())
}
fn local_exists(name: &str) -> bool {
let full = format!("refs/heads/{name}");
git::git_raw(
&["show-ref", "--verify", "--quiet", &full],
&Opts::default(),
)
.map(|o| o.ok())
.unwrap_or(false)
}
fn merged_into(base: &str) -> Result<Vec<String>> {
let out = git::git_ok(
&["branch", "--merged", base, "--format=%(refname:short)"],
&Opts::default(),
)?;
Ok(out.lines().map(|l| l.trim().to_string()).collect())
}
pub fn create_branch(name: &str, rev: Option<&str>, unborn: bool) -> Result<Attempt> {
validate_name(name)?;
if unborn {
let first = attempt(&["switch", "-c", name])?;
if let Attempt::Failed(_) = first {
let full = format!("refs/heads/{name}");
git::git_ok(&["symbolic-ref", "HEAD", &full], &Opts::default())?;
return Ok(Attempt::Done(String::new()));
}
return Ok(first);
}
match rev {
Some(rev) => attempt(&["switch", "-c", name, rev]),
None => attempt(&["switch", "-c", name]),
}
}
fn is_unborn() -> bool {
matches!(
repo_state::load().map(|s| s.branch.head),
Ok(Head::Unborn { .. })
)
}
fn run_switch(cfg: &Config, args: Vec<String>, target: &str) -> Result<()> {
if let Some((count, backup)) = backup_detached_commits()? {
ui::notice(
"Leaving a detached HEAD",
&[
screen::warning(format!(
"{count} commit(s) here are not on any branch and could be lost."
)),
format!("They are saved as {backup}"),
format!("Get them back later with: git branch <name> {backup}"),
],
)?;
}
let first = attempt(&refs(&args))?;
finish_switch(cfg, first, &args, target)
}
fn finish_switch(cfg: &Config, first: Attempt, args: &[String], target: &str) -> Result<()> {
let command = format!("git {}", args.join(" "));
match first {
Attempt::Done(_) => {
let mut lines = vec![format!("Done: {command}")];
lines.extend(ui::explain(
cfg,
&["You are now working on a different branch."],
));
ui::notice("Branch", &lines)
}
Attempt::Failed(err) => ui::notice("Branch: git refused", &[err]),
Attempt::Dirty(err) => {
let mut context = vec![
"Your uncommitted changes would be overwritten by this switch.".to_string(),
String::new(),
err,
];
context.extend(ui::explain(
cfg,
&["Stashing saves your changes safely; you can bring them back later."],
));
let pick = ui::choose("Switch blocked", &context, &["Stash & switch", "Cancel"])?;
if pick != Some(0) {
return Ok(());
}
match stash_and_switch(args, target)? {
Attempt::Done(_) => ui::notice(
"Branch",
&[
format!("Stashed your changes, then ran: {command}"),
format!("The stash \"gct: before switch to {target}\" is kept."),
"Bring it back later in Stash mode (apply or pop).".to_string(),
],
),
Attempt::Dirty(e) | Attempt::Failed(e) => ui::notice(
"Branch: switch failed after stashing",
&[
e,
"Your changes are safe in the stash (see Stash mode).".to_string(),
],
),
}
}
}
}
fn ask_name(prompt: &str) -> Result<Option<String>> {
let Some(name) = ui::ask(prompt, "")? else {
return Ok(None);
};
let name = name.trim().to_string();
if let Err(e) = validate_name(&name) {
ui::notice("Invalid branch name", &[e.to_string()])?;
return Ok(None);
}
Ok(Some(name))
}
pub fn create_at(cfg: &mut Config, rev: &str) -> Result<()> {
let Some(name) = ask_name(&format!("New branch name (at {rev})"))? else {
return Ok(());
};
let unborn = is_unborn();
let args: Vec<String> = if unborn {
vec!["switch".into(), "-c".into(), name.clone()]
} else {
vec!["switch".into(), "-c".into(), name.clone(), rev.to_string()]
};
let first = create_branch(&name, (!unborn).then_some(rev), unborn)?;
finish_switch(cfg, first, &args, &name)
}
fn rename_flow(cfg: &Config, b: &BranchRef) -> Result<()> {
if policy::is_protected(cfg, &b.name)
&& !ui::confirm_typed(
&format!(
"'{}' is a protected branch; renaming it can break others and CI",
b.name
),
&format!("git branch -m {} <new name>", b.name),
&b.name,
)?
{
return Ok(());
}
let Some(new) = ui::ask(&format!("Rename {} to", b.name), &b.name)? else {
return Ok(());
};
let new = new.trim();
if new == b.name {
return Ok(());
}
match rename_branch(&b.name, new) {
Ok(_) => ui::notice(
"Branch",
&[format!("Renamed {} to {new} (git branch -m).", b.name)],
),
Err(e) => ui::notice("Rename failed", &[e.to_string()]),
}
}
fn delete_flow(cfg: &Config, b: &BranchRef, current: &str) -> Result<()> {
if b.remote {
return ui::notice(
"Branch",
&["Remote branches are deleted from Sync mode, not here.".to_string()],
);
}
if b.name == current {
return ui::notice(
"Branch",
&["You are on this branch. Switch to another one before deleting it.".to_string()],
);
}
if policy::is_protected(cfg, &b.name) {
let ok = ui::confirm_typed(
&format!("'{}' is a protected branch", b.name),
&format!("git branch -d {}", b.name),
&b.name,
)?;
if !ok {
return Ok(());
}
}
let verdict = policy::check(
cfg,
&Op::DeleteBranch {
branch: &b.name,
merged: true,
},
);
if !ui::gate(
cfg,
&verdict,
&format!("Delete branch {}", b.name),
&format!("git branch -d {}", b.name),
)? {
return Ok(());
}
match delete_merged(&b.name) {
Ok(Deleted::Done) => {
ui::notice("Branch", &[format!("Deleted {} (git branch -d).", b.name)])
}
Ok(Deleted::NotMerged) => {
let verdict = policy::check(
cfg,
&Op::DeleteBranch {
branch: &b.name,
merged: false,
},
);
let what = format!("{} has commits that are not merged anywhere", b.name);
if !ui::gate(cfg, &verdict, &what, &format!("git branch -D {}", b.name))? {
return Ok(());
}
let backup = force_delete(&b.name)?;
let mut lines = vec![
format!("Deleted {} (git branch -D).", b.name),
format!("Backup kept: {backup}"),
format!("Restore it with: git branch {} {backup}", b.name),
];
lines.extend(ui::explain(
cfg,
&["The backup ref lets you get the branch back."],
));
ui::notice("Branch", &lines)
}
Err(e) => ui::notice("Branch: delete failed", &[e.to_string()]),
}
}
fn prune_flow(cfg: &Config) -> Result<()> {
let state = repo_state::load()?;
let current = match &state.branch.head {
Head::Branch { name, .. } | Head::Unborn { name } => name.clone(),
Head::Detached { .. } => String::new(),
};
let Some(base) = default_branch(cfg) else {
return ui::notice(
"Prune",
&["No main/master branch found to compare against.".to_string()],
);
};
let merged = merged_into(&base)?;
let list = prune_candidates(
&merged,
&|b| b == base || policy::is_protected(cfg, b),
¤t,
);
if list.is_empty() {
return ui::notice(
"Prune",
&[format!(
"No branches are merged into {base} (besides protected ones)."
)],
);
}
let mut checked = vec![true; list.len()];
if !ui::check_list(
&format!("Delete branches merged into {base}"),
&list,
&mut checked,
)? {
return Ok(());
}
let chosen: Vec<&String> = list
.iter()
.zip(&checked)
.filter(|(_, c)| **c)
.map(|(b, _)| b)
.collect();
if chosen.is_empty() {
return Ok(());
}
let command = format!(
"git branch -d {}",
chosen
.iter()
.map(|b| b.as_str())
.collect::<Vec<_>>()
.join(" ")
);
let verdict = policy::check(
cfg,
&Op::DeleteBranch {
branch: "",
merged: true,
},
);
if !ui::gate(
cfg,
&verdict,
&format!("Delete {} merged branches", chosen.len()),
&command,
)? {
return Ok(());
}
let mut lines = Vec::new();
for b in chosen {
match delete_merged(b) {
Ok(Deleted::Done) => lines.push(format!("Deleted {b}")),
Ok(Deleted::NotMerged) => lines.push(format!("Kept {b}: not fully merged")),
Err(e) => lines.push(format!("Failed {b}: {e}")),
}
}
ui::notice("Prune", &lines)
}
fn merge_flow(cfg: &mut Config, b: &BranchRef, current: &str) -> Result<()> {
if current.is_empty() || b.name == current {
return ui::notice(
"Merge",
&["Pick a different branch than the one you are on.".to_string()],
);
}
let command = format!("git merge --no-edit {}", b.name);
let verdict = policy::check(cfg, &Op::CreatesCommit);
if !ui::gate(
cfg,
&verdict,
&format!("Merge {} into {current}", b.name),
&command,
)? {
return Ok(());
}
let out = git::git_raw(&["merge", "--no-edit", &b.name], &Opts::default())?;
if out.ok() {
let mut lines = vec![
format!("Merged {} into {current}.", b.name),
format!("Ran: {command}"),
];
lines.extend(ui::explain(
cfg,
&["A merge brings the other branch's commits into yours."],
));
return ui::notice("Merge", &lines);
}
let state = repo_state::load()?;
if state.op == Some(InProgress::Merge) || state.entries.iter().any(|e| e.conflicted()) {
ui::notice(
"Merge",
&["The merge has conflicts. Opening Conflicts mode.".to_string()],
)?;
return crate::modes::open("conflicts", cfg);
}
ui::notice("Merge failed", &[out.stderr.trim().to_string(), out.text()])
}
fn upstream_flow(cfg: &Config, b: &BranchRef, remotes: &[BranchRef]) -> Result<()> {
if b.remote {
return ui::notice("Upstream", &["Select a local branch.".to_string()]);
}
let guess = format!("{}/{}", cfg.default_remote, b.name);
let Some(answer) = ui::ask("Upstream (remote/branch)", &guess)? else {
return Ok(());
};
let answer = answer.trim().to_string();
if answer.starts_with('-') || !remotes.iter().any(|r| r.name == answer) {
return ui::notice(
"Upstream",
&[format!(
"'{answer}' is not a known remote branch. Fetch first in Sync mode."
)],
);
}
let arg = format!("--set-upstream-to={answer}");
match ui::run_git(cfg, "Setting upstream", &["branch", &arg, &b.name]) {
Ok(msg) => ui::notice("Upstream", &[msg]),
Err(e) if crate::input::is_cancel(&e) => Err(e),
Err(e) => ui::notice("Upstream failed", &[e.to_string()]),
}
}
const KEYS: &[ui::Key] = &[
ui::Key {
key: 'n',
label: "new",
},
ui::Key {
key: 'R',
label: "rename (Shift)",
},
ui::Key {
key: 'd',
label: "delete",
},
ui::Key {
key: 'u',
label: "upstream",
},
ui::Key {
key: 'm',
label: "merge",
},
ui::Key {
key: 'c',
label: "compare",
},
ui::Key {
key: 'p',
label: "prune",
},
ui::Key {
key: 'v',
label: "local/remote",
},
ui::Key {
key: 'r',
label: "refresh",
},
];
const MENU: &[(&str, char)] = &[
("Switch to this branch", 'S'),
("New branch (from current)", 'n'),
("Rename", 'R'),
("Delete", 'd'),
("Set upstream", 'u'),
("Merge into current", 'm'),
("Compare with current", 'c'),
("Prune merged branches", 'p'),
];
pub fn run(config: &mut Config) -> Result<()> {
let mut show_remote = false;
let mut index = 0usize;
loop {
let state = match repo_state::load() {
Ok(s) => s,
Err(e) => return ui::notice("Branch mode", &[e.to_string()]),
};
let all = list_refs()?;
let locals: Vec<String> = all
.iter()
.filter(|b| !b.remote)
.map(|b| b.name.clone())
.collect();
let remotes: Vec<BranchRef> = all.iter().filter(|b| b.remote).cloned().collect();
let shown: Vec<BranchRef> = all
.iter()
.filter(|b| b.remote == show_remote)
.cloned()
.collect();
let current = match &state.branch.head {
Head::Branch { name, .. } | Head::Unborn { name } => name.clone(),
Head::Detached { .. } => String::new(),
};
let mut header = vec![match &state.branch.head {
Head::Branch { name, .. } => format!("On branch {}", screen::accent(name)),
Head::Unborn { name } => format!(
"{} (no commits yet: the branch is created by your first commit; n renames it)",
screen::warning(format!("On unborn branch {name}"))
),
Head::Detached { oid } => screen::warning(format!(
"Detached HEAD at {} (press n to create a branch here)",
oid.chars().take(7).collect::<String>()
)),
}];
header.push(format!(
"Showing {} branches",
if show_remote { "remote" } else { "local" }
));
let rows: Vec<String> = shown.iter().map(row_text).collect();
if rows.is_empty() {
header.push(if show_remote {
"No remote branches. Fetch in Sync mode.".to_string()
} else {
"No local branches yet. Make a first commit, or press n.".to_string()
});
}
let choice = ui::action_list("Branches", &header, &rows, KEYS, &mut index)?;
let (key, i) = match choice {
ui::Choice::Back => return Ok(()),
ui::Choice::Action(k, i) => (k, i),
ui::Choice::Open(i) => {
let Some(sel) = shown.get(i) else { continue };
let options: Vec<&str> = MENU.iter().map(|m| m.0).collect();
match ui::choose(&format!("Branch {}", sel.name), &[], &options)? {
Some(n) => (MENU[n].1, i),
None => continue,
}
}
};
let selected = shown.get(i);
match (key, selected) {
('v', _) => {
show_remote = !show_remote;
index = 0;
}
('r', _) => {}
('n', _) => create_at(config, "HEAD")?,
('p', _) => prune_flow(config)?,
('S', Some(b)) => {
if b.current {
ui::notice("Branch", &["You are already on this branch.".to_string()])?;
} else {
run_switch(config, switch_args(b, &locals), &b.name)?;
}
}
('R', Some(b)) if !b.remote => rename_flow(config, b)?,
('d', Some(b)) => delete_flow(config, b, ¤t)?,
('u', Some(b)) => upstream_flow(config, b, &remotes)?,
('m', Some(b)) => merge_flow(config, b, ¤t)?,
('c', Some(b)) => {
if current.is_empty() {
ui::notice(
"Compare",
&["Detached HEAD: compare from Log mode instead.".to_string()],
)?;
} else {
crate::modes::compare::open(config, ¤t, &b.name)?;
}
}
('R', Some(_)) => ui::notice(
"Branch",
&["Only local branches can be renamed.".to_string()],
)?,
_ => {}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::testutil::TempRepo;
#[test]
fn detached_head_with_orphans_is_backed_up() {
let repo = TempRepo::new(2);
repo.run(|| {
assert!(backup_detached_commits().unwrap().is_none(), "on a branch");
});
repo.git(&["switch", "-q", "--detach", "HEAD"]);
repo.run(|| {
assert!(
backup_detached_commits().unwrap().is_none(),
"reachable from main"
);
});
repo.write("x.txt", "x\n");
repo.git(&["add", "."]);
repo.git(&["commit", "-q", "-m", "orphan"]);
let tip = repo.git(&["rev-parse", "HEAD"]);
repo.run(|| {
let (count, backup) = backup_detached_commits().unwrap().unwrap();
assert_eq!(count, 1);
assert!(backup.starts_with("refs/gct/backup/"));
assert_eq!(repo.git(&["rev-parse", &backup]), tip);
});
}
#[test]
fn rename_flow_pieces_work_on_a_protected_name() {
let repo = TempRepo::new(1);
let cfg = Config::default();
assert!(policy::is_protected(&cfg, "main"));
repo.run(|| {
rename_branch("main", "trunk").unwrap();
assert!(rename_branch("trunk", "-x").is_err());
});
}
#[test]
fn key_labels_do_not_repeat_the_key_letter() {
for key in KEYS {
let first = key.label.chars().next().unwrap();
assert!(
!(first.eq_ignore_ascii_case(&key.key) && key.label.chars().nth(1) == Some(' ')),
"{}",
key.label
);
}
}
#[test]
fn track_table() {
let t = |s| parse_track(s);
assert_eq!(t(""), Track::default());
assert_eq!(
t("ahead 2, behind 1"),
Track {
ahead: 2,
behind: 1,
gone: false
}
);
assert_eq!(
t("behind 4"),
Track {
ahead: 0,
behind: 4,
gone: false
}
);
assert_eq!(
t("ahead 3"),
Track {
ahead: 3,
behind: 0,
gone: false
}
);
assert_eq!(
t("gone"),
Track {
ahead: 0,
behind: 0,
gone: true
}
);
assert_eq!(t("ahead x"), Track::default());
}
#[test]
fn refs_table() {
let text = "refs/heads/main\0abc1234\0origin/main\0ahead 1\0last week\0*\r\n\
refs/heads/ünï/x\0def5678\0\0\0now\0 \n\
refs/remotes/origin/HEAD\0abc1234\0\0\0now\0 \n\
refs/remotes/origin/main\0abc1234\0\0\0now\0 \n\
refs/remotes/origin\0abc1234\0\0\0now\0 \n\
garbage\n\n";
let r = parse_refs(text);
assert_eq!(r.len(), 3);
assert!(r[0].current && !r[0].remote);
assert_eq!(r[0].upstream, "origin/main");
assert_eq!(r[0].track.ahead, 1);
assert_eq!(r[0].date, "last week");
assert_eq!(r[1].name, "ünï/x");
assert!(!r[1].current);
assert!(r[2].remote && r[2].name == "origin/main");
assert!(parse_refs("").is_empty());
}
#[test]
fn prune_filters() {
let merged: Vec<String> = ["main", "* dev", "feat", "release/1", "(HEAD detached)", ""]
.iter()
.map(|s| s.to_string())
.collect();
let protected = |b: &str| b == "main" || b.starts_with("release/");
assert_eq!(
prune_candidates(&merged, &protected, "feat"),
vec!["dev".to_string()]
);
}
#[test]
fn dirty_error_cases() {
assert!(is_dirty_switch_error("error: Your local changes to the following files would be overwritten by checkout:\n\ta.txt\nPlease commit your changes or stash them before you switch branches."));
assert!(is_dirty_switch_error(
"error: The following untracked working tree files would be overwritten by checkout:"
));
assert!(!is_dirty_switch_error("fatal: invalid reference: nope"));
assert!(!is_dirty_switch_error(""));
}
#[test]
fn switch_args_and_names() {
let mk = |name: &str, remote| BranchRef {
name: name.into(),
remote,
oid: String::new(),
upstream: String::new(),
track: Track::default(),
date: String::new(),
current: false,
};
let locals = vec!["main".to_string()];
assert_eq!(switch_args(&mk("dev", false), &locals), ["switch", "dev"]);
assert_eq!(
switch_args(&mk("origin/main", true), &locals),
["switch", "main"]
);
assert_eq!(
switch_args(&mk("origin/a/b", true), &locals),
["switch", "--track", "origin/a/b"]
);
assert!(name_problem("-x").is_some());
assert!(name_problem("a b").is_some());
assert!(name_problem("ok/x").is_none());
}
#[test]
fn dirty_switch_refused_then_stash_works() {
let repo = TempRepo::new(1);
repo.git(&["switch", "-c", "other"]);
repo.write("f1.txt", "other\n");
repo.git(&["commit", "-qam", "other change"]);
repo.git(&["switch", "main"]);
repo.write("f1.txt", "dirty\n");
repo.run(|| {
let first = attempt(&["switch", "other"]).unwrap();
assert!(matches!(first, Attempt::Dirty(_)), "{first:?}");
let args = vec!["switch".to_string(), "other".to_string()];
assert!(matches!(
stash_and_switch(&args, "other").unwrap(),
Attempt::Done(_)
));
});
assert_eq!(repo.git(&["rev-parse", "--abbrev-ref", "HEAD"]), "other");
assert!(repo
.git(&["stash", "list"])
.contains("gct: before switch to other"));
}
#[test]
fn delete_unmerged_backs_up() {
let repo = TempRepo::new(1);
repo.git(&["switch", "-c", "wip"]);
repo.write("w.txt", "w\n");
repo.git(&["add", "."]);
repo.git(&["commit", "-qm", "wip work"]);
let tip = repo.git(&["rev-parse", "wip"]);
repo.git(&["switch", "main"]);
repo.run(|| {
assert_eq!(delete_merged("wip").unwrap(), Deleted::NotMerged);
let backup = force_delete("wip").unwrap();
assert!(backup.starts_with("refs/gct/backup/"));
assert!(list_refs().unwrap().iter().all(|b| b.name != "wip"));
let out = git::git_ok(&["rev-parse", &backup], &Opts::default()).unwrap();
assert_eq!(out, tip);
});
}
#[test]
fn delete_merged_branch_and_list() {
let repo = TempRepo::new(1);
repo.git(&["branch", "done"]);
repo.run(|| {
assert_eq!(delete_merged("done").unwrap(), Deleted::Done);
let refs = list_refs().unwrap();
assert_eq!(refs.len(), 1);
assert!(refs[0].current);
assert_eq!(merged_into("main").unwrap(), vec!["main".to_string()]);
assert_eq!(default_branch(&Config::default()), Some("main".to_string()));
});
}
#[test]
fn create_at_rev_and_rename() {
let repo = TempRepo::new(3);
let first = repo.git(&["rev-parse", "HEAD~2"]);
repo.run(|| {
assert!(validate_name("-bad").is_err());
assert!(validate_name("bad..name").is_err());
let r = create_branch("from-first", Some(&first), false).unwrap();
assert!(matches!(r, Attempt::Done(_)), "{r:?}");
rename_branch("from-first", "renamed").unwrap();
});
assert_eq!(repo.git(&["rev-parse", "renamed"]), first);
assert_eq!(repo.git(&["rev-parse", "--abbrev-ref", "HEAD"]), "renamed");
}
#[test]
fn unborn_create_renames_branch() {
let repo = TempRepo::new(0);
repo.run(|| {
assert!(is_unborn());
let r = create_branch("trunk", None, true).unwrap();
assert!(matches!(r, Attempt::Done(_)), "{r:?}");
});
assert_eq!(repo.git(&["symbolic-ref", "--short", "HEAD"]), "trunk");
}
}