Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions src/python.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,9 @@ fn is_clean(_path: String) -> PyResult<bool> {
}

#[pyfunction]
fn current_branch(_path: String) -> PyResult<Option<String>> {
todo!("repo::current_branch (None if detached)")
fn current_branch(path: String) -> PyResult<Option<String>> {
// soft-fail: any error -> None (API.md)
Ok(crate::repo::current_branch(std::path::Path::new(&path)).unwrap_or(None))
}

#[pyfunction]
Expand Down
38 changes: 38 additions & 0 deletions src/repo/current_branch.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
use crate::error::GitxtendError;
use crate::repo::Result;
use std::path::Path;

/// Short name of the current branch (e.g. "main"); `Ok(None)` when HEAD is
/// detached (mirrors `git rev-parse --abbrev-ref HEAD`, which prints "HEAD"
/// when detached — we return None in that case).
pub fn current_branch(path: &Path) -> Result<Option<String>> {
let repo = gix::open(path).map_err(GitxtendError::from_err)?;
let head = repo.head().map_err(GitxtendError::from_err)?;
Ok(head.referent_name().map(|n| n.shorten().to_string()))
}

#[cfg(test)]
mod tests {
use super::*;
use crate::repo::fixtures;

#[test]
fn test_current_branch_on_main() {
let td = fixtures::repo();
let p = td.path();
assert_eq!(current_branch(p).unwrap(), Some("main".into()));
assert_eq!(
current_branch(p).unwrap(),
Some(fixtures::git(p, &["rev-parse", "--abbrev-ref", "HEAD"]))
);
}

#[test]
fn test_current_branch_detached_head() {
let td = fixtures::repo();
let p = td.path();
let sha = fixtures::git(p, &["rev-parse", "HEAD"]);
fixtures::git(p, &["checkout", "--detach", &sha]);
assert_eq!(current_branch(p).unwrap(), None);
}
}
3 changes: 3 additions & 0 deletions src/repo/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@ pub use is_git_repo::is_git_repo;
mod head_sha;
pub use head_sha::head_sha;

mod current_branch;
pub use current_branch::current_branch;

/// Temp-dir git fixtures shared by the per-method parity tests.
///
/// Fixtures are built with the real `git` CLI, so each parity test asserts
Expand Down
Loading