Skip to main content

References

Struct References 

Source
pub struct References<'repo> { /* private fields */ }
Expand description

Resolve, list, and update refs for one open repository.

Implementations§

Source§

impl<'repo> References<'repo>

Source

pub fn new(repo: &'repo Repository) -> Self

Bind ref operations to repo.

Source

pub fn repository(&self) -> &'repo Repository

Underlying repository.

Source

pub fn store(&self) -> &'repo dyn RefStore

Low-level ref storage backend (same as Repository::ref_store).

§Examples
use grit_lib::refs::store::RefNameRef;
use grit_lib::repo::{InitOptions, Repository};
let dir = tempfile::tempdir()?;
let (repo, _) = Repository::init(dir.path(), &InitOptions::default())?;
let _ = repo
    .references()
    .store()
    .read_raw(RefNameRef::from_trusted("HEAD"))?;
Source

pub fn resolve(&self, name: impl AsRef<RefNameRef>) -> Result<ObjectId>

Resolve a ref name to an object id, following symbolic refs.

§Errors

Propagates ref store and resolution errors.

§Examples
use grit_lib::refs::store::{RefName, RefNameRef};
use grit_lib::repo::{InitOptions, Repository};
use grit_lib::ident::Signature;
use grit_lib::porcelain::commit::CommitRequest;
use grit_lib::progress::NullProgress;
let dir = std::env::temp_dir().join("grit-refs-resolve-doc");
let (repo, _) = Repository::init(&dir, &InitOptions::default())?;
let mut req = CommitRequest::new("doc");
req.author = Some(Signature::new("Doc", "doc@example.com", repo.identity_now())?);
req.committer = Some(Signature::new("Doc", "doc@example.com", repo.identity_now())?);
req.allow_empty = true;
let _ = repo.commits().create_staged(&req, &mut NullProgress, &grit_lib::progress::CancelToken::never())?;
let main = RefName::try_from("refs/heads/main").expect("valid ref");
let head = repo.references().resolve(&main)?;
assert!(!head.to_hex().is_empty());
Source

pub fn head(&self) -> Result<HeadState>

Where HEAD points: a branch (possibly unborn), a detached commit, or nothing usable.

Files repositories read the on-disk HEAD (including a symlinked HEAD) and resolve the branch tip through this repository’s ref store; reftable and injected stores are the only source of HEAD. A missing or malformed HEAD is HeadState::Invalid, not an error.

§Errors

Propagates ref store read and resolution failures other than a missing branch tip.

§Examples
use grit_lib::repo::{InitOptions, Repository};
let dir = tempfile::tempdir()?;
let (repo, _) = Repository::init(dir.path(), &InitOptions::default())?;
let head = repo.references().head()?;
assert!(head.is_unborn());
assert_eq!(head.branch_name(), Some("main"));
Source

pub fn symbolic(&self, name: impl AsRef<RefNameRef>) -> Result<Option<RefName>>

The target of the symbolic ref name, or None when name is missing or direct.

Only one level is read: HEAD pointing at refs/heads/main yields refs/heads/main even when that ref is itself symbolic.

§Errors

Propagates ref store read failures.

§Examples
use grit_lib::repo::{InitOptions, Repository};
let dir = tempfile::tempdir()?;
let (repo, _) = Repository::init(dir.path(), &InitOptions::default())?;
let target = repo.references().symbolic("HEAD")?;
assert_eq!(target.as_ref().map(|name| name.as_str()), Some("refs/heads/main"));
Source

pub fn dwim(&self, spec: &str) -> Result<Option<DwimMatch>>

Expand a short name the way revision arguments are expanded (main to refs/heads/main, v1.0 to refs/tags/v1.0, origin to refs/remotes/origin/HEAD, …).

Returns None when no rule names an existing ref that resolves. A symbolic ref whose target is missing does not match; the repository’s warning sink is told about it.

§Errors

Propagates ref store read failures and a symbolic ref chain that loops.

§Examples
use grit_lib::repo::{InitOptions, Repository};
let dir = tempfile::tempdir()?;
let (repo, _) = Repository::init(dir.path(), &InitOptions::default())?;
assert!(repo.references().dwim("main")?.is_none());
Source

pub fn list(&self, prefix: &str) -> Result<Vec<(RefName, ObjectId)>>

List refs under prefix (for example "refs/heads/"), sorted by name.

§Errors

Propagates ref store iteration errors.

Source

pub fn list_glob(&self, pattern: &str) -> Result<Vec<(RefName, ObjectId)>>

List refs whose full names match the glob pattern (for example refs/heads/topic/* or refs/tags/v1.*), sorted by name.

The text before the first wildcard is a name prefix, so refs/tags/v* lists refs/tags/v1. A pattern without wildcards lists the refs under that directory.

§Errors

Propagates ref store iteration errors.

§Examples
use grit_lib::repo::{InitOptions, Repository};
let dir = tempfile::tempdir()?;
let (repo, _) = Repository::init(dir.path(), &InitOptions::default())?;
assert!(repo.references().list_glob("refs/tags/v*")?.is_empty());
Source

pub fn query( &self, query: &RefQuery, options: &RefQueryOptions, ) -> Result<Vec<RefListing>>

List refs matching query (patterns, sort, limit) through this repository’s ref store.

§Errors

Returns ref store errors when the ref store cannot be read, when creator-date sort is requested without object data, or when an object read fails.

Source

pub fn update(&self, name: impl AsRef<RefNameRef>, oid: &ObjectId) -> Result<()>

Point name at oid, creating parent directories as needed.

Uses the RefStore installed on this repository (including injected in-memory stores), not a fresh open from git_dir alone.

Symbolic refs are followed: updating HEAD while it points at refs/heads/main moves main and leaves HEAD symbolic. Reflog entries are appended when core.logAllRefUpdates allows (same policy as git update-ref). Identity comes from the repository committer signature.

To rewrite HEAD itself (detach or replace the symref file), use Self::update_direct. To require the ref tip to match an expected oid first, use Self::compare_and_swap.

oid must be stored in this repository, and must be a commit when name is a branch (refs/heads/…) or HEAD. This catches a commit that a concurrent prune deleted after you wrote it, instead of leaving the ref pointing at a missing object.

§Errors

The two object errors are returned as crate::error::RefError::Store. The ref is unchanged on error.

§Examples
use grit_lib::refs::store::{RefName, RefNameRef};
use grit_lib::repo::{InitOptions, Repository};
use grit_lib::ident::Signature;
use grit_lib::porcelain::commit::CommitRequest;
use grit_lib::progress::NullProgress;
let dir = std::env::temp_dir().join("grit-refs-write-doc");
let (repo, _) = Repository::init(&dir, &InitOptions::default())?;
let mut req = CommitRequest::new("doc");
req.author = Some(Signature::new("Doc", "doc@example.com", repo.identity_now())?);
req.committer = Some(Signature::new("Doc", "doc@example.com", repo.identity_now())?);
req.allow_empty = true;
let commit = repo.commits().create_staged(&req, &mut NullProgress, &grit_lib::progress::CancelToken::never())?.oid;
let name = RefName::try_from("refs/heads/handle-demo").expect("valid ref");
repo.references().update(&name, &commit)?;
assert_eq!(repo.references().resolve(&name)?, commit);
Source

pub fn update_direct( &self, name: impl AsRef<RefNameRef>, oid: &ObjectId, ) -> Result<()>

Point name at oid without following symbolic refs.

Updating HEAD writes the object id into .git/HEAD (detached HEAD) instead of moving the branch HEAD points at. Reflog policy matches Self::update.

§Errors

Same validation and backend errors as Self::update.

Source

pub fn compare_and_swap( &self, name: impl AsRef<RefNameRef>, expected: &ObjectId, oid: &ObjectId, ) -> Result<()>

Point name at oid only when it currently resolves to expected.

Symbolic refs are followed the same way as Self::update. On mismatch the ref is unchanged and the error is RefStoreError::ExpectedMismatch.

§Errors

Same as Self::update, plus compare-and-swap mismatch.

Source

pub fn update_symbolic( &self, name: impl AsRef<RefNameRef>, target: impl AsRef<RefNameRef>, ) -> Result<()>

Make name a symbolic ref pointing at target (for example HEAD at refs/heads/main), replacing whatever name held. No reflog entry is written.

target does not have to exist: pointing HEAD at a branch with no commits yet leaves the repository on an unborn branch.

§Errors

RefError::Invalid when name is not safe to store, a namespace conflict with an existing ref, and lock and I/O failures from the ref backend.

§Examples
use grit_lib::repo::{InitOptions, Repository};
let dir = tempfile::tempdir()?;
let (repo, _) = Repository::init(dir.path(), &InitOptions::default())?;
repo.references().update_symbolic("HEAD", "refs/heads/trunk")?;
assert_eq!(repo.references().head()?.branch_name(), Some("trunk"));
Source

pub fn delete(&self, name: impl AsRef<RefNameRef>) -> Result<()>

Delete name and its reflog. A symbolic ref is deleted itself, not its target.

§Errors

RefStoreError::NotFound (as RefError::Store) when name does not exist, RefError::Invalid when it is not safe to store, and lock and I/O failures from the ref backend.

Source

pub fn compare_and_delete( &self, name: impl AsRef<RefNameRef>, expected: &ObjectId, ) -> Result<()>

Delete name only when it currently resolves to expected.

On mismatch the ref is unchanged and the error is RefStoreError::ExpectedMismatch.

§Errors

Same as Self::delete, plus the compare-and-swap mismatch.

Source

pub fn apply(&self, updates: &[RefUpdate]) -> Result<()>

Apply updates as one all-or-nothing transaction through this repository’s ref store.

Every update is checked (compare-and-swap expectations, name conflicts, and that a direct value names a stored object, and a commit on a branch or HEAD) before any ref moves. Reflog lines are written only for updates that carry RefUpdate::reflog.

§Errors

RefStoreError (as RefError::Store) for duplicate names, expectation mismatches, lock and name conflicts, and missing or non-commit objects; I/O and corrupt-store failures from the backend. No ref changes on error.

§Examples
use grit_lib::refs::store::{Expected, RawRef, RefName, RefUpdate, RefUpdateFlags};
use grit_lib::repo::{InitOptions, Repository};
let dir = tempfile::tempdir()?;
let (repo, _) = Repository::init(dir.path(), &InitOptions::default())?;
let target = RefName::try_from("refs/heads/main").expect("valid ref");
repo.references().apply(&[RefUpdate {
    name: RefName::try_from("refs/heads/alias").expect("valid ref"),
    new_value: Some(RawRef::Symbolic(target.as_str().to_owned())),
    expected: Expected::Missing,
    reflog: None,
    flags: RefUpdateFlags::default(),
}])?;
assert_eq!(repo.references().symbolic("refs/heads/alias")?, Some(target));
Source

pub fn apply_each( &self, updates: Vec<RefUpdate>, ) -> Result<Vec<RefUpdateCommitOutcome>>

Apply updates one ref at a time, the way a non-atomic push is applied: deletions commit together first, then creates and updates, and a failing ref is reported in its outcome instead of failing its siblings.

Outcomes are returned in input order.

§Errors

Only failures that stop a whole phase (for example the backend cannot be locked or read); per-ref rejections are in RefUpdateCommitOutcome::result.

Source

pub fn reflog(&self, name: impl AsRef<RefNameRef>) -> Result<Vec<ReflogEntry>>

Read reflog entries for name (oldest first).

§Errors

Propagates reflog parse and backend errors.

Source

pub fn pack(&self, opts: &PackRefsOptions) -> Result<PackRefsReport>

Pack loose refs into packed-refs (files backend) or compact reftable tables.

§Errors

Propagates ref-store, locking, and I/O failures.

Trait Implementations§

Source§

impl<'repo> Clone for References<'repo>

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<'repo> Copy for References<'repo>

Source§

impl<'repo> Debug for References<'repo>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<'repo> !RefUnwindSafe for References<'repo>

§

impl<'repo> !UnwindSafe for References<'repo>

§

impl<'repo> Forget for References<'repo>

§

impl<'repo> Freeze for References<'repo>

§

impl<'repo> Send for References<'repo>

§

impl<'repo> Sync for References<'repo>

§

impl<'repo> Unpin for References<'repo>

§

impl<'repo> UnsafeUnpin for References<'repo>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.