Skip to content

Commit

Permalink
refactor: clean up minor code details
Browse files Browse the repository at this point in the history
  • Loading branch information
tranzystorekk authored and oknozor committed Jul 29, 2021
1 parent 434c222 commit 8b2aafa
Show file tree
Hide file tree
Showing 12 changed files with 59 additions and 79 deletions.
6 changes: 3 additions & 3 deletions src/bin/coco.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,10 +56,10 @@ fn main() -> Result<()> {
}

fn app<'a, 'b>() -> App<'a, 'b> {
let keys = CocoGitto::get_commit_metadata()
let keys: Vec<&str> = CocoGitto::get_commit_metadata()
.iter()
.map(|(commit_type, _)| commit_type.as_ref())
.collect::<Vec<&str>>();
.collect();

App::new("Coco")
.settings(APP_SETTINGS)
Expand All @@ -69,7 +69,7 @@ fn app<'a, 'b>() -> App<'a, 'b> {
.arg(
Arg::with_name("type")
.help("The type of the commit message")
.possible_values(keys.as_slice())
.possible_values(&keys)
.required(true),
)
.arg(
Expand Down
35 changes: 15 additions & 20 deletions src/bin/cog.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ use anyhow::{Context, Result};
use clap::{App, AppSettings, Arg, Shell, SubCommand};

use cocogitto::conventional::commit;
use cocogitto::conventional::commit::CommitType;
use cocogitto::conventional::version::VersionIncrement;
use cocogitto::git::hook::HookKind;
use cocogitto::log::filter::{CommitFilter, CommitFilters};
Expand Down Expand Up @@ -94,10 +93,8 @@ fn main() -> Result<()> {
LOG => {
let cocogitto = CocoGitto::get()?;

let repo_tag_name = match cocogitto.get_repo_tag_name() {
Some(name) => name,
None => "cog log".to_string(),
};
let repo_tag_name = cocogitto.get_repo_tag_name();
let repo_tag_name = repo_tag_name.as_deref().unwrap_or("cog log");

let mut output = Output::builder()
.with_pager_from_env("PAGER")
Expand All @@ -108,21 +105,17 @@ fn main() -> Result<()> {

let mut filters = vec![];
if let Some(commit_types) = subcommand.values_of("type") {
commit_types.for_each(|commit_type| {
filters.push(CommitFilter::Type(CommitType::from(commit_type)));
});
filters.extend(
commit_types.map(|commit_type| CommitFilter::Type(commit_type.into())),
);
}

if let Some(scopes) = subcommand.values_of("scope") {
scopes.for_each(|scope| {
filters.push(CommitFilter::Scope(scope.to_string()));
});
filters.extend(scopes.map(|scope| CommitFilter::Scope(scope.to_string())));
}

if let Some(authors) = subcommand.values_of("author") {
authors.for_each(|author| {
filters.push(CommitFilter::Author(author.to_string()));
});
filters.extend(authors.map(|author| CommitFilter::Author(author.to_string())));
}

if subcommand.is_present("breaking-change") {
Expand All @@ -144,12 +137,14 @@ fn main() -> Result<()> {
CHANGELOG => {
let cocogitto = CocoGitto::get()?;
let subcommand = matches.subcommand_matches(CHANGELOG).unwrap();
let from = subcommand.value_of("from");
let to = subcommand.value_of("to");
let at = subcommand.value_of("at");
let result = match (from, to, at) {
(_, _, Some(at)) => cocogitto.get_colored_changelog_at_tag(at)?,
_ => cocogitto.get_colored_changelog(from, to)?,
let result = match at {
Some(at) => cocogitto.get_colored_changelog_at_tag(at)?,
None => {
let from = subcommand.value_of("from");
let to = subcommand.value_of("to");
cocogitto.get_colored_changelog(from, to)?
}
};
println!("{}", result);
}
Expand Down Expand Up @@ -364,7 +359,7 @@ fn app<'a, 'b>() -> App<'a, 'b> {
.version(env!("CARGO_PKG_VERSION"))
.author("Paul D. <paul.delafosse@protonmail.com>")
.about("A command line tool for the conventional commits and semver specifications")
.subcommands(vec![
.subcommands([
verify_command,
init_subcommand,
check_command,
Expand Down
8 changes: 2 additions & 6 deletions src/conventional/changelog.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,9 +66,7 @@ impl Changelog {
let meta = &COMMITS_METADATA[&commit_type];

write!(&mut out, "\n### {}\n\n", meta.changelog_title).unwrap();
for description in commits {
out.push_str(&description);
}
out.extend(commits);
}

out
Expand All @@ -90,9 +88,7 @@ impl Changelog {
}

fn changelog_template() -> String {
let mut content = Changelog::default_header();
content.push_str(&Changelog::default_footer());
content
[Changelog::default_header(), Changelog::default_footer()].join("")
}
}

Expand Down
10 changes: 5 additions & 5 deletions src/conventional/commit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -280,14 +280,14 @@ impl Commit {
"{}{} ({}) - {}\n\t{} {}\n\t{} {}\n\t{} {}\n",
breaking_change,
message_display,
&self.shorthand().bold(),
self.shorthand().bold(),
elapsed,
author_format,
&self.author,
self.author,
type_format,
&self.message.commit_type,
self.message.commit_type,
scope_format,
&self.message.scope.as_ref().unwrap_or(&"none".to_string()),
self.message.scope.as_deref().unwrap_or("none"),
)
}
}
Expand All @@ -300,7 +300,7 @@ impl fmt::Display for Commit {

impl AsRef<str> for CommitType {
fn as_ref(&self) -> &str {
match &self {
match self {
Feature => "feat",
BugFix => "fix",
Chore => "chore",
Expand Down
2 changes: 1 addition & 1 deletion src/conventional/version.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ impl VersionIncrement {
.map(Result::unwrap)
.collect();

VersionIncrement::get_next_auto_version(current_version, conventional_commits.as_slice())
VersionIncrement::get_next_auto_version(current_version, &conventional_commits)
}

fn get_next_auto_version(current_version: &Version, commits: &[Commit]) -> Result<Version> {
Expand Down
9 changes: 4 additions & 5 deletions src/git/repository.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ impl Repository {

pub(crate) fn add_all(&self) -> Result<()> {
let mut index = self.0.index()?;
index.add_all(["*"].iter(), IndexAddOption::DEFAULT, None)?;
index.add_all(["*"], IndexAddOption::DEFAULT, None)?;
index.write().map_err(|err| anyhow!(err))
}

Expand Down Expand Up @@ -107,10 +107,9 @@ impl Repository {
pub(crate) fn get_head_commit(&self) -> Result<Git2Commit> {
let head_ref = self.0.head();
match head_ref {
Ok(head) => match head.peel_to_commit() {
Ok(head_commit) => Ok(head_commit),
Err(err) => Err(anyhow!("Could not peel head to commit {}", err)),
},
Ok(head) => head
.peel_to_commit()
.map_err(|err| anyhow!("Could not peel head to commit {}", err)),
Err(err) => Err(anyhow!("Repo as not HEAD : {}", err)),
}
}
Expand Down
12 changes: 3 additions & 9 deletions src/hook/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ impl FromStr for Hook {

impl fmt::Display for Hook {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let command = shell_words::join(self.0.iter());
let command = shell_words::join(&self.0);
f.write_str(&command)
}
}
Expand Down Expand Up @@ -75,10 +75,7 @@ mod test {
#[test]
fn parse_valid_string() -> Result<()> {
let hook = Hook::from_str("cargo bump {{version}}")?;
assert_eq!(
&hook.0,
&["cargo".to_string(), "bump".into(), "{{version}}".into()]
);
assert_eq!(&hook.0, &["cargo", "bump", "{{version}}"]);
Ok(())
}

Expand All @@ -87,10 +84,7 @@ mod test {
let mut hook = Hook::from_str("cargo bump {{version}}")?;
hook.insert_version("1.0.0").unwrap();

assert_eq!(
&hook.0,
&["cargo".to_string(), "bump".into(), "1.0.0".into()]
);
assert_eq!(&hook.0, &["cargo", "bump", "1.0.0"]);
Ok(())
}

Expand Down
9 changes: 4 additions & 5 deletions src/hook/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -123,8 +123,7 @@ impl HookExpr {
match token {
Token::Add => version = self.calculate_increment(version)?,
Token::AlphaNumeric(string) => {
let mut output = version.to_string();
output.push_str(&string);
let output = [version.to_string(), string].join("");
return Ok(output);
}
_ => return Err(anyhow!("Unexpected token in hook expression : {:?}", token)),
Expand Down Expand Up @@ -193,7 +192,7 @@ mod tests {
let (range, mut expr) = HookExpr::scan_hook_entry(entry).unwrap();
expr.tokenize();
assert_eq!(range, 5..22);
assert_eq!(expr.tokens, vec![Token::Version, Token::Add, Token::Minor])
assert_eq!(expr.tokens, [Token::Version, Token::Add, Token::Minor])
}

#[test]
Expand All @@ -206,7 +205,7 @@ mod tests {
assert_eq!(range, 5..23);
assert_eq!(
expr.tokens,
vec![Token::Version, Token::Add, Token::Amount(2), Token::Major]
[Token::Version, Token::Add, Token::Amount(2), Token::Major]
)
}

Expand All @@ -220,7 +219,7 @@ mod tests {
assert_eq!(range, 5..27);
assert_eq!(
expr.tokens,
vec![
[
Token::Version,
Token::Add,
Token::Amount(33),
Expand Down
25 changes: 11 additions & 14 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,17 +27,18 @@ use conventional::version::{parse_pre_release, VersionIncrement};
use git::repository::Repository;
use git2::{Oid, RebaseOptions};
use hook::Hook;
use itertools::Itertools;
use log::filter::CommitFilters;
use semver::Version;
use settings::AuthorSetting;
use std::collections::HashMap;
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};
use std::process::{exit, Command, Stdio};
use std::{collections::HashMap, str::FromStr};
use tempfile::TempDir;

pub type CommitsMetadata = HashMap<CommitType, CommitConfig>;
Expand Down Expand Up @@ -223,7 +224,7 @@ impl CocoGitto {
original_commit.id()
);

let mut message_bytes: Vec<u8> = hint.as_bytes().to_vec();
let mut message_bytes: Vec<u8> = hint.clone().into();
message_bytes.extend_from_slice(original_commit.message_bytes());
file.write_all(&message_bytes)?;

Expand All @@ -234,11 +235,11 @@ impl CocoGitto {
.stderr(Stdio::inherit())
.output()?;

let new_message = std::fs::read_to_string(&file_path)?
let new_message: String = std::fs::read_to_string(&file_path)?
.lines()
.filter(|line| !line.starts_with('#'))
.filter(|line| !line.trim().is_empty())
.collect::<String>();
.collect();

rebase.commit(None, &original_commit.committer(), Some(&new_message))?;
match verify(self.repository.get_author().ok(), &new_message) {
Expand Down Expand Up @@ -289,8 +290,6 @@ impl CocoGitto {
.map(|err| err.unwrap_err())
.collect();

use itertools::Itertools;

if errors.is_empty() {
let msg = "No errored commits".green();
println!("{}", msg);
Expand Down Expand Up @@ -467,9 +466,8 @@ impl CocoGitto {
.repository
.0
.find_commit(to)?
.parent(0)
.parent_id(0)
.expect("Unexpected error : Unable to get parent commit")
.id()
.to_string();
let mut changelog = self.get_changelog(
Some(from.as_str()),
Expand Down Expand Up @@ -515,7 +513,7 @@ impl CocoGitto {
match Commit::from_git_commit(&commit) {
Ok(commit) => commits.push(commit),
Err(err) => {
let err = format!("{}", err).red();
let err = err.to_string().red();
eprintln!("{}", err);
}
};
Expand Down Expand Up @@ -577,18 +575,17 @@ impl CocoGitto {
) -> Result<()> {
let settings = Settings::get(&self.repository, hooks_config)?;

let hooks = settings
let hooks: Vec<Hook> = settings
.get_hooks(hook_type)
.iter()
.map(String::as_str)
.map(Hook::from_str)
.map(|s| s.parse())
.enumerate()
.map(|(idx, result)| result.context(format!("Cannot parse hook at index {}", idx)))
.collect::<Result<Vec<Hook>>>()?;
.try_collect()?;

for mut hook in hooks {
hook.insert_version(next_version)?;
hook.run().context(format!("{}", hook))?;
hook.run().context(hook.to_string())?;
}

Ok(())
Expand Down
Loading

0 comments on commit 8b2aafa

Please sign in to comment.