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

Organize type imports #55269

Merged
merged 17 commits into from
Jan 10, 2024
Merged
Show file tree
Hide file tree
Changes from 5 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
1 change: 1 addition & 0 deletions src/compiler/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9995,6 +9995,7 @@ export interface UserPreferences {
readonly organizeImportsNumericCollation?: boolean;
readonly organizeImportsAccentCollation?: boolean;
readonly organizeImportsCaseFirst?: "upper" | "lower" | false;
readonly organizeImportsTypeOrder?: "first" | "last" | "inline";
}

/** Represents a bigint literal value without requiring bigint support */
Expand Down
7 changes: 7 additions & 0 deletions src/server/protocol.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3598,6 +3598,13 @@ export interface UserPreferences {
* Default: `false`
*/
readonly organizeImportsCaseFirst?: "upper" | "lower" | false;
/**
* Indicates where named type-only imports should sort. The default order ("inline") sorts imports regardless of if imports are
* type-only.
*
* Default: `inline`
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The current default is effectively "last"; for backwards compat I'm thinking we should probaby keep that?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That makes sense to me, and is inline with the past changes to organize imports

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Of course, changing the default to inline was what I was doing when I was attempting to make this change, was very helpful in debugging.

*/
readonly organizeImportsTypeOrder?: "first" | "last" | "inline";

/**
* Indicates whether {@link ReferencesResponseItem.lineText} is supported.
Expand Down
12 changes: 7 additions & 5 deletions src/services/codefixes/importFixes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ import {
getSourceFileOfNode,
getSymbolId,
getTokenAtPosition,
getTokenPosOfNode,
getTypeKeywordOfTypeOnlyImport,
getUniqueSymbolId,
hostGetCanonicalFileName,
Expand Down Expand Up @@ -1329,15 +1330,16 @@ function promoteFromTypeOnly(changes: textChanges.ChangeTracker, aliasDeclaratio
if (aliasDeclaration.isTypeOnly) {
const sortKind = OrganizeImports.detectImportSpecifierSorting(aliasDeclaration.parent.elements, preferences);
if (aliasDeclaration.parent.elements.length > 1 && sortKind) {
changes.delete(sourceFile, aliasDeclaration);
const newSpecifier = factory.updateImportSpecifier(aliasDeclaration, /*isTypeOnly*/ false, aliasDeclaration.propertyName, aliasDeclaration.name);
const comparer = OrganizeImports.getOrganizeImportsComparer(preferences, sortKind === SortKind.CaseInsensitive);
const insertionIndex = OrganizeImports.getImportSpecifierInsertionIndex(aliasDeclaration.parent.elements, newSpecifier, comparer);
changes.insertImportSpecifierAtIndex(sourceFile, newSpecifier, aliasDeclaration.parent, insertionIndex);
}
else {
changes.deleteRange(sourceFile, aliasDeclaration.getFirstToken()!);
if (insertionIndex !== aliasDeclaration.parent.elements.indexOf(aliasDeclaration)) {
changes.delete(sourceFile, aliasDeclaration);
changes.insertImportSpecifierAtIndex(sourceFile, newSpecifier, aliasDeclaration.parent, insertionIndex);
return aliasDeclaration;
}
}
changes.deleteRange(sourceFile, { pos: getTokenPosOfNode(aliasDeclaration.getFirstToken()!), end: getTokenPosOfNode(aliasDeclaration.propertyName ?? aliasDeclaration.name) });
return aliasDeclaration;
}
else {
Expand Down
44 changes: 27 additions & 17 deletions src/services/organizeImports.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ export function organizeImports(

const processImportsOfSameModuleSpecifier = (importGroup: readonly ImportDeclaration[]) => {
if (shouldRemove) importGroup = removeUnusedImports(importGroup, sourceFile, program);
if (shouldCombine) importGroup = coalesceImportsWorker(importGroup, comparer, sourceFile);
if (shouldCombine) importGroup = coalesceImportsWorker(importGroup, comparer, sourceFile, preferences);
if (shouldSort) importGroup = stableSort(importGroup, (s1, s2) => compareImportsOrRequireStatements(s1, s2, comparer));
return importGroup;
};
Expand All @@ -105,7 +105,7 @@ export function organizeImports(
if (mode !== OrganizeImportsMode.RemoveUnused) {
// All of the old ExportDeclarations in the file, in syntactic order.
getTopLevelExportGroups(sourceFile).forEach(exportGroupDecl =>
organizeImportsWorker(exportGroupDecl, group => coalesceExportsWorker(group, comparer)));
organizeImportsWorker(exportGroupDecl, group => coalesceExportsWorker(group, comparer, preferences)));
}

for (const ambientModule of sourceFile.statements.filter(isAmbientModule)) {
Expand All @@ -117,7 +117,7 @@ export function organizeImports(
// Exports are always used
if (mode !== OrganizeImportsMode.RemoveUnused) {
const ambientModuleExportDecls = ambientModule.body.statements.filter(isExportDeclaration);
organizeImportsWorker(ambientModuleExportDecls, group => coalesceExportsWorker(group, comparer));
organizeImportsWorker(ambientModuleExportDecls, group => coalesceExportsWorker(group, comparer, preferences));
}
}

Expand Down Expand Up @@ -310,12 +310,12 @@ function getExternalModuleName(specifier: Expression | undefined) {
* @deprecated Only used for testing
* @internal
*/
export function coalesceImports(importGroup: readonly ImportDeclaration[], ignoreCase: boolean, sourceFile?: SourceFile): readonly ImportDeclaration[] {
export function coalesceImports(importGroup: readonly ImportDeclaration[], ignoreCase: boolean, sourceFile?: SourceFile, preferences?: UserPreferences): readonly ImportDeclaration[] {
const comparer = getOrganizeImportsOrdinalStringComparer(ignoreCase);
return coalesceImportsWorker(importGroup, comparer, sourceFile);
return coalesceImportsWorker(importGroup, comparer, sourceFile, preferences);
}

function coalesceImportsWorker(importGroup: readonly ImportDeclaration[], comparer: Comparer<string>, sourceFile?: SourceFile): readonly ImportDeclaration[] {
function coalesceImportsWorker(importGroup: readonly ImportDeclaration[], comparer: Comparer<string>, sourceFile?: SourceFile, preferences?: UserPreferences): readonly ImportDeclaration[] {
if (importGroup.length === 0) {
return importGroup;
}
Expand Down Expand Up @@ -372,7 +372,7 @@ function coalesceImportsWorker(importGroup: readonly ImportDeclaration[], compar
newImportSpecifiers.push(...getNewImportSpecifiers(namedImports));

const sortedImportSpecifiers = factory.createNodeArray(
sortSpecifiers(newImportSpecifiers, comparer),
sortSpecifiers(newImportSpecifiers, comparer, preferences),
firstNamedImport?.importClause.namedBindings.elements.hasTrailingComma
);

Expand Down Expand Up @@ -485,18 +485,17 @@ function getCategorizedImports(importGroup: readonly ImportDeclaration[]) {
* @deprecated Only used for testing
* @internal
*/
export function coalesceExports(exportGroup: readonly ExportDeclaration[], ignoreCase: boolean) {
export function coalesceExports(exportGroup: readonly ExportDeclaration[], ignoreCase: boolean, preferences?: UserPreferences) {
const comparer = getOrganizeImportsOrdinalStringComparer(ignoreCase);
return coalesceExportsWorker(exportGroup, comparer);
return coalesceExportsWorker(exportGroup, comparer, preferences);
}

function coalesceExportsWorker(exportGroup: readonly ExportDeclaration[], comparer: Comparer<string>) {
function coalesceExportsWorker(exportGroup: readonly ExportDeclaration[], comparer: Comparer<string>, preferences?: UserPreferences) {
if (exportGroup.length === 0) {
return exportGroup;
}

const { exportWithoutClause, namedExports, typeOnlyExports } = getCategorizedExports(exportGroup);

const coalescedExports: ExportDeclaration[] = [];

if (exportWithoutClause) {
Expand All @@ -510,7 +509,7 @@ function coalesceExportsWorker(exportGroup: readonly ExportDeclaration[], compar
const newExportSpecifiers: ExportSpecifier[] = [];
newExportSpecifiers.push(...flatMap(exportGroup, i => i.exportClause && isNamedExports(i.exportClause) ? i.exportClause.elements : emptyArray));

const sortedExportSpecifiers = sortSpecifiers(newExportSpecifiers, comparer);
const sortedExportSpecifiers = sortSpecifiers(newExportSpecifiers, comparer, preferences);

const exportDecl = exportGroup[0];
coalescedExports.push(
Expand Down Expand Up @@ -574,13 +573,20 @@ function updateImportDeclarationAndClause(
importDeclaration.assertClause);
}

function sortSpecifiers<T extends ImportOrExportSpecifier>(specifiers: readonly T[], comparer: Comparer<string>) {
return stableSort(specifiers, (s1, s2) => compareImportOrExportSpecifiers(s1, s2, comparer));
function sortSpecifiers<T extends ImportOrExportSpecifier>(specifiers: readonly T[], comparer: Comparer<string>, preferences?: UserPreferences): readonly T[] {
return stableSort(specifiers, (s1, s2) => compareImportOrExportSpecifiers(s1, s2, comparer, preferences));
}

/** @internal */
export function compareImportOrExportSpecifiers<T extends ImportOrExportSpecifier>(s1: T, s2: T, comparer: Comparer<string>): Comparison {
return compareBooleans(s1.isTypeOnly, s2.isTypeOnly) || comparer(s1.name.text, s2.name.text);
export function compareImportOrExportSpecifiers<T extends ImportOrExportSpecifier>(s1: T, s2: T, comparer: Comparer<string>, preferences?: UserPreferences): Comparison {
switch (preferences?.organizeImportsTypeOrder){
case "first":
return compareBooleans(s2.isTypeOnly, s1.isTypeOnly) || comparer(s1.name.text, s2.name.text);
case "last":
return compareBooleans(s1.isTypeOnly, s2.isTypeOnly) || comparer(s1.name.text, s2.name.text);
default:
return comparer(s1.name.text, s2.name.text);
}
}

/**
Expand Down Expand Up @@ -709,9 +715,13 @@ class ImportSpecifierSortingCache implements MemoizeCache<[readonly ImportSpecif

/** @internal */
export const detectImportSpecifierSorting = memoizeCached((specifiers: readonly ImportSpecifier[], preferences: UserPreferences): SortKind => {
if (!arrayIsSorted(specifiers, (s1, s2) => compareBooleans(s1.isTypeOnly, s2.isTypeOnly))) {
// If types are not sorted as specified, then imports are assumed to be unsorted.
// If there is no type sorting specification, then we move on to case sensitivity detection.
if (preferences.organizeImportsTypeOrder === "last" && !arrayIsSorted(specifiers, (s1, s2) => compareBooleans(s1.isTypeOnly, s2.isTypeOnly))
|| preferences.organizeImportsTypeOrder === "first" && !arrayIsSorted(specifiers, (s1, s2) => compareBooleans(s2.isTypeOnly, s1.isTypeOnly))) {
return SortKind.None;
}

const collateCaseSensitive = getOrganizeImportsComparer(preferences, /*ignoreCase*/ false);
const collateCaseInsensitive = getOrganizeImportsComparer(preferences, /*ignoreCase*/ true);
return detectSortCaseSensitivity(specifiers, specifier => specifier.name.text, collateCaseSensitive, collateCaseInsensitive);
Expand Down
2 changes: 1 addition & 1 deletion src/testRunner/unittests/services/organizeImports.ts
Original file line number Diff line number Diff line change
Expand Up @@ -217,7 +217,7 @@ describe("unittests:: services:: organizeImports", () => {
it("Sort specifiers - type-only", () => {
const sortedImports = parseImports(`import { type z, y, type x, c, type b, a } from "lib";`);
const actualCoalescedImports = ts.OrganizeImports.coalesceImports(sortedImports, /*ignoreCase*/ true);
const expectedCoalescedImports = parseImports(`import { a, c, y, type b, type x, type z } from "lib";`);
const expectedCoalescedImports = parseImports(`import { a, type b, c, type x, y, type z } from "lib";`);
assertListEqual(actualCoalescedImports, expectedCoalescedImports);
});

Expand Down
8 changes: 8 additions & 0 deletions tests/baselines/reference/api/tsserverlibrary.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2891,6 +2891,13 @@ declare namespace ts {
* Default: `false`
*/
readonly organizeImportsCaseFirst?: "upper" | "lower" | false;
/**
* Indicates where named type-only imports should sort. The default order ("inline") sorts imports regardless of if imports are
* type-only.
*
* Default: `inline`
*/
readonly organizeImportsTypeOrder?: "first" | "last" | "inline";
/**
* Indicates whether {@link ReferencesResponseItem.lineText} is supported.
*/
Expand Down Expand Up @@ -8414,6 +8421,7 @@ declare namespace ts {
readonly organizeImportsNumericCollation?: boolean;
readonly organizeImportsAccentCollation?: boolean;
readonly organizeImportsCaseFirst?: "upper" | "lower" | false;
readonly organizeImportsTypeOrder?: "first" | "last" | "inline";
}
/** Represents a bigint literal value without requiring bigint support */
interface PseudoBigInt {
Expand Down
1 change: 1 addition & 0 deletions tests/baselines/reference/api/typescript.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4356,6 +4356,7 @@ declare namespace ts {
readonly organizeImportsNumericCollation?: boolean;
readonly organizeImportsAccentCollation?: boolean;
readonly organizeImportsCaseFirst?: "upper" | "lower" | false;
readonly organizeImportsTypeOrder?: "first" | "last" | "inline";
}
/** Represents a bigint literal value without requiring bigint support */
interface PseudoBigInt {
Expand Down
41 changes: 41 additions & 0 deletions tests/cases/fourslash/autoImportTypeImport1.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
/// <reference path="fourslash.ts" />

// @verbatimModuleSyntax: true
// @target: esnext

// @Filename: /foo.ts
//// export const A = 1;
//// export type B = { x: number };
//// export type C = 1;
//// export class D = { y: string };

// @Filename: /test.ts
//// import { A, D, type C } from './foo';
//// const b: B/**/ | C;
//// console.log(A, D);

goTo.marker("");

verify.importFixAtPosition([
`import { A, D, type C, type B } from './foo';
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why does this one turn out to have C first? The next one doesn't which feels odd.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since it's adding type B and it's determined that the types are unsorted (since it specified inline), it adds it on to the end. If the imports were unsorted before, it would always add onto the end, otherwise it might add the import somewhere weird in the middle, since we're not changing the order of the rest of the imports

const b: B | C;
console.log(A, D);`],
/*errorCode*/ undefined,
{ organizeImportsTypeOrder: "inline" }
);

verify.importFixAtPosition([
`import { A, D, type C, type B } from './foo';
const b: B | C;
console.log(A, D);`],
/*errorCode*/ undefined,
{ organizeImportsTypeOrder: "last" }
);
iisaduan marked this conversation as resolved.
Show resolved Hide resolved

verify.importFixAtPosition([
`import { A, D, type C, type B } from './foo';
jakebailey marked this conversation as resolved.
Show resolved Hide resolved
const b: B | C;
console.log(A, D);`],
/*errorCode*/ undefined,
{ organizeImportsTypeOrder: "first" }
);
41 changes: 41 additions & 0 deletions tests/cases/fourslash/autoImportTypeImport2.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
/// <reference path="fourslash.ts" />

// @verbatimModuleSyntax: true
// @target: esnext

// @Filename: /foo.ts
//// export const A = 1;
//// export type B = { x: number };
//// export type C = 1;
//// export class D = { y: string };

// @Filename: /test.ts
//// import { A, type C, D } from './foo';
//// const b: B/**/ | C;
//// console.log(A, D);

goTo.marker("");

verify.importFixAtPosition([
`import { A, type B, type C, D } from './foo';
const b: B | C;
console.log(A, D);`],
/*errorCode*/ undefined,
{ organizeImportsTypeOrder: "inline" }
);

verify.importFixAtPosition([
`import { A, type C, D, type B } from './foo';
jakebailey marked this conversation as resolved.
Show resolved Hide resolved
const b: B | C;
console.log(A, D);`],
/*errorCode*/ undefined,
{ organizeImportsTypeOrder: "last" }
);

verify.importFixAtPosition([
`import { A, type C, D, type B } from './foo';
const b: B | C;
console.log(A, D);`],
/*errorCode*/ undefined,
{ organizeImportsTypeOrder: "first" }
);
1 change: 1 addition & 0 deletions tests/cases/fourslash/fourslash.ts
Original file line number Diff line number Diff line change
Expand Up @@ -670,6 +670,7 @@ declare namespace FourSlashInterface {
readonly organizeImportsNumericCollation?: boolean;
readonly organizeImportsAccentCollation?: boolean;
readonly organizeImportsCaseFirst?: "upper" | "lower" | false;
readonly organizeImportsTypeOrder?: "first" | "last" | "inline";
}
interface InlayHintsOptions extends UserPreferences {
readonly includeInlayParameterNameHints?: "none" | "literals" | "all";
Expand Down
2 changes: 1 addition & 1 deletion tests/cases/fourslash/importNameCodeFix_importType7.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
goTo.marker("");
verify.importFixAtPosition([
`import {
SomePig,
type SomeInterface,
SomePig,
} from "./exports.js";
new SomePig`]);
45 changes: 45 additions & 0 deletions tests/cases/fourslash/organizeImportsType1.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
/// <reference path='fourslash.ts' />

// @allowSyntheticDefaultImports: true
// @moduleResolution: node
// @noUnusedLocals: true
// @target: es2018

//// import { A } from "foo";
//// import { type B } from "foo";
//// import { C } from "foo";
//// import { type E } from "foo";
//// import { D } from "foo";
////
//// console.log(A, B, C, D, E);

verify.organizeImports(
`import { A, type B, C, D, type E } from "foo";

console.log(A, B, C, D, E);`
);

verify.organizeImports(
`import { A, type B, C, D, type E } from "foo";

console.log(A, B, C, D, E);`,
undefined,
{ organizeImportsTypeOrder : "inline" }
);


verify.organizeImports(
`import { type B, type E, A, C, D } from "foo";

console.log(A, B, C, D, E);`,
undefined,
{ organizeImportsTypeOrder : "first" }
);

verify.organizeImports(
`import { A, C, D, type B, type E } from "foo";

console.log(A, B, C, D, E);`,
undefined,
{ organizeImportsTypeOrder : "last" }
);
Loading