Skip to content

Commit

Permalink
refactor: do some general code clean-up
Browse files Browse the repository at this point in the history
  • Loading branch information
tranzystorekk authored and oknozor committed Feb 18, 2021
1 parent b442d49 commit 4c74429
Show file tree
Hide file tree
Showing 7 changed files with 61 additions and 92 deletions.
7 changes: 3 additions & 4 deletions src/conventional/changelog.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use crate::conventional::commit::Commit;
use crate::{OidOf, COMMITS_METADATA};
use anyhow::Result;
use itertools::Itertools;
use std::fmt::Write;
use std::fs;
use std::path::PathBuf;

Expand Down Expand Up @@ -43,16 +44,14 @@ impl ChangelogWriter {

impl Changelog {
pub(crate) fn markdown(&mut self, colored: bool) -> String {
let mut out = String::new();

let short_to = &self.to;
let short_from = &self.from;
let version_title = self
.tag_name
.clone()
.unwrap_or_else(|| format!("{}..{}", short_from, short_to));

out.push_str(&format!("\n## {} - {}\n\n", version_title, self.date));
let mut out = format!("\n## {} - {}\n\n", version_title, self.date);

let grouped = self
.commits
Expand All @@ -66,7 +65,7 @@ impl Changelog {
for (commit_type, commits) in grouped {
let meta = &COMMITS_METADATA[&commit_type];

out.push_str(&format!("\n### {}\n\n", meta.changelog_title));
write!(&mut out, "\n### {}\n\n", meta.changelog_title).unwrap();
for description in commits {
out.push_str(&description);
}
Expand Down
23 changes: 11 additions & 12 deletions src/conventional/commit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -118,12 +118,11 @@ impl Commit {
// Todo extract to ParseError
pub(crate) fn parse_commit_message(message: &str) -> Result<CommitMessage> {
let type_separator = message.find(": ");
if type_separator.is_none() {
return Err(anyhow!(
"invalid commit format : missing `{}` separator",
": ".yellow()
));
}
ensure!(
type_separator.is_some(),
"invalid commit format: missing `{}` separator",
": ".yellow()
);

let idx = type_separator.unwrap();

Expand Down Expand Up @@ -157,9 +156,7 @@ impl Commit {

let description = contents.get(0).map(|desc| desc.to_string());

if description.is_none() {
return Err(anyhow!("missing commit description"));
}
ensure!(description.is_some(), "missing commit description");

let description = description.unwrap();

Expand All @@ -176,9 +173,11 @@ impl Commit {
let commit_type = CommitType::from(commit_type_str);
let allowed_commit = COMMITS_METADATA.get(&commit_type);

if allowed_commit.is_none() {
return Err(anyhow!("unknown commit type `{}`", commit_type_str.red()));
};
ensure!(
allowed_commit.is_some(),
"unknown commit type `{}`",
commit_type_str.red()
);

Ok(CommitMessage {
description,
Expand Down
25 changes: 12 additions & 13 deletions src/conventional/version.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ impl VersionIncrement {
} else if is_patch_bump() {
next_version.increment_patch();
} else {
return Err(anyhow!("No commit found to bump current version"));
bail!("No commit found to bump current version");
}

Ok(next_version)
Expand Down Expand Up @@ -135,18 +135,17 @@ impl VersionIncrement {
}

pub fn parse_pre_release(string: &str) -> Result<Vec<Identifier>> {
if !string
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '.' || c == '-')
{
return Err(anyhow!("Pre-release string must be a dot-separated list of identifiers comprised of ASCII alphanumerics and hyphens [0-9A-Za-z-]"));
}

if string.starts_with('.') || string.contains("..") || string.ends_with('.') {
return Err(anyhow!(
"Dot-separated identifiers in the pre-release string must not be empty"
));
}
ensure!(
string
.chars()
.all(|c| c.is_ascii_alphanumeric() || ['.', '-'].contains(&c)),
"Pre-release string must be a dot-separated list of identifiers comprised of ASCII alphanumerics and hyphens [0-9A-Za-z-]"
);

ensure!(
!string.starts_with('.') && !string.contains("..") && !string.ends_with('.'),
"Dot-separated identifiers in the pre-release string must not be empty"
);

let idents = string
.split('.')
Expand Down
49 changes: 17 additions & 32 deletions src/git/repository.rs
Original file line number Diff line number Diff line change
Expand Up @@ -121,22 +121,11 @@ impl Repository {

pub(crate) fn get_latest_tag(&self) -> Result<String> {
let tag_names = self.0.tag_names(None)?;
let mut versions = Vec::new();
let latest_tag = tag_names.iter().flatten().flat_map(Version::parse).max();

for tag in tag_names.iter().collect::<Vec<Option<&str>>>() {
if let Some(tag) = tag {
if let Ok(version) = Version::parse(tag) {
versions.push(version);
}
}
}

versions.sort();

if let Some(tag) = versions.last() {
Ok(tag.to_string())
} else {
Err(anyhow!("Unable to get any tag"))
match latest_tag {
Some(tag) => Ok(tag.to_string()),
None => Err(anyhow!("Unable to get any tag")),
}
}

Expand Down Expand Up @@ -165,29 +154,25 @@ impl Repository {
}

pub(crate) fn get_head(&self) -> Option<Object> {
if let Ok(head) = Repository::tree_to_treeish(&self.0, Some(&"HEAD".to_string())) {
head
} else {
None
}
Repository::tree_to_treeish(&self.0, Some(&"HEAD".to_string()))
.ok()
.flatten()
}

pub(crate) fn get_branch_shorthand(&self) -> Option<String> {
if let Ok(head) = self.0.head() {
Some(head.shorthand()?.to_string())
} else {
None
}
self.0
.head()
.ok()
.and_then(|head| head.shorthand().map(|shorthand| shorthand.to_string()))
}

pub(crate) fn create_tag(&self, name: &str) -> Result<()> {
if self.get_diff(true).is_some() {
return Err(anyhow!(
"{}{}",
self.get_statuses()?,
"Cannot create tag : changes needs to be commited".red()
));
}
ensure!(
self.get_diff(true).is_none(),
"{}{}",
self.get_statuses()?,
"Cannot create tag: changes need to be committed".red()
);

let head = self.get_head_commit().unwrap();
self.0
Expand Down
22 changes: 7 additions & 15 deletions src/hook.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,7 @@ impl FromStr for Hook {
type Err = anyhow::Error;

fn from_str(s: &str) -> Result<Self, Self::Err> {
if s.is_empty() {
bail!("hook must not be an empty string")
}
ensure!(!s.is_empty(), "hook must not be an empty string");

let words = shell_words::split(s)?;

Expand All @@ -29,25 +27,19 @@ impl fmt::Display for Hook {

impl Hook {
pub fn insert_version(&mut self, value: &str) {
let entries_with_version = self
.0
.iter()
.map(|entry| entry.replace(VERSION_KEY, value))
.collect();

self.0 = entries_with_version
for entry in &mut self.0 {
*entry = entry.replace(VERSION_KEY, value);
}
}

pub fn run(&self) -> Result<()> {
let (cmd, args) = self.0.split_first().expect("hook must not be empty");

let status = Command::new(&cmd).args(args).status()?;

if !status.success() {
Err(anyhow!("hook failed with status {}", status))
} else {
Ok(())
}
ensure!(status.success(), "hook failed with status {}", status);

Ok(())
}
}

Expand Down
25 changes: 10 additions & 15 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ use semver::Version;
use settings::AuthorSetting;
use std::fmt::Display;
use std::fmt::Formatter;
use std::fmt::Write as FmtWrite;
use std::fs::File;
use std::io::Write;
use std::path::{Path, PathBuf};
Expand Down Expand Up @@ -154,19 +155,15 @@ impl CocoGitto {
}

pub fn get_repo_tag_name(&self) -> Option<String> {
let mut repo_tag_name = String::new();

let repo_path = self.repository.get_repo_dir()?.iter().last()?;
repo_tag_name.push_str(repo_path.to_str()?);
let mut repo_tag_name = repo_path.to_str()?.to_string();

if let Some(branch_shorthand) = self.repository.get_branch_shorthand() {
repo_tag_name.push_str(" on ");
repo_tag_name.push_str(&branch_shorthand);
write!(&mut repo_tag_name, " on {}", branch_shorthand).unwrap();
}

if let Ok(latest_tag) = self.repository.get_latest_tag() {
repo_tag_name.push(' ');
repo_tag_name.push_str(&latest_tag);
write!(&mut repo_tag_name, " {}", latest_tag).unwrap();
};

Some(repo_tag_name)
Expand Down Expand Up @@ -362,9 +359,7 @@ impl CocoGitto {
let statuses = self.repository.get_statuses()?;

// Fail if repo contains un-staged or un-committed changes
if !statuses.0.is_empty() {
return Err(anyhow!("{}", self.repository.get_statuses()?));
}
ensure!(statuses.0.is_empty(), "{}", self.repository.get_statuses()?);

let current_tag = self
.repository
Expand All @@ -385,10 +380,10 @@ impl CocoGitto {
cause_key, comparison
);

return Err(anyhow!(Semver {
bail!(Semver {
level: "SemVer Error".red().to_string(),
cause
}));
});
};

if let Some(pre_release) = pre_release {
Expand All @@ -397,7 +392,7 @@ impl CocoGitto {

let version_str = next_version.to_string();

let origin = if current_tag.as_str() == "0.0.0" {
let origin = if current_tag == "0.0.0" {
self.repository.get_first_commit()?.to_string()
} else {
current_tag
Expand All @@ -409,12 +404,12 @@ impl CocoGitto {
Some(next_version.to_string()),
)?;

let mut writter = ChangelogWriter {
let mut writer = ChangelogWriter {
changelog,
path: self.changelog_path.clone(),
};

writter
writer
.write()
.map_err(|err| anyhow!("Unable to write CHANGELOG.md : {}", err))?;

Expand Down
2 changes: 1 addition & 1 deletion tests/helper.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ pub fn git_commit(message: &str) -> Result<()> {
Command::new("git")
.arg("commit")
.arg("-m")
.arg(&format!("{}", message))
.arg(message)
.stdout(Stdio::inherit())
.stderr(Stdio::inherit())
.output()?;
Expand Down

0 comments on commit 4c74429

Please sign in to comment.