microsoft/vscode-react-native

Public

mirrored fromhttps://github.com/microsoft/vscode-react-nativeAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
f521686613075eb4a9cebc89a01cbcf289ec258f

Branches

Tags

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

Clone

HTTPS

Download ZIP

src/debugger/debugSessionBase.ts

197lines · 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 * as vscode from "vscode";
5import * as Q from "q";
6import * as path from "path";
7import * as fs from "fs";
8import stripJsonComments = require("strip-json-comments");
9import { LoggingDebugSession, Logger, logger, ErrorDestination } from "vscode-debugadapter";
10import { DebugProtocol } from "vscode-debugprotocol";
11import { getLoggingDirectory, LogHelper } from "../extension/log/LogHelper";
12import { ReactNativeProjectHelper } from "../common/reactNativeProjectHelper";
13import { ErrorHelper } from "../common/error/errorHelper";
14import { InternalErrorCode } from "../common/error/internalErrorCode";
15import { InternalError, NestedError } from "../common/error/internalError";
16import { ILaunchArgs } from "../extension/launchArgs";
17import { AppLauncher } from "../extension/appLauncher";
18import { LogLevel } from "../extension/log/LogHelper";
19import * as nls from "vscode-nls";
20const localize = nls.loadMessageBundle();
21
22/**
23 * Enum of possible statuses of debug session
24 */
25export 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
40export interface TerminateEventArgs {
41 debugSession: vscode.DebugSession;
42 args: any;
43}
44
45export interface IAttachRequestArgs extends DebugProtocol.AttachRequestArguments, ILaunchArgs {
46 cwd: string; /* Automatically set by VS Code to the currently opened folder */
47 port: number;
48 url?: string;
49 address?: string;
50 trace?: string;
51 skipFiles?: [];
52}
53
54export interface ILaunchRequestArgs extends DebugProtocol.LaunchRequestArguments, IAttachRequestArgs { }
55
56export abstract class DebugSessionBase extends LoggingDebugSession {
57
58 protected static rootSessionTerminatedEventEmitter: vscode.EventEmitter<TerminateEventArgs> = new vscode.EventEmitter<TerminateEventArgs>();
59 public static readonly onDidTerminateRootDebugSession = DebugSessionBase.rootSessionTerminatedEventEmitter.event;
60
61 protected readonly disconnectCommand: string;
62 protected readonly pwaNodeSessionName: string;
63
64 protected appLauncher: AppLauncher;
65 protected projectRootPath: string;
66 protected isSettingsInitialized: boolean; // used to prevent parameters reinitialization when attach is called from launch function
67 protected previousAttachArgs: IAttachRequestArgs;
68 protected cdpProxyLogLevel: LogLevel;
69 protected debugSessionStatus: DebugSessionStatus;
70 protected session: vscode.DebugSession;
71 protected cancellationTokenSource: vscode.CancellationTokenSource;
72
73 constructor(session: vscode.DebugSession) {
74 super();
75
76 // constants definition
77 this.pwaNodeSessionName = "pwa-node"; // the name of node debug session created by js-debug extension
78 this.disconnectCommand = "disconnect";
79
80 // variables definition
81 this.session = session;
82 this.isSettingsInitialized = false;
83 this.debugSessionStatus = DebugSessionStatus.FirstConnection;
84 this.cancellationTokenSource = new vscode.CancellationTokenSource();
85 }
86
87 protected initializeRequest(response: DebugProtocol.InitializeResponse, args: DebugProtocol.InitializeRequestArguments): void {
88 response.body = response.body || {};
89
90 response.body.supportsConfigurationDoneRequest = true;
91 response.body.supportsEvaluateForHovers = true;
92 response.body.supportTerminateDebuggee = true;
93 response.body.supportsCancelRequest = true;
94
95 this.sendResponse(response);
96 }
97
98 protected abstract establishDebugSession(attachArgs: IAttachRequestArgs, resolve?: (value?: void | PromiseLike<void> | undefined) => void): void;
99
100 protected initializeSettings(args: any): Q.Promise<any> {
101 if (!this.isSettingsInitialized) {
102 let chromeDebugCoreLogs = getLoggingDirectory();
103 if (chromeDebugCoreLogs) {
104 chromeDebugCoreLogs = path.join(chromeDebugCoreLogs, "DebugSessionLogs.txt");
105 }
106 let logLevel: string = args.trace;
107 if (logLevel) {
108 logLevel = logLevel.replace(logLevel[0], logLevel[0].toUpperCase());
109 logger.setup(Logger.LogLevel[logLevel], chromeDebugCoreLogs || false);
110 this.cdpProxyLogLevel = LogLevel[logLevel] === LogLevel.Verbose ? LogLevel.Custom : LogLevel.None;
111 } else {
112 logger.setup(Logger.LogLevel.Log, chromeDebugCoreLogs || false);
113 this.cdpProxyLogLevel = LogHelper.LOG_LEVEL === LogLevel.Trace ? LogLevel.Custom : LogLevel.None;
114 }
115
116 if (!args.sourceMaps) {
117 args.sourceMaps = true;
118 }
119
120 const projectRootPath = getProjectRoot(args);
121 return ReactNativeProjectHelper.isReactNativeProject(projectRootPath)
122 .then((result) => {
123 if (!result) {
124 throw ErrorHelper.getInternalError(InternalErrorCode.NotInReactNativeFolderError);
125 }
126 this.projectRootPath = projectRootPath;
127 this.appLauncher = AppLauncher.getAppLauncherByProjectRootPath(projectRootPath);
128 this.isSettingsInitialized = true;
129
130 return void 0;
131 });
132 } else {
133 return Q.resolve<void>(void 0);
134 }
135 }
136
137 protected async disconnectRequest(response: DebugProtocol.DisconnectResponse, args: DebugProtocol.DisconnectArguments, request?: DebugProtocol.Request): Promise<void> {
138 await this.appLauncher.getRnCdpProxy().stopServer();
139
140 this.cancellationTokenSource.cancel();
141 this.cancellationTokenSource.dispose();
142
143 // Then we tell the extension to stop monitoring the logcat, and then we disconnect the debugging session
144 if (this.previousAttachArgs && this.previousAttachArgs.platform === "android") {
145 try {
146 this.appLauncher.stopMonitoringLogCat();
147 } catch (err) {
148 logger.warn(localize("CouldNotStopMonitoringLogcat", "Couldn't stop monitoring logcat: {0}", err.message || err));
149 }
150 }
151
152 DebugSessionBase.rootSessionTerminatedEventEmitter.fire({
153 debugSession: this.session,
154 args: {
155 forcedStop: (<any>args).forcedStop,
156 },
157 });
158
159 this.sendResponse(response);
160 }
161
162 protected showError(error: Error, response: DebugProtocol.Response): void {
163
164 // We can't print error messages after the debugging session is stopped. This could break the extension work.
165 if ((error instanceof InternalError || error instanceof NestedError)
166 && error.errorCode === InternalErrorCode.CancellationTokenTriggered
167 ) {
168 return;
169 }
170
171 this.sendErrorResponse(
172 response,
173 { format: error.message, id: 1 },
174 undefined,
175 undefined,
176 ErrorDestination.User
177 );
178 }
179}
180
181/**
182 * Parses settings.json file for workspace root property
183 */
184export function getProjectRoot(args: any): string {
185 const vsCodeRoot = args.cwd ? path.resolve(args.cwd) : path.resolve(args.program, "../..");
186 const settingsPath = path.resolve(vsCodeRoot, ".vscode/settings.json");
187 try {
188 let settingsContent = fs.readFileSync(settingsPath, "utf8");
189 settingsContent = stripJsonComments(settingsContent);
190 let parsedSettings = JSON.parse(settingsContent);
191 let projectRootPath = parsedSettings["react-native-tools.projectRoot"] || parsedSettings["react-native-tools"].projectRoot;
192 return path.resolve(vsCodeRoot, projectRootPath);
193 } catch (e) {
194 logger.verbose(`${settingsPath} file doesn't exist or its content is incorrect. This file will be ignored.`);
195 return args.cwd ? path.resolve(args.cwd) : path.resolve(args.program, "../..");
196 }
197}
198