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

feat: converting error handing to anyhow #47

Merged
merged 1 commit into from
Oct 16, 2024
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
7 changes: 7 additions & 0 deletions Cargo.lock

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

3 changes: 3 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,9 @@ lazy_static = "1.4.0"
strum = "0.26.0"
strum_macros = "0.26.0"

# For error handling.
anyhow = "1.0.89"


[dev-dependencies]
# For parameterized testing.
Expand Down
6 changes: 6 additions & 0 deletions end-to-end-tests/features/steps/assertions.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,12 @@ def assert_error_equals(result, error):
f"Error = {error.encode()}.\n"


def assert_error_contains(result, error):
assert error in result.stderr, "Expected standard error to contain the error.\n" + \
f"Standard error = {result.stderr.encode()}.\n" + \
f"Error = {error.encode()}.\n"


def assert_error_matches_regex(result, regex):
assert regex.match(result.stderr) is not None, f"Expected standard errors to match the regex.\n" + \
f"Standard error = {result.stderr.encode()}.\n" + \
Expand Down
14 changes: 7 additions & 7 deletions end-to-end-tests/features/steps/then.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,45 +41,45 @@ def assert_current_version_assertion_fails(context):
@then('their is a could not find commit hash "{commit_hash}" error.')
def assert_could_not_find_commit_hash_error(context, commit_hash):
# Given
could_not_find_commit_hash_error = f" ERROR conventional_commits_next_version::commits > Can not find a commit with the hash '{commit_hash}'.\n" # fmt: off
could_not_find_commit_hash_error = f"Can not find a commit with the hash '{commit_hash}'.\n" # fmt: off

# When
result = execute_conventional_commits_next_version(context)

# Then
assert_no_output(result)
assert_command_unsuccessful(result)
assert_error_equals(result, could_not_find_commit_hash_error)
assert_error_contains(result, could_not_find_commit_hash_error)


@then('their is a could not find reference "{reference}" error.')
def assert_could_not_find_reference_error(context, reference):
# Given
could_not_find_reference_error = f" ERROR conventional_commits_next_version::commits > Could not find a reference with the name \"{reference}\".\n" # fmt: off
could_not_find_reference_error = f"Could not find a reference with the name \"{reference}\".\n" # fmt: off

# When/Then
result = assert_current_version_assertion_fails(context)

# Then
assert_error_equals(result, could_not_find_reference_error)
assert_error_contains(result, could_not_find_reference_error)


@then('their is a could not find shortened commit hash "{shortened_commit_hash}" error.')
def assert_could_not_find_shortened_commit_hash_error(context, shortened_commit_hash):
# Given
could_not_find_shortened_commit_hash_error = f" ERROR conventional_commits_next_version::commits > No commit hashes start with the provided short commit hash \"{shortened_commit_hash}\".\n" # fmt: off
could_not_find_shortened_commit_hash_error = f"No commit hashes start with the provided short commit hash \"{shortened_commit_hash}\".\n" # fmt: off

# When/Then
result = assert_current_version_assertion_fails(context)

# Then
assert_error_equals(result, could_not_find_shortened_commit_hash_error)
assert_error_contains(result, could_not_find_shortened_commit_hash_error)


@then('their is a ambiguous shortened commit hash "{shortened_commit_hash}" error.')
def assert_ambiguous_shortened_commit_hash_error(context, shortened_commit_hash):
# Given
ambiguous_shortened_commit_hash_error = re.compile(f"^ ERROR conventional_commits_next_version::commits > Ambiguous short commit hash, the commit hashes [[]({shortened_commit_hash}[a-f0-9]*(, )?)*[]] all start with the provided short commit hash \"{shortened_commit_hash}\".\n$") # fmt: off
ambiguous_shortened_commit_hash_error = re.compile(f"^ ERROR conventional_commits_next_version > Ambiguous short commit hash, the commit hashes [[]({shortened_commit_hash}[a-f0-9]*(, )?)*[]] all start with the provided short commit hash \"{shortened_commit_hash}\".\n$") # fmt: off

# When/Then
result = assert_current_version_assertion_fails(context)
Expand Down
79 changes: 35 additions & 44 deletions src/commits/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use std::collections::VecDeque;

use anyhow::{bail, Context, Result};
use git2::{Oid, Repository, Revwalk};
use semver::{BuildMetadata, Prerelease, Version};

Expand Down Expand Up @@ -27,7 +28,7 @@ impl Commits {
reference: T,
commit_filters: Vec<String>,
git_history_mode: GitHistoryMode,
) -> Result<Commits, git2::Error> {
) -> Result<Commits> {
let reference_oid = get_reference_oid(repository, reference.as_ref())?;
get_commits_till_head_from_oid(repository, reference_oid, commit_filters, git_history_mode)
}
Expand All @@ -37,7 +38,7 @@ impl Commits {
commit_hash: T,
commit_filters: Vec<String>,
git_history_mode: GitHistoryMode,
) -> Result<Commits, git2::Error> {
) -> Result<Commits> {
let commit_oid = parse_to_oid(repository, commit_hash.as_ref())?;
get_commits_till_head_from_oid(repository, commit_oid, commit_filters, git_history_mode)
}
Expand Down Expand Up @@ -138,25 +139,23 @@ fn get_commits_till_head_from_oid(
from_commit_hash: Oid,
commit_filters: Vec<String>,
git_history_mode: GitHistoryMode,
) -> Result<Commits, git2::Error> {
) -> Result<Commits> {
fn get_revwalker(
repository: &Repository,
from_commit_hash: Oid,
git_history_mode: GitHistoryMode,
) -> Result<Revwalk, git2::Error> {
) -> Result<Revwalk> {
let mut commits = repository.revwalk()?;
if git_history_mode == GitHistoryMode::FirstParent {
commits.simplify_first_parent()?;
}
commits.push_head()?;

match commits.hide(from_commit_hash) {
Ok(_) => Ok(commits),
Err(error) => {
error!("Can not find a commit with the hash '{from_commit_hash}'.");
Err(error)
}
}
commits.hide(from_commit_hash).context(format!(
"Can not find a commit with the hash '{}'.",
from_commit_hash
))?;
Ok(commits)
}

let revwalker = get_revwalker(repository, from_commit_hash, git_history_mode)?;
Expand All @@ -178,31 +177,32 @@ fn get_commits_till_head_from_oid(
}

debug!("Operating upon {} commits.", commits.len());

Ok(Commits { commits })
}

fn get_reference_oid(repository: &Repository, matching: &str) -> Result<Oid, git2::Error> {
match repository.resolve_reference_from_short_name(matching) {
Ok(reference) => {
trace!(
"Matched {matching:?} to the reference {:?}.",
reference.name().unwrap()
);
let commit = reference.peel_to_commit()?;
Ok(commit.id())
}
Err(error) => {
error!("Could not find a reference with the name {matching:?}.");
Err(error)
}
}
fn get_reference_oid(repository: &Repository, matching: &str) -> Result<Oid> {
let reference = repository
.resolve_reference_from_short_name(matching)
.context(format!(
"Could not find a reference with the name {:?}.",
matching
))?;
trace!(
"Matched {:?} to the reference {:?}.",
matching,
reference.name().unwrap()
);
let commit = reference.peel_to_commit()?;
Ok(commit.id())
}

fn parse_to_oid(repository: &Repository, oid: &str) -> Result<Oid, git2::Error> {
fn parse_to_oid(repository: &Repository, oid: &str) -> Result<Oid> {
match oid.len() {
1..=39 => {
trace!("Attempting to find a match for the short commit hash {oid:?}.");
trace!(
"Attempting to find a match for the short commit hash {:?}.",
oid
);
let matching_oid_lowercase = oid.to_lowercase();

let mut revwalker = repository.revwalk()?;
Expand All @@ -220,34 +220,25 @@ fn parse_to_oid(repository: &Repository, oid: &str) -> Result<Oid, git2::Error>
None
}
Err(error) => {
error!("{error:?}");
error!("{:?}", error);
None
}
})
.collect();

match matched_commit_hashes.len() {
0 => {
let error_message = format!(
"No commit hashes start with the provided short commit hash {matching_oid_lowercase:?}."
bail!(
"No commit hashes start with the provided short commit hash {:?}.",
matching_oid_lowercase
);
error!("{error_message}");
Err(git2::Error::from_str(&error_message))
}
1 => Ok(*matched_commit_hashes.first().unwrap()),
_ => {
let error_message = format!("Ambiguous short commit hash, the commit hashes {matched_commit_hashes:?} all start with the provided short commit hash {matching_oid_lowercase:?}.");
error!("{error_message}");
Err(git2::Error::from_str(&error_message))
bail!("Ambiguous short commit hash, the commit hashes {:?} all start with the provided short commit hash {:?}.", matched_commit_hashes, matching_oid_lowercase);
}
}
}
_ => match git2::Oid::from_str(oid) {
Ok(oid) => Ok(oid),
Err(error) => {
error!("{oid:?} is not a valid commit hash.");
Err(error)
}
},
_ => git2::Oid::from_str(oid).context(format!("{:?} is not a valid commit hash.", oid)),
}
}
16 changes: 7 additions & 9 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,12 @@ extern crate pretty_env_logger;

use std::io::{stdin, Read};

use anyhow::{bail, Result};
use clap::Parser;
use git2::Repository;

pub use crate::calculation_mode::CalculationMode;
use crate::cli::Arguments;
pub use crate::commits::Commits;
pub use crate::git_history_mode::GitHistoryMode;
use crate::commits::Commits;

mod calculation_mode;
mod cli;
Expand All @@ -27,12 +26,13 @@ fn main() {
let arguments = Arguments::parse();
trace!("The command line arguments provided are {arguments:?}.");

if run(arguments).is_err() {
if let Err(err) = run(arguments) {
error!("{:?}", err);
std::process::exit(ERROR_EXIT_CODE);
}
}

fn run(arguments: Arguments) -> Result<(), git2::Error> {
fn run(arguments: Arguments) -> Result<()> {
let commits = match (
arguments.from_stdin,
arguments.from_commit_hash,
Expand Down Expand Up @@ -63,17 +63,15 @@ fn run(arguments: Arguments) -> Result<(), git2::Error> {
)
}
(_, _, _) => {
unreachable!("Invalid combination of arguments.");
bail!("Invalid combination of arguments.");
}
}?;
let expected_version =
commits.get_next_version(arguments.from_version, arguments.calculation_mode);

if let Some(current_version) = arguments.current_version {
if current_version < expected_version {
let error_message = format!("The current version {current_version} is not larger or equal to the expected version {expected_version}.");
error!("{error_message}");
return Err(git2::Error::from_str(&error_message));
bail!(format!("The current version {current_version} is not larger or equal to the expected version {expected_version}."));
}
info!("The current version {current_version} is larger or equal to the expected version {expected_version}.");
} else {
Expand Down