|
| 1 | +use std::{ |
| 2 | + collections::HashSet, |
| 3 | + hash::{DefaultHasher, Hash, Hasher}, |
| 4 | + path::Path, |
| 5 | +}; |
| 6 | + |
| 7 | +use ruff_source_file::LineColumn; |
| 8 | +use serde::{Serialize, Serializer, ser::SerializeSeq}; |
| 9 | + |
| 10 | +use crate::diagnostic::{Diagnostic, Severity}; |
| 11 | + |
| 12 | +use super::FileResolver; |
| 13 | + |
| 14 | +pub(super) struct GitlabRenderer<'a> { |
| 15 | + resolver: &'a dyn FileResolver, |
| 16 | +} |
| 17 | + |
| 18 | +impl<'a> GitlabRenderer<'a> { |
| 19 | + pub(super) fn new(resolver: &'a dyn FileResolver) -> Self { |
| 20 | + Self { resolver } |
| 21 | + } |
| 22 | +} |
| 23 | + |
| 24 | +impl GitlabRenderer<'_> { |
| 25 | + pub(super) fn render( |
| 26 | + &self, |
| 27 | + f: &mut std::fmt::Formatter, |
| 28 | + diagnostics: &[Diagnostic], |
| 29 | + ) -> std::fmt::Result { |
| 30 | + write!( |
| 31 | + f, |
| 32 | + "{}", |
| 33 | + serde_json::to_string_pretty(&SerializedMessages { |
| 34 | + diagnostics, |
| 35 | + resolver: self.resolver, |
| 36 | + #[expect( |
| 37 | + clippy::disallowed_methods, |
| 38 | + reason = "We don't have access to a `System` here, \ |
| 39 | + and this is only intended for use by GitLab CI, \ |
| 40 | + which runs on a real `System`." |
| 41 | + )] |
| 42 | + project_dir: std::env::var("CI_PROJECT_DIR").ok().as_deref(), |
| 43 | + }) |
| 44 | + .unwrap() |
| 45 | + ) |
| 46 | + } |
| 47 | +} |
| 48 | + |
| 49 | +struct SerializedMessages<'a> { |
| 50 | + diagnostics: &'a [Diagnostic], |
| 51 | + resolver: &'a dyn FileResolver, |
| 52 | + project_dir: Option<&'a str>, |
| 53 | +} |
| 54 | + |
| 55 | +impl Serialize for SerializedMessages<'_> { |
| 56 | + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> |
| 57 | + where |
| 58 | + S: Serializer, |
| 59 | + { |
| 60 | + let mut s = serializer.serialize_seq(Some(self.diagnostics.len()))?; |
| 61 | + let mut fingerprints = HashSet::<u64>::with_capacity(self.diagnostics.len()); |
| 62 | + |
| 63 | + for diagnostic in self.diagnostics { |
| 64 | + let location = diagnostic |
| 65 | + .primary_span() |
| 66 | + .map(|span| { |
| 67 | + let file = span.file(); |
| 68 | + let positions = if self.resolver.is_notebook(file) { |
| 69 | + // We can't give a reasonable location for the structured formats, |
| 70 | + // so we show one that's clearly a fallback |
| 71 | + Default::default() |
| 72 | + } else { |
| 73 | + let diagnostic_source = file.diagnostic_source(self.resolver); |
| 74 | + let source_code = diagnostic_source.as_source_code(); |
| 75 | + span.range() |
| 76 | + .map(|range| Positions { |
| 77 | + begin: source_code.line_column(range.start()), |
| 78 | + end: source_code.line_column(range.end()), |
| 79 | + }) |
| 80 | + .unwrap_or_default() |
| 81 | + }; |
| 82 | + |
| 83 | + let path = self.project_dir.as_ref().map_or_else( |
| 84 | + || file.relative_path(self.resolver).display().to_string(), |
| 85 | + |project_dir| relativize_path_to(file.path(self.resolver), project_dir), |
| 86 | + ); |
| 87 | + |
| 88 | + Location { path, positions } |
| 89 | + }) |
| 90 | + .unwrap_or_default(); |
| 91 | + |
| 92 | + let mut message_fingerprint = fingerprint(diagnostic, &location.path, 0); |
| 93 | + |
| 94 | + // Make sure that we do not get a fingerprint that is already in use |
| 95 | + // by adding in the previously generated one. |
| 96 | + while fingerprints.contains(&message_fingerprint) { |
| 97 | + message_fingerprint = fingerprint(diagnostic, &location.path, message_fingerprint); |
| 98 | + } |
| 99 | + fingerprints.insert(message_fingerprint); |
| 100 | + |
| 101 | + let description = diagnostic.body(); |
| 102 | + let check_name = diagnostic.secondary_code_or_id(); |
| 103 | + let severity = match diagnostic.severity() { |
| 104 | + Severity::Info => "info", |
| 105 | + Severity::Warning => "minor", |
| 106 | + Severity::Error => "major", |
| 107 | + // Another option here is `blocker` |
| 108 | + Severity::Fatal => "critical", |
| 109 | + }; |
| 110 | + |
| 111 | + let value = Message { |
| 112 | + check_name, |
| 113 | + // GitLab doesn't display the separate `check_name` field in a Code Quality report, |
| 114 | + // so prepend it to the description too. |
| 115 | + description: format!("{check_name}: {description}"), |
| 116 | + severity, |
| 117 | + fingerprint: format!("{:x}", message_fingerprint), |
| 118 | + location, |
| 119 | + }; |
| 120 | + |
| 121 | + s.serialize_element(&value)?; |
| 122 | + } |
| 123 | + |
| 124 | + s.end() |
| 125 | + } |
| 126 | +} |
| 127 | + |
| 128 | +#[derive(Serialize)] |
| 129 | +struct Message<'a> { |
| 130 | + check_name: &'a str, |
| 131 | + description: String, |
| 132 | + severity: &'static str, |
| 133 | + fingerprint: String, |
| 134 | + location: Location, |
| 135 | +} |
| 136 | + |
| 137 | +/// The place in the source code where the issue was discovered. |
| 138 | +/// |
| 139 | +/// According to the CodeClimate report format [specification] linked from the GitLab [docs], this |
| 140 | +/// field is required, so we fall back on a default `path` and position if the diagnostic doesn't |
| 141 | +/// have a primary span. |
| 142 | +/// |
| 143 | +/// [specification]: https://github.com/codeclimate/platform/blob/master/spec/analyzers/SPEC.md#data-types |
| 144 | +/// [docs]: https://docs.gitlab.com/ci/testing/code_quality/#code-quality-report-format |
| 145 | +#[derive(Default, Serialize)] |
| 146 | +struct Location { |
| 147 | + path: String, |
| 148 | + positions: Positions, |
| 149 | +} |
| 150 | + |
| 151 | +#[derive(Default, Serialize)] |
| 152 | +struct Positions { |
| 153 | + begin: LineColumn, |
| 154 | + end: LineColumn, |
| 155 | +} |
| 156 | + |
| 157 | +/// Generate a unique fingerprint to identify a violation. |
| 158 | +fn fingerprint(diagnostic: &Diagnostic, project_path: &str, salt: u64) -> u64 { |
| 159 | + let mut hasher = DefaultHasher::new(); |
| 160 | + |
| 161 | + salt.hash(&mut hasher); |
| 162 | + diagnostic.name().hash(&mut hasher); |
| 163 | + project_path.hash(&mut hasher); |
| 164 | + |
| 165 | + hasher.finish() |
| 166 | +} |
| 167 | + |
| 168 | +/// Convert an absolute path to be relative to the specified project root. |
| 169 | +fn relativize_path_to<P: AsRef<Path>, R: AsRef<Path>>(path: P, project_root: R) -> String { |
| 170 | + format!( |
| 171 | + "{}", |
| 172 | + pathdiff::diff_paths(&path, project_root) |
| 173 | + .expect("Could not diff paths") |
| 174 | + .display() |
| 175 | + ) |
| 176 | +} |
| 177 | + |
| 178 | +#[cfg(test)] |
| 179 | +mod tests { |
| 180 | + use crate::diagnostic::{ |
| 181 | + DiagnosticFormat, |
| 182 | + render::tests::{create_diagnostics, create_syntax_error_diagnostics}, |
| 183 | + }; |
| 184 | + |
| 185 | + const FINGERPRINT_FILTERS: [(&str, &str); 1] = [( |
| 186 | + r#""fingerprint": "[a-z0-9]+","#, |
| 187 | + r#""fingerprint": "<redacted>","#, |
| 188 | + )]; |
| 189 | + |
| 190 | + #[test] |
| 191 | + fn output() { |
| 192 | + let (env, diagnostics) = create_diagnostics(DiagnosticFormat::Gitlab); |
| 193 | + insta::with_settings!({filters => FINGERPRINT_FILTERS}, { |
| 194 | + insta::assert_snapshot!(env.render_diagnostics(&diagnostics)); |
| 195 | + }); |
| 196 | + } |
| 197 | + |
| 198 | + #[test] |
| 199 | + fn syntax_errors() { |
| 200 | + let (env, diagnostics) = create_syntax_error_diagnostics(DiagnosticFormat::Gitlab); |
| 201 | + insta::with_settings!({filters => FINGERPRINT_FILTERS}, { |
| 202 | + insta::assert_snapshot!(env.render_diagnostics(&diagnostics)); |
| 203 | + }); |
| 204 | + } |
| 205 | +} |
0 commit comments