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
extern crate serde;
extern crate serde_json;
#[macro_use]
extern crate serde_derive;
extern crate md5;

use std::io;
use std::path::Path;
use std::fs::File;
use std::io::prelude::*;
use std::ops::Deref;
use std::collections::HashMap;
use serde::ser::{Serialize, Serializer, SerializeStruct};



/// Representation of branch data
pub struct BranchData {
    pub line_number: usize,
    pub block_name: usize,
    pub branch_number: usize,
    pub hits: usize,
}


fn expand_lines(lines: &HashMap<usize, usize>, line_count: usize) -> Vec<Option<usize>> {
    (0..line_count).map(|x| match lines.get(&(x+1)){
        Some(x) => Some(*x),
        None => None
    }).collect::<Vec<Option<usize>>>()
}


fn expand_branches(branches: &Vec<BranchData>) -> Vec<usize> {
    branches.iter()
            .flat_map(|x| vec![x.line_number, x.block_name, x.branch_number, x.hits])
            .collect::<Vec<usize>>()
}




/// Struct representing source files and the coverage for coveralls
#[derive(Serialize)]
pub struct Source {
    /// Name of the source file. Represented as path relative to root of repo
    name: String,
    /// MD5 hash of the source file
    source_digest: [u8; 16],
    /// Coverage for the source. Each element is a line with the following rules:
    /// None - not relevant to coverage
    /// 0 - not covered
    /// 1+ - covered and how often
    coverage: Vec<Option<usize>>,
    /// Branch data for branch coverage.
    #[serde(skip_serializing_if="Option::is_none")]
    branches: Option<Vec<usize>>,
    /// Contents of the source file (Manual Repos on Enterprise only)
    #[serde(skip_serializing_if="Option::is_none")]
    source: Option<String>
}


impl Source {
    /// Creates a source description for a given file.
    /// display_name: Name given to the source file
    /// repo_path - Path to file relative to repository root 
    /// path - absolute path on file system
    /// lines - map of line numbers to hits
    /// branches - optional, vector of branches in code
    pub fn new(repo_path: &Path, 
           path: &Path, 
           lines: &HashMap<usize, usize>, 
           branches: &Option<Vec<BranchData>>,
           include_source: bool) -> Result<Source, io::Error> {
        
        let mut code = File::open(path)?;
        let mut content = String::new();
        code.read_to_string(&mut content)?;
        let src = if include_source {
            Some(content.clone())
        } else {
            None
        };

        let brch = match branches {
            &Some(ref b) => Some(expand_branches(&b)),
            &None => None,
        };
        let line_count = content.lines().count();
        Ok(Source {
            name: repo_path.to_str().unwrap_or("").to_string(),
            source_digest: *md5::compute(content).deref(),
            coverage:  expand_lines(lines, line_count),
            branches: brch,
            source:src,
        })
    }
}


/// Service's are used for CI integration. Coveralls current supports
/// * travis ci
/// * travis pro
/// * circleCI
/// * Semaphore
/// * JenkinsCI
/// * Codeship
pub struct Service {
    service_name: String,
    service_job_id: String,
}

/// Repo tokens are alternatives to Services and involve a secret token on coveralls
pub enum Identity {
    RepoToken(String),
    ServiceToken(Service)
}


/// Coveralls report struct 
/// for more details: https://coveralls.zendesk.com/hc/en-us/articles/201350799-API-Reference 
pub struct CoverallsReport {
    id: Identity,
    /// List of source files which includes coverage information.
    source_files: Vec<Source>,
}


impl CoverallsReport {
    /// Create new coveralls report given a unique identifier which allows 
    /// coveralls to identify the user and project
    pub fn new(id: Identity) -> CoverallsReport {
        CoverallsReport {
            id: id,
            source_files: Vec::new()
        }
    }

    /// Add generated source data to coveralls report.
    pub fn add_source(&mut self, source: Source) {
        self.source_files.push(source);
    }
}


impl Serialize for CoverallsReport {
    
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer {
        let size = 1 + match self.id {
            Identity::RepoToken(_) => 1,
            Identity::ServiceToken(_) => 2,
        };
        let mut s = serializer.serialize_struct("CoverallsReport", size)?;
        match self.id {
            Identity::RepoToken(ref r) => {
                s.serialize_field("repo_token", &r)?;
            },
            Identity::ServiceToken(ref serv) => {
                s.serialize_field("service_name", &serv.service_name)?;
                s.serialize_field("service_job_id", &serv.service_job_id)?;
            },
        }
        s.serialize_field("source_files", &self.source_files)?;
        s.end()
    }
}