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
use cargo_metadata::Message;
use failure::Error;
use itertools::process_results;
use md5::compute;
use serde::Serialize;
use std::io::BufRead;

/// Code Quality report artifact implementing a subset of the Code Climate spec
/// per [documentation](https://docs.gitlab.com/ee/user/project/merge_requests/code_quality.html#implementing-a-custom-tool)
#[derive(Debug, Serialize)]
pub struct GitLabCQ {
    /// A description of the code quality violation
    pub description: String,
    /// A unique fingerprint to identify the code quality violation
    pub fingerprint: String,
    /// See `Location` documentation for details
    pub location: Location,
}

impl GitLabCQ {
    /// Calculates MD5 hash from parameters
    fn calculate_fingerprint(message: &str, file: &str, line: usize) -> String {
        let fingerprint = format!("{}{}{}", message, file, line);
        let digest = compute(Vec::from(fingerprint));
        format!("{:x}", digest)
    }

    /// Easy to use constructor
    pub fn new(message: &str, file: &str, line: usize) -> Self {
        Self {
            description: String::from(message),
            fingerprint: Self::calculate_fingerprint(message, file, line),
            location: Location {
                path: String::from(file),
                lines: Lines { begin: line },
            },
        }
    }
}

/// The relative path to the file containing the code quality violation
#[derive(Debug, Serialize)]
pub struct Location {
    /// The relative path to the file
    pub path: String,
    /// See `Lines` documentation for details
    pub lines: Lines,
}

#[derive(Debug, Serialize)]
/// Contains the line information for code quality violation
pub struct Lines {
    /// The line on which the code quality violation occurred
    pub begin: usize,
}

/// Returns a vector of `GitLabCQ` from a compiler message
///
/// # Arguments
///
/// * `message` - A cargo message
fn parse_compiler_message(message: &Message) -> Vec<GitLabCQ> {
    match message {
        Message::CompilerMessage(msg) => {
            let message = &msg.message;
            message
                .spans
                .iter()
                .map(|span| GitLabCQ::new(&message.message, &span.file_name, span.line_start))
                .collect()
        }
        _ => vec![],
    }
}

/// Returns a vector of `GitLabCQ` serialized into JSON
///
/// # Arguments
///
/// * `reader` - A `BufRead` of cargo output
pub fn parse<R: BufRead>(reader: R) -> Result<String, Error> {
    let result: Result<Vec<GitLabCQ>, std::io::Error> =
        process_results(Message::parse_stream(reader), |input| {
            input
                .flat_map(|message| parse_compiler_message(&message))
                .collect()
        });
    let results = result?;
    let json = serde_json::to_string_pretty(&results)?;
    Ok(json)
}

#[cfg(test)]
mod tests {
    use super::*;
    use proptest::prelude::*;

    proptest! {
        #[test]
        fn fingerprint_is_unique(message1 in "\\PC*", message2 in "\\PC*", file1 in "\\PC*", file2 in "\\PC*", line1 in 0usize..10000, line2 in 0usize..10000) {
            let fingerprint1 = GitLabCQ::calculate_fingerprint(&message1, &file1, line1);
            let fingerprint2 = GitLabCQ::calculate_fingerprint(&message2, &file2, line2);
            assert_ne!(fingerprint1, fingerprint2);
        }
    }
}