Skip to content

Commit 53435a7

Browse files
committed
refactor: reduce allocations in no_mentions
This patch adds the below optimisations: - Allocate a single formatted string for the list of commits instead of a mutable vector which may possibly be resized at runtime. - Use `String::from` instead of `format!` for the warning string. - Eliminate the `mentions_in_commits_warn` function which moved the vector in the parameter and allocated a new string. Signed-off-by: Prajwal S N <[email protected]>
1 parent 7528644 commit 53435a7

File tree

1 file changed

+12
-22
lines changed

1 file changed

+12
-22
lines changed

src/handlers/check_commits/no_mentions.rs

+12-22
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,27 @@
11
//! Purpose: When opening a PR, or pushing new changes, check for github mentions
22
//! in commits and notify the user of our no-mentions in commits policy.
33
4-
use std::fmt::Write;
5-
64
use crate::{config::NoMentionsConfig, github::GithubCommit};
75

86
pub(super) fn mentions_in_commits(
97
_conf: &NoMentionsConfig,
108
commits: &[GithubCommit],
119
) -> Option<String> {
12-
let mut mentions_commits = Vec::new();
13-
14-
for commit in commits {
15-
if !parser::get_mentions(&commit.commit.message).is_empty() {
16-
mentions_commits.push(&*commit.sha);
17-
}
18-
}
10+
let mentions_commits = commits
11+
.into_iter()
12+
.filter(|c| !parser::get_mentions(&c.commit.message).is_empty())
13+
.map(|c| format!(" - {}\n", c.sha))
14+
.collect::<String>();
1915

2016
if mentions_commits.is_empty() {
2117
None
2218
} else {
23-
Some(mentions_in_commits_warn(mentions_commits))
24-
}
25-
}
26-
27-
fn mentions_in_commits_warn(commits: Vec<&str>) -> String {
28-
let mut warning = format!("There are username mentions (such as `@user`) in the commit messages of the following commits.\n *Please remove the mentions to avoid spamming these users.*\n");
29-
30-
for commit in commits {
31-
let _ = writeln!(warning, " - {commit}");
19+
Some(format!(
20+
r"There are username mentions (such as `@user`) in the commit messages of the following commits.
21+
*Please remove the mentions to avoid spamming these users.*
22+
{mentions_commits}",
23+
))
3224
}
33-
34-
warning
3525
}
3626

3727
#[test]
@@ -69,10 +59,10 @@ fn test_mentions_in_commits() {
6959
assert_eq!(
7060
mentions_in_commits(&NoMentionsConfig {}, &commits),
7161
Some(
72-
r#"There are username mentions (such as `@user`) in the commit messages of the following commits.
62+
r"There are username mentions (such as `@user`) in the commit messages of the following commits.
7363
*Please remove the mentions to avoid spamming these users.*
7464
- d7daa17bc97df9377640b0d33cbd0bbeed703c3a
75-
"#.to_string()
65+
".to_string()
7666
)
7767
);
7868
}

0 commit comments

Comments
 (0)