| 554ccacf Andy McCall ↶ |
1 |
|
| 2 |
|
| 3 |
|
| 7fff30c4 Andy McCall ↶ |
4 |
|
| 554ccacf Andy McCall ↶ |
5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
use crate::db::{now_ms, Pool}; |
| 10 |
use crate::Shared; |
| 11 |
use std::collections::{BTreeMap, HashSet}; |
| 12 |
use std::sync::Mutex; |
| 13 |
|
| 14 |
|
| 15 |
pub const ARTIFACT: &str = "coverage"; |
| 16 |
|
| 17 |
pub const MAX_REPORT: usize = 64 << 20; |
| 18 |
|
| 19 |
|
| 20 |
#[derive(Clone, Debug, Default, PartialEq, Eq)] |
| 21 |
pub struct FileCoverage { |
| 22 |
|
| 23 |
pub path: String, |
| 24 |
|
| 25 |
pub lines: BTreeMap<u32, u64>, |
| 26 |
pub functions_found: u64, |
| 27 |
pub functions_hit: u64, |
| 28 |
pub branches_found: u64, |
| 29 |
pub branches_hit: u64, |
| 30 |
|
| 31 |
|
| 32 |
|
| 33 |
pub declared_lines: Option<(u64, u64)>, |
| 34 |
} |
| 35 |
|
| 36 |
impl FileCoverage { |
| 37 |
pub fn lines_found(&self) -> u64 { |
| 38 |
self.declared_lines.map(|d| d.0).unwrap_or(self.lines.len() as u64) |
| 39 |
} |
| 40 |
|
| 41 |
pub fn lines_hit(&self) -> u64 { |
| 42 |
self.declared_lines.map(|d| d.1).unwrap_or_else(|| self.lines.values().filter(|n| **n > 0).count() as u64) |
| 43 |
} |
| c987c865 Andy McCall ↶ |
44 |
|
| 45 |
|
| 46 |
pub fn hits(&self) -> u64 { |
| 47 |
self.lines.values().fold(0u64, |a, n| a.saturating_add(*n)) |
| 48 |
} |
| 554ccacf Andy McCall ↶ |
49 |
} |
| 50 |
|
| 51 |
|
| 52 |
|
| 53 |
|
| 54 |
pub fn relative(path: &str) -> Option<String> { |
| 55 |
let p = path.trim(); |
| 56 |
let p = p.strip_prefix("/src/").unwrap_or(p); |
| 57 |
let p = p.strip_prefix("./").unwrap_or(p); |
| 58 |
if p.is_empty() || p.starts_with('/') || p.contains('\\') || p.split('/').any(|s| s.is_empty() || s == "." || s == "..") { |
| 59 |
return None; |
| 60 |
} |
| 61 |
Some(p.to_string()) |
| 62 |
} |
| 63 |
|
| 64 |
#[derive(Default)] |
| 65 |
struct Acc { |
| 66 |
lines: BTreeMap<u32, u64>, |
| 67 |
functions: BTreeMap<String, u64>, |
| 68 |
branches: BTreeMap<(u32, String, String), u64>, |
| 69 |
declared_fn: (u64, u64), |
| 70 |
declared_br: (u64, u64), |
| 71 |
declared_lines: (Option<u64>, Option<u64>), |
| 72 |
records: u32, |
| 73 |
} |
| 74 |
|
| 75 |
|
| 76 |
|
| 77 |
|
| 78 |
pub fn parse_lcov(text: &str) -> Result<(Vec<FileCoverage>, usize), String> { |
| 79 |
let mut files: BTreeMap<String, Acc> = BTreeMap::new(); |
| 80 |
let mut current: Option<Option<String>> = None; |
| 81 |
let mut outside = HashSet::new(); |
| 82 |
let mut records = 0usize; |
| 83 |
|
| 84 |
let mut started = false; |
| 85 |
let num = |s: &str| s.trim().parse::<u64>().unwrap_or(0); |
| 86 |
for line in text.lines() { |
| 87 |
let line = line.trim(); |
| 88 |
if let Some(path) = line.strip_prefix("SF:") { |
| 89 |
records += 1; |
| 90 |
let rel = relative(path); |
| 91 |
if rel.is_none() { |
| 92 |
outside.insert(path.to_string()); |
| 93 |
} |
| 94 |
current = Some(rel); |
| 95 |
started = true; |
| 96 |
continue; |
| 97 |
} |
| 98 |
if line == "end_of_record" { |
| 99 |
current = None; |
| 100 |
continue; |
| 101 |
} |
| 102 |
let Some(Some(path)) = ¤t else { continue }; |
| 103 |
let acc = files.entry(path.clone()).or_default(); |
| 104 |
if line == "TN:" || line.starts_with("TN:") { |
| 105 |
continue; |
| 106 |
} |
| 107 |
if std::mem::take(&mut started) { |
| 108 |
acc.records += 1; |
| 109 |
} |
| 110 |
if let Some(n) = line.strip_prefix("LF:") { |
| 111 |
acc.declared_lines.0 = Some(num(n)); |
| 112 |
} else if let Some(n) = line.strip_prefix("LH:") { |
| 113 |
acc.declared_lines.1 = Some(num(n)); |
| 114 |
} else if let Some(rest) = line.strip_prefix("DA:") { |
| 115 |
let mut parts = rest.split(','); |
| 116 |
if let (Some(l), Some(n)) = (parts.next(), parts.next()) { |
| 117 |
if let Ok(l) = l.trim().parse::<u32>() { |
| 118 |
*acc.lines.entry(l).or_default() += num(n); |
| 119 |
} |
| 120 |
} |
| 121 |
} else if let Some(rest) = line.strip_prefix("FN:") { |
| 122 |
if let Some((_, name)) = rest.split_once(',') { |
| 123 |
acc.functions.entry(name.to_string()).or_default(); |
| 124 |
} |
| 125 |
} else if let Some(rest) = line.strip_prefix("FNDA:") { |
| 126 |
if let Some((n, name)) = rest.split_once(',') { |
| 127 |
*acc.functions.entry(name.to_string()).or_default() += num(n); |
| 128 |
} |
| 129 |
} else if let Some(rest) = line.strip_prefix("BRDA:") { |
| 130 |
let parts: Vec<&str> = rest.split(',').collect(); |
| 131 |
if let [l, block, branch, taken] = parts[..] { |
| 132 |
if let Ok(l) = l.trim().parse::<u32>() { |
| 133 |
let taken = if taken.trim() == "-" { 0 } else { num(taken) }; |
| 134 |
*acc.branches.entry((l, block.to_string(), branch.to_string())).or_default() += taken; |
| 135 |
} |
| 136 |
} |
| 137 |
} else if let Some(n) = line.strip_prefix("FNF:") { |
| 138 |
acc.declared_fn.0 = acc.declared_fn.0.max(num(n)); |
| 139 |
} else if let Some(n) = line.strip_prefix("FNH:") { |
| 140 |
acc.declared_fn.1 = acc.declared_fn.1.max(num(n)); |
| 141 |
} else if let Some(n) = line.strip_prefix("BRF:") { |
| 142 |
acc.declared_br.0 = acc.declared_br.0.max(num(n)); |
| 143 |
} else if let Some(n) = line.strip_prefix("BRH:") { |
| 144 |
acc.declared_br.1 = acc.declared_br.1.max(num(n)); |
| 145 |
} |
| 146 |
} |
| 147 |
if records == 0 { |
| 148 |
return Err("this is not an LCOV report: it names no source file (no SF: line)".into()); |
| 149 |
} |
| 150 |
let out = files |
| 151 |
.into_iter() |
| 152 |
.map(|(path, a)| { |
| 153 |
let (functions_found, functions_hit) = if a.functions.is_empty() { |
| 154 |
a.declared_fn |
| 155 |
} else { |
| 156 |
(a.functions.len() as u64, a.functions.values().filter(|n| **n > 0).count() as u64) |
| 157 |
}; |
| 158 |
let (branches_found, branches_hit) = if a.branches.is_empty() { |
| 159 |
a.declared_br |
| 160 |
} else { |
| 161 |
(a.branches.len() as u64, a.branches.values().filter(|n| **n > 0).count() as u64) |
| 162 |
}; |
| 163 |
let declared_lines = match (a.records, a.declared_lines) { |
| 164 |
(1, (Some(f), Some(h))) if h <= f && f >= a.lines.len() as u64 => Some((f, h)), |
| 165 |
_ => None, |
| 166 |
}; |
| 167 |
FileCoverage { path, lines: a.lines, functions_found, functions_hit, branches_found, branches_hit, declared_lines } |
| 168 |
}) |
| 169 |
.collect(); |
| 170 |
Ok((out, outside.len())) |
| 171 |
} |
| 172 |
|
| 7fff30c4 Andy McCall ↶ |
173 |
|
| 174 |
|
| 175 |
|
| 176 |
pub fn parse(text: &str) -> Result<(Vec<FileCoverage>, usize, &'static str), String> { |
| 177 |
if text.trim_start().starts_with('<') { |
| 178 |
parse_cobertura(text).map(|(f, o)| (f, o, "cobertura")) |
| 179 |
} else { |
| 180 |
parse_lcov(text).map(|(f, o)| (f, o, "lcov")) |
| 181 |
} |
| 182 |
} |
| 183 |
|
| 184 |
fn xml_attr(e: &quick_xml::events::BytesStart, name: &str) -> String { |
| 185 |
e.try_get_attribute(name) |
| 186 |
.ok() |
| 187 |
.flatten() |
| 188 |
.and_then(|a| a.normalized_value(quick_xml::XmlVersion::Implicit1_0).ok().map(|v| v.into_owned())) |
| 189 |
.unwrap_or_default() |
| 190 |
} |
| 191 |
|
| 192 |
|
| 193 |
|
| 194 |
|
| 195 |
|
| 196 |
|
| 197 |
|
| 198 |
|
| 199 |
pub fn parse_cobertura(text: &str) -> Result<(Vec<FileCoverage>, usize), String> { |
| 200 |
use quick_xml::events::Event; |
| 201 |
let mut r = quick_xml::Reader::from_str(text); |
| 202 |
let mut sources: Vec<String> = Vec::new(); |
| 203 |
let mut in_source = false; |
| 204 |
let mut source_text = String::new(); |
| 205 |
|
| 206 |
let mut raw: BTreeMap<String, Acc> = BTreeMap::new(); |
| 207 |
let mut file: Option<String> = None; |
| 208 |
let mut method: Option<(String, bool)> = None; |
| 209 |
let mut seen_root = false; |
| 210 |
loop { |
| 211 |
let ev = r.read_event().map_err(|e| format!("this is not a Cobertura report: {e}"))?; |
| 212 |
match ev { |
| 213 |
Event::Start(ref e) | Event::Empty(ref e) => { |
| 214 |
let tag = e.local_name().as_ref().to_string(); |
| 215 |
match tag.as_str() { |
| 216 |
"coverage" => seen_root = true, |
| 217 |
"source" if matches!(ev, Event::Start(_)) => { |
| 218 |
in_source = true; |
| 219 |
source_text.clear(); |
| 220 |
} |
| 221 |
"class" => { |
| 222 |
let f = xml_attr(e, "filename"); |
| 223 |
raw.entry(f.clone()).or_default().records += 1; |
| 224 |
file = Some(f); |
| 225 |
} |
| 226 |
"method" => method = Some((xml_attr(e, "name") + &xml_attr(e, "signature"), false)), |
| 227 |
"line" => { |
| 228 |
let Some(f) = &file else { continue }; |
| 229 |
let Ok(n) = xml_attr(e, "number").trim().parse::<u32>() else { continue }; |
| 230 |
let hits = xml_attr(e, "hits").trim().parse::<u64>().unwrap_or(0); |
| 231 |
if let Some((_, hit)) = &mut method { |
| 232 |
*hit |= hits > 0; |
| 233 |
|
| 234 |
continue; |
| 235 |
} |
| 236 |
let acc = raw.entry(f.clone()).or_default(); |
| 237 |
*acc.lines.entry(n).or_default() += hits; |
| 238 |
if xml_attr(e, "branch") == "true" { |
| 239 |
|
| 240 |
let cc = xml_attr(e, "condition-coverage"); |
| 241 |
if let Some((hit, total)) = cc |
| 242 |
.split_once('(') |
| 243 |
.and_then(|(_, rest)| rest.trim_end_matches(')').split_once('/')) |
| 244 |
.and_then(|(h, t)| Some((h.trim().parse::<u64>().ok()?, t.trim().parse::<u64>().ok()?))) |
| 245 |
{ |
| 246 |
for i in 0..total { |
| 247 |
let b = acc.branches.entry((n, "0".into(), i.to_string())).or_default(); |
| 248 |
*b = (*b).max(u64::from(i < hit)); |
| 249 |
} |
| 250 |
} |
| 251 |
} |
| 252 |
} |
| 253 |
_ => {} |
| 254 |
} |
| 255 |
if matches!(ev, Event::Empty(_)) && tag == "method" { |
| 256 |
if let (Some(f), Some((name, hit))) = (&file, method.take()) { |
| 257 |
*raw.entry(f.clone()).or_default().functions.entry(name).or_default() += u64::from(hit); |
| 258 |
} |
| 259 |
} |
| 260 |
} |
| 261 |
Event::Text(t) if in_source => source_text.push_str(&t.xml10_content()), |
| 262 |
Event::End(e) => match e.local_name().as_ref() { |
| 263 |
"source" => { |
| 264 |
in_source = false; |
| 265 |
sources.push(source_text.trim().trim_end_matches('/').to_string()); |
| 266 |
} |
| 267 |
"class" => file = None, |
| 268 |
"method" => { |
| 269 |
if let (Some(f), Some((name, hit))) = (&file, method.take()) { |
| 270 |
*raw.entry(f.clone()).or_default().functions.entry(name).or_default() += u64::from(hit); |
| 271 |
} |
| 272 |
} |
| 273 |
_ => {} |
| 274 |
}, |
| 275 |
Event::Eof => break, |
| 276 |
_ => {} |
| 277 |
} |
| 278 |
} |
| 279 |
if !seen_root { |
| 280 |
return Err("this is not a Cobertura report: no <coverage> element".into()); |
| 281 |
} |
| 282 |
if raw.is_empty() { |
| 283 |
return Err("this Cobertura report names no source file (no <class filename>)".into()); |
| 284 |
} |
| 285 |
|
| 286 |
let resolve = |f: &str| -> Option<String> { |
| 287 |
if f.starts_with('/') { |
| 288 |
return relative(f); |
| 289 |
} |
| 290 |
sources.iter().filter(|s| !s.is_empty() && *s != ".").find_map(|s| relative(&format!("{s}/{f}"))).or_else(|| relative(f)) |
| 291 |
}; |
| 292 |
let mut files: BTreeMap<String, Acc> = BTreeMap::new(); |
| 293 |
let mut outside = HashSet::new(); |
| 294 |
for (f, a) in raw { |
| 295 |
let Some(path) = resolve(&f) else { |
| 296 |
outside.insert(f); |
| 297 |
continue; |
| 298 |
}; |
| 299 |
let into = files.entry(path).or_default(); |
| 300 |
for (l, n) in a.lines { |
| 301 |
*into.lines.entry(l).or_default() += n; |
| 302 |
} |
| 303 |
for (k, n) in a.functions { |
| 304 |
*into.functions.entry(k).or_default() += n; |
| 305 |
} |
| 306 |
for (k, n) in a.branches { |
| 307 |
let b = into.branches.entry(k).or_default(); |
| 308 |
*b = (*b).max(n); |
| 309 |
} |
| 310 |
} |
| 311 |
let out = files |
| 312 |
.into_iter() |
| 313 |
.map(|(path, a)| FileCoverage { |
| 314 |
path, |
| 315 |
functions_found: a.functions.len() as u64, |
| 316 |
functions_hit: a.functions.values().filter(|n| **n > 0).count() as u64, |
| 317 |
branches_found: a.branches.len() as u64, |
| 318 |
branches_hit: a.branches.values().filter(|n| **n > 0).count() as u64, |
| 319 |
lines: a.lines, |
| 320 |
declared_lines: None, |
| 321 |
}) |
| 322 |
.collect(); |
| 323 |
Ok((out, outside.len())) |
| 324 |
} |
| 325 |
|
| 554ccacf Andy McCall ↶ |
326 |
|
| 327 |
pub fn percent(hit: i64, found: i64) -> Option<f64> { |
| 328 |
(found > 0).then(|| (hit as f64 * 1000.0 / found as f64).round() / 10.0) |
| 329 |
} |
| 330 |
|
| 331 |
#[derive(Clone, Debug, sqlx::FromRow)] |
| 332 |
pub struct Report { |
| 333 |
pub id: i64, |
| 334 |
pub repo_id: i64, |
| 40dd3f86 Andy McCall ↶ |
335 |
|
| 336 |
pub run_id: Option<i64>, |
| 337 |
pub job_id: Option<i64>, |
| 554ccacf Andy McCall ↶ |
338 |
pub job: String, |
| 339 |
pub run_number: i64, |
| 340 |
pub bookmark: String, |
| 341 |
pub state: String, |
| 342 |
pub heads: String, |
| 343 |
pub blob: String, |
| 344 |
pub format: String, |
| 345 |
pub lines_found: i64, |
| 346 |
pub lines_hit: i64, |
| 347 |
pub functions_found: i64, |
| 348 |
pub functions_hit: i64, |
| 349 |
pub branches_found: i64, |
| 350 |
pub branches_hit: i64, |
| c987c865 Andy McCall ↶ |
351 |
pub hits: i64, |
| 554ccacf Andy McCall ↶ |
352 |
pub files: i64, |
| 353 |
pub dropped: i64, |
| 354 |
pub created_ms: i64, |
| 40dd3f86 Andy McCall ↶ |
355 |
|
| 356 |
pub uploader: String, |
| 554ccacf Andy McCall ↶ |
357 |
} |
| 358 |
|
| 359 |
impl Report { |
| 40dd3f86 Andy McCall ↶ |
360 |
|
| 361 |
pub fn uploaded(&self) -> bool { |
| 362 |
!self.uploader.is_empty() |
| 363 |
} |
| 364 |
|
| 365 |
|
| 366 |
pub fn source(&self) -> String { |
| 367 |
if self.uploaded() { |
| 368 |
format!("uploaded by {}", self.uploader) |
| 369 |
} else { |
| 370 |
format!("run #{}", self.run_number) |
| 371 |
} |
| 372 |
} |
| 373 |
|
| c987c865 Andy McCall ↶ |
374 |
|
| 375 |
pub fn hits_per_line(&self) -> Option<f64> { |
| 376 |
(self.lines_found > 0).then(|| self.hits as f64 / self.lines_found as f64) |
| 377 |
} |
| 378 |
|
| 554ccacf Andy McCall ↶ |
379 |
pub fn percent(&self) -> Option<f64> { |
| 380 |
percent(self.lines_hit, self.lines_found) |
| 381 |
} |
| 382 |
|
| 383 |
pub fn functions_percent(&self) -> Option<f64> { |
| 384 |
percent(self.functions_hit, self.functions_found) |
| 385 |
} |
| 386 |
|
| 387 |
pub fn branches_percent(&self) -> Option<f64> { |
| 388 |
percent(self.branches_hit, self.branches_found) |
| 389 |
} |
| 390 |
|
| 391 |
pub fn head_list(&self) -> Vec<&str> { |
| 392 |
self.heads.split(',').filter(|h| !h.is_empty()).collect() |
| 393 |
} |
| 394 |
} |
| 395 |
|
| 396 |
#[derive(Clone, Debug, sqlx::FromRow)] |
| 397 |
pub struct FileRow { |
| 398 |
pub report_id: i64, |
| 399 |
pub path: String, |
| 400 |
pub lines_found: i64, |
| 401 |
pub lines_hit: i64, |
| 402 |
pub functions_found: i64, |
| 403 |
pub functions_hit: i64, |
| 404 |
pub branches_found: i64, |
| 405 |
pub branches_hit: i64, |
| 406 |
} |
| 407 |
|
| 408 |
impl FileRow { |
| 409 |
pub fn percent(&self) -> Option<f64> { |
| 410 |
percent(self.lines_hit, self.lines_found) |
| 411 |
} |
| 412 |
|
| 413 |
pub fn missed(&self) -> i64 { |
| 414 |
self.lines_found - self.lines_hit |
| 415 |
} |
| 416 |
} |
| 417 |
|
| 418 |
|
| 419 |
|
| 420 |
|
| 421 |
static HAS: Mutex<Option<HashSet<String>>> = Mutex::new(None); |
| 422 |
|
| 423 |
fn key(app: &Shared, repo_id: i64) -> String { |
| 424 |
format!("{}#{repo_id}", app.repos.root().display()) |
| 425 |
} |
| 426 |
|
| 427 |
pub fn has_reports(app: &Shared, repo_id: i64) -> bool { |
| 428 |
HAS.lock().unwrap_or_else(|p| p.into_inner()).as_ref().is_some_and(|s| s.contains(&key(app, repo_id))) |
| 429 |
} |
| 430 |
|
| 431 |
fn mark(app: &Shared, repo_id: i64) { |
| 432 |
HAS.lock().unwrap_or_else(|p| p.into_inner()).get_or_insert_with(HashSet::new).insert(key(app, repo_id)); |
| 433 |
} |
| 434 |
|
| 435 |
|
| 436 |
pub async fn load(app: &Shared) -> sqlx::Result<()> { |
| 437 |
let ids: Vec<(i64,)> = sqlx::query_as("SELECT DISTINCT repo_id FROM coverage_reports").fetch_all(&app.db).await?; |
| 438 |
for (id,) in ids { |
| 439 |
mark(app, id); |
| 440 |
} |
| 441 |
Ok(()) |
| 442 |
} |
| 443 |
|
| 444 |
|
| 445 |
pub struct Origin<'a> { |
| 446 |
pub repo_id: i64, |
| 40dd3f86 Andy McCall ↶ |
447 |
|
| 448 |
pub run_id: Option<i64>, |
| 554ccacf Andy McCall ↶ |
449 |
pub run_number: i64, |
| 40dd3f86 Andy McCall ↶ |
450 |
pub job_id: Option<i64>, |
| 451 |
pub uploader: &'a str, |
| 554ccacf Andy McCall ↶ |
452 |
pub job: &'a str, |
| 453 |
pub bookmark: &'a str, |
| 454 |
pub state: &'a str, |
| 455 |
pub heads: &'a [String], |
| 456 |
pub blob: &'a str, |
| 7fff30c4 Andy McCall ↶ |
457 |
|
| 458 |
pub format: &'a str, |
| 554ccacf Andy McCall ↶ |
459 |
} |
| 460 |
|
| 461 |
|
| 462 |
|
| 463 |
pub async fn keep(app: &Shared, o: &Origin<'_>, files: Vec<FileCoverage>, outside: usize, in_state: &HashSet<String>) -> sqlx::Result<i64> { |
| 464 |
let (kept, missing): (Vec<FileCoverage>, Vec<FileCoverage>) = files.into_iter().partition(|f| in_state.contains(&f.path)); |
| 465 |
let sum = |f: &dyn Fn(&FileCoverage) -> u64| kept.iter().map(f).sum::<u64>() as i64; |
| 466 |
let mut tx = crate::db::begin_write(&app.db).await?; |
| 40dd3f86 Andy McCall ↶ |
467 |
if let Some(job) = o.job_id { |
| 5d90e0e0 Andy McCall |
468 |
sqlx::query("DELETE FROM coverage_reports WHERE job_id = $1").bind(job).execute(&mut *tx).await?; |
| 40dd3f86 Andy McCall ↶ |
469 |
} |
| 554ccacf Andy McCall ↶ |
470 |
let id: i64 = sqlx::query_scalar( |
| 471 |
"INSERT INTO coverage_reports (repo_id, run_id, job_id, job, run_number, bookmark, state, heads, blob, format, \ |
| 40dd3f86 Andy McCall ↶ |
472 |
lines_found, lines_hit, functions_found, functions_hit, branches_found, branches_hit, hits, files, dropped, created_ms, uploader) \ |
| 5d90e0e0 Andy McCall |
473 |
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21) RETURNING id", |
| 554ccacf Andy McCall ↶ |
474 |
) |
| 475 |
.bind(o.repo_id) |
| 476 |
.bind(o.run_id) |
| 477 |
.bind(o.job_id) |
| 478 |
.bind(o.job) |
| 479 |
.bind(o.run_number) |
| 480 |
.bind(o.bookmark) |
| 481 |
.bind(o.state) |
| 482 |
.bind(o.heads.join(",")) |
| 483 |
.bind(o.blob) |
| 7fff30c4 Andy McCall ↶ |
484 |
.bind(o.format) |
| 554ccacf Andy McCall ↶ |
485 |
.bind(sum(&|f| f.lines_found())) |
| 486 |
.bind(sum(&|f| f.lines_hit())) |
| 487 |
.bind(sum(&|f| f.functions_found)) |
| 488 |
.bind(sum(&|f| f.functions_hit)) |
| 489 |
.bind(sum(&|f| f.branches_found)) |
| 490 |
.bind(sum(&|f| f.branches_hit)) |
| c987c865 Andy McCall ↶ |
491 |
.bind(kept.iter().fold(0u64, |a, f| a.saturating_add(f.hits())).min(i64::MAX as u64) as i64) |
| 554ccacf Andy McCall ↶ |
492 |
.bind(kept.len() as i64) |
| 493 |
.bind((missing.len() + outside) as i64) |
| 494 |
.bind(now_ms()) |
| 40dd3f86 Andy McCall ↶ |
495 |
.bind(o.uploader) |
| 554ccacf Andy McCall ↶ |
496 |
.fetch_one(&mut *tx) |
| 497 |
.await?; |
| 498 |
for f in &kept { |
| 499 |
sqlx::query( |
| 500 |
"INSERT INTO coverage_files (report_id, path, lines_found, lines_hit, functions_found, functions_hit, branches_found, branches_hit) \ |
| 5d90e0e0 Andy McCall |
501 |
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)", |
| 554ccacf Andy McCall ↶ |
502 |
) |
| 503 |
.bind(id) |
| 504 |
.bind(&f.path) |
| 505 |
.bind(f.lines_found() as i64) |
| 506 |
.bind(f.lines_hit() as i64) |
| 507 |
.bind(f.functions_found as i64) |
| 508 |
.bind(f.functions_hit as i64) |
| 509 |
.bind(f.branches_found as i64) |
| 510 |
.bind(f.branches_hit as i64) |
| 511 |
.execute(&mut *tx) |
| 512 |
.await?; |
| 513 |
} |
| 514 |
tx.commit().await?; |
| 515 |
mark(app, o.repo_id); |
| 516 |
Ok(id) |
| 517 |
} |
| 518 |
|
| 519 |
pub async fn report(pool: &Pool, repo_id: i64, id: i64) -> sqlx::Result<Option<Report>> { |
| 5d90e0e0 Andy McCall |
520 |
sqlx::query_as("SELECT * FROM coverage_reports WHERE id = $1 AND repo_id = $2").bind(id).bind(repo_id).fetch_optional(pool).await |
| 554ccacf Andy McCall ↶ |
521 |
} |
| 522 |
|
| 523 |
|
| 524 |
pub async fn on_bookmark(pool: &Pool, repo_id: i64, bookmark: &str, limit: i64) -> sqlx::Result<Vec<Report>> { |
| 5d90e0e0 Andy McCall |
525 |
sqlx::query_as("SELECT * FROM coverage_reports WHERE repo_id = $1 AND bookmark = $2 ORDER BY created_ms DESC, id DESC LIMIT $3") |
| 554ccacf Andy McCall ↶ |
526 |
.bind(repo_id) |
| 527 |
.bind(bookmark) |
| 528 |
.bind(limit) |
| c987c865 Andy McCall ↶ |
529 |
.fetch_all(pool) |
| 530 |
.await |
| 531 |
} |
| 532 |
|
| 533 |
|
| 534 |
pub async fn first_ms(pool: &Pool, repo_id: i64) -> sqlx::Result<Option<i64>> { |
| 5d90e0e0 Andy McCall |
535 |
sqlx::query_scalar("SELECT MIN(created_ms) FROM coverage_reports WHERE repo_id = $1").bind(repo_id).fetch_one(pool).await |
| c987c865 Andy McCall ↶ |
536 |
} |
| 537 |
|
| 538 |
|
| 539 |
pub async fn bookmarks(pool: &Pool, repo_id: i64) -> sqlx::Result<Vec<String>> { |
| 5d90e0e0 Andy McCall |
540 |
sqlx::query_scalar("SELECT bookmark FROM coverage_reports WHERE repo_id = $1 GROUP BY bookmark ORDER BY MAX(created_ms) DESC") |
| c987c865 Andy McCall ↶ |
541 |
.bind(repo_id) |
| 554ccacf Andy McCall ↶ |
542 |
.fetch_all(pool) |
| 543 |
.await |
| 544 |
} |
| 545 |
|
| 7edaff01 Andy McCall ↶ |
546 |
|
| 547 |
#[derive(Clone, Copy, Debug, Default, PartialEq)] |
| 548 |
pub struct Rules { |
| 549 |
|
| 550 |
pub min: Option<f64>, |
| 551 |
|
| 552 |
pub max_drop: Option<f64>, |
| 553 |
} |
| 554 |
|
| 555 |
pub async fn rules(pool: &Pool, repo_id: i64) -> sqlx::Result<Rules> { |
| 556 |
let row: Option<(Option<f64>, Option<f64>)> = |
| 5d90e0e0 Andy McCall |
557 |
sqlx::query_as("SELECT min, max_drop FROM coverage_settings WHERE repo_id = $1").bind(repo_id).fetch_optional(pool).await?; |
| 7edaff01 Andy McCall ↶ |
558 |
Ok(row.map(|(min, max_drop)| Rules { min, max_drop }).unwrap_or_default()) |
| 559 |
} |
| 560 |
|
| 561 |
pub async fn set_rules(pool: &Pool, repo_id: i64, r: Rules) -> sqlx::Result<()> { |
| 562 |
sqlx::query( |
| 5d90e0e0 Andy McCall |
563 |
"INSERT INTO coverage_settings (repo_id, min, max_drop) VALUES ($1, $2, $3) \ |
| 7edaff01 Andy McCall ↶ |
564 |
ON CONFLICT (repo_id) DO UPDATE SET min = excluded.min, max_drop = excluded.max_drop", |
| 565 |
) |
| 566 |
.bind(repo_id) |
| 567 |
.bind(r.min) |
| 568 |
.bind(r.max_drop) |
| 569 |
.execute(pool) |
| 570 |
.await?; |
| 571 |
Ok(()) |
| 572 |
} |
| 573 |
|
| 574 |
|
| 575 |
|
| 576 |
pub async fn baseline(pool: &Pool, r: &Report, default_bookmark: &str) -> sqlx::Result<Option<Report>> { |
| 577 |
sqlx::query_as( |
| 5d90e0e0 Andy McCall |
578 |
"SELECT * FROM coverage_reports WHERE repo_id = $1 AND bookmark = $2 AND id <> $3 AND (created_ms < $4 OR (created_ms = $5 AND id < $6)) \ |
| 7edaff01 Andy McCall ↶ |
579 |
ORDER BY created_ms DESC, id DESC LIMIT 1", |
| 580 |
) |
| 581 |
.bind(r.repo_id) |
| 582 |
.bind(default_bookmark) |
| 583 |
.bind(r.id) |
| 584 |
.bind(r.created_ms) |
| 585 |
.bind(r.created_ms) |
| 586 |
.bind(r.id) |
| 587 |
.fetch_optional(pool) |
| 588 |
.await |
| 589 |
} |
| 590 |
|
| 591 |
|
| 592 |
pub fn verdict(r: &Report, base: Option<&Report>, base_name: &str, rules: Rules) -> (&'static str, String) { |
| 593 |
let Some(p) = r.percent() else { return ("passed", "no instrumented lines".into()) }; |
| 594 |
let delta = base.and_then(|b| Some(p - b.percent()?)); |
| 595 |
let against = match delta { |
| 596 |
Some(d) if d.abs() < 0.05 => format!(", unchanged against {base_name}"), |
| 597 |
Some(d) => format!(" ({d:+.1} against {base_name})"), |
| 598 |
None => String::new(), |
| 599 |
}; |
| 600 |
if let Some(min) = rules.min.filter(|m| p < *m) { |
| 601 |
return ("failed", format!("{p:.1}%{against}: below the minimum of {min}%")); |
| 602 |
} |
| 603 |
if let (Some(max), Some(d)) = (rules.max_drop, delta) { |
| 604 |
if d < -max { |
| 605 |
return ("failed", format!("{p:.1}%{against}: falls more than the {max} points allowed")); |
| 606 |
} |
| 607 |
} |
| 608 |
("passed", format!("{p:.1}%{against}")) |
| 609 |
} |
| 610 |
|
| 554ccacf Andy McCall ↶ |
611 |
pub async fn for_run(pool: &Pool, run_id: i64) -> sqlx::Result<Vec<Report>> { |
| 5d90e0e0 Andy McCall |
612 |
sqlx::query_as("SELECT * FROM coverage_reports WHERE run_id = $1 ORDER BY job").bind(run_id).fetch_all(pool).await |
| 554ccacf Andy McCall ↶ |
613 |
} |
| 614 |
|
| 615 |
pub async fn files(pool: &Pool, report_id: i64) -> sqlx::Result<Vec<FileRow>> { |
| 5d90e0e0 Andy McCall |
616 |
sqlx::query_as("SELECT * FROM coverage_files WHERE report_id = $1 ORDER BY path").bind(report_id).fetch_all(pool).await |
| 554ccacf Andy McCall ↶ |
617 |
} |
| 618 |
|
| 619 |
#[cfg(test)] |
| 620 |
mod tests { |
| 621 |
use super::*; |
| 622 |
|
| 623 |
const LCOV: &str = "TN:\nSF:/src/crates/a/src/lib.rs\nFN:3,alpha\nFN:9,beta\nFNDA:4,alpha\nFNDA:0,beta\nFNF:2\nFNH:1\n\ |
| 624 |
DA:3,4\nDA:4,4\nDA:9,0\nDA:10,0\nBRDA:4,0,0,3\nBRDA:4,0,1,-\nBRF:2\nBRH:1\nLF:4\nLH:2\nend_of_record\n\ |
| 625 |
SF:/src/crates/a/src/lib.rs\nDA:9,1\nend_of_record\n\ |
| 626 |
SF:./README.md\nDA:1,1\nend_of_record\n\ |
| 627 |
SF:/home/runner/.cargo/registry/src/dep/lib.rs\nDA:1,1\nend_of_record\n"; |
| 628 |
|
| 629 |
#[test] |
| 630 |
fn lcov_reports_are_read_and_merged() { |
| 631 |
let (files, outside) = parse_lcov(LCOV).unwrap(); |
| 632 |
assert_eq!(outside, 1, "the dependency outside the workspace"); |
| 633 |
assert_eq!(files.len(), 2); |
| 634 |
let lib = &files[1]; |
| 635 |
assert_eq!(lib.path, "crates/a/src/lib.rs"); |
| 636 |
assert_eq!(lib.lines, [(3, 4), (4, 4), (9, 1), (10, 0)].into_iter().collect()); |
| 637 |
assert_eq!((lib.lines_found(), lib.lines_hit()), (4, 3), "the second record ran line 9"); |
| 638 |
assert_eq!((lib.functions_found, lib.functions_hit), (2, 1)); |
| 639 |
assert_eq!((lib.branches_found, lib.branches_hit), (2, 1)); |
| 640 |
assert_eq!(files[0].path, "README.md"); |
| 641 |
assert_eq!(lib.declared_lines, None, "two records: counted from the lines"); |
| 642 |
|
| 643 |
let (one, _) = parse_lcov("SF:/src/a.rs\nDA:1,1\nDA:2,0\nLF:5\nLH:3\nend_of_record\n").unwrap(); |
| 644 |
assert_eq!((one[0].lines_found(), one[0].lines_hit()), (5, 3)); |
| 645 |
assert!(parse_lcov("not a report\n").unwrap_err().contains("not an LCOV report")); |
| 7edaff01 Andy McCall ↶ |
646 |
} |
| 647 |
|
| 648 |
#[test] |
| 649 |
fn the_check_follows_the_rules() { |
| 650 |
let report = |pct_hit: i64| Report { |
| 651 |
id: 2, |
| 652 |
repo_id: 1, |
| 40dd3f86 Andy McCall ↶ |
653 |
run_id: Some(1), |
| 654 |
job_id: Some(1), |
| 7edaff01 Andy McCall ↶ |
655 |
job: "test".into(), |
| 656 |
run_number: 1, |
| 657 |
bookmark: "feature".into(), |
| 658 |
state: String::new(), |
| 659 |
heads: String::new(), |
| 660 |
blob: String::new(), |
| 661 |
format: "lcov".into(), |
| 662 |
lines_found: 1000, |
| 663 |
lines_hit: pct_hit, |
| 664 |
functions_found: 0, |
| 665 |
functions_hit: 0, |
| 666 |
branches_found: 0, |
| 667 |
branches_hit: 0, |
| 668 |
hits: 0, |
| 669 |
files: 1, |
| 670 |
dropped: 0, |
| 671 |
created_ms: 0, |
| 40dd3f86 Andy McCall ↶ |
672 |
uploader: String::new(), |
| 7edaff01 Andy McCall ↶ |
673 |
}; |
| 674 |
let (now, before) = (report(819), report(822)); |
| 675 |
let none = Rules::default(); |
| 676 |
assert_eq!(verdict(&now, Some(&before), "main", none), ("passed", "81.9% (-0.3 against main)".to_string())); |
| 677 |
assert_eq!(verdict(&now, None, "main", none), ("passed", "81.9%".to_string())); |
| 678 |
assert_eq!(verdict(&now, Some(&now), "main", none).1, "81.9%, unchanged against main"); |
| 679 |
let strict = Rules { min: Some(85.0), max_drop: None }; |
| 680 |
assert_eq!( |
| 681 |
verdict(&now, Some(&before), "main", strict), |
| 682 |
("failed", "81.9% (-0.3 against main): below the minimum of 85%".to_string()) |
| 683 |
); |
| 684 |
let drop = Rules { min: None, max_drop: Some(0.2) }; |
| 685 |
assert_eq!(verdict(&now, Some(&before), "main", drop).0, "failed"); |
| 686 |
assert_eq!(verdict(&now, Some(&before), "main", Rules { min: None, max_drop: Some(0.5) }).0, "passed"); |
| 554ccacf Andy McCall ↶ |
687 |
} |
| 688 |
|
| 689 |
#[test] |
| 690 |
fn paths_are_taken_relative_to_the_workspace() { |
| 691 |
assert_eq!(relative("/src/a/b.rs").as_deref(), Some("a/b.rs")); |
| 692 |
assert_eq!(relative("./a/b.rs").as_deref(), Some("a/b.rs")); |
| 693 |
assert_eq!(relative("a/b.rs").as_deref(), Some("a/b.rs")); |
| 694 |
for bad in ["/etc/passwd", "a/../b", "", "/src/", "a//b", "C:\\x\\y.rs"] { |
| 695 |
assert_eq!(relative(bad), None, "{bad}"); |
| 696 |
} |
| 697 |
assert_eq!(percent(1, 3), Some(33.3)); |
| 698 |
assert_eq!(percent(0, 0), None); |
| 7fff30c4 Andy McCall ↶ |
699 |
} |
| 700 |
|
| 701 |
#[test] |
| 702 |
fn cobertura_from_coverage_py_and_coverlet() { |
| 703 |
|
| 704 |
let py = r#"<?xml version="1.0" ?> |
| 705 |
<coverage version="7.4" line-rate="0.6" branch-rate="0.5"> |
| 706 |
<sources><source>/src/app</source></sources> |
| 707 |
<packages><package name="app"><classes> |
| 708 |
<class name="main.py" filename="main.py" line-rate="0.66"> |
| 709 |
<methods/> |
| 710 |
<lines> |
| 711 |
<line number="1" hits="1"/> |
| 712 |
<line number="2" hits="0"/> |
| 713 |
<line number="3" hits="4" branch="true" condition-coverage="50% (1/2)"/> |
| 714 |
</lines> |
| 715 |
</class> |
| 716 |
<class name="gone.py" filename="/usr/lib/python3/x.py"><lines><line number="1" hits="1"/></lines></class> |
| 717 |
</classes></package></packages> |
| 718 |
</coverage>"#; |
| 719 |
let (files, outside, format) = parse(py).unwrap(); |
| 720 |
assert_eq!((format, outside), ("cobertura", 1)); |
| 721 |
let f = &files[0]; |
| 722 |
assert_eq!(f.path, "app/main.py"); |
| 723 |
assert_eq!((f.lines_found(), f.lines_hit(), f.hits()), (3, 2, 5)); |
| 724 |
assert_eq!((f.branches_found, f.branches_hit), (2, 1)); |
| 725 |
|
| 726 |
|
| 727 |
let net = r#"<coverage><sources><source>/src/</source></sources><packages><package name="Lib"><classes> |
| 728 |
<class name="Lib.A" filename="Lib/A.cs"><methods><method name="Run" signature="()"><lines><line number="5" hits="2"/></lines></method><method name="Idle" signature="()"><lines><line number="9" hits="0"/></lines></method></methods> |
| 729 |
<lines><line number="5" hits="2"/><line number="9" hits="0"/></lines></class> |
| 730 |
<class name="Lib.A/Inner" filename="Lib/A.cs"><methods/><lines><line number="12" hits="1"/></lines></class> |
| 731 |
</classes></package></packages></coverage>"#; |
| 732 |
let (files, _, _) = parse(net).unwrap(); |
| 733 |
let f = &files[0]; |
| 734 |
assert_eq!(f.path, "Lib/A.cs"); |
| 735 |
assert_eq!((f.lines_found(), f.lines_hit()), (3, 2)); |
| 736 |
assert_eq!((f.functions_found, f.functions_hit), (2, 1)); |
| 737 |
|
| 738 |
assert!(parse("<html/>").unwrap_err().contains("Cobertura")); |
| 739 |
assert_eq!(parse("SF:/src/a.rs\nDA:1,1\nend_of_record\n").unwrap().2, "lcov"); |
| 554ccacf Andy McCall ↶ |
740 |
} |
| 741 |
} |