//! Branch operations used by the branches page: ahead/behind counts, creating and deleting. use std::path::Path; use crate::command::GitEnv; use crate::error::{Error, Result}; use crate::history::{git, validate_oid}; use crate::pulls::{delete_ref_cas, update_ref_cas}; /// `(ahead, behind)` of `tip` relative to `base`: commits only in `tip`, and commits only in `base`. pub async fn ahead_behind(env: &GitEnv, repo: &Path, base: &str, tip: &str) -> Result<(u32, u32)> { validate_oid(base)?; validate_oid(tip)?; let range = format!("{base}...{tip}"); let out = git(env, "rev-list") .git_dir(repo) .arg("--left-right") .arg("--count") .user_revs(&[range.as_str()])? .output() .await?; let text = String::from_utf8_lossy(&out); let mut it = text.split_whitespace(); let behind = it.next().and_then(|n| n.parse().ok()); let ahead = it.next().and_then(|n| n.parse().ok()); match (ahead, behind) { (Some(a), Some(b)) => Ok((a, b)), _ => Err(Error::Failed(format!( "unexpected rev-list output: {text:?}" ))), } } fn zero_oid(like: &str) -> String { "0".repeat(like.len()) } /// Creates `refs/heads/` at `oid`. Fails when the branch exists already. pub async fn create_branch(env: &GitEnv, repo: &Path, name: &str, oid: &str) -> Result<()> { validate_oid(oid)?; update_ref_cas( env, repo, &format!("refs/heads/{name}"), oid, &zero_oid(oid), ) .await } /// Deletes `refs/heads/` if it still points at `oid`. pub async fn delete_branch(env: &GitEnv, repo: &Path, name: &str, oid: &str) -> Result<()> { delete_ref_cas(env, repo, &format!("refs/heads/{name}"), oid).await }