use std::collections::HashMap;
pub struct SemanticSimilarity {
}
impl SemanticSimilarity {
pub fn new() -> Self {
Self {}
}
}
impl Default for SemanticSimilarity {
fn default() -> Self {
Self::new()
}
}
impl SemanticSimilarity {
pub fn calculate_similarities(
&self,
change_keywords: &[String],
historical_messages: &[String],
) -> Vec<(usize, f32)> {
let mut similarities = Vec::new();
for (idx, message) in historical_messages.iter().enumerate() {
let similarity = self.calculate_message_similarity(change_keywords, message);
similarities.push((idx, similarity));
}
similarities.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));
similarities
}
#[allow(clippy::cast_precision_loss)]
#[allow(clippy::as_conversions)]
#[allow(clippy::unused_self)]
fn calculate_message_similarity(&self, keywords: &[String], message: &str) -> f32 {
if keywords.is_empty() {
return 0.0;
}
let message_lower = message.to_lowercase();
let mut matches = 0;
let mut total_weight = 0.0;
for keyword in keywords {
let weight = Self::get_keyword_weight(keyword);
total_weight += weight;
if message_lower.contains(keyword) {
matches += 1;
}
}
if total_weight == 0.0 {
0.0
} else {
(matches as f32) / (keywords.len() as f32)
}
}
fn get_keyword_weight(keyword: &str) -> f32 {
if keyword.contains('.') || keyword.contains('/') {
2.0
} else {
1.0
}
}
pub fn extract_keywords(
&self,
staged_files: &[crate::core::context::StagedFile],
) -> Vec<String> {
let mut keywords = Vec::new();
let mut keyword_counts = HashMap::new();
for file in staged_files {
Self::extract_from_path(&file.path, &mut keywords, &mut keyword_counts);
if let Some(content) = &file.content {
Self::extract_from_content(content, &mut keywords, &mut keyword_counts);
}
Self::extract_from_diff(&file.diff, &mut keywords, &mut keyword_counts);
}
let mut sorted_keywords: Vec<_> = keyword_counts.into_iter().collect();
sorted_keywords.sort_by(|a, b| b.1.cmp(&a.1));
sorted_keywords
.into_iter()
.take(20) .map(|(k, _)| k)
.collect()
}
fn extract_from_path(
path: &str,
keywords: &mut Vec<String>,
counts: &mut HashMap<String, usize>,
) {
let file_name = path.split('/').next_back().unwrap_or(path);
let parts: Vec<&str> = file_name.split('.').collect();
if let Some(name_without_ext) = parts.first() {
let words: Vec<String> = name_without_ext
.split('_')
.flat_map(split_camel_case)
.map(|s| s.to_lowercase())
.filter(|s| s.len() > 2) .collect();
for word in words {
if !word.is_empty() {
*counts.entry(word.clone()).or_insert(0) += 2; if !keywords.contains(&word) {
keywords.push(word);
}
}
}
}
}
fn extract_from_content(
content: &str,
keywords: &mut Vec<String>,
counts: &mut HashMap<String, usize>,
) {
let content_words: Vec<String> = content
.split_whitespace()
.take(100) .filter(|word| word.len() > 3 && word.chars().all(|c| c.is_alphanumeric() || c == '_'))
.map(str::to_lowercase)
.collect();
for word in content_words {
*counts.entry(word.clone()).or_insert(0) += 1;
if !keywords.contains(&word) {
keywords.push(word);
}
}
}
fn extract_from_diff(
diff: &str,
keywords: &mut Vec<String>,
counts: &mut HashMap<String, usize>,
) {
let diff_words: Vec<String> = diff
.lines()
.filter(|line| line.starts_with('+') || line.starts_with('-'))
.flat_map(|line| line.split_whitespace())
.filter(|word| word.len() > 3 && word.chars().all(|c| c.is_alphanumeric() || c == '_'))
.map(str::to_lowercase)
.take(50) .collect();
for word in diff_words {
*counts.entry(word.clone()).or_insert(0) += 1;
if !keywords.contains(&word) {
keywords.push(word);
}
}
}
}
fn split_camel_case(s: &str) -> Vec<String> {
let mut words = Vec::new();
let mut current_word = String::new();
let chars: Vec<char> = s.chars().collect();
let mut i = 0;
while i < chars.len() {
if chars[i].is_uppercase() {
if !current_word.is_empty() {
words.push(current_word);
current_word = String::new();
}
let mut j = i;
while j < chars.len() && chars[j].is_uppercase() {
j += 1;
}
if j > i + 1 && (j == chars.len() || (j < chars.len() && chars[j].is_lowercase())) {
if j - i > 1 {
words.push(chars[i..j - 1].iter().collect());
current_word.push(chars[j - 1]);
} else {
current_word.push(chars[i]);
}
i = j;
} else {
current_word.push(chars[i]);
i += 1;
}
} else {
current_word.push(chars[i]);
i += 1;
}
}
if !current_word.is_empty() {
words.push(current_word);
}
words
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_split_camel_case() {
assert_eq!(split_camel_case("camelCase"), vec!["camel", "Case"]);
assert_eq!(
split_camel_case("XMLHttpRequest"),
vec!["XML", "Http", "Request"]
);
assert_eq!(split_camel_case("simple"), vec!["simple"]);
}
#[test]
fn test_semantic_similarity() {
let similarity = SemanticSimilarity::new();
let keywords = vec!["test".to_string(), "function".to_string()];
let message = "add test function".to_string();
let score = similarity.calculate_message_similarity(&keywords, &message);
assert!(score > 0.0);
}
}