Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: multi line deno_lint diagnostics #7303

Merged
merged 5 commits into from
Sep 2, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion cli/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ winapi = "0.3.9"
[dependencies]
deno_core = { path = "../core", version = "0.55.0" }
deno_doc = { version = "0.1.3" }
deno_lint = { version = "0.1.26", features = ["json"] }
deno_lint = { version = "0.1.27", features = ["json"] }

atty = "0.2.14"
base64 = "0.12.3"
Expand Down
104 changes: 77 additions & 27 deletions cli/lint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,10 +73,11 @@ pub async fn lint_files(
let mut reporter = reporter_lock.lock().unwrap();

match r {
Ok(file_diagnostics) => {
Ok((mut file_diagnostics, source)) => {
sort_diagnostics(&mut file_diagnostics);
for d in file_diagnostics.iter() {
has_error.store(true, Ordering::Relaxed);
reporter.visit(&d);
reporter.visit(&d, source.split('\n').collect());
}
}
Err(err) => {
Expand Down Expand Up @@ -124,7 +125,9 @@ fn create_linter(syntax: Syntax, rules: Vec<Box<dyn LintRule>>) -> Linter {
.build()
}

fn lint_file(file_path: PathBuf) -> Result<Vec<LintDiagnostic>, ErrBox> {
fn lint_file(
file_path: PathBuf,
) -> Result<(Vec<LintDiagnostic>, String), ErrBox> {
let file_name = file_path.to_string_lossy().to_string();
let source_code = fs::read_to_string(&file_path)?;
let media_type = map_file_extension(&file_path);
Expand All @@ -133,9 +136,9 @@ fn lint_file(file_path: PathBuf) -> Result<Vec<LintDiagnostic>, ErrBox> {
let lint_rules = rules::get_recommended_rules();
let mut linter = create_linter(syntax, lint_rules);

let file_diagnostics = linter.lint(file_name, source_code)?;
let file_diagnostics = linter.lint(file_name, source_code.clone())?;

Ok(file_diagnostics)
Ok((file_diagnostics, source_code))
}

/// Lint stdin and write result to stdout.
Expand All @@ -159,13 +162,13 @@ fn lint_stdin(json: bool) -> Result<(), ErrBox> {
let mut has_error = false;
let pseudo_file_name = "_stdin.ts";
match linter
.lint(pseudo_file_name.to_string(), source)
.lint(pseudo_file_name.to_string(), source.clone())
.map_err(|e| e.into())
{
Ok(diagnostics) => {
for d in diagnostics {
has_error = true;
reporter.visit(&d);
reporter.visit(&d, source.split('\n').collect());
}
}
Err(err) => {
Expand All @@ -184,7 +187,7 @@ fn lint_stdin(json: bool) -> Result<(), ErrBox> {
}

trait LintReporter {
fn visit(&mut self, d: &LintDiagnostic);
fn visit(&mut self, d: &LintDiagnostic, source_lines: Vec<&str>);
fn visit_error(&mut self, file_path: &str, err: &ErrBox);
fn close(&mut self);
}
Expand All @@ -206,24 +209,21 @@ impl PrettyLintReporter {
}

impl LintReporter for PrettyLintReporter {
fn visit(&mut self, d: &LintDiagnostic) {
fn visit(&mut self, d: &LintDiagnostic, source_lines: Vec<&str>) {
self.lint_count += 1;

let pretty_message =
format!("({}) {}", colors::gray(&d.code), d.message.clone());

let message = fmt_errors::format_stack(
true,
let message = format_diagnostic(
&pretty_message,
Some(&d.line_src),
Some(d.location.col as i64),
Some((d.location.col + d.snippet_length) as i64),
&[fmt_errors::format_location(
&source_lines,
d.range.clone(),
&fmt_errors::format_location(
&d.filename,
d.location.line as i64,
d.location.col as i64,
)],
0,
d.range.start.line as i64,
d.range.start.col as i64,
),
);

eprintln!("{}\n", message);
Expand All @@ -243,6 +243,46 @@ impl LintReporter for PrettyLintReporter {
}
}

pub fn format_diagnostic(
message_line: &str,
source_lines: &[&str],
range: deno_lint::diagnostic::Range,
formatted_location: &str,
) -> String {
let mut lines = vec![];

for i in range.start.line..=range.end.line {
lines.push(source_lines[i - 1].to_string());
if range.start.line == range.end.line {
lines.push(format!(
"{}{}",
" ".repeat(range.start.col),
colors::red(&"^".repeat(range.end.col - range.start.col))
));
} else {
let line_len = source_lines[i - 1].len();
if range.start.line == i {
lines.push(format!(
"{}{}",
" ".repeat(range.start.col),
colors::red(&"^".repeat(line_len - range.start.col))
));
} else if range.end.line == i {
lines.push(format!("{}", colors::red(&"^".repeat(range.end.col))));
} else if line_len != 0 {
lines.push(format!("{}", colors::red(&"^".repeat(line_len))));
}
}
}

format!(
"{}\n{}\n at {}",
message_line,
lines.join("\n"),
formatted_location
)
}

#[derive(Serialize)]
struct JsonLintReporter {
diagnostics: Vec<LintDiagnostic>,
Expand All @@ -259,7 +299,7 @@ impl JsonLintReporter {
}

impl LintReporter for JsonLintReporter {
fn visit(&mut self, d: &LintDiagnostic) {
fn visit(&mut self, d: &LintDiagnostic, _source_lines: Vec<&str>) {
self.diagnostics.push(d.clone());
}

Expand All @@ -271,16 +311,26 @@ impl LintReporter for JsonLintReporter {
}

fn close(&mut self) {
// Sort so that we guarantee a deterministic output which is useful for tests
self.diagnostics.sort_by_key(|key| get_sort_key(&key));

sort_diagnostics(&mut self.diagnostics);
let json = serde_json::to_string_pretty(&self);
eprintln!("{}", json.unwrap());
}
}

pub fn get_sort_key(a: &LintDiagnostic) -> String {
let location = &a.location;

return format!("{}:{}:{}", a.filename, location.line, location.col);
fn sort_diagnostics(diagnostics: &mut Vec<LintDiagnostic>) {
// Sort so that we guarantee a deterministic output which is useful for tests
diagnostics.sort_by(|a, b| {
use std::cmp::Ordering;
let file_order = a.filename.cmp(&b.filename);
match file_order {
Ordering::Equal => {
let line_order = a.range.start.line.cmp(&b.range.start.line);
match line_order {
Ordering::Equal => a.range.start.col.cmp(&b.range.start.col),
_ => line_order,
}
}
_ => file_order,
}
});
}
16 changes: 10 additions & 6 deletions cli/tests/lint/expected_from_stdin_json.out
Original file line number Diff line number Diff line change
@@ -1,15 +1,19 @@
{
"diagnostics": [
{
"location": {
"line": 1,
"col": 7
"range": {
"start": {
"line": 1,
"col": 7
},
"end": {
"line": 1,
"col": 10
}
},
"filename": "_stdin.ts",
"message": "`any` type is not allowed",
"code": "no-explicit-any",
"line_src": "let a: any;",
"snippet_length": 3
"code": "no-explicit-any"
}
],
"errors": []
Expand Down
54 changes: 33 additions & 21 deletions cli/tests/lint/expected_json.out
Original file line number Diff line number Diff line change
@@ -1,37 +1,49 @@
{
"diagnostics": [
{
"location": {
"line": 1,
"col": 0
"range": {
"start": {
"line": 1,
"col": 0
},
"end": {
"line": 1,
"col": 19
}
},
"filename": "[WILDCARD]",
"filename": "[WILDCARD]file1.js",
"message": "Ignore directive requires lint rule code",
"code": "ban-untagged-ignore",
"line_src": "// deno-lint-ignore",
"snippet_length": 19
"code": "ban-untagged-ignore"
},
{
"location": {
"line": 2,
"col": 14
"range": {
"start": {
"line": 2,
"col": 14
},
"end": {
"line": 2,
"col": 16
}
},
"filename": "[WILDCARD]",
"filename": "[WILDCARD]file1.js",
"message": "Empty block statement",
"code": "no-empty",
"line_src": "while (false) {}",
"snippet_length": 2
"code": "no-empty"
},
{
"location": {
"line": 3,
"col": 12
"range": {
"start": {
"line": 3,
"col": 12
},
"end": {
"line": 3,
"col": 14
}
},
"filename": "[WILDCARD]",
"filename": "[WILDCARD]file2.ts",
"message": "Empty block statement",
"code": "no-empty",
"line_src": "} catch (e) {}",
"snippet_length": 2
"code": "no-empty"
}
],
"errors": [
Expand Down