Skip to content

Commit 3cdbf14

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 <prajwalnadig21@gmail.com>
1 parent 7528644 commit 3cdbf14

1 file changed

Lines changed: 14 additions & 22 deletions

File tree

src/handlers/check_commits/no_mentions.rs

Lines changed: 14 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,29 @@
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(
20+
String::from(
21+
r"There are username mentions (such as `@user`) in the commit messages of the following commits.
22+
*Please remove the mentions to avoid spamming these users.*
23+
",
24+
) + &mentions_commits,
25+
)
3226
}
33-
34-
warning
3527
}
3628

3729
#[test]
@@ -69,10 +61,10 @@ fn test_mentions_in_commits() {
6961
assert_eq!(
7062
mentions_in_commits(&NoMentionsConfig {}, &commits),
7163
Some(
72-
r#"There are username mentions (such as `@user`) in the commit messages of the following commits.
64+
r"There are username mentions (such as `@user`) in the commit messages of the following commits.
7365
*Please remove the mentions to avoid spamming these users.*
7466
- d7daa17bc97df9377640b0d33cbd0bbeed703c3a
75-
"#.to_string()
67+
".to_string()
7668
)
7769
);
7870
}

0 commit comments

Comments
 (0)