-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathdiagnostics.rs
More file actions
363 lines (343 loc) · 11.9 KB
/
diagnostics.rs
File metadata and controls
363 lines (343 loc) · 11.9 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
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
use serde::Serialize;
use std::io::Write;
use std::path::PathBuf;
/** SARIF severity */
#[derive(Serialize)]
#[serde(rename_all = "lowercase")]
pub enum Severity {
Error,
Warning,
#[allow(unused)]
Note,
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Source {
/** An identifier under which it makes sense to group this diagnostic message. This is used to build the SARIF reporting descriptor object.*/
pub id: String,
/** Display name for the ID. This is used to build the SARIF reporting descriptor object. */
pub name: String,
#[serde(skip_serializing_if = "Option::is_none")]
/** Name of the CodeQL extractor. This is used to identify which tool component the reporting descriptor object should be nested under in SARIF.*/
pub extractor_name: Option<String>,
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Visibility {
#[serde(skip_serializing_if = "std::ops::Not::not")]
/** True if the message should be displayed on the status page (defaults to false) */
pub status_page: bool,
#[serde(skip_serializing_if = "std::ops::Not::not")]
/** True if the message should be counted in the diagnostics summary table printed by `codeql database analyze` (defaults to false) */
pub cli_summary_table: bool,
#[serde(skip_serializing_if = "std::ops::Not::not")]
/** True if the message should be sent to telemetry (defaults to false) */
pub telemetry: bool,
}
#[derive(Serialize, Clone, Default)]
#[serde(rename_all = "camelCase")]
pub struct Location {
#[serde(skip_serializing_if = "Option::is_none")]
/** Path to the affected file if appropriate, relative to the source root */
pub file: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub start_line: Option<usize>,
#[serde(skip_serializing_if = "Option::is_none")]
pub start_column: Option<usize>,
#[serde(skip_serializing_if = "Option::is_none")]
pub end_line: Option<usize>,
#[serde(skip_serializing_if = "Option::is_none")]
pub end_column: Option<usize>,
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DiagnosticMessage {
/** Unix timestamp */
pub timestamp: chrono::DateTime<chrono::Utc>,
pub source: Source,
#[serde(skip_serializing_if = "String::is_empty")]
/** GitHub flavored Markdown formatted message. Should include inline links to any help pages. */
pub markdown_message: String,
#[serde(skip_serializing_if = "String::is_empty")]
/** Plain text message. Used by components where the string processing needed to support Markdown is cumbersome. */
pub plaintext_message: String,
#[serde(skip_serializing_if = "Vec::is_empty")]
/** List of help links intended to supplement the `plaintextMessage`. */
pub help_links: Vec<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub severity: Option<Severity>,
#[serde(skip_serializing_if = "std::ops::Not::not")]
pub internal: bool,
#[serde(skip_serializing_if = "is_default_visibility")]
pub visibility: Visibility,
#[serde(skip_serializing_if = "Option::is_none")]
pub location: Option<Location>,
}
fn is_default_visibility(v: &Visibility) -> bool {
!v.cli_summary_table && !v.status_page && !v.telemetry
}
pub struct LogWriter {
extractor: String,
path: Option<PathBuf>,
inner: Option<std::io::BufWriter<std::fs::File>>,
}
impl LogWriter {
pub fn new_entry(&self, id: &str, name: &str) -> DiagnosticMessage {
DiagnosticMessage {
timestamp: chrono::Utc::now(),
source: Source {
id: format!("{}/{}", self.extractor, id),
name: name.to_owned(),
extractor_name: Some(self.extractor.to_owned()),
},
markdown_message: String::new(),
plaintext_message: String::new(),
help_links: vec![],
severity: None,
internal: false,
visibility: Visibility {
cli_summary_table: false,
status_page: false,
telemetry: false,
},
location: None,
}
}
pub fn write(&mut self, mesg: &DiagnosticMessage) {
let full_error_message = mesg.full_error_message();
match mesg.severity {
Some(Severity::Error) => tracing::error!("{}", full_error_message),
Some(Severity::Warning) => tracing::warn!("{}", full_error_message),
Some(Severity::Note) => tracing::info!("{}", full_error_message),
None => tracing::debug!("{}", full_error_message),
}
if self.inner.is_none() {
if let Some(path) = self.path.as_ref() {
match std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(path)
{
Err(e) => {
tracing::error!(
"Could not open log file '{}': {}",
&path.to_string_lossy(),
e
);
self.path = None;
self.inner = None
}
Ok(file) => self.inner = Some(std::io::BufWriter::new(file)),
}
}
}
if let Some(mut writer) = self.inner.as_mut() {
serde_json::to_writer(&mut writer, mesg)
.unwrap_or_else(|e| tracing::debug!("Failed to write log entry: {}", e));
writer
.write_all(b"\n")
.unwrap_or_else(|e| tracing::debug!("Failed to write log entry: {}", e));
}
}
}
pub struct DiagnosticLoggers {
extractor: String,
root: Option<PathBuf>,
}
impl DiagnosticLoggers {
pub fn new(extractor: &str) -> Self {
let env_var = format!(
"CODEQL_EXTRACTOR_{}_DIAGNOSTIC_DIR",
extractor.to_ascii_uppercase()
);
let root = match std::env::var(&env_var) {
Err(e) => {
tracing::error!("{}: {}", e, &env_var);
None
}
Ok(dir) => {
if let Err(e) = std::fs::create_dir_all(&dir) {
tracing::error!("Failed to create log directory {}: {}", &dir, e);
None
} else {
Some(PathBuf::from(dir))
}
}
};
DiagnosticLoggers {
extractor: extractor.to_owned(),
root,
}
}
pub fn logger(&self) -> LogWriter {
thread_local! {
static THREAD_NUM: usize = {
static COUNT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
COUNT.fetch_add(1, std::sync::atomic::Ordering::SeqCst)
};
}
THREAD_NUM.with(|n| LogWriter {
extractor: self.extractor.to_owned(),
inner: None,
path: self
.root
.as_ref()
.map(|root| root.to_owned().join(format!("extractor_{n}.jsonl"))),
})
}
}
fn longest_backtick_sequence_length(text: &str) -> usize {
let mut result = 0;
let mut count = 0;
for c in text.chars() {
if c == '`' {
count += 1;
} else {
if count > result {
result = count;
}
count = 0;
}
}
result
}
/// An argument of a diagnostic message format string.
/// A message argument is either a "code" snippet or a link.
pub enum MessageArg<'a> {
Code(&'a str),
Link(&'a str, &'a str),
}
impl DiagnosticMessage {
pub fn full_error_message(&self) -> String {
match &self.location {
Some(Location {
file: Some(path),
start_line: None,
..
}) => format!("{}: {}", path, self.plaintext_message),
Some(Location {
file: Some(path),
start_line: Some(line),
..
}) => format!("{}:{}: {}", path, line, self.plaintext_message),
_ => self.plaintext_message.to_owned(),
}
}
fn text(&mut self, text: &str) -> &mut Self {
self.plaintext_message = text.to_owned();
self
}
pub fn message(&mut self, text: &str, args: &[MessageArg]) -> &mut Self {
let parts = text.split("{}");
let mut plain = String::with_capacity(2 * text.len());
let mut markdown = String::with_capacity(2 * text.len());
for (i, p) in parts.enumerate() {
plain.push_str(p);
markdown.push_str(p);
match args.get(i) {
Some(MessageArg::Code(t)) => {
plain.push_str(t);
if !t.is_empty() {
let count = longest_backtick_sequence_length(t) + 1;
markdown.push_str(&"`".repeat(count));
if count > 1 {
markdown.push(' ');
}
markdown.push_str(t);
if count > 1 {
markdown.push(' ');
}
markdown.push_str(&"`".repeat(count));
}
}
Some(MessageArg::Link(text, url)) => {
plain.push_str(text);
self.help_link(url);
markdown.push('[');
markdown.push_str(text);
markdown.push_str("](");
markdown.push_str(url);
markdown.push(')');
}
None => {}
}
}
self.text(&plain);
self.markdown(&markdown);
self
}
pub fn markdown(&mut self, text: &str) -> &mut Self {
self.markdown_message = text.to_owned();
self
}
pub fn severity(&mut self, severity: Severity) -> &mut Self {
self.severity = Some(severity);
self
}
#[allow(unused)]
pub fn help_link(&mut self, link: &str) -> &mut Self {
self.help_links.push(link.to_owned());
self
}
#[allow(unused)]
pub fn internal(&mut self) -> &mut Self {
self.internal = true;
self
}
#[allow(unused)]
pub fn cli_summary_table(&mut self) -> &mut Self {
self.visibility.cli_summary_table = true;
self
}
pub fn status_page(&mut self) -> &mut Self {
self.visibility.status_page = true;
self
}
#[allow(unused)]
pub fn telemetry(&mut self) -> &mut Self {
self.visibility.telemetry = true;
self
}
pub fn file(&mut self, path: &str) -> &mut Self {
let loc = self.location.get_or_insert(Default::default());
loc.file = Some(path.to_owned());
self
}
pub fn location(
&mut self,
path: &str,
start_line: usize,
start_column: usize,
end_line: usize,
end_column: usize,
) -> &mut Self {
let loc = self.location.get_or_insert(Default::default());
loc.file = Some(path.to_owned());
loc.start_line = Some(start_line);
loc.start_column = Some(start_column);
loc.end_line = Some(end_line);
loc.end_column = Some(end_column);
self
}
}
#[test]
fn test_message() {
let mut m = DiagnosticLoggers::new("foo")
.logger()
.new_entry("id", "name");
m.message("hello: {}", &[MessageArg::Code("hello")]);
assert_eq!("hello: hello", m.plaintext_message);
assert_eq!("hello: `hello`", m.markdown_message);
let mut m = DiagnosticLoggers::new("foo")
.logger()
.new_entry("id", "name");
m.message(
"hello with backticks: {}",
&[MessageArg::Code("oh `hello`!")],
);
assert_eq!("hello with backticks: oh `hello`!", m.plaintext_message);
assert_eq!(
"hello with backticks: `` oh `hello`! ``",
m.markdown_message
);
}