From 620ce2cbd6e1d57e1a1de37ee7660119d2a9820c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Tue, 20 Oct 2026 11:45:59 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat:=20git=20layer=20for=20whitesp?= =?UTF-8?q?ace=20diffs,=20patches,=20file=20lists,=20blame=20and=20branch?= =?UTF-8?q?=20counts?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/forge-git/src/blame.rs | 159 ++++++++++++++++ crates/forge-git/src/branches.rs | 54 ++++++ crates/forge-git/src/history.rs | 162 ++++++++++++++++- crates/forge-git/src/lib.rs | 2 + crates/forge-git/src/pulls.rs | 15 +- crates/forge-git/tests/browse_tools.rs | 242 +++++++++++++++++++++++++ 6 files changed, 628 insertions(+), 6 deletions(-) create mode 100644 crates/forge-git/src/blame.rs create mode 100644 crates/forge-git/src/branches.rs create mode 100644 crates/forge-git/tests/browse_tools.rs diff --git a/crates/forge-git/src/blame.rs b/crates/forge-git/src/blame.rs new file mode 100644 index 0000000..f05b7ac --- /dev/null +++ b/crates/forge-git/src/blame.rs @@ -0,0 +1,159 @@ +//! `blame --porcelain`, parsed into runs of consecutive lines that share a commit. +//! The subprocess pattern is the same as `history`: validated arguments, a byte cap on stdout. + +use std::collections::HashMap; +use std::path::Path; + +use crate::browse::validate_repo_path; +use crate::command::GitEnv; +use crate::error::{Error, Result}; +use crate::history::{git, read_capped, validate_oid}; + +/// What blame knows about one commit. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct BlameCommit { + pub oid: String, + pub author: String, + pub author_time: i64, + pub summary: String, + /// The parent revision and the file's name there, for "blame prior to this commit". None for + /// a boundary or root commit. + pub previous: Option<(String, String)>, +} + +/// A run of consecutive final lines that came from the same commit. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct BlameGroup { + pub commit: String, + /// First final line number of the run (1-based). + pub start: u32, + pub lines: u32, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Blame { + pub groups: Vec, + pub commits: HashMap, + /// Total lines blamed. + pub total: u32, +} + +fn is_header(line: &str) -> Option<(&str, u32)> { + let mut parts = line.split(' '); + let oid = parts.next()?; + if !(oid.len() == 40 || oid.len() == 64) || !oid.bytes().all(|b| b.is_ascii_hexdigit()) { + return None; + } + let _orig = parts.next()?.parse::().ok()?; + let fin = parts.next()?.parse::().ok()?; + Some((oid, fin)) +} + +/// Parses `--porcelain` output. +pub fn parse_porcelain(text: &str) -> Blame { + let mut commits: HashMap = HashMap::new(); + let mut groups: Vec = Vec::new(); + let mut current: Option = None; + let mut total = 0u32; + for line in text.split('\n') { + if line.starts_with('\t') { + // Content line: the final line number came from the header just before it. + continue; + } + if let Some((oid, fin)) = is_header(line) { + commits + .entry(oid.to_owned()) + .or_insert_with(|| BlameCommit { + oid: oid.to_owned(), + author: String::new(), + author_time: 0, + summary: String::new(), + previous: None, + }); + current = Some(oid.to_owned()); + total = total.max(fin); + match groups.last_mut() { + Some(g) if g.commit == oid && g.start + g.lines == fin => g.lines += 1, + _ => groups.push(BlameGroup { + commit: oid.to_owned(), + start: fin, + lines: 1, + }), + } + continue; + } + let Some(oid) = current.as_ref() else { + continue; + }; + let Some(c) = commits.get_mut(oid) else { + continue; + }; + if let Some(v) = line.strip_prefix("author ") { + c.author = v.to_owned(); + } else if let Some(v) = line.strip_prefix("author-time ") { + c.author_time = v.parse().unwrap_or(0); + } else if let Some(v) = line.strip_prefix("summary ") { + c.summary = v.to_owned(); + } else if let Some(v) = line.strip_prefix("previous ") + && let Some((prev, file)) = v.split_once(' ') + { + c.previous = Some((prev.to_owned(), file.to_owned())); + } + } + Blame { + groups, + commits, + total, + } +} + +/// Blames `path` at `commit` (a full oid). Output beyond the cap is an error, so the caller can +/// show its "too large" message rather than a partial blame. The caller bounds the run time. +pub async fn blame( + env: &GitEnv, + repo: &Path, + commit: &str, + path: &str, + ignore_ws: bool, +) -> Result { + validate_oid(commit)?; + validate_repo_path(path)?; + let cmd = git(env, "blame").git_dir(repo).arg("--porcelain"); + let cmd = if ignore_ws { cmd.arg("-w") } else { cmd }; + // `blame` does not understand `--end-of-options`; the oid is validated hex. + let cmd = cmd.user_arg(commit)?.paths(&[path]); + let (buf, complete) = read_capped(cmd).await?; + if !complete { + return Err(Error::Failed("blame output too large".into())); + } + Ok(parse_porcelain(&String::from_utf8_lossy(&buf))) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn groups_consecutive_lines() { + let a = "a".repeat(40); + let b = "b".repeat(40); + let text = format!( + "{a} 1 1 2\nauthor tahinli\nauthor-time 100\nsummary first\nfilename f\n\tone\n\ + {a} 2 2\n\ttwo\n\ + {b} 1 3 1\nauthor other\nauthor-time 200\nsummary second\nprevious {a} f\nfilename f\n\tthree\n\ + {a} 3 4 1\n\tfour\n" + ); + let blame = parse_porcelain(&text); + assert_eq!(blame.total, 4); + assert_eq!(blame.groups.len(), 3); + assert_eq!((blame.groups[0].start, blame.groups[0].lines), (1, 2)); + assert_eq!(blame.groups[1].commit, b); + assert_eq!(blame.groups[2].commit, a); + assert_eq!(blame.commits[&a].author, "tahinli"); + assert_eq!( + blame.commits[&b].previous, + Some((a.clone(), "f".to_owned())) + ); + assert_eq!(blame.commits[&a].previous, None); + } +} diff --git a/crates/forge-git/src/branches.rs b/crates/forge-git/src/branches.rs new file mode 100644 index 0000000..21efcd1 --- /dev/null +++ b/crates/forge-git/src/branches.rs @@ -0,0 +1,54 @@ +//! 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 +} diff --git a/crates/forge-git/src/history.rs b/crates/forge-git/src/history.rs index 06b1630..6402fe2 100644 --- a/crates/forge-git/src/history.rs +++ b/crates/forge-git/src/history.rs @@ -181,7 +181,7 @@ async fn for_each_chunk(cmd: GitCommand, mut f: impl FnMut(&[u8]) -> bool) -> Re } /// Reads the whole stdout up to [`OUTPUT_CAP`]. The flag is `false` when the cap cut it short. -async fn read_capped(cmd: GitCommand) -> Result<(Vec, bool)> { +pub(crate) async fn read_capped(cmd: GitCommand) -> Result<(Vec, bool)> { let mut buf = Vec::new(); let complete = for_each_chunk(cmd, |c| { buf.extend_from_slice(c); @@ -329,6 +329,7 @@ fn diff_tree_cmd( base: &str, oid: &str, mode: DiffMode, + ignore_ws: bool, ) -> Result { let cmd = git(env, "diff-tree") .git_dir(repo) @@ -338,6 +339,9 @@ fn diff_tree_cmd( .arg("--no-color") .arg("--no-ext-diff") .arg("--no-textconv"); + // `-w` on both runs drops files whose only changes are whitespace from the names as well as + // the patch, so the two streams still line up by position. + let cmd = if ignore_ws { cmd.arg("-w") } else { cmd }; let cmd = match mode { DiffMode::NameStatus => cmd.arg("-z").arg("--name-status"), DiffMode::Patch => cmd.arg("-p").arg("--full-index"), @@ -345,7 +349,7 @@ fn diff_tree_cmd( cmd.objects(src)?.user_revs(&[base, oid]) } -pub(crate) fn empty_tree_for(oid: &str) -> &'static str { +pub fn empty_tree_for(oid: &str) -> &'static str { if oid.len() == 64 { EMPTY_TREE_SHA256 } else { @@ -545,13 +549,33 @@ pub async fn commit_diff( repo: &Path, oid: &str, limits: DiffLimits, +) -> Result { + commit_diff_ws(env, repo, oid, limits, false).await +} + +/// [`commit_diff`], optionally ignoring whitespace changes (`git diff -w`). +pub async fn commit_diff_ws( + env: &GitEnv, + repo: &Path, + oid: &str, + limits: DiffLimits, + ignore_ws: bool, ) -> Result { validate_oid(oid)?; let base = match first_parent(env, repo, oid).await? { Some(p) => p, None => empty_tree_for(oid).to_owned(), }; - diff_between(env, repo, ObjectSource::default(), &base, oid, limits).await + diff_between( + env, + repo, + ObjectSource::default(), + &base, + oid, + limits, + ignore_ws, + ) + .await } /// The diff from `base` (a commit or tree id) to `oid` (a commit id), with the same parsing and @@ -563,6 +587,7 @@ pub(crate) async fn diff_between( base: &str, oid: &str, limits: DiffLimits, + ignore_ws: bool, ) -> Result { validate_oid(base)?; validate_oid(oid)?; @@ -573,6 +598,7 @@ pub(crate) async fn diff_between( base, oid, DiffMode::NameStatus, + ignore_ws, )?) .await?; let mut entries = parse_name_status(&name_buf); @@ -586,8 +612,16 @@ pub(crate) async fn diff_between( truncated_files = true; } - let (patch_buf, patch_complete) = - read_capped(diff_tree_cmd(env, repo, src, base, oid, DiffMode::Patch)?).await?; + let (patch_buf, patch_complete) = read_capped(diff_tree_cmd( + env, + repo, + src, + base, + oid, + DiffMode::Patch, + ignore_ws, + )?) + .await?; let patch = String::from_utf8_lossy(&patch_buf); let starts = block_starts(&patch); // A capped patch may end inside its last section, so that section is dropped. @@ -631,6 +665,124 @@ pub(crate) async fn diff_between( }) } +/// A downloadable patch: the bytes and whether they are complete (not cut at the output cap). +pub struct PatchOut { + pub data: Vec, + pub complete: bool, +} + +/// Mbox of one commit in `format-patch` style (`/commit/{oid}.patch`). Binary changes are +/// included so the patch applies. +pub async fn commit_patch(env: &GitEnv, repo: &Path, oid: &str) -> Result { + validate_oid(oid)?; + let cmd = git(env, "format-patch") + .git_dir(repo) + .arg("--stdout") + .arg("--binary") + .arg("--no-signature") + .arg("--no-color") + .arg("--root") + .arg("-1") + .user_revs(&[oid])?; + let (data, complete) = read_capped(cmd).await?; + Ok(PatchOut { data, complete }) +} + +/// Plain unified diff of one commit against its first parent (`/commit/{oid}.diff`). +pub async fn commit_raw_diff(env: &GitEnv, repo: &Path, oid: &str) -> Result { + validate_oid(oid)?; + let base = match first_parent(env, repo, oid).await? { + Some(p) => p, + None => empty_tree_for(oid).to_owned(), + }; + raw_diff(env, repo, ObjectSource::default(), &base, oid).await +} + +/// Plain unified diff from `base` to `oid`, both full object ids. +pub async fn raw_diff( + env: &GitEnv, + repo: &Path, + src: ObjectSource<'_>, + base: &str, + oid: &str, +) -> Result { + validate_oid(base)?; + validate_oid(oid)?; + let cmd = git(env, "diff-tree") + .git_dir(repo) + .arg("-r") + .arg("-p") + .arg("-M") + .arg("--binary") + .arg("--no-commit-id") + .arg("--no-color") + .arg("--no-ext-diff") + .arg("--no-textconv") + .objects(src)? + .user_revs(&[base, oid])?; + let (data, complete) = read_capped(cmd).await?; + Ok(PatchOut { data, complete }) +} + +/// Mbox of the commits reachable from `head` but not from `base`, oldest first. +pub async fn range_patch( + env: &GitEnv, + repo: &Path, + src: ObjectSource<'_>, + base: &str, + head: &str, +) -> Result { + validate_oid(base)?; + validate_oid(head)?; + let exclude = format!("^{base}"); + let cmd = git(env, "format-patch") + .git_dir(repo) + .arg("--stdout") + .arg("--binary") + .arg("--no-signature") + .arg("--no-color") + .objects(src)? + .user_revs(&[head, exclude.as_str()])?; + let (data, complete) = read_capped(cmd).await?; + Ok(PatchOut { data, complete }) +} + +/// Every file path in the tree of `commit`, in tree order, at most `max` of them. The flag is true +/// when the list was cut at `max` or at the output cap. +pub async fn list_files( + env: &GitEnv, + repo: &Path, + commit: &str, + max: usize, +) -> Result<(Vec, bool)> { + validate_oid(commit)?; + let cmd = git(env, "ls-tree") + .git_dir(repo) + .arg("-r") + .arg("-z") + .arg("--name-only") + .arg("--full-tree") + .user_revs(&[commit])?; + let (buf, complete) = read_capped(cmd).await?; + let mut paths: Vec<&[u8]> = buf.split(|&b| b == 0).filter(|p| !p.is_empty()).collect(); + let mut cut = !complete; + if !complete { + // The last record may be partial. + paths.pop(); + } + if paths.len() > max { + paths.truncate(max); + cut = true; + } + Ok(( + paths + .into_iter() + .map(|p| String::from_utf8_lossy(p).into_owned()) + .collect(), + cut, + )) +} + /// The newest commit (walking back from `commit`) that touched each direct child of `dir`, /// keyed by child name. One `git log` walk, limited to `max_walk` commits, and it stops /// early once every name is found. `dir` is `""` for the repo root. diff --git a/crates/forge-git/src/lib.rs b/crates/forge-git/src/lib.rs index 6651689..4e84731 100644 --- a/crates/forge-git/src/lib.rs +++ b/crates/forge-git/src/lib.rs @@ -1,6 +1,8 @@ //! Git plumbing for forge: a safe command builder, repo management and smart-HTTP helpers. pub mod backup; +pub mod blame; +pub mod branches; pub mod browse; pub mod command; pub mod error; diff --git a/crates/forge-git/src/pulls.rs b/crates/forge-git/src/pulls.rs index 072e102..79fd01d 100644 --- a/crates/forge-git/src/pulls.rs +++ b/crates/forge-git/src/pulls.rs @@ -456,6 +456,19 @@ pub async fn range_diff_files_with( base_oid: &str, head_oid: &str, limits: DiffLimits, +) -> Result { + range_diff_files_ws(env, repo, src, base_oid, head_oid, limits, false).await +} + +/// [`range_diff_files_with`], optionally ignoring whitespace changes. +pub async fn range_diff_files_ws( + env: &GitEnv, + repo: &Path, + src: ObjectSource<'_>, + base_oid: &str, + head_oid: &str, + limits: DiffLimits, + ignore_ws: bool, ) -> Result { validate_oid(base_oid)?; validate_oid(head_oid)?; @@ -463,7 +476,7 @@ pub async fn range_diff_files_with( Some(b) => b, None => empty_tree_for(head_oid).to_owned(), }; - diff_between(env, repo, src, &from, head_oid, limits).await + diff_between(env, repo, src, &from, head_oid, limits, ignore_ws).await } /// Commits reachable from `head` but not from `base` (`log ^`), oldest first. diff --git a/crates/forge-git/tests/browse_tools.rs b/crates/forge-git/tests/browse_tools.rs new file mode 100644 index 0000000..3d30d67 --- /dev/null +++ b/crates/forge-git/tests/browse_tools.rs @@ -0,0 +1,242 @@ +//! Tests for the code-browsing helpers: whitespace-free diffs, patches, the recursive file list, +//! blame and branch operations. + +use std::path::{Path, PathBuf}; +use std::process::Command; + +use forge_git::GitEnv; +use forge_git::blame::blame; +use forge_git::branches::{ahead_behind, create_branch, delete_branch}; +use forge_git::command::ObjectSource; +use forge_git::history::{ + DiffLimits, commit_diff_ws, commit_patch, commit_raw_diff, list_files, range_patch, +}; + +const BIG: DiffLimits = DiffLimits { + max_files: 1000, + max_lines_per_file: 10_000, + max_total_lines: 100_000, +}; + +struct Fixture { + _dir: tempfile::TempDir, + work: PathBuf, + git_dir: PathBuf, + env: GitEnv, +} + +fn run(dir: &Path, home: &Path, args: &[&str]) -> String { + let out = Command::new("/usr/bin/git") + .arg("-C") + .arg(dir) + .args([ + "-c", + "user.name=tahinli", + "-c", + "user.email=tahinli@example.com", + "-c", + "commit.gpgsign=false", + ]) + .args(args) + .env_clear() + .env("PATH", "/usr/bin:/bin") + .env("HOME", home) + .env("GIT_CONFIG_NOSYSTEM", "1") + .env("GIT_CONFIG_GLOBAL", "/dev/null") + .output() + .unwrap(); + assert!( + out.status.success(), + "{args:?} failed: {}", + String::from_utf8_lossy(&out.stderr) + ); + String::from_utf8_lossy(&out.stdout).into_owned() +} + +fn fixture() -> Fixture { + let dir = tempfile::tempdir().unwrap(); + let work = dir.path().join("work"); + std::fs::create_dir(&work).unwrap(); + run(&work, dir.path(), &["init", "-q", "-b", "main"]); + let env = GitEnv { + git_bin: PathBuf::from("/usr/bin/git"), + data_dir: dir.path().to_path_buf(), + }; + let git_dir = work.join(".git"); + Fixture { + _dir: dir, + work, + git_dir, + env, + } +} + +impl Fixture { + fn sh(&self, args: &[&str]) -> String { + run(&self.work, self._dir.path(), args) + } + + fn write(&self, name: &str, content: &str) { + let p = self.work.join(name); + std::fs::create_dir_all(p.parent().unwrap()).unwrap(); + std::fs::write(p, content).unwrap(); + } + + fn commit(&self, msg: &str) -> String { + self.sh(&["add", "-A"]); + self.sh(&["commit", "-q", "--allow-empty", "-m", msg]); + self.sh(&["rev-parse", "HEAD"]).trim().to_owned() + } +} + +#[tokio::test] +async fn ignore_whitespace_drops_whitespace_only_files() { + let f = fixture(); + f.write("x.txt", "a\nb\n"); + f.write("y.txt", "c\n"); + f.commit("one"); + f.write("x.txt", "a \nb\n"); + f.write("y.txt", "c\nd\n"); + let head = f.commit("two"); + + let full = commit_diff_ws(&f.env, &f.git_dir, &head, BIG, false) + .await + .unwrap(); + assert_eq!(full.files.len(), 2); + let ws = commit_diff_ws(&f.env, &f.git_dir, &head, BIG, true) + .await + .unwrap(); + assert_eq!(ws.files.len(), 1); + assert_eq!(ws.files[0].new_path.as_deref(), Some("y.txt")); + assert_eq!(ws.files[0].additions, 1); +} + +#[tokio::test] +async fn patch_and_diff_outputs() { + let f = fixture(); + f.write("x.txt", "a\n"); + let root = f.commit("root commit"); + f.write("x.txt", "a\nb\n"); + let head = f.commit("add b"); + + let patch = commit_patch(&f.env, &f.git_dir, &head).await.unwrap(); + assert!(patch.complete); + let text = String::from_utf8(patch.data).unwrap(); + assert!(text.starts_with(&format!("From {head} "))); + assert!(text.contains("Subject: [PATCH] add b")); + assert!(text.contains("+b")); + + let root_patch = commit_patch(&f.env, &f.git_dir, &root).await.unwrap(); + assert!( + String::from_utf8(root_patch.data) + .unwrap() + .contains("+++ b/x.txt") + ); + + let diff = commit_raw_diff(&f.env, &f.git_dir, &head).await.unwrap(); + let diff = String::from_utf8(diff.data).unwrap(); + assert!(diff.starts_with("diff --git a/x.txt b/x.txt")); + + let range = range_patch(&f.env, &f.git_dir, ObjectSource::default(), &root, &head) + .await + .unwrap(); + let range = String::from_utf8(range.data).unwrap(); + assert_eq!(range.matches("\nSubject: ").count(), 1); + assert!(range.contains("add b")); + assert!(!range.contains("root commit")); +} + +#[tokio::test] +async fn list_files_is_recursive_and_capped() { + let f = fixture(); + f.write("a.txt", "1"); + f.write("dir/b.txt", "2"); + f.write("dir/sub/c.txt", "3"); + let head = f.commit("files"); + + let (all, cut) = list_files(&f.env, &f.git_dir, &head, 100).await.unwrap(); + assert!(!cut); + assert_eq!(all, ["a.txt", "dir/b.txt", "dir/sub/c.txt"]); + let (two, cut) = list_files(&f.env, &f.git_dir, &head, 2).await.unwrap(); + assert!(cut); + assert_eq!(two.len(), 2); +} + +#[tokio::test] +async fn blame_groups_by_commit() { + let f = fixture(); + f.write("f.txt", "one\ntwo\nthree\n"); + let first = f.commit("first"); + f.write("f.txt", "one\nTWO\nthree\nfour\n"); + let second = f.commit("second"); + + let b = blame(&f.env, &f.git_dir, &second, "f.txt", false) + .await + .unwrap(); + assert_eq!(b.total, 4); + let shape: Vec<(&str, u32, u32)> = b + .groups + .iter() + .map(|g| (g.commit.as_str(), g.start, g.lines)) + .collect(); + assert_eq!( + shape, + [ + (first.as_str(), 1, 1), + (second.as_str(), 2, 1), + (first.as_str(), 3, 1), + (second.as_str(), 4, 1), + ] + ); + assert_eq!(b.commits[&second].summary, "second"); + assert_eq!(b.commits[&second].author, "tahinli"); + assert_eq!( + b.commits[&second].previous, + Some((first.clone(), "f.txt".to_owned())) + ); +} + +#[tokio::test] +async fn branch_counts_create_and_delete() { + let f = fixture(); + f.write("a.txt", "1"); + let base = f.commit("base"); + f.sh(&["checkout", "-q", "-b", "feature"]); + f.write("b.txt", "2"); + f.commit("feature 1"); + let tip = f.commit("feature 2"); + f.sh(&["checkout", "-q", "main"]); + f.write("c.txt", "3"); + let main_tip = f.commit("main moved"); + + let (ahead, behind) = ahead_behind(&f.env, &f.git_dir, &main_tip, &tip) + .await + .unwrap(); + assert_eq!((ahead, behind), (2, 1)); + + create_branch(&f.env, &f.git_dir, "topic/x", &base) + .await + .unwrap(); + assert_eq!( + f.sh(&["rev-parse", "refs/heads/topic/x"]).trim(), + base.as_str() + ); + assert!( + create_branch(&f.env, &f.git_dir, "topic/x", &base) + .await + .is_err() + ); + assert!( + create_branch(&f.env, &f.git_dir, "bad..name", &base) + .await + .is_err() + ); + delete_branch(&f.env, &f.git_dir, "topic/x", &base) + .await + .unwrap(); + assert!( + delete_branch(&f.env, &f.git_dir, "topic/x", &base) + .await + .is_err() + ); +}