From ee7a9029ce2c1e5e2632e0a095ecf5b36ac392a4 Mon Sep 17 00:00:00 2001 From: Fintan Halpenny Date: Mon, 26 Sep 2022 11:59:34 +0100 Subject: [PATCH] git-storage: fallible functions for finding objects When an object does not exist the `find_*` functions will return None. It will be a common case that users of the API will follow the pattern of `find_blob(store, oid)?.ok_or(Error::NotFound)`. Add fallible functions corresponding to each `find_` function returning a `git2::Error` if the object is not found. Signed-off-by: Fintan Halpenny --- git-storage/src/odb.rs | 64 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) diff --git a/git-storage/src/odb.rs b/git-storage/src/odb.rs index ed15052..5b6f59a 100644 --- a/git-storage/src/odb.rs +++ b/git-storage/src/odb.rs @@ -31,3 +31,67 @@ pub use read::Read; pub mod write; pub use write::Write; + +/// Find the [`Object`] corresponding to the given `oid`. +/// +/// Will fail if the object does not exist. +pub fn object(storage: &S, oid: Oid) -> Result +where + S: Read, +{ + storage + .find_object(oid)? + .ok_or_else(|| not_found("object", oid)) +} + +/// Find the [`Blob`] corresponding to the given `oid`. +/// +/// Will fail if the blob does not exist. +pub fn blob(storage: &S, oid: Oid) -> Result +where + S: Read, +{ + storage + .find_blob(oid)? + .ok_or_else(|| not_found("blob", oid)) +} + +/// Find the [`Commit`] corresponding to the given `oid`. +/// +/// Will fail if the commit does not exist. +pub fn commit(storage: &S, oid: Oid) -> Result +where + S: Read, +{ + storage + .find_commit(oid)? + .ok_or_else(|| not_found("commit", oid)) +} + +/// Find the [`Tag`] corresponding to the given `oid`. +/// +/// Will fail if the tag does not exist. +pub fn tag(storage: &S, oid: Oid) -> Result +where + S: Read, +{ + storage.find_tag(oid)?.ok_or_else(|| not_found("tag", oid)) +} + +/// Find the [`Tree`] corresponding to the given `oid`. +/// +/// Will fail if the tree does not exist. +pub fn tree(storage: &S, oid: Oid) -> Result +where + S: Read, +{ + storage + .find_tree(oid)? + .ok_or_else(|| not_found("tree", oid)) +} + +fn not_found(kind: &str, oid: Oid) -> git2::Error { + use git2::{ErrorClass::*, ErrorCode::*}; + + git2::Error::new(NotFound, Object, format!("could not find {kind} {oid}")) +}