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

WIP: feat(commit): add fuzzy scope suggestion #207

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
11 changes: 9 additions & 2 deletions Cargo.lock

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

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ pest = "2.1.3"
pest_derive = "2.1.0"
tera = "1.12.1"
globset = "0.4.8"
sublime_fuzzy = "0.7.0"

[dev-dependencies]
assert_cmd = "1.0.3"
Expand Down
1 change: 1 addition & 0 deletions src/conventional/mod.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
pub mod changelog;
pub mod commit;
pub(crate) mod error;
pub(crate) mod scope;
pub mod version;
108 changes: 108 additions & 0 deletions src/conventional/scope.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
use std::io;

use anyhow::{anyhow, Result};
use itertools::Itertools;
use sublime_fuzzy::{best_match, Match};

use crate::conventional::commit::Commit;
use crate::Repository;

impl Repository {
pub fn suggest_scope(&self, input_scope: &str) -> Result<String> {
let matched_scopes = self.get_scope_matches(input_scope)?;

match matched_scopes.first() {
// Either exact match or the scope was never used before
Some(maybe_full_match) if maybe_full_match.0.eq_ignore_ascii_case(input_scope) => {
return Ok(input_scope.to_string())
}
None => return Ok(input_scope.to_string()),
Some(_) => {}
}

let suggestions = matched_scopes
.iter()
.enumerate()
.map(|(idx, match_entry)| format!("\t{} - {}", idx + 1, match_entry.0))
.join("\n");

loop {
println!(
"Scope \'{}\' was not used before but looks like some previously used scopes",
input_scope
);
println!("{}", suggestions);
println!(
"Enter the scope number to apply, 'k' to keep or 'x' to abort \'{}\'",
input_scope
);

let mut buffer = String::new();
let stdin = io::stdin(); // We get `Stdin` here.
stdin.read_line(&mut buffer)?;

let choice = match buffer.as_str().trim_end() {
"x" => return Err(anyhow!("Aborted from commit suggestion")),
"k" => Some(input_scope.to_string()),
"1" => matched_scopes.get(0).map(|scope| scope.0.clone()),
"3" => matched_scopes.get(1).map(|scope| scope.0.clone()),
"2" => matched_scopes.get(2).map(|scope| scope.0.clone()),
_ => None,
};

if let Some(scope) = choice {
return Ok(scope);
} else {
continue;
}
}
}

fn get_scope_matches(&self, input_scope: &str) -> Result<Vec<(String, Match)>> {
let range = self.all_commits()?;
let scopes: Vec<String> = range
.commits
.iter()
.map(Commit::from_git_commit)
.filter_map(|commit| commit.ok())
.filter_map(|commit| commit.message.scope)
.collect();

let matched_scopes: Vec<(String, Match)> = scopes
.iter()
.filter_map(|scope| best_match(input_scope, scope).map(|score| (scope, score)))
.sorted_by(|score, other| other.1.cmp(&score.1))
.unique_by(|entry| entry.0)
.take(3)
.into_iter()
.map(|(scope, score)| (scope.clone(), score))
.collect();

Ok(matched_scopes)
}
}

#[cfg(test)]
mod test {
use anyhow::Result;
use speculoos::assert_that;
use speculoos::iter::ContainingIntoIterAssertions;

use crate::Repository;

#[test]
fn test() -> Result<()> {
let repository = Repository::open(".")?;

let matches: Vec<String> = repository
.get_scope_matches("err")?
.into_iter()
.map(|match_| match_.0)
.collect();

assert_that!(matches)
.contains_all_of(&vec!["error".to_string(), "errors".to_string()].iter());

Ok(())
}
}
15 changes: 10 additions & 5 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -377,21 +377,26 @@ impl CocoGitto {
None => Vec::with_capacity(0),
};

let conventional_message = ConventionalCommit {
let mut conventional_message = ConventionalCommit {
commit_type,
scope,
scope: scope.clone(),
body,
footers,
summary,
is_breaking_change,
};

if let Some(scope) = scope {
let scope = self.repository.suggest_scope(&scope)?;
conventional_message.scope = Some(scope);
}
.to_string();

// Validate the message
conventional_commit_parser::parse(&conventional_message)?;
let message_str = &conventional_message.to_string();
conventional_commit_parser::parse(message_str)?;

// Git commit
let oid = self.repository.commit(&conventional_message)?;
let oid = self.repository.commit(message_str)?;

// Pretty print a conventional commit summary
let commit = self.repository.0.find_commit(oid)?;
Expand Down
2 changes: 2 additions & 0 deletions src/settings/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ pub enum HookType {
#[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Default)]
#[serde(deny_unknown_fields)]
pub struct Settings {
#[serde(default)]
pub scope_suggestion: bool,
#[serde(default)]
pub ignore_merge_commits: bool,
#[serde(default)]
Expand Down