OXYGENHUB
# f3e5e2bc78e9 oxygenhub / crates / hub / src / coverage.rs
28.9 KiB · Rust · last changed Coverage: read Cobertura XML reports too 1 month ago source blame history raw
554ccacf Andy McCall ↶ 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
7fff30c4 Andy McCall ↶ 4
//! gcov/lcov write) or Cobertura XML has it parsed when it is uploaded. The totals and each
554ccacf Andy McCall ↶ 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 {
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
    /// Every run of every line, added up.
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
/// 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.
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
/// 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.
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
    // A new SF: record has begun and not yet been counted for its file.
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)) = &current 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
/// Parse a report in either format the hub reads: Cobertura XML (it
174
/// starts with `<`) or LCOV. Returns the files, those outside the
175
/// repository, and the format's name.
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
/// Parse a Cobertura XML report (coverage.py `coverage xml`, JaCoCo via
193
/// cover2cover, .NET Coverlet, `cargo llvm-cov --cobertura`): each
194
/// `<class>`'s `<line number hits>` by file, with `branch` lines'
195
/// `condition-coverage="50% (1/2)"` as branches and `<method>`s as
196
/// functions (one is hit when any of its lines ran). A file named by
197
/// several classes is added together. A `<source>` is tried as the base of
198
/// a relative filename, the workspace's `/src` among them.
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
    // Files as the classes name them, resolved once the sources are known.
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
                            // A method's lines repeat the class's; count them once.
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
                            // "50% (1/2)": covered of total conditions.
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
    // A filename relative to one of the sources, or to the workspace.
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
/// A percentage to one decimal place, or none when nothing was counted.
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,
335
    pub run_id: i64,
336
    pub job_id: i64,
337
    pub job: String,
338
    pub run_number: i64,
339
    pub bookmark: String,
340
    pub state: String,
341
    pub heads: String,
342
    pub blob: String,
343
    pub format: String,
344
    pub lines_found: i64,
345
    pub lines_hit: i64,
346
    pub functions_found: i64,
347
    pub functions_hit: i64,
348
    pub branches_found: i64,
349
    pub branches_hit: i64,
c987c865 Andy McCall ↶ 350
    pub hits: i64,
554ccacf Andy McCall ↶ 351
    pub files: i64,
352
    pub dropped: i64,
353
    pub created_ms: i64,
354
}
355
356
impl Report {
c987c865 Andy McCall ↶ 357
    /// How often an instrumented line ran, on average.
358
    pub fn hits_per_line(&self) -> Option<f64> {
359
        (self.lines_found > 0).then(|| self.hits as f64 / self.lines_found as f64)
360
    }
361
554ccacf Andy McCall ↶ 362
    pub fn percent(&self) -> Option<f64> {
363
        percent(self.lines_hit, self.lines_found)
364
    }
365
366
    pub fn functions_percent(&self) -> Option<f64> {
367
        percent(self.functions_hit, self.functions_found)
368
    }
369
370
    pub fn branches_percent(&self) -> Option<f64> {
371
        percent(self.branches_hit, self.branches_found)
372
    }
373
374
    pub fn head_list(&self) -> Vec<&str> {
375
        self.heads.split(',').filter(|h| !h.is_empty()).collect()
376
    }
377
}
378
379
#[derive(Clone, Debug, sqlx::FromRow)]
380
pub struct FileRow {
381
    pub report_id: i64,
382
    pub path: String,
383
    pub lines_found: i64,
384
    pub lines_hit: i64,
385
    pub functions_found: i64,
386
    pub functions_hit: i64,
387
    pub branches_found: i64,
388
    pub branches_hit: i64,
389
}
390
391
impl FileRow {
392
    pub fn percent(&self) -> Option<f64> {
393
        percent(self.lines_hit, self.lines_found)
394
    }
395
396
    pub fn missed(&self) -> i64 {
397
        self.lines_found - self.lines_hit
398
    }
399
}
400
401
/// Repositories with a report, so their pages show the Coverage tab:
402
/// keyed by the hub's repository root and the id, unique even between
403
/// hubs in one process.
404
static HAS: Mutex<Option<HashSet<String>>> = Mutex::new(None);
405
406
fn key(app: &Shared, repo_id: i64) -> String {
407
    format!("{}#{repo_id}", app.repos.root().display())
408
}
409
410
pub fn has_reports(app: &Shared, repo_id: i64) -> bool {
411
    HAS.lock().unwrap_or_else(|p| p.into_inner()).as_ref().is_some_and(|s| s.contains(&key(app, repo_id)))
412
}
413
414
fn mark(app: &Shared, repo_id: i64) {
415
    HAS.lock().unwrap_or_else(|p| p.into_inner()).get_or_insert_with(HashSet::new).insert(key(app, repo_id));
416
}
417
418
/// At start: which repositories have reports.
419
pub async fn load(app: &Shared) -> sqlx::Result<()> {
420
    let ids: Vec<(i64,)> = sqlx::query_as("SELECT DISTINCT repo_id FROM coverage_reports").fetch_all(&app.db).await?;
421
    for (id,) in ids {
422
        mark(app, id);
423
    }
424
    Ok(())
425
}
426
427
/// What a run's report is kept with.
428
pub struct Origin<'a> {
429
    pub repo_id: i64,
430
    pub run_id: i64,
431
    pub run_number: i64,
432
    pub job_id: i64,
433
    pub job: &'a str,
434
    pub bookmark: &'a str,
435
    pub state: &'a str,
436
    pub heads: &'a [String],
437
    pub blob: &'a str,
7fff30c4 Andy McCall ↶ 438
    /// `lcov` or `cobertura`.
439
    pub format: &'a str,
554ccacf Andy McCall ↶ 440
}
441
442
/// Keep a parsed report: the files outside `in_state` are dropped and
443
/// counted. Replaces an earlier report of the same job.
444
pub async fn keep(app: &Shared, o: &Origin<'_>, files: Vec<FileCoverage>, outside: usize, in_state: &HashSet<String>) -> sqlx::Result<i64> {
445
    let (kept, missing): (Vec<FileCoverage>, Vec<FileCoverage>) = files.into_iter().partition(|f| in_state.contains(&f.path));
446
    let sum = |f: &dyn Fn(&FileCoverage) -> u64| kept.iter().map(f).sum::<u64>() as i64;
447
    let mut tx = crate::db::begin_write(&app.db).await?;
448
    sqlx::query("DELETE FROM coverage_reports WHERE job_id = ?").bind(o.job_id).execute(&mut *tx).await?;
449
    let id: i64 = sqlx::query_scalar(
450
        "INSERT INTO coverage_reports (repo_id, run_id, job_id, job, run_number, bookmark, state, heads, blob, format, \
c987c865 Andy McCall ↶ 451
         lines_found, lines_hit, functions_found, functions_hit, branches_found, branches_hit, hits, files, dropped, created_ms) \
7fff30c4 Andy McCall ↶ 452
         VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id",
554ccacf Andy McCall ↶ 453
    )
454
    .bind(o.repo_id)
455
    .bind(o.run_id)
456
    .bind(o.job_id)
457
    .bind(o.job)
458
    .bind(o.run_number)
459
    .bind(o.bookmark)
460
    .bind(o.state)
461
    .bind(o.heads.join(","))
462
    .bind(o.blob)
7fff30c4 Andy McCall ↶ 463
    .bind(o.format)
554ccacf Andy McCall ↶ 464
    .bind(sum(&|f| f.lines_found()))
465
    .bind(sum(&|f| f.lines_hit()))
466
    .bind(sum(&|f| f.functions_found))
467
    .bind(sum(&|f| f.functions_hit))
468
    .bind(sum(&|f| f.branches_found))
469
    .bind(sum(&|f| f.branches_hit))
c987c865 Andy McCall ↶ 470
    .bind(kept.iter().fold(0u64, |a, f| a.saturating_add(f.hits())).min(i64::MAX as u64) as i64)
554ccacf Andy McCall ↶ 471
    .bind(kept.len() as i64)
472
    .bind((missing.len() + outside) as i64)
473
    .bind(now_ms())
474
    .fetch_one(&mut *tx)
475
    .await?;
476
    for f in &kept {
477
        sqlx::query(
478
            "INSERT INTO coverage_files (report_id, path, lines_found, lines_hit, functions_found, functions_hit, branches_found, branches_hit) \
479
             VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
480
        )
481
        .bind(id)
482
        .bind(&f.path)
483
        .bind(f.lines_found() as i64)
484
        .bind(f.lines_hit() as i64)
485
        .bind(f.functions_found as i64)
486
        .bind(f.functions_hit as i64)
487
        .bind(f.branches_found as i64)
488
        .bind(f.branches_hit as i64)
489
        .execute(&mut *tx)
490
        .await?;
491
    }
492
    tx.commit().await?;
493
    mark(app, o.repo_id);
494
    Ok(id)
495
}
496
497
pub async fn report(pool: &Pool, repo_id: i64, id: i64) -> sqlx::Result<Option<Report>> {
498
    sqlx::query_as("SELECT * FROM coverage_reports WHERE id = ? AND repo_id = ?").bind(id).bind(repo_id).fetch_optional(pool).await
499
}
500
501
/// The newest reports on a bookmark, newest first.
502
pub async fn on_bookmark(pool: &Pool, repo_id: i64, bookmark: &str, limit: i64) -> sqlx::Result<Vec<Report>> {
503
    sqlx::query_as("SELECT * FROM coverage_reports WHERE repo_id = ? AND bookmark = ? ORDER BY created_ms DESC, id DESC LIMIT ?")
504
        .bind(repo_id)
505
        .bind(bookmark)
506
        .bind(limit)
c987c865 Andy McCall ↶ 507
        .fetch_all(pool)
508
        .await
509
}
510
511
/// When the repository's first report on any bookmark was kept.
512
pub async fn first_ms(pool: &Pool, repo_id: i64) -> sqlx::Result<Option<i64>> {
513
    sqlx::query_scalar("SELECT MIN(created_ms) FROM coverage_reports WHERE repo_id = ?").bind(repo_id).fetch_one(pool).await
514
}
515
516
/// The bookmarks with reports, the most recent first.
517
pub async fn bookmarks(pool: &Pool, repo_id: i64) -> sqlx::Result<Vec<String>> {
518
    sqlx::query_scalar("SELECT bookmark FROM coverage_reports WHERE repo_id = ? GROUP BY bookmark ORDER BY MAX(created_ms) DESC")
519
        .bind(repo_id)
554ccacf Andy McCall ↶ 520
        .fetch_all(pool)
521
        .await
522
}
523
7edaff01 Andy McCall ↶ 524
/// A repository's coverage rules.
525
#[derive(Clone, Copy, Debug, Default, PartialEq)]
526
pub struct Rules {
527
    /// The check fails below this percentage.
528
    pub min: Option<f64>,
529
    /// The check fails when coverage falls more than this many points.
530
    pub max_drop: Option<f64>,
531
}
532
533
pub async fn rules(pool: &Pool, repo_id: i64) -> sqlx::Result<Rules> {
534
    let row: Option<(Option<f64>, Option<f64>)> =
535
        sqlx::query_as("SELECT min, max_drop FROM coverage_settings WHERE repo_id = ?").bind(repo_id).fetch_optional(pool).await?;
536
    Ok(row.map(|(min, max_drop)| Rules { min, max_drop }).unwrap_or_default())
537
}
538
539
pub async fn set_rules(pool: &Pool, repo_id: i64, r: Rules) -> sqlx::Result<()> {
540
    sqlx::query(
541
        "INSERT INTO coverage_settings (repo_id, min, max_drop) VALUES (?, ?, ?) \
542
         ON CONFLICT (repo_id) DO UPDATE SET min = excluded.min, max_drop = excluded.max_drop",
543
    )
544
    .bind(repo_id)
545
    .bind(r.min)
546
    .bind(r.max_drop)
547
    .execute(pool)
548
    .await?;
549
    Ok(())
550
}
551
552
/// What a report is measured against: on the default bookmark, the report
553
/// before it there; on any other, the default bookmark's latest before it.
554
pub async fn baseline(pool: &Pool, r: &Report, default_bookmark: &str) -> sqlx::Result<Option<Report>> {
555
    sqlx::query_as(
556
        "SELECT * FROM coverage_reports WHERE repo_id = ? AND bookmark = ? AND id <> ? AND (created_ms < ? OR (created_ms = ? AND id < ?)) \
557
         ORDER BY created_ms DESC, id DESC LIMIT 1",
558
    )
559
    .bind(r.repo_id)
560
    .bind(default_bookmark)
561
    .bind(r.id)
562
    .bind(r.created_ms)
563
    .bind(r.created_ms)
564
    .bind(r.id)
565
    .fetch_optional(pool)
566
    .await
567
}
568
569
/// The `coverage` check for a report: passed or failed, and what to say.
570
pub fn verdict(r: &Report, base: Option<&Report>, base_name: &str, rules: Rules) -> (&'static str, String) {
571
    let Some(p) = r.percent() else { return ("passed", "no instrumented lines".into()) };
572
    let delta = base.and_then(|b| Some(p - b.percent()?));
573
    let against = match delta {
574
        Some(d) if d.abs() < 0.05 => format!(", unchanged against {base_name}"),
575
        Some(d) => format!(" ({d:+.1} against {base_name})"),
576
        None => String::new(),
577
    };
578
    if let Some(min) = rules.min.filter(|m| p < *m) {
579
        return ("failed", format!("{p:.1}%{against}: below the minimum of {min}%"));
580
    }
581
    if let (Some(max), Some(d)) = (rules.max_drop, delta) {
582
        if d < -max {
583
            return ("failed", format!("{p:.1}%{against}: falls more than the {max} points allowed"));
584
        }
585
    }
586
    ("passed", format!("{p:.1}%{against}"))
587
}
588
554ccacf Andy McCall ↶ 589
pub async fn for_run(pool: &Pool, run_id: i64) -> sqlx::Result<Vec<Report>> {
590
    sqlx::query_as("SELECT * FROM coverage_reports WHERE run_id = ? ORDER BY job").bind(run_id).fetch_all(pool).await
591
}
592
593
pub async fn files(pool: &Pool, report_id: i64) -> sqlx::Result<Vec<FileRow>> {
594
    sqlx::query_as("SELECT * FROM coverage_files WHERE report_id = ? ORDER BY path").bind(report_id).fetch_all(pool).await
595
}
596
597
#[cfg(test)]
598
mod tests {
599
    use super::*;
600
601
    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\
602
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\
603
SF:/src/crates/a/src/lib.rs\nDA:9,1\nend_of_record\n\
604
SF:./README.md\nDA:1,1\nend_of_record\n\
605
SF:/home/runner/.cargo/registry/src/dep/lib.rs\nDA:1,1\nend_of_record\n";
606
607
    #[test]
608
    fn lcov_reports_are_read_and_merged() {
609
        let (files, outside) = parse_lcov(LCOV).unwrap();
610
        assert_eq!(outside, 1, "the dependency outside the workspace");
611
        assert_eq!(files.len(), 2);
612
        let lib = &files[1];
613
        assert_eq!(lib.path, "crates/a/src/lib.rs");
614
        assert_eq!(lib.lines, [(3, 4), (4, 4), (9, 1), (10, 0)].into_iter().collect());
615
        assert_eq!((lib.lines_found(), lib.lines_hit()), (4, 3), "the second record ran line 9");
616
        assert_eq!((lib.functions_found, lib.functions_hit), (2, 1));
617
        assert_eq!((lib.branches_found, lib.branches_hit), (2, 1));
618
        assert_eq!(files[0].path, "README.md");
619
        assert_eq!(lib.declared_lines, None, "two records: counted from the lines");
620
        // One record whose totals name lines its DA lines leave out, as llvm-cov writes.
621
        let (one, _) = parse_lcov("SF:/src/a.rs\nDA:1,1\nDA:2,0\nLF:5\nLH:3\nend_of_record\n").unwrap();
622
        assert_eq!((one[0].lines_found(), one[0].lines_hit()), (5, 3));
623
        assert!(parse_lcov("not a report\n").unwrap_err().contains("not an LCOV report"));
7edaff01 Andy McCall ↶ 624
    }
625
626
    #[test]
627
    fn the_check_follows_the_rules() {
628
        let report = |pct_hit: i64| Report {
629
            id: 2,
630
            repo_id: 1,
631
            run_id: 1,
632
            job_id: 1,
633
            job: "test".into(),
634
            run_number: 1,
635
            bookmark: "feature".into(),
636
            state: String::new(),
637
            heads: String::new(),
638
            blob: String::new(),
639
            format: "lcov".into(),
640
            lines_found: 1000,
641
            lines_hit: pct_hit,
642
            functions_found: 0,
643
            functions_hit: 0,
644
            branches_found: 0,
645
            branches_hit: 0,
646
            hits: 0,
647
            files: 1,
648
            dropped: 0,
649
            created_ms: 0,
650
        };
651
        let (now, before) = (report(819), report(822));
652
        let none = Rules::default();
653
        assert_eq!(verdict(&now, Some(&before), "main", none), ("passed", "81.9% (-0.3 against main)".to_string()));
654
        assert_eq!(verdict(&now, None, "main", none), ("passed", "81.9%".to_string()));
655
        assert_eq!(verdict(&now, Some(&now), "main", none).1, "81.9%, unchanged against main");
656
        let strict = Rules { min: Some(85.0), max_drop: None };
657
        assert_eq!(
658
            verdict(&now, Some(&before), "main", strict),
659
            ("failed", "81.9% (-0.3 against main): below the minimum of 85%".to_string())
660
        );
661
        let drop = Rules { min: None, max_drop: Some(0.2) };
662
        assert_eq!(verdict(&now, Some(&before), "main", drop).0, "failed");
663
        assert_eq!(verdict(&now, Some(&before), "main", Rules { min: None, max_drop: Some(0.5) }).0, "passed");
554ccacf Andy McCall ↶ 664
    }
665
666
    #[test]
667
    fn paths_are_taken_relative_to_the_workspace() {
668
        assert_eq!(relative("/src/a/b.rs").as_deref(), Some("a/b.rs"));
669
        assert_eq!(relative("./a/b.rs").as_deref(), Some("a/b.rs"));
670
        assert_eq!(relative("a/b.rs").as_deref(), Some("a/b.rs"));
671
        for bad in ["/etc/passwd", "a/../b", "", "/src/", "a//b", "C:\\x\\y.rs"] {
672
            assert_eq!(relative(bad), None, "{bad}");
673
        }
674
        assert_eq!(percent(1, 3), Some(33.3));
675
        assert_eq!(percent(0, 0), None);
7fff30c4 Andy McCall ↶ 676
    }
677
678
    #[test]
679
    fn cobertura_from_coverage_py_and_coverlet() {
680
        // coverage.py: a source to resolve against, branches by condition.
681
        let py = r#"<?xml version="1.0" ?>
682
<coverage version="7.4" line-rate="0.6" branch-rate="0.5">
683
  <sources><source>/src/app</source></sources>
684
  <packages><package name="app"><classes>
685
    <class name="main.py" filename="main.py" line-rate="0.66">
686
      <methods/>
687
      <lines>
688
        <line number="1" hits="1"/>
689
        <line number="2" hits="0"/>
690
        <line number="3" hits="4" branch="true" condition-coverage="50% (1/2)"/>
691
      </lines>
692
    </class>
693
    <class name="gone.py" filename="/usr/lib/python3/x.py"><lines><line number="1" hits="1"/></lines></class>
694
  </classes></package></packages>
695
</coverage>"#;
696
        let (files, outside, format) = parse(py).unwrap();
697
        assert_eq!((format, outside), ("cobertura", 1));
698
        let f = &files[0];
699
        assert_eq!(f.path, "app/main.py");
700
        assert_eq!((f.lines_found(), f.lines_hit(), f.hits()), (3, 2, 5));
701
        assert_eq!((f.branches_found, f.branches_hit), (2, 1));
702
703
        // Coverlet: methods with their own lines, two classes in one file.
704
        let net = r#"<coverage><sources><source>/src/</source></sources><packages><package name="Lib"><classes>
705
<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>
706
<lines><line number="5" hits="2"/><line number="9" hits="0"/></lines></class>
707
<class name="Lib.A/Inner" filename="Lib/A.cs"><methods/><lines><line number="12" hits="1"/></lines></class>
708
</classes></package></packages></coverage>"#;
709
        let (files, _, _) = parse(net).unwrap();
710
        let f = &files[0];
711
        assert_eq!(f.path, "Lib/A.cs");
712
        assert_eq!((f.lines_found(), f.lines_hit()), (3, 2));
713
        assert_eq!((f.functions_found, f.functions_hit), (2, 1));
714
715
        assert!(parse("<html/>").unwrap_err().contains("Cobertura"));
716
        assert_eq!(parse("SF:/src/a.rs\nDA:1,1\nend_of_record\n").unwrap().2, "lcov");
554ccacf Andy McCall ↶ 717
    }
718
}