microsoft/vscode-react-native

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
81f88231b0c98e7265fe93cd7fb01b25ee66f67f

Branches

Tags

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

Clone

HTTPS

Download ZIP

src/extension/intellisenseHelper.ts

276lines · 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 {HostPlatform} 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.createTsConfigIfNotPresent())
43 .then(() => IntellisenseHelper.installReactNativeTypings());
44
45 // The actions taken in the promise chain below may result in requring a restart.
46 const configureTypescript = Q(false)
47 .then((isRestartRequired: boolean) => IntellisenseHelper.enableSalsa(isRestartRequired))
48 .then((isRestartRequired: boolean) => IntellisenseHelper.verifyInstallTypeScript(isRestartRequired))
49 .then((isRestartRequired: boolean) => IntellisenseHelper.configureWorkspaceSettings(isRestartRequired))
50 .then((isRestartRequired: boolean) => IntellisenseHelper.warnIfRestartIsRequired(isRestartRequired))
51 .catch((err: any) => {
52 Log.logError("Error while setting up IntelliSense: " + err);
53 return Q.reject<void>(err);
54 });
55
56 /* TODO #83: Refactor this code to
57 Q.all([enableSalsa(), installTypescript(), configureWorkspace()])
58 .then((result) => warnIfRestartIsRequired(result.any((x) => x)))
59 */
60 return Q.all([configureWorkspace, configureTypescript]).then(() => { });
61 }
62
63 /**
64 * Helper method that install typings for React Native.
65 */
66 public static installReactNativeTypings(): Q.Promise<void> {
67 const typingsSource = path.resolve(__dirname, "..", "..", "ReactTypings");
68 const reactTypings = path.resolve(typingsSource, "react");
69 const reactNativeTypings = path.resolve(typingsSource, "react-native");
70
71 const typingsDestination = path.resolve(vscode.workspace.rootPath, ".vscode", "typings");
72 const reactTypingsDestination = path.resolve(typingsDestination, "react");
73 const reactNativeTypingsDestination = path.resolve(typingsDestination, "react-native");
74
75 let fileSystem = new FileSystem();
76
77 const createTypingsDirectoryIfNeeded = fileSystem.directoryExists(typingsDestination).
78 then((exists) => {
79 if (!exists) {
80 return fileSystem.makeDirectoryRecursiveSync(typingsDestination);
81 }
82 });
83 const copyReactTypingsIfNeeded = fileSystem.directoryExists(reactTypingsDestination)
84 .then((exists) => {
85 if (!exists) {
86 return fileSystem.copyRecursive(reactTypings, reactTypingsDestination);
87 }
88 });
89 const copyReactNativeTypingsIfNeeded = fileSystem.directoryExists(reactNativeTypingsDestination)
90 .then((exists) => {
91 if (!exists) {
92 return fileSystem.copyRecursive(reactNativeTypings, reactNativeTypingsDestination);
93 }
94 });
95 return Q.all([createTypingsDirectoryIfNeeded, copyReactTypingsIfNeeded, copyReactNativeTypingsIfNeeded]).then(() => { });
96 }
97
98 /**
99 * Helper method that verifies the correct version of TypeScript is installed.
100 * If using a newer version of VSCode TypeScript is installed by default and no
101 * action is needed. If using an older version, verify that the correct TS version is
102 * installed, if not install it.
103 */
104 public static verifyInstallTypeScript(isRestartRequired: boolean): Q.Promise<boolean> {
105
106 if (IntellisenseHelper.isSalsaSupported()) {
107 // this is the correct version of vscode, which includes TypeScript (Salsa) support, nothing to do here
108 return Q.resolve<boolean>(isRestartRequired);
109 }
110
111 return IntellisenseHelper.getInstalledTypeScriptVersion()
112 .then(function(installProps: IInstallProps) {
113
114 if (installProps.installed === true) {
115
116 if (semver.neq(IntellisenseHelper.s_typeScriptVersion, installProps.version)) {
117 Log.logInternalMessage(LogLevel.Debug, "TypeScript is installed with the wrong version: " + installProps.version);
118 return true;
119 } else {
120 Log.logInternalMessage(LogLevel.Debug, "Installed TypeScript version is correct");
121 return false;
122 }
123 } else {
124 Log.logInternalMessage(LogLevel.Debug, "TypeScript is not installed");
125 return true;
126 }
127 })
128 .then((install: boolean) => {
129
130 if (install) {
131 let installPath: string = path.resolve(HostPlatform.getUserHomePath(), ".vscode");
132 let runArguments: string[] = [];
133 let npmCommand: string = HostPlatform.getNpmCliCommand("npm");
134 runArguments.push("install");
135 runArguments.push("--prefix " + installPath);
136 runArguments.push("typescript@" + IntellisenseHelper.s_typeScriptVersion);
137
138 return new CommandExecutor(installPath).spawn(npmCommand, runArguments)
139 .then(() => {
140 return true;
141 })
142 .catch((err: any) => {
143 Log.logError("Error attempting to install TypeScript: " + err);
144 return Q.reject<boolean>(err);
145 });
146
147 } else {
148 return isRestartRequired;
149 }
150 });
151 }
152
153
154
155 public static configureWorkspaceSettings(isRestartRequired: boolean): boolean {
156 let typeScriptLibPath: string = path.resolve(IntellisenseHelper.getTypeScriptInstallPath(), "lib");
157 const tsdkPath = SettingsHelper.getTypeScriptTsdk();
158
159 if (IntellisenseHelper.isSalsaSupported()) {
160 if (tsdkPath === typeScriptLibPath) {
161 // Note: In previous releases of VSCode (< 0.10.10) the Salsa TypeScript
162 // IntelliSense was not enabled by default, this extension would install
163 // Salsa itself, and update the settings to point at that. Here we
164 // attempt to reset that value to null if it still points to the previous
165 // installed (and no longer valid) version of TypeScript.
166 SettingsHelper.notifyUserToRemoveTSDKFromSettingsJson(tsdkPath);
167 // We are already telling the user to restart. No need to show another message.
168 return false;
169 }
170 } else {
171 if (tsdkPath === null) {
172 SettingsHelper.notifyUserToAddTSDKInSettingsJson(typeScriptLibPath);
173 // We are already telling the user to restart. No need to show another message.
174 return false;
175 }
176 }
177 return isRestartRequired;
178 }
179
180 public static warnIfRestartIsRequired(isRestartRequired: boolean): Q.Promise<void> {
181 if (isRestartRequired) {
182 vscode.window.showInformationMessage("React Native intellisense was successfully configured for this project. Restart to enable it.");
183 }
184
185 return;
186 }
187
188 /**
189 * Helper method that sets the environment variable and informs the user they need to restart
190 * in order to enable the Salsa intellisense.
191 */
192 public static enableSalsa(isRestartRequired: boolean): Q.Promise<boolean> {
193 if (!IntellisenseHelper.isSalsaSupported() && !process.env.VSCODE_TSJS) {
194 return Q({})
195 .then(() => HostPlatform.setEnvironmentVariable("VSCODE_TSJS", "1"))
196 .then(() => { return true; });
197 }
198
199 return Q(isRestartRequired);
200 }
201
202 /**
203 * Simple check to see if the TypeScript package is in the expected location (where we installed it)
204 */
205 private static isTypeScriptInstalled(): Q.Promise<boolean> {
206 let fileSystem: FileSystem = new FileSystem();
207 let installPath: string = path.join(IntellisenseHelper.getTypeScriptInstallPath(), "lib");
208 return fileSystem.exists(installPath);
209 }
210
211 /**
212 * Checks for the existance of our installed TypeScript package, if it exists also determine its version
213 */
214 private static getInstalledTypeScriptVersion(): Q.Promise<IInstallProps> {
215 return IntellisenseHelper.isTypeScriptInstalled()
216 .then((installed: boolean) => {
217 let installProps: IInstallProps = {
218 installed: installed,
219 version: "",
220 };
221
222 if (installed === true) {
223 Log.logInternalMessage(LogLevel.Debug, "TypeScript is installed - checking version");
224 return IntellisenseHelper.readPackageJson()
225 .then((version: string) => {
226 installProps.version = version;
227 return installProps;
228 });
229 } else {
230 return installProps;
231 }
232 });
233 }
234
235 /**
236 * Read the package.json from the TypeScript install path and return the version if it's available
237 */
238 private static readPackageJson(): Q.Promise<string> {
239 let packageFilePath: string = path.join(IntellisenseHelper.getTypeScriptInstallPath(), "package.json");
240 let fileSystem = new FileSystem();
241
242 return fileSystem.exists(packageFilePath)
243 .then(function(exists: boolean): Q.Promise<string> {
244 if (!exists) {
245 return Q.reject<string>("package.json not found at:" + packageFilePath);
246 }
247
248 return fileSystem.readFile(packageFilePath, "utf-8");
249 })
250 .then(function(jsonContents: string): Q.Promise<any> {
251 let data = JSON.parse(jsonContents);
252 return data.version;
253 })
254 .catch((err: any) => {
255 Log.logError("Error while processing package.json: " + err);
256 return "0.0.0";
257 });
258 }
259
260 /**
261 * Simple helper to get the TypeScript install path
262 */
263 private static getTypeScriptInstallPath(): string {
264
265 let codePath: string = path.resolve(HostPlatform.getUserHomePath(), ".vscode");
266 let typeScriptLibPath: string = path.join(codePath, "node_modules", "typescript");
267 return typeScriptLibPath;
268 }
269
270 /**
271 * Simple helper to determine if the current version of VSCode supports TypeScript (Salsa) or better
272 */
273 private static isSalsaSupported(): boolean {
274 return semver.gte(vscode.version, IntellisenseHelper.s_vsCodeVersion, true);
275 }
276}
277