microsoft/vscode-react-native

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
17bf2e6423d9b2b85ca346a4f0116dfe25b16cff

Branches

Tags

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

Clone

HTTPS

Download ZIP

src/debugger/debugSessionBase.ts

197lines · 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 Q from "q";
6import * as path from "path";
7import * as fs from "fs";
8import stripJsonComments = require("strip-json-comments");
984ca036RedMickey6 years ago9import { LoggingDebugSession, Logger, logger, ErrorDestination } from "vscode-debugadapter";
2c19da7fRedMickey6 years ago10import { 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";
e23d1841RedMickey6 years ago15import { InternalError, NestedError } from "../common/error/internalError";
2c19da7fRedMickey6 years ago16import { ILaunchArgs } from "../extension/launchArgs";
17import { AppLauncher } from "../extension/appLauncher";
18import { LogLevel } from "../extension/log/LogHelper";
e23d1841RedMickey6 years ago19import * as nls from "vscode-nls";
20const 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?: [];
2c19da7fRedMickey6 years ago52}
53
54export interface ILaunchRequestArgs extends DebugProtocol.LaunchRequestArguments, IAttachRequestArgs { }
55
56export abstract class DebugSessionBase extends LoggingDebugSession {
57
ebbd64f1RedMickey6 years ago58protected static rootSessionTerminatedEventEmitter: vscode.EventEmitter<TerminateEventArgs> = new vscode.EventEmitter<TerminateEventArgs>();
59public static readonly onDidTerminateRootDebugSession = DebugSessionBase.rootSessionTerminatedEventEmitter.event;
60
61protected readonly disconnectCommand: string;
62protected readonly pwaNodeSessionName: string;
63
2c19da7fRedMickey6 years ago64protected appLauncher: AppLauncher;
65protected projectRootPath: string;
66protected isSettingsInitialized: boolean; // used to prevent parameters reinitialization when attach is called from launch function
67protected previousAttachArgs: IAttachRequestArgs;
68protected cdpProxyLogLevel: LogLevel;
69protected debugSessionStatus: DebugSessionStatus;
70protected session: vscode.DebugSession;
e23d1841RedMickey6 years ago71protected cancellationTokenSource: vscode.CancellationTokenSource;
2c19da7fRedMickey6 years ago72
73constructor(session: vscode.DebugSession) {
74super();
75
ebbd64f1RedMickey6 years ago76// constants definition
77this.pwaNodeSessionName = "pwa-node"; // the name of node debug session created by js-debug extension
78this.disconnectCommand = "disconnect";
79
80// variables definition
2c19da7fRedMickey6 years ago81this.session = session;
82this.isSettingsInitialized = false;
83this.debugSessionStatus = DebugSessionStatus.FirstConnection;
e23d1841RedMickey6 years ago84this.cancellationTokenSource = new vscode.CancellationTokenSource();
85}
86
87protected initializeRequest(response: DebugProtocol.InitializeResponse, args: DebugProtocol.InitializeRequestArguments): void {
88response.body = response.body || {};
89
90response.body.supportsConfigurationDoneRequest = true;
91response.body.supportsEvaluateForHovers = true;
92response.body.supportTerminateDebuggee = true;
93response.body.supportsCancelRequest = true;
94
95this.sendResponse(response);
2c19da7fRedMickey6 years ago96}
97
5d47053fRedMickey6 years ago98protected abstract establishDebugSession(attachArgs: IAttachRequestArgs, resolve?: (value?: void | PromiseLike<void> | undefined) => void): void;
b7451aefRedMickey6 years ago99
2c19da7fRedMickey6 years ago100protected initializeSettings(args: any): Q.Promise<any> {
101if (!this.isSettingsInitialized) {
102let chromeDebugCoreLogs = getLoggingDirectory();
103if (chromeDebugCoreLogs) {
104chromeDebugCoreLogs = path.join(chromeDebugCoreLogs, "DebugSessionLogs.txt");
105}
106let logLevel: string = args.trace;
107if (logLevel) {
108logLevel = logLevel.replace(logLevel[0], logLevel[0].toUpperCase());
109logger.setup(Logger.LogLevel[logLevel], chromeDebugCoreLogs || false);
110this.cdpProxyLogLevel = LogLevel[logLevel] === LogLevel.Verbose ? LogLevel.Custom : LogLevel.None;
111} else {
112logger.setup(Logger.LogLevel.Log, chromeDebugCoreLogs || false);
113this.cdpProxyLogLevel = LogHelper.LOG_LEVEL === LogLevel.Trace ? LogLevel.Custom : LogLevel.None;
114}
115
116if (!args.sourceMaps) {
117args.sourceMaps = true;
118}
119
120const projectRootPath = getProjectRoot(args);
121return ReactNativeProjectHelper.isReactNativeProject(projectRootPath)
122.then((result) => {
123if (!result) {
124throw ErrorHelper.getInternalError(InternalErrorCode.NotInReactNativeFolderError);
125}
126this.projectRootPath = projectRootPath;
127this.appLauncher = AppLauncher.getAppLauncherByProjectRootPath(projectRootPath);
128this.isSettingsInitialized = true;
129
130return void 0;
131});
132} else {
133return Q.resolve<void>(void 0);
134}
135}
984ca036RedMickey6 years ago136
e23d1841RedMickey6 years ago137protected async disconnectRequest(response: DebugProtocol.DisconnectResponse, args: DebugProtocol.DisconnectArguments, request?: DebugProtocol.Request): Promise<void> {
138await this.appLauncher.getRnCdpProxy().stopServer();
139
140this.cancellationTokenSource.cancel();
141this.cancellationTokenSource.dispose();
142
143// Then we tell the extension to stop monitoring the logcat, and then we disconnect the debugging session
6213678cYuri Skorokhodov6 years ago144if (this.previousAttachArgs && this.previousAttachArgs.platform === "android") {
e23d1841RedMickey6 years ago145try {
146this.appLauncher.stopMonitoringLogCat();
147} catch (err) {
148logger.warn(localize("CouldNotStopMonitoringLogcat", "Couldn't stop monitoring logcat: {0}", err.message || err));
149}
150}
151
ebbd64f1RedMickey6 years ago152DebugSessionBase.rootSessionTerminatedEventEmitter.fire({
153debugSession: this.session,
154args: {
155forcedStop: (<any>args).forcedStop,
156},
157});
158
159this.sendResponse(response);
e23d1841RedMickey6 years ago160}
161
162protected 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.
165if ((error instanceof InternalError || error instanceof NestedError)
166&& error.errorCode === InternalErrorCode.CancellationTokenTriggered
167) {
168return;
169}
170
984ca036RedMickey6 years ago171this.sendErrorResponse(
172response,
e23d1841RedMickey6 years ago173{ format: error.message, id: 1 },
984ca036RedMickey6 years ago174undefined,
175undefined,
176ErrorDestination.User
177);
178}
2c19da7fRedMickey6 years ago179}
180
181/**
182* Parses settings.json file for workspace root property
183*/
184export function getProjectRoot(args: any): string {
185const vsCodeRoot = args.cwd ? path.resolve(args.cwd) : path.resolve(args.program, "../..");
186const settingsPath = path.resolve(vsCodeRoot, ".vscode/settings.json");
187try {
188let settingsContent = fs.readFileSync(settingsPath, "utf8");
189settingsContent = stripJsonComments(settingsContent);
190let parsedSettings = JSON.parse(settingsContent);
191let projectRootPath = parsedSettings["react-native-tools.projectRoot"] || parsedSettings["react-native-tools"].projectRoot;
192return path.resolve(vsCodeRoot, projectRootPath);
193} catch (e) {
194logger.verbose(`${settingsPath} file doesn't exist or its content is incorrect. This file will be ignored.`);
195return args.cwd ? path.resolve(args.cwd) : path.resolve(args.program, "../..");
196}
197}