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
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
use crate::config::*;
use crate::errors::*;
use crate::test_loader::TracerData;
use crate::traces::*;
use log::{error, info};
use serde::Serialize;
use std::fs::{create_dir_all, File};
use std::io::BufReader;

pub mod cobertura;
pub mod coveralls;
pub mod html;
pub mod lcov;
mod safe_json;
/// Trait for report formats to implement.
/// Currently reports must be serializable using serde
pub trait Report<Out: Serialize> {
    /// Export coverage report
    fn export(coverage_data: &[TracerData], config: &Config);
}

/// Reports the test coverage using the users preferred method. See config.rs
/// or help text for details.
pub fn report_coverage(config: &Config, result: &TraceMap) -> Result<(), RunError> {
    if !result.is_empty() {
        info!("Coverage Results:");
        if config.verbose {
            print_missing_lines(config, result);
        }
        print_summary(config, result);
        generate_requested_reports(config, result)?;
        if let Some(project_dir) = config.manifest.parent() {
            let mut report_dir = project_dir.join("target");
            report_dir.push("tarpaulin");
            report_dir.push("coverage.json");
            let file = File::create(&report_dir)
                .map_err(|_| RunError::CovReport("Failed to create run report".to_string()))?;
            serde_json::to_writer(&file, &result)
                .map_err(|_| RunError::CovReport("Failed to save run report".to_string()))?;
        }
        Ok(())
    } else if !config.no_run {
        Err(RunError::CovReport(
            "No coverage results collected.".to_string(),
        ))
    } else {
        Ok(())
    }
}

fn generate_requested_reports(config: &Config, result: &TraceMap) -> Result<(), RunError> {
    if config.is_coveralls() {
        coveralls::export(result, config)?;
        info!("Coverage data sent");
    }

    if !config.is_default_output_dir() {
        if create_dir_all(&config.output_directory).is_err() {
            return Err(RunError::OutFormat(format!(
                "Failed to create or locate custom output directory: {:?}",
                config.output_directory,
            )));
        }
    }

    for g in &config.generate {
        match *g {
            OutputFile::Xml => {
                cobertura::report(result, config).map_err(|e| RunError::XML(e))?;
            }
            OutputFile::Html => {
                html::export(result, config)?;
            }
            OutputFile::Lcov => {
                lcov::export(result, config)?;
            }
            _ => {
                return Err(RunError::OutFormat(
                    "Output format is currently not supported!".to_string(),
                ));
            }
        }
    }
    Ok(())
}

fn print_missing_lines(config: &Config, result: &TraceMap) {
    println!("|| Uncovered Lines:");
    for (ref key, ref value) in result.iter() {
        let path = config.strip_base_dir(key);
        let mut uncovered_lines = vec![];
        for v in value.iter() {
            match v.stats {
                CoverageStat::Line(count) if count == 0 => {
                    uncovered_lines.push(v.line);
                }
                _ => (),
            }
        }
        uncovered_lines.sort();
        let (groups, last_group) = uncovered_lines
            .into_iter()
            .fold((vec![], vec![]), accumulate_lines);
        let (groups, _) = accumulate_lines((groups, last_group), u64::max_value());
        if !groups.is_empty() {
            println!("|| {}: {}", path.display(), groups.join(", "));
        }
    }
}

fn get_previous_result(config: &Config) -> Option<TraceMap> {
    // Check for previous report
    if let Some(project_dir) = config.manifest.parent() {
        let mut report_dir = project_dir.join("target");
        report_dir.push("tarpaulin");
        if report_dir.exists() {
            // is report there?
            report_dir.push("coverage.json");
            let file = File::open(&report_dir).ok()?;
            let reader = BufReader::new(file);
            serde_json::from_reader(reader).ok()
        } else {
            // make directory
            std::fs::create_dir(&report_dir)
                .unwrap_or_else(|e| error!("Failed to create report directory: {}", e));
            None
        }
    } else {
        None
    }
}

fn print_summary(config: &Config, result: &TraceMap) {
    let last = match get_previous_result(config) {
        Some(l) => l,
        None => TraceMap::new(),
    };
    println!("|| Tested/Total Lines:");
    for file in result.files() {
        let path = config.strip_base_dir(file);
        if last.contains_file(file) {
            let last_percent = coverage_percentage(&last.get_child_traces(file));
            let current_percent = coverage_percentage(&result.get_child_traces(file));
            let delta = 100.0f64 * (current_percent - last_percent);
            println!(
                "|| {}: {}/{} {:+}%",
                path.display(),
                result.covered_in_path(&file),
                result.coverable_in_path(&file),
                delta
            );
        } else {
            println!(
                "|| {}: {}/{}",
                path.display(),
                result.covered_in_path(&file),
                result.coverable_in_path(&file)
            );
        }
    }
    let percent = result.coverage_percentage() * 100.0f64;
    if last.is_empty() {
        println!(
            "|| \n{:.2}% coverage, {}/{} lines covered",
            percent,
            result.total_covered(),
            result.total_coverable()
        );
    } else {
        let delta = percent - 100.0f64 * last.coverage_percentage();
        println!(
            "|| \n{:.2}% coverage, {}/{} lines covered, {:+}% change in coverage",
            percent,
            result.total_covered(),
            result.total_coverable(),
            delta
        );
    }
}

fn accumulate_lines(
    (mut acc, mut group): (Vec<String>, Vec<u64>),
    next: u64,
) -> (Vec<String>, Vec<u64>) {
    if let Some(last) = group.last().cloned() {
        if next == last + 1 {
            group.push(next);
            (acc, group)
        } else {
            match (group.first(), group.last()) {
                (Some(first), Some(last)) if first == last => {
                    acc.push(format!("{}", first));
                }
                (Some(first), Some(last)) => {
                    acc.push(format!("{}-{}", first, last));
                }
                (Some(_), None) | (None, _) => (),
            };
            (acc, vec![next])
        }
    } else {
        group.push(next);
        (acc, group)
    }
}