-
Notifications
You must be signed in to change notification settings - Fork 104
Expand file tree
/
Copy pathnotify_zulip.rs
More file actions
362 lines (323 loc) · 11.8 KB
/
Copy pathnotify_zulip.rs
File metadata and controls
362 lines (323 loc) · 11.8 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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
//! Handles sending messages to the Zulip chat instance.
//!
//! Configured in [notify-zulip.*] sections
//!
use crate::github::GitHubUser;
use crate::zulip::api::Recipient;
use crate::zulip::render_zulip_username;
use crate::{
config::{NotifyZulipConfig, NotifyZulipLabelConfig, NotifyZulipTablesConfig},
github::{Issue, IssuesAction, IssuesEvent, Label},
handlers::Context,
};
use futures::future::join_all;
use tracing as log;
pub(super) struct NotifyZulipInput {
notification_type: NotificationType,
/// Label that triggered this notification.
///
/// For example, if an `I-prioritize` issue is closed,
/// this field will be `I-prioritize`.
label: Label,
/// List of strings for tables such as [notify-zulip."beta-nominated"]
/// and/or [notify-zulip."beta-nominated".compiler]
include_config_names: Vec<String>,
}
pub(super) enum NotificationType {
Open,
Labeled,
Unlabeled,
Closed,
Reopened,
}
pub(super) async fn parse_input(
_ctx: &Context,
event: &IssuesEvent,
config: Option<&NotifyZulipConfig>,
) -> Result<Option<Vec<NotifyZulipInput>>, String> {
let Some(config) = config else {
return Ok(None);
};
match &event.action {
IssuesAction::Labeled { label } | IssuesAction::Unlabeled { label: Some(label) } => {
let applied_label = label.clone();
Ok(config
.labels
.get(&applied_label.name)
.and_then(|label_config| {
parse_label_change_input(event, applied_label, label_config)
})
.map(|input| vec![input]))
}
IssuesAction::Opened | IssuesAction::Closed | IssuesAction::Reopened => {
Ok(Some(parse_open_close_reopen_input(event, config)))
}
_ => Ok(None),
}
}
fn parse_label_change_input(
event: &IssuesEvent,
label: Label,
config: &NotifyZulipTablesConfig,
) -> Option<NotifyZulipInput> {
let mut include_config_names: Vec<String> = vec![];
for (name, label_config) in &config.subtables {
if has_all_required_labels(&event.issue, label_config) {
match event.action {
IssuesAction::Labeled { .. } if !label_config.messages_on_add.is_empty() => {
include_config_names.push(name.to_string());
}
IssuesAction::Unlabeled { .. } if !label_config.messages_on_remove.is_empty() => {
include_config_names.push(name.to_string());
}
_ => (),
}
}
}
if include_config_names.is_empty() {
// It seems that there is no match between this event and any notify-zulip config, ignore this event
return None;
}
match event.action {
IssuesAction::Labeled { .. } => Some(NotifyZulipInput {
notification_type: NotificationType::Labeled,
label,
include_config_names,
}),
IssuesAction::Unlabeled { .. } => Some(NotifyZulipInput {
notification_type: NotificationType::Unlabeled,
label,
include_config_names,
}),
_ => None,
}
}
fn parse_open_close_reopen_input(
event: &IssuesEvent,
global_config: &NotifyZulipConfig,
) -> Vec<NotifyZulipInput> {
event
.issue
.labels
.iter()
.cloned()
.filter_map(|label| {
global_config
.labels
.get(&label.name)
.map(|config| (label, config))
})
.filter_map(|(label, config)| {
let mut include_config_names: Vec<String> = vec![];
for (name, label_config) in &config.subtables {
if has_all_required_labels(&event.issue, label_config) {
match event.action {
IssuesAction::Opened if !label_config.messages_on_add.is_empty() => {
include_config_names.push(name.to_string());
}
IssuesAction::Closed if !label_config.messages_on_close.is_empty() => {
include_config_names.push(name.to_string());
}
IssuesAction::Reopened if !label_config.messages_on_reopen.is_empty() => {
include_config_names.push(name.to_string());
}
_ => (),
}
}
}
if include_config_names.is_empty() {
// It seems that there is no match between this event and any notify-zulip config, ignore this event
return None;
}
match event.action {
IssuesAction::Opened => Some(NotifyZulipInput {
notification_type: NotificationType::Open,
label,
include_config_names,
}),
IssuesAction::Closed => Some(NotifyZulipInput {
notification_type: NotificationType::Closed,
label,
include_config_names,
}),
IssuesAction::Reopened => Some(NotifyZulipInput {
notification_type: NotificationType::Reopened,
label,
include_config_names,
}),
_ => None,
}
})
.collect()
}
fn has_all_required_labels(issue: &Issue, config: &NotifyZulipLabelConfig) -> bool {
for req_label in &config.required_labels {
let pattern = match globset::Glob::new(req_label) {
Ok(pattern) => pattern,
Err(err) => {
log::error!("Invalid glob pattern: {err}");
continue;
}
};
let matcher = pattern.compile_matcher();
if !issue.labels().iter().any(|l| matcher.is_match(&l.name)) {
return false;
}
}
true
}
pub(super) async fn handle_input(
ctx: &Context,
config: &NotifyZulipConfig,
event: &IssuesEvent,
inputs: Vec<NotifyZulipInput>,
) -> anyhow::Result<()> {
for input in inputs {
let tables_config = &config.labels[&input.label.name];
// Get valid label configs
let mut label_configs: Vec<&NotifyZulipLabelConfig> = vec![];
for name in input.include_config_names {
label_configs.push(&tables_config.subtables[&name]);
}
for label_config in label_configs {
let config = label_config;
let topic = &config.topic;
let topic = topic.replace("{number}", &event.issue.number.to_string());
let mut topic = topic.replace("{title}", &event.issue.title);
// Truncate to 60 chars (a Zulip limitation)
let mut chars = topic.char_indices().skip(59);
if let (Some((len, _)), Some(_)) = (chars.next(), chars.next()) {
topic.truncate(len);
topic.push('…');
}
let msgs = match input.notification_type {
NotificationType::Open | NotificationType::Labeled => &config.messages_on_add,
NotificationType::Unlabeled => &config.messages_on_remove,
NotificationType::Closed => &config.messages_on_close,
NotificationType::Reopened => &config.messages_on_reopen,
};
let github_comment = match input.notification_type {
NotificationType::Open | NotificationType::Labeled => &config.github_comment,
NotificationType::Unlabeled
| NotificationType::Closed
| NotificationType::Reopened => &None,
};
let recipient = Recipient::Stream {
id: config.zulip_stream,
topic: &topic,
};
// Issue/PR authors/reviewers will receive a mention if the template has `{recipients}`.
let recipients = &mut event.issue.assignees.clone();
recipients.push(event.issue.user.clone());
let mut msgs_send = 0;
for msg in msgs {
let msg = msg.replace("{number}", &event.issue.number.to_string());
let msg = msg.replace("{title}", &event.issue.title);
let msg = replace_team_to_be_nominated(&event.issue.labels, msg);
let msg = msg.replace("{recipients}", &get_zulip_ids(ctx, recipients).await);
let req = crate::zulip::MessageApiRequest {
recipient,
content: &msg,
}
.send(&ctx.zulip)
.await;
if let Err(err) = req {
log::error!("Failed to send notification to Zulip {err}");
} else {
msgs_send += 1;
}
}
if msgs_send > 0
&& let Some(github_comment) = &github_comment
{
let github_comment =
github_comment.replace("{zulip_topic_url}", &recipient.url(&ctx.zulip));
if let Err(err) = event.issue.post_comment(&ctx.github, &github_comment).await {
log::error!("failed to post github notification comment {err}");
}
}
}
}
Ok(())
}
async fn get_zulip_ids(ctx: &Context, recipients: &[GitHubUser]) -> String {
let gh_ids_fut = recipients
.iter()
.map(|recipient| async move { ctx.team.github_to_zulip_id(recipient.id).await });
let zulip_ids = join_all(gh_ids_fut).await;
let zulip_ids = zulip_ids
.iter()
.filter_map(|x| {
if let Ok(id2) = x.as_ref()
&& let Some(id) = *id2
{
Some(render_zulip_username(id))
} else {
None
}
})
.collect::<Vec<String>>();
if !zulip_ids.is_empty() {
zulip_ids.join(", ")
} else {
"".to_string()
}
}
/// Replace the placeholder "{team}" with the correct team name
fn replace_team_to_be_nominated(labels: &[Label], msg: String) -> String {
let teams = labels
.iter()
.map(|label| &label.name)
.filter_map(|label| label.strip_prefix("T-"))
.collect::<Vec<&str>>();
// - If a single team label is found, replace the placeholder with that one
// - If multiple team labels are found and one of them is "compiler", pick that one
// (currently the only team handling these Zulip notification)
// - else, do nothing
if let [team] = &*teams {
msg.replace("{team}", team)
} else if teams.contains(&"compiler") {
msg.replace("{team}", "compiler")
} else {
msg
}
}
#[test]
fn test_notification() {
let mut msg = replace_team_to_be_nominated(&[], "Needs `I-{team}-nominated`?".to_string());
assert!(msg.contains("Needs `I-{team}-nominated`?"), "{msg}");
msg = replace_team_to_be_nominated(
&[Label {
name: "T-cooks".to_string(),
}],
"Needs `I-{team}-nominated`?".to_string(),
);
assert!(msg.contains("I-cooks-nominated"), "{msg}");
msg = replace_team_to_be_nominated(
&[
Label {
name: "T-compiler".to_string(),
},
Label {
name: "T-libs".to_string(),
},
Label {
name: "T-cooks".to_string(),
},
],
"Needs `I-{team}-nominated`?".to_string(),
);
assert!(msg.contains("I-compiler-nominated"), "{msg}");
msg = replace_team_to_be_nominated(
&[
Label {
name: "T-libs".to_string(),
},
Label {
name: "T-cooks".to_string(),
},
],
"Needs `I-{team}-nominated`?".to_string(),
);
assert!(msg.contains("Needs `I-{team}-nominated`?"), "{msg}");
}