Skip to content

Commit

Permalink
refactor(errors): remove thiserror crate and rework error format
Browse files Browse the repository at this point in the history
  • Loading branch information
oknozor committed Nov 30, 2021
1 parent abc8f01 commit 5b00f9e
Show file tree
Hide file tree
Showing 8 changed files with 217 additions and 85 deletions.
21 changes: 0 additions & 21 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ and semver specifications.
[dependencies]
git2 = { version = "^0", default-features = false, features = [] }
anyhow = "^1"
thiserror = "^1"
colored = "^2"
chrono = "^0"
config = "^0"
Expand Down
96 changes: 74 additions & 22 deletions src/conventional/commit.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::error::ErrorKind::CommitFormat;
use crate::error::CocogittoError::CommitFormat;
use crate::AUTHORS;
use crate::REMOTE_URL;
use anyhow::Result;
Expand Down Expand Up @@ -54,26 +54,14 @@ impl Commit {
date,
}),
Err(err) => {
let additional_info = if commit.parent_count() == 0 {
format!(
"{} Init commit or commit with no parent cannot be edited",
"warning:".yellow()
)
} else {
"".to_string()
};

let message = git2_message.trim_end();
let commit_message = Commit::format_summary(message).red().to_string();
let summary = Commit::short_summary_from_str(message);

let cause = format!("{} {}", "cause:".magenta(), err);
let level = "ERROR".red().bold().to_string();
Err(anyhow!(CommitFormat {
level,
shorthand: oid[0..6].into(),
commit_message,
additional_info,
cause
oid,
summary,
author,
cause: err.to_string()
}))
}
}
Expand Down Expand Up @@ -119,7 +107,7 @@ impl Commit {

pub fn get_log(&self) -> String {
let summary = &self.message.summary;
let message_display = Commit::format_summary(summary).yellow();
let message_display = Commit::short_summary_from_str(summary).yellow();
let author_format = "Author:".green().bold();
let type_format = "Type:".green().bold();
let scope_format = "Scope:".green().bold();
Expand Down Expand Up @@ -188,7 +176,19 @@ impl Commit {
}
}

fn format_summary(summary: &str) -> String {
pub(crate) fn format_summary(&self) -> String {
match &self.message.scope {
None => format!("{}: {}", self.message.commit_type, self.message.summary,),
Some(scope) => {
format!(
"{}({}): {}",
self.message.commit_type, scope, self.message.summary,
)
}
}
}

fn short_summary_from_str(summary: &str) -> String {
if summary.len() > 80 {
// display a maximum of 80 char (77 char + ...)
let message = summary.chars().take(77).collect::<String>();
Expand Down Expand Up @@ -239,8 +239,10 @@ pub fn verify(author: Option<String>, message: &str) -> Result<(), ParseError> {

#[cfg(test)]
mod test {
use crate::conventional::commit::verify;
use conventional_commit_parser::commit::CommitType;
use crate::conventional::commit::{verify, Commit};
use chrono::NaiveDateTime;
use conventional_commit_parser::commit::{CommitType, ConventionalCommit};
use speculoos::prelude::*;

#[test]
fn should_map_conventional_commit_message_to_struct() {
Expand Down Expand Up @@ -283,4 +285,54 @@ mod test {
// Assert
assert!(result.is_err());
}

#[test]
fn format_summary() {
// Arrange
let commit = Commit {
oid: "1234567".to_string(),
message: ConventionalCommit {
commit_type: CommitType::BugFix,
scope: Some("scope".to_string()),
summary: "this is the message".to_string(),
body: None,
footers: vec![],
is_breaking_change: false,
},

author: "".to_string(),
date: NaiveDateTime::from_timestamp(0, 0),
};

// Act
let summary = commit.format_summary();

// Assert
assert_that(&summary).is_equal_to("fix(scope): this is the message".to_string());
}

#[test]
fn format_summary_without_scope() {
// Arrange
let commit = Commit {
oid: "1234567".to_string(),
message: ConventionalCommit {
commit_type: CommitType::BugFix,
scope: None,
summary: "this is the message".to_string(),
body: None,
footers: vec![],
is_breaking_change: false,
},

author: "".to_string(),
date: NaiveDateTime::from_timestamp(0, 0),
};

// Act
let summary = commit.format_summary();

// Assert
assert_that(&summary).is_equal_to("fix: this is the message".to_string());
}
}
126 changes: 110 additions & 16 deletions src/error.rs
Original file line number Diff line number Diff line change
@@ -1,26 +1,120 @@
use crate::OidOf;
use colored::*;
use std::fmt;
use std::fmt::Formatter;
use thiserror::Error;
use std::fmt::{Debug, Display, Formatter};

#[derive(Error, Debug)]
pub(crate) enum ErrorKind {
#[error("{level} - {commit_message} - ({shorthand})\n\t{cause}\n\t{additional_info}")]
#[derive(Debug)]
pub(crate) enum CocogittoError {
CommitFormat {
level: String,
shorthand: String,
commit_message: String,
oid: String,
summary: String,
author: String,
cause: String,
additional_info: String,
},
#[error("On branch {branch}\nNothing to commit")]
NothingToCommitWithBranch { branch: String },
#[error("Nothing to commit")]
CommitTypeNotAllowed {
oid: String,
summary: String,
commit_type: String,
author: String,
},
NothingToCommitWithBranch {
branch: String,
},
NothingToCommit,
#[error("{level}:\n\t{cause}\n")]
Semver { level: String, cause: String },
#[error("{level}:\n\t{cause}\n")]
Git { level: String, cause: String },
Semver {
level: String,
cause: String,
},
Git {
level: String,
cause: String,
},
}

impl Display for CocogittoError {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
CocogittoError::CommitFormat {
summary,
oid,
author,
cause,
} => {
let error_header = "Errored commit : ".bold().red();
let author = format!("<{}>", author).blue();
writeln!(
f,
"{header}{oid} {author}\n\t{message_title}'{summary}'\n\t{cause_title}{cause}",
header = error_header,
oid = oid,
author = author,
message_title = "Commit message : ".yellow().bold(),
summary = summary.italic(),
cause_title = "Cause : ".yellow().bold(),
cause = cause
)
}
CocogittoError::CommitTypeNotAllowed {
summary,
commit_type,
oid,
author,
} => {
let error_header = "Errored commit : ".bold().red();
let author = format!("<{}>", author).blue();
writeln!(
f,
"{header}{oid} {author}\n\t{message}'{summary}'\n\t{cause}Commit type `{commit_type}` not allowed",
header = error_header,
oid = oid,
author = author,
message = "Commit message : ".yellow().bold(),
cause = "Cause : ".yellow().bold(),
summary = summary.italic(),
commit_type = commit_type.red()
)
}
CocogittoError::NothingToCommitWithBranch { branch } => {
writeln!(f, "On branch {}\nNothing to commit", branch)
}
CocogittoError::NothingToCommit => {
writeln!(f, "Nothing to commit")
}
CocogittoError::Semver { cause, level } => {
writeln!(f, "{}:\n\t{}\n", level, cause)
}
CocogittoError::Git { level, cause } => {
writeln!(f, "{}:\n\t{}\n", level, cause)
}
}
}
}

#[derive(Debug)]
pub(crate) struct CogCheckReport {
pub from: OidOf,
pub errors: Vec<anyhow::Error>,
}

impl Display for CogCheckReport {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
let header = format!(
"\nFound {} non compliant commits in {}..HEAD:\n",
self.errors.len(),
self.from
)
.red()
.bold();

writeln!(f, "{}", header)?;

for err in &self.errors {
let underline = format!("{:>57}", " ").underline();
writeln!(f, "{:>5}\n", underline)?;
write!(f, "{}", err)?;
}
Ok(())
}
}

// This is not meant to be unwrapped like other errors
Expand Down
12 changes: 8 additions & 4 deletions src/git/repository.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ use git2::{
use itertools::Itertools;
use semver::Version;

use crate::error::ErrorKind;
use crate::error::ErrorKind::Git;
use crate::error::CocogittoError;
use crate::error::CocogittoError::Git;
use crate::OidOf;

use super::status::Statuses;
Expand Down Expand Up @@ -83,8 +83,8 @@ impl Repository {
} else {
let err = self
.get_branch_shorthand()
.map(|branch| ErrorKind::NothingToCommitWithBranch { branch })
.unwrap_or_else(|| ErrorKind::NothingToCommit);
.map(|branch| CocogittoError::NothingToCommitWithBranch { branch })
.unwrap_or_else(|| CocogittoError::NothingToCommit);

Err(anyhow!(err))
}
Expand Down Expand Up @@ -177,6 +177,10 @@ impl Repository {
.map_err(|err| anyhow!("Could not resolve latest tag : {}", err))
}

pub(crate) fn get_first_commit_oidof(&self) -> Result<OidOf> {
self.get_first_commit().map(OidOf::Other)
}

pub(crate) fn get_first_commit(&self) -> Result<Oid> {
let mut revwalk = self.0.revwalk()?;
revwalk.push_head()?;
Expand Down

0 comments on commit 5b00f9e

Please sign in to comment.