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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
use deflate::deflate_bytes_gzip;
use reqwest::{
    blocking::{
        multipart::{Form, Part},
        Client,
    },
    StatusCode,
};
use serde::{
    ser::{SerializeStruct, Serializer},
    Deserialize, Serialize,
};
use std::collections::HashMap;
use std::env::var;
use std::fs::File;
use std::io;
use std::io::prelude::*;
use std::path::Path;
use std::str::FromStr;

/// Representation of branch data
#[derive(
    Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Default, Deserialize, Serialize,
)]
pub struct BranchData {
    pub line_number: usize,
    pub block_name: usize,
    pub branch_number: usize,
    pub hits: usize,
}

/// Expands the line map into the form expected by coveralls (includes uncoverable lines)
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>>>()
}

/// Expands branch coverage into the less user friendly format used by coveralls -
/// an array with the contents of the structs repeated one after another in an array.
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(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Default, Deserialize, 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: String,
    /// 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: format!("{:x}", md5::compute(content)),
            coverage: expand_lines(lines, line_count),
            branches: brch,
            source: src,
        })
    }
}

#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Default, Deserialize, Serialize)]
pub struct Head {
    pub id: String,
    pub author_name: String,
    pub author_email: String,
    pub committer_name: String,
    pub committer_email: String,
    pub message: String,
}

#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Default, Deserialize, Serialize)]
pub struct Remote {
    pub name: String,
    pub url: String,
}

#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Default, Deserialize, Serialize)]
pub struct GitInfo {
    pub head: Head,
    pub branch: String,
    pub remotes: Vec<Remote>,
}

/// Reports the status of a coveralls report upload.
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Deserialize, Serialize)]
pub enum UploadStatus {
    /// Upload failed. Includes HTTP error code.
    Failed(u32),
    /// Upload succeeded
    Succeeded,
    /// Waiting for response from server or timeout
    Pending,
    /// Retrieving response code resulted in a CURL error no way of determining
    /// success
    Unknown,
}

/// Continuous Integration services and the string identifiers coveralls.io
/// uses to present them.
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Deserialize, Serialize)]
pub enum CiService {
    Travis,
    TravisPro,
    Circle,
    Semaphore,
    Jenkins,
    Codeship,
    /// Other Ci Service, coveralls-ruby is a valid input which gives same features
    /// as travis for coveralls users.
    Other(String),
}

impl FromStr for CiService {
    type Err = ();

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let res = match s {
            "travis-ci" => CiService::Travis,
            "travis-pro" => CiService::TravisPro,
            "circle-ci" => CiService::Circle,
            "semaphore" => CiService::Semaphore,
            "jenkins" => CiService::Jenkins,
            "codeship" => CiService::Codeship,
            e => CiService::Other(e.to_string()),
        };
        Ok(res)
    }
}

impl CiService {
    fn value<'a>(&'a self) -> &'a str {
        use CiService::*;
        // Only travis and ruby have special features but the others might gain
        // those features in future so best to put them all for now.
        match *self {
            Travis => "travis-ci",
            TravisPro => "travis-pro",
            Other(ref x) => x.as_str(),
            Circle => "circle-ci",
            Semaphore => "semaphore",
            Jenkins => "jenkins",
            Codeship => "codeship",
        }
    }
}

/// Service's are used for CI integration. Coveralls current supports
/// * travis ci
/// * travis pro
/// * circleCI
/// * Semaphore
/// * JenkinsCI
/// * Codeship
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
pub struct Service {
    /// Name of the CiService
    pub name: CiService,
    /// Job ID
    pub job_id: Option<String>,
    /// Optional service_number
    pub number: Option<String>,
    /// Optional service_build_url
    pub build_url: Option<String>,
    /// Optional service_branch
    pub branch: Option<String>,
    /// Optional service_pull_request
    pub pull_request: Option<String>,
}

impl Service {
    pub fn from_env() -> Option<Self> {
        if var("TRAVIS").is_ok() {
            Some(Self::get_travis_env())
        } else if var("CIRCLECI").is_ok() {
            Some(Self::get_circle_env())
        } else if var("JENKINS_URL").is_ok() {
            Some(Self::get_jenkins_env())
        } else if var("SEMAPHORE").is_ok() {
            Some(Self::get_semaphore_env())
        } else {
            Self::get_generic_env()
        }
    }

    pub fn from_ci(ci: CiService) -> Option<Self> {
        use CiService::*;
        match ci {
            Travis | TravisPro => {
                let mut temp = Self::get_travis_env();
                temp.name = ci;
                Some(temp)
            }
            Circle => Some(Self::get_circle_env()),
            Semaphore => Some(Self::get_semaphore_env()),
            Jenkins => Some(Self::get_jenkins_env()),
            _ => Self::get_generic_env(),
        }
    }

    /// Gets service variables from travis environment
    /// Warning is unable to figure out if travis pro or free so assumes free
    pub fn get_travis_env() -> Self {
        let id = var("TRAVIS_JOB_ID").ok();
        let pr = match var("TRAVIS_PULL_REQUEST") {
            Ok(ref s) if s != "false" => Some(s.to_string()),
            _ => None,
        };
        let branch = var("TRAVIS_BRANCH").ok();
        Service {
            name: CiService::Travis,
            job_id: id,
            number: None,
            build_url: None,
            pull_request: pr,
            branch: branch,
        }
    }

    pub fn get_circle_env() -> Self {
        let num = var("CIRCLE_BUILD_NUM").ok();
        let branch = var("CIRCLE_BRANCH").ok();
        Service {
            name: CiService::Circle,
            job_id: None, // Not happy with this but apparently it works
            number: num,
            build_url: None,
            pull_request: None,
            branch: branch,
        }
    }

    pub fn get_jenkins_env() -> Self {
        let num = var("BUILD_NUM").ok();
        let url = var("BUILD_URL").ok();
        let branch = var("GIT_BRANCH").ok();
        Service {
            name: CiService::Jenkins,
            job_id: None, // Not happy with this but apparently it works
            number: num,
            build_url: url,
            pull_request: None,
            branch: branch,
        }
    }

    pub fn get_semaphore_env() -> Self {
        let num = var("SEMAPHORE_BUILD_NUMBER").ok();
        let pr = var("PULL_REQUEST_NUMBER").ok();
        Service {
            name: CiService::Semaphore,
            job_id: None,
            number: num,
            pull_request: pr,
            branch: None,
            build_url: None,
        }
    }

    pub fn get_generic_env() -> Option<Self> {
        let name = var("CI_NAME").ok();
        let num = var("CI_BUILD_NUMBER").ok();
        let id = var("CI_JOB_ID").ok();
        let url = var("CI_BUILD_URL").ok();
        let branch = var("CI_BRANCH").ok();
        let pr = var("CI_PULL_REQUEST").ok();
        if name.is_some()
            || num.is_some()
            || id.is_some()
            || url.is_some()
            || branch.is_some()
            || pr.is_some()
        {
            let name = name.unwrap_or_else(|| "unknown".to_string());

            Some(Service {
                name: CiService::from_str(&name).unwrap(),
                job_id: id,
                number: num,
                pull_request: pr,
                branch: branch,
                build_url: url,
            })
        } else {
            None
        }
    }
}

/// Repo tokens are alternatives to Services and involve a secret token on coveralls
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
pub enum Identity {
    RepoToken(String),
    ServiceToken(String, Service),
}

impl Identity {
    /// Creates a report identity from a coveralls repo token if one is available
    /// Only checks via environment variables - this doesn't take into account
    /// the presence of a .coveralls.yml file
    pub fn from_token() -> Option<Self> {
        match var("COVERALLS_REPO_TOKEN") {
            Ok(token) => Some(Identity::RepoToken(token)),
            _ => None,
        }
    }

    /// Creates a report identity based on the CI service auto-detect functionality
    pub fn from_env() -> Option<Self> {
        let token = match var("COVERALLS_REPO_TOKEN") {
            Ok(token) => token,
            _ => String::new(),
        };
        match Service::from_env() {
            Some(s) => Some(Identity::ServiceToken(token, s)),
            _ => None,
        }
    }

    /// Prefers a coveralls repo token otherwise falls back on CI environment
    /// variables
    pub fn best_match() -> Option<Self> {
        if let Some(s) = Self::from_env() {
            Some(s)
        } else if let Some(s) = Self::from_token() {
            Some(s)
        } else {
            None
        }
    }

    pub fn best_match_with_token(token: String) -> Self {
        if let Some(Identity::ServiceToken(_, s)) = Self::from_env() {
            Identity::ServiceToken(token, s)
        } else {
            Identity::RepoToken(token)
        }
    }
}

/// 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>,
    /// Git commit SHA
    commit: Option<String>,
    /// Git information
    git: Option<GitInfo>,
    /// Client for HTTP requests
    client: Client,
    /// Last upload status code
    last_status: UploadStatus,
}

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(),
            commit: None,
            git: None,
            client: Client::new(),
            last_status: UploadStatus::Pending,
        }
    }

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

    /// Sets the commit ID. Overrides more detailed git info
    pub fn set_commit(&mut self, commit: &str) {
        self.commit = Some(commit.to_string());
        self.git = None;
    }

    /// Set detailed git information, overrides commit ID if set.
    pub fn set_detailed_git_info(&mut self, git: GitInfo) {
        self.git = Some(git);
        self.commit = None;
    }

    /// Send report to the coveralls.io directly. For coveralls hosted on other
    /// platforms see send_to_endpoint
    pub fn send_to_coveralls(&mut self) -> Result<(), reqwest::Error> {
        self.send_to_endpoint("https://coveralls.io/api/v1/jobs")
    }

    /// Sends coveralls report to the specified url
    pub fn send_to_endpoint(&mut self, url: &str) -> Result<(), reqwest::Error> {
        let body = match serde_json::to_vec(&self) {
            Ok(body) => body,
            Err(e) => panic!("Error {}", e),
        };

        let body = deflate_bytes_gzip(&body);

        let form = Form::new().part(
            "json_file",
            Part::bytes(body).mime_str("gzip/json")?.file_name("report"),
        );

        let response = self.client.post(url).multipart(form).send()?;

        let code = response.status();
        self.last_status = match code {
            StatusCode::OK => UploadStatus::Succeeded,
            _ => UploadStatus::Failed(code.as_u16() as u32),
        };

        Ok(())
    }

    pub fn upload_status(&mut self) -> UploadStatus {
        self.last_status
    }
}

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 + self.commit.is_some() as usize,
            Identity::ServiceToken(_, _) => 2 + self.commit.is_some() as usize,
        };
        let mut s = serializer.serialize_struct("CoverallsReport", size)?;
        match self.id {
            Identity::RepoToken(ref r) => {
                s.serialize_field("repo_token", &r)?;
            }
            Identity::ServiceToken(ref r, ref serv) => {
                if !r.is_empty() {
                    s.serialize_field("repo_token", &r)?;
                }
                s.serialize_field("service_name", serv.name.value())?;
                if let Some(ref id) = serv.job_id {
                    s.serialize_field("service_job_id", id)?;
                }
                if let Some(ref num) = serv.number {
                    s.serialize_field("service_number", &num)?;
                }
                if let Some(ref url) = serv.build_url {
                    s.serialize_field("service_build_url", &url)?;
                }
                if let Some(ref branch) = serv.branch {
                    s.serialize_field("service_branch", &branch)?;
                }
                if let Some(ref pr) = serv.pull_request {
                    s.serialize_field("service_pull_request", &pr)?;
                }
            }
        }
        if let Some(ref sha) = self.commit {
            s.serialize_field("commit_sha", &sha)?;
        }
        if let Some(ref git) = self.git {
            s.serialize_field("git", &git)?;
        }
        s.serialize_field("source_files", &self.source_files)?;
        s.end()
    }
}

#[cfg(test)]
mod tests {

    use crate::*;
    use std::collections::HashMap;

    #[test]
    fn test_expand_lines() {
        let line_count = 10;
        let mut example: HashMap<usize, usize> = HashMap::new();
        example.insert(5, 1);
        example.insert(6, 1);
        example.insert(8, 2);

        let expected = vec![
            None,
            None,
            None,
            None,
            Some(1),
            Some(1),
            None,
            Some(2),
            None,
            None,
        ];

        assert_eq!(expand_lines(&example, line_count), expected);
    }

    #[test]
    fn test_branch_expand() {
        let b1 = BranchData {
            line_number: 3,
            block_name: 1,
            branch_number: 1,
            hits: 1,
        };
        let b2 = BranchData {
            line_number: 4,
            block_name: 1,
            branch_number: 2,
            hits: 0,
        };

        let v = vec![b1, b2];
        let actual = expand_branches(&v);
        let expected = vec![3, 1, 1, 1, 4, 1, 2, 0];
        assert_eq!(actual, expected);
    }
}