Skip to content

Commit f7766ac

Browse files
committed
Add alias for compound labels
Configure relabel command aliases from the `triagebot.toml`. When a valid alias is parsed, it will be replaced with the labels configured. Example configuration: ``` [relabel.cmd-alias] add-labels = ["Foo", "Bar"] rem-labels = ["Baz"] ``` The command `@rustbot label cmd-alias` translates to: ``` @rustbot label +Foo +Bar -Baz ``` The command `@rustbot label -cmd-alias` translates to: ``` @rustbot label +Baz -Foo -Bar ``` Note: self-canceling labels will be omitted. The command `@rustbot label cmd-alias +Baz` translates to: ``` @rustbot label +Foo +Bar ``` Signed-off-by: apiraino <[email protected]>
1 parent 842e2bd commit f7766ac

File tree

4 files changed

+197
-13
lines changed

4 files changed

+197
-13
lines changed

parser/src/command/relabel.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,7 @@ fn delta_empty() {
102102
}
103103

104104
impl RelabelCommand {
105+
/// Parse and validate command tokens
105106
pub fn parse<'a>(input: &mut Tokenizer<'a>) -> Result<Option<Self>, Error<'a>> {
106107
let mut toks = input.clone();
107108

src/config.rs

Lines changed: 180 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
use crate::changelogs::ChangelogFormat;
22
use crate::github::{GithubClient, Repository};
3+
use parser::command::relabel::{Label, LabelDelta, RelabelCommand};
34
use std::collections::{HashMap, HashSet};
45
use std::fmt;
56
use std::sync::{Arc, LazyLock, RwLock};
@@ -250,10 +251,66 @@ pub(crate) struct MentionsEntryConfig {
250251

251252
#[derive(PartialEq, Eq, Debug, serde::Deserialize)]
252253
#[serde(rename_all = "kebab-case")]
253-
#[serde(deny_unknown_fields)]
254254
pub(crate) struct RelabelConfig {
255255
#[serde(default)]
256256
pub(crate) allow_unauthenticated: Vec<String>,
257+
// alias identifier -> labels
258+
#[serde(flatten)]
259+
pub(crate) aliases: HashMap<String, RelabelAliasConfig>,
260+
}
261+
262+
impl RelabelConfig {
263+
pub(crate) fn retrieve_command_from_alias(&self, input: RelabelCommand) -> RelabelCommand {
264+
let mut deltas = vec![];
265+
// parse all tokens: if one matches an alias, extract the labels
266+
// else, it will assumed to be a label
267+
for tk in input.0.into_iter() {
268+
if !self.aliases.is_empty() {
269+
let name = tk.label() as &str;
270+
if let Some(alias) = self.aliases.get(name) {
271+
let cmd = alias.to_command(matches!(tk, LabelDelta::Remove(_)));
272+
deltas.extend(cmd.0);
273+
} else {
274+
deltas.push(tk);
275+
}
276+
} else {
277+
deltas.push(tk);
278+
}
279+
}
280+
RelabelCommand(deltas)
281+
}
282+
}
283+
284+
#[derive(Default, PartialEq, Eq, Debug, serde::Deserialize)]
285+
#[serde(rename_all = "kebab-case")]
286+
#[serde(deny_unknown_fields)]
287+
pub(crate) struct RelabelAliasConfig {
288+
/// Labels to be added
289+
pub(crate) add_labels: Vec<String>,
290+
/// Labels to be removed
291+
pub(crate) rem_labels: Vec<String>,
292+
}
293+
294+
impl RelabelAliasConfig {
295+
/// Translate a RelabelAliasConfig into a RelabelCommand for GitHub consumption
296+
fn to_command(&self, inverted: bool) -> RelabelCommand {
297+
let mut deltas = Vec::new();
298+
let mut add_labels = &self.add_labels;
299+
let mut rem_labels = &self.rem_labels;
300+
301+
// if the polarity of the alias is inverted, swap labels before parsing the command
302+
if inverted {
303+
std::mem::swap(&mut add_labels, &mut rem_labels);
304+
}
305+
306+
for l in add_labels.iter() {
307+
deltas.push(LabelDelta::Add(Label(l.into())));
308+
}
309+
for l in rem_labels.iter() {
310+
deltas.push(LabelDelta::Remove(Label(l.into())));
311+
}
312+
RelabelCommand(deltas)
313+
}
257314
}
258315

259316
#[derive(PartialEq, Eq, Debug, serde::Deserialize)]
@@ -761,11 +818,11 @@ mod tests {
761818
762819
[mentions."src/"]
763820
cc = ["@someone"]
764-
821+
765822
[mentions."target/"]
766823
message = "This is a message."
767824
cc = ["@someone"]
768-
825+
769826
[mentions."#[rustc_attr]"]
770827
type = "content"
771828
message = "This is a message."
@@ -835,6 +892,7 @@ mod tests {
835892
Config {
836893
relabel: Some(RelabelConfig {
837894
allow_unauthenticated: vec!["C-*".into()],
895+
aliases: HashMap::new()
838896
}),
839897
assign: Some(AssignConfig {
840898
warn_non_default_branch: WarnNonDefaultBranchConfig::Simple(false),
@@ -1033,6 +1091,93 @@ mod tests {
10331091
);
10341092
}
10351093

1094+
#[test]
1095+
fn relabel_alias_config() {
1096+
let config = r#"
1097+
[relabel.to-stable]
1098+
add-labels = ["regression-from-stable-to-stable"]
1099+
rem-labels = ["regression-from-stable-to-beta", "regression-from-stable-to-nightly"]
1100+
"#;
1101+
let config = toml::from_str::<Config>(&config).unwrap();
1102+
1103+
let mut relabel_configs = HashMap::new();
1104+
relabel_configs.insert(
1105+
"to-stable".into(),
1106+
RelabelAliasConfig {
1107+
add_labels: vec!["regression-from-stable-to-stable".to_string()],
1108+
rem_labels: vec![
1109+
"regression-from-stable-to-beta".to_string(),
1110+
"regression-from-stable-to-nightly".to_string(),
1111+
],
1112+
},
1113+
);
1114+
1115+
let expected_cfg = RelabelConfig {
1116+
allow_unauthenticated: vec![],
1117+
aliases: relabel_configs,
1118+
};
1119+
1120+
assert_eq!(config.relabel, Some(expected_cfg));
1121+
}
1122+
1123+
#[test]
1124+
fn relabel_alias() {
1125+
// [relabel.my-alias]
1126+
// add-labels = ["Alpha"]
1127+
// rem-labels = ["Bravo", "Charlie"]
1128+
let relabel_cfg = RelabelConfig {
1129+
allow_unauthenticated: vec![],
1130+
aliases: HashMap::from([(
1131+
"my-alias".to_string(),
1132+
RelabelAliasConfig {
1133+
add_labels: vec!["Alpha".to_string()],
1134+
rem_labels: vec!["Bravo".to_string(), "Charlie".to_string()],
1135+
},
1136+
)]),
1137+
};
1138+
1139+
// @triagebot label my-alias
1140+
let deltas = vec![LabelDelta::Add(Label("my-alias".into()))];
1141+
let new_input = relabel_cfg.retrieve_command_from_alias(RelabelCommand(deltas));
1142+
assert_eq!(
1143+
new_input,
1144+
RelabelCommand(vec![
1145+
LabelDelta::Add(Label("Alpha".into())),
1146+
LabelDelta::Remove(Label("Bravo".into())),
1147+
LabelDelta::Remove(Label("Charlie".into())),
1148+
])
1149+
);
1150+
1151+
// @triagebot label -my-alias
1152+
let deltas = vec![LabelDelta::Remove(Label("my-alias".into()))];
1153+
let new_input = relabel_cfg.retrieve_command_from_alias(RelabelCommand(deltas));
1154+
assert_eq!(
1155+
new_input,
1156+
RelabelCommand(vec![
1157+
LabelDelta::Add(Label("Bravo".into())),
1158+
LabelDelta::Add(Label("Charlie".into())),
1159+
LabelDelta::Remove(Label("Alpha".into())),
1160+
])
1161+
);
1162+
}
1163+
1164+
#[test]
1165+
fn relabel_alias_empty_config() {
1166+
// empty alias config
1167+
let relabel_cfg = RelabelConfig {
1168+
allow_unauthenticated: vec![],
1169+
aliases: HashMap::new(),
1170+
};
1171+
1172+
// @triagebot label T-compiler
1173+
let deltas = vec![LabelDelta::Add(Label("T-compiler".into()))];
1174+
let new_input = relabel_cfg.retrieve_command_from_alias(RelabelCommand(deltas));
1175+
assert_eq!(
1176+
new_input,
1177+
RelabelCommand(vec![LabelDelta::Add(Label("T-compiler".into())),])
1178+
);
1179+
}
1180+
10361181
#[test]
10371182
fn issue_links_uncanonicalized() {
10381183
let config = r#"
@@ -1093,4 +1238,36 @@ Multi text body with ${mcp_issue} and ${mcp_title}
10931238
})
10941239
);
10951240
}
1241+
1242+
#[test]
1243+
fn relabel_new_config() {
1244+
let config = r#"
1245+
[relabel]
1246+
allow-unauthenticated = ["ABCD-*"]
1247+
1248+
[relabel.to-stable]
1249+
add-labels = ["regression-from-stable-to-stable"]
1250+
rem-labels = ["regression-from-stable-to-beta", "regression-from-stable-to-nightly"]
1251+
"#;
1252+
let config = toml::from_str::<Config>(&config).unwrap();
1253+
1254+
let mut relabel_configs = HashMap::new();
1255+
relabel_configs.insert(
1256+
"to-stable".into(),
1257+
RelabelAliasConfig {
1258+
add_labels: vec!["regression-from-stable-to-stable".to_string()],
1259+
rem_labels: vec![
1260+
"regression-from-stable-to-beta".to_string(),
1261+
"regression-from-stable-to-nightly".to_string(),
1262+
],
1263+
},
1264+
);
1265+
1266+
let expected_cfg = RelabelConfig {
1267+
allow_unauthenticated: vec!["ABCD-*".to_string()],
1268+
aliases: relabel_configs,
1269+
};
1270+
1271+
assert_eq!(config.relabel, Some(expected_cfg));
1272+
}
10961273
}

src/github.rs

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1338,9 +1338,6 @@ impl IssuesEvent {
13381338
}
13391339
}
13401340

1341-
#[derive(Debug, serde::Deserialize)]
1342-
struct PullRequestEventFields {}
1343-
13441341
#[derive(Debug, serde::Deserialize)]
13451342
pub struct WorkflowRunJob {
13461343
pub name: String,

src/handlers/relabel.rs

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
1-
//! Purpose: Allow any user to modify issue labels on GitHub via comments.
1+
//! Purpose: Allow any user to modify labels on GitHub issues and pull requests via comments.
22
//!
3-
//! Labels are checked against the labels in the project; the bot does not support creating new
4-
//! labels.
3+
//! Labels are checked against the existing set in the git repository; the bot does not support
4+
//! creating new labels.
55
//!
66
//! Parsing is done in the `parser::command::relabel` module.
77
//!
@@ -27,13 +27,17 @@ pub(super) async fn handle_command(
2727
input: RelabelCommand,
2828
) -> anyhow::Result<()> {
2929
let Some(issue) = event.issue() else {
30-
return user_error!("Can only add and remove labels on an issue");
30+
return user_error!("Can only add and remove labels on issues and pull requests");
3131
};
3232

33+
// If the input matches a valid alias, read the [relabel] config.
34+
// if any alias matches, extract the alias config (RelabelAliasConfig) and build a new RelabelCommand.
35+
let new_input = config.retrieve_command_from_alias(input);
36+
3337
// Check label authorization for the current user
34-
for delta in &input.0 {
38+
for delta in &new_input.0 {
3539
let name = delta.label() as &str;
36-
let err = match check_filter(name, config, is_member(event.user(), &ctx.team).await) {
40+
let err = match check_filter(name, config, is_member(&event.user(), &ctx.team).await) {
3741
Ok(CheckFilterResult::Allow) => None,
3842
Ok(CheckFilterResult::Deny) => {
3943
Some(format!("Label {name} can only be set by Rust team members"))
@@ -44,14 +48,15 @@ pub(super) async fn handle_command(
4448
)),
4549
Err(err) => Some(err),
4650
};
51+
4752
if let Some(err) = err {
4853
// bail-out and inform the user why
4954
return user_error!(err);
5055
}
5156
}
5257

5358
// Compute the labels to add and remove
54-
let (to_add, to_remove) = compute_label_deltas(&input.0);
59+
let (to_add, to_remove) = compute_label_deltas(&new_input.0);
5560

5661
// Add labels
5762
if let Err(e) = issue.add_labels(&ctx.github, to_add.clone()).await {
@@ -103,6 +108,8 @@ enum CheckFilterResult {
103108
DenyUnknown,
104109
}
105110

111+
/// Check if the team member is allowed to apply labels
112+
/// configured in `allow_unauthenticated`
106113
fn check_filter(
107114
label: &str,
108115
config: &RelabelConfig,
@@ -194,6 +201,7 @@ fn compute_label_deltas(deltas: &[LabelDelta]) -> (Vec<Label>, Vec<Label>) {
194201
#[cfg(test)]
195202
mod tests {
196203
use parser::command::relabel::{Label, LabelDelta};
204+
use std::collections::HashMap;
197205

198206
use super::{
199207
CheckFilterResult, MatchPatternResult, TeamMembership, check_filter, compute_label_deltas,
@@ -232,6 +240,7 @@ mod tests {
232240
($($member:ident { $($label:expr => $res:ident,)* })*) => {
233241
let config = RelabelConfig {
234242
allow_unauthenticated: vec!["T-*".into(), "I-*".into(), "!I-*nominated".into()],
243+
aliases: HashMap::new()
235244
};
236245
$($(assert_eq!(
237246
check_filter($label, &config, TeamMembership::$member),

0 commit comments

Comments
 (0)