-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpr-metadata-validator.rs
More file actions
237 lines (205 loc) · 7.99 KB
/
pr-metadata-validator.rs
File metadata and controls
237 lines (205 loc) · 7.99 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
use std::{collections::BTreeMap, process::exit};
use chrono::NaiveDate;
use indexmap::IndexMap;
use maplit::btreemap;
use octocrab::Octocrab;
use regex::Regex;
use trainee_tracker::{
config::{CourseSchedule, CourseScheduleWithRegisterSheetId},
course::match_prs_to_assignments,
newtypes::Region,
octocrab::octocrab_for_token,
prs::get_prs,
Error,
};
const ARBITRARY_REGION: Region = Region(String::new());
#[tokio::main]
async fn main() {
let Ok([_argv0, pr_url]) = <[_; 2]>::try_from(std::env::args().collect::<Vec<_>>()) else {
eprintln!("Expected one arg - PR URL");
exit(1);
};
let pr_parts: Vec<_> = pr_url.split("/").collect();
let (github_org_name, module_name, pr_number) = match pr_parts.as_slice() {
[_http, _scheme, _domain, github_org_name, module_name, _pull, number] => (
(*github_org_name).to_owned(),
(*module_name).to_owned(),
number.parse::<u64>().expect("Failed to parse PR number"),
),
_ => {
eprintln!("Failed to parse PR URL");
exit(1);
}
};
// TODO: Fetch this from classplanner or somewhere when we have access to a useful API.
let known_region_aliases = KnownRegions(btreemap! {
"Cape Town" => vec!["South Africa", "SouthAfrica", "ZA", "ZA Cape Town"],
"Glasgow" => vec!["Scotland"],
"London" => vec![],
"North West" => vec!["NW", "Manchester"],
"Sheffield" => vec![],
"West Midlands" => vec!["WM", "WestMidlands", "West-Midlands", "Birmingham"],
});
let github_token =
std::env::var("GH_TOKEN").expect("GH_TOKEN wasn't set - must be set to a GitHub API token");
let octocrab = octocrab_for_token(github_token).expect("Failed to get octocrab");
let course_schedule = make_fake_course_schedule(module_name.clone());
let course = CourseScheduleWithRegisterSheetId {
name: "itp".to_owned(),
register_sheet_id: "".to_owned(),
course_schedule,
};
let result = validate_pr(
&octocrab,
course,
&module_name,
&github_org_name,
pr_number,
&known_region_aliases,
)
.await
.expect("Failed to validate PR");
let message = match result {
ValidationResult::Ok => {
exit(0);
}
ValidationResult::CouldNotMatch => COULD_NOT_MATCH_COMMENT,
ValidationResult::BodyTemplateNotFilledOut => BODY_TEMPLATE_NOT_FILLED_IN_COMMENT,
ValidationResult::BadTitleFormat { reason } => {
&format!("{}{}", BAD_TITLE_COMMENT_PREFIX, reason)
}
ValidationResult::UnknownRegion => UNKNOWN_REGION_COMMENT,
};
let full_message = format!("{message}\n\nIf this PR is not coursework, please add the NotCoursework label (and message on Slack in #cyf-curriculum or it will probably not be noticed).");
eprintln!("{}", full_message);
octocrab
.issues(github_org_name, module_name)
.create_comment(pr_number, full_message)
.await
.expect("Failed to create comment with validation error");
exit(2);
}
const COULD_NOT_MATCH_COMMENT: &str = r#"Your PR couldn't be matched to an assignment in this module.
Please check its title is in the correct format, and that you only have one PR per assignment."#;
const BODY_TEMPLATE_NOT_FILLED_IN_COMMENT: &str = r#"Your PR description contained template fields which weren't filled in.
Check you've ticked everything in the self checklist, and that any sections which prompt you to fill in an answer are either filled in or removed."#;
const BAD_TITLE_COMMENT_PREFIX: &str = r#"Your PR's title isn't in the expected format.
Please check the expected title format, and update yours to match.
Reason: "#;
const UNKNOWN_REGION_COMMENT: &str = r#"Your PR's title didn't contain a known region.
Please check the expected title format, and make sure your region is in the correct place and spelled correctly."#;
enum ValidationResult {
Ok,
BodyTemplateNotFilledOut,
CouldNotMatch,
BadTitleFormat { reason: String },
UnknownRegion,
}
async fn validate_pr(
octocrab: &Octocrab,
course_schedule: CourseScheduleWithRegisterSheetId,
module_name: &str,
github_org_name: &str,
pr_number: u64,
known_region_aliases: &KnownRegions,
) -> Result<ValidationResult, Error> {
let course = course_schedule
.with_assignments(octocrab, github_org_name)
.await
.map_err(|err| err.context("Failed to get assignments"))?;
let module_prs = get_prs(octocrab, github_org_name, module_name, false)
.await
.map_err(|err| err.context("Failed to get PRs"))?;
let pr_in_question = module_prs
.iter()
.find(|pr| pr.number == pr_number)
.ok_or_else(|| {
anyhow::anyhow!(
"Failed to find PR {} in list of PRs for module {}",
pr_number,
module_name
)
})?
.clone();
if pr_in_question.labels.contains("NotCoursework") {
return Ok(ValidationResult::Ok);
}
let user_prs: Vec<_> = module_prs
.into_iter()
.filter(|pr| pr.author == pr_in_question.author)
.collect();
let matched = match_prs_to_assignments(
&course.modules[module_name],
user_prs,
Vec::new(),
&ARBITRARY_REGION,
)
.map_err(|err| err.context("Failed to match PRs to assignments"))?;
for pr in matched.unknown_prs {
if pr.number == pr_number {
return Ok(ValidationResult::CouldNotMatch);
}
}
let title_sections: Vec<&str> = pr_in_question.title.split("|").collect();
if title_sections.len() != 5 {
return Ok(ValidationResult::BadTitleFormat {
reason: "Wrong number of parts separated by |s".to_owned(),
});
}
if !known_region_aliases.is_known_ignoring_case(title_sections[0].trim()) {
return Ok(ValidationResult::UnknownRegion);
}
// TODO: Validate cohorts when they're known (1)
let sprint_regex = Regex::new(r"^(S|s)print \d+$").unwrap();
let sprint_section = title_sections[3].trim();
if !sprint_regex.is_match(sprint_section) {
return Ok(ValidationResult::BadTitleFormat { reason: format!("Sprint part ({}) doesn't match expected format (example: 'Sprint 2', without quotes)", sprint_section) });
}
if pr_in_question.title.to_ascii_uppercase() == pr_in_question.title {
return Ok(ValidationResult::BadTitleFormat {
reason: "PR title should not all be in uppercase".to_owned(),
});
}
if pr_in_question.body.contains("Briefly explain your PR.")
|| pr_in_question
.body
.contains("Ask any questions you have for your reviewer.")
|| pr_in_question.body.contains("- [ ]")
{
return Ok(ValidationResult::BodyTemplateNotFilledOut);
}
Ok(ValidationResult::Ok)
}
struct KnownRegions(BTreeMap<&'static str, Vec<&'static str>>);
impl KnownRegions {
fn is_known_ignoring_case(&self, possible_region: &str) -> bool {
let possible_region_lower = possible_region.to_ascii_lowercase();
for (known_region, known_region_aliases) in &self.0 {
if known_region.to_ascii_lowercase() == possible_region_lower {
return true;
}
for known_region_alias in known_region_aliases {
if known_region_alias.to_ascii_lowercase() == possible_region_lower {
return true;
}
}
}
false
}
}
fn make_fake_course_schedule(module_name: String) -> CourseSchedule {
let fixed_date = NaiveDate::from_ymd_opt(2030, 1, 1).unwrap();
let mut sprints = IndexMap::new();
sprints.insert(
module_name,
std::iter::repeat_with(|| btreemap![ARBITRARY_REGION => fixed_date])
// 5 is the max number of sprints a module (currently) contains.
.take(5)
.collect(),
);
CourseSchedule {
start: fixed_date,
end: fixed_date,
sprints,
}
}