Skip to content

getEditsForFileRename: Avoid changing import specifier ending #26177

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

Merged
8 commits merged into from
Aug 28, 2018
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
17 changes: 13 additions & 4 deletions src/compiler/checker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3895,13 +3895,22 @@ namespace ts {
const links = getSymbolLinks(symbol);
let specifier = links.specifierCache && links.specifierCache.get(contextFile.path);
if (!specifier) {
specifier = moduleSpecifiers.getModuleSpecifierForDeclarationFile(
const isBundle = (compilerOptions.out || compilerOptions.outFile);
// For declaration bundles, we need to generate absolute paths relative to the common source dir for imports,
// just like how the declaration emitter does for the ambient module declarations - we can easily accomplish this
// using the `baseUrl` compiler option (which we would otherwise never use in declaration emit) and a non-relative
// specifier preference
const { moduleResolverHost } = context.tracker;
const specifierCompilerOptions = isBundle ? { ...compilerOptions, baseUrl: moduleResolverHost.getCommonSourceDirectory() } : compilerOptions;
specifier = first(first(moduleSpecifiers.getModuleSpecifiers(
symbol,
compilerOptions,
specifierCompilerOptions,
contextFile,
context.tracker.moduleResolverHost,
moduleResolverHost,
host.getSourceFiles(),
{ importModuleSpecifierPreference: isBundle ? "non-relative" : "relative" },
host.redirectTargetsMap,
);
)));
links.specifierCache = links.specifierCache || createMap();
links.specifierCache.set(contextFile.path, specifier);
}
Expand Down
198 changes: 104 additions & 94 deletions src/compiler/moduleSpecifiers.ts

Large diffs are not rendered by default.

15 changes: 12 additions & 3 deletions src/compiler/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5335,8 +5335,6 @@ namespace ts {
useCaseSensitiveFileNames?(): boolean;
fileExists?(path: string): boolean;
readFile?(path: string): string | undefined;
getSourceFiles?(): ReadonlyArray<SourceFile>; // Used for cached resolutions to find symlinks without traversing the fs (again)
getCommonSourceDirectory?(): string;
}

// Note: this used to be deprecated in our public API, but is still used internally
Expand All @@ -5349,7 +5347,7 @@ namespace ts {
reportInaccessibleThisError?(): void;
reportPrivateInBaseOfClassExpression?(propertyName: string): void;
reportInaccessibleUniqueSymbolError?(): void;
moduleResolverHost?: ModuleSpecifierResolutionHost;
moduleResolverHost?: EmitHost;
trackReferencedAmbientModule?(decl: ModuleDeclaration, symbol: Symbol): void;
trackExternalModuleSymbolOfImportTypeNode?(symbol: Symbol): void;
}
Expand Down Expand Up @@ -5599,4 +5597,15 @@ namespace ts {
get<TKey extends keyof PragmaPsuedoMap>(key: TKey): PragmaPsuedoMap[TKey] | PragmaPsuedoMap[TKey][];
forEach(action: <TKey extends keyof PragmaPsuedoMap>(value: PragmaPsuedoMap[TKey] | PragmaPsuedoMap[TKey][], key: TKey) => void): void;
}

export interface UserPreferences {
readonly disableSuggestions?: boolean;
readonly quotePreference?: "double" | "single";
readonly includeCompletionsForModuleExports?: boolean;
readonly includeCompletionsWithInsertText?: boolean;
readonly importModuleSpecifierPreference?: "relative" | "non-relative";
/** Determines whether we import `foo/index.ts` as "foo", "foo/index", or "foo/index.js" */
readonly importModuleSpecifierEnding?: "minimal" | "index" | "js";
readonly allowTextChangesInNewFiles?: boolean;
}
}
5 changes: 5 additions & 0 deletions src/compiler/utilities.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7877,6 +7877,7 @@ namespace ts {
/** Must have ".d.ts" first because if ".ts" goes first, that will be detected as the extension instead of ".d.ts". */
export const supportedTypescriptExtensionsForExtractExtension: ReadonlyArray<Extension> = [Extension.Dts, Extension.Ts, Extension.Tsx];
export const supportedJavascriptExtensions: ReadonlyArray<Extension> = [Extension.Js, Extension.Jsx];
export const supportedJavaScriptAndJsonExtensions: ReadonlyArray<Extension> = [Extension.Js, Extension.Jsx, Extension.Json];
const allSupportedExtensions: ReadonlyArray<Extension> = [...supportedTypeScriptExtensions, ...supportedJavascriptExtensions];

export function getSupportedExtensions(options?: CompilerOptions, extraFileExtensions?: ReadonlyArray<FileExtensionInfo>): ReadonlyArray<string> {
Expand All @@ -7902,6 +7903,10 @@ namespace ts {
return some(supportedJavascriptExtensions, extension => fileExtensionIs(fileName, extension));
}

export function hasJavaScriptOrJsonFileExtension(fileName: string): boolean {
return supportedJavaScriptAndJsonExtensions.some(ext => fileExtensionIs(fileName, ext));
}

export function hasTypeScriptFileExtension(fileName: string): boolean {
return some(supportedTypeScriptExtensions, extension => fileExtensionIs(fileName, extension));
}
Expand Down
9 changes: 4 additions & 5 deletions src/services/getEditsForFileRename.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ namespace ts {
newFileOrDirPath: string,
host: LanguageServiceHost,
formatContext: formatting.FormatContext,
preferences: UserPreferences,
_preferences: UserPreferences,
sourceMapper: SourceMapper,
): ReadonlyArray<FileTextChanges> {
const useCaseSensitiveFileNames = hostUsesCaseSensitiveFileNames(host);
Expand All @@ -15,7 +15,7 @@ namespace ts {
const newToOld = getPathUpdater(newFileOrDirPath, oldFileOrDirPath, getCanonicalFileName, sourceMapper);
return textChanges.ChangeTracker.with({ host, formatContext }, changeTracker => {
updateTsconfigFiles(program, changeTracker, oldToNew, newFileOrDirPath, host.getCurrentDirectory(), useCaseSensitiveFileNames);
updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName, preferences);
updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName);
});
}

Expand Down Expand Up @@ -122,7 +122,6 @@ namespace ts {
newToOld: PathUpdater,
host: LanguageServiceHost,
getCanonicalFileName: GetCanonicalFileName,
preferences: UserPreferences,
): void {
const allFiles = program.getSourceFiles();
for (const sourceFile of allFiles) {
Expand Down Expand Up @@ -156,7 +155,7 @@ namespace ts {

// Need an update if the imported file moved, or the importing file moved and was using a relative path.
return toImport !== undefined && (toImport.updated || (importingSourceFileMoved && pathIsRelative(importLiteral.text)))
? moduleSpecifiers.getModuleSpecifier(program.getCompilerOptions(), sourceFile, newImportFromPath, toImport.newFileName, host, allFiles, preferences, program.redirectTargetsMap)
? moduleSpecifiers.updateModuleSpecifier(program.getCompilerOptions(), newImportFromPath, toImport.newFileName, host, allFiles, program.redirectTargetsMap, importLiteral.text)
: undefined;
});
}
Expand Down Expand Up @@ -210,7 +209,7 @@ namespace ts {
}

function updateImportsWorker(sourceFile: SourceFile, changeTracker: textChanges.ChangeTracker, updateRef: (refText: string) => string | undefined, updateImport: (importLiteral: StringLiteralLike) => string | undefined) {
for (const ref of sourceFile.referencedFiles) {
for (const ref of sourceFile.referencedFiles || emptyArray) { // TODO: GH#26162
const updated = updateRef(ref.fileName);
if (updated !== undefined && updated !== sourceFile.text.slice(ref.pos, ref.end)) changeTracker.replaceRangeWithText(sourceFile, ref, updated);
}
Expand Down
8 changes: 0 additions & 8 deletions src/services/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -233,14 +233,6 @@ namespace ts {
installPackage?(options: InstallPackageOptions): Promise<ApplyCodeActionCommandResult>;
}

export interface UserPreferences {
readonly disableSuggestions?: boolean;
readonly quotePreference?: "double" | "single";
readonly includeCompletionsForModuleExports?: boolean;
readonly includeCompletionsWithInsertText?: boolean;
readonly importModuleSpecifierPreference?: "relative" | "non-relative";
readonly allowTextChangesInNewFiles?: boolean;
}
/* @internal */
export const emptyOptions = {};

Expand Down
18 changes: 10 additions & 8 deletions tests/baselines/reference/api/tsserverlibrary.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3001,6 +3001,16 @@ declare namespace ts {
Parameters = 1296,
IndexSignatureParameters = 4432
}
interface UserPreferences {
readonly disableSuggestions?: boolean;
readonly quotePreference?: "double" | "single";
readonly includeCompletionsForModuleExports?: boolean;
readonly includeCompletionsWithInsertText?: boolean;
readonly importModuleSpecifierPreference?: "relative" | "non-relative";
/** Determines whether we import `foo/index.ts` as "foo", "foo/index", or "foo/index.js" */
readonly importModuleSpecifierEnding?: "minimal" | "index" | "js";
readonly allowTextChangesInNewFiles?: boolean;
}
}
declare function setTimeout(handler: (...args: any[]) => void, timeout: number): any;
declare function clearTimeout(handle: any): void;
Expand Down Expand Up @@ -4818,14 +4828,6 @@ declare namespace ts {
isKnownTypesPackageName?(name: string): boolean;
installPackage?(options: InstallPackageOptions): Promise<ApplyCodeActionCommandResult>;
}
interface UserPreferences {
readonly disableSuggestions?: boolean;
readonly quotePreference?: "double" | "single";
readonly includeCompletionsForModuleExports?: boolean;
readonly includeCompletionsWithInsertText?: boolean;
readonly importModuleSpecifierPreference?: "relative" | "non-relative";
readonly allowTextChangesInNewFiles?: boolean;
}
interface LanguageService {
cleanupSemanticCache(): void;
getSyntacticDiagnostics(fileName: string): DiagnosticWithLocation[];
Expand Down
18 changes: 10 additions & 8 deletions tests/baselines/reference/api/typescript.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3001,6 +3001,16 @@ declare namespace ts {
Parameters = 1296,
IndexSignatureParameters = 4432
}
interface UserPreferences {
readonly disableSuggestions?: boolean;
readonly quotePreference?: "double" | "single";
readonly includeCompletionsForModuleExports?: boolean;
readonly includeCompletionsWithInsertText?: boolean;
readonly importModuleSpecifierPreference?: "relative" | "non-relative";
/** Determines whether we import `foo/index.ts` as "foo", "foo/index", or "foo/index.js" */
readonly importModuleSpecifierEnding?: "minimal" | "index" | "js";
readonly allowTextChangesInNewFiles?: boolean;
}
}
declare function setTimeout(handler: (...args: any[]) => void, timeout: number): any;
declare function clearTimeout(handle: any): void;
Expand Down Expand Up @@ -4818,14 +4828,6 @@ declare namespace ts {
isKnownTypesPackageName?(name: string): boolean;
installPackage?(options: InstallPackageOptions): Promise<ApplyCodeActionCommandResult>;
}
interface UserPreferences {
readonly disableSuggestions?: boolean;
readonly quotePreference?: "double" | "single";
readonly includeCompletionsForModuleExports?: boolean;
readonly includeCompletionsWithInsertText?: boolean;
readonly importModuleSpecifierPreference?: "relative" | "non-relative";
readonly allowTextChangesInNewFiles?: boolean;
}
interface LanguageService {
cleanupSemanticCache(): void;
getSyntacticDiagnostics(fileName: string): DiagnosticWithLocation[];
Expand Down
9 changes: 5 additions & 4 deletions tests/cases/fourslash/fourslash.ts
Original file line number Diff line number Diff line change
Expand Up @@ -526,10 +526,11 @@ declare namespace FourSlashInterface {
filesToSearch?: ReadonlyArray<string>;
}
interface UserPreferences {
quotePreference?: "double" | "single";
includeCompletionsForModuleExports?: boolean;
includeInsertTextCompletions?: boolean;
importModuleSpecifierPreference?: "relative" | "non-relative";
readonly quotePreference?: "double" | "single";
readonly includeCompletionsForModuleExports?: boolean;
readonly includeInsertTextCompletions?: boolean;
readonly importModuleSpecifierPreference?: "relative" | "non-relative";
readonly importModuleSpecifierEnding?: "minimal" | "index" | "js";
}
interface CompletionsAtOptions extends UserPreferences {
triggerCharacter?: string;
Expand Down
44 changes: 44 additions & 0 deletions tests/cases/fourslash/getEditsForFileRename_preservePathEnding.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
/// <reference path='fourslash.ts' />

// @allowJs: true
// @checkJs: true
// @strict: true
// @jsx: preserve
// @resolveJsonModule: true

// @Filename: /index.js
////export const x = 0;

// @Filename: /jsx.jsx
////export const y = 0;

// @Filename: /j.jonah.json
////{ "j": 0 }

// @Filename: /a.js
////import { x as x0 } from ".";
////import { x as x1 } from "./index";
////import { x as x2 } from "./index.js";
////import { y } from "./jsx.jsx";
////import { j } from "./j.jonah.json";

verify.noErrors();

verify.getEditsForFileRename({
oldPath: "/a.js",
newPath: "/b.js",
newFileContents: {}, // No change
});

verify.getEditsForFileRename({
oldPath: "/b.js",
newPath: "/src/b.js",
newFileContents: {
"/b.js":
`import { x as x0 } from "..";
import { x as x1 } from "../index";
import { x as x2 } from "../index.js";
import { y } from "../jsx.jsx";
import { j } from "../j.jonah.json";`,
},
});
45 changes: 23 additions & 22 deletions tests/cases/fourslash/importNameCodeFixNewImportTypeRoots0.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,23 @@
/// <reference path="fourslash.ts" />
Copy link
Author

Choose a reason for hiding this comment

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

typeRoots doesn't affect module resolution. It affects what directories are searched for automatically adding global definitions to the project. So it doesn't make sense to synthesize a specifier based on typeRoots because that will then be a compile error. paths should be used instead (which we already have a test for in importNameCodeFix_fromPathMapping.ts).
(Ref: microsoft/TypeScript-Handbook#692)

Copy link
Member

Choose a reason for hiding this comment

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

I dont agree with this, many times the typeRoots will add ambient module definitions to program and getting import module fix would be good. Adding @DanielRosenwasser please comment on this. (look at vscode code i believe it adds typeRoots to add additional typings)

In anycase instead of deleting this test case (where we are using typeroots, add negative test to help catch any future regressions)

Copy link
Author

Choose a reason for hiding this comment

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

If there is an ambient module definition we should already be handling that without typeRoots. See importNameCodeFixNewImportAmbient0.ts.


// @Filename: a/f1.ts
//// [|foo/*0*/();|]

// @Filename: types/random/index.ts
//// export function foo() {};

// @Filename: tsconfig.json
//// {
//// "compilerOptions": {
//// "typeRoots": [
//// "./types"
//// ]
//// }
//// }

verify.importFixAtPosition([
`import { foo } from "random";

foo();`
]);
/// <reference path="fourslash.ts" />

// @Filename: a/f1.ts
//// [|foo/*0*/();|]

// @Filename: types/random/index.ts
//// export function foo() {};

// @Filename: tsconfig.json
//// {
//// "compilerOptions": {
//// "typeRoots": [
//// "./types"
//// ]
//// }
//// }

// "typeRoots" does not affect module resolution. Importing from "random" would be a compile error.
verify.importFixAtPosition([
`import { foo } from "../types/random";

foo();`
]);
50 changes: 27 additions & 23 deletions tests/cases/fourslash/importNameCodeFixNewImportTypeRoots1.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,27 @@
/// <reference path="fourslash.ts" />

// @Filename: a/f1.ts
//// [|foo/*0*/();|]

// @Filename: types/random/index.ts
//// export function foo() {};

// @Filename: tsconfig.json
//// {
//// "compilerOptions": {
//// "baseUrl": ".",
//// "typeRoots": [
//// "./types"
//// ]
//// }
//// }

verify.importFixAtPosition([
`import { foo } from "random";

foo();`
]);
/// <reference path="fourslash.ts" />

// @Filename: a/f1.ts
//// [|foo/*0*/();|]

// @Filename: types/random/index.ts
//// export function foo() {};

// @Filename: tsconfig.json
//// {
//// "compilerOptions": {
//// "baseUrl": ".",
//// "typeRoots": [
//// "./types"
//// ]
//// }
//// }

// "typeRoots" does not affect module resolution. Importing from "random" would be a compile error.
verify.importFixAtPosition([
`import { foo } from "types/random";

foo();`,
`import { foo } from "../types/random";

foo();`
]);
26 changes: 26 additions & 0 deletions tests/cases/fourslash/importNameCodeFix_endingPreference.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/// <reference path="fourslash.ts" />

// @moduleResolution: node

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

// @Filename: /a.ts
////foo;

// @Filename: /b.ts
////foo;

// @Filename: /c.ts
////foo;

const tests: ReadonlyArray<[string, FourSlashInterface.UserPreferences["importModuleSpecifierEnding"], string]> = [
["/a.ts", "js", "./foo/index.js"],
["/b.ts", "index", "./foo/index"],
["/c.ts", "minimal", "./foo"],
];

for (const [fileName, importModuleSpecifierEnding, specifier] of tests) {
goTo.file(fileName);
verify.importFixAtPosition([`import { foo } from "${specifier}";\n\nfoo;`,], /*errorCode*/ undefined, { importModuleSpecifierEnding });
}
Loading