forked from rust-lang/relnotes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.rs
More file actions
461 lines (409 loc) · 14.6 KB
/
main.rs
File metadata and controls
461 lines (409 loc) · 14.6 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
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
use std::collections::BTreeMap;
use std::collections::HashMap;
use std::env;
use askama::Template;
use chrono::prelude::*;
use chrono::Duration;
use reqwest::header::HeaderMap;
use serde_json as json;
const SKIP_LABELS: &[&str] = &["rollup"];
const RELNOTES_LABELS: &[&str] = &[
"relnotes",
"relnotes-perf",
"finished-final-comment-period",
"needs-fcp",
];
#[derive(Clone, Template)]
#[template(path = "relnotes.md", escape = "none")]
struct ReleaseNotes {
version: String,
date: NaiveDate,
language_relnotes: String,
compiler_relnotes: String,
libraries_relnotes: String,
stabilized_apis_relnotes: String,
const_stabilized_apis_relnotes: String,
cargo_relnotes: String,
rustdoc_relnotes: String,
compat_relnotes: String,
internal_changes_relnotes: String,
other_relnotes: String,
}
fn main() {
let mut args = env::args();
let _ = args.next();
let version = args
.next()
.expect("A version number (xx.yy.zz) for the Rust release is required.");
let today = Utc::now().date_naive();
// A known rust release date. (1.42.0)
let mut end = Utc
.with_ymd_and_hms(2020, 3, 12, 0, 0, 0)
.single()
.unwrap()
.date_naive();
let six_weeks = Duration::weeks(6);
// Get the most recent rust release date.
while today - end > six_weeks {
end = end + six_weeks;
}
let issues = get_issues_by_milestone(&version, "rust");
let mut tracking_rust = TrackingIssues::collect(&issues);
// Skips some PRs that aren't themselves interesting.
let in_release = issues.iter().filter(|v| {
!v["labels"]["nodes"]
.as_array()
.unwrap()
.iter()
.any(|o| SKIP_LABELS.contains(&o["name"].as_str().unwrap()))
});
let relnotes = in_release
.into_iter()
.filter(|o| has_tags(o, RELNOTES_LABELS))
.collect::<Vec<_>>();
let Sections {
language_relnotes,
compiler_relnotes,
libraries_relnotes,
stabilized_apis_relnotes,
const_stabilized_apis_relnotes,
rustdoc_relnotes,
compat_relnotes,
internal_changes_relnotes,
other_relnotes,
} = to_sections(relnotes, &mut tracking_rust);
let cargo_issues = get_issues_by_milestone(&version, "cargo");
let cargo_relnotes = {
let relnotes = cargo_issues
.iter()
.filter(|o| has_tags(o, RELNOTES_LABELS))
.collect::<Vec<_>>();
relnotes
.iter()
.map(|o| {
format!(
"- [{title}]({url}/)",
title = o["title"].as_str().unwrap(),
url = o["url"].as_str().unwrap(),
)
})
.collect::<Vec<_>>()
.join("\n")
};
for issue in tracking_rust.issues.values() {
for (section, (used, _)) in issue.sections.iter() {
if issue.raw["labels"]["nodes"]
.as_array()
.unwrap()
.iter()
.any(|l| l["name"] == "relnotes-tracking-issue")
&& issue.raw["state"] == "CLOSED"
{
assert!(
!*used,
"{} <{}> used despite tracking issue being closed",
issue.raw["title"].as_str().unwrap(),
issue.raw["url"].as_str().unwrap()
);
continue;
}
if *used {
continue;
}
eprintln!(
"Did not use {:?} from {} <{}> (intended to provide relnotes for: {:?})",
section,
issue.raw["title"].as_str().unwrap(),
issue.raw["url"].as_str().unwrap(),
issues
.iter()
.find(|i| i["number"].as_u64().unwrap() == issue.for_number)
);
}
}
let relnotes = ReleaseNotes {
version,
date: end + six_weeks,
language_relnotes,
compiler_relnotes,
libraries_relnotes,
rustdoc_relnotes,
stabilized_apis_relnotes,
const_stabilized_apis_relnotes,
cargo_relnotes,
internal_changes_relnotes,
compat_relnotes,
other_relnotes,
};
println!("{}", relnotes.render().unwrap());
}
fn get_issues_by_milestone(version: &str, repo_name: &'static str) -> Vec<json::Value> {
let mut out = get_issues_by_milestone_inner(version, repo_name, "issues");
out.extend(get_issues_by_milestone_inner(
version,
repo_name,
"pullRequests",
));
out.sort_unstable_by_key(|v| v["number"].as_u64().unwrap());
out.dedup_by_key(|v| v["number"].as_u64().unwrap());
out
}
fn get_issues_by_milestone_inner(
version: &str,
repo_name: &'static str,
ty: &str,
) -> Vec<json::Value> {
use reqwest::blocking::Client;
let headers = request_header();
let mut args = BTreeMap::new();
if ty == "pullRequests" {
args.insert("states", String::from("[MERGED]"));
}
args.insert("last", String::from("100"));
let mut issues = Vec::new();
loop {
let query = format!(
r#"
query {{
repository(owner: "rust-lang", name: "{repo_name}") {{
milestones(query: "{version}", first: 1) {{
totalCount
nodes {{
{ty}({args}) {{
nodes {{
number
title
url
body
state
labels(last: 100) {{
nodes {{
name
}}
}}
}}
pageInfo {{
startCursor
}}
}}
}}
}}
}}
}}"#,
repo_name = repo_name,
version = version,
ty = ty,
args = args
.iter()
.map(|(k, v)| format!("{}: {}", k, v))
.collect::<Vec<_>>()
.join(",")
)
.replace(" ", "")
.replace("\n", " ")
.replace('"', "\\\"");
let json_query = format!("{{\"query\": \"{}\"}}", query);
let client = Client::new();
let response = client
.post("https://api.github.com/graphql")
.headers(headers.clone())
.body(json_query)
.send()
.unwrap();
let status = response.status();
let json = response.json::<json::Value>().unwrap();
if !status.is_success() {
panic!("API Error {}: {}", status, json);
}
let milestones_data = json["data"]["repository"]["milestones"].clone();
assert_eq!(
milestones_data["totalCount"].as_u64().unwrap(),
1,
"More than one milestone matched the query \"{version}\". Please be more specific.",
version = version
);
let pull_requests_data = milestones_data["nodes"][0][ty].clone();
let mut pull_requests = pull_requests_data["nodes"].as_array().unwrap().clone();
issues.append(&mut pull_requests);
match &pull_requests_data["pageInfo"]["startCursor"] {
json::Value::String(cursor) => {
args.insert("before", format!("\"{}\"", cursor));
}
json::Value::Null => {
break issues;
}
_ => unreachable!(),
}
}
}
fn request_header() -> HeaderMap {
use reqwest::header::*;
let token = env::var("GITHUB_TOKEN").expect("Set GITHUB_TOKEN to a valid token");
let mut headers = HeaderMap::new();
headers.insert(CONTENT_TYPE, "application/json".parse().unwrap());
headers.insert(ACCEPT, "application/json".parse().unwrap());
headers.insert(AUTHORIZATION, format!("Bearer {}", token).parse().unwrap());
headers.insert(USER_AGENT, "Rust-relnotes/0.1.0".parse().unwrap());
headers
}
struct TrackingIssues {
// Maps the issue/PR number *tracked* by the issue in `json::Value`.
//
// bool is tracking whether we've used that issue already.
issues: HashMap<u64, TrackingIssue>,
}
#[derive(Debug)]
struct TrackingIssue {
for_number: u64,
raw: json::Value,
// Section name -> (used, lines)
sections: HashMap<String, (bool, Vec<String>)>,
}
impl TrackingIssues {
fn collect(all: &[json::Value]) -> Self {
const PREFIX: &str = "Tracking issue for release notes of #";
const MARKDOWN: &str = r"(?ms)^(`{3,})markdown\r?\n(.*?)^\1\r?\n";
let markdown_re = fancy_regex::Regex::new(MARKDOWN).unwrap();
let mut tracking_issues = HashMap::new();
for o in all.iter() {
let title = o["title"].as_str().unwrap();
if let Some(tail) = title.strip_prefix(PREFIX) {
let for_number = tail[..tail.find(':').unwrap()].parse::<u64>().unwrap();
let mut sections = HashMap::new();
let body = o["body"].as_str().unwrap();
let Ok(Some(captures)) = markdown_re.captures(body) else {
let issue = &o["number"];
eprintln!("WARNING: skipping {issue}, markdown not found:");
eprintln!(" {body:?}");
continue;
};
let relnotes = &captures[2];
let mut in_section = None;
for line in relnotes.lines() {
if line.trim().is_empty() {
continue;
}
if let Some(header) = line.strip_prefix("# ") {
in_section = Some(header);
continue;
}
if let Some(section) = in_section {
sections
.entry(section.to_owned())
.or_insert_with(|| (false, vec![]))
.1
.push(line.to_owned());
}
}
tracking_issues.insert(
for_number,
TrackingIssue {
for_number,
raw: o.clone(),
sections,
},
);
}
}
Self {
issues: tracking_issues,
}
}
}
fn map_to_line_items<'a>(
iter: impl IntoIterator<Item = &'a json::Value>,
tracking_issues: &mut TrackingIssues,
by_section: &mut HashMap<&'static str, String>,
) {
for o in iter {
let title = o["title"].as_str().unwrap();
if title.starts_with("Tracking issue for release notes of #") {
continue;
}
let number = o["number"].as_u64().unwrap();
if let Some(issue) = tracking_issues.issues.get_mut(&number) {
// If the tracking issue is closed, skip.
if issue.raw["state"] == "CLOSED" {
continue;
}
for (section, (used, lines)) in issue.sections.iter_mut() {
if let Some((_, contents)) = by_section
.iter_mut()
.find(|(s, _)| s.eq_ignore_ascii_case(section))
{
*used = true;
for line in lines.iter() {
contents.push_str(line);
contents.push('\n');
}
}
}
// If we have a dedicated tracking issue, don't use our default rules.
continue;
}
// In the future we expect to have increasingly few things fall into this category, as
// things are added to the dedicated tracking issue category in triagebot (today mostly
// FCPs are missing).
let section = if has_tags(o, &["C-future-compatibility"]) {
"Compatibility Notes"
} else if has_tags(o, &["T-libs", "T-libs-api"]) {
"Library"
} else if has_tags(o, &["T-lang"]) {
"Language"
} else if has_tags(o, &["T-compiler"]) {
"Compiler"
} else {
"Other"
};
by_section.get_mut(section).unwrap().push_str(&format!(
"- [{title}]({url}/)\n",
title = o["title"].as_str().unwrap(),
url = o["url"].as_str().unwrap(),
));
}
}
fn has_tags<'a>(o: &'a json::Value, tags: &[&str]) -> bool {
o["labels"]["nodes"]
.as_array()
.unwrap()
.iter()
.any(|o| tags.iter().any(|tag| o["name"] == *tag))
}
struct Sections {
language_relnotes: String,
compiler_relnotes: String,
libraries_relnotes: String,
stabilized_apis_relnotes: String,
const_stabilized_apis_relnotes: String,
rustdoc_relnotes: String,
compat_relnotes: String,
internal_changes_relnotes: String,
other_relnotes: String,
}
fn to_sections<'a>(
iter: impl IntoIterator<Item = &'a json::Value>,
mut tracking: &mut TrackingIssues,
) -> Sections {
let mut by_section = HashMap::new();
by_section.insert("Language", String::new());
by_section.insert("Compiler", String::new());
by_section.insert("Libraries", String::new());
by_section.insert("Stabilized APIs", String::new());
by_section.insert("Const Stabilized APIs", String::new());
by_section.insert("Rustdoc", String::new());
by_section.insert("Compatibility Notes", String::new());
by_section.insert("Internal Changes", String::new());
by_section.insert("Other", String::new());
map_to_line_items(iter, &mut tracking, &mut by_section);
Sections {
language_relnotes: by_section.remove("Language").unwrap(),
compiler_relnotes: by_section.remove("Compiler").unwrap(),
libraries_relnotes: by_section.remove("Libraries").unwrap(),
stabilized_apis_relnotes: by_section.remove("Stabilized APIs").unwrap(),
const_stabilized_apis_relnotes: by_section.remove("Const Stabilized APIs").unwrap(),
rustdoc_relnotes: by_section.remove("Rustdoc").unwrap(),
compat_relnotes: by_section.remove("Compatibility Notes").unwrap(),
internal_changes_relnotes: by_section.remove("Internal Changes").unwrap(),
other_relnotes: by_section.remove("Other").unwrap(),
}
}