-
Notifications
You must be signed in to change notification settings - Fork 115
Expand file tree
/
Copy pathgitlab.rs
More file actions
245 lines (219 loc) · 7.45 KB
/
gitlab.rs
File metadata and controls
245 lines (219 loc) · 7.45 KB
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
use crate::{DiagnosticsPayload, Execution, Reporter, ReporterVisitor, TraversalSummary};
use path_absolutize::Absolutize;
use pglt_console::fmt::{Display, Formatter};
use pglt_console::{Console, ConsoleExt, markup};
use pglt_diagnostics::display::SourceFile;
use pglt_diagnostics::{Error, PrintDescription, Resource, Severity};
use serde::Serialize;
use std::sync::RwLock;
use std::{
collections::HashSet,
hash::{DefaultHasher, Hash, Hasher},
path::{Path, PathBuf},
};
pub struct GitLabReporter {
pub(crate) execution: Execution,
pub(crate) diagnostics: DiagnosticsPayload,
}
impl Reporter for GitLabReporter {
fn write(self, visitor: &mut dyn ReporterVisitor) -> std::io::Result<()> {
visitor.report_diagnostics(&self.execution, self.diagnostics)?;
Ok(())
}
}
pub(crate) struct GitLabReporterVisitor<'a> {
console: &'a mut dyn Console,
repository_root: Option<PathBuf>,
}
#[derive(Default)]
struct GitLabHasher(HashSet<u64>);
impl GitLabHasher {
/// Enforces uniqueness of generated fingerprints in the context of a
/// single report.
fn rehash_until_unique(&mut self, fingerprint: u64) -> u64 {
let mut current = fingerprint;
while self.0.contains(¤t) {
let mut hasher = DefaultHasher::new();
current.hash(&mut hasher);
current = hasher.finish();
}
self.0.insert(current);
current
}
}
impl<'a> GitLabReporterVisitor<'a> {
pub fn new(console: &'a mut dyn Console, repository_root: Option<PathBuf>) -> Self {
Self {
console,
repository_root,
}
}
}
impl ReporterVisitor for GitLabReporterVisitor<'_> {
fn report_summary(&mut self, _: &Execution, _: TraversalSummary) -> std::io::Result<()> {
Ok(())
}
fn report_diagnostics(
&mut self,
_execution: &Execution,
payload: DiagnosticsPayload,
) -> std::io::Result<()> {
let hasher = RwLock::default();
let diagnostics = GitLabDiagnostics(payload, &hasher, self.repository_root.as_deref());
self.console.log(markup!({ diagnostics }));
Ok(())
}
}
struct GitLabDiagnostics<'a>(
DiagnosticsPayload,
&'a RwLock<GitLabHasher>,
Option<&'a Path>,
);
impl GitLabDiagnostics<'_> {
fn attempt_to_relativize(&self, subject: &str) -> Option<PathBuf> {
let Ok(resolved) = Path::new(subject).absolutize() else {
return None;
};
let Ok(relativized) = resolved.strip_prefix(self.2?) else {
return None;
};
Some(relativized.to_path_buf())
}
fn compute_initial_fingerprint(&self, diagnostic: &Error, path: &str) -> u64 {
let location = diagnostic.location();
let code = match location.span {
Some(span) => match location.source_code {
Some(source_code) => &source_code.text[span],
None => "",
},
None => "",
};
let check_name = diagnostic
.category()
.map(|category| category.name())
.unwrap_or_default();
calculate_hash(&Fingerprint {
check_name,
path,
code,
})
}
}
impl Display for GitLabDiagnostics<'_> {
fn fmt(&self, fmt: &mut Formatter) -> std::io::Result<()> {
let mut hasher = self.1.write().unwrap();
let gitlab_diagnostics: Vec<_> = self
.0
.diagnostics
.iter()
.filter(|d| d.severity() >= self.0.diagnostic_level)
.filter(|d| {
if self.0.verbose {
d.tags().is_verbose()
} else {
true
}
})
.filter_map(|pglt_diagnostic| {
let absolute_path = match pglt_diagnostic.location().resource {
Some(Resource::File(file)) => Some(file),
_ => None,
}
.unwrap_or_default();
let path_buf = self.attempt_to_relativize(absolute_path);
let path = match path_buf {
Some(buf) => buf.to_str().unwrap_or(absolute_path).to_owned(),
None => absolute_path.to_owned(),
};
let initial_fingerprint = self.compute_initial_fingerprint(pglt_diagnostic, &path);
let fingerprint = hasher.rehash_until_unique(initial_fingerprint);
GitLabDiagnostic::try_from_diagnostic(
pglt_diagnostic,
path.to_string(),
fingerprint,
)
})
.collect();
let serialized = serde_json::to_string_pretty(&gitlab_diagnostics)?;
fmt.write_str(serialized.as_str())?;
Ok(())
}
}
/// An entry in the GitLab Code Quality report.
/// See https://docs.gitlab.com/ee/ci/testing/code_quality.html#implement-a-custom-tool
#[derive(Serialize)]
pub struct GitLabDiagnostic<'a> {
/// A description of the code quality violation.
description: String,
/// A unique name representing the static analysis check that emitted this issue.
check_name: &'a str,
/// A unique fingerprint to identify the code quality violation. For example, an MD5 hash.
fingerprint: String,
/// A severity string (can be info, minor, major, critical, or blocker).
severity: &'a str,
/// The location where the code quality violation occurred.
location: Location,
}
impl<'a> GitLabDiagnostic<'a> {
pub fn try_from_diagnostic(
diagnostic: &'a Error,
path: String,
fingerprint: u64,
) -> Option<Self> {
let location = diagnostic.location();
let span = location.span?;
let source_code = location.source_code?;
let description = PrintDescription(diagnostic).to_string();
let begin = match SourceFile::new(source_code).location(span.start()) {
Ok(start) => start.line_number.get(),
Err(_) => return None,
};
let check_name = diagnostic
.category()
.map(|category| category.name())
.unwrap_or_default();
Some(GitLabDiagnostic {
severity: match diagnostic.severity() {
Severity::Hint => "info",
Severity::Information => "minor",
Severity::Warning => "major",
Severity::Error => "critical",
Severity::Fatal => "blocker",
},
description,
check_name,
// A u64 does not fit into a JSON number, so we serialize this as a
// string
fingerprint: fingerprint.to_string(),
location: Location {
path,
lines: Lines { begin },
},
})
}
}
#[derive(Serialize)]
struct Location {
/// The relative path to the file containing the code quality violation.
path: String,
lines: Lines,
}
#[derive(Serialize)]
struct Lines {
/// The line on which the code quality violation occurred.
begin: usize,
}
#[derive(Hash)]
struct Fingerprint<'a> {
// Including the source code in our hash leads to more stable
// fingerprints. If you instead rely on e.g. the line number and change
// the first line of a file, all of its fingerprint would change.
code: &'a str,
check_name: &'a str,
path: &'a str,
}
fn calculate_hash<T: Hash>(t: &T) -> u64 {
let mut s = DefaultHasher::new();
t.hash(&mut s);
s.finish()
}