microsoft/vscode-react-native
Publicmirrored from https://github.com/microsoft/vscode-react-nativeAvailable
src/debugger/debugSessionBase.ts
209lines · modeblame
2c19da7fRedMickey6 years ago | 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 | import * as vscode from "vscode"; | |
| 5 | import * as path from "path"; | |
| 6 | import * as fs from "fs"; | |
| 7 | import stripJsonComments = require("strip-json-comments"); | |
984ca036RedMickey6 years ago | 8 | import { LoggingDebugSession, Logger, logger, ErrorDestination } from "vscode-debugadapter"; |
2c19da7fRedMickey6 years ago | 9 | import { DebugProtocol } from "vscode-debugprotocol"; |
| 10 | import { getLoggingDirectory, LogHelper } from "../extension/log/LogHelper"; | |
| 11 | import { ReactNativeProjectHelper } from "../common/reactNativeProjectHelper"; | |
| 12 | import { ErrorHelper } from "../common/error/errorHelper"; | |
| 13 | import { InternalErrorCode } from "../common/error/internalErrorCode"; | |
e23d1841RedMickey6 years ago | 14 | import { InternalError, NestedError } from "../common/error/internalError"; |
259c018fYuri Skorokhodov5 years ago | 15 | import { ILaunchArgs, PlatformType } from "../extension/launchArgs"; |
2c19da7fRedMickey6 years ago | 16 | import { AppLauncher } from "../extension/appLauncher"; |
| 17 | import { LogLevel } from "../extension/log/LogHelper"; | |
e23d1841RedMickey6 years ago | 18 | import * as nls from "vscode-nls"; |
2d8af448Yuri Skorokhodov6 years ago | 19 | nls.config({ messageFormat: nls.MessageFormat.bundle, bundleFormat: nls.BundleFormat.standalone })(); |
e23d1841RedMickey6 years ago | 20 | const localize = nls.loadMessageBundle(); |
2c19da7fRedMickey6 years ago | 21 | |
| 22 | /** | |
| 23 | * Enum of possible statuses of debug session | |
| 24 | */ | |
| 25 | export enum DebugSessionStatus { | |
| 26 | /** A session has been just created */ | |
| 27 | FirstConnection, | |
| 28 | /** This status is required in order to exclude the possible creation of several debug sessions at the first start */ | |
| 29 | FirstConnectionPending, | |
| 30 | /** This status means that an application can be reloaded */ | |
| 31 | ConnectionAllowed, | |
| 32 | /** This status means that an application is reloading now, and we shouldn't terminate the current debug session */ | |
| 33 | ConnectionPending, | |
| 34 | /** A debuggee connected successfully */ | |
| 35 | ConnectionDone, | |
| 36 | /** A debuggee failed to connect */ | |
| 37 | ConnectionFailed, | |
| 38 | } | |
| 39 | | |
ebbd64f1RedMickey6 years ago | 40 | export interface TerminateEventArgs { |
| 41 | debugSession: vscode.DebugSession; | |
| 42 | args: any; | |
| 43 | } | |
| 44 | | |
2c19da7fRedMickey6 years ago | 45 | export interface IAttachRequestArgs extends DebugProtocol.AttachRequestArguments, ILaunchArgs { |
259c018fYuri Skorokhodov5 years ago | 46 | webkitRangeMax: number; |
| 47 | webkitRangeMin: number; | |
2c19da7fRedMickey6 years ago | 48 | cwd: string; /* Automatically set by VS Code to the currently opened folder */ |
| 49 | port: number; | |
| 50 | url?: string; | |
| 51 | address?: string; | |
| 52 | trace?: string; | |
5d47053fRedMickey6 years ago | 53 | skipFiles?: []; |
1bdccb66RedMickey6 years ago | 54 | sourceMaps?: boolean; |
| 55 | sourceMapPathOverrides?: { [key: string]: string }; | |
2c19da7fRedMickey6 years ago | 56 | } |
| 57 | | |
| 58 | export interface ILaunchRequestArgs extends DebugProtocol.LaunchRequestArguments, IAttachRequestArgs { } | |
| 59 | | |
| 60 | export abstract class DebugSessionBase extends LoggingDebugSession { | |
| 61 | | |
ebbd64f1RedMickey6 years ago | 62 | protected static rootSessionTerminatedEventEmitter: vscode.EventEmitter<TerminateEventArgs> = new vscode.EventEmitter<TerminateEventArgs>(); |
| 63 | public static readonly onDidTerminateRootDebugSession = DebugSessionBase.rootSessionTerminatedEventEmitter.event; | |
| 64 | | |
a2ddbba5RedMickey5 years ago | 65 | protected readonly stopCommand: string; |
ebbd64f1RedMickey6 years ago | 66 | protected readonly pwaNodeSessionName: string; |
| 67 | | |
2c19da7fRedMickey6 years ago | 68 | protected appLauncher: AppLauncher; |
| 69 | protected projectRootPath: string; | |
| 70 | protected isSettingsInitialized: boolean; // used to prevent parameters reinitialization when attach is called from launch function | |
| 71 | protected previousAttachArgs: IAttachRequestArgs; | |
| 72 | protected cdpProxyLogLevel: LogLevel; | |
| 73 | protected debugSessionStatus: DebugSessionStatus; | |
| 74 | protected session: vscode.DebugSession; | |
e23d1841RedMickey6 years ago | 75 | protected cancellationTokenSource: vscode.CancellationTokenSource; |
2c19da7fRedMickey6 years ago | 76 | |
| 77 | constructor(session: vscode.DebugSession) { | |
| 78 | super(); | |
| 79 | | |
ebbd64f1RedMickey6 years ago | 80 | // constants definition |
| 81 | this.pwaNodeSessionName = "pwa-node"; // the name of node debug session created by js-debug extension | |
a2ddbba5RedMickey5 years ago | 82 | this.stopCommand = "workbench.action.debug.stop"; // the command which simulates a click on the "Stop" button |
ebbd64f1RedMickey6 years ago | 83 | |
| 84 | // variables definition | |
2c19da7fRedMickey6 years ago | 85 | this.session = session; |
| 86 | this.isSettingsInitialized = false; | |
| 87 | this.debugSessionStatus = DebugSessionStatus.FirstConnection; | |
e23d1841RedMickey6 years ago | 88 | this.cancellationTokenSource = new vscode.CancellationTokenSource(); |
| 89 | } | |
| 90 | | |
| 91 | protected initializeRequest(response: DebugProtocol.InitializeResponse, args: DebugProtocol.InitializeRequestArguments): void { | |
| 92 | response.body = response.body || {}; | |
| 93 | | |
| 94 | response.body.supportsConfigurationDoneRequest = true; | |
| 95 | response.body.supportsEvaluateForHovers = true; | |
| 96 | response.body.supportTerminateDebuggee = true; | |
| 97 | response.body.supportsCancelRequest = true; | |
| 98 | | |
| 99 | this.sendResponse(response); | |
2c19da7fRedMickey6 years ago | 100 | } |
| 101 | | |
5d47053fRedMickey6 years ago | 102 | protected abstract establishDebugSession(attachArgs: IAttachRequestArgs, resolve?: (value?: void | PromiseLike<void> | undefined) => void): void; |
b7451aefRedMickey6 years ago | 103 | |
ce5e88eeYuri Skorokhodov5 years ago | 104 | protected initializeSettings(args: any): Promise<any> { |
2c19da7fRedMickey6 years ago | 105 | if (!this.isSettingsInitialized) { |
| 106 | let chromeDebugCoreLogs = getLoggingDirectory(); | |
| 107 | if (chromeDebugCoreLogs) { | |
| 108 | chromeDebugCoreLogs = path.join(chromeDebugCoreLogs, "DebugSessionLogs.txt"); | |
| 109 | } | |
| 110 | let logLevel: string = args.trace; | |
| 111 | if (logLevel) { | |
| 112 | logLevel = logLevel.replace(logLevel[0], logLevel[0].toUpperCase()); | |
| 113 | logger.setup(Logger.LogLevel[logLevel], chromeDebugCoreLogs || false); | |
| 114 | this.cdpProxyLogLevel = LogLevel[logLevel] === LogLevel.Verbose ? LogLevel.Custom : LogLevel.None; | |
| 115 | } else { | |
| 116 | logger.setup(Logger.LogLevel.Log, chromeDebugCoreLogs || false); | |
| 117 | this.cdpProxyLogLevel = LogHelper.LOG_LEVEL === LogLevel.Trace ? LogLevel.Custom : LogLevel.None; | |
| 118 | } | |
| 119 | | |
2db9ac85Yuri Skorokhodov5 years ago | 120 | if (typeof args.sourceMaps !== "boolean") { |
2c19da7fRedMickey6 years ago | 121 | args.sourceMaps = true; |
| 122 | } | |
| 123 | | |
5514e287RedMickey6 years ago | 124 | if (typeof args.enableDebug !== "boolean") { |
| 125 | args.enableDebug = true; | |
| 126 | } | |
| 127 | | |
2c19da7fRedMickey6 years ago | 128 | const projectRootPath = getProjectRoot(args); |
| 129 | return ReactNativeProjectHelper.isReactNativeProject(projectRootPath) | |
| 130 | .then((result) => { | |
| 131 | if (!result) { | |
| 132 | throw ErrorHelper.getInternalError(InternalErrorCode.NotInReactNativeFolderError); | |
| 133 | } | |
| 134 | this.projectRootPath = projectRootPath; | |
| 135 | this.appLauncher = AppLauncher.getAppLauncherByProjectRootPath(projectRootPath); | |
| 136 | this.isSettingsInitialized = true; | |
| 137 | | |
| 138 | return void 0; | |
| 139 | }); | |
| 140 | } else { | |
ce5e88eeYuri Skorokhodov5 years ago | 141 | return Promise.resolve(); |
2c19da7fRedMickey6 years ago | 142 | } |
| 143 | } | |
984ca036RedMickey6 years ago | 144 | |
e23d1841RedMickey6 years ago | 145 | protected async disconnectRequest(response: DebugProtocol.DisconnectResponse, args: DebugProtocol.DisconnectArguments, request?: DebugProtocol.Request): Promise<void> { |
a32e1e1fYuri Skorokhodov5 years ago | 146 | if (this.appLauncher) { |
| 147 | await this.appLauncher.getRnCdpProxy().stopServer(); | |
| 148 | } | |
e23d1841RedMickey6 years ago | 149 | |
| 150 | this.cancellationTokenSource.cancel(); | |
| 151 | this.cancellationTokenSource.dispose(); | |
| 152 | | |
| 153 | // Then we tell the extension to stop monitoring the logcat, and then we disconnect the debugging session | |
259c018fYuri Skorokhodov5 years ago | 154 | if (this.previousAttachArgs && this.previousAttachArgs.platform === PlatformType.Android) { |
e23d1841RedMickey6 years ago | 155 | try { |
8df5011eYuri Skorokhodov5 years ago | 156 | this.appLauncher.getMobilePlatform().dispose(); |
e23d1841RedMickey6 years ago | 157 | } catch (err) { |
| 158 | logger.warn(localize("CouldNotStopMonitoringLogcat", "Couldn't stop monitoring logcat: {0}", err.message || err)); | |
| 159 | } | |
| 160 | } | |
| 161 | | |
67ffa5b4RedMickey5 years ago | 162 | await logger.dispose(); |
| 163 | | |
ebbd64f1RedMickey6 years ago | 164 | DebugSessionBase.rootSessionTerminatedEventEmitter.fire({ |
| 165 | debugSession: this.session, | |
| 166 | args: { | |
a2ddbba5RedMickey5 years ago | 167 | forcedStop: !!(<any>args).forcedStop, |
ebbd64f1RedMickey6 years ago | 168 | }, |
| 169 | }); | |
| 170 | | |
| 171 | this.sendResponse(response); | |
e23d1841RedMickey6 years ago | 172 | } |
| 173 | | |
| 174 | protected showError(error: Error, response: DebugProtocol.Response): void { | |
| 175 | | |
| 176 | // We can't print error messages after the debugging session is stopped. This could break the extension work. | |
| 177 | if ((error instanceof InternalError || error instanceof NestedError) | |
| 178 | && error.errorCode === InternalErrorCode.CancellationTokenTriggered | |
| 179 | ) { | |
| 180 | return; | |
| 181 | } | |
| 182 | | |
984ca036RedMickey6 years ago | 183 | this.sendErrorResponse( |
| 184 | response, | |
e23d1841RedMickey6 years ago | 185 | { format: error.message, id: 1 }, |
984ca036RedMickey6 years ago | 186 | undefined, |
| 187 | undefined, | |
| 188 | ErrorDestination.User | |
| 189 | ); | |
| 190 | } | |
2c19da7fRedMickey6 years ago | 191 | } |
| 192 | | |
| 193 | /** | |
| 194 | * Parses settings.json file for workspace root property | |
| 195 | */ | |
| 196 | export function getProjectRoot(args: any): string { | |
| 197 | const vsCodeRoot = args.cwd ? path.resolve(args.cwd) : path.resolve(args.program, "../.."); | |
| 198 | const settingsPath = path.resolve(vsCodeRoot, ".vscode/settings.json"); | |
| 199 | try { | |
| 200 | let settingsContent = fs.readFileSync(settingsPath, "utf8"); | |
| 201 | settingsContent = stripJsonComments(settingsContent); | |
| 202 | let parsedSettings = JSON.parse(settingsContent); | |
| 203 | let projectRootPath = parsedSettings["react-native-tools.projectRoot"] || parsedSettings["react-native-tools"].projectRoot; | |
| 204 | return path.resolve(vsCodeRoot, projectRootPath); | |
| 205 | } catch (e) { | |
| 206 | logger.verbose(`${settingsPath} file doesn't exist or its content is incorrect. This file will be ignored.`); | |
| 207 | return args.cwd ? path.resolve(args.cwd) : path.resolve(args.program, "../.."); | |
| 208 | } | |
| 209 | } |