From 5ec3c5c3a46ca95f355a4520676b85ac619ca102 Mon Sep 17 00:00:00 2001 From: Nathan Whitaker <17734409+nathanwhit@users.noreply.github.com> Date: Thu, 15 Aug 2024 13:43:04 -0700 Subject: feat(lint): Add lint for usage of node globals (with autofix) (#25048) From upgrading `deno_lint`. Previously if you had a node project that used a bunch of node globals (`process.env`, etc), you would have to fix the errors by hand. This PR includes a new lint that detects usages of node globals (`process`, `setImmediate`, `Buffer`, etc.) and provides an autofix to import the correct value. For instance: ```ts // main.ts const _foo = process.env.FOO; ``` `deno lint` gives you ```ts error[no-node-globals]: NodeJS globals are not available in Deno --> /home/foo.ts:1:14 | 1 | const _foo = process.env.FOO; | ^^^^^^^ = hint: Add `import process from "node:process";` docs: https://lint.deno.land/rules/no-node-globals Found 1 problem (1 fixable via --fix) Checked 1 file ``` And `deno lint --fix` adds the import for you: ```ts // main.ts import process from "node:process"; const _foo = process.env.FOO; ``` --- cli/tools/lint/linter.rs | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) (limited to 'cli/tools') diff --git a/cli/tools/lint/linter.rs b/cli/tools/lint/linter.rs index f6ea76c14..777fe4d09 100644 --- a/cli/tools/lint/linter.rs +++ b/cli/tools/lint/linter.rs @@ -1,5 +1,6 @@ // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. +use std::collections::HashSet; use std::path::Path; use deno_ast::MediaType; @@ -225,14 +226,23 @@ fn apply_lint_fixes( if quick_fixes.is_empty() { return None; } + + let mut import_fixes = HashSet::new(); // remove any overlapping text changes, we'll circle // back for another pass to fix the remaining quick_fixes.sort_by_key(|change| change.range.start); for i in (1..quick_fixes.len()).rev() { let cur = &quick_fixes[i]; let previous = &quick_fixes[i - 1]; - let is_overlapping = cur.range.start < previous.range.end; - if is_overlapping { + // hack: deduplicate import fixes to avoid creating errors + if previous.new_text.trim_start().starts_with("import ") { + import_fixes.insert(previous.new_text.trim().to_string()); + } + let is_overlapping = cur.range.start <= previous.range.end; + if is_overlapping + || (cur.new_text.trim_start().starts_with("import ") + && import_fixes.contains(cur.new_text.trim())) + { quick_fixes.remove(i); } } -- cgit v1.2.3