forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.010.5 MiB0a2c24cTahinli1 month ago179 commits

branches.rs54 lines, 1.7 KiBHistoryRawDownload
1//! Branch operations used by the branches page: ahead/behind counts, creating and deleting.
2
3use std::path::Path;
4
5use crate::command::GitEnv;
6use crate::error::{Error, Result};
7use crate::history::{git, validate_oid};
8use crate::pulls::{delete_ref_cas, update_ref_cas};
9
10/// `(ahead, behind)` of `tip` relative to `base`: commits only in `tip`, and commits only in `base`.
11pub async fn ahead_behind(env: &GitEnv, repo: &Path, base: &str, tip: &str) -> Result<(u32, u32)> {
12 validate_oid(base)?;
13 validate_oid(tip)?;
14 let range = format!("{base}...{tip}");
15 let out = git(env, "rev-list")
16 .git_dir(repo)
17 .arg("--left-right")
18 .arg("--count")
19 .user_revs(&[range.as_str()])?
20 .output()
21 .await?;
22 let text = String::from_utf8_lossy(&out);
23 let mut it = text.split_whitespace();
24 let behind = it.next().and_then(|n| n.parse().ok());
25 let ahead = it.next().and_then(|n| n.parse().ok());
26 match (ahead, behind) {
27 (Some(a), Some(b)) => Ok((a, b)),
28 _ => Err(Error::Failed(format!(
29 "unexpected rev-list output: {text:?}"
30 ))),
31 }
32}
33
34fn zero_oid(like: &str) -> String {
35 "0".repeat(like.len())
36}
37
38/// Creates `refs/heads/<name>` at `oid`. Fails when the branch exists already.
39pub async fn create_branch(env: &GitEnv, repo: &Path, name: &str, oid: &str) -> Result<()> {
40 validate_oid(oid)?;
41 update_ref_cas(
42 env,
43 repo,
44 &format!("refs/heads/{name}"),
45 oid,
46 &zero_oid(oid),
47 )
48 .await
49}
50
51/// Deletes `refs/heads/<name>` if it still points at `oid`.
52pub async fn delete_branch(env: &GitEnv, repo: &Path, name: &str, oid: &str) -> Result<()> {
53 delete_ref_cas(env, repo, &format!("refs/heads/{name}"), oid).await
54}