OXYGENHUB

Coverage / crates/hub/src/coverage.rs 96.3%

643 of 668 lines run, 116 of 194 functions · run #469 on main · run missed

1
//! Coverage reports (oxygenhub#113): Coveralls built into the hub. An
2
//! OxygenFlow job that declares an artifact named `coverage` in LCOV
3
//! format (what `cargo llvm-cov --lcov`, Istanbul, coverage.py and
4
//! gcov/lcov write) or Cobertura XML has it parsed when it is uploaded. The totals and each
5
//! file's counts are kept per run; the per-line counts are read again from
6
//! the artifact's blob for the file view. Paths are taken relative to the
7
//! job's workspace (`/src`), and only files of the run's state are kept.
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
/// The artifact name a pipeline gives its report.
15
pub const ARTIFACT: &str = "coverage";
16
/// The largest report parsed.
17
pub const MAX_REPORT: usize = 64 << 20;
18
19
/// One file's coverage, from a report.
20
#[derive(Clone, Debug, Default, PartialEq, Eq)]
21
pub struct FileCoverage {
22
    /// Relative to the repository's root.
23
    pub path: String,
24
    /// Each instrumented line and how often it ran, by line number.
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
    /// The file's own `LF`/`LH` totals, when it had one record: the tool's
31
    /// own count, which can name lines the `DA` lines leave out (llvm-cov
32
    /// does), so the hub agrees with what the tool printed.
33
    pub declared_lines: Option<(u64, u64)>,
34
}
35
36
impl FileCoverage {
3711×
    pub fn lines_found(&self) -> u64 {
3811×
        self.declared_lines.map(|d| d.0).unwrap_or(self.lines.len() as u64)
3911×
    }
40
4111×
    pub fn lines_hit(&self) -> u64 {
4237×
        self.declared_lines.map(|d| d.1).unwrap_or_else(|| self.lines.values().filter(|n| **n > 0).count() as u64)
4311×
    }
44
45
    /// Every run of every line, added up.
464×
    pub fn hits(&self) -> u64 {
4715×
        self.lines.values().fold(0u64, |a, n| a.saturating_add(*n))
484×
    }
49
}
50
51
/// A path as a report names it, relative to the repository: the Flow
52
/// workspace's `/src/` and a leading `./` taken off. `None` for a path
53
/// outside the repository.
5429×
pub fn relative(path: &str) -> Option<String> {
5529×
    let p = path.trim();
5629×
    let p = p.strip_prefix("/src/").unwrap_or(p);
5729×
    let p = p.strip_prefix("./").unwrap_or(p);
5841×
    if p.is_empty() || p.starts_with('/') || p.contains('\\') || p.split('/').any(|s| s.is_empty() || s == "." || s == "..") {
5911×
        return None;
6018×
    }
6118×
    Some(p.to_string())
6229×
}
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
/// Parse an LCOV report into each file's coverage, records for the same
76
/// file (from several test binaries) added together. Files whose paths
77
/// are outside the repository are counted in the second value.
789×
pub fn parse_lcov(text: &str) -> Result<(Vec<FileCoverage>, usize), String> {
799×
    let mut files: BTreeMap<String, Acc> = BTreeMap::new();
809×
    let mut current: Option<Option<String>> = None;
819×
    let mut outside = HashSet::new();
829×
    let mut records = 0usize;
83
    // A new SF: record has begun and not yet been counted for its file.
849×
    let mut started = false;
8546×
    let num = |s: &str| s.trim().parse::<u64>().unwrap_or(0);
8699×
    for line in text.lines() {
8799×
        let line = line.trim();
8899×
        if let Some(path) = line.strip_prefix("SF:") {
8917×
            records += 1;
9017×
            let rel = relative(path);
9117×
            if rel.is_none() {
924×
                outside.insert(path.to_string());
9313×
            }
9417×
            current = Some(rel);
9517×
            started = true;
9617×
            continue;
9782×
        }
9882×
        if line == "end_of_record" {
9917×
            current = None;
10017×
            continue;
10165×
        }
10259×
        let Some(Some(path)) = &current else { continue };
10355×
        let acc = files.entry(path.clone()).or_default();
10455×
        if line == "TN:" || line.starts_with("TN:") {
1050×
            continue;
10655×
        }
10755×
        if std::mem::take(&mut started) {
10813×
            acc.records += 1;
10942×
        }
11055×
        if let Some(n) = line.strip_prefix("LF:") {
1112×
            acc.declared_lines.0 = Some(num(n));
11253×
        } else if let Some(n) = line.strip_prefix("LH:") {
1132×
            acc.declared_lines.1 = Some(num(n));
11451×
        } else if let Some(rest) = line.strip_prefix("DA:") {
11529×
            let mut parts = rest.split(',');
11629×
            if let (Some(l), Some(n)) = (parts.next(), parts.next()) {
11729×
                if let Ok(l) = l.trim().parse::<u32>() {
11829×
                    *acc.lines.entry(l).or_default() += num(n);
11929×
                }
1200×
            }
12122×
        } else if let Some(rest) = line.strip_prefix("FN:") {
1228×
            if let Some((_, name)) = rest.split_once(',') {
1238×
                acc.functions.entry(name.to_string()).or_default();
1248×
            }
12514×
        } else if let Some(rest) = line.strip_prefix("FNDA:") {
1268×
            if let Some((n, name)) = rest.split_once(',') {
1278×
                *acc.functions.entry(name.to_string()).or_default() += num(n);
1288×
            }
1296×
        } else if let Some(rest) = line.strip_prefix("BRDA:") {
1302×
            let parts: Vec<&str> = rest.split(',').collect();
1312×
            if let [l, block, branch, taken] = parts[..] {
1322×
                if let Ok(l) = l.trim().parse::<u32>() {
1332×
                    let taken = if taken.trim() == "-" { 0 } else { num(taken) };
1342×
                    *acc.branches.entry((l, block.to_string(), branch.to_string())).or_default() += taken;
1350×
                }
1360×
            }
1374×
        } else if let Some(n) = line.strip_prefix("FNF:") {
1381×
            acc.declared_fn.0 = acc.declared_fn.0.max(num(n));
1393×
        } else if let Some(n) = line.strip_prefix("FNH:") {
1401×
            acc.declared_fn.1 = acc.declared_fn.1.max(num(n));
1412×
        } else if let Some(n) = line.strip_prefix("BRF:") {
1421×
            acc.declared_br.0 = acc.declared_br.0.max(num(n));
1431×
        } else if let Some(n) = line.strip_prefix("BRH:") {
1441×
            acc.declared_br.1 = acc.declared_br.1.max(num(n));
1451×
        }
146
    }
1479×
    if records == 0 {
1482×
        return Err("this is not an LCOV report: it names no source file (no SF: line)".into());
1497×
    }
1507×
    let out = files
1517×
        .into_iter()
15212×
        .map(|(path, a)| {
15312×
            let (functions_found, functions_hit) = if a.functions.is_empty() {
1548×
                a.declared_fn
155
            } else {
1568×
                (a.functions.len() as u64, a.functions.values().filter(|n| **n > 0).count() as u64)
157
            };
15812×
            let (branches_found, branches_hit) = if a.branches.is_empty() {
15911×
                a.declared_br
160
            } else {
1612×
                (a.branches.len() as u64, a.branches.values().filter(|n| **n > 0).count() as u64)
162
            };
16312×
            let declared_lines = match (a.records, a.declared_lines) {
1641×
                (1, (Some(f), Some(h))) if h <= f && f >= a.lines.len() as u64 => Some((f, h)),
16511×
                _ => None,
166
            };
16712×
            FileCoverage { path, lines: a.lines, functions_found, functions_hit, branches_found, branches_hit, declared_lines }
16812×
        })
1697×
        .collect();
1707×
    Ok((out, outside.len()))
1719×
}
172
173
/// Parse a report in any format the hub reads: JaCoCo XML (a `<report>`),
174
/// Cobertura XML (a `<coverage>`) or LCOV. Returns the files, those outside
175
/// the repository, and the format's name.
17610×
pub fn parse(text: &str) -> Result<(Vec<FileCoverage>, usize, &'static str), String> {
17710×
    let t = text.trim_start();
17810×
    if t.starts_with('<') && root_element(t).as_deref() == Some("report") {
1791×
        parse_jacoco(text).map(|(f, o)| (f, o, "jacoco"))
1809×
    } else if t.starts_with('<') {
1813×
        parse_cobertura(text).map(|(f, o)| (f, o, "cobertura"))
182
    } else {
1836×
        parse_lcov(text).map(|(f, o)| (f, o, "lcov"))
184
    }
18510×
}
186
187
/// The name of an XML document's first element.
1884×
fn root_element(text: &str) -> Option<String> {
189
    use quick_xml::events::Event;
1904×
    let mut r = quick_xml::Reader::from_str(text);
191
    loop {
1928×
        match r.read_event().ok()? {
1934×
            Event::Start(e) | Event::Empty(e) => return Some(e.local_name().as_ref().to_string()),
1940×
            Event::Eof => return None,
1954×
            _ => {}
196
        }
197
    }
1984×
}
199
200
/// Parse a JaCoCo XML report (Gradle's `jacocoTestReport`, Kotlin's Kover;
201
/// oxygenhub#308): each `<package name>`'s `<sourcefile name>` with its
202
/// `<line nr mi ci mb cb>` (hit when any of the line's instructions ran;
203
/// its branches missed and covered), and each `<class sourcefilename>`'s
204
/// `<method>`s as functions, hit when their METHOD counter says so. Paths
205
/// are the package's, relative to a source root (`io/oxygenhub/api/X.kt`);
206
/// [`keep`] finds them in the state by their ending.
2072×
pub fn parse_jacoco(text: &str) -> Result<(Vec<FileCoverage>, usize), String> {
208
    use quick_xml::events::Event;
2092×
    let mut r = quick_xml::Reader::from_str(text);
2102×
    let mut files: BTreeMap<String, Acc> = BTreeMap::new();
2112×
    let mut package = String::new();
2122×
    let mut sourcefile: Option<String> = None;
2132×
    let mut class_file: Option<String> = None;
2142×
    let mut method: Option<(String, bool)> = None;
2152×
    let mut seen_root = false;
2162×
    let path = |package: &str, name: &str| if package.is_empty() { name.to_string() } else { format!("{package}/{name}") };
217
    loop {
21826×
        let ev = r.read_event().map_err(|e| format!("this is not a JaCoCo report: {e}"))?;
21926×
        match ev {
2208×
            Event::Start(ref e) | Event::Empty(ref e) => {
22115×
                let tag = e.local_name().as_ref().to_string();
22215×
                match tag.as_str() {
22315×
                    "report" => seen_root = true,
22413×
                    "package" => package = xml_attr(e, "name").trim_matches('/').to_string(),
22512×
                    "class" => {
2261×
                        let f = xml_attr(e, "sourcefilename");
2271×
                        class_file = (!f.is_empty()).then(|| path(&package, &f));
228
                    }
22911×
                    "method" if class_file.is_some() => method = Some((xml_attr(e, "name") + &xml_attr(e, "desc"), false)),
2309×
                    "counter" => {
2314×
                        if let Some((_, hit)) = &mut method {
2323×
                            if xml_attr(e, "type") == "METHOD" {
2332×
                                *hit |= xml_attr(e, "covered").trim().parse::<u64>().unwrap_or(0) > 0;
2342×
                            }
2351×
                        }
236
                    }
2375×
                    "sourcefile" => {
2381×
                        let f = path(&package, &xml_attr(e, "name"));
2391×
                        files.entry(f.clone()).or_default().records += 1;
2401×
                        sourcefile = Some(f);
2411×
                    }
2424×
                    "line" => {
2433×
                        let Some(f) = &sourcefile else { continue };
2443×
                        let Ok(n) = xml_attr(e, "nr").trim().parse::<u32>() else { continue };
2459×
                        let num = |a: &str| xml_attr(e, a).trim().parse::<u64>().unwrap_or(0);
2463×
                        let acc = files.entry(f.clone()).or_default();
2473×
                        *acc.lines.entry(n).or_default() += num("ci");
2483×
                        let (missed, covered) = (num("mb"), num("cb"));
2493×
                        for i in 0..missed + covered {
2502×
                            let b = acc.branches.entry((n, "0".into(), i.to_string())).or_default();
2512×
                            *b = (*b).max(u64::from(i < covered));
2522×
                        }
253
                    }
2541×
                    _ => {}
255
                }
25615×
                if matches!(ev, Event::Empty(_)) && tag == "method" {
2570×
                    if let (Some(f), Some((name, hit))) = (&class_file, method.take()) {
2580×
                        *files.entry(f.clone()).or_default().functions.entry(name).or_default() += u64::from(hit);
2590×
                    }
26015×
                }
261
            }
2627×
            Event::End(e) => match e.local_name().as_ref() {
2637×
                "package" => package.clear(),
2646×
                "sourcefile" => sourcefile = None,
2655×
                "class" => class_file = None,
2664×
                "method" => {
2672×
                    if let (Some(f), Some((name, hit))) = (&class_file, method.take()) {
2682×
                        *files.entry(f.clone()).or_default().functions.entry(name).or_default() += u64::from(hit);
2692×
                    }
270
                }
2712×
                _ => {}
272
            },
2732×
            Event::Eof => break,
2742×
            _ => {}
275
        }
276
    }
2772×
    if !seen_root {
2780×
        return Err("this is not a JaCoCo report: no <report> element".into());
2792×
    }
2802×
    let out: Vec<FileCoverage> = files
2812×
        .into_iter()
2822×
        .filter(|(_, a)| a.records > 0)
2832×
        .map(|(path, a)| FileCoverage {
2841×
            path,
2851×
            functions_found: a.functions.len() as u64,
2862×
            functions_hit: a.functions.values().filter(|n| **n > 0).count() as u64,
2871×
            branches_found: a.branches.len() as u64,
2882×
            branches_hit: a.branches.values().filter(|n| **n > 0).count() as u64,
2891×
            lines: a.lines,
2901×
            declared_lines: None,
2911×
        })
2922×
        .collect();
2932×
    if out.is_empty() {
2941×
        return Err("this JaCoCo report names no source file (no <sourcefile>)".into());
2951×
    }
2961×
    Ok((out, 0))
2972×
}
298
299
/// A report's path that is not in the state, matched by its ending to the
300
/// one file of the state it can be (a JaCoCo or JVM Cobertura path is
301
/// relative to a source root, `app/src/main/java`); left as it is when
302
/// none or several match.
3035×
pub fn resolve_endings(files: Vec<FileCoverage>, in_state: &HashSet<String>) -> Vec<FileCoverage> {
3045×
    files
3055×
        .into_iter()
3068×
        .map(|mut f| {
3078×
            if !in_state.contains(&f.path) {
3085×
                let tail = format!("/{}", f.path);
30914×
                let mut found = in_state.iter().filter(|p| p.ends_with(&tail));
3105×
                if let (Some(p), None) = (found.next(), found.next()) {
3111×
                    f.path = p.clone();
3124×
                }
3133×
            }
3148×
            f
3158×
        })
3165×
        .collect()
3175×
}
318
31958×
fn xml_attr(e: &quick_xml::events::BytesStart, name: &str) -> String {
32058×
    e.try_get_attribute(name)
32158×
        .ok()
32258×
        .flatten()
32358×
        .and_then(|a| a.normalized_value(quick_xml::XmlVersion::Implicit1_0).ok().map(|v| v.into_owned()))
32458×
        .unwrap_or_default()
32558×
}
326
327
/// Parse a Cobertura XML report (coverage.py `coverage xml`, JaCoCo via
328
/// cover2cover, .NET Coverlet, `cargo llvm-cov --cobertura`): each
329
/// `<class>`'s `<line number hits>` by file, with `branch` lines'
330
/// `condition-coverage="50% (1/2)"` as branches and `<method>`s as
331
/// functions (one is hit when any of its lines ran). A file named by
332
/// several classes is added together. A `<source>` is tried as the base of
333
/// a relative filename, the workspace's `/src` among them.
3343×
pub fn parse_cobertura(text: &str) -> Result<(Vec<FileCoverage>, usize), String> {
335
    use quick_xml::events::Event;
3363×
    let mut r = quick_xml::Reader::from_str(text);
3373×
    let mut sources: Vec<String> = Vec::new();
3383×
    let mut in_source = false;
3393×
    let mut source_text = String::new();
340
    // Files as the classes name them, resolved once the sources are known.
3413×
    let mut raw: BTreeMap<String, Acc> = BTreeMap::new();
3423×
    let mut file: Option<String> = None;
3433×
    let mut method: Option<(String, bool)> = None;
3443×
    let mut seen_root = false;
345
    loop {
34686×
        let ev = r.read_event().map_err(|e| format!("this is not a Cobertura report: {e}"))?;
34720×
        match ev {
34825×
            Event::Start(ref e) | Event::Empty(ref e) => {
34937×
                let tag = e.local_name().as_ref().to_string();
35037×
                match tag.as_str() {
35137×
                    "coverage" => seen_root = true,
35235×
                    "source" if matches!(ev, Event::Start(_)) => {
3532×
                        in_source = true;
3542×
                        source_text.clear();
3552×
                    }
35633×
                    "class" => {
3574×
                        let f = xml_attr(e, "filename");
3584×
                        raw.entry(f.clone()).or_default().records += 1;
3594×
                        file = Some(f);
3604×
                    }
36129×
                    "method" => method = Some((xml_attr(e, "name") + &xml_attr(e, "signature"), false)),
36227×
                    "line" => {
3639×
                        let Some(f) = &file else { continue };
3649×
                        let Ok(n) = xml_attr(e, "number").trim().parse::<u32>() else { continue };
3659×
                        let hits = xml_attr(e, "hits").trim().parse::<u64>().unwrap_or(0);
3669×
                        if let Some((_, hit)) = &mut method {
3672×
                            *hit |= hits > 0;
368
                            // A method's lines repeat the class's; count them once.
3692×
                            continue;
3707×
                        }
3717×
                        let acc = raw.entry(f.clone()).or_default();
3727×
                        *acc.lines.entry(n).or_default() += hits;
3737×
                        if xml_attr(e, "branch") == "true" {
374
                            // "50% (1/2)": covered of total conditions.
3751×
                            let cc = xml_attr(e, "condition-coverage");
3761×
                            if let Some((hit, total)) = cc
3771×
                                .split_once('(')
3781×
                                .and_then(|(_, rest)| rest.trim_end_matches(')').split_once('/'))
3791×
                                .and_then(|(h, t)| Some((h.trim().parse::<u64>().ok()?, t.trim().parse::<u64>().ok()?)))
380
                            {
3812×
                                for i in 0..total {
3822×
                                    let b = acc.branches.entry((n, "0".into(), i.to_string())).or_default();
3832×
                                    *b = (*b).max(u64::from(i < hit));
3842×
                                }
3850×
                            }
3866×
                        }
387
                    }
38818×
                    _ => {}
389
                }
39035×
                if matches!(ev, Event::Empty(_)) && tag == "method" {
3910×
                    if let (Some(f), Some((name, hit))) = (&file, method.take()) {
3920×
                        *raw.entry(f.clone()).or_default().functions.entry(name).or_default() += u64::from(hit);
3930×
                    }
39435×
                }
395
            }
3962×
            Event::Text(t) if in_source => source_text.push_str(&t.xml10_content()),
39725×
            Event::End(e) => match e.local_name().as_ref() {
39825×
                "source" => {
3992×
                    in_source = false;
4002×
                    sources.push(source_text.trim().trim_end_matches('/').to_string());
4012×
                }
40223×
                "class" => file = None,
40319×
                "method" => {
4042×
                    if let (Some(f), Some((name, hit))) = (&file, method.take()) {
4052×
                        *raw.entry(f.clone()).or_default().functions.entry(name).or_default() += u64::from(hit);
4062×
                    }
407
                }
40817×
                _ => {}
409
            },
4103×
            Event::Eof => break,
41119×
            _ => {}
412
        }
413
    }
4143×
    if !seen_root {
4151×
        return Err("this is not a Cobertura report: no <coverage> element".into());
4162×
    }
4172×
    if raw.is_empty() {
4180×
        return Err("this Cobertura report names no source file (no <class filename>)".into());
4192×
    }
420
    // A filename relative to one of the sources, or to the workspace.
4213×
    let resolve = |f: &str| -> Option<String> {
4223×
        if f.starts_with('/') {
4231×
            return relative(f);
4242×
        }
4252×
        sources.iter().filter(|s| !s.is_empty() && *s != ".").find_map(|s| relative(&format!("{s}/{f}"))).or_else(|| relative(f))
4263×
    };
4272×
    let mut files: BTreeMap<String, Acc> = BTreeMap::new();
4282×
    let mut outside = HashSet::new();
4293×
    for (f, a) in raw {
4303×
        let Some(path) = resolve(&f) else {
4311×
            outside.insert(f);
4321×
            continue;
433
        };
4342×
        let into = files.entry(path).or_default();
4356×
        for (l, n) in a.lines {
4366×
            *into.lines.entry(l).or_default() += n;
4376×
        }
4382×
        for (k, n) in a.functions {
4392×
            *into.functions.entry(k).or_default() += n;
4402×
        }
4412×
        for (k, n) in a.branches {
4422×
            let b = into.branches.entry(k).or_default();
4432×
            *b = (*b).max(n);
4442×
        }
445
    }
4462×
    let out = files
4472×
        .into_iter()
4482×
        .map(|(path, a)| FileCoverage {
4492×
            path,
4502×
            functions_found: a.functions.len() as u64,
4512×
            functions_hit: a.functions.values().filter(|n| **n > 0).count() as u64,
4522×
            branches_found: a.branches.len() as u64,
4532×
            branches_hit: a.branches.values().filter(|n| **n > 0).count() as u64,
4542×
            lines: a.lines,
4552×
            declared_lines: None,
4562×
        })
4572×
        .collect();
4582×
    Ok((out, outside.len()))
4593×
}
460
461
/// A percentage to one decimal place, or none when nothing was counted.
46260×
pub fn percent(hit: i64, found: i64) -> Option<f64> {
46360×
    (found > 0).then(|| (hit as f64 * 1000.0 / found as f64).round() / 10.0)
46460×
}
465
466
#[derive(Clone, Debug, sqlx::FromRow)]
467
pub struct Report {
468
    pub id: i64,
469
    pub repo_id: i64,
470
    /// The Flow run and job it came from; none for an upload (#136).
471
    pub run_id: Option<i64>,
472
    pub job_id: Option<i64>,
473
    pub job: String,
474
    pub run_number: i64,
475
    pub bookmark: String,
476
    pub state: String,
477
    pub heads: String,
478
    pub blob: String,
479
    pub format: String,
480
    pub lines_found: i64,
481
    pub lines_hit: i64,
482
    pub functions_found: i64,
483
    pub functions_hit: i64,
484
    pub branches_found: i64,
485
    pub branches_hit: i64,
486
    pub hits: i64,
487
    pub files: i64,
488
    pub dropped: i64,
489
    pub created_ms: i64,
490
    /// Who uploaded it from a workstation (#136); empty for a job's report.
491
    pub uploader: String,
492
}
493
494
impl Report {
495
    /// Whether it was uploaded rather than measured by a Flow job.
49612×
    pub fn uploaded(&self) -> bool {
49712×
        !self.uploader.is_empty()
49812×
    }
499
500
    /// Where its figure came from: "run #61", or "uploaded by NAME".
5014×
    pub fn source(&self) -> String {
5024×
        if self.uploaded() {
5033×
            format!("uploaded by {}", self.uploader)
504
        } else {
5051×
            format!("run #{}", self.run_number)
506
        }
5074×
    }
508
509
    /// How often an instrumented line ran, on average.
5104×
    pub fn hits_per_line(&self) -> Option<f64> {
5114×
        (self.lines_found > 0).then(|| self.hits as f64 / self.lines_found as f64)
5124×
    }
513
51436×
    pub fn percent(&self) -> Option<f64> {
51536×
        percent(self.lines_hit, self.lines_found)
51636×
    }
517
5181×
    pub fn functions_percent(&self) -> Option<f64> {
5191×
        percent(self.functions_hit, self.functions_found)
5201×
    }
521
5220×
    pub fn branches_percent(&self) -> Option<f64> {
5230×
        percent(self.branches_hit, self.branches_found)
5240×
    }
525
5261×
    pub fn head_list(&self) -> Vec<&str> {
5271×
        self.heads.split(',').filter(|h| !h.is_empty()).collect()
5281×
    }
529
}
530
531
#[derive(Clone, Debug, sqlx::FromRow)]
532
pub struct FileRow {
533
    pub report_id: i64,
534
    pub path: String,
535
    pub lines_found: i64,
536
    pub lines_hit: i64,
537
    pub functions_found: i64,
538
    pub functions_hit: i64,
539
    pub branches_found: i64,
540
    pub branches_hit: i64,
541
}
542
543
impl FileRow {
54421×
    pub fn percent(&self) -> Option<f64> {
54521×
        percent(self.lines_hit, self.lines_found)
54621×
    }
547
5482×
    pub fn missed(&self) -> i64 {
5492×
        self.lines_found - self.lines_hit
5502×
    }
551
}
552
553
/// Repositories with a report, so their pages show the Coverage tab:
554
/// keyed by the hub's repository root and the id, unique even between
555
/// hubs in one process.
556
static HAS: Mutex<Option<HashSet<String>>> = Mutex::new(None);
557
5588×
fn key(app: &Shared, repo_id: i64) -> String {
5598×
    format!("{}#{repo_id}", app.repos.root().display())
5608×
}
561
562517×
pub fn has_reports(app: &Shared, repo_id: i64) -> bool {
563517×
    HAS.lock().unwrap_or_else(|p| p.into_inner()).as_ref().is_some_and(|s| s.contains(&key(app, repo_id)))
564517×
}
565
5663×
fn mark(app: &Shared, repo_id: i64) {
5673×
    HAS.lock().unwrap_or_else(|p| p.into_inner()).get_or_insert_with(HashSet::new).insert(key(app, repo_id));
5683×
}
569
570
/// At start: which repositories have reports.
571190×
pub async fn load(app: &Shared) -> sqlx::Result<()> {
572190×
    let ids: Vec<(i64,)> = sqlx::query_as("SELECT DISTINCT repo_id FROM coverage_reports").fetch_all(&app.db).await?;
573190×
    for (id,) in ids {
5740×
        mark(app, id);
5750×
    }
576190×
    Ok(())
577190×
}
578
579
/// What a run's report is kept with.
580
pub struct Origin<'a> {
581
    pub repo_id: i64,
582
    /// The Flow run and job; none for an upload, which names its uploader.
583
    pub run_id: Option<i64>,
584
    pub run_number: i64,
585
    pub job_id: Option<i64>,
586
    pub uploader: &'a str,
587
    pub job: &'a str,
588
    pub bookmark: &'a str,
589
    pub state: &'a str,
590
    pub heads: &'a [String],
591
    pub blob: &'a str,
592
    /// `lcov` or `cobertura`.
593
    pub format: &'a str,
594
}
595
596
/// Keep a parsed report: the files outside `in_state` are dropped and
597
/// counted. Replaces an earlier report of the same job.
5983×
pub async fn keep(app: &Shared, o: &Origin<'_>, files: Vec<FileCoverage>, outside: usize, in_state: &HashSet<String>) -> sqlx::Result<i64> {
5993×
    let files = resolve_endings(files, in_state);
6006×
    let (kept, missing): (Vec<FileCoverage>, Vec<FileCoverage>) = files.into_iter().partition(|f| in_state.contains(&f.path));
60118×
    let sum = |f: &dyn Fn(&FileCoverage) -> u64| kept.iter().map(f).sum::<u64>() as i64;
6023×
    let mut tx = crate::db::begin_write(&app.db).await?;
6033×
    if let Some(job) = o.job_id {
6042×
        sqlx::query("DELETE FROM coverage_reports WHERE job_id = $1").bind(job).execute(&mut *tx).await?;
6051×
    }
6063×
    let id: i64 = sqlx::query_scalar(
6073×
        "INSERT INTO coverage_reports (repo_id, run_id, job_id, job, run_number, bookmark, state, heads, blob, format, \
6083×
         lines_found, lines_hit, functions_found, functions_hit, branches_found, branches_hit, hits, files, dropped, created_ms, uploader) \
6093×
         VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21) RETURNING id",
610
    )
6113×
    .bind(o.repo_id)
6123×
    .bind(o.run_id)
6133×
    .bind(o.job_id)
6143×
    .bind(o.job)
6153×
    .bind(o.run_number)
6163×
    .bind(o.bookmark)
6173×
    .bind(o.state)
6183×
    .bind(o.heads.join(","))
6193×
    .bind(o.blob)
6203×
    .bind(o.format)
6213×
    .bind(sum(&|f| f.lines_found()))
6223×
    .bind(sum(&|f| f.lines_hit()))
6233×
    .bind(sum(&|f| f.functions_found))
6243×
    .bind(sum(&|f| f.functions_hit))
6253×
    .bind(sum(&|f| f.branches_found))
6263×
    .bind(sum(&|f| f.branches_hit))
6273×
    .bind(kept.iter().fold(0u64, |a, f| a.saturating_add(f.hits())).min(i64::MAX as u64) as i64)
6283×
    .bind(kept.len() as i64)
6293×
    .bind((missing.len() + outside) as i64)
6303×
    .bind(now_ms())
6313×
    .bind(o.uploader)
6323×
    .fetch_one(&mut *tx)
6333×
    .await?;
6343×
    for f in &kept {
6353×
        sqlx::query(
6363×
            "INSERT INTO coverage_files (report_id, path, lines_found, lines_hit, functions_found, functions_hit, branches_found, branches_hit) \
6373×
             VALUES ($1, $2, $3, $4, $5, $6, $7, $8)",
6383×
        )
6393×
        .bind(id)
6403×
        .bind(&f.path)
6413×
        .bind(f.lines_found() as i64)
6423×
        .bind(f.lines_hit() as i64)
6433×
        .bind(f.functions_found as i64)
6443×
        .bind(f.functions_hit as i64)
6453×
        .bind(f.branches_found as i64)
6463×
        .bind(f.branches_hit as i64)
6473×
        .execute(&mut *tx)
6483×
        .await?;
649
    }
6503×
    tx.commit().await?;
6513×
    mark(app, o.repo_id);
6523×
    Ok(id)
6533×
}
654
6556×
pub async fn report(pool: &Pool, repo_id: i64, id: i64) -> sqlx::Result<Option<Report>> {
6566×
    sqlx::query_as("SELECT * FROM coverage_reports WHERE id = $1 AND repo_id = $2").bind(id).bind(repo_id).fetch_optional(pool).await
6576×
}
658
659
/// The newest reports on a bookmark, newest first.
6605×
pub async fn on_bookmark(pool: &Pool, repo_id: i64, bookmark: &str, limit: i64) -> sqlx::Result<Vec<Report>> {
6615×
    sqlx::query_as("SELECT * FROM coverage_reports WHERE repo_id = $1 AND bookmark = $2 ORDER BY created_ms DESC, id DESC LIMIT $3")
6625×
        .bind(repo_id)
6635×
        .bind(bookmark)
6645×
        .bind(limit)
6655×
        .fetch_all(pool)
6665×
        .await
6675×
}
668
669
/// When the repository's first report on any bookmark was kept.
6702×
pub async fn first_ms(pool: &Pool, repo_id: i64) -> sqlx::Result<Option<i64>> {
6712×
    sqlx::query_scalar("SELECT MIN(created_ms) FROM coverage_reports WHERE repo_id = $1").bind(repo_id).fetch_one(pool).await
6722×
}
673
674
/// The bookmarks with reports, the most recent first.
6754×
pub async fn bookmarks(pool: &Pool, repo_id: i64) -> sqlx::Result<Vec<String>> {
6764×
    sqlx::query_scalar("SELECT bookmark FROM coverage_reports WHERE repo_id = $1 GROUP BY bookmark ORDER BY MAX(created_ms) DESC")
6774×
        .bind(repo_id)
6784×
        .fetch_all(pool)
6794×
        .await
6804×
}
681
682
/// A repository's coverage rules.
683
#[derive(Clone, Copy, Debug, Default, PartialEq)]
684
pub struct Rules {
685
    /// The check fails below this percentage.
686
    pub min: Option<f64>,
687
    /// The check fails when coverage falls more than this many points.
688
    pub max_drop: Option<f64>,
689
}
690
691135×
pub async fn rules(pool: &Pool, repo_id: i64) -> sqlx::Result<Rules> {
692135×
    let row: Option<(Option<f64>, Option<f64>)> =
693135×
        sqlx::query_as("SELECT min, max_drop FROM coverage_settings WHERE repo_id = $1").bind(repo_id).fetch_optional(pool).await?;
694135×
    Ok(row.map(|(min, max_drop)| Rules { min, max_drop }).unwrap_or_default())
695135×
}
696
6972×
pub async fn set_rules(pool: &Pool, repo_id: i64, r: Rules) -> sqlx::Result<()> {
6982×
    sqlx::query(
6992×
        "INSERT INTO coverage_settings (repo_id, min, max_drop) VALUES ($1, $2, $3) \
7002×
         ON CONFLICT (repo_id) DO UPDATE SET min = excluded.min, max_drop = excluded.max_drop",
7012×
    )
7022×
    .bind(repo_id)
7032×
    .bind(r.min)
7042×
    .bind(r.max_drop)
7052×
    .execute(pool)
7062×
    .await?;
7072×
    Ok(())
7082×
}
709
710
/// What a report is measured against: on the default bookmark, the report
711
/// before it there; on any other, the default bookmark's latest before it.
7122×
pub async fn baseline(pool: &Pool, r: &Report, default_bookmark: &str) -> sqlx::Result<Option<Report>> {
7132×
    sqlx::query_as(
7142×
        "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)) \
7152×
         ORDER BY created_ms DESC, id DESC LIMIT 1",
7162×
    )
7172×
    .bind(r.repo_id)
7182×
    .bind(default_bookmark)
7192×
    .bind(r.id)
7202×
    .bind(r.created_ms)
7212×
    .bind(r.created_ms)
7222×
    .bind(r.id)
7232×
    .fetch_optional(pool)
7242×
    .await
7252×
}
726
727
/// The `coverage` check for a report: passed or failed, and what to say.
7288×
pub fn verdict(r: &Report, base: Option<&Report>, base_name: &str, rules: Rules) -> (&'static str, String) {
7298×
    let Some(p) = r.percent() else { return ("passed", "no instrumented lines".into()) };
7308×
    let delta = base.and_then(|b| Some(p - b.percent()?));
7318×
    let against = match delta {
7325×
        Some(d) if d.abs() < 0.05 => format!(", unchanged against {base_name}"),
7334×
        Some(d) => format!(" ({d:+.1} against {base_name})"),
7343×
        None => String::new(),
735
    };
7368×
    if let Some(min) = rules.min.filter(|m| p < *m) {
7372×
        return ("failed", format!("{p:.1}%{against}: below the minimum of {min}%"));
7386×
    }
7396×
    if let (Some(max), Some(d)) = (rules.max_drop, delta) {
7402×
        if d < -max {
7411×
            return ("failed", format!("{p:.1}%{against}: falls more than the {max} points allowed"));
7421×
        }
7434×
    }
7445×
    ("passed", format!("{p:.1}%{against}"))
7458×
}
746
74723×
pub async fn for_run(pool: &Pool, run_id: i64) -> sqlx::Result<Vec<Report>> {
74823×
    sqlx::query_as("SELECT * FROM coverage_reports WHERE run_id = $1 ORDER BY job").bind(run_id).fetch_all(pool).await
74923×
}
750
7515×
pub async fn files(pool: &Pool, report_id: i64) -> sqlx::Result<Vec<FileRow>> {
7525×
    sqlx::query_as("SELECT * FROM coverage_files WHERE report_id = $1 ORDER BY path").bind(report_id).fetch_all(pool).await
7535×
}
754
755
#[cfg(test)]
756
mod tests {
757
    use super::*;
758
759
    /// oxygenhub#308: a JaCoCo report (Gradle's jacocoTestReport, Kover):
760
    /// lines hit when an instruction ran, branches, methods; package paths
761
    /// found in the state by their ending.
762
    #[test]
7631×
    fn a_jacoco_report_is_read_and_its_paths_found() {
7641×
        let xml = r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><!DOCTYPE report PUBLIC "-//JACOCO//DTD Report 1.1//EN" "report.dtd"><report name="app"><sessioninfo id="x" start="1" dump="2"/><package name="io/oxygenhub/android/api"><class name="io/oxygenhub/android/api/Links" sourcefilename="Links.kt"><method name="routeFor" desc="(Ljava/lang/String;)" line="11"><counter type="INSTRUCTION" missed="2" covered="30"/><counter type="METHOD" missed="0" covered="1"/></method><method name="unused" desc="()V" line="40"><counter type="METHOD" missed="1" covered="0"/></method></class><sourcefile name="Links.kt"><line nr="11" mi="0" ci="5" mb="1" cb="1"/><line nr="12" mi="3" ci="0" mb="0" cb="0"/><line nr="40" mi="2" ci="0" mb="0" cb="0"/><counter type="LINE" missed="2" covered="1"/></sourcefile></package></report>"#;
7651×
        let (files, outside, format) = parse(xml).unwrap();
7661×
        assert_eq!((format, outside, files.len()), ("jacoco", 0, 1));
7671×
        let f = &files[0];
7681×
        assert_eq!(f.path, "io/oxygenhub/android/api/Links.kt");
7691×
        assert_eq!((f.lines_found(), f.lines_hit()), (3, 1));
7701×
        assert_eq!((f.branches_found, f.branches_hit), (2, 1));
7711×
        assert_eq!((f.functions_found, f.functions_hit), (2, 1));
7721×
        let state: HashSet<String> =
7731×
            ["app/src/main/java/io/oxygenhub/android/api/Links.kt".to_string(), "README.md".to_string()].into_iter().collect();
7741×
        let found = resolve_endings(files, &state);
7751×
        assert_eq!(found[0].path, "app/src/main/java/io/oxygenhub/android/api/Links.kt");
776
        // Two files of the state end the same way: left as it is.
7771×
        let twice: HashSet<String> = ["a/x/Links.kt".to_string(), "b/x/Links.kt".to_string()].into_iter().collect();
7781×
        let left = resolve_endings(vec![FileCoverage { path: "x/Links.kt".into(), ..Default::default() }], &twice);
7791×
        assert_eq!(left[0].path, "x/Links.kt");
7801×
        assert!(parse_jacoco("<report></report>").is_err(), "no source file");
7811×
    }
782
783
    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\
784
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\
785
SF:/src/crates/a/src/lib.rs\nDA:9,1\nend_of_record\n\
786
SF:./README.md\nDA:1,1\nend_of_record\n\
787
SF:/home/runner/.cargo/registry/src/dep/lib.rs\nDA:1,1\nend_of_record\n";
788
789
    #[test]
7901×
    fn lcov_reports_are_read_and_merged() {
7911×
        let (files, outside) = parse_lcov(LCOV).unwrap();
7921×
        assert_eq!(outside, 1, "the dependency outside the workspace");
7931×
        assert_eq!(files.len(), 2);
7941×
        let lib = &files[1];
7951×
        assert_eq!(lib.path, "crates/a/src/lib.rs");
7961×
        assert_eq!(lib.lines, [(3, 4), (4, 4), (9, 1), (10, 0)].into_iter().collect());
7971×
        assert_eq!((lib.lines_found(), lib.lines_hit()), (4, 3), "the second record ran line 9");
7981×
        assert_eq!((lib.functions_found, lib.functions_hit), (2, 1));
7991×
        assert_eq!((lib.branches_found, lib.branches_hit), (2, 1));
8001×
        assert_eq!(files[0].path, "README.md");
8011×
        assert_eq!(lib.declared_lines, None, "two records: counted from the lines");
802
        // One record whose totals name lines its DA lines leave out, as llvm-cov writes.
8031×
        let (one, _) = parse_lcov("SF:/src/a.rs\nDA:1,1\nDA:2,0\nLF:5\nLH:3\nend_of_record\n").unwrap();
8041×
        assert_eq!((one[0].lines_found(), one[0].lines_hit()), (5, 3));
8051×
        assert!(parse_lcov("not a report\n").unwrap_err().contains("not an LCOV report"));
8061×
    }
807
808
    #[test]
8091×
    fn the_check_follows_the_rules() {
8101×
        let report = |pct_hit: i64| Report {
811
            id: 2,
812
            repo_id: 1,
8132×
            run_id: Some(1),
8142×
            job_id: Some(1),
8152×
            job: "test".into(),
816
            run_number: 1,
8172×
            bookmark: "feature".into(),
8182×
            state: String::new(),
8192×
            heads: String::new(),
8202×
            blob: String::new(),
8212×
            format: "lcov".into(),
822
            lines_found: 1000,
8232×
            lines_hit: pct_hit,
824
            functions_found: 0,
825
            functions_hit: 0,
826
            branches_found: 0,
827
            branches_hit: 0,
828
            hits: 0,
829
            files: 1,
830
            dropped: 0,
831
            created_ms: 0,
8322×
            uploader: String::new(),
8332×
        };
8341×
        let (now, before) = (report(819), report(822));
8351×
        let none = Rules::default();
8361×
        assert_eq!(verdict(&now, Some(&before), "main", none), ("passed", "81.9% (-0.3 against main)".to_string()));
8371×
        assert_eq!(verdict(&now, None, "main", none), ("passed", "81.9%".to_string()));
8381×
        assert_eq!(verdict(&now, Some(&now), "main", none).1, "81.9%, unchanged against main");
8391×
        let strict = Rules { min: Some(85.0), max_drop: None };
8401×
        assert_eq!(
8411×
            verdict(&now, Some(&before), "main", strict),
8421×
            ("failed", "81.9% (-0.3 against main): below the minimum of 85%".to_string())
843
        );
8441×
        let drop = Rules { min: None, max_drop: Some(0.2) };
8451×
        assert_eq!(verdict(&now, Some(&before), "main", drop).0, "failed");
8461×
        assert_eq!(verdict(&now, Some(&before), "main", Rules { min: None, max_drop: Some(0.5) }).0, "passed");
8471×
    }
848
849
    #[test]
8501×
    fn paths_are_taken_relative_to_the_workspace() {
8511×
        assert_eq!(relative("/src/a/b.rs").as_deref(), Some("a/b.rs"));
8521×
        assert_eq!(relative("./a/b.rs").as_deref(), Some("a/b.rs"));
8531×
        assert_eq!(relative("a/b.rs").as_deref(), Some("a/b.rs"));
8546×
        for bad in ["/etc/passwd", "a/../b", "", "/src/", "a//b", "C:\\x\\y.rs"] {
8556×
            assert_eq!(relative(bad), None, "{bad}");
856
        }
8571×
        assert_eq!(percent(1, 3), Some(33.3));
8581×
        assert_eq!(percent(0, 0), None);
8591×
    }
860
861
    #[test]
8621×
    fn cobertura_from_coverage_py_and_coverlet() {
863
        // coverage.py: a source to resolve against, branches by condition.
8641×
        let py = r#"<?xml version="1.0" ?>
8651×
<coverage version="7.4" line-rate="0.6" branch-rate="0.5">
8661×
  <sources><source>/src/app</source></sources>
8671×
  <packages><package name="app"><classes>
8681×
    <class name="main.py" filename="main.py" line-rate="0.66">
8691×
      <methods/>
8701×
      <lines>
8711×
        <line number="1" hits="1"/>
8721×
        <line number="2" hits="0"/>
8731×
        <line number="3" hits="4" branch="true" condition-coverage="50% (1/2)"/>
8741×
      </lines>
8751×
    </class>
8761×
    <class name="gone.py" filename="/usr/lib/python3/x.py"><lines><line number="1" hits="1"/></lines></class>
8771×
  </classes></package></packages>
8781×
</coverage>"#;
8791×
        let (files, outside, format) = parse(py).unwrap();
8801×
        assert_eq!((format, outside), ("cobertura", 1));
8811×
        let f = &files[0];
8821×
        assert_eq!(f.path, "app/main.py");
8831×
        assert_eq!((f.lines_found(), f.lines_hit(), f.hits()), (3, 2, 5));
8841×
        assert_eq!((f.branches_found, f.branches_hit), (2, 1));
885
886
        // Coverlet: methods with their own lines, two classes in one file.
8871×
        let net = r#"<coverage><sources><source>/src/</source></sources><packages><package name="Lib"><classes>
8881×
<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>
8891×
<lines><line number="5" hits="2"/><line number="9" hits="0"/></lines></class>
8901×
<class name="Lib.A/Inner" filename="Lib/A.cs"><methods/><lines><line number="12" hits="1"/></lines></class>
8911×
</classes></package></packages></coverage>"#;
8921×
        let (files, _, _) = parse(net).unwrap();
8931×
        let f = &files[0];
8941×
        assert_eq!(f.path, "Lib/A.cs");
8951×
        assert_eq!((f.lines_found(), f.lines_hit()), (3, 2));
8961×
        assert_eq!((f.functions_found, f.functions_hit), (2, 1));
897
8981×
        assert!(parse("<html/>").unwrap_err().contains("Cobertura"));
8991×
        assert_eq!(parse("SF:/src/a.rs\nDA:1,1\nend_of_record\n").unwrap().2, "lcov");
9001×
    }
901
}