Skip to content

Commit

Permalink
Deprioritize import paths made up of only dots and slashes (#47432)
Browse files Browse the repository at this point in the history
* Deprioritize import paths made up of only dots and slashes

* Fix test

* Hoist regex

* Yaaaay RegExp state
  • Loading branch information
andrewbranch authored Jan 14, 2022
1 parent 16bbddb commit 28c2084
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
6 changes: 6 additions & 0 deletions src/services/codefixes/importFixes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -678,11 +678,17 @@ namespace ts.codefix {
if (a.kind !== ImportFixKind.UseNamespace && b.kind !== ImportFixKind.UseNamespace) {
return compareBooleans(allowsImportingSpecifier(b.moduleSpecifier), allowsImportingSpecifier(a.moduleSpecifier))
|| compareNodeCoreModuleSpecifiers(a.moduleSpecifier, b.moduleSpecifier, importingFile, program)
|| compareBooleans(isOnlyDotsAndSlashes(a.moduleSpecifier), isOnlyDotsAndSlashes(b.moduleSpecifier))
|| compareNumberOfDirectorySeparators(a.moduleSpecifier, b.moduleSpecifier);
}
return Comparison.EqualTo;
}

const notDotOrSlashPattern = /[^.\/]/;
function isOnlyDotsAndSlashes(path: string) {
return !notDotOrSlashPattern.test(path);
}

function compareNodeCoreModuleSpecifiers(a: string, b: string, importingFile: SourceFile, program: Program): Comparison {
if (startsWith(a, "node:") && !startsWith(b, "node:")) return shouldUseUriStyleNodeCoreModules(importingFile, program) ? Comparison.LessThan : Comparison.GreaterThan;
if (startsWith(b, "node:") && !startsWith(a, "node:")) return shouldUseUriStyleNodeCoreModules(importingFile, program) ? Comparison.GreaterThan : Comparison.LessThan;
Expand Down
29 changes: 29 additions & 0 deletions tests/cases/fourslash/importNameCodeFix_barrelExport.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/// <reference path="fourslash.ts" />

// @module: commonjs

// @Filename: /foo/a.ts
//// export const A = 0;

// @Filename: /foo/b.ts
//// export {};
//// A/*sibling*/

// @Filename: /foo/index.ts
//// export * from "./a";
//// export * from "./b";

// @Filename: /index.ts
//// export * from "./foo";
//// export * from "./src";

// @Filename: /src/a.ts
//// export {};
//// A/*parent*/

// @Filename: /src/index.ts
//// export * from "./a";

// Module specifiers made up of only "." and ".." components are deprioritized
verify.importFixModuleSpecifiers("sibling", ["./a", ".", ".."]);
verify.importFixModuleSpecifiers("parent", ["../foo", "../foo/a", ".."]);

0 comments on commit 28c2084

Please sign in to comment.