OXYGENHUB
# 36e5a9c15a84 oxygenhub / crates / hub / src / coverage.rs
15.9 KiB · Rust · last changed Coverage page: charts and a livelier layout 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
4
//! gcov/lcov write) 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 {
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
173
/// A percentage to one decimal place, or none when nothing was counted.
174
pub fn percent(hit: i64, found: i64) -> Option<f64> {
175
    (found > 0).then(|| (hit as f64 * 1000.0 / found as f64).round() / 10.0)
176
}
177
178
#[derive(Clone, Debug, sqlx::FromRow)]
179
pub struct Report {
180
    pub id: i64,
181
    pub repo_id: i64,
182
    pub run_id: i64,
183
    pub job_id: i64,
184
    pub job: String,
185
    pub run_number: i64,
186
    pub bookmark: String,
187
    pub state: String,
188
    pub heads: String,
189
    pub blob: String,
190
    pub format: String,
191
    pub lines_found: i64,
192
    pub lines_hit: i64,
193
    pub functions_found: i64,
194
    pub functions_hit: i64,
195
    pub branches_found: i64,
196
    pub branches_hit: i64,
c987c865 Andy McCall ↶ 197
    pub hits: i64,
554ccacf Andy McCall ↶ 198
    pub files: i64,
199
    pub dropped: i64,
200
    pub created_ms: i64,
201
}
202
203
impl Report {
c987c865 Andy McCall ↶ 204
    /// How often an instrumented line ran, on average.
205
    pub fn hits_per_line(&self) -> Option<f64> {
206
        (self.lines_found > 0).then(|| self.hits as f64 / self.lines_found as f64)
207
    }
208
554ccacf Andy McCall ↶ 209
    pub fn percent(&self) -> Option<f64> {
210
        percent(self.lines_hit, self.lines_found)
211
    }
212
213
    pub fn functions_percent(&self) -> Option<f64> {
214
        percent(self.functions_hit, self.functions_found)
215
    }
216
217
    pub fn branches_percent(&self) -> Option<f64> {
218
        percent(self.branches_hit, self.branches_found)
219
    }
220
221
    pub fn head_list(&self) -> Vec<&str> {
222
        self.heads.split(',').filter(|h| !h.is_empty()).collect()
223
    }
224
}
225
226
#[derive(Clone, Debug, sqlx::FromRow)]
227
pub struct FileRow {
228
    pub report_id: i64,
229
    pub path: String,
230
    pub lines_found: i64,
231
    pub lines_hit: i64,
232
    pub functions_found: i64,
233
    pub functions_hit: i64,
234
    pub branches_found: i64,
235
    pub branches_hit: i64,
236
}
237
238
impl FileRow {
239
    pub fn percent(&self) -> Option<f64> {
240
        percent(self.lines_hit, self.lines_found)
241
    }
242
243
    pub fn missed(&self) -> i64 {
244
        self.lines_found - self.lines_hit
245
    }
246
}
247
248
/// Repositories with a report, so their pages show the Coverage tab:
249
/// keyed by the hub's repository root and the id, unique even between
250
/// hubs in one process.
251
static HAS: Mutex<Option<HashSet<String>>> = Mutex::new(None);
252
253
fn key(app: &Shared, repo_id: i64) -> String {
254
    format!("{}#{repo_id}", app.repos.root().display())
255
}
256
257
pub fn has_reports(app: &Shared, repo_id: i64) -> bool {
258
    HAS.lock().unwrap_or_else(|p| p.into_inner()).as_ref().is_some_and(|s| s.contains(&key(app, repo_id)))
259
}
260
261
fn mark(app: &Shared, repo_id: i64) {
262
    HAS.lock().unwrap_or_else(|p| p.into_inner()).get_or_insert_with(HashSet::new).insert(key(app, repo_id));
263
}
264
265
/// At start: which repositories have reports.
266
pub async fn load(app: &Shared) -> sqlx::Result<()> {
267
    let ids: Vec<(i64,)> = sqlx::query_as("SELECT DISTINCT repo_id FROM coverage_reports").fetch_all(&app.db).await?;
268
    for (id,) in ids {
269
        mark(app, id);
270
    }
271
    Ok(())
272
}
273
274
/// What a run's report is kept with.
275
pub struct Origin<'a> {
276
    pub repo_id: i64,
277
    pub run_id: i64,
278
    pub run_number: i64,
279
    pub job_id: i64,
280
    pub job: &'a str,
281
    pub bookmark: &'a str,
282
    pub state: &'a str,
283
    pub heads: &'a [String],
284
    pub blob: &'a str,
285
}
286
287
/// Keep a parsed report: the files outside `in_state` are dropped and
288
/// counted. Replaces an earlier report of the same job.
289
pub async fn keep(app: &Shared, o: &Origin<'_>, files: Vec<FileCoverage>, outside: usize, in_state: &HashSet<String>) -> sqlx::Result<i64> {
290
    let (kept, missing): (Vec<FileCoverage>, Vec<FileCoverage>) = files.into_iter().partition(|f| in_state.contains(&f.path));
291
    let sum = |f: &dyn Fn(&FileCoverage) -> u64| kept.iter().map(f).sum::<u64>() as i64;
292
    let mut tx = crate::db::begin_write(&app.db).await?;
293
    sqlx::query("DELETE FROM coverage_reports WHERE job_id = ?").bind(o.job_id).execute(&mut *tx).await?;
294
    let id: i64 = sqlx::query_scalar(
295
        "INSERT INTO coverage_reports (repo_id, run_id, job_id, job, run_number, bookmark, state, heads, blob, format, \
c987c865 Andy McCall ↶ 296
         lines_found, lines_hit, functions_found, functions_hit, branches_found, branches_hit, hits, files, dropped, created_ms) \
297
         VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'lcov', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id",
554ccacf Andy McCall ↶ 298
    )
299
    .bind(o.repo_id)
300
    .bind(o.run_id)
301
    .bind(o.job_id)
302
    .bind(o.job)
303
    .bind(o.run_number)
304
    .bind(o.bookmark)
305
    .bind(o.state)
306
    .bind(o.heads.join(","))
307
    .bind(o.blob)
308
    .bind(sum(&|f| f.lines_found()))
309
    .bind(sum(&|f| f.lines_hit()))
310
    .bind(sum(&|f| f.functions_found))
311
    .bind(sum(&|f| f.functions_hit))
312
    .bind(sum(&|f| f.branches_found))
313
    .bind(sum(&|f| f.branches_hit))
c987c865 Andy McCall ↶ 314
    .bind(kept.iter().fold(0u64, |a, f| a.saturating_add(f.hits())).min(i64::MAX as u64) as i64)
554ccacf Andy McCall ↶ 315
    .bind(kept.len() as i64)
316
    .bind((missing.len() + outside) as i64)
317
    .bind(now_ms())
318
    .fetch_one(&mut *tx)
319
    .await?;
320
    for f in &kept {
321
        sqlx::query(
322
            "INSERT INTO coverage_files (report_id, path, lines_found, lines_hit, functions_found, functions_hit, branches_found, branches_hit) \
323
             VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
324
        )
325
        .bind(id)
326
        .bind(&f.path)
327
        .bind(f.lines_found() as i64)
328
        .bind(f.lines_hit() as i64)
329
        .bind(f.functions_found as i64)
330
        .bind(f.functions_hit as i64)
331
        .bind(f.branches_found as i64)
332
        .bind(f.branches_hit as i64)
333
        .execute(&mut *tx)
334
        .await?;
335
    }
336
    tx.commit().await?;
337
    mark(app, o.repo_id);
338
    Ok(id)
339
}
340
341
pub async fn report(pool: &Pool, repo_id: i64, id: i64) -> sqlx::Result<Option<Report>> {
342
    sqlx::query_as("SELECT * FROM coverage_reports WHERE id = ? AND repo_id = ?").bind(id).bind(repo_id).fetch_optional(pool).await
343
}
344
345
/// The newest reports on a bookmark, newest first.
346
pub async fn on_bookmark(pool: &Pool, repo_id: i64, bookmark: &str, limit: i64) -> sqlx::Result<Vec<Report>> {
347
    sqlx::query_as("SELECT * FROM coverage_reports WHERE repo_id = ? AND bookmark = ? ORDER BY created_ms DESC, id DESC LIMIT ?")
348
        .bind(repo_id)
349
        .bind(bookmark)
350
        .bind(limit)
c987c865 Andy McCall ↶ 351
        .fetch_all(pool)
352
        .await
353
}
354
355
/// When the repository's first report on any bookmark was kept.
356
pub async fn first_ms(pool: &Pool, repo_id: i64) -> sqlx::Result<Option<i64>> {
357
    sqlx::query_scalar("SELECT MIN(created_ms) FROM coverage_reports WHERE repo_id = ?").bind(repo_id).fetch_one(pool).await
358
}
359
360
/// The bookmarks with reports, the most recent first.
361
pub async fn bookmarks(pool: &Pool, repo_id: i64) -> sqlx::Result<Vec<String>> {
362
    sqlx::query_scalar("SELECT bookmark FROM coverage_reports WHERE repo_id = ? GROUP BY bookmark ORDER BY MAX(created_ms) DESC")
363
        .bind(repo_id)
554ccacf Andy McCall ↶ 364
        .fetch_all(pool)
365
        .await
366
}
367
368
pub async fn for_run(pool: &Pool, run_id: i64) -> sqlx::Result<Vec<Report>> {
369
    sqlx::query_as("SELECT * FROM coverage_reports WHERE run_id = ? ORDER BY job").bind(run_id).fetch_all(pool).await
370
}
371
372
pub async fn files(pool: &Pool, report_id: i64) -> sqlx::Result<Vec<FileRow>> {
373
    sqlx::query_as("SELECT * FROM coverage_files WHERE report_id = ? ORDER BY path").bind(report_id).fetch_all(pool).await
374
}
375
376
#[cfg(test)]
377
mod tests {
378
    use super::*;
379
380
    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\
381
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\
382
SF:/src/crates/a/src/lib.rs\nDA:9,1\nend_of_record\n\
383
SF:./README.md\nDA:1,1\nend_of_record\n\
384
SF:/home/runner/.cargo/registry/src/dep/lib.rs\nDA:1,1\nend_of_record\n";
385
386
    #[test]
387
    fn lcov_reports_are_read_and_merged() {
388
        let (files, outside) = parse_lcov(LCOV).unwrap();
389
        assert_eq!(outside, 1, "the dependency outside the workspace");
390
        assert_eq!(files.len(), 2);
391
        let lib = &files[1];
392
        assert_eq!(lib.path, "crates/a/src/lib.rs");
393
        assert_eq!(lib.lines, [(3, 4), (4, 4), (9, 1), (10, 0)].into_iter().collect());
394
        assert_eq!((lib.lines_found(), lib.lines_hit()), (4, 3), "the second record ran line 9");
395
        assert_eq!((lib.functions_found, lib.functions_hit), (2, 1));
396
        assert_eq!((lib.branches_found, lib.branches_hit), (2, 1));
397
        assert_eq!(files[0].path, "README.md");
398
        assert_eq!(lib.declared_lines, None, "two records: counted from the lines");
399
        // One record whose totals name lines its DA lines leave out, as llvm-cov writes.
400
        let (one, _) = parse_lcov("SF:/src/a.rs\nDA:1,1\nDA:2,0\nLF:5\nLH:3\nend_of_record\n").unwrap();
401
        assert_eq!((one[0].lines_found(), one[0].lines_hit()), (5, 3));
402
        assert!(parse_lcov("not a report\n").unwrap_err().contains("not an LCOV report"));
403
    }
404
405
    #[test]
406
    fn paths_are_taken_relative_to_the_workspace() {
407
        assert_eq!(relative("/src/a/b.rs").as_deref(), Some("a/b.rs"));
408
        assert_eq!(relative("./a/b.rs").as_deref(), Some("a/b.rs"));
409
        assert_eq!(relative("a/b.rs").as_deref(), Some("a/b.rs"));
410
        for bad in ["/etc/passwd", "a/../b", "", "/src/", "a//b", "C:\\x\\y.rs"] {
411
            assert_eq!(relative(bad), None, "{bad}");
412
        }
413
        assert_eq!(percent(1, 3), Some(33.3));
414
        assert_eq!(percent(0, 0), None);
415
    }
416
}