Skip to content

Commit

Permalink
feat: Add Reference::follow() as a way to peel symbolic refs step b…
Browse files Browse the repository at this point in the history
…y step.
  • Loading branch information
Byron committed Jul 31, 2023
1 parent 5f6cf22 commit d9e551b
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
13 changes: 13 additions & 0 deletions gix/src/reference/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ impl<'repo> Reference<'repo> {
}
}

/// Peeling
impl<'repo> Reference<'repo> {
/// Follow all symbolic targets this reference might point to and peel the underlying object
/// to the end of the chain, and return it.
Expand All @@ -81,6 +82,18 @@ impl<'repo> Reference<'repo> {
pub fn into_fully_peeled_id(mut self) -> Result<Id<'repo>, peel::Error> {
self.peel_to_id_in_place()
}

/// Follow this symbolic reference one level and return the ref it refers to.
///
/// Returns `None` if this is not a symbolic reference, hence the leaf of the chain.
pub fn follow(&self) -> Option<Result<Reference<'repo>, gix_ref::file::find::existing::Error>> {
self.inner.follow(&self.repo.refs).map(|res| {
res.map(|r| Reference {
inner: r,
repo: self.repo,
})
})
}
}

mod edits;
Expand Down
21 changes: 20 additions & 1 deletion gix/tests/reference/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ mod find {
use std::convert::TryInto;

use gix_ref as refs;
use gix_ref::FullNameRef;
use gix_ref::{FullName, FullNameRef, Target};

use crate::util::hex_to_id;

Expand Down Expand Up @@ -64,6 +64,25 @@ mod find {
assert_eq!(symbolic_ref.into_fully_peeled_id()?, the_commit, "idempotency");
Ok(())
}

#[test]
fn and_follow() -> crate::Result {
let repo = repo()?;
let mut symbolic_ref = repo.find_reference("multi-link-target1")?;
let first_hop = Target::Symbolic(FullName::try_from("refs/tags/multi-link-target2").expect("valid"));
assert_eq!(symbolic_ref.target(), first_hop.to_ref());

let second_hop = Target::Symbolic(FullName::try_from("refs/remotes/origin/multi-link-target3").expect("valid"));
symbolic_ref = symbolic_ref.follow().expect("another hop")?;
assert_eq!(symbolic_ref.target(), second_hop.to_ref());

let last_hop = Target::Peeled(hex_to_id("134385f6d781b7e97062102c6a483440bfda2a03"));
symbolic_ref = symbolic_ref.follow().expect("another hop")?;
assert_eq!(symbolic_ref.target(), last_hop.to_ref());

assert!(symbolic_ref.follow().is_none(), "direct references can't be followed");
Ok(())
}
}

#[test]
Expand Down

0 comments on commit d9e551b

Please sign in to comment.