use std::error::Error;
use std::fmt::{self, Display, Formatter};
use std::num::NonZeroUsize;
use std::str::FromStr;
const SHA1_HEX_LENGTH: usize = 40;
const SHA256_HEX_LENGTH: usize = 64;
const ABBREVIATED_OBJECT_ID_LENGTH: usize = 10;
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct CommitPage {
skip: usize,
limit: NonZeroUsize,
}
impl CommitPage {
#[must_use]
pub const fn new(skip: usize, limit: NonZeroUsize) -> Self {
Self { skip, limit }
}
#[must_use]
pub const fn skip(self) -> usize {
self.skip
}
#[must_use]
pub const fn limit(self) -> NonZeroUsize {
self.limit
}
}
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct ObjectId(String);
#[non_exhaustive]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ObjectIdError {
InvalidLength(usize),
NonHexadecimal,
}
impl Display for ObjectIdError {
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
match self {
Self::InvalidLength(length) => write!(
formatter,
"object ID must contain 40 or 64 hexadecimal characters, got {length}"
),
Self::NonHexadecimal => {
formatter.write_str("object ID must contain only hexadecimal ASCII characters")
}
}
}
}
impl Error for ObjectIdError {}
impl ObjectId {
pub fn parse(value: impl Into<String>) -> Result<Self, ObjectIdError> {
let value = value.into();
if !matches!(value.len(), SHA1_HEX_LENGTH | SHA256_HEX_LENGTH) {
return Err(ObjectIdError::InvalidLength(value.len()));
}
if !value.bytes().all(|byte| byte.is_ascii_hexdigit()) {
return Err(ObjectIdError::NonHexadecimal);
}
Ok(Self(value))
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
#[must_use]
pub fn short(&self) -> &str {
let end = self.0.len().min(ABBREVIATED_OBJECT_ID_LENGTH);
&self.0[..end]
}
}
#[cfg(test)]
mod tests {
use super::ObjectId;
#[test]
fn object_id_requires_a_full_sha1_or_sha256_value() {
assert!(ObjectId::parse("a".repeat(40)).is_ok());
assert!(ObjectId::parse("b".repeat(64)).is_ok());
assert!(ObjectId::parse("abcd").is_err());
assert!(ObjectId::parse("z".repeat(40)).is_err());
}
}
impl Display for ObjectId {
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
formatter.write_str(&self.0)
}
}
impl AsRef<str> for ObjectId {
fn as_ref(&self) -> &str {
self.as_str()
}
}
impl FromStr for ObjectId {
type Err = ObjectIdError;
fn from_str(value: &str) -> Result<Self, Self::Err> {
Self::parse(value)
}
}
impl TryFrom<String> for ObjectId {
type Error = ObjectIdError;
fn try_from(value: String) -> Result<Self, Self::Error> {
Self::parse(value)
}
}
impl TryFrom<&str> for ObjectId {
type Error = ObjectIdError;
fn try_from(value: &str) -> Result<Self, Self::Error> {
Self::parse(value)
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CommitSummary {
id: ObjectId,
parents: Vec<ObjectId>,
author: String,
authored_at: String,
subject: String,
}
impl CommitSummary {
#[must_use]
pub fn new(
id: ObjectId,
parents: Vec<ObjectId>,
author: String,
authored_at: String,
subject: String,
) -> Self {
Self {
id,
parents,
author,
authored_at,
subject,
}
}
#[must_use]
pub fn id(&self) -> &ObjectId {
&self.id
}
#[must_use]
pub fn parents(&self) -> &[ObjectId] {
&self.parents
}
#[must_use]
pub fn author(&self) -> &str {
&self.author
}
#[must_use]
pub fn authored_at(&self) -> &str {
&self.authored_at
}
#[must_use]
pub fn subject(&self) -> &str {
&self.subject
}
#[must_use]
pub fn baseline(&self) -> CommitBaseline {
self.parents
.first()
.cloned()
.map_or(CommitBaseline::EmptyTree, CommitBaseline::FirstParent)
}
}
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub enum CommitBaseline {
EmptyTree,
FirstParent(ObjectId),
}
impl Display for CommitBaseline {
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
match self {
Self::EmptyTree => formatter.write_str("empty tree (root commit)"),
Self::FirstParent(parent) => write!(formatter, "first parent {}", parent.short()),
}
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CommitMessage(String);
impl CommitMessage {
#[must_use]
pub fn new(value: String) -> Self {
Self(value)
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
#[must_use]
pub fn body(&self) -> &str {
self.0.split_once('\n').map_or("", |(_, remainder)| {
remainder.strip_prefix('\n').unwrap_or(remainder)
})
}
}
impl AsRef<str> for CommitMessage {
fn as_ref(&self) -> &str {
self.as_str()
}
}
impl Display for CommitMessage {
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
formatter.write_str(self.as_str())
}
}
#[cfg(test)]
mod message_tests {
use super::CommitMessage;
#[test]
fn commit_body_excludes_the_subject_and_separator() {
let message = CommitMessage::new("Subject\n\nBody line\nTrailer: value\n".to_owned());
assert_eq!(message.body(), "Body line\nTrailer: value\n");
assert_eq!(CommitMessage::new("Subject only\n".to_owned()).body(), "");
}
}