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

/// 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,
    /// The potential impact of the issue found (info, minor, major, critical, or blocker)
    pub severity: String,
}

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, severity: &str) -> Self {
        Self {
            description: String::from(message),
            fingerprint: Self::calculate_fingerprint(message, file, line),
            location: Location {
                path: String::from(file),
                lines: Lines { begin: line },
            },
            severity: String::from(severity),
        }
    }
}

/// 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,
                        match message.level {
                            DiagnosticLevel::Help | DiagnosticLevel::Note => "info",
                            DiagnosticLevel::Warning => "minor",
                            DiagnosticLevel::Error => "major",
                            _ => "",
                        },
                    )
                })
                .collect()
        }
        _ => vec![],
    }
}

fn process<R: BufRead>(reader: R) -> Result<Vec<GitLabCQ>, std::io::Error> {
    process_results(Message::parse_stream(reader), |input| {
        input
            .flat_map(|message| parse_compiler_message(&message))
            .collect()
    })
}

/// Returns a vector of `GitLabCQ` serialized into a JSON stream
///
/// # Arguments
///
/// * `reader` - A `BufRead` of cargo output
/// * `writer` - A `Writer` to write the results to
pub fn parse_to_writer<R: BufRead, W: Write>(reader: R, writer: W) -> Result<(), Error> {
    let results = process(reader)?;
    serde_json::to_writer_pretty(writer, &results)?;
    Ok(())
}

/// Returns a vector of `GitLabCQ` serialized into a JSON string
///
/// # Arguments
///
/// * `reader` - A `BufRead` of cargo output
pub fn parse_to_string<R: BufRead>(reader: R) -> Result<String, Error> {
    let results = process(reader)?;
    let json = serde_json::to_string_pretty(&results)?;
    Ok(json)
}

/// Deprecated, please use lib::parse_to_string() instead.
///
/// # Arguments
///
/// * `reader` - A `BufRead` of cargo output
#[deprecated(since = "0.2.0", note = "please use `lib::parse_to_string` instead")]
pub fn parse<R: BufRead>(reader: R) -> Result<String, Error> {
    parse_to_string(reader)
}

#[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);
        }
    }
}