use super::*;
pub fn current_branch(root: &Path) -> Option<String> {
let out = run_git(root, &["symbolic-ref", "--quiet", "--short", "HEAD"]).ok()?;
let name = out.trim();
(!name.is_empty()).then(|| name.to_string())
}
pub fn default_branch(root: &Path) -> Result<String, String> {
let path_str = root
.to_str()
.ok_or_else(|| "non-utf8 workspace path".to_string())?;
if let Ok(out) = Git::new()
.at(path_str)
.args(["symbolic-ref", "--short", "refs/remotes/origin/HEAD"])
.into_command()
.output()
&& out.status.success()
{
let raw = String::from_utf8_lossy(&out.stdout).trim().to_string();
if let Some(short) = raw.strip_prefix("origin/") {
if !short.is_empty() {
return Ok(short.to_string());
}
} else if !raw.is_empty() {
return Ok(raw);
}
}
for candidate in ["main", "master", "develop", "trunk"] {
let out = Git::new()
.at(path_str)
.args(["rev-parse", "--verify", "--quiet", candidate])
.into_command()
.output();
if let Ok(o) = out
&& o.status.success()
{
return Ok(candidate.to_string());
}
}
Err(
"Could not resolve a default branch (tried origin/HEAD, main, master, develop, trunk)"
.to_string(),
)
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct BranchInfo {
pub display: String,
pub checkout_name: String,
pub is_current: bool,
pub is_remote: bool,
pub track: Option<String>,
}
pub fn list_branches(root: &Path) -> Result<Vec<BranchInfo>, String> {
let locals_raw = run_git(
root,
&[
"for-each-ref",
"--sort=-committerdate",
"--format=%(refname:short)%09%(HEAD)",
"refs/heads",
],
)
.map_err(|e| e.to_string())?;
let mut branches: Vec<BranchInfo> = Vec::new();
let mut local_names: std::collections::HashSet<String> = std::collections::HashSet::new();
for line in locals_raw.lines() {
let mut parts = line.split('\t');
let Some(name) = parts.next() else { continue };
if name.is_empty() {
continue;
}
let is_current = parts.next().map(|m| m.trim() == "*").unwrap_or(false);
local_names.insert(name.to_string());
branches.push(BranchInfo {
display: name.to_string(),
checkout_name: name.to_string(),
is_current,
is_remote: false,
track: None,
});
}
let remotes_raw = run_git(
root,
&[
"for-each-ref",
"--sort=-committerdate",
"--format=%(refname)%09%(symref)",
"refs/remotes",
],
)
.unwrap_or_default();
let mut remotes: Vec<String> = run_git(root, &["remote"])
.unwrap_or_default()
.lines()
.filter(|l| !l.is_empty())
.map(str::to_string)
.collect();
remotes.sort_by_key(|r| std::cmp::Reverse(r.len()));
for line in remotes_raw.lines() {
let (refname, symref) = line.split_once('\t').unwrap_or((line, ""));
let Some(full) = refname.strip_prefix("refs/remotes/") else {
continue;
};
if full.is_empty() || !symref.is_empty() || full.ends_with("/HEAD") {
continue;
}
let short = remotes
.iter()
.find_map(|r| full.strip_prefix(r.as_str())?.strip_prefix('/'))
.or_else(|| full.split_once('/').map(|(_, s)| s))
.unwrap_or(full);
if local_names.contains(short) {
continue;
}
branches.push(BranchInfo {
display: full.to_string(),
checkout_name: short.to_string(),
is_current: false,
is_remote: true,
track: Some(full.to_string()),
});
}
Ok(branches)
}
pub(super) const ENGLISH_MESSAGES: (&str, &str) = ("LANGUAGE", "en");
pub fn checkout_branch(root: &Path, name: &str) -> Result<String, String> {
run_mutation_with_env(root, &["switch", name], &[ENGLISH_MESSAGES])
}
pub fn track_remote_branch(root: &Path, remote_ref: &str, name: &str) -> Result<String, String> {
run_mutation_with_env(
root,
&["switch", "-c", name, "--track", remote_ref],
&[ENGLISH_MESSAGES],
)
}
pub fn create_branch(root: &Path, name: &str) -> Result<String, String> {
run_mutation(root, &["switch", "-c", name])
}
pub fn create_branch_from(root: &Path, name: &str, base: &str) -> Result<String, String> {
run_mutation(root, &["switch", "-c", name, base])
}
pub fn rename_branch(root: &Path, new_name: &str) -> Result<String, String> {
run_mutation(root, &["branch", "-m", new_name])
}
pub fn delete_branch(root: &Path, name: &str) -> Result<String, String> {
run_mutation(root, &["branch", "-d", name])
}
pub fn merge_branch(root: &Path, branch: &str) -> Result<String, String> {
run_mutation_keeping_conflicts(root, &["merge", branch])
}
pub fn rebase_branch(root: &Path, branch: &str) -> Result<String, String> {
run_mutation_keeping_conflicts(root, &["rebase", branch])
}