-
Notifications
You must be signed in to change notification settings - Fork 108
Expand file tree
/
Copy pathrelabel.rs
More file actions
330 lines (298 loc) · 9.83 KB
/
Copy pathrelabel.rs
File metadata and controls
330 lines (298 loc) · 9.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
//! Purpose: Allow any user to modify labels on GitHub issues and pull requests via comments.
//!
//! Labels are checked against the existing set in the git repository; the bot does not support
//! creating new labels.
//!
//! Parsing is done in the `parser::command::relabel` module.
//!
//! If the command was successful, there will be no feedback beyond the label change to reduce
//! notification noise.
use std::collections::BTreeSet;
use crate::errors::user_error;
use crate::github::Label;
use crate::team_data::TeamClient;
use crate::{
config::RelabelConfig,
github::{self, Event},
handlers::Context,
};
use anyhow::Context as _;
use parser::command::relabel::{LabelDelta, RelabelCommand};
use tracing as log;
pub(super) async fn handle_command(
ctx: &Context,
config: &RelabelConfig,
event: &Event,
input: RelabelCommand,
) -> anyhow::Result<()> {
let Some(issue) = event.issue() else {
return user_error!("Can only add and remove labels on issues and pull requests");
};
// If the input matches a valid alias, read the [relabel] config.
// if any alias matches, extract the alias config (RelabelAliasConfig) and build a new RelabelCommand.
let new_input = config.retrieve_command_from_alias(input);
// Check label authorization for the current user
for delta in &new_input.0 {
let name = delta.label() as &str;
let err = match check_filter(name, config, is_member(&event.user(), &ctx.team).await) {
Ok(CheckFilterResult::Allow) => None,
Ok(CheckFilterResult::Deny) => {
Some(format!("Label {name} can only be set by Rust team members"))
}
Ok(CheckFilterResult::DenyUnknown) => Some(format!(
"Label {name} can only be set by Rust team members;\
we were unable to check if you are a team member."
)),
Err(err) => Some(err),
};
if let Some(err) = err {
// bail-out and inform the user why
return user_error!(err);
}
}
// Compute the labels to add and remove
let (to_add, to_remove) = compute_label_deltas(&new_input.0);
// Add labels
issue
.add_labels(&ctx.github, to_add.clone())
.await
.context("failed to add labels to the issue")?;
// Remove labels
issue
.remove_labels(&ctx.github, to_remove.clone())
.await
.context("failed to remove labels from the issue")?;
Ok(())
}
#[derive(Debug, PartialEq, Eq)]
enum TeamMembership {
Member,
Outsider,
Unknown,
}
async fn is_member(user: &github::GitHubUser, team: &TeamClient) -> TeamMembership {
match team.is_team_member(&user.login).await {
Ok(true) => TeamMembership::Member,
Ok(false) => TeamMembership::Outsider,
Err(err) => {
log::error!("failed to check team membership: {err:?}");
TeamMembership::Unknown
}
}
}
#[cfg_attr(test, derive(Debug, PartialEq, Eq))]
enum CheckFilterResult {
Allow,
Deny,
DenyUnknown,
}
/// Check if the team member is allowed to apply labels
/// configured in `allow_unauthenticated`
fn check_filter(
label: &str,
config: &RelabelConfig,
is_member: TeamMembership,
) -> Result<CheckFilterResult, String> {
if is_member == TeamMembership::Member {
return Ok(CheckFilterResult::Allow);
}
let mut matched = false;
for pattern in &config.allow_unauthenticated {
match match_pattern(pattern, label) {
Ok(MatchPatternResult::Allow) => matched = true,
Ok(MatchPatternResult::Deny) => {
// An explicit deny overrides any allowed pattern
matched = false;
break;
}
Ok(MatchPatternResult::NoMatch) => {}
Err(err) => {
log::error!("failed to match pattern {pattern}: {err}");
return Err(format!("failed to match pattern {pattern}"));
}
}
}
if matched {
Ok(CheckFilterResult::Allow)
} else if is_member == TeamMembership::Outsider {
Ok(CheckFilterResult::Deny)
} else {
Ok(CheckFilterResult::DenyUnknown)
}
}
#[cfg_attr(test, derive(Debug, PartialEq, Eq))]
enum MatchPatternResult {
Allow,
Deny,
NoMatch,
}
fn match_pattern(pattern: &str, label: &str) -> anyhow::Result<MatchPatternResult> {
let (pattern, inverse) = if let Some(pat) = pattern.strip_prefix('!') {
(pat, true)
} else {
(pattern, false)
};
let glob = globset::GlobBuilder::new(pattern)
.case_insensitive(true)
.build()?;
Ok(match (glob.compile_matcher().is_match(label), inverse) {
(true, false) => MatchPatternResult::Allow,
(true, true) => MatchPatternResult::Deny,
(false, _) => MatchPatternResult::NoMatch,
})
}
fn compute_label_deltas(deltas: &[LabelDelta]) -> (Vec<Label>, Vec<Label>) {
let mut add = BTreeSet::new();
let mut remove = BTreeSet::new();
for delta in deltas {
match delta {
LabelDelta::Add(label) => {
let label = Label {
name: label.to_string(),
};
if !remove.remove(&label) {
add.insert(label);
}
}
LabelDelta::Remove(label) => {
let label = Label {
name: label.to_string(),
};
if !add.remove(&label) {
remove.insert(label);
}
}
}
}
(add.into_iter().collect(), remove.into_iter().collect())
}
#[cfg(test)]
mod tests {
use parser::command::relabel::{Label, LabelDelta};
use std::collections::HashMap;
use super::{
CheckFilterResult, MatchPatternResult, TeamMembership, check_filter, compute_label_deltas,
match_pattern,
};
use crate::config::RelabelConfig;
use crate::github::Label as GitHubLabel;
use crate::tests::github::issue;
#[test]
fn test_match_pattern() -> anyhow::Result<()> {
assert_eq!(
match_pattern("I-*", "I-nominated")?,
MatchPatternResult::Allow
);
assert_eq!(
match_pattern("i-*", "I-nominated")?,
MatchPatternResult::Allow
);
assert_eq!(
match_pattern("!I-no*", "I-nominated")?,
MatchPatternResult::Deny
);
assert_eq!(
match_pattern("I-*", "T-infra")?,
MatchPatternResult::NoMatch
);
assert_eq!(
match_pattern("!I-no*", "T-infra")?,
MatchPatternResult::NoMatch
);
Ok(())
}
#[test]
fn test_check_filter() -> anyhow::Result<()> {
macro_rules! t {
($($member:ident { $($label:expr => $res:ident,)* })*) => {
let config = RelabelConfig {
allow_unauthenticated: vec!["T-*".into(), "I-*".into(), "!I-*nominated".into()],
aliases: HashMap::new()
};
$($(assert_eq!(
check_filter($label, &config, TeamMembership::$member),
Ok(CheckFilterResult::$res)
);)*)*
}
}
t! {
Member {
"T-release" => Allow,
"I-slow" => Allow,
"I-lang-nominated" => Allow,
"I-nominated" => Allow,
"A-spurious" => Allow,
}
Outsider {
"T-release" => Allow,
"I-slow" => Allow,
"I-lang-nominated" => Deny,
"I-nominated" => Deny,
"A-spurious" => Deny,
}
Unknown {
"T-release" => Allow,
"I-slow" => Allow,
"I-lang-nominated" => DenyUnknown,
"I-nominated" => DenyUnknown,
"A-spurious" => DenyUnknown,
}
}
Ok(())
}
#[test]
fn test_compute_label_deltas() {
let mut deltas = vec![
LabelDelta::Add(Label("I-nominated".to_string())),
LabelDelta::Add(Label("I-nominated".to_string())),
LabelDelta::Add(Label("I-lang-nominated".to_string())),
LabelDelta::Add(Label("I-libs-nominated".to_string())),
LabelDelta::Remove(Label("I-lang-nominated".to_string())),
];
assert_eq!(
compute_label_deltas(&deltas),
(
vec![
GitHubLabel {
name: "I-libs-nominated".to_string()
},
GitHubLabel {
name: "I-nominated".to_string()
},
],
vec![],
),
);
deltas.push(LabelDelta::Remove(Label("needs-triage".to_string())));
deltas.push(LabelDelta::Add(Label("I-lang-nominated".to_string())));
assert_eq!(
compute_label_deltas(&deltas),
(
vec![
GitHubLabel {
name: "I-lang-nominated".to_string()
},
GitHubLabel {
name: "I-libs-nominated".to_string()
},
GitHubLabel {
name: "I-nominated".to_string()
},
],
vec![GitHubLabel {
name: "needs-triage".to_string()
}],
),
);
}
#[test]
fn test_case_insensitive_label_lookup() {
let issue = issue().labels(vec!["E-needs-mcve"]).call();
assert!(issue.contains_label(&GitHubLabel {
name: "E-needs-mcve".to_string(),
}));
assert!(issue.contains_label(&GitHubLabel {
name: "e-needs-mcve".to_string(),
}));
}
}