microsoft/vscode-react-native

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
68a5b8d5c6704ec52a8966b3776a8c976314d895

Branches

Tags

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

Clone

HTTPS

Download ZIP

src/debugger/debugSessionBase.ts

205lines · modeblame

2c19da7fRedMickey6 years ago1// 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 path from "path";
6import * as fs from "fs";
7import stripJsonComments = require("strip-json-comments");
984ca036RedMickey6 years ago8import { LoggingDebugSession, Logger, logger, ErrorDestination } from "vscode-debugadapter";
2c19da7fRedMickey6 years ago9import { DebugProtocol } from "vscode-debugprotocol";
10import { getLoggingDirectory, LogHelper } from "../extension/log/LogHelper";
11import { ReactNativeProjectHelper } from "../common/reactNativeProjectHelper";
12import { ErrorHelper } from "../common/error/errorHelper";
13import { InternalErrorCode } from "../common/error/internalErrorCode";
e23d1841RedMickey6 years ago14import { InternalError, NestedError } from "../common/error/internalError";
2c19da7fRedMickey6 years ago15import { ILaunchArgs } from "../extension/launchArgs";
16import { AppLauncher } from "../extension/appLauncher";
17import { LogLevel } from "../extension/log/LogHelper";
e23d1841RedMickey6 years ago18import * as nls from "vscode-nls";
2d8af448Yuri Skorokhodov6 years ago19nls.config({ messageFormat: nls.MessageFormat.bundle, bundleFormat: nls.BundleFormat.standalone })();
e23d1841RedMickey6 years ago20const localize = nls.loadMessageBundle();
2c19da7fRedMickey6 years ago21
22/**
23* Enum of possible statuses of debug session
24*/
25export enum DebugSessionStatus {
26/** A session has been just created */
27FirstConnection,
28/** This status is required in order to exclude the possible creation of several debug sessions at the first start */
29FirstConnectionPending,
30/** This status means that an application can be reloaded */
31ConnectionAllowed,
32/** This status means that an application is reloading now, and we shouldn't terminate the current debug session */
33ConnectionPending,
34/** A debuggee connected successfully */
35ConnectionDone,
36/** A debuggee failed to connect */
37ConnectionFailed,
38}
39
ebbd64f1RedMickey6 years ago40export interface TerminateEventArgs {
41debugSession: vscode.DebugSession;
42args: any;
43}
44
2c19da7fRedMickey6 years ago45export interface IAttachRequestArgs extends DebugProtocol.AttachRequestArguments, ILaunchArgs {
46cwd: string; /* Automatically set by VS Code to the currently opened folder */
47port: number;
48url?: string;
49address?: string;
50trace?: string;
5d47053fRedMickey6 years ago51skipFiles?: [];
1bdccb66RedMickey6 years ago52sourceMaps?: boolean;
53sourceMapPathOverrides?: { [key: string]: string };
2c19da7fRedMickey6 years ago54}
55
56export interface ILaunchRequestArgs extends DebugProtocol.LaunchRequestArguments, IAttachRequestArgs { }
57
58export abstract class DebugSessionBase extends LoggingDebugSession {
59
ebbd64f1RedMickey6 years ago60protected static rootSessionTerminatedEventEmitter: vscode.EventEmitter<TerminateEventArgs> = new vscode.EventEmitter<TerminateEventArgs>();
61public static readonly onDidTerminateRootDebugSession = DebugSessionBase.rootSessionTerminatedEventEmitter.event;
62
63protected readonly disconnectCommand: string;
64protected readonly pwaNodeSessionName: string;
65
2c19da7fRedMickey6 years ago66protected appLauncher: AppLauncher;
67protected projectRootPath: string;
68protected isSettingsInitialized: boolean; // used to prevent parameters reinitialization when attach is called from launch function
69protected previousAttachArgs: IAttachRequestArgs;
70protected cdpProxyLogLevel: LogLevel;
71protected debugSessionStatus: DebugSessionStatus;
72protected session: vscode.DebugSession;
e23d1841RedMickey6 years ago73protected cancellationTokenSource: vscode.CancellationTokenSource;
2c19da7fRedMickey6 years ago74
75constructor(session: vscode.DebugSession) {
76super();
77
ebbd64f1RedMickey6 years ago78// constants definition
79this.pwaNodeSessionName = "pwa-node"; // the name of node debug session created by js-debug extension
80this.disconnectCommand = "disconnect";
81
82// variables definition
2c19da7fRedMickey6 years ago83this.session = session;
84this.isSettingsInitialized = false;
85this.debugSessionStatus = DebugSessionStatus.FirstConnection;
e23d1841RedMickey6 years ago86this.cancellationTokenSource = new vscode.CancellationTokenSource();
87}
88
89protected initializeRequest(response: DebugProtocol.InitializeResponse, args: DebugProtocol.InitializeRequestArguments): void {
90response.body = response.body || {};
91
92response.body.supportsConfigurationDoneRequest = true;
93response.body.supportsEvaluateForHovers = true;
94response.body.supportTerminateDebuggee = true;
95response.body.supportsCancelRequest = true;
96
97this.sendResponse(response);
2c19da7fRedMickey6 years ago98}
99
5d47053fRedMickey6 years ago100protected abstract establishDebugSession(attachArgs: IAttachRequestArgs, resolve?: (value?: void | PromiseLike<void> | undefined) => void): void;
b7451aefRedMickey6 years ago101
ce5e88eeYuri Skorokhodov5 years ago102protected initializeSettings(args: any): Promise<any> {
2c19da7fRedMickey6 years ago103if (!this.isSettingsInitialized) {
104let chromeDebugCoreLogs = getLoggingDirectory();
105if (chromeDebugCoreLogs) {
106chromeDebugCoreLogs = path.join(chromeDebugCoreLogs, "DebugSessionLogs.txt");
107}
108let logLevel: string = args.trace;
109if (logLevel) {
110logLevel = logLevel.replace(logLevel[0], logLevel[0].toUpperCase());
111logger.setup(Logger.LogLevel[logLevel], chromeDebugCoreLogs || false);
112this.cdpProxyLogLevel = LogLevel[logLevel] === LogLevel.Verbose ? LogLevel.Custom : LogLevel.None;
113} else {
114logger.setup(Logger.LogLevel.Log, chromeDebugCoreLogs || false);
115this.cdpProxyLogLevel = LogHelper.LOG_LEVEL === LogLevel.Trace ? LogLevel.Custom : LogLevel.None;
116}
117
118if (!args.sourceMaps) {
119args.sourceMaps = true;
120}
121
5514e287RedMickey6 years ago122if (typeof args.enableDebug !== "boolean") {
123args.enableDebug = true;
124}
125
2c19da7fRedMickey6 years ago126const projectRootPath = getProjectRoot(args);
127return ReactNativeProjectHelper.isReactNativeProject(projectRootPath)
128.then((result) => {
129if (!result) {
130throw ErrorHelper.getInternalError(InternalErrorCode.NotInReactNativeFolderError);
131}
132this.projectRootPath = projectRootPath;
133this.appLauncher = AppLauncher.getAppLauncherByProjectRootPath(projectRootPath);
134this.isSettingsInitialized = true;
135
136return void 0;
137});
138} else {
ce5e88eeYuri Skorokhodov5 years ago139return Promise.resolve();
2c19da7fRedMickey6 years ago140}
141}
984ca036RedMickey6 years ago142
e23d1841RedMickey6 years ago143protected async disconnectRequest(response: DebugProtocol.DisconnectResponse, args: DebugProtocol.DisconnectArguments, request?: DebugProtocol.Request): Promise<void> {
144await this.appLauncher.getRnCdpProxy().stopServer();
145
146this.cancellationTokenSource.cancel();
147this.cancellationTokenSource.dispose();
148
149// Then we tell the extension to stop monitoring the logcat, and then we disconnect the debugging session
6213678cYuri Skorokhodov6 years ago150if (this.previousAttachArgs && this.previousAttachArgs.platform === "android") {
e23d1841RedMickey6 years ago151try {
152this.appLauncher.stopMonitoringLogCat();
153} catch (err) {
154logger.warn(localize("CouldNotStopMonitoringLogcat", "Couldn't stop monitoring logcat: {0}", err.message || err));
155}
156}
157
67ffa5b4RedMickey6 years ago158await logger.dispose();
159
ebbd64f1RedMickey6 years ago160DebugSessionBase.rootSessionTerminatedEventEmitter.fire({
161debugSession: this.session,
162args: {
163forcedStop: (<any>args).forcedStop,
164},
165});
166
167this.sendResponse(response);
e23d1841RedMickey6 years ago168}
169
170protected showError(error: Error, response: DebugProtocol.Response): void {
171
172// We can't print error messages after the debugging session is stopped. This could break the extension work.
173if ((error instanceof InternalError || error instanceof NestedError)
174&& error.errorCode === InternalErrorCode.CancellationTokenTriggered
175) {
176return;
177}
178
984ca036RedMickey6 years ago179this.sendErrorResponse(
180response,
e23d1841RedMickey6 years ago181{ format: error.message, id: 1 },
984ca036RedMickey6 years ago182undefined,
183undefined,
184ErrorDestination.User
185);
186}
2c19da7fRedMickey6 years ago187}
188
189/**
190* Parses settings.json file for workspace root property
191*/
192export function getProjectRoot(args: any): string {
193const vsCodeRoot = args.cwd ? path.resolve(args.cwd) : path.resolve(args.program, "../..");
194const settingsPath = path.resolve(vsCodeRoot, ".vscode/settings.json");
195try {
196let settingsContent = fs.readFileSync(settingsPath, "utf8");
197settingsContent = stripJsonComments(settingsContent);
198let parsedSettings = JSON.parse(settingsContent);
199let projectRootPath = parsedSettings["react-native-tools.projectRoot"] || parsedSettings["react-native-tools"].projectRoot;
200return path.resolve(vsCodeRoot, projectRootPath);
201} catch (e) {
202logger.verbose(`${settingsPath} file doesn't exist or its content is incorrect. This file will be ignored.`);
203return args.cwd ? path.resolve(args.cwd) : path.resolve(args.program, "../..");
204}
205}