Path: blob/main/extensions/copilot/test/simulation/fixtures/multiFileEdit/issue-8098/debugUtils.ts
13405 views
/*---------------------------------------------------------------------------------------------1* Copyright (c) Microsoft Corporation. All rights reserved.2* Licensed under the MIT License. See License.txt in the project root for license information.3*--------------------------------------------------------------------------------------------*/45import { equalsIgnoreCase } from '../../../../base/common/strings.js';6import { IDebuggerContribution, IDebugSession, IConfigPresentation } from './debug.js';7import { URI as uri } from '../../../../base/common/uri.js';8import { isAbsolute } from '../../../../base/common/path.js';9import { deepClone } from '../../../../base/common/objects.js';10import { Schemas } from '../../../../base/common/network.js';11import { IEditorService } from '../../../services/editor/common/editorService.js';12import { IConfigurationService } from '../../../../platform/configuration/common/configuration.js';13import { ITextModel } from '../../../../editor/common/model.js';14import { Position } from '../../../../editor/common/core/position.js';15import { IRange, Range } from '../../../../editor/common/core/range.js';16import { CancellationToken } from '../../../../base/common/cancellation.js';17import { coalesce } from '../../../../base/common/arrays.js';18import { ILanguageFeaturesService } from '../../../../editor/common/services/languageFeatures.js';1920const _formatPIIRegexp = /{([^}]+)}/g;2122export function formatPII(value: string, excludePII: boolean, args: { [key: string]: string } | undefined): string {23return value.replace(_formatPIIRegexp, function (match, group) {24if (excludePII && group.length > 0 && group[0] !== '_') {25return match;26}2728return args && args.hasOwnProperty(group) ?29args[group] :30match;31});32}3334/**35* Filters exceptions (keys marked with "!") from the given object. Used to36* ensure exception data is not sent on web remotes, see #97628.37*/38export function filterExceptionsFromTelemetry<T extends { [key: string]: unknown }>(data: T): Partial<T> {39const output: Partial<T> = {};40for (const key of Object.keys(data) as (keyof T & string)[]) {41if (!key.startsWith('!')) {42output[key] = data[key];43}44}4546return output;47}484950export function isSessionAttach(session: IDebugSession): boolean {51return session.configuration.request === 'attach' && !getExtensionHostDebugSession(session) && (!session.parentSession || isSessionAttach(session.parentSession));52}5354/**55* Returns the session or any parent which is an extension host debug session.56* Returns undefined if there's none.57*/58export function getExtensionHostDebugSession(session: IDebugSession): IDebugSession | void {59let type = session.configuration.type;60if (!type) {61return;62}6364if (type === 'vslsShare') {65type = (<any>session.configuration).adapterProxy.configuration.type;66}6768if (equalsIgnoreCase(type, 'extensionhost') || equalsIgnoreCase(type, 'pwa-extensionhost')) {69return session;70}7172return session.parentSession ? getExtensionHostDebugSession(session.parentSession) : undefined;73}7475// only a debugger contributions with a label, program, or runtime attribute is considered a "defining" or "main" debugger contribution76export function isDebuggerMainContribution(dbg: IDebuggerContribution) {77return dbg.type && (dbg.label || dbg.program || dbg.runtime);78}7980export function getExactExpressionStartAndEnd(lineContent: string, looseStart: number, looseEnd: number): { start: number; end: number } {81let matchingExpression: string | undefined = undefined;82let startOffset = 0;8384// Some example supported expressions: myVar.prop, a.b.c.d, myVar?.prop, myVar->prop, MyClass::StaticProp, *myVar85// Match any character except a set of characters which often break interesting sub-expressions86const expression: RegExp = /([^()\[\]{}<>\s+\-/%~#^;=|,`!]|\->)+/g;87let result: RegExpExecArray | null = null;8889// First find the full expression under the cursor90while (result = expression.exec(lineContent)) {91const start = result.index + 1;92const end = start + result[0].length;9394if (start <= looseStart && end >= looseEnd) {95matchingExpression = result[0];96startOffset = start;97break;98}99}100101// If there are non-word characters after the cursor, we want to truncate the expression then.102// For example in expression 'a.b.c.d', if the focus was under 'b', 'a.b' would be evaluated.103if (matchingExpression) {104const subExpression: RegExp = /(\w|\p{L})+/gu;105let subExpressionResult: RegExpExecArray | null = null;106while (subExpressionResult = subExpression.exec(matchingExpression)) {107const subEnd = subExpressionResult.index + 1 + startOffset + subExpressionResult[0].length;108if (subEnd >= looseEnd) {109break;110}111}112113if (subExpressionResult) {114matchingExpression = matchingExpression.substring(0, subExpression.lastIndex);115}116}117118return matchingExpression ?119{ start: startOffset, end: startOffset + matchingExpression.length - 1 } :120{ start: 0, end: 0 };121}122123export async function getEvaluatableExpressionAtPosition(languageFeaturesService: ILanguageFeaturesService, model: ITextModel, position: Position, token?: CancellationToken): Promise<{ range: IRange; matchingExpression: string } | null> {124if (languageFeaturesService.evaluatableExpressionProvider.has(model)) {125const supports = languageFeaturesService.evaluatableExpressionProvider.ordered(model);126127const results = coalesce(await Promise.all(supports.map(async support => {128try {129return await support.provideEvaluatableExpression(model, position, token ?? CancellationToken.None);130} catch (err) {131return undefined;132}133})));134135if (results.length > 0) {136let matchingExpression = results[0].expression;137const range = results[0].range;138139if (!matchingExpression) {140const lineContent = model.getLineContent(position.lineNumber);141matchingExpression = lineContent.substring(range.startColumn - 1, range.endColumn - 1);142}143144return { range, matchingExpression };145}146} else { // old one-size-fits-all strategy147const lineContent = model.getLineContent(position.lineNumber);148const { start, end } = getExactExpressionStartAndEnd(lineContent, position.column, position.column);149150// use regex to extract the sub-expression #9821151const matchingExpression = lineContent.substring(start - 1, end);152return {153matchingExpression,154range: new Range(position.lineNumber, start, position.lineNumber, start + matchingExpression.length)155};156}157158return null;159}160161// RFC 2396, Appendix A: https://www.ietf.org/rfc/rfc2396.txt162const _schemePattern = /^[a-zA-Z][a-zA-Z0-9\+\-\.]+:/;163164export function isUri(s: string | undefined): boolean {165// heuristics: a valid uri starts with a scheme and166// the scheme has at least 2 characters so that it doesn't look like a drive letter.167return !!(s && s.match(_schemePattern));168}169170function stringToUri(source: PathContainer): string | undefined {171if (typeof source.path === 'string') {172if (typeof source.sourceReference === 'number' && source.sourceReference > 0) {173// if there is a source reference, don't touch path174} else {175if (isUri(source.path)) {176return <string><unknown>uri.parse(source.path);177} else {178// assume path179if (isAbsolute(source.path)) {180return <string><unknown>uri.file(source.path);181} else {182// leave relative path as is183}184}185}186}187return source.path;188}189190function uriToString(source: PathContainer): string | undefined {191if (typeof source.path === 'object') {192const u = uri.revive(source.path);193if (u) {194if (u.scheme === Schemas.file) {195return u.fsPath;196} else {197return u.toString();198}199}200}201return source.path;202}203204// path hooks helpers205206interface PathContainer {207path?: string;208sourceReference?: number;209}210211export function convertToDAPaths(message: DebugProtocol.ProtocolMessage, toUri: boolean): DebugProtocol.ProtocolMessage {212213const fixPath = toUri ? stringToUri : uriToString;214215// since we modify Source.paths in the message in place, we need to make a copy of it (see #61129)216const msg = deepClone(message);217218convertPaths(msg, (toDA: boolean, source: PathContainer | undefined) => {219if (toDA && source) {220source.path = fixPath(source);221}222});223return msg;224}225226export function convertToVSCPaths(message: DebugProtocol.ProtocolMessage, toUri: boolean): DebugProtocol.ProtocolMessage {227228const fixPath = toUri ? stringToUri : uriToString;229230// since we modify Source.paths in the message in place, we need to make a copy of it (see #61129)231const msg = deepClone(message);232233convertPaths(msg, (toDA: boolean, source: PathContainer | undefined) => {234if (!toDA && source) {235source.path = fixPath(source);236}237});238return msg;239}240241function convertPaths(msg: DebugProtocol.ProtocolMessage, fixSourcePath: (toDA: boolean, source: PathContainer | undefined) => void): void {242243switch (msg.type) {244case 'event': {245const event = <DebugProtocol.Event>msg;246switch (event.event) {247case 'output':248fixSourcePath(false, (<DebugProtocol.OutputEvent>event).body.source);249break;250case 'loadedSource':251fixSourcePath(false, (<DebugProtocol.LoadedSourceEvent>event).body.source);252break;253case 'breakpoint':254fixSourcePath(false, (<DebugProtocol.BreakpointEvent>event).body.breakpoint.source);255break;256default:257break;258}259break;260}261case 'request': {262const request = <DebugProtocol.Request>msg;263switch (request.command) {264case 'setBreakpoints':265fixSourcePath(true, (<DebugProtocol.SetBreakpointsArguments>request.arguments).source);266break;267case 'breakpointLocations':268fixSourcePath(true, (<DebugProtocol.BreakpointLocationsArguments>request.arguments).source);269break;270case 'source':271fixSourcePath(true, (<DebugProtocol.SourceArguments>request.arguments).source);272break;273case 'gotoTargets':274fixSourcePath(true, (<DebugProtocol.GotoTargetsArguments>request.arguments).source);275break;276case 'launchVSCode':277request.arguments.args.forEach((arg: PathContainer | undefined) => fixSourcePath(false, arg));278break;279default:280break;281}282break;283}284case 'response': {285const response = <DebugProtocol.Response>msg;286if (response.success && response.body) {287switch (response.command) {288case 'stackTrace':289(<DebugProtocol.StackTraceResponse>response).body.stackFrames.forEach(frame => fixSourcePath(false, frame.source));290break;291case 'loadedSources':292(<DebugProtocol.LoadedSourcesResponse>response).body.sources.forEach(source => fixSourcePath(false, source));293break;294case 'scopes':295(<DebugProtocol.ScopesResponse>response).body.scopes.forEach(scope => fixSourcePath(false, scope.source));296break;297case 'setFunctionBreakpoints':298(<DebugProtocol.SetFunctionBreakpointsResponse>response).body.breakpoints.forEach(bp => fixSourcePath(false, bp.source));299break;300case 'setBreakpoints':301(<DebugProtocol.SetBreakpointsResponse>response).body.breakpoints.forEach(bp => fixSourcePath(false, bp.source));302break;303case 'disassemble':304{305const di = <DebugProtocol.DisassembleResponse>response;306di.body?.instructions.forEach(di => fixSourcePath(false, di.location));307}308break;309case 'locations':310fixSourcePath(false, (<DebugProtocol.LocationsResponse>response).body?.source);311break;312default:313break;314}315}316break;317}318}319}320321export function getVisibleAndSorted<T extends { presentation?: IConfigPresentation }>(array: T[]): T[] {322return array.filter(config => !config.presentation?.hidden).sort((first, second) => {323if (!first.presentation) {324if (!second.presentation) {325return 0;326}327return 1;328}329if (!second.presentation) {330return -1;331}332if (!first.presentation.group) {333if (!second.presentation.group) {334return compareOrders(first.presentation.order, second.presentation.order);335}336return 1;337}338if (!second.presentation.group) {339return -1;340}341if (first.presentation.group !== second.presentation.group) {342return first.presentation.group.localeCompare(second.presentation.group);343}344345return compareOrders(first.presentation.order, second.presentation.order);346});347}348349function compareOrders(first: number | undefined, second: number | undefined): number {350if (typeof first !== 'number') {351if (typeof second !== 'number') {352return 0;353}354355return 1;356}357if (typeof second !== 'number') {358return -1;359}360361return first - second;362}363364export async function saveAllBeforeDebugStart(configurationService: IConfigurationService, editorService: IEditorService): Promise<void> {365const saveBeforeStartConfig: string = configurationService.getValue('debug.saveBeforeStart', { overrideIdentifier: editorService.activeTextEditorLanguageId });366if (saveBeforeStartConfig !== 'none') {367await editorService.saveAll();368if (saveBeforeStartConfig === 'allEditorsInActiveGroup') {369const activeEditor = editorService.activeEditorPane;370if (activeEditor && activeEditor.input.resource?.scheme === Schemas.untitled) {371// Make sure to save the active editor in case it is in untitled file it wont be saved as part of saveAll #111850372await editorService.save({ editor: activeEditor.input, groupId: activeEditor.group.id });373}374}375}376await configurationService.reloadConfiguration();377}378379export const sourcesEqual = (a: DebugProtocol.Source | undefined, b: DebugProtocol.Source | undefined): boolean =>380!a || !b ? a === b : a.name === b.name && a.path === b.path && a.sourceReference === b.sourceReference;381382383