Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

surf: expose BlobRef #148

Merged
merged 1 commit into from
Dec 4, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 30 additions & 1 deletion radicle-surf/src/blob.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,13 @@ impl<'a> Blob<BlobRef<'a>> {

/// Represents a blob with borrowed content bytes.
pub struct BlobRef<'a> {
inner: git2::Blob<'a>,
pub(crate) inner: git2::Blob<'a>,
}

impl<'a> BlobRef<'a> {
pub fn id(&self) -> Oid {
self.inner.id().into()
}
}

impl AsRef<[u8]> for BlobRef<'_> {
Expand Down Expand Up @@ -138,3 +144,26 @@ where
state.end()
}
}

#[cfg(feature = "serde")]
impl<'a> Serialize for BlobRef<'a> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
const FIELDS: usize = 3;
let mut state = serializer.serialize_struct("BlobRef", FIELDS)?;
state.serialize_field("id", &self.id())?;
state.serialize_field("binary", &self.inner.is_binary())?;

let bytes = self.as_ref();
match std::str::from_utf8(bytes) {
Ok(s) => state.serialize_field("content", s)?,
Err(_) => {
let encoded = base64::encode(bytes);
state.serialize_field("content", &encoded)?
},
};
state.end()
}
}
6 changes: 6 additions & 0 deletions radicle-surf/src/repo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -301,6 +301,12 @@ impl Repository {
Ok(Blob::<BlobRef<'a>>::new(file.id(), git2_blob, last_commit))
}

pub fn blob_ref(&self, oid: Oid) -> Result<BlobRef<'_>, Error> {
Ok(BlobRef {
inner: self.find_blob(oid)?,
})
}

/// Returns the last commit, if exists, for a `path` in the history of
/// `rev`.
pub fn last_commit<P, C>(&self, path: &P, rev: C) -> Result<Option<Commit>, Error>
Expand Down
Loading