microsoft/vscode-react-native

Public

mirrored from https://github.com/microsoft/vscode-react-nativeAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
445b113fa38f291ca910604a6a87bab6cb5f95e9

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

src/extension/intellisenseHelper.ts

258lines · modecode

1// Copyright (c) Microsoft Corporation. All rights reserved.
2// Licensed under the MIT license. See LICENSE file in the project root for details.
3
4import {FileSystem} from "../common/node/fileSystem";
5import * as path from "path";
6import * as Q from "q";
7import * as vscode from "vscode";
8import * as semver from "semver";
9import {Telemetry} from "../common/telemetry";
10import {TelemetryHelper} from "../common/telemetryHelper";
11import {CommandExecutor} from "../common/commandExecutor";
12import {TsConfigHelper} from "./tsconfigHelper";
13import {SettingsHelper} from "./settingsHelper";
14import {HostPlatformResolver, IHostPlatform} from "../common/hostPlatform";
15import {Log} from "../common/log/log";
16import {LogLevel} from "../common/log/logHelper";
17
18
19
20interface IInstallProps {
21 installed: boolean;
22 version: string;
23}
24
25export class IntellisenseHelper {
26
27 private static s_typeScriptVersion = "1.8.2"; // preferred version of TypeScript for legacy VSCode installs
28 private static s_vsCodeVersion = "0.10.10-insider"; // preferred version of VSCode (current is 0.10.9, 0.10.10-insider+ will include native TypeScript support)
29 // note: semver considers "x.x.x-<string>" to be < "x.x.x"" - so we include insider here as the
30 // insider build is less than the release build of 0.10.10 and we will support it.
31
32 /**
33 * Helper method that configures the workspace for Salsa intellisense.
34 */
35 public static setupReactNativeIntellisense(): Q.Promise<void> {
36 // Telemetry - Send Salsa Environment setup information
37 const tsSalsaEnvSetup = TelemetryHelper.createTelemetryEvent("RNIntellisense");
38 TelemetryHelper.addTelemetryEventProperty(tsSalsaEnvSetup, "TsSalsaEnvSetup", !!process.env.VSCODE_TSJS, false);
39 Telemetry.send(tsSalsaEnvSetup);
40
41 const configureWorkspace = Q({})
42 .then(() => TsConfigHelper.allowJs(true))
43 .then(() => TsConfigHelper.addExcludePaths(["node_modules"]))
44 .then(() => IntellisenseHelper.installReactNativeTypings());
45
46 // The actions taken in the promise chain below may result in requring a restart.
47 const configureTypescript = Q(false)
48 .then((isRestartRequired: boolean) => IntellisenseHelper.enableSalsa(isRestartRequired))
49 .then((isRestartRequired: boolean) => IntellisenseHelper.verifyInstallTypeScript(isRestartRequired))
50 .then((isRestartRequired: boolean) => IntellisenseHelper.configureWorkspaceSettings(isRestartRequired))
51 .then((isRestartRequired: boolean) => IntellisenseHelper.warnIfRestartIsRequired(isRestartRequired))
52 .catch((err: any) => {
53 Log.logError("Error while setting up IntelliSense: " + err);
54 return Q.reject<void>(err);
55 });
56
57 /* TODO #83: Refactor this code to
58 Q.all([enableSalsa(), installTypescript(), configureWorkspace()])
59 .then((result) => warnIfRestartIsRequired(result.any((x) => x)))
60 */
61 return Q.all([configureWorkspace, configureTypescript]).then(() => { });
62 }
63
64 /**
65 * Helper method that install typings for React Native.
66 */
67 public static installReactNativeTypings(): Q.Promise<void> {
68 let reactTypingsSource = path.resolve(__dirname, "..", "..", "ReactTypings");
69 let reactTypingsDest = path.resolve(vscode.workspace.rootPath, ".vscode", "typings");
70 let fileSystem = new FileSystem();
71
72 return fileSystem.copyRecursive(reactTypingsSource, reactTypingsDest);
73 }
74
75 /**
76 * Helper method that verifies the correct version of TypeScript is installed.
77 * If using a newer version of VSCode TypeScript is installed by default and no
78 * action is needed. If using an older version, verify that the correct TS version is
79 * installed, if not install it.
80 */
81 public static verifyInstallTypeScript(isRestartRequired: boolean): Q.Promise<boolean> {
82
83 if (IntellisenseHelper.isSalsaSupported()) {
84 // this is the correct version of vscode, which includes TypeScript (Salsa) support, nothing to do here
85 return Q.resolve<boolean>(isRestartRequired);
86 }
87
88 return IntellisenseHelper.getInstalledTypeScriptVersion()
89 .then(function(installProps: IInstallProps) {
90
91 if (installProps.installed === true) {
92
93 if (semver.neq(IntellisenseHelper.s_typeScriptVersion, installProps.version)) {
94 Log.logInternalMessage(LogLevel.Debug, "TypeScript is installed with the wrong version: " + installProps.version);
95 return true;
96 } else {
97 Log.logInternalMessage(LogLevel.Debug, "Installed TypeScript version is correct");
98 return false;
99 }
100 } else {
101 Log.logInternalMessage(LogLevel.Debug, "TypeScript is not installed");
102 return true;
103 }
104 })
105 .then((install: boolean) => {
106
107 if (install) {
108 let hostPlatform: IHostPlatform = HostPlatformResolver.getHostPlatform();
109 let installPath: string = path.resolve(hostPlatform.getUserHomePath(), ".vscode");
110 let runArguments: string[] = [];
111 let npmCommand: string = hostPlatform.getNpmCommand();
112 runArguments.push("install");
113 runArguments.push("--prefix " + installPath);
114 runArguments.push("typescript@" + IntellisenseHelper.s_typeScriptVersion);
115
116 return new CommandExecutor(installPath).spawnAndWaitForCompletion(npmCommand, runArguments)
117 .then(() => {
118 return true;
119 })
120 .catch((err: any) => {
121 Log.logError("Error attempting to install TypeScript: " + err);
122 return Q.reject<boolean>(err);
123 });
124
125 } else {
126 return isRestartRequired;
127 }
128 });
129 }
130
131
132
133 public static configureWorkspaceSettings(isRestartRequired: boolean): Q.Promise<boolean> {
134 let typeScriptLibPath: string = path.resolve(IntellisenseHelper.getTypeScriptInstallPath(), "lib");
135
136 return SettingsHelper.getTypeScriptTsdk()
137 .then((tsdkPath: string) => {
138
139 if (IntellisenseHelper.isSalsaSupported()) {
140 if (tsdkPath !== null &&
141 tsdkPath === typeScriptLibPath) {
142 // Note: In previous releases of VSCode (< 0.10.10) the Salsa TypeScript
143 // IntelliSense was not enabled by default, this extension would install
144 // Salsa itself, and update the settings to point at that. Here we
145 // attempt to reset that value to null if it still points to the previous
146 // installed (and no longer valid) version of TypeScript.
147 return SettingsHelper.removeTypeScriptTsdk()
148 .then(() => { return true; });
149 }
150 } else {
151 if (tsdkPath === null) {
152 return SettingsHelper.setTypeScriptTsdk(typeScriptLibPath)
153 .then(() => { return true; });
154 }
155 }
156
157 return isRestartRequired;
158 });
159 }
160
161 public static warnIfRestartIsRequired(isRestartRequired: boolean): Q.Promise<void> {
162 if (isRestartRequired) {
163 vscode.window.showInformationMessage("React Native intellisense was successfully configured for this project. Restart to enable it.");
164 }
165
166 return;
167 }
168
169 /**
170 * Helper method that sets the environment variable and informs the user they need to restart
171 * in order to enable the Salsa intellisense.
172 */
173 public static enableSalsa(isRestartRequired: boolean): Q.Promise<boolean> {
174 if (!process.env.VSCODE_TSJS) {
175
176 return Q({})
177 .then(() => HostPlatformResolver.getHostPlatform().setEnvironmentVariable("VSCODE_TSJS", "1"))
178 .then(() => { return true; });
179 }
180
181 return Q(isRestartRequired);
182 }
183
184 /**
185 * Simple check to see if the TypeScript package is in the expected location (where we installed it)
186 */
187 private static isTypeScriptInstalled(): Q.Promise<boolean> {
188 let fileSystem: FileSystem = new FileSystem();
189 let installPath: string = path.join(IntellisenseHelper.getTypeScriptInstallPath(), "lib");
190 return fileSystem.exists(installPath);
191 }
192
193 /**
194 * Checks for the existance of our installed TypeScript package, if it exists also determine its version
195 */
196 private static getInstalledTypeScriptVersion(): Q.Promise<IInstallProps> {
197 return IntellisenseHelper.isTypeScriptInstalled()
198 .then((installed: boolean) => {
199 let installProps: IInstallProps = {
200 installed: installed,
201 version: ""
202 };
203
204 if (installed === true) {
205 Log.logInternalMessage(LogLevel.Debug, "TypeScript is installed - checking version");
206 return IntellisenseHelper.readPackageJson()
207 .then((version: string) => {
208 installProps.version = version;
209 return installProps;
210 });
211 } else {
212 return installProps;
213 }
214 });
215 }
216
217 /**
218 * Read the package.json from the TypeScript install path and return the version if it's available
219 */
220 private static readPackageJson(): Q.Promise<string> {
221 let packageFilePath: string = path.join(IntellisenseHelper.getTypeScriptInstallPath(), "package.json");
222 let fileSystem = new FileSystem();
223
224 return fileSystem.exists(packageFilePath)
225 .then(function(exists: boolean): Q.Promise<string> {
226 if (!exists) {
227 return Q.reject<string>("package.json not found at:" + packageFilePath);
228 }
229
230 return fileSystem.readFile(packageFilePath, "utf-8");
231 })
232 .then(function(jsonContents: string): Q.Promise<any> {
233 let data = JSON.parse(jsonContents);
234 return data.version;
235 })
236 .catch((err: any) => {
237 Log.logError("Error while procesing package.json: " + err);
238 return "0.0.0";
239 });
240 }
241
242 /**
243 * Simple helper to get the TypeScript install path
244 */
245 private static getTypeScriptInstallPath(): string {
246
247 let codePath: string = path.resolve(HostPlatformResolver.getHostPlatform().getUserHomePath(), ".vscode");
248 let typeScriptLibPath: string = path.join(codePath, "node_modules", "typescript");
249 return typeScriptLibPath;
250 }
251
252 /**
253 * Simple helper to determine if the current version of VSCode supports TypeScript (Salsa) or better
254 */
255 private static isSalsaSupported(): boolean {
256 return semver.gte(vscode.version, IntellisenseHelper.s_vsCodeVersion, true);
257 }
258}