1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
use std::convert::From;
use std::{fs, io::Write};

use crate::config::Config;
use crate::errors::*;
use crate::traces::{Trace, TraceMap};
use std::slice::Iter;

use serde::Serialize;

#[derive(Serialize)]
struct SourceFile {
    path: Vec<String>,
    content: String,
    traces: Vec<Trace>,
    covered: usize,
    coverable: usize,
}

#[derive(Serialize)]
pub struct CoverageReport {
    files: Vec<SourceFile>,
}

impl CoverageReport {
    fn iter(&self) -> Iter<SourceFile> {
        self.files.iter()
    }

    pub fn covered(&self) -> Vec<usize> {
        self.iter().map(|r| r.covered).collect()
    }

    pub fn coverable(&self) -> Vec<usize> {
        self.iter().map(|r| r.coverable).collect()
    }
}

impl From<&TraceMap> for Vec<SourceFile> {
    fn from(coverage_data: &TraceMap) -> Self {
        coverage_data
            .iter()
            .map(|(path, traces)| -> Result<SourceFile, RunError> {
                let content = fs::read_to_string(path).map_err(RunError::from)?;
                Ok(SourceFile {
                    path: path
                        .components()
                        .map(|c| c.as_os_str().to_string_lossy().to_string())
                        .collect(),
                    content,
                    traces: traces.clone(),
                    covered: coverage_data.covered_in_path(path),
                    coverable: coverage_data.coverable_in_path(path),
                })
            })
            .filter_map(Result::ok)
            .collect()
    }
}

impl From<&TraceMap> for CoverageReport {
    fn from(coverage_data: &TraceMap) -> Self {
        CoverageReport {
            files: Vec::<SourceFile>::from(coverage_data),
        }
    }
}

type JsonStringResult = Result<String, serde_json::error::Error>;

impl From<&TraceMap> for JsonStringResult {
    fn from(val: &TraceMap) -> Self {
        serde_json::to_string(&CoverageReport::from(val))
    }
}

pub fn export(coverage_data: &TraceMap, config: &Config) -> Result<(), RunError> {
    let file_path = config.output_dir().join("tarpaulin-report.json");
    let report: JsonStringResult = coverage_data.into();
    fs::File::create(file_path)?
        .write_all(report?.as_bytes())
        .map_err(RunError::from)
}