microsoft/vscode-react-native
Publicmirrored fromhttps://github.com/microsoft/vscode-react-nativeAvailable
src/extension/exponent/exponentHelper.ts
308lines · 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 | |
| 4 | /// <reference path="exponentHelper.d.ts" /> |
| 5 | |
| 6 | import * as path from "path"; |
| 7 | import * as Q from "q"; |
| 8 | import * as XDL from "./xdlInterface"; |
| 9 | import { Package } from "../../common/node/package"; |
| 10 | import { ReactNativeProjectHelper } from "../../common/reactNativeProjectHelper"; |
| 11 | import { FileSystem } from "../../common/node/fileSystem"; |
| 12 | import {OutputChannelLogger} from "../log/OutputChannelLogger"; |
| 13 | import stripJSONComments = require("strip-json-comments"); |
| 14 | |
| 15 | const APP_JSON = "app.json"; |
| 16 | const EXP_JSON = "exp.json"; |
| 17 | |
| 18 | const EXPONENT_INDEX = "exponentIndex.js"; |
| 19 | const DEFAULT_EXPONENT_INDEX = "index.js"; |
| 20 | const DEFAULT_IOS_INDEX = "index.ios.js"; |
| 21 | const DEFAULT_ANDROID_INDEX = "index.android.js"; |
| 22 | |
| 23 | const DBL_SLASHES = /\\/g; |
| 24 | |
| 25 | export class ExponentHelper { |
| 26 | private workspaceRootPath: string; |
| 27 | private projectRootPath: string; |
| 28 | private fs: FileSystem; |
| 29 | private hasInitialized: boolean; |
| 30 | private logger: OutputChannelLogger = OutputChannelLogger.getMainChannel(); |
| 31 | |
| 32 | public constructor(workspaceRootPath: string, projectRootPath: string) { |
| 33 | this.workspaceRootPath = workspaceRootPath; |
| 34 | this.projectRootPath = projectRootPath; |
| 35 | this.hasInitialized = false; |
| 36 | // Constructor is slim by design. This is to add as less computation as possible |
| 37 | // to the initialization of the extension. If a public method is added, make sure |
| 38 | // to call this.lazilyInitialize() at the begining of the code to be sure all variables |
| 39 | // are correctly initialized. |
| 40 | } |
| 41 | |
| 42 | public configureExponentEnvironment(): Q.Promise<void> { |
| 43 | this.lazilyInitialize(); |
| 44 | this.logger.info("Making sure your project uses the correct dependencies for exponent. This may take a while..."); |
| 45 | return this.isExpoApp(true) |
| 46 | .then(isExpo => { |
| 47 | this.logger.logStream(".\n"); |
| 48 | |
| 49 | return this.patchAppJson(isExpo); |
| 50 | }); |
| 51 | } |
| 52 | |
| 53 | /** |
| 54 | * Returns the current user. If there is none, asks user for username and password and logins to exponent servers. |
| 55 | */ |
| 56 | public loginToExponent( |
| 57 | promptForInformation: (message: string, password: boolean) => Q.Promise<string>, |
| 58 | showMessage: (message: string) => Q.Promise<string> |
| 59 | ): Q.Promise<XDL.IUser> { |
| 60 | this.lazilyInitialize(); |
| 61 | return XDL.currentUser() |
| 62 | .then((user) => { |
| 63 | if (!user) { |
| 64 | let username = ""; |
| 65 | return showMessage("You need to login to exponent. Please provide username and password to login. If you don't have an account we will create one for you.") |
| 66 | .then(() => |
| 67 | promptForInformation("Exponent username", false) |
| 68 | ).then((name: string) => { |
| 69 | username = name; |
| 70 | return promptForInformation("Exponent password", true); |
| 71 | }) |
| 72 | .then((password: string) => |
| 73 | XDL.login(username, password)); |
| 74 | } |
| 75 | return user; |
| 76 | }) |
| 77 | .catch(error => { |
| 78 | return Q.reject<XDL.IUser>(error); |
| 79 | }); |
| 80 | } |
| 81 | |
| 82 | public getExpPackagerOptions(): Q.Promise<ExpConfigPackager> { |
| 83 | this.lazilyInitialize(); |
| 84 | return this.getFromExpConfig("packagerOpts") |
| 85 | .then(opts => opts || {}); |
| 86 | } |
| 87 | |
| 88 | /** |
| 89 | * Path to a given file inside the .vscode directory |
| 90 | */ |
| 91 | private dotvscodePath(filename: string): string { |
| 92 | return path.join(this.workspaceRootPath, ".vscode", filename); |
| 93 | } |
| 94 | |
| 95 | private createExpoEntry(name: string): Q.Promise<void> { |
| 96 | this.lazilyInitialize(); |
| 97 | return this.detectEntry() |
| 98 | .then((entryPoint: string) => { |
| 99 | const content = this.generateFileContent(name, entryPoint); |
| 100 | return this.fs.writeFile(this.dotvscodePath(EXPONENT_INDEX), content); |
| 101 | }); |
| 102 | |
| 103 | } |
| 104 | |
| 105 | private detectEntry(): Q.Promise<string> { |
| 106 | this.lazilyInitialize(); |
| 107 | return Q.all([ |
| 108 | this.fs.exists(this.pathToFileInWorkspace(DEFAULT_EXPONENT_INDEX)), |
| 109 | this.fs.exists(this.pathToFileInWorkspace(DEFAULT_IOS_INDEX)), |
| 110 | this.fs.exists(this.pathToFileInWorkspace(DEFAULT_ANDROID_INDEX)), |
| 111 | ]) |
| 112 | .spread((expo: boolean, ios: boolean): string => { |
| 113 | return expo ? this.pathToFileInWorkspace(DEFAULT_EXPONENT_INDEX) : |
| 114 | ios ? this.pathToFileInWorkspace(DEFAULT_IOS_INDEX) : |
| 115 | this.pathToFileInWorkspace(DEFAULT_ANDROID_INDEX); |
| 116 | }); |
| 117 | } |
| 118 | |
| 119 | private generateFileContent(name: string, entryPoint: string): string { |
| 120 | return `// This file is automatically generated by VS Code |
| 121 | // Please do not modify it manually. All changes will be lost. |
| 122 | var React = require('${this.pathToFileInWorkspace("/node_modules/react")}'); |
| 123 | var { Component } = React; |
| 124 | var ReactNative = require('${this.pathToFileInWorkspace("/node_modules/react-native")}'); |
| 125 | var { AppRegistry } = ReactNative; |
| 126 | var entryPoint = require('${entryPoint}'); |
| 127 | AppRegistry.registerRunnable('main', function(appParameters) { |
| 128 | AppRegistry.runApplication('${name}', appParameters); |
| 129 | });`; |
| 130 | } |
| 131 | |
| 132 | private patchAppJson(isExpo: boolean = true): Q.Promise<void> { |
| 133 | return this.readAppJson() |
| 134 | .catch(() => { |
| 135 | // if app.json doesn't exist but it's ok, we will create it |
| 136 | return {}; |
| 137 | }) |
| 138 | .then((config: AppJson) => { |
| 139 | let expoConfig = <ExpConfig>(config.expo || {}); |
| 140 | if (!expoConfig.name || !expoConfig.slug) { |
| 141 | return this.getPackageName() |
| 142 | .then((name: string) => { |
| 143 | expoConfig.slug = expoConfig.slug || config.name || name.replace(" ", "-"); |
| 144 | expoConfig.name = expoConfig.name || config.name || name; |
| 145 | config.expo = expoConfig; |
| 146 | return config; |
| 147 | }); |
| 148 | } |
| 149 | |
| 150 | return config; |
| 151 | }) |
| 152 | .then((config: AppJson) => { |
| 153 | if (!config.expo.sdkVersion) { |
| 154 | return this.exponentSdk(true) |
| 155 | .then(sdkVersion => { |
| 156 | config.expo.sdkVersion = sdkVersion; |
| 157 | return config; |
| 158 | }); |
| 159 | } |
| 160 | return config; |
| 161 | }) |
| 162 | .then((config: AppJson) => { |
| 163 | if (!isExpo) { |
| 164 | config.expo.entryPoint = this.dotvscodePath(EXPONENT_INDEX); |
| 165 | } |
| 166 | |
| 167 | return config; |
| 168 | }) |
| 169 | .then((config: AppJson) => { |
| 170 | return config ? this.writeAppJson(config) : config; |
| 171 | }) |
| 172 | .then((config: AppJson) => { |
| 173 | return isExpo ? Q.resolve(void 0) : this.createExpoEntry(config.expo.name); |
| 174 | }); |
| 175 | } |
| 176 | |
| 177 | /** |
| 178 | * Exponent sdk version that maps to the current react-native version |
| 179 | * If react native version is not supported it returns null. |
| 180 | */ |
| 181 | private exponentSdk(showProgress: boolean = false): Q.Promise<string> { |
| 182 | if (showProgress) { |
| 183 | this.logger.logStream("..."); |
| 184 | } |
| 185 | |
| 186 | return ReactNativeProjectHelper.getReactNativeVersion(this.projectRootPath) |
| 187 | .then(version => { |
| 188 | if (showProgress) this.logger.logStream("."); |
| 189 | return XDL.mapVersion(version) |
| 190 | .then(sdkVersion => { |
| 191 | if (!sdkVersion) { |
| 192 | return XDL.supportedVersions() |
| 193 | .then((versions) => { |
| 194 | return Q.reject<string>(new Error(`React Native version not supported by exponent. Major versions supported: ${versions.join(", ")}`)); |
| 195 | }); |
| 196 | } |
| 197 | return sdkVersion; |
| 198 | }); |
| 199 | }); |
| 200 | } |
| 201 | |
| 202 | |
| 203 | /** |
| 204 | * Name specified on user's package.json |
| 205 | */ |
| 206 | private getPackageName(): Q.Promise<string> { |
| 207 | return new Package(this.projectRootPath, { fileSystem: this.fs }).name(); |
| 208 | } |
| 209 | |
| 210 | private getExpConfig(): Q.Promise<ExpConfig> { |
| 211 | return this.readExpJson() |
| 212 | .catch(err => { |
| 213 | if (err.code === "ENOENT") { |
| 214 | return this.readAppJson() |
| 215 | .then((config: AppJson) => { |
| 216 | return config.expo || {}; |
| 217 | }); |
| 218 | } |
| 219 | |
| 220 | return err; |
| 221 | }); |
| 222 | } |
| 223 | |
| 224 | private getFromExpConfig(key: string): Q.Promise<any> { |
| 225 | return this.getExpConfig() |
| 226 | .then((config: ExpConfig) => config[key]); |
| 227 | } |
| 228 | |
| 229 | /** |
| 230 | * Returns the specified setting from exp.json if it exists |
| 231 | */ |
| 232 | private readExpJson(): Q.Promise<ExpConfig> { |
| 233 | const expJsonPath = this.pathToFileInWorkspace(EXP_JSON); |
| 234 | return this.fs.readFile(expJsonPath) |
| 235 | .then(content => { |
| 236 | return JSON.parse(stripJSONComments(content)); |
| 237 | }); |
| 238 | } |
| 239 | |
| 240 | private readAppJson(): Q.Promise<AppJson> { |
| 241 | const appJsonPath = this.pathToFileInWorkspace(APP_JSON); |
| 242 | return this.fs.readFile(appJsonPath) |
| 243 | .then(content => { |
| 244 | return JSON.parse(stripJSONComments(content)); |
| 245 | }); |
| 246 | } |
| 247 | |
| 248 | private writeAppJson(config: AppJson): Q.Promise<AppJson> { |
| 249 | const appJsonPath = this.pathToFileInWorkspace(APP_JSON); |
| 250 | return this.fs.writeFile(appJsonPath, JSON.stringify(config, null, 2)) |
| 251 | .then(() => config); |
| 252 | } |
| 253 | |
| 254 | /** |
| 255 | * Path to a given file from the workspace root |
| 256 | */ |
| 257 | private pathToFileInWorkspace(filename: string): string { |
| 258 | return path.join(this.projectRootPath, filename).replace(DBL_SLASHES, "/"); |
| 259 | } |
| 260 | |
| 261 | private isExpoApp(showProgress: boolean = false): Q.Promise<boolean> { |
| 262 | this.logger.logStream("Checking if this is Expo app."); |
| 263 | if (showProgress) { |
| 264 | this.logger.logStream("..."); |
| 265 | } |
| 266 | |
| 267 | const packageJsonPath = this.pathToFileInWorkspace("package.json"); |
| 268 | return this.fs.readFile(packageJsonPath) |
| 269 | .then(content => { |
| 270 | const packageJson = JSON.parse(content); |
| 271 | const isExp = packageJson.dependencies && !!packageJson.dependencies.expo || false; |
| 272 | if (showProgress) this.logger.logStream("."); |
| 273 | return isExp; |
| 274 | }).catch(() => { |
| 275 | if (showProgress) { |
| 276 | this.logger.logStream("."); |
| 277 | } |
| 278 | // Not in a react-native project |
| 279 | return false; |
| 280 | }); |
| 281 | } |
| 282 | |
| 283 | /** |
| 284 | * Works as a constructor but only initiliazes when it's actually needed. |
| 285 | */ |
| 286 | private lazilyInitialize(): void { |
| 287 | if (!this.hasInitialized) { |
| 288 | this.hasInitialized = true; |
| 289 | this.fs = new FileSystem(); |
| 290 | |
| 291 | XDL.configReactNativeVersionWargnings(); |
| 292 | XDL.attachLoggerStream(this.projectRootPath, { |
| 293 | stream: { |
| 294 | write: (chunk: any) => { |
| 295 | if (chunk.level <= 30) { |
| 296 | this.logger.logStream(chunk.msg); |
| 297 | } else if (chunk.level === 40) { |
| 298 | this.logger.warning(chunk.msg); |
| 299 | } else { |
| 300 | this.logger.error(chunk.msg); |
| 301 | } |
| 302 | }, |
| 303 | }, |
| 304 | type: "raw", |
| 305 | }); |
| 306 | } |
| 307 | } |
| 308 | } |
| 309 | |