Skip to content

Commit

Permalink
feat!: Let 'easy::Object::try_into_…() return try_into::Error`. (#298)
Browse files Browse the repository at this point in the history
That way, the typical usage of `try_into_commit()?` will not result
in a strange error about `Object` not being convertible into some
error. We think having a real error there is the least surprising.
  • Loading branch information
Byron committed Jan 26, 2022
1 parent 6980090 commit 813a3be
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 8 deletions.
6 changes: 2 additions & 4 deletions git-repository/src/easy/object/commit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ mod error {
pub use error::Error;

use crate::bstr::BStr;
use crate::easy;

impl<'repo> Commit<'repo> {
/// Parse the commits message into a [`MessageRef`][git_object::commit::MessageRef], after decoding the entire commit object.
Expand All @@ -46,10 +47,7 @@ impl<'repo> Commit<'repo> {
let tree_id = self.tree_id().ok_or(Error::Decode)?;
match self.handle.find_object(tree_id)?.try_into_tree() {
Ok(tree) => Ok(tree),
Err(obj) => Err(Error::ObjectKind {
actual: obj.kind,
expected: git_object::Kind::Tree,
}),
Err(easy::object::try_into::Error { actual, expected, .. }) => Err(Error::ObjectKind { actual, expected }),
}
}

Expand Down
28 changes: 24 additions & 4 deletions git-repository/src/easy/object/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,18 @@ pub mod peel;
///
pub mod tree;

///
pub mod try_into {
#[derive(thiserror::Error, Debug)]
#[allow(missing_docs)]
#[error("Object named {id} was supposed to be of kind {expected}, but was kind {actual}.")]
pub struct Error {
pub actual: git_object::Kind,
pub expected: git_object::Kind,
pub id: git_hash::ObjectId,
}
}

impl DetachedObject {
/// Infuse this owned object with an [`easy::Handle`].
pub fn attach(self, handle: &easy::Handle) -> Object<'_> {
Expand Down Expand Up @@ -60,13 +72,21 @@ impl<'repo> Object<'repo> {
}

/// Transform this object into a commit, or return it as part of the `Err` if it is no commit.
pub fn try_into_commit(self) -> Result<Commit<'repo>, Self> {
self.try_into()
pub fn try_into_commit(self) -> Result<Commit<'repo>, try_into::Error> {
self.try_into().map_err(|this: Self| try_into::Error {
id: this.id,
actual: this.kind,
expected: git_object::Kind::Commit,
})
}

/// Transform this object into a tree, or return it as part of the `Err` if it is no tree.
pub fn try_into_tree(self) -> Result<Tree<'repo>, Self> {
self.try_into()
pub fn try_into_tree(self) -> Result<Tree<'repo>, try_into::Error> {
self.try_into().map_err(|this: Self| try_into::Error {
id: this.id,
actual: this.kind,
expected: git_object::Kind::Tree,
})
}
}

Expand Down

0 comments on commit 813a3be

Please sign in to comment.