Skip to content

Commit

Permalink
feat: add Repository::index_or_empty().
Browse files Browse the repository at this point in the history
This is useful if a missing index should mean it's empty.
  • Loading branch information
Byron committed Oct 5, 2023
1 parent 54fb7c2 commit 7d9ecdd
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 0 deletions.
10 changes: 10 additions & 0 deletions gix/src/repository/index.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,16 @@ impl crate::Repository {
})
}

/// Return the shared worktree index if present, or return a new empty one which has an association to the place where the index would be.
pub fn index_or_empty(&self) -> Result<worktree::Index, worktree::open_index::Error> {
Ok(self.try_index()?.unwrap_or_else(|| {
worktree::Index::new(gix_fs::FileSnapshot::new(gix_index::File::from_state(
gix_index::State::new(self.object_hash()),
self.index_path(),
)))
}))
}

/// Return a shared worktree index which is updated automatically if the in-memory snapshot has become stale as the underlying file
/// on disk has changed, or `None` if no such file exists.
///
Expand Down
3 changes: 3 additions & 0 deletions gix/tests/repository/worktree.rs
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,7 @@ mod with_core_worktree_config {
}

#[test]
#[cfg(feature = "index")]
fn bare_relative() -> crate::Result {
let repo = repo("bare-relative-worktree");

Expand All @@ -123,6 +124,8 @@ mod with_core_worktree_config {
repo.work_dir().is_none(),
"we simply don't load core.worktree in bare repos either to match this behaviour"
);
assert!(repo.try_index()?.is_none());
assert!(repo.index_or_empty()?.entries().is_empty());
Ok(())
}

Expand Down

0 comments on commit 7d9ecdd

Please sign in to comment.