hunk
dict
file
stringlengths
0
11.8M
file_path
stringlengths
2
234
label
int64
0
1
commit_url
stringlengths
74
103
dependency_score
sequencelengths
5
5
{ "id": 2, "code_window": [ "\t\t\trange: columnUntilEOLRange\n", "\t\t});\n", "\n", "\t\tif (topStackFrameRange && topStackFrameRange.startLineNumber === stackFrame.range.startLineNumber && topStackFrameRange.startColumn !== stackFrame.range.startColumn) {\n", "\t\t\tresult.push({\n", "\t\t\t\toptions: TOP_STACK_FRAME_INLINE_DECORATION,\n", "\t\t\t\trange: columnUntilEOLRange\n", "\t\t\t});\n", "\t\t}\n", "\t\ttopStackFrameRange = columnUntilEOLRange;\n", "\t} else {\n", "\t\tif (isFocusedSession) {\n", "\t\t\tresult.push({\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tresult.push({\n", "\t\t\toptions: TOP_STACK_FRAME_INLINE_DECORATION,\n", "\t\t\trange: columnUntilEOLRange\n", "\t\t});\n" ], "file_path": "src/vs/workbench/contrib/debug/browser/callStackEditorContribution.ts", "type": "replace", "edit_start_line_idx": 77 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ //@ts-check 'use strict'; const withDefaults = require('../shared.webpack.config'); module.exports = withDefaults({ context: __dirname, entry: { main: './src/main.ts', }, resolve: { mainFields: ['module', 'main'] } });
extensions/jake/extension.webpack.config.js
0
https://github.com/microsoft/vscode/commit/f554a745505474ba031a79f5ab4a5c9d1ed3af39
[ 0.00017335228039883077, 0.00017165369354188442, 0.00016948490520007908, 0.00017212390957865864, 0.0000016134789575517061 ]
{ "id": 2, "code_window": [ "\t\t\trange: columnUntilEOLRange\n", "\t\t});\n", "\n", "\t\tif (topStackFrameRange && topStackFrameRange.startLineNumber === stackFrame.range.startLineNumber && topStackFrameRange.startColumn !== stackFrame.range.startColumn) {\n", "\t\t\tresult.push({\n", "\t\t\t\toptions: TOP_STACK_FRAME_INLINE_DECORATION,\n", "\t\t\t\trange: columnUntilEOLRange\n", "\t\t\t});\n", "\t\t}\n", "\t\ttopStackFrameRange = columnUntilEOLRange;\n", "\t} else {\n", "\t\tif (isFocusedSession) {\n", "\t\t\tresult.push({\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tresult.push({\n", "\t\t\toptions: TOP_STACK_FRAME_INLINE_DECORATION,\n", "\t\t\trange: columnUntilEOLRange\n", "\t\t});\n" ], "file_path": "src/vs/workbench/contrib/debug/browser/callStackEditorContribution.ts", "type": "replace", "edit_start_line_idx": 77 }
{ "displayName": "Handlebars Language Basics", "description": "Provides syntax highlighting and bracket matching in Handlebars files." }
extensions/handlebars/package.nls.json
0
https://github.com/microsoft/vscode/commit/f554a745505474ba031a79f5ab4a5c9d1ed3af39
[ 0.0001703226298559457, 0.0001703226298559457, 0.0001703226298559457, 0.0001703226298559457, 0 ]
{ "id": 3, "code_window": [ "\n", "export class CallStackEditorContribution implements IEditorContribution {\n", "\tprivate toDispose: IDisposable[] = [];\n", "\tprivate decorationIds: string[] = [];\n", "\tprivate topStackFrameRange: Range | undefined;\n", "\n", "\tconstructor(\n", "\t\tprivate readonly editor: ICodeEditor,\n", "\t\t@IDebugService private readonly debugService: IDebugService,\n", "\t\t@IUriIdentityService private readonly uriIdentityService: IUriIdentityService\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/debug/browser/callStackEditorContribution.ts", "type": "replace", "edit_start_line_idx": 104 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as assert from 'assert'; import { DebugModel, StackFrame, Thread } from 'vs/workbench/contrib/debug/common/debugModel'; import * as sinon from 'sinon'; import { MockRawSession, createMockDebugModel, mockUriIdentityService } from 'vs/workbench/contrib/debug/test/browser/mockDebug'; import { Source } from 'vs/workbench/contrib/debug/common/debugSource'; import { DebugSession } from 'vs/workbench/contrib/debug/browser/debugSession'; import { Range } from 'vs/editor/common/core/range'; import { IDebugSessionOptions, State, IDebugService } from 'vs/workbench/contrib/debug/common/debug'; import { NullOpenerService } from 'vs/platform/opener/common/opener'; import { createDecorationsForStackFrame } from 'vs/workbench/contrib/debug/browser/callStackEditorContribution'; import { Constants } from 'vs/base/common/uint'; import { getContext, getContextForContributedActions, getSpecificSourceName } from 'vs/workbench/contrib/debug/browser/callStackView'; import { getStackFrameThreadAndSessionToFocus } from 'vs/workbench/contrib/debug/browser/debugService'; import { generateUuid } from 'vs/base/common/uuid'; import { debugStackframe, debugStackframeFocused } from 'vs/workbench/contrib/debug/browser/debugIcons'; import { ThemeIcon } from 'vs/platform/theme/common/themeService'; import { TestConfigurationService } from 'vs/platform/configuration/test/common/testConfigurationService'; const mockWorkspaceContextService = { getWorkspace: () => { return { folders: [] }; } } as any; export function createMockSession(model: DebugModel, name = 'mockSession', options?: IDebugSessionOptions): DebugSession { return new DebugSession(generateUuid(), { resolved: { name, type: 'node', request: 'launch' }, unresolved: undefined }, undefined!, model, options, { getViewModel(): any { return { updateViews(): void { // noop } }; } } as IDebugService, undefined!, undefined!, new TestConfigurationService({ debug: { console: { collapseIdenticalLines: true } } }), undefined!, mockWorkspaceContextService, undefined!, undefined!, NullOpenerService, undefined!, undefined!, mockUriIdentityService, undefined!); } function createTwoStackFrames(session: DebugSession): { firstStackFrame: StackFrame, secondStackFrame: StackFrame } { let firstStackFrame: StackFrame; let secondStackFrame: StackFrame; const thread = new class extends Thread { public getCallStack(): StackFrame[] { return [firstStackFrame, secondStackFrame]; } }(session, 'mockthread', 1); const firstSource = new Source({ name: 'internalModule.js', path: 'a/b/c/d/internalModule.js', sourceReference: 10, }, 'aDebugSessionId', mockUriIdentityService); const secondSource = new Source({ name: 'internalModule.js', path: 'z/x/c/d/internalModule.js', sourceReference: 11, }, 'aDebugSessionId', mockUriIdentityService); firstStackFrame = new StackFrame(thread, 0, firstSource, 'app.js', 'normal', { startLineNumber: 1, startColumn: 1, endLineNumber: 1, endColumn: 10 }, 0, true); secondStackFrame = new StackFrame(thread, 1, secondSource, 'app2.js', 'normal', { startLineNumber: 1, startColumn: 1, endLineNumber: 1, endColumn: 10 }, 1, true); return { firstStackFrame, secondStackFrame }; } suite('Debug - CallStack', () => { let model: DebugModel; let rawSession: MockRawSession; setup(() => { model = createMockDebugModel(); rawSession = new MockRawSession(); }); // Threads test('threads simple', () => { const threadId = 1; const threadName = 'firstThread'; const session = createMockSession(model); model.addSession(session); assert.strictEqual(model.getSessions(true).length, 1); model.rawUpdate({ sessionId: session.getId(), threads: [{ id: threadId, name: threadName }] }); assert.strictEqual(session.getThread(threadId)!.name, threadName); model.clearThreads(session.getId(), true); assert.strictEqual(session.getThread(threadId), undefined); assert.strictEqual(model.getSessions(true).length, 1); }); test('threads multiple wtih allThreadsStopped', async () => { const threadId1 = 1; const threadName1 = 'firstThread'; const threadId2 = 2; const threadName2 = 'secondThread'; const stoppedReason = 'breakpoint'; // Add the threads const session = createMockSession(model); model.addSession(session); session['raw'] = <any>rawSession; model.rawUpdate({ sessionId: session.getId(), threads: [{ id: threadId1, name: threadName1 }] }); // Stopped event with all threads stopped model.rawUpdate({ sessionId: session.getId(), threads: [{ id: threadId1, name: threadName1 }, { id: threadId2, name: threadName2 }], stoppedDetails: { reason: stoppedReason, threadId: 1, allThreadsStopped: true }, }); const thread1 = session.getThread(threadId1)!; const thread2 = session.getThread(threadId2)!; // at the beginning, callstacks are obtainable but not available assert.strictEqual(session.getAllThreads().length, 2); assert.strictEqual(thread1.name, threadName1); assert.strictEqual(thread1.stopped, true); assert.strictEqual(thread1.getCallStack().length, 0); assert.strictEqual(thread1.stoppedDetails!.reason, stoppedReason); assert.strictEqual(thread2.name, threadName2); assert.strictEqual(thread2.stopped, true); assert.strictEqual(thread2.getCallStack().length, 0); assert.strictEqual(thread2.stoppedDetails!.reason, undefined); // after calling getCallStack, the callstack becomes available // and results in a request for the callstack in the debug adapter await thread1.fetchCallStack(); assert.notStrictEqual(thread1.getCallStack().length, 0); await thread2.fetchCallStack(); assert.notStrictEqual(thread2.getCallStack().length, 0); // calling multiple times getCallStack doesn't result in multiple calls // to the debug adapter await thread1.fetchCallStack(); await thread2.fetchCallStack(); // clearing the callstack results in the callstack not being available thread1.clearCallStack(); assert.strictEqual(thread1.stopped, true); assert.strictEqual(thread1.getCallStack().length, 0); thread2.clearCallStack(); assert.strictEqual(thread2.stopped, true); assert.strictEqual(thread2.getCallStack().length, 0); model.clearThreads(session.getId(), true); assert.strictEqual(session.getThread(threadId1), undefined); assert.strictEqual(session.getThread(threadId2), undefined); assert.strictEqual(session.getAllThreads().length, 0); }); test('threads mutltiple without allThreadsStopped', async () => { const sessionStub = sinon.spy(rawSession, 'stackTrace'); const stoppedThreadId = 1; const stoppedThreadName = 'stoppedThread'; const runningThreadId = 2; const runningThreadName = 'runningThread'; const stoppedReason = 'breakpoint'; const session = createMockSession(model); model.addSession(session); session['raw'] = <any>rawSession; // Add the threads model.rawUpdate({ sessionId: session.getId(), threads: [{ id: stoppedThreadId, name: stoppedThreadName }] }); // Stopped event with only one thread stopped model.rawUpdate({ sessionId: session.getId(), threads: [{ id: 1, name: stoppedThreadName }, { id: runningThreadId, name: runningThreadName }], stoppedDetails: { reason: stoppedReason, threadId: 1, allThreadsStopped: false } }); const stoppedThread = session.getThread(stoppedThreadId)!; const runningThread = session.getThread(runningThreadId)!; // the callstack for the stopped thread is obtainable but not available // the callstack for the running thread is not obtainable nor available assert.strictEqual(stoppedThread.name, stoppedThreadName); assert.strictEqual(stoppedThread.stopped, true); assert.strictEqual(session.getAllThreads().length, 2); assert.strictEqual(stoppedThread.getCallStack().length, 0); assert.strictEqual(stoppedThread.stoppedDetails!.reason, stoppedReason); assert.strictEqual(runningThread.name, runningThreadName); assert.strictEqual(runningThread.stopped, false); assert.strictEqual(runningThread.getCallStack().length, 0); assert.strictEqual(runningThread.stoppedDetails, undefined); // after calling getCallStack, the callstack becomes available // and results in a request for the callstack in the debug adapter await stoppedThread.fetchCallStack(); assert.notStrictEqual(stoppedThread.getCallStack().length, 0); assert.strictEqual(runningThread.getCallStack().length, 0); assert.strictEqual(sessionStub.callCount, 1); // calling getCallStack on the running thread returns empty array // and does not return in a request for the callstack in the debug // adapter await runningThread.fetchCallStack(); assert.strictEqual(runningThread.getCallStack().length, 0); assert.strictEqual(sessionStub.callCount, 1); // clearing the callstack results in the callstack not being available stoppedThread.clearCallStack(); assert.strictEqual(stoppedThread.stopped, true); assert.strictEqual(stoppedThread.getCallStack().length, 0); model.clearThreads(session.getId(), true); assert.strictEqual(session.getThread(stoppedThreadId), undefined); assert.strictEqual(session.getThread(runningThreadId), undefined); assert.strictEqual(session.getAllThreads().length, 0); }); test('stack frame get specific source name', () => { const session = createMockSession(model); model.addSession(session); const { firstStackFrame, secondStackFrame } = createTwoStackFrames(session); assert.strictEqual(getSpecificSourceName(firstStackFrame), '.../b/c/d/internalModule.js'); assert.strictEqual(getSpecificSourceName(secondStackFrame), '.../x/c/d/internalModule.js'); }); test('stack frame toString()', () => { const session = createMockSession(model); const thread = new Thread(session, 'mockthread', 1); const firstSource = new Source({ name: 'internalModule.js', path: 'a/b/c/d/internalModule.js', sourceReference: 10, }, 'aDebugSessionId', mockUriIdentityService); const stackFrame = new StackFrame(thread, 1, firstSource, 'app', 'normal', { startLineNumber: 1, startColumn: 1, endLineNumber: 1, endColumn: 10 }, 1, true); assert.strictEqual(stackFrame.toString(), 'app (internalModule.js:1)'); const secondSource = new Source(undefined, 'aDebugSessionId', mockUriIdentityService); const stackFrame2 = new StackFrame(thread, 2, secondSource, 'module', 'normal', { startLineNumber: undefined!, startColumn: undefined!, endLineNumber: undefined!, endColumn: undefined! }, 2, true); assert.strictEqual(stackFrame2.toString(), 'module'); }); test('debug child sessions are added in correct order', () => { const session = createMockSession(model); model.addSession(session); const secondSession = createMockSession(model, 'mockSession2'); model.addSession(secondSession); const firstChild = createMockSession(model, 'firstChild', { parentSession: session }); model.addSession(firstChild); const secondChild = createMockSession(model, 'secondChild', { parentSession: session }); model.addSession(secondChild); const thirdSession = createMockSession(model, 'mockSession3'); model.addSession(thirdSession); const anotherChild = createMockSession(model, 'secondChild', { parentSession: secondSession }); model.addSession(anotherChild); const sessions = model.getSessions(); assert.strictEqual(sessions[0].getId(), session.getId()); assert.strictEqual(sessions[1].getId(), firstChild.getId()); assert.strictEqual(sessions[2].getId(), secondChild.getId()); assert.strictEqual(sessions[3].getId(), secondSession.getId()); assert.strictEqual(sessions[4].getId(), anotherChild.getId()); assert.strictEqual(sessions[5].getId(), thirdSession.getId()); }); test('decorations', () => { const session = createMockSession(model); model.addSession(session); const { firstStackFrame, secondStackFrame } = createTwoStackFrames(session); let decorations = createDecorationsForStackFrame(firstStackFrame, firstStackFrame.range, true); assert.strictEqual(decorations.length, 2); assert.deepStrictEqual(decorations[0].range, new Range(1, 2, 1, 1)); assert.strictEqual(decorations[0].options.glyphMarginClassName, ThemeIcon.asClassName(debugStackframe)); assert.deepStrictEqual(decorations[1].range, new Range(1, Constants.MAX_SAFE_SMALL_INTEGER, 1, 1)); assert.strictEqual(decorations[1].options.className, 'debug-top-stack-frame-line'); assert.strictEqual(decorations[1].options.isWholeLine, true); decorations = createDecorationsForStackFrame(secondStackFrame, firstStackFrame.range, true); assert.strictEqual(decorations.length, 2); assert.deepStrictEqual(decorations[0].range, new Range(1, 2, 1, 1)); assert.strictEqual(decorations[0].options.glyphMarginClassName, ThemeIcon.asClassName(debugStackframeFocused)); assert.deepStrictEqual(decorations[1].range, new Range(1, Constants.MAX_SAFE_SMALL_INTEGER, 1, 1)); assert.strictEqual(decorations[1].options.className, 'debug-focused-stack-frame-line'); assert.strictEqual(decorations[1].options.isWholeLine, true); decorations = createDecorationsForStackFrame(firstStackFrame, new Range(1, 5, 1, 6), true); assert.strictEqual(decorations.length, 3); assert.deepStrictEqual(decorations[0].range, new Range(1, 2, 1, 1)); assert.strictEqual(decorations[0].options.glyphMarginClassName, ThemeIcon.asClassName(debugStackframe)); assert.deepStrictEqual(decorations[1].range, new Range(1, Constants.MAX_SAFE_SMALL_INTEGER, 1, 1)); assert.strictEqual(decorations[1].options.className, 'debug-top-stack-frame-line'); assert.strictEqual(decorations[1].options.isWholeLine, true); // Inline decoration gets rendered in this case assert.strictEqual(decorations[2].options.beforeContentClassName, 'debug-top-stack-frame-column'); assert.deepStrictEqual(decorations[2].range, new Range(1, Constants.MAX_SAFE_SMALL_INTEGER, 1, 1)); }); test('contexts', () => { const session = createMockSession(model); model.addSession(session); const { firstStackFrame, secondStackFrame } = createTwoStackFrames(session); let context = getContext(firstStackFrame); assert.strictEqual(context.sessionId, firstStackFrame.thread.session.getId()); assert.strictEqual(context.threadId, firstStackFrame.thread.getId()); assert.strictEqual(context.frameId, firstStackFrame.getId()); context = getContext(secondStackFrame.thread); assert.strictEqual(context.sessionId, secondStackFrame.thread.session.getId()); assert.strictEqual(context.threadId, secondStackFrame.thread.getId()); assert.strictEqual(context.frameId, undefined); context = getContext(session); assert.strictEqual(context.sessionId, session.getId()); assert.strictEqual(context.threadId, undefined); assert.strictEqual(context.frameId, undefined); let contributedContext = getContextForContributedActions(firstStackFrame); assert.strictEqual(contributedContext, firstStackFrame.source.raw.path); contributedContext = getContextForContributedActions(firstStackFrame.thread); assert.strictEqual(contributedContext, firstStackFrame.thread.threadId); contributedContext = getContextForContributedActions(session); assert.strictEqual(contributedContext, session.getId()); }); test('focusStackFrameThreadAndSesion', () => { const threadId1 = 1; const threadName1 = 'firstThread'; const threadId2 = 2; const threadName2 = 'secondThread'; const stoppedReason = 'breakpoint'; // Add the threads const session = new class extends DebugSession { get state(): State { return State.Stopped; } }(generateUuid(), { resolved: { name: 'stoppedSession', type: 'node', request: 'launch' }, unresolved: undefined }, undefined!, model, undefined, undefined!, undefined!, undefined!, undefined!, undefined!, mockWorkspaceContextService, undefined!, undefined!, NullOpenerService, undefined!, undefined!, mockUriIdentityService, undefined!); const runningSession = createMockSession(model); model.addSession(runningSession); model.addSession(session); session['raw'] = <any>rawSession; model.rawUpdate({ sessionId: session.getId(), threads: [{ id: threadId1, name: threadName1 }] }); // Stopped event with all threads stopped model.rawUpdate({ sessionId: session.getId(), threads: [{ id: threadId1, name: threadName1 }, { id: threadId2, name: threadName2 }], stoppedDetails: { reason: stoppedReason, threadId: 1, allThreadsStopped: true }, }); const thread = session.getThread(threadId1)!; const runningThread = session.getThread(threadId2); let toFocus = getStackFrameThreadAndSessionToFocus(model, undefined); // Verify stopped session and stopped thread get focused assert.deepStrictEqual(toFocus, { stackFrame: undefined, thread: thread, session: session }); toFocus = getStackFrameThreadAndSessionToFocus(model, undefined, undefined, runningSession); assert.deepStrictEqual(toFocus, { stackFrame: undefined, thread: undefined, session: runningSession }); toFocus = getStackFrameThreadAndSessionToFocus(model, undefined, thread); assert.deepStrictEqual(toFocus, { stackFrame: undefined, thread: thread, session: session }); toFocus = getStackFrameThreadAndSessionToFocus(model, undefined, runningThread); assert.deepStrictEqual(toFocus, { stackFrame: undefined, thread: runningThread, session: session }); const stackFrame = new StackFrame(thread, 5, undefined!, 'stackframename2', undefined, undefined!, 1, true); toFocus = getStackFrameThreadAndSessionToFocus(model, stackFrame); assert.deepStrictEqual(toFocus, { stackFrame: stackFrame, thread: thread, session: session }); }); });
src/vs/workbench/contrib/debug/test/browser/callStack.test.ts
1
https://github.com/microsoft/vscode/commit/f554a745505474ba031a79f5ab4a5c9d1ed3af39
[ 0.00910105835646391, 0.0004886487731710076, 0.00016509724082425237, 0.0001731493539409712, 0.0013564331457018852 ]
{ "id": 3, "code_window": [ "\n", "export class CallStackEditorContribution implements IEditorContribution {\n", "\tprivate toDispose: IDisposable[] = [];\n", "\tprivate decorationIds: string[] = [];\n", "\tprivate topStackFrameRange: Range | undefined;\n", "\n", "\tconstructor(\n", "\t\tprivate readonly editor: ICodeEditor,\n", "\t\t@IDebugService private readonly debugService: IDebugService,\n", "\t\t@IUriIdentityService private readonly uriIdentityService: IUriIdentityService\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/debug/browser/callStackEditorContribution.ts", "type": "replace", "edit_start_line_idx": 104 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as assert from 'assert'; import { BoundModelReferenceCollection } from 'vs/workbench/api/browser/mainThreadDocuments'; import { createTextModel } from 'vs/editor/test/common/editorTestUtils'; import { timeout } from 'vs/base/common/async'; import { URI } from 'vs/base/common/uri'; import { extUri } from 'vs/base/common/resources'; suite('BoundModelReferenceCollection', () => { let col = new BoundModelReferenceCollection(extUri, 15, 75); teardown(() => { col.dispose(); }); test('max age', async () => { let didDispose = false; col.add( URI.parse('test://farboo'), { object: <any>{ textEditorModel: createTextModel('farboo') }, dispose() { didDispose = true; } }); await timeout(30); assert.strictEqual(didDispose, true); }); test('max size', () => { let disposed: number[] = []; col.add( URI.parse('test://farboo'), { object: <any>{ textEditorModel: createTextModel('farboo') }, dispose() { disposed.push(0); } }, 6); col.add( URI.parse('test://boofar'), { object: <any>{ textEditorModel: createTextModel('boofar') }, dispose() { disposed.push(1); } }, 6); col.add( URI.parse('test://xxxxxxx'), { object: <any>{ textEditorModel: createTextModel(new Array(71).join('x')) }, dispose() { disposed.push(2); } }, 70); assert.deepStrictEqual(disposed, [0, 1]); }); test('dispose uri', () => { let disposed: number[] = []; col.add( URI.parse('test:///farboo'), { object: <any>{ textEditorModel: createTextModel('farboo') }, dispose() { disposed.push(0); } }); col.add( URI.parse('test:///boofar'), { object: <any>{ textEditorModel: createTextModel('boofar') }, dispose() { disposed.push(1); } }); col.add( URI.parse('test:///boo/far1'), { object: <any>{ textEditorModel: createTextModel('boo/far1') }, dispose() { disposed.push(2); } }); col.add( URI.parse('test:///boo/far2'), { object: <any>{ textEditorModel: createTextModel('boo/far2') }, dispose() { disposed.push(3); } }); col.add( URI.parse('test:///boo1/far'), { object: <any>{ textEditorModel: createTextModel('boo1/far') }, dispose() { disposed.push(4); } }); col.remove(URI.parse('test:///unknown')); assert.strictEqual(disposed.length, 0); col.remove(URI.parse('test:///farboo')); assert.deepStrictEqual(disposed, [0]); disposed = []; col.remove(URI.parse('test:///boo')); assert.deepStrictEqual(disposed, [2, 3]); }); });
src/vs/workbench/test/browser/api/mainThreadDocuments.test.ts
0
https://github.com/microsoft/vscode/commit/f554a745505474ba031a79f5ab4a5c9d1ed3af39
[ 0.00017502231639809906, 0.00016937966574914753, 0.00016664116992615163, 0.00016843780758790672, 0.0000028680233299382962 ]
{ "id": 3, "code_window": [ "\n", "export class CallStackEditorContribution implements IEditorContribution {\n", "\tprivate toDispose: IDisposable[] = [];\n", "\tprivate decorationIds: string[] = [];\n", "\tprivate topStackFrameRange: Range | undefined;\n", "\n", "\tconstructor(\n", "\t\tprivate readonly editor: ICodeEditor,\n", "\t\t@IDebugService private readonly debugService: IDebugService,\n", "\t\t@IUriIdentityService private readonly uriIdentityService: IUriIdentityService\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/debug/browser/callStackEditorContribution.ts", "type": "replace", "edit_start_line_idx": 104 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import 'vs/css!./media/panel'; import * as nls from 'vs/nls'; import * as dom from 'vs/base/browser/dom'; import { basename } from 'vs/base/common/resources'; import { isCodeEditor } from 'vs/editor/browser/editorBrowser'; import { IInstantiationService, ServicesAccessor } from 'vs/platform/instantiation/common/instantiation'; import { IThemeService } from 'vs/platform/theme/common/themeService'; import { CommentNode, CommentsModel, ResourceWithCommentThreads, ICommentThreadChangedEvent } from 'vs/workbench/contrib/comments/common/commentModel'; import { CommentController } from 'vs/workbench/contrib/comments/browser/commentsEditorContribution'; import { IWorkspaceCommentThreadsEvent, ICommentService } from 'vs/workbench/contrib/comments/browser/commentService'; import { IEditorService, ACTIVE_GROUP, SIDE_GROUP } from 'vs/workbench/services/editor/common/editorService'; import { CommandsRegistry } from 'vs/platform/commands/common/commands'; import { textLinkForeground, textLinkActiveForeground, focusBorder, textPreformatForeground } from 'vs/platform/theme/common/colorRegistry'; import { ResourceLabels } from 'vs/workbench/browser/labels'; import { CommentsList, COMMENTS_VIEW_ID, COMMENTS_VIEW_TITLE } from 'vs/workbench/contrib/comments/browser/commentsTreeViewer'; import { ViewPane, IViewPaneOptions, ViewAction } from 'vs/workbench/browser/parts/views/viewPane'; import { IViewDescriptorService, IViewsService } from 'vs/workbench/common/views'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { ContextKeyAndExpr, ContextKeyEqualsExpr, IContextKey, IContextKeyService, RawContextKey } from 'vs/platform/contextkey/common/contextkey'; import { IContextMenuService } from 'vs/platform/contextview/browser/contextView'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { IOpenerService } from 'vs/platform/opener/common/opener'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IUriIdentityService } from 'vs/workbench/services/uriIdentity/common/uriIdentity'; import { MenuId, registerAction2 } from 'vs/platform/actions/common/actions'; import { Codicon } from 'vs/base/common/codicons'; const CONTEXT_KEY_HAS_COMMENTS = new RawContextKey<boolean>('commentsView.hasComments', false); export class CommentsPanel extends ViewPane { private treeLabels!: ResourceLabels; private tree!: CommentsList; private treeContainer!: HTMLElement; private messageBoxContainer!: HTMLElement; private commentsModel!: CommentsModel; private readonly hasCommentsContextKey: IContextKey<boolean>; readonly onDidChangeVisibility = this.onDidChangeBodyVisibility; constructor( options: IViewPaneOptions, @IInstantiationService readonly instantiationService: IInstantiationService, @IViewDescriptorService viewDescriptorService: IViewDescriptorService, @IEditorService private readonly editorService: IEditorService, @IConfigurationService configurationService: IConfigurationService, @IContextKeyService contextKeyService: IContextKeyService, @IContextMenuService contextMenuService: IContextMenuService, @IKeybindingService keybindingService: IKeybindingService, @IOpenerService openerService: IOpenerService, @IThemeService themeService: IThemeService, @ICommentService private readonly commentService: ICommentService, @ITelemetryService telemetryService: ITelemetryService, @IUriIdentityService private readonly uriIdentityService: IUriIdentityService ) { super(options, keybindingService, contextMenuService, configurationService, contextKeyService, viewDescriptorService, instantiationService, openerService, themeService, telemetryService); this.hasCommentsContextKey = CONTEXT_KEY_HAS_COMMENTS.bindTo(contextKeyService); } public renderBody(container: HTMLElement): void { super.renderBody(container); container.classList.add('comments-panel'); let domContainer = dom.append(container, dom.$('.comments-panel-container')); this.treeContainer = dom.append(domContainer, dom.$('.tree-container')); this.commentsModel = new CommentsModel(); this.createTree(); this.createMessageBox(domContainer); this._register(this.commentService.onDidSetAllCommentThreads(this.onAllCommentsChanged, this)); this._register(this.commentService.onDidUpdateCommentThreads(this.onCommentsUpdated, this)); const styleElement = dom.createStyleSheet(container); this.applyStyles(styleElement); this._register(this.themeService.onDidColorThemeChange(_ => this.applyStyles(styleElement))); this._register(this.onDidChangeBodyVisibility(visible => { if (visible) { this.refresh(); } })); this.renderComments(); } public focus(): void { if (this.tree && this.tree.getHTMLElement() === document.activeElement) { return; } if (!this.commentsModel.hasCommentThreads() && this.messageBoxContainer) { this.messageBoxContainer.focus(); } else if (this.tree) { this.tree.domFocus(); } } private applyStyles(styleElement: HTMLStyleElement) { const content: string[] = []; const theme = this.themeService.getColorTheme(); const linkColor = theme.getColor(textLinkForeground); if (linkColor) { content.push(`.comments-panel .comments-panel-container a { color: ${linkColor}; }`); } const linkActiveColor = theme.getColor(textLinkActiveForeground); if (linkActiveColor) { content.push(`.comments-panel .comments-panel-container a:hover, a:active { color: ${linkActiveColor}; }`); } const focusColor = theme.getColor(focusBorder); if (focusColor) { content.push(`.comments-panel .commenst-panel-container a:focus { outline-color: ${focusColor}; }`); } const codeTextForegroundColor = theme.getColor(textPreformatForeground); if (codeTextForegroundColor) { content.push(`.comments-panel .comments-panel-container .text code { color: ${codeTextForegroundColor}; }`); } styleElement.textContent = content.join('\n'); } private async renderComments(): Promise<void> { this.treeContainer.classList.toggle('hidden', !this.commentsModel.hasCommentThreads()); this.renderMessage(); await this.tree.setInput(this.commentsModel); } public collapseAll() { if (this.tree) { this.tree.collapseAll(); this.tree.setSelection([]); this.tree.setFocus([]); this.tree.domFocus(); this.tree.focusFirst(); } } public layoutBody(height: number, width: number): void { super.layoutBody(height, width); this.tree.layout(height, width); } public getTitle(): string { return COMMENTS_VIEW_TITLE; } private createMessageBox(parent: HTMLElement): void { this.messageBoxContainer = dom.append(parent, dom.$('.message-box-container')); this.messageBoxContainer.setAttribute('tabIndex', '0'); } private renderMessage(): void { this.messageBoxContainer.textContent = this.commentsModel.getMessage(); this.messageBoxContainer.classList.toggle('hidden', this.commentsModel.hasCommentThreads()); } private createTree(): void { this.treeLabels = this._register(this.instantiationService.createInstance(ResourceLabels, this)); this.tree = this._register(this.instantiationService.createInstance(CommentsList, this.treeLabels, this.treeContainer, { overrideStyles: { listBackground: this.getBackgroundColor() }, selectionNavigation: true, accessibilityProvider: { getAriaLabel(element: any): string { if (element instanceof CommentsModel) { return nls.localize('rootCommentsLabel', "Comments for current workspace"); } if (element instanceof ResourceWithCommentThreads) { return nls.localize('resourceWithCommentThreadsLabel', "Comments in {0}, full path {1}", basename(element.resource), element.resource.fsPath); } if (element instanceof CommentNode) { return nls.localize('resourceWithCommentLabel', "Comment from ${0} at line {1} column {2} in {3}, source: {4}", element.comment.userName, element.range.startLineNumber, element.range.startColumn, basename(element.resource), element.comment.body.value ); } return ''; }, getWidgetAriaLabel(): string { return COMMENTS_VIEW_TITLE; } } })); this._register(this.tree.onDidOpen(e => { this.openFile(e.element, e.editorOptions.pinned, e.editorOptions.preserveFocus, e.sideBySide); })); } private openFile(element: any, pinned?: boolean, preserveFocus?: boolean, sideBySide?: boolean): boolean { if (!element) { return false; } if (!(element instanceof ResourceWithCommentThreads || element instanceof CommentNode)) { return false; } const range = element instanceof ResourceWithCommentThreads ? element.commentThreads[0].range : element.range; const activeEditor = this.editorService.activeEditor; let currentActiveResource = activeEditor ? activeEditor.resource : undefined; if (this.uriIdentityService.extUri.isEqual(element.resource, currentActiveResource)) { const threadToReveal = element instanceof ResourceWithCommentThreads ? element.commentThreads[0].threadId : element.threadId; const commentToReveal = element instanceof ResourceWithCommentThreads ? element.commentThreads[0].comment.uniqueIdInThread : element.comment.uniqueIdInThread; const control = this.editorService.activeTextEditorControl; if (threadToReveal && isCodeEditor(control)) { const controller = CommentController.get(control); controller.revealCommentThread(threadToReveal, commentToReveal, false); } return true; } const threadToReveal = element instanceof ResourceWithCommentThreads ? element.commentThreads[0].threadId : element.threadId; const commentToReveal = element instanceof ResourceWithCommentThreads ? element.commentThreads[0].comment : element.comment; this.editorService.openEditor({ resource: element.resource, options: { pinned: pinned, preserveFocus: preserveFocus, selection: range } }, sideBySide ? SIDE_GROUP : ACTIVE_GROUP).then(editor => { if (editor) { const control = editor.getControl(); if (threadToReveal && isCodeEditor(control)) { const controller = CommentController.get(control); controller.revealCommentThread(threadToReveal, commentToReveal.uniqueIdInThread, true); } } }); return true; } private async refresh(): Promise<void> { if (this.isVisible()) { this.hasCommentsContextKey.set(this.commentsModel.hasCommentThreads()); this.treeContainer.classList.toggle('hidden', !this.commentsModel.hasCommentThreads()); this.renderMessage(); await this.tree.updateChildren(); if (this.tree.getSelection().length === 0 && this.commentsModel.hasCommentThreads()) { const firstComment = this.commentsModel.resourceCommentThreads[0].commentThreads[0]; if (firstComment) { this.tree.setFocus([firstComment]); this.tree.setSelection([firstComment]); } } } } private onAllCommentsChanged(e: IWorkspaceCommentThreadsEvent): void { this.commentsModel.setCommentThreads(e.ownerId, e.commentThreads); this.refresh(); } private onCommentsUpdated(e: ICommentThreadChangedEvent): void { const didUpdate = this.commentsModel.updateCommentThreads(e); if (didUpdate) { this.refresh(); } } } CommandsRegistry.registerCommand({ id: 'workbench.action.focusCommentsPanel', handler: async (accessor) => { const viewsService = accessor.get(IViewsService); viewsService.openView(COMMENTS_VIEW_ID, true); } }); registerAction2(class Collapse extends ViewAction<CommentsPanel> { constructor() { super({ viewId: COMMENTS_VIEW_ID, id: 'comments.collapse', title: nls.localize('collapseAll', "Collapse All"), f1: false, icon: Codicon.collapseAll, menu: { id: MenuId.ViewTitle, group: 'navigation', when: ContextKeyAndExpr.create([ContextKeyEqualsExpr.create('view', COMMENTS_VIEW_ID), CONTEXT_KEY_HAS_COMMENTS]) } }); } runInView(_accessor: ServicesAccessor, view: CommentsPanel) { view.collapseAll(); } });
src/vs/workbench/contrib/comments/browser/commentsView.ts
0
https://github.com/microsoft/vscode/commit/f554a745505474ba031a79f5ab4a5c9d1ed3af39
[ 0.0022519126068800688, 0.0002443423727527261, 0.000165825811563991, 0.00017265485075768083, 0.0003669547149911523 ]
{ "id": 3, "code_window": [ "\n", "export class CallStackEditorContribution implements IEditorContribution {\n", "\tprivate toDispose: IDisposable[] = [];\n", "\tprivate decorationIds: string[] = [];\n", "\tprivate topStackFrameRange: Range | undefined;\n", "\n", "\tconstructor(\n", "\t\tprivate readonly editor: ICodeEditor,\n", "\t\t@IDebugService private readonly debugService: IDebugService,\n", "\t\t@IUriIdentityService private readonly uriIdentityService: IUriIdentityService\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/debug/browser/callStackEditorContribution.ts", "type": "replace", "edit_start_line_idx": 104 }
This is some UTF 8 with BOM file.
src/vs/platform/files/test/electron-browser/fixtures/service/some_utf8_bom.txt
0
https://github.com/microsoft/vscode/commit/f554a745505474ba031a79f5ab4a5c9d1ed3af39
[ 0.00017033253971021622, 0.00017033253971021622, 0.00017033253971021622, 0.00017033253971021622, 0 ]
{ "id": 4, "code_window": [ "\t\t\t\t\t\tstackFrames.push(callStack[0]);\n", "\t\t\t\t\t}\n", "\n", "\t\t\t\t\tstackFrames.forEach(candidateStackFrame => {\n", "\t\t\t\t\t\tif (candidateStackFrame && this.uriIdentityService.extUri.isEqual(candidateStackFrame.source.uri, this.editor.getModel()?.uri)) {\n", "\t\t\t\t\t\t\tdecorations.push(...createDecorationsForStackFrame(candidateStackFrame, this.topStackFrameRange, isSessionFocused));\n", "\t\t\t\t\t\t}\n", "\t\t\t\t\t});\n", "\t\t\t\t}\n", "\t\t\t});\n", "\t\t});\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\t\t\t\tdecorations.push(...createDecorationsForStackFrame(candidateStackFrame, isSessionFocused));\n" ], "file_path": "src/vs/workbench/contrib/debug/browser/callStackEditorContribution.ts", "type": "replace", "edit_start_line_idx": 141 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Constants } from 'vs/base/common/uint'; import { Range, IRange } from 'vs/editor/common/core/range'; import { TrackedRangeStickiness, IModelDeltaDecoration, IModelDecorationOptions, OverviewRulerLane } from 'vs/editor/common/model'; import { IDebugService, IStackFrame } from 'vs/workbench/contrib/debug/common/debug'; import { registerThemingParticipant, themeColorFromId, ThemeIcon } from 'vs/platform/theme/common/themeService'; import { registerColor } from 'vs/platform/theme/common/colorRegistry'; import { localize } from 'vs/nls'; import { Event } from 'vs/base/common/event'; import { IDisposable, dispose } from 'vs/base/common/lifecycle'; import { IEditorContribution } from 'vs/editor/common/editorCommon'; import { ICodeEditor } from 'vs/editor/browser/editorBrowser'; import { distinct } from 'vs/base/common/arrays'; import { IUriIdentityService } from 'vs/workbench/services/uriIdentity/common/uriIdentity'; import { debugStackframe, debugStackframeFocused } from 'vs/workbench/contrib/debug/browser/debugIcons'; const topStackFrameColor = registerColor('editor.stackFrameHighlightBackground', { dark: '#ffff0033', light: '#ffff6673', hc: '#ffff0033' }, localize('topStackFrameLineHighlight', 'Background color for the highlight of line at the top stack frame position.')); const focusedStackFrameColor = registerColor('editor.focusedStackFrameHighlightBackground', { dark: '#7abd7a4d', light: '#cee7ce73', hc: '#7abd7a4d' }, localize('focusedStackFrameLineHighlight', 'Background color for the highlight of line at focused stack frame position.')); const stickiness = TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges; // we need a separate decoration for glyph margin, since we do not want it on each line of a multi line statement. const TOP_STACK_FRAME_MARGIN: IModelDecorationOptions = { glyphMarginClassName: ThemeIcon.asClassName(debugStackframe), stickiness, overviewRuler: { position: OverviewRulerLane.Full, color: themeColorFromId(topStackFrameColor) } }; const FOCUSED_STACK_FRAME_MARGIN: IModelDecorationOptions = { glyphMarginClassName: ThemeIcon.asClassName(debugStackframeFocused), stickiness, overviewRuler: { position: OverviewRulerLane.Full, color: themeColorFromId(focusedStackFrameColor) } }; const TOP_STACK_FRAME_DECORATION: IModelDecorationOptions = { isWholeLine: true, className: 'debug-top-stack-frame-line', stickiness }; const TOP_STACK_FRAME_INLINE_DECORATION: IModelDecorationOptions = { beforeContentClassName: 'debug-top-stack-frame-column' }; const FOCUSED_STACK_FRAME_DECORATION: IModelDecorationOptions = { isWholeLine: true, className: 'debug-focused-stack-frame-line', stickiness }; export function createDecorationsForStackFrame(stackFrame: IStackFrame, topStackFrameRange: IRange | undefined, isFocusedSession: boolean): IModelDeltaDecoration[] { // only show decorations for the currently focused thread. const result: IModelDeltaDecoration[] = []; const columnUntilEOLRange = new Range(stackFrame.range.startLineNumber, stackFrame.range.startColumn, stackFrame.range.startLineNumber, Constants.MAX_SAFE_SMALL_INTEGER); const range = new Range(stackFrame.range.startLineNumber, stackFrame.range.startColumn, stackFrame.range.startLineNumber, stackFrame.range.startColumn + 1); // compute how to decorate the editor. Different decorations are used if this is a top stack frame, focused stack frame, // an exception or a stack frame that did not change the line number (we only decorate the columns, not the whole line). const topStackFrame = stackFrame.thread.getTopStackFrame(); if (stackFrame.getId() === topStackFrame?.getId()) { if (isFocusedSession) { result.push({ options: TOP_STACK_FRAME_MARGIN, range }); } result.push({ options: TOP_STACK_FRAME_DECORATION, range: columnUntilEOLRange }); if (topStackFrameRange && topStackFrameRange.startLineNumber === stackFrame.range.startLineNumber && topStackFrameRange.startColumn !== stackFrame.range.startColumn) { result.push({ options: TOP_STACK_FRAME_INLINE_DECORATION, range: columnUntilEOLRange }); } topStackFrameRange = columnUntilEOLRange; } else { if (isFocusedSession) { result.push({ options: FOCUSED_STACK_FRAME_MARGIN, range }); } result.push({ options: FOCUSED_STACK_FRAME_DECORATION, range: columnUntilEOLRange }); } return result; } export class CallStackEditorContribution implements IEditorContribution { private toDispose: IDisposable[] = []; private decorationIds: string[] = []; private topStackFrameRange: Range | undefined; constructor( private readonly editor: ICodeEditor, @IDebugService private readonly debugService: IDebugService, @IUriIdentityService private readonly uriIdentityService: IUriIdentityService ) { const setDecorations = () => this.decorationIds = this.editor.deltaDecorations(this.decorationIds, this.createCallStackDecorations()); this.toDispose.push(Event.any(this.debugService.getViewModel().onDidFocusStackFrame, this.debugService.getModel().onDidChangeCallStack)(() => { setDecorations(); })); this.toDispose.push(this.editor.onDidChangeModel(e => { if (e.newModelUrl) { setDecorations(); } })); } private createCallStackDecorations(): IModelDeltaDecoration[] { const focusedStackFrame = this.debugService.getViewModel().focusedStackFrame; const decorations: IModelDeltaDecoration[] = []; this.debugService.getModel().getSessions().forEach(s => { const isSessionFocused = s === focusedStackFrame?.thread.session; s.getAllThreads().forEach(t => { if (t.stopped) { const callStack = t.getCallStack(); const stackFrames: IStackFrame[] = []; if (callStack.length > 0) { // Always decorate top stack frame, and decorate focused stack frame if it is not the top stack frame if (focusedStackFrame && !focusedStackFrame.equals(callStack[0])) { stackFrames.push(focusedStackFrame); } stackFrames.push(callStack[0]); } stackFrames.forEach(candidateStackFrame => { if (candidateStackFrame && this.uriIdentityService.extUri.isEqual(candidateStackFrame.source.uri, this.editor.getModel()?.uri)) { decorations.push(...createDecorationsForStackFrame(candidateStackFrame, this.topStackFrameRange, isSessionFocused)); } }); } }); }); // Deduplicate same decorations so colors do not stack #109045 return distinct(decorations, d => `${d.options.className} ${d.options.glyphMarginClassName} ${d.range.startLineNumber} ${d.range.startColumn}`); } dispose(): void { this.editor.deltaDecorations(this.decorationIds, []); this.toDispose = dispose(this.toDispose); } } registerThemingParticipant((theme, collector) => { const topStackFrame = theme.getColor(topStackFrameColor); if (topStackFrame) { collector.addRule(`.monaco-editor .view-overlays .debug-top-stack-frame-line { background: ${topStackFrame}; }`); } const focusedStackFrame = theme.getColor(focusedStackFrameColor); if (focusedStackFrame) { collector.addRule(`.monaco-editor .view-overlays .debug-focused-stack-frame-line { background: ${focusedStackFrame}; }`); } });
src/vs/workbench/contrib/debug/browser/callStackEditorContribution.ts
1
https://github.com/microsoft/vscode/commit/f554a745505474ba031a79f5ab4a5c9d1ed3af39
[ 0.7826037406921387, 0.04824322834610939, 0.00016645219875499606, 0.001787705929018557, 0.18360765278339386 ]
{ "id": 4, "code_window": [ "\t\t\t\t\t\tstackFrames.push(callStack[0]);\n", "\t\t\t\t\t}\n", "\n", "\t\t\t\t\tstackFrames.forEach(candidateStackFrame => {\n", "\t\t\t\t\t\tif (candidateStackFrame && this.uriIdentityService.extUri.isEqual(candidateStackFrame.source.uri, this.editor.getModel()?.uri)) {\n", "\t\t\t\t\t\t\tdecorations.push(...createDecorationsForStackFrame(candidateStackFrame, this.topStackFrameRange, isSessionFocused));\n", "\t\t\t\t\t\t}\n", "\t\t\t\t\t});\n", "\t\t\t\t}\n", "\t\t\t});\n", "\t\t});\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\t\t\t\tdecorations.push(...createDecorationsForStackFrame(candidateStackFrame, isSessionFocused));\n" ], "file_path": "src/vs/workbench/contrib/debug/browser/callStackEditorContribution.ts", "type": "replace", "edit_start_line_idx": 141 }
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 386 197.26"><defs><style>.cls-1{fill:#252526;}.cls-2{fill:#3c3c3c;stroke:#073655;}.cls-2,.cls-4{stroke-miterlimit:10;}.cls-3{fill:#ccc;}.cls-4{fill:none;stroke:#ccc;}.cls-5{fill:#073655;}.cls-6{opacity:0.52;}</style></defs><title>Asset 8</title><g id="Layer_2" data-name="Layer 2"><g id="Layer_1-2" data-name="Layer 1"><rect class="cls-1" y="0.26" width="386" height="197"/><rect class="cls-2" x="5.25" y="8.26" width="374" height="23"/><path class="cls-3" d="M17.22,21.52l-7.14,3.59V23.87l5.35-2.59v0l-5.35-3V17l7.14,4Z"/><line class="cls-4" x1="18.75" y1="12.26" x2="18.75" y2="28.26"/><rect class="cls-5" y="38.76" width="385.75" height="20.5"/><path class="cls-3" d="M17.65,53.95a5.34,5.34,0,0,1-2.51.53A4.06,4.06,0,0,1,12,53.23,4.61,4.61,0,0,1,10.86,50a4.83,4.83,0,0,1,1.31-3.53,4.46,4.46,0,0,1,3.33-1.35,5.36,5.36,0,0,1,2.15.37v1.14A4.35,4.35,0,0,0,15.49,46a3.31,3.31,0,0,0-2.54,1,3.94,3.94,0,0,0-1,2.8,3.76,3.76,0,0,0,.91,2.65,3.1,3.1,0,0,0,2.39,1,4.48,4.48,0,0,0,2.37-.61Z"/><path class="cls-3" d="M24.76,54.33h-1V50.58q0-2-1.51-2a1.65,1.65,0,0,0-1.28.59,2.19,2.19,0,0,0-.52,1.51v3.68h-1V44.71h1v4.2h0a2.36,2.36,0,0,1,2.13-1.23q2.2,0,2.2,2.65Z"/><path class="cls-3" d="M31.37,54.33h-1v-1h0a2.18,2.18,0,0,1-2,1.17A2.14,2.14,0,0,1,26.79,54a1.78,1.78,0,0,1-.55-1.37q0-1.82,2.14-2.12l1.95-.27q0-1.66-1.34-1.66a3.2,3.2,0,0,0-2.12.8V48.29a4,4,0,0,1,2.21-.61q2.29,0,2.29,2.42Zm-1-3.29-1.57.22a2.55,2.55,0,0,0-1.09.36,1,1,0,0,0-.37.91,1,1,0,0,0,.34.78,1.31,1.31,0,0,0,.9.3,1.67,1.67,0,0,0,1.28-.54,1.94,1.94,0,0,0,.5-1.37Z"/><path class="cls-3" d="M38.73,54.33h-1V50.62q0-2.07-1.51-2.07a1.64,1.64,0,0,0-1.29.59,2.18,2.18,0,0,0-.51,1.48v3.71h-1v-6.5h1v1.08h0a2.35,2.35,0,0,1,2.13-1.23,2,2,0,0,1,1.63.69,3.07,3.07,0,0,1,.57,2Z"/><path class="cls-3" d="M46.24,53.81q0,3.58-3.43,3.58a4.6,4.6,0,0,1-2.11-.46v-1a4.33,4.33,0,0,0,2.09.61q2.4,0,2.4-2.55v-.71h0a2.63,2.63,0,0,1-4.19.38,3.47,3.47,0,0,1-.74-2.33,4,4,0,0,1,.8-2.63,2.66,2.66,0,0,1,2.18-1,2.12,2.12,0,0,1,1.95,1.05h0v-.9h1Zm-1-2.42v-1a1.86,1.86,0,0,0-.52-1.33,1.73,1.73,0,0,0-1.3-.55,1.81,1.81,0,0,0-1.51.7,3.14,3.14,0,0,0-.55,2A2.69,2.69,0,0,0,41.83,53a1.69,1.69,0,0,0,1.39.65A1.81,1.81,0,0,0,44.65,53,2.32,2.32,0,0,0,45.2,51.39Z"/><path class="cls-3" d="M53.57,51.34H49A2.43,2.43,0,0,0,49.56,53a2,2,0,0,0,1.54.59,3.19,3.19,0,0,0,2-.72v1a3.77,3.77,0,0,1-2.27.62,2.75,2.75,0,0,1-2.16-.89,3.62,3.62,0,0,1-.79-2.49,3.55,3.55,0,0,1,.86-2.47,2.76,2.76,0,0,1,2.14-1,2.45,2.45,0,0,1,2,.83,3.44,3.44,0,0,1,.7,2.29Zm-1.07-.88a2.12,2.12,0,0,0-.43-1.4,1.48,1.48,0,0,0-1.19-.5,1.68,1.68,0,0,0-1.25.53A2.39,2.39,0,0,0,49,50.46Z"/><path class="cls-3" d="M63.67,54.33H58.84v-9.1h4.62v1H59.91v3H63.2v1H59.91v3.19h3.76Z"/><path class="cls-3" d="M70.68,54.33h-1V50.62q0-2.07-1.51-2.07a1.64,1.64,0,0,0-1.29.59,2.18,2.18,0,0,0-.51,1.48v3.71h-1v-6.5h1v1.08h0a2.35,2.35,0,0,1,2.13-1.23,2,2,0,0,1,1.63.69,3.07,3.07,0,0,1,.56,2Z"/><path class="cls-3" d="M78.19,54.33h-1v-1.1h0a2.62,2.62,0,0,1-4.19.38,3.58,3.58,0,0,1-.73-2.38A3.9,3.9,0,0,1,73,48.65a2.68,2.68,0,0,1,2.16-1,2.09,2.09,0,0,1,1.95,1.05h0v-4h1Zm-1-2.94v-1a1.86,1.86,0,0,0-.52-1.33,1.74,1.74,0,0,0-1.32-.55,1.8,1.8,0,0,0-1.5.7,3.06,3.06,0,0,0-.54,1.93A2.75,2.75,0,0,0,73.78,53a1.71,1.71,0,0,0,1.41.65A1.78,1.78,0,0,0,76.6,53,2.35,2.35,0,0,0,77.14,51.39Z"/><path class="cls-3" d="M86.57,54.48a3,3,0,0,1-2.3-.91,3.37,3.37,0,0,1-.86-2.42,3.51,3.51,0,0,1,.9-2.56,3.22,3.22,0,0,1,2.42-.92,2.92,2.92,0,0,1,2.27.89,3.56,3.56,0,0,1,.82,2.48,3.49,3.49,0,0,1-.88,2.49A3.08,3.08,0,0,1,86.57,54.48Zm.08-5.93a2,2,0,0,0-1.59.68,2.8,2.8,0,0,0-.58,1.88,2.64,2.64,0,0,0,.59,1.82,2,2,0,0,0,1.58.67A1.9,1.9,0,0,0,88.2,53a2.84,2.84,0,0,0,.54-1.86,2.88,2.88,0,0,0-.54-1.88A1.89,1.89,0,0,0,86.65,48.55Z"/><path class="cls-3" d="M94.45,45.62a1.39,1.39,0,0,0-.69-.17q-1.09,0-1.09,1.38v1h1.52v.89H92.66v5.61h-1V48.72H90.52v-.89h1.11V46.78a2.19,2.19,0,0,1,.59-1.62,2,2,0,0,1,1.47-.59,2,2,0,0,1,.75.11Z"/><path class="cls-3" d="M103.73,54.33H99v-9.1h1.07v8.14h3.66Z"/><path class="cls-3" d="M105.52,46.18A.66.66,0,0,1,105,46a.64.64,0,0,1-.2-.48.67.67,0,0,1,.67-.68A.67.67,0,0,1,106,45a.68.68,0,0,1,0,1A.66.66,0,0,1,105.52,46.18Zm.51,8.15h-1v-6.5h1Z"/><path class="cls-3" d="M113.53,54.33h-1V50.62q0-2.07-1.51-2.07a1.64,1.64,0,0,0-1.29.59,2.18,2.18,0,0,0-.51,1.48v3.71h-1v-6.5h1v1.08h0a2.35,2.35,0,0,1,2.13-1.23,2,2,0,0,1,1.63.69,3.07,3.07,0,0,1,.57,2Z"/><path class="cls-3" d="M120.71,51.34h-4.59a2.43,2.43,0,0,0,.58,1.68,2,2,0,0,0,1.54.59,3.19,3.19,0,0,0,2-.72v1a3.77,3.77,0,0,1-2.27.62,2.75,2.75,0,0,1-2.17-.89,3.63,3.63,0,0,1-.79-2.49,3.55,3.55,0,0,1,.86-2.47,2.76,2.76,0,0,1,2.14-1,2.44,2.44,0,0,1,2,.83,3.44,3.44,0,0,1,.7,2.29Zm-1.07-.88a2.12,2.12,0,0,0-.44-1.4,1.48,1.48,0,0,0-1.19-.5,1.68,1.68,0,0,0-1.25.53,2.4,2.4,0,0,0-.63,1.38Z"/><path class="cls-3" d="M125.56,54V52.71a2.45,2.45,0,0,0,.52.34,4.17,4.17,0,0,0,.63.26,5,5,0,0,0,.67.16,3.72,3.72,0,0,0,.62.06,2.44,2.44,0,0,0,1.47-.36,1.37,1.37,0,0,0,.32-1.69,1.82,1.82,0,0,0-.45-.5,4.46,4.46,0,0,0-.68-.43l-.84-.43c-.32-.16-.61-.32-.89-.49a3.85,3.85,0,0,1-.72-.54,2.28,2.28,0,0,1-.48-.68,2.3,2.3,0,0,1,.1-2,2.33,2.33,0,0,1,.72-.76,3.27,3.27,0,0,1,1-.45,4.67,4.67,0,0,1,1.16-.15,4.45,4.45,0,0,1,2,.32v1.2a3.56,3.56,0,0,0-2.07-.56,3.39,3.39,0,0,0-.7.07,2,2,0,0,0-.62.24,1.36,1.36,0,0,0-.44.42,1.13,1.13,0,0,0-.17.63,1.3,1.3,0,0,0,.13.6,1.46,1.46,0,0,0,.38.46,3.8,3.8,0,0,0,.62.41l.84.43q.49.24.93.51a4.22,4.22,0,0,1,.77.59,2.6,2.6,0,0,1,.52.72,2,2,0,0,1,.19.9,2.29,2.29,0,0,1-.26,1.14,2.16,2.16,0,0,1-.71.76,3.1,3.1,0,0,1-1,.42,5.63,5.63,0,0,1-1.23.13l-.53,0c-.21,0-.43-.06-.65-.1a5.16,5.16,0,0,1-.62-.17A1.94,1.94,0,0,1,125.56,54Z"/><path class="cls-3" d="M138,51.34h-4.59A2.43,2.43,0,0,0,134,53a2,2,0,0,0,1.54.59,3.19,3.19,0,0,0,2-.72v1a3.77,3.77,0,0,1-2.27.62,2.75,2.75,0,0,1-2.17-.89,3.63,3.63,0,0,1-.79-2.49,3.55,3.55,0,0,1,.86-2.47,2.76,2.76,0,0,1,2.14-1,2.44,2.44,0,0,1,2,.83,3.44,3.44,0,0,1,.7,2.29Zm-1.07-.88a2.12,2.12,0,0,0-.44-1.4,1.48,1.48,0,0,0-1.19-.5,1.68,1.68,0,0,0-1.25.53,2.4,2.4,0,0,0-.63,1.38Z"/><path class="cls-3" d="M145.1,57.32h-1V53.21h0a2.33,2.33,0,0,1-2.22,1.27,2.44,2.44,0,0,1-2-.87,3.56,3.56,0,0,1-.74-2.38,3.9,3.9,0,0,1,.81-2.59,2.7,2.7,0,0,1,2.18-1A2,2,0,0,1,144,48.73h0v-.9h1Zm-1-5.92v-.95a1.89,1.89,0,0,0-.52-1.35,1.76,1.76,0,0,0-1.33-.55,1.78,1.78,0,0,0-1.48.7,3.1,3.1,0,0,0-.55,2A2.69,2.69,0,0,0,140.7,53a1.68,1.68,0,0,0,1.36.64,1.83,1.83,0,0,0,1.46-.62A2.31,2.31,0,0,0,144.06,51.4Z"/><path class="cls-3" d="M152.46,54.33h-1v-1h0a2.14,2.14,0,0,1-2,1.18q-2.32,0-2.32-2.77V47.83h1v3.72q0,2.06,1.57,2.06a1.59,1.59,0,0,0,1.25-.56,2.15,2.15,0,0,0,.49-1.47V47.83h1Z"/><path class="cls-3" d="M159.79,51.34H155.2a2.43,2.43,0,0,0,.58,1.68,2,2,0,0,0,1.54.59,3.19,3.19,0,0,0,2-.72v1a3.77,3.77,0,0,1-2.27.62,2.75,2.75,0,0,1-2.17-.89,3.63,3.63,0,0,1-.79-2.49,3.55,3.55,0,0,1,.86-2.47,2.76,2.76,0,0,1,2.14-1,2.44,2.44,0,0,1,2,.83,3.44,3.44,0,0,1,.7,2.29Zm-1.07-.88a2.12,2.12,0,0,0-.44-1.4,1.48,1.48,0,0,0-1.19-.5,1.68,1.68,0,0,0-1.25.53,2.4,2.4,0,0,0-.63,1.38Z"/><path class="cls-3" d="M166.76,54.33h-1V50.62q0-2.07-1.51-2.07a1.64,1.64,0,0,0-1.29.59,2.18,2.18,0,0,0-.51,1.48v3.71h-1v-6.5h1v1.08h0a2.34,2.34,0,0,1,2.13-1.23,2,2,0,0,1,1.63.69,3.07,3.07,0,0,1,.56,2Z"/><path class="cls-3" d="M173.15,54a3.38,3.38,0,0,1-1.78.45,2.94,2.94,0,0,1-2.24-.9,3.28,3.28,0,0,1-.85-2.35,3.6,3.6,0,0,1,.92-2.58,3.22,3.22,0,0,1,2.46-1,3.42,3.42,0,0,1,1.51.32v1.07a2.65,2.65,0,0,0-1.55-.51,2.09,2.09,0,0,0-1.63.71,2.71,2.71,0,0,0-.64,1.88,2.58,2.58,0,0,0,.6,1.8,2.07,2.07,0,0,0,1.61.66,2.61,2.61,0,0,0,1.6-.57Z"/><path class="cls-3" d="M180,51.34h-4.59a2.43,2.43,0,0,0,.58,1.68,2,2,0,0,0,1.54.59,3.19,3.19,0,0,0,2-.72v1a3.77,3.77,0,0,1-2.27.62,2.75,2.75,0,0,1-2.17-.89,3.63,3.63,0,0,1-.79-2.49,3.55,3.55,0,0,1,.86-2.47,2.76,2.76,0,0,1,2.14-1,2.44,2.44,0,0,1,2,.83,3.44,3.44,0,0,1,.7,2.29Zm-1.07-.88a2.12,2.12,0,0,0-.44-1.4,1.48,1.48,0,0,0-1.19-.5,1.68,1.68,0,0,0-1.25.53,2.4,2.4,0,0,0-.63,1.38Z"/><path class="cls-3" d="M17.65,75.95a5.34,5.34,0,0,1-2.51.53A4.06,4.06,0,0,1,12,75.23,4.61,4.61,0,0,1,10.86,72a4.83,4.83,0,0,1,1.31-3.53,4.46,4.46,0,0,1,3.33-1.35,5.36,5.36,0,0,1,2.15.37v1.14A4.35,4.35,0,0,0,15.49,68a3.31,3.31,0,0,0-2.54,1,3.94,3.94,0,0,0-1,2.8,3.76,3.76,0,0,0,.91,2.65,3.1,3.1,0,0,0,2.39,1,4.48,4.48,0,0,0,2.37-.61Z"/><path class="cls-3" d="M24.76,76.33h-1V72.58q0-2-1.51-2a1.65,1.65,0,0,0-1.28.59,2.19,2.19,0,0,0-.52,1.51v3.68h-1V66.71h1v4.2h0a2.36,2.36,0,0,1,2.13-1.23q2.2,0,2.2,2.65Z"/><path class="cls-3" d="M31.37,76.33h-1v-1h0a2.18,2.18,0,0,1-2,1.17A2.14,2.14,0,0,1,26.79,76a1.78,1.78,0,0,1-.55-1.37q0-1.82,2.14-2.12l1.95-.27q0-1.66-1.34-1.66a3.2,3.2,0,0,0-2.12.8V70.29a4,4,0,0,1,2.21-.61q2.29,0,2.29,2.42Zm-1-3.29-1.57.22a2.55,2.55,0,0,0-1.09.36,1,1,0,0,0-.37.91,1,1,0,0,0,.34.78,1.31,1.31,0,0,0,.9.3,1.67,1.67,0,0,0,1.28-.54,1.94,1.94,0,0,0,.5-1.37Z"/><path class="cls-3" d="M38.73,76.33h-1V72.62q0-2.07-1.51-2.07a1.64,1.64,0,0,0-1.29.59,2.18,2.18,0,0,0-.51,1.48v3.71h-1v-6.5h1v1.08h0a2.35,2.35,0,0,1,2.13-1.23,2,2,0,0,1,1.63.69,3.07,3.07,0,0,1,.57,2Z"/><path class="cls-3" d="M46.24,75.81q0,3.58-3.43,3.58a4.6,4.6,0,0,1-2.11-.46v-1a4.33,4.33,0,0,0,2.09.61q2.4,0,2.4-2.55v-.71h0a2.63,2.63,0,0,1-4.19.38,3.47,3.47,0,0,1-.74-2.33,4,4,0,0,1,.8-2.63,2.66,2.66,0,0,1,2.18-1,2.12,2.12,0,0,1,1.95,1.05h0v-.9h1Zm-1-2.42v-1a1.86,1.86,0,0,0-.52-1.33,1.73,1.73,0,0,0-1.3-.55,1.81,1.81,0,0,0-1.51.7,3.14,3.14,0,0,0-.55,2A2.69,2.69,0,0,0,41.83,75a1.69,1.69,0,0,0,1.39.65A1.81,1.81,0,0,0,44.65,75,2.32,2.32,0,0,0,45.2,73.39Z"/><path class="cls-3" d="M53.57,73.34H49A2.43,2.43,0,0,0,49.56,75a2,2,0,0,0,1.54.59,3.19,3.19,0,0,0,2-.72v1a3.77,3.77,0,0,1-2.27.62,2.75,2.75,0,0,1-2.16-.89,3.62,3.62,0,0,1-.79-2.49,3.55,3.55,0,0,1,.86-2.47,2.76,2.76,0,0,1,2.14-1,2.45,2.45,0,0,1,2,.83,3.44,3.44,0,0,1,.7,2.29Zm-1.07-.88a2.12,2.12,0,0,0-.43-1.4,1.48,1.48,0,0,0-1.19-.5,1.68,1.68,0,0,0-1.25.53A2.39,2.39,0,0,0,49,72.46Z"/><path class="cls-3" d="M63.46,68.19H59.91v3.15H63.2v1H59.91v4H58.84v-9.1h4.62Z"/><path class="cls-3" d="M65.58,68.18a.66.66,0,0,1-.48-.19.64.64,0,0,1-.2-.48.67.67,0,0,1,.67-.68.67.67,0,0,1,.49.19.68.68,0,0,1,0,1A.66.66,0,0,1,65.58,68.18Zm.51,8.15h-1v-6.5h1Z"/><path class="cls-3" d="M69.24,76.33h-1V66.71h1Z"/><path class="cls-3" d="M76.57,73.34H72A2.43,2.43,0,0,0,72.57,75a2,2,0,0,0,1.54.59,3.19,3.19,0,0,0,2-.72v1a3.77,3.77,0,0,1-2.27.62,2.75,2.75,0,0,1-2.16-.89,3.62,3.62,0,0,1-.79-2.49,3.55,3.55,0,0,1,.86-2.47,2.76,2.76,0,0,1,2.14-1,2.45,2.45,0,0,1,2,.83,3.44,3.44,0,0,1,.7,2.29Zm-1.07-.88a2.12,2.12,0,0,0-.43-1.4,1.48,1.48,0,0,0-1.19-.5,1.68,1.68,0,0,0-1.25.53A2.39,2.39,0,0,0,72,72.46Z"/><path class="cls-3" d="M86.67,76.33H81.85v-9.1h4.62v1H82.91v3H86.2v1H82.91v3.19h3.76Z"/><path class="cls-3" d="M93.68,76.33h-1V72.62q0-2.07-1.51-2.07a1.64,1.64,0,0,0-1.29.59,2.18,2.18,0,0,0-.51,1.48v3.71h-1v-6.5h1v1.08h0a2.35,2.35,0,0,1,2.13-1.23,2,2,0,0,1,1.63.69,3.07,3.07,0,0,1,.56,2Z"/><path class="cls-3" d="M100.07,76a3.38,3.38,0,0,1-1.78.45,2.94,2.94,0,0,1-2.24-.9,3.28,3.28,0,0,1-.85-2.35,3.6,3.6,0,0,1,.92-2.58,3.22,3.22,0,0,1,2.46-1,3.41,3.41,0,0,1,1.51.32v1.07a2.64,2.64,0,0,0-1.55-.51,2.1,2.1,0,0,0-1.63.71,2.72,2.72,0,0,0-.64,1.88,2.58,2.58,0,0,0,.6,1.8,2.07,2.07,0,0,0,1.61.66,2.61,2.61,0,0,0,1.6-.57Z"/><path class="cls-3" d="M104.36,76.48a3,3,0,0,1-2.3-.91,3.37,3.37,0,0,1-.86-2.42,3.52,3.52,0,0,1,.9-2.56,3.22,3.22,0,0,1,2.42-.92,2.92,2.92,0,0,1,2.27.89,3.56,3.56,0,0,1,.81,2.48,3.49,3.49,0,0,1-.88,2.49A3.08,3.08,0,0,1,104.36,76.48Zm.08-5.93a2,2,0,0,0-1.59.68,2.81,2.81,0,0,0-.58,1.88,2.65,2.65,0,0,0,.59,1.82,2,2,0,0,0,1.58.67A1.9,1.9,0,0,0,106,75a2.83,2.83,0,0,0,.54-1.86,2.88,2.88,0,0,0-.54-1.88A1.89,1.89,0,0,0,104.44,70.55Z"/><path class="cls-3" d="M114.81,76.33h-1v-1.1h0a2.62,2.62,0,0,1-4.19.38,3.57,3.57,0,0,1-.73-2.38,3.9,3.9,0,0,1,.81-2.58,2.68,2.68,0,0,1,2.17-1,2.08,2.08,0,0,1,1.95,1.05h0v-4h1Zm-1-2.94v-1a1.86,1.86,0,0,0-.52-1.33,1.75,1.75,0,0,0-1.32-.55,1.8,1.8,0,0,0-1.5.7,3.06,3.06,0,0,0-.55,1.93,2.76,2.76,0,0,0,.52,1.77,1.71,1.71,0,0,0,1.41.65,1.78,1.78,0,0,0,1.41-.63A2.34,2.34,0,0,0,113.77,73.39Z"/><path class="cls-3" d="M117.45,68.18A.66.66,0,0,1,117,68a.64.64,0,0,1-.2-.48.67.67,0,0,1,.67-.68.67.67,0,0,1,.49.19.68.68,0,0,1,0,1A.66.66,0,0,1,117.45,68.18Zm.51,8.15h-1v-6.5h1Z"/><path class="cls-3" d="M125.46,76.33h-1V72.62q0-2.07-1.51-2.07a1.64,1.64,0,0,0-1.29.59,2.18,2.18,0,0,0-.51,1.48v3.71h-1v-6.5h1v1.08h0a2.35,2.35,0,0,1,2.13-1.23,2,2,0,0,1,1.63.69,3.07,3.07,0,0,1,.57,2Z"/><path class="cls-3" d="M133,75.81q0,3.58-3.43,3.58a4.6,4.6,0,0,1-2.11-.46v-1a4.33,4.33,0,0,0,2.09.61q2.4,0,2.4-2.55v-.71h0a2.63,2.63,0,0,1-4.19.38,3.47,3.47,0,0,1-.74-2.33,4,4,0,0,1,.8-2.63,2.66,2.66,0,0,1,2.18-1,2.12,2.12,0,0,1,1.95,1.05h0v-.9h1Zm-1-2.42v-1a1.86,1.86,0,0,0-.52-1.33,1.73,1.73,0,0,0-1.3-.55,1.81,1.81,0,0,0-1.51.7,3.14,3.14,0,0,0-.55,2,2.69,2.69,0,0,0,.52,1.74,1.69,1.69,0,0,0,1.39.65,1.81,1.81,0,0,0,1.42-.62A2.32,2.32,0,0,0,131.93,73.39Z"/><path class="cls-3" d="M17.65,97.95a5.34,5.34,0,0,1-2.51.53A4.06,4.06,0,0,1,12,97.23,4.61,4.61,0,0,1,10.86,94a4.83,4.83,0,0,1,1.31-3.53,4.46,4.46,0,0,1,3.33-1.35,5.36,5.36,0,0,1,2.15.37v1.14A4.35,4.35,0,0,0,15.49,90a3.31,3.31,0,0,0-2.54,1,3.94,3.94,0,0,0-1,2.8,3.76,3.76,0,0,0,.91,2.65,3.1,3.1,0,0,0,2.39,1,4.48,4.48,0,0,0,2.37-.61Z"/><path class="cls-3" d="M24.76,98.33h-1V94.58q0-2-1.51-2a1.65,1.65,0,0,0-1.28.59,2.19,2.19,0,0,0-.52,1.51v3.68h-1V88.71h1v4.2h0a2.36,2.36,0,0,1,2.13-1.23q2.2,0,2.2,2.65Z"/><path class="cls-3" d="M31.37,98.33h-1v-1h0a2.18,2.18,0,0,1-2,1.17A2.14,2.14,0,0,1,26.79,98a1.78,1.78,0,0,1-.55-1.37q0-1.82,2.14-2.12l1.95-.27q0-1.66-1.34-1.66a3.2,3.2,0,0,0-2.12.8V92.29a4,4,0,0,1,2.21-.61q2.29,0,2.29,2.42Zm-1-3.29-1.57.22a2.55,2.55,0,0,0-1.09.36,1,1,0,0,0-.37.91,1,1,0,0,0,.34.78,1.31,1.31,0,0,0,.9.3,1.67,1.67,0,0,0,1.28-.54,1.94,1.94,0,0,0,.5-1.37Z"/><path class="cls-3" d="M38.73,98.33h-1V94.62q0-2.07-1.51-2.07a1.64,1.64,0,0,0-1.29.59,2.18,2.18,0,0,0-.51,1.48v3.71h-1v-6.5h1v1.08h0a2.35,2.35,0,0,1,2.13-1.23,2,2,0,0,1,1.63.69,3.07,3.07,0,0,1,.57,2Z"/><path class="cls-3" d="M46.24,97.81q0,3.58-3.43,3.58a4.6,4.6,0,0,1-2.11-.46v-1a4.33,4.33,0,0,0,2.09.61q2.4,0,2.4-2.55v-.71h0a2.63,2.63,0,0,1-4.19.38,3.47,3.47,0,0,1-.74-2.33,4,4,0,0,1,.8-2.63,2.66,2.66,0,0,1,2.18-1,2.12,2.12,0,0,1,1.95,1.05h0v-.9h1Zm-1-2.42v-1a1.86,1.86,0,0,0-.52-1.33,1.73,1.73,0,0,0-1.3-.55,1.81,1.81,0,0,0-1.51.7,3.14,3.14,0,0,0-.55,2A2.69,2.69,0,0,0,41.83,97a1.69,1.69,0,0,0,1.39.65A1.81,1.81,0,0,0,44.65,97,2.32,2.32,0,0,0,45.2,95.39Z"/><path class="cls-3" d="M53.57,95.34H49A2.43,2.43,0,0,0,49.56,97a2,2,0,0,0,1.54.59,3.19,3.19,0,0,0,2-.72v1a3.77,3.77,0,0,1-2.27.62,2.75,2.75,0,0,1-2.16-.89,3.62,3.62,0,0,1-.79-2.49,3.55,3.55,0,0,1,.86-2.47,2.76,2.76,0,0,1,2.14-1,2.45,2.45,0,0,1,2,.83,3.44,3.44,0,0,1,.7,2.29Zm-1.07-.88a2.12,2.12,0,0,0-.43-1.4,1.48,1.48,0,0,0-1.19-.5,1.68,1.68,0,0,0-1.25.53A2.39,2.39,0,0,0,49,94.46Z"/><path class="cls-3" d="M63.57,98.33H58.84v-9.1h1.07v8.14h3.66Z"/><path class="cls-3" d="M69.48,98.33h-1v-1h0a2.18,2.18,0,0,1-2,1.17A2.14,2.14,0,0,1,64.89,98a1.78,1.78,0,0,1-.55-1.37q0-1.82,2.15-2.12l1.95-.27q0-1.66-1.34-1.66a3.2,3.2,0,0,0-2.12.8V92.29a4,4,0,0,1,2.21-.61q2.29,0,2.29,2.42Zm-1-3.29-1.57.22a2.55,2.55,0,0,0-1.09.36,1,1,0,0,0-.37.91,1,1,0,0,0,.34.78,1.31,1.31,0,0,0,.9.3,1.67,1.67,0,0,0,1.28-.54,1.94,1.94,0,0,0,.5-1.37Z"/><path class="cls-3" d="M76.83,98.33h-1V94.62q0-2.07-1.51-2.07a1.64,1.64,0,0,0-1.29.59,2.18,2.18,0,0,0-.51,1.48v3.71h-1v-6.5h1v1.08h0a2.34,2.34,0,0,1,2.13-1.23,2,2,0,0,1,1.63.69,3.07,3.07,0,0,1,.57,2Z"/><path class="cls-3" d="M84.34,97.81q0,3.58-3.43,3.58a4.61,4.61,0,0,1-2.11-.46v-1a4.33,4.33,0,0,0,2.1.61q2.4,0,2.4-2.55v-.71h0a2.63,2.63,0,0,1-4.19.38,3.47,3.47,0,0,1-.74-2.33,4,4,0,0,1,.8-2.63,2.66,2.66,0,0,1,2.18-1,2.12,2.12,0,0,1,1.95,1.05h0v-.9h1Zm-1-2.42v-1a1.86,1.86,0,0,0-.52-1.33,1.73,1.73,0,0,0-1.3-.55,1.81,1.81,0,0,0-1.51.7,3.13,3.13,0,0,0-.55,2A2.7,2.7,0,0,0,79.94,97a1.69,1.69,0,0,0,1.39.65A1.81,1.81,0,0,0,82.75,97,2.32,2.32,0,0,0,83.3,95.39Z"/><path class="cls-3" d="M91.71,98.33h-1v-1h0a2.14,2.14,0,0,1-2,1.18q-2.32,0-2.32-2.77V91.83h1v3.72q0,2.06,1.57,2.06A1.59,1.59,0,0,0,90.17,97a2.15,2.15,0,0,0,.49-1.47V91.83h1Z"/><path class="cls-3" d="M98.46,98.33h-1v-1h0a2.18,2.18,0,0,1-2,1.17A2.14,2.14,0,0,1,93.87,98a1.79,1.79,0,0,1-.55-1.37q0-1.82,2.15-2.12l1.95-.27q0-1.66-1.34-1.66a3.2,3.2,0,0,0-2.12.8V92.29a4,4,0,0,1,2.21-.61q2.29,0,2.29,2.42Zm-1-3.29-1.57.22a2.55,2.55,0,0,0-1.09.36,1,1,0,0,0-.37.91,1,1,0,0,0,.34.78,1.31,1.31,0,0,0,.9.3,1.67,1.67,0,0,0,1.28-.54,1.94,1.94,0,0,0,.5-1.37Z"/><path class="cls-3" d="M106,97.81q0,3.58-3.43,3.58a4.6,4.6,0,0,1-2.11-.46v-1a4.33,4.33,0,0,0,2.09.61q2.4,0,2.4-2.55v-.71h0a2.63,2.63,0,0,1-4.19.38,3.46,3.46,0,0,1-.74-2.33,4,4,0,0,1,.8-2.63,2.66,2.66,0,0,1,2.18-1,2.12,2.12,0,0,1,1.95,1.05h0v-.9h1Zm-1-2.42v-1a1.86,1.86,0,0,0-.52-1.33,1.73,1.73,0,0,0-1.3-.55,1.81,1.81,0,0,0-1.51.7,3.13,3.13,0,0,0-.55,2,2.69,2.69,0,0,0,.52,1.74,1.69,1.69,0,0,0,1.39.65,1.81,1.81,0,0,0,1.43-.62A2.32,2.32,0,0,0,104.93,95.39Z"/><path class="cls-3" d="M113.3,95.34h-4.59a2.43,2.43,0,0,0,.58,1.68,2,2,0,0,0,1.54.59,3.19,3.19,0,0,0,2-.72v1a3.77,3.77,0,0,1-2.27.62,2.75,2.75,0,0,1-2.17-.89,3.63,3.63,0,0,1-.79-2.49,3.55,3.55,0,0,1,.86-2.47,2.76,2.76,0,0,1,2.14-1,2.44,2.44,0,0,1,2,.83,3.44,3.44,0,0,1,.7,2.29Zm-1.07-.88a2.12,2.12,0,0,0-.44-1.4,1.48,1.48,0,0,0-1.19-.5,1.68,1.68,0,0,0-1.25.53,2.4,2.4,0,0,0-.63,1.38Z"/><path class="cls-3" d="M127.86,98.33h-1.06V92.22q0-.72.09-1.77h0a5.69,5.69,0,0,1-.27.88l-3.11,7H123l-3.1-6.94a5.42,5.42,0,0,1-.27-.93h0q0,.54.05,1.78v6.09h-1v-9.1H120l2.79,6.35a8.11,8.11,0,0,1,.42,1.09h0q.27-.75.44-1.12l2.85-6.32h1.33Z"/><path class="cls-3" d="M132.83,98.48a3,3,0,0,1-2.3-.91,3.37,3.37,0,0,1-.86-2.42,3.52,3.52,0,0,1,.9-2.56,3.22,3.22,0,0,1,2.42-.92,2.92,2.92,0,0,1,2.27.89,3.56,3.56,0,0,1,.81,2.48,3.49,3.49,0,0,1-.88,2.49A3.08,3.08,0,0,1,132.83,98.48Zm.08-5.93a2,2,0,0,0-1.59.68,2.81,2.81,0,0,0-.58,1.88,2.65,2.65,0,0,0,.59,1.82,2,2,0,0,0,1.58.67,1.9,1.9,0,0,0,1.55-.65,2.83,2.83,0,0,0,.54-1.86,2.88,2.88,0,0,0-.54-1.88A1.89,1.89,0,0,0,132.9,92.55Z"/><path class="cls-3" d="M143.27,98.33h-1v-1.1h0a2.62,2.62,0,0,1-4.19.38,3.57,3.57,0,0,1-.73-2.38,3.9,3.9,0,0,1,.81-2.58,2.68,2.68,0,0,1,2.17-1,2.08,2.08,0,0,1,1.95,1.05h0v-4h1Zm-1-2.94v-1a1.86,1.86,0,0,0-.52-1.33,1.75,1.75,0,0,0-1.32-.55,1.8,1.8,0,0,0-1.5.7,3.06,3.06,0,0,0-.55,1.93,2.76,2.76,0,0,0,.52,1.77,1.71,1.71,0,0,0,1.41.65,1.78,1.78,0,0,0,1.41-.63A2.34,2.34,0,0,0,142.23,95.39Z"/><path class="cls-3" d="M150.61,95.34H146A2.43,2.43,0,0,0,146.6,97a2,2,0,0,0,1.54.59,3.19,3.19,0,0,0,2-.72v1a3.77,3.77,0,0,1-2.27.62,2.74,2.74,0,0,1-2.16-.89,3.62,3.62,0,0,1-.79-2.49,3.55,3.55,0,0,1,.86-2.47,2.76,2.76,0,0,1,2.14-1,2.45,2.45,0,0,1,2,.83,3.44,3.44,0,0,1,.7,2.29Zm-1.07-.88a2.11,2.11,0,0,0-.44-1.4,1.48,1.48,0,0,0-1.19-.5,1.68,1.68,0,0,0-1.25.53,2.38,2.38,0,0,0-.63,1.38Z"/><path class="cls-3" d="M17.65,119.95a5.34,5.34,0,0,1-2.51.53A4.06,4.06,0,0,1,12,119.23,4.61,4.61,0,0,1,10.86,116a4.83,4.83,0,0,1,1.31-3.53,4.46,4.46,0,0,1,3.33-1.35,5.36,5.36,0,0,1,2.15.37v1.14a4.35,4.35,0,0,0-2.16-.55,3.31,3.31,0,0,0-2.54,1,3.94,3.94,0,0,0-1,2.8,3.76,3.76,0,0,0,.91,2.65,3.1,3.1,0,0,0,2.39,1,4.48,4.48,0,0,0,2.37-.61Z"/><path class="cls-3" d="M20.4,120.33h-1v-9.62h1Z"/><path class="cls-3" d="M27.73,117.34H23.14a2.43,2.43,0,0,0,.58,1.68,2,2,0,0,0,1.54.59,3.19,3.19,0,0,0,2-.72v1a3.77,3.77,0,0,1-2.27.62,2.75,2.75,0,0,1-2.17-.89,3.63,3.63,0,0,1-.79-2.49,3.55,3.55,0,0,1,.86-2.47,2.76,2.76,0,0,1,2.14-1,2.44,2.44,0,0,1,2,.83,3.44,3.44,0,0,1,.7,2.29Zm-1.07-.88a2.12,2.12,0,0,0-.44-1.4,1.48,1.48,0,0,0-1.19-.5,1.68,1.68,0,0,0-1.25.53,2.4,2.4,0,0,0-.63,1.38Z"/><path class="cls-3" d="M34,120.33h-1v-1h0a2.18,2.18,0,0,1-2,1.17,2.14,2.14,0,0,1-1.52-.51,1.78,1.78,0,0,1-.55-1.37q0-1.82,2.14-2.12l1.95-.27q0-1.66-1.34-1.66a3.2,3.2,0,0,0-2.12.8v-1.07a4,4,0,0,1,2.21-.61q2.29,0,2.29,2.42Zm-1-3.29-1.57.22a2.55,2.55,0,0,0-1.09.36,1,1,0,0,0-.37.91,1,1,0,0,0,.34.78,1.31,1.31,0,0,0,.9.3,1.67,1.67,0,0,0,1.28-.54,1.94,1.94,0,0,0,.5-1.37Z"/><path class="cls-3" d="M39.31,114.88a1.28,1.28,0,0,0-.79-.21,1.33,1.33,0,0,0-1.12.63A2.92,2.92,0,0,0,37,117v3.31h-1v-6.5h1v1.34h0a2.27,2.27,0,0,1,.68-1.07,1.55,1.55,0,0,1,1-.38,1.7,1.7,0,0,1,.62.09Z"/><path class="cls-3" d="M49,120.33H44.14v-9.1h4.62v1H45.21v3H48.5v1H45.21v3.19H49Z"/><path class="cls-3" d="M56.13,120.33h-1v-1.1h0a2.4,2.4,0,0,1-2.23,1.26,2.43,2.43,0,0,1-2-.87,3.58,3.58,0,0,1-.73-2.38,3.9,3.9,0,0,1,.81-2.58,2.68,2.68,0,0,1,2.16-1,2.08,2.08,0,0,1,1.95,1.05h0v-4h1Zm-1-2.94v-1a1.86,1.86,0,0,0-.52-1.33,1.74,1.74,0,0,0-1.32-.55,1.8,1.8,0,0,0-1.5.7,3.06,3.06,0,0,0-.55,1.93,2.76,2.76,0,0,0,.52,1.77,1.71,1.71,0,0,0,1.41.65,1.78,1.78,0,0,0,1.41-.63A2.34,2.34,0,0,0,55.09,117.39Z"/><path class="cls-3" d="M58.77,112.18a.66.66,0,0,1-.48-.19.64.64,0,0,1-.2-.48.67.67,0,0,1,.67-.68.67.67,0,0,1,.49.19.68.68,0,0,1,0,1A.66.66,0,0,1,58.77,112.18Zm.51,8.15h-1v-6.5h1Z"/><path class="cls-3" d="M64.4,120.27a2,2,0,0,1-1,.2q-1.71,0-1.71-1.9v-3.85H60.6v-.89h1.12v-1.59l1-.34v1.92H64.4v.89H62.76v3.66a1.52,1.52,0,0,0,.22.93.89.89,0,0,0,.74.28,1.1,1.1,0,0,0,.68-.22Z"/><path class="cls-3" d="M68.4,120.48a3,3,0,0,1-2.3-.91,3.37,3.37,0,0,1-.86-2.42,3.52,3.52,0,0,1,.89-2.56,3.22,3.22,0,0,1,2.42-.92,2.92,2.92,0,0,1,2.27.89,3.55,3.55,0,0,1,.82,2.48,3.49,3.49,0,0,1-.88,2.49A3.08,3.08,0,0,1,68.4,120.48Zm.08-5.93a2,2,0,0,0-1.59.68,2.81,2.81,0,0,0-.58,1.88,2.65,2.65,0,0,0,.59,1.82,2,2,0,0,0,1.58.67A1.9,1.9,0,0,0,70,119a2.84,2.84,0,0,0,.54-1.86,2.88,2.88,0,0,0-.54-1.88A1.89,1.89,0,0,0,68.48,114.55Z"/><path class="cls-3" d="M76.69,114.88a1.27,1.27,0,0,0-.79-.21,1.33,1.33,0,0,0-1.11.63,2.91,2.91,0,0,0-.45,1.71v3.31h-1v-6.5h1v1.34h0A2.27,2.27,0,0,1,75,114.1a1.55,1.55,0,0,1,1-.38,1.7,1.7,0,0,1,.62.09Z"/><path class="cls-3" d="M88.37,120.33H87.3v-4.15H82.59v4.15H81.52v-9.1h1.07v4H87.3v-4h1.07Z"/><path class="cls-3" d="M91.15,112.18a.66.66,0,0,1-.48-.19.64.64,0,0,1-.2-.48.67.67,0,0,1,.67-.68.67.67,0,0,1,.49.19.68.68,0,0,1,0,1A.66.66,0,0,1,91.15,112.18Zm.51,8.15h-1v-6.5h1Z"/><path class="cls-3" d="M93.37,120.1V119a3.09,3.09,0,0,0,1.87.63q1.37,0,1.37-.91a.79.79,0,0,0-.12-.44,1.17,1.17,0,0,0-.32-.32,2.44,2.44,0,0,0-.47-.25l-.58-.23a7.45,7.45,0,0,1-.76-.35,2.3,2.3,0,0,1-.55-.39,1.47,1.47,0,0,1-.33-.5,1.76,1.76,0,0,1-.11-.65,1.56,1.56,0,0,1,.21-.81,1.85,1.85,0,0,1,.56-.59,2.6,2.6,0,0,1,.8-.36,3.52,3.52,0,0,1,.92-.12,3.74,3.74,0,0,1,1.51.29V115a2.94,2.94,0,0,0-1.65-.47,2,2,0,0,0-.53.07,1.3,1.3,0,0,0-.4.19.87.87,0,0,0-.26.29.77.77,0,0,0-.09.37.9.9,0,0,0,.09.42.94.94,0,0,0,.27.3,2,2,0,0,0,.43.24l.58.23a8.15,8.15,0,0,1,.78.34,2.64,2.64,0,0,1,.58.39,1.53,1.53,0,0,1,.37.5,1.63,1.63,0,0,1,.13.68,1.61,1.61,0,0,1-.21.84,1.84,1.84,0,0,1-.57.59,2.61,2.61,0,0,1-.82.35,4,4,0,0,1-1,.11A3.69,3.69,0,0,1,93.37,120.1Z"/><path class="cls-3" d="M102.29,120.27a2,2,0,0,1-1,.2q-1.71,0-1.71-1.9v-3.85H98.5v-.89h1.12v-1.59l1-.34v1.92h1.64v.89h-1.64v3.66a1.52,1.52,0,0,0,.22.93.88.88,0,0,0,.74.28,1.09,1.09,0,0,0,.68-.22Z"/><path class="cls-3" d="M106.3,120.48a3,3,0,0,1-2.3-.91,3.37,3.37,0,0,1-.86-2.42,3.51,3.51,0,0,1,.9-2.56,3.22,3.22,0,0,1,2.42-.92,2.92,2.92,0,0,1,2.27.89,3.56,3.56,0,0,1,.82,2.48,3.49,3.49,0,0,1-.88,2.49A3.08,3.08,0,0,1,106.3,120.48Zm.08-5.93a2,2,0,0,0-1.59.68,2.8,2.8,0,0,0-.58,1.88,2.64,2.64,0,0,0,.59,1.82,2,2,0,0,0,1.58.67,1.9,1.9,0,0,0,1.55-.65,2.84,2.84,0,0,0,.54-1.86,2.88,2.88,0,0,0-.54-1.88A1.89,1.89,0,0,0,106.38,114.55Z"/><path class="cls-3" d="M114.59,114.88a1.27,1.27,0,0,0-.79-.21,1.33,1.33,0,0,0-1.11.63,2.91,2.91,0,0,0-.45,1.71v3.31h-1v-6.5h1v1.34h0a2.27,2.27,0,0,1,.68-1.07,1.55,1.55,0,0,1,1-.38,1.69,1.69,0,0,1,.62.09Z"/><path class="cls-3" d="M121.41,113.83l-3,7.54q-.8,2-2.25,2a2.36,2.36,0,0,1-.68-.08v-.93a1.93,1.93,0,0,0,.62.11,1.28,1.28,0,0,0,1.18-.94l.52-1.23-2.54-6.49h1.16l1.76,5q0,.1.13.5h0q0-.15.13-.48l1.85-5Z"/><path class="cls-3" d="M17.65,141.95a5.34,5.34,0,0,1-2.51.53A4.06,4.06,0,0,1,12,141.23,4.61,4.61,0,0,1,10.86,138a4.83,4.83,0,0,1,1.31-3.53,4.46,4.46,0,0,1,3.33-1.35,5.36,5.36,0,0,1,2.15.37v1.14a4.35,4.35,0,0,0-2.16-.55,3.31,3.31,0,0,0-2.54,1,3.94,3.94,0,0,0-1,2.8,3.76,3.76,0,0,0,.91,2.65,3.1,3.1,0,0,0,2.39,1,4.48,4.48,0,0,0,2.37-.61Z"/><path class="cls-3" d="M20.4,142.33h-1v-9.62h1Z"/><path class="cls-3" d="M25.23,142.48a3,3,0,0,1-2.3-.91,3.37,3.37,0,0,1-.86-2.42,3.51,3.51,0,0,1,.9-2.56,3.22,3.22,0,0,1,2.42-.92,2.92,2.92,0,0,1,2.27.89,3.56,3.56,0,0,1,.82,2.48,3.49,3.49,0,0,1-.88,2.49A3.08,3.08,0,0,1,25.23,142.48Zm.08-5.93a2,2,0,0,0-1.59.68,2.8,2.8,0,0,0-.58,1.88,2.64,2.64,0,0,0,.59,1.82,2,2,0,0,0,1.58.67,1.9,1.9,0,0,0,1.55-.65,2.84,2.84,0,0,0,.54-1.86,2.88,2.88,0,0,0-.54-1.88A1.89,1.89,0,0,0,25.3,136.55Z"/><path class="cls-3" d="M29.73,142.1V141a3.09,3.09,0,0,0,1.87.63q1.37,0,1.37-.91a.8.8,0,0,0-.12-.44,1.16,1.16,0,0,0-.32-.32,2.46,2.46,0,0,0-.47-.25l-.58-.23a7.47,7.47,0,0,1-.76-.35,2.29,2.29,0,0,1-.55-.39,1.47,1.47,0,0,1-.33-.5,1.76,1.76,0,0,1-.11-.65,1.56,1.56,0,0,1,.21-.81,1.87,1.87,0,0,1,.56-.59,2.6,2.6,0,0,1,.8-.36,3.51,3.51,0,0,1,.92-.12,3.74,3.74,0,0,1,1.51.29V137a2.94,2.94,0,0,0-1.65-.47,1.94,1.94,0,0,0-.53.07,1.3,1.3,0,0,0-.4.19.86.86,0,0,0-.26.29.77.77,0,0,0-.09.37.9.9,0,0,0,.09.42.92.92,0,0,0,.27.3,2.06,2.06,0,0,0,.43.24l.58.23A8.23,8.23,0,0,1,33,139a2.64,2.64,0,0,1,.58.39,1.52,1.52,0,0,1,.37.5,1.8,1.8,0,0,1-.08,1.52,1.82,1.82,0,0,1-.57.59,2.61,2.61,0,0,1-.82.35,4,4,0,0,1-1,.11A3.69,3.69,0,0,1,29.73,142.1Z"/><path class="cls-3" d="M40.87,139.34H36.28a2.43,2.43,0,0,0,.58,1.68,2,2,0,0,0,1.54.59,3.19,3.19,0,0,0,2-.72v1a3.77,3.77,0,0,1-2.27.62A2.74,2.74,0,0,1,36,141.6a3.62,3.62,0,0,1-.79-2.49,3.55,3.55,0,0,1,.86-2.47,2.76,2.76,0,0,1,2.14-1,2.45,2.45,0,0,1,2,.83,3.44,3.44,0,0,1,.7,2.29Zm-1.07-.88a2.11,2.11,0,0,0-.44-1.4,1.48,1.48,0,0,0-1.19-.5,1.68,1.68,0,0,0-1.25.53,2.38,2.38,0,0,0-.63,1.38Z"/><path class="cls-3" d="M53.48,142.33H52.17l-4.68-7.26a3,3,0,0,1-.29-.57h0a9.48,9.48,0,0,1,.05,1.25v6.58H46.14v-9.1h1.38l4.56,7.14c.19.3.31.5.37.61h0a9.73,9.73,0,0,1-.06-1.34v-6.41h1.07Z"/><path class="cls-3" d="M58.44,142.48a3,3,0,0,1-2.3-.91,3.37,3.37,0,0,1-.86-2.42,3.52,3.52,0,0,1,.89-2.56,3.22,3.22,0,0,1,2.42-.92,2.92,2.92,0,0,1,2.27.89,3.55,3.55,0,0,1,.82,2.48,3.49,3.49,0,0,1-.88,2.49A3.08,3.08,0,0,1,58.44,142.48Zm.08-5.93a2,2,0,0,0-1.59.68,2.8,2.8,0,0,0-.58,1.88,2.65,2.65,0,0,0,.59,1.82,2,2,0,0,0,1.58.67,1.9,1.9,0,0,0,1.55-.65,2.84,2.84,0,0,0,.54-1.86,2.89,2.89,0,0,0-.54-1.88A1.89,1.89,0,0,0,58.52,136.55Z"/><path class="cls-3" d="M66.36,142.27a2,2,0,0,1-1,.2q-1.71,0-1.71-1.9v-3.85H62.56v-.89h1.12v-1.59l1-.34v1.92h1.64v.89H64.72v3.66a1.52,1.52,0,0,0,.22.93.89.89,0,0,0,.74.28,1.1,1.1,0,0,0,.68-.22Z"/><path class="cls-3" d="M68.28,134.18a.66.66,0,0,1-.48-.19.64.64,0,0,1-.2-.48.67.67,0,0,1,.67-.68.67.67,0,0,1,.48.19.67.67,0,0,1,0,1A.66.66,0,0,1,68.28,134.18Zm.51,8.15h-1v-6.5h1Z"/><path class="cls-3" d="M74.11,133.62a1.39,1.39,0,0,0-.69-.17q-1.09,0-1.09,1.38v1h1.52v.89H72.33v5.61h-1v-5.61H70.18v-.89h1.11v-1.05a2.19,2.19,0,0,1,.59-1.62,2,2,0,0,1,1.47-.59,2,2,0,0,1,.75.11Z"/><path class="cls-3" d="M75.5,134.18A.66.66,0,0,1,75,134a.64.64,0,0,1-.2-.48.67.67,0,0,1,.67-.68A.67.67,0,0,1,76,133a.68.68,0,0,1,0,1A.66.66,0,0,1,75.5,134.18Zm.51,8.15H75v-6.5h1Z"/><path class="cls-3" d="M82.55,142a3.38,3.38,0,0,1-1.78.45,2.94,2.94,0,0,1-2.24-.9,3.28,3.28,0,0,1-.85-2.35,3.6,3.6,0,0,1,.92-2.58,3.22,3.22,0,0,1,2.46-1,3.41,3.41,0,0,1,1.51.32v1.07a2.64,2.64,0,0,0-1.55-.51,2.1,2.1,0,0,0-1.63.71,2.71,2.71,0,0,0-.64,1.88,2.58,2.58,0,0,0,.6,1.8,2.07,2.07,0,0,0,1.61.66,2.61,2.61,0,0,0,1.6-.57Z"/><path class="cls-3" d="M88.77,142.33h-1v-1h0a2.18,2.18,0,0,1-2,1.17,2.14,2.14,0,0,1-1.52-.51,1.78,1.78,0,0,1-.55-1.37q0-1.82,2.15-2.12l1.95-.27q0-1.66-1.34-1.66a3.2,3.2,0,0,0-2.12.8v-1.07a4,4,0,0,1,2.21-.61q2.29,0,2.29,2.42Zm-1-3.29-1.57.22a2.55,2.55,0,0,0-1.09.36,1,1,0,0,0-.37.91,1,1,0,0,0,.34.78,1.31,1.31,0,0,0,.9.3,1.67,1.67,0,0,0,1.28-.54,1.94,1.94,0,0,0,.5-1.37Z"/><path class="cls-3" d="M93.75,142.27a2,2,0,0,1-1,.2q-1.71,0-1.71-1.9v-3.85H90v-.89h1.12v-1.59l1-.34v1.92h1.64v.89H92.11v3.66a1.52,1.52,0,0,0,.22.93.89.89,0,0,0,.74.28,1.1,1.1,0,0,0,.68-.22Z"/><path class="cls-3" d="M95.67,134.18a.66.66,0,0,1-.48-.19.64.64,0,0,1-.2-.48.67.67,0,0,1,.67-.68.67.67,0,0,1,.49.19.68.68,0,0,1,0,1A.66.66,0,0,1,95.67,134.18Zm.51,8.15h-1v-6.5h1Z"/><path class="cls-3" d="M101,142.48a3,3,0,0,1-2.3-.91,3.37,3.37,0,0,1-.86-2.42,3.52,3.52,0,0,1,.89-2.56,3.22,3.22,0,0,1,2.42-.92,2.92,2.92,0,0,1,2.27.89,3.55,3.55,0,0,1,.82,2.48,3.49,3.49,0,0,1-.88,2.49A3.08,3.08,0,0,1,101,142.48Zm.08-5.93a2,2,0,0,0-1.59.68,2.81,2.81,0,0,0-.58,1.88,2.65,2.65,0,0,0,.59,1.82,2,2,0,0,0,1.58.67,1.9,1.9,0,0,0,1.55-.65,2.84,2.84,0,0,0,.54-1.86,2.88,2.88,0,0,0-.54-1.88A1.89,1.89,0,0,0,101.08,136.55Z"/><path class="cls-3" d="M111.3,142.33h-1v-3.71q0-2.07-1.51-2.07a1.64,1.64,0,0,0-1.29.59,2.18,2.18,0,0,0-.51,1.48v3.71h-1v-6.5h1v1.08h0a2.35,2.35,0,0,1,2.13-1.23,2,2,0,0,1,1.63.69,3.07,3.07,0,0,1,.56,2Z"/><path class="cls-3" d="M126.24,142.33h-1.06v-6.11q0-.72.09-1.77h0a5.6,5.6,0,0,1-.27.88l-3.11,7h-.52l-3.1-6.94a5.53,5.53,0,0,1-.27-.93h0q.05.54.05,1.78v6.09h-1v-9.1h1.41l2.79,6.35a8.11,8.11,0,0,1,.42,1.09h0q.27-.75.44-1.12l2.85-6.32h1.33Z"/><path class="cls-3" d="M133.72,139.34h-4.59a2.43,2.43,0,0,0,.58,1.68,2,2,0,0,0,1.54.59,3.19,3.19,0,0,0,2-.72v1a3.77,3.77,0,0,1-2.27.62,2.74,2.74,0,0,1-2.16-.89,3.62,3.62,0,0,1-.79-2.49,3.55,3.55,0,0,1,.86-2.47,2.76,2.76,0,0,1,2.14-1,2.45,2.45,0,0,1,2,.83,3.44,3.44,0,0,1,.7,2.29Zm-1.07-.88a2.11,2.11,0,0,0-.44-1.4,1.48,1.48,0,0,0-1.19-.5,1.68,1.68,0,0,0-1.25.53,2.38,2.38,0,0,0-.63,1.38Z"/><path class="cls-3" d="M134.9,142.1V141a3.09,3.09,0,0,0,1.87.63q1.37,0,1.37-.91a.8.8,0,0,0-.12-.44,1.16,1.16,0,0,0-.32-.32,2.46,2.46,0,0,0-.47-.25l-.58-.23a7.47,7.47,0,0,1-.76-.35,2.29,2.29,0,0,1-.55-.39,1.47,1.47,0,0,1-.33-.5,1.76,1.76,0,0,1-.11-.65,1.56,1.56,0,0,1,.21-.81,1.87,1.87,0,0,1,.56-.59,2.6,2.6,0,0,1,.8-.36,3.51,3.51,0,0,1,.92-.12,3.74,3.74,0,0,1,1.51.29V137a2.94,2.94,0,0,0-1.65-.47,1.94,1.94,0,0,0-.53.07,1.3,1.3,0,0,0-.4.19.86.86,0,0,0-.26.29.77.77,0,0,0-.09.37.9.9,0,0,0,.09.42.92.92,0,0,0,.27.3,2.06,2.06,0,0,0,.43.24l.58.23a8.23,8.23,0,0,1,.77.34,2.64,2.64,0,0,1,.58.39,1.52,1.52,0,0,1,.37.5,1.8,1.8,0,0,1-.08,1.52,1.82,1.82,0,0,1-.57.59,2.61,2.61,0,0,1-.82.35,4,4,0,0,1-1,.11A3.69,3.69,0,0,1,134.9,142.1Z"/><path class="cls-3" d="M140.42,142.1V141a3.09,3.09,0,0,0,1.87.63q1.37,0,1.37-.91a.79.79,0,0,0-.12-.44,1.17,1.17,0,0,0-.32-.32,2.44,2.44,0,0,0-.47-.25l-.58-.23a7.45,7.45,0,0,1-.76-.35,2.3,2.3,0,0,1-.55-.39,1.47,1.47,0,0,1-.33-.5,1.76,1.76,0,0,1-.11-.65,1.56,1.56,0,0,1,.21-.81,1.85,1.85,0,0,1,.56-.59,2.6,2.6,0,0,1,.8-.36,3.52,3.52,0,0,1,.92-.12,3.74,3.74,0,0,1,1.51.29V137a2.94,2.94,0,0,0-1.65-.47,2,2,0,0,0-.53.07,1.3,1.3,0,0,0-.4.19.87.87,0,0,0-.26.29.77.77,0,0,0-.09.37.9.9,0,0,0,.09.42.94.94,0,0,0,.27.3,2,2,0,0,0,.43.24l.58.23a8.15,8.15,0,0,1,.78.34,2.64,2.64,0,0,1,.58.39,1.53,1.53,0,0,1,.37.5,1.63,1.63,0,0,1,.13.68,1.61,1.61,0,0,1-.21.84,1.84,1.84,0,0,1-.57.59,2.61,2.61,0,0,1-.82.35,4,4,0,0,1-1,.11A3.69,3.69,0,0,1,140.42,142.1Z"/><path class="cls-3" d="M151,142.33h-1v-1h0a2.18,2.18,0,0,1-2,1.17,2.14,2.14,0,0,1-1.52-.51,1.78,1.78,0,0,1-.55-1.37q0-1.82,2.15-2.12l1.95-.27q0-1.66-1.34-1.66a3.2,3.2,0,0,0-2.12.8v-1.07a4,4,0,0,1,2.21-.61q2.29,0,2.29,2.42Zm-1-3.29-1.57.22a2.55,2.55,0,0,0-1.09.36,1,1,0,0,0-.37.91,1,1,0,0,0,.34.78,1.31,1.31,0,0,0,.9.3,1.67,1.67,0,0,0,1.28-.54,1.94,1.94,0,0,0,.5-1.37Z"/><path class="cls-3" d="M158.49,141.81q0,3.58-3.43,3.58a4.6,4.6,0,0,1-2.11-.46v-1a4.33,4.33,0,0,0,2.09.61q2.4,0,2.4-2.55v-.71h0a2.63,2.63,0,0,1-4.19.38,3.47,3.47,0,0,1-.74-2.33,4,4,0,0,1,.8-2.63,2.66,2.66,0,0,1,2.18-1,2.12,2.12,0,0,1,1.95,1.05h0v-.9h1Zm-1-2.42v-1a1.86,1.86,0,0,0-.52-1.33,1.73,1.73,0,0,0-1.3-.55,1.81,1.81,0,0,0-1.51.7,3.14,3.14,0,0,0-.55,2,2.69,2.69,0,0,0,.52,1.74,1.69,1.69,0,0,0,1.39.65,1.81,1.81,0,0,0,1.42-.62A2.32,2.32,0,0,0,157.45,139.39Z"/><path class="cls-3" d="M165.82,139.34h-4.59a2.43,2.43,0,0,0,.58,1.68,2,2,0,0,0,1.54.59,3.19,3.19,0,0,0,2-.72v1a3.77,3.77,0,0,1-2.27.62,2.75,2.75,0,0,1-2.16-.89,3.62,3.62,0,0,1-.79-2.49,3.55,3.55,0,0,1,.86-2.47,2.76,2.76,0,0,1,2.14-1,2.45,2.45,0,0,1,2,.83,3.44,3.44,0,0,1,.7,2.29Zm-1.07-.88a2.12,2.12,0,0,0-.43-1.4,1.48,1.48,0,0,0-1.19-.5,1.68,1.68,0,0,0-1.25.53,2.39,2.39,0,0,0-.63,1.38Z"/><path class="cls-3" d="M167,142.1V141a3.09,3.09,0,0,0,1.87.63q1.37,0,1.37-.91a.79.79,0,0,0-.12-.44,1.17,1.17,0,0,0-.32-.32,2.44,2.44,0,0,0-.47-.25l-.58-.23a7.45,7.45,0,0,1-.76-.35,2.3,2.3,0,0,1-.55-.39,1.47,1.47,0,0,1-.33-.5,1.76,1.76,0,0,1-.11-.65,1.56,1.56,0,0,1,.21-.81,1.85,1.85,0,0,1,.56-.59,2.6,2.6,0,0,1,.8-.36,3.52,3.52,0,0,1,.92-.12A3.74,3.74,0,0,1,171,136V137a2.94,2.94,0,0,0-1.65-.47,2,2,0,0,0-.53.07,1.3,1.3,0,0,0-.4.19.87.87,0,0,0-.26.29.77.77,0,0,0-.09.37.9.9,0,0,0,.09.42.94.94,0,0,0,.27.3,2,2,0,0,0,.43.24l.58.23a8.15,8.15,0,0,1,.78.34,2.64,2.64,0,0,1,.58.39,1.53,1.53,0,0,1,.37.5,1.63,1.63,0,0,1,.13.68,1.61,1.61,0,0,1-.21.84,1.84,1.84,0,0,1-.57.59,2.61,2.61,0,0,1-.82.35,4,4,0,0,1-1,.11A3.69,3.69,0,0,1,167,142.1Z"/><path class="cls-3" d="M17.65,163.95a5.34,5.34,0,0,1-2.51.53A4.06,4.06,0,0,1,12,163.23,4.61,4.61,0,0,1,10.86,160a4.83,4.83,0,0,1,1.31-3.53,4.46,4.46,0,0,1,3.33-1.35,5.36,5.36,0,0,1,2.15.37v1.14a4.35,4.35,0,0,0-2.16-.55,3.31,3.31,0,0,0-2.54,1,3.94,3.94,0,0,0-1,2.8,3.76,3.76,0,0,0,.91,2.65,3.1,3.1,0,0,0,2.39,1,4.48,4.48,0,0,0,2.37-.61Z"/><path class="cls-3" d="M20.4,164.33h-1v-9.62h1Z"/><path class="cls-3" d="M25.23,164.48a3,3,0,0,1-2.3-.91,3.37,3.37,0,0,1-.86-2.42,3.51,3.51,0,0,1,.9-2.56,3.22,3.22,0,0,1,2.42-.92,2.92,2.92,0,0,1,2.27.89,3.56,3.56,0,0,1,.82,2.48,3.49,3.49,0,0,1-.88,2.49A3.08,3.08,0,0,1,25.23,164.48Zm.08-5.93a2,2,0,0,0-1.59.68,2.8,2.8,0,0,0-.58,1.88,2.64,2.64,0,0,0,.59,1.82,2,2,0,0,0,1.58.67,1.9,1.9,0,0,0,1.55-.65,2.84,2.84,0,0,0,.54-1.86,2.88,2.88,0,0,0-.54-1.88A1.89,1.89,0,0,0,25.3,158.55Z"/><path class="cls-3" d="M29.73,164.1V163a3.09,3.09,0,0,0,1.87.63q1.37,0,1.37-.91a.8.8,0,0,0-.12-.44,1.16,1.16,0,0,0-.32-.32,2.46,2.46,0,0,0-.47-.25l-.58-.23a7.47,7.47,0,0,1-.76-.35,2.29,2.29,0,0,1-.55-.39,1.47,1.47,0,0,1-.33-.5,1.76,1.76,0,0,1-.11-.65,1.56,1.56,0,0,1,.21-.81,1.87,1.87,0,0,1,.56-.59,2.6,2.6,0,0,1,.8-.36,3.51,3.51,0,0,1,.92-.12,3.74,3.74,0,0,1,1.51.29V159a2.94,2.94,0,0,0-1.65-.47,1.94,1.94,0,0,0-.53.07,1.3,1.3,0,0,0-.4.19.86.86,0,0,0-.26.29.77.77,0,0,0-.09.37.9.9,0,0,0,.09.42.92.92,0,0,0,.27.3,2.06,2.06,0,0,0,.43.24l.58.23A8.23,8.23,0,0,1,33,161a2.64,2.64,0,0,1,.58.39,1.52,1.52,0,0,1,.37.5,1.8,1.8,0,0,1-.08,1.52,1.82,1.82,0,0,1-.57.59,2.61,2.61,0,0,1-.82.35,4,4,0,0,1-1,.11A3.69,3.69,0,0,1,29.73,164.1Z"/><path class="cls-3" d="M40.87,161.34H36.28a2.43,2.43,0,0,0,.58,1.68,2,2,0,0,0,1.54.59,3.19,3.19,0,0,0,2-.72v1a3.77,3.77,0,0,1-2.27.62A2.74,2.74,0,0,1,36,163.6a3.62,3.62,0,0,1-.79-2.49,3.55,3.55,0,0,1,.86-2.47,2.76,2.76,0,0,1,2.14-1,2.45,2.45,0,0,1,2,.83,3.44,3.44,0,0,1,.7,2.29Zm-1.07-.88a2.11,2.11,0,0,0-.44-1.4,1.48,1.48,0,0,0-1.19-.5,1.68,1.68,0,0,0-1.25.53,2.38,2.38,0,0,0-.63,1.38Z"/><path class="cls-3" d="M56.93,155.23l-2.57,9.1H53.11l-1.87-6.65a4.11,4.11,0,0,1-.15-.93h0a4.67,4.67,0,0,1-.17.91L49,164.33H47.78l-2.67-9.1h1.17l1.94,7a4.63,4.63,0,0,1,.15.91h0a5.39,5.39,0,0,1,.2-.91l2-7h1l1.93,7a5,5,0,0,1,.15.85h0a5.15,5.15,0,0,1,.17-.88l1.86-7Z"/><path class="cls-3" d="M58.68,156.18a.66.66,0,0,1-.48-.19.64.64,0,0,1-.2-.48.67.67,0,0,1,.67-.68.67.67,0,0,1,.49.19.68.68,0,0,1,0,1A.66.66,0,0,1,58.68,156.18Zm.51,8.15h-1v-6.5h1Z"/><path class="cls-3" d="M66.69,164.33h-1v-3.71q0-2.07-1.51-2.07a1.64,1.64,0,0,0-1.29.59,2.18,2.18,0,0,0-.51,1.48v3.71h-1v-6.5h1v1.08h0a2.35,2.35,0,0,1,2.13-1.23,2,2,0,0,1,1.63.69,3.07,3.07,0,0,1,.56,2Z"/><path class="cls-3" d="M74.2,164.33h-1v-1.1h0a2.62,2.62,0,0,1-4.19.38,3.58,3.58,0,0,1-.73-2.38,3.9,3.9,0,0,1,.81-2.58,2.68,2.68,0,0,1,2.16-1,2.09,2.09,0,0,1,1.95,1.05h0v-4h1Zm-1-2.94v-1a1.86,1.86,0,0,0-.52-1.33,1.74,1.74,0,0,0-1.32-.55,1.8,1.8,0,0,0-1.5.7,3.06,3.06,0,0,0-.54,1.93A2.75,2.75,0,0,0,69.8,163a1.71,1.71,0,0,0,1.41.65,1.78,1.78,0,0,0,1.41-.63A2.35,2.35,0,0,0,73.16,161.39Z"/><path class="cls-3" d="M79,164.48a3,3,0,0,1-2.3-.91,3.37,3.37,0,0,1-.86-2.42,3.52,3.52,0,0,1,.9-2.56,3.22,3.22,0,0,1,2.42-.92,2.92,2.92,0,0,1,2.27.89,3.56,3.56,0,0,1,.81,2.48,3.49,3.49,0,0,1-.88,2.49A3.08,3.08,0,0,1,79,164.48Zm.08-5.93a2,2,0,0,0-1.59.68,2.81,2.81,0,0,0-.58,1.88,2.65,2.65,0,0,0,.59,1.82,2,2,0,0,0,1.58.67,1.9,1.9,0,0,0,1.55-.65,2.83,2.83,0,0,0,.54-1.86,2.88,2.88,0,0,0-.54-1.88A1.89,1.89,0,0,0,79.1,158.55Z"/><path class="cls-3" d="M92.11,157.83l-1.95,6.5H89.08l-1.34-4.65a3.08,3.08,0,0,1-.1-.6h0a2.76,2.76,0,0,1-.13.59L86,164.33H85l-2-6.5h1.09l1.35,4.89a2.94,2.94,0,0,1,.09.58h.05a2.73,2.73,0,0,1,.11-.6l1.5-4.87h1l1.35,4.9a3.47,3.47,0,0,1,.09.58h.05a2.67,2.67,0,0,1,.11-.58l1.32-4.9Z"/><path class="cls-3" d="M17.65,185.95a5.34,5.34,0,0,1-2.51.53A4.06,4.06,0,0,1,12,185.23,4.61,4.61,0,0,1,10.86,182a4.83,4.83,0,0,1,1.31-3.53,4.46,4.46,0,0,1,3.33-1.35,5.36,5.36,0,0,1,2.15.37v1.14a4.35,4.35,0,0,0-2.16-.55,3.31,3.31,0,0,0-2.54,1,3.94,3.94,0,0,0-1,2.8,3.76,3.76,0,0,0,.91,2.65,3.1,3.1,0,0,0,2.39,1,4.48,4.48,0,0,0,2.37-.61Z"/><path class="cls-3" d="M22.08,186.48a3,3,0,0,1-2.3-.91,3.37,3.37,0,0,1-.86-2.42,3.51,3.51,0,0,1,.9-2.56,3.22,3.22,0,0,1,2.42-.92,2.92,2.92,0,0,1,2.27.89,3.56,3.56,0,0,1,.82,2.48,3.49,3.49,0,0,1-.88,2.49A3.08,3.08,0,0,1,22.08,186.48Zm.08-5.93a2,2,0,0,0-1.59.68,2.8,2.8,0,0,0-.58,1.88,2.64,2.64,0,0,0,.59,1.82,2,2,0,0,0,1.58.67,1.9,1.9,0,0,0,1.55-.65,2.84,2.84,0,0,0,.54-1.86,2.88,2.88,0,0,0-.54-1.88A1.89,1.89,0,0,0,22.15,180.55Z"/><path class="cls-3" d="M32.37,186.33h-1v-3.71q0-2.07-1.51-2.07a1.64,1.64,0,0,0-1.29.59,2.18,2.18,0,0,0-.51,1.48v3.71H27v-6.5h1v1.08h0a2.34,2.34,0,0,1,2.13-1.23,2,2,0,0,1,1.63.69,3.07,3.07,0,0,1,.57,2Z"/><path class="cls-3" d="M37.55,177.62a1.39,1.39,0,0,0-.69-.17q-1.09,0-1.09,1.38v1h1.52v.89H35.76v5.61h-1v-5.61H33.62v-.89h1.11v-1.05a2.19,2.19,0,0,1,.59-1.62,2,2,0,0,1,1.47-.59,2,2,0,0,1,.75.11Z"/><path class="cls-3" d="M38.94,178.18a.66.66,0,0,1-.48-.19.64.64,0,0,1-.2-.48.67.67,0,0,1,.67-.68.67.67,0,0,1,.49.19.68.68,0,0,1,0,1A.66.66,0,0,1,38.94,178.18Zm.51,8.15h-1v-6.5h1Z"/><path class="cls-3" d="M47.1,185.81q0,3.58-3.43,3.58a4.6,4.6,0,0,1-2.11-.46v-1a4.33,4.33,0,0,0,2.09.61q2.4,0,2.4-2.55v-.71h0a2.63,2.63,0,0,1-4.19.38,3.47,3.47,0,0,1-.74-2.33,4,4,0,0,1,.8-2.63,2.66,2.66,0,0,1,2.18-1A2.12,2.12,0,0,1,46,180.73h0v-.9h1Zm-1-2.42v-1a1.86,1.86,0,0,0-.52-1.33,1.73,1.73,0,0,0-1.3-.55,1.81,1.81,0,0,0-1.51.7,3.14,3.14,0,0,0-.55,2A2.69,2.69,0,0,0,42.7,185a1.69,1.69,0,0,0,1.39.65,1.81,1.81,0,0,0,1.42-.62A2.32,2.32,0,0,0,46.06,183.39Z"/><path class="cls-3" d="M54.46,186.33h-1v-1h0a2.14,2.14,0,0,1-2,1.18q-2.32,0-2.32-2.77v-3.88h1v3.72q0,2.06,1.57,2.06a1.59,1.59,0,0,0,1.25-.56,2.15,2.15,0,0,0,.49-1.47v-3.75h1Z"/><path class="cls-3" d="M60,180.88a1.28,1.28,0,0,0-.79-.21,1.33,1.33,0,0,0-1.12.63,2.92,2.92,0,0,0-.45,1.71v3.31h-1v-6.5h1v1.34h0a2.27,2.27,0,0,1,.68-1.07,1.55,1.55,0,0,1,1-.38,1.7,1.7,0,0,1,.62.09Z"/><path class="cls-3" d="M66.14,183.34H61.55a2.43,2.43,0,0,0,.58,1.68,2,2,0,0,0,1.54.59,3.19,3.19,0,0,0,2-.72v1a3.77,3.77,0,0,1-2.27.62,2.75,2.75,0,0,1-2.16-.89,3.62,3.62,0,0,1-.79-2.49,3.55,3.55,0,0,1,.86-2.47,2.76,2.76,0,0,1,2.14-1,2.45,2.45,0,0,1,2,.83,3.44,3.44,0,0,1,.7,2.29Zm-1.07-.88a2.12,2.12,0,0,0-.43-1.4,1.48,1.48,0,0,0-1.19-.5,1.68,1.68,0,0,0-1.25.53,2.39,2.39,0,0,0-.63,1.38Z"/><path class="cls-3" d="M76.13,186.33H71.41v-9.1h1.07v8.14h3.66Z"/><path class="cls-3" d="M82,186.33H81v-1h0a2.18,2.18,0,0,1-2,1.17,2.14,2.14,0,0,1-1.52-.51,1.78,1.78,0,0,1-.55-1.37q0-1.82,2.15-2.12l1.95-.27q0-1.66-1.34-1.66a3.2,3.2,0,0,0-2.12.8v-1.07a4,4,0,0,1,2.21-.61q2.29,0,2.29,2.42ZM81,183l-1.57.22a2.55,2.55,0,0,0-1.09.36,1,1,0,0,0-.37.91,1,1,0,0,0,.34.78,1.31,1.31,0,0,0,.9.3,1.67,1.67,0,0,0,1.28-.54,1.94,1.94,0,0,0,.5-1.37Z"/><path class="cls-3" d="M89.4,186.33h-1v-3.71q0-2.07-1.51-2.07a1.64,1.64,0,0,0-1.29.59,2.18,2.18,0,0,0-.51,1.48v3.71H84v-6.5h1v1.08h0a2.34,2.34,0,0,1,2.13-1.23,2,2,0,0,1,1.63.69,3.07,3.07,0,0,1,.57,2Z"/><path class="cls-3" d="M96.91,185.81q0,3.58-3.43,3.58a4.61,4.61,0,0,1-2.11-.46v-1a4.33,4.33,0,0,0,2.1.61q2.4,0,2.4-2.55v-.71h0a2.63,2.63,0,0,1-4.19.38,3.47,3.47,0,0,1-.74-2.33,4,4,0,0,1,.8-2.63,2.66,2.66,0,0,1,2.18-1,2.12,2.12,0,0,1,1.95,1.05h0v-.9h1Zm-1-2.42v-1a1.86,1.86,0,0,0-.52-1.33,1.73,1.73,0,0,0-1.3-.55,1.81,1.81,0,0,0-1.51.7,3.13,3.13,0,0,0-.55,2,2.7,2.7,0,0,0,.52,1.74,1.69,1.69,0,0,0,1.39.65,1.81,1.81,0,0,0,1.42-.62A2.32,2.32,0,0,0,95.87,183.39Z"/><path class="cls-3" d="M104.27,186.33h-1v-1h0a2.14,2.14,0,0,1-2,1.18q-2.32,0-2.32-2.77v-3.88h1v3.72q0,2.06,1.57,2.06a1.59,1.59,0,0,0,1.25-.56,2.15,2.15,0,0,0,.49-1.47v-3.75h1Z"/><path class="cls-3" d="M111,186.33h-1v-1h0a2.18,2.18,0,0,1-2,1.17,2.14,2.14,0,0,1-1.52-.51,1.79,1.79,0,0,1-.55-1.37q0-1.82,2.15-2.12l1.95-.27q0-1.66-1.34-1.66a3.2,3.2,0,0,0-2.12.8v-1.07a4,4,0,0,1,2.21-.61q2.29,0,2.29,2.42ZM110,183l-1.57.22a2.55,2.55,0,0,0-1.09.36,1,1,0,0,0-.37.91,1,1,0,0,0,.34.78,1.31,1.31,0,0,0,.9.3,1.67,1.67,0,0,0,1.28-.54,1.94,1.94,0,0,0,.5-1.37Z"/><path class="cls-3" d="M118.54,185.81q0,3.58-3.43,3.58a4.6,4.6,0,0,1-2.11-.46v-1a4.33,4.33,0,0,0,2.09.61q2.4,0,2.4-2.55v-.71h0a2.63,2.63,0,0,1-4.19.38,3.46,3.46,0,0,1-.74-2.33,4,4,0,0,1,.8-2.63,2.66,2.66,0,0,1,2.18-1,2.12,2.12,0,0,1,1.95,1.05h0v-.9h1Zm-1-2.42v-1a1.86,1.86,0,0,0-.52-1.33,1.73,1.73,0,0,0-1.3-.55,1.81,1.81,0,0,0-1.51.7,3.13,3.13,0,0,0-.55,2,2.69,2.69,0,0,0,.52,1.74,1.69,1.69,0,0,0,1.39.65,1.81,1.81,0,0,0,1.43-.62A2.32,2.32,0,0,0,117.5,183.39Z"/><path class="cls-3" d="M125.87,183.34h-4.59a2.43,2.43,0,0,0,.58,1.68,2,2,0,0,0,1.54.59,3.19,3.19,0,0,0,2-.72v1a3.77,3.77,0,0,1-2.27.62,2.75,2.75,0,0,1-2.17-.89,3.63,3.63,0,0,1-.79-2.49,3.55,3.55,0,0,1,.86-2.47,2.76,2.76,0,0,1,2.14-1,2.44,2.44,0,0,1,2,.83,3.44,3.44,0,0,1,.7,2.29Zm-1.07-.88a2.12,2.12,0,0,0-.44-1.4,1.48,1.48,0,0,0-1.19-.5,1.68,1.68,0,0,0-1.25.53,2.4,2.4,0,0,0-.63,1.38Z"/><rect class="cls-6" width="386" height="197"/></g></g></svg>
src/vs/workbench/contrib/welcome/overlay/browser/media/commandpalette-dark.svg
0
https://github.com/microsoft/vscode/commit/f554a745505474ba031a79f5ab4a5c9d1ed3af39
[ 0.0001710432698018849, 0.0001710432698018849, 0.0001710432698018849, 0.0001710432698018849, 0 ]
{ "id": 4, "code_window": [ "\t\t\t\t\t\tstackFrames.push(callStack[0]);\n", "\t\t\t\t\t}\n", "\n", "\t\t\t\t\tstackFrames.forEach(candidateStackFrame => {\n", "\t\t\t\t\t\tif (candidateStackFrame && this.uriIdentityService.extUri.isEqual(candidateStackFrame.source.uri, this.editor.getModel()?.uri)) {\n", "\t\t\t\t\t\t\tdecorations.push(...createDecorationsForStackFrame(candidateStackFrame, this.topStackFrameRange, isSessionFocused));\n", "\t\t\t\t\t\t}\n", "\t\t\t\t\t});\n", "\t\t\t\t}\n", "\t\t\t});\n", "\t\t});\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\t\t\t\tdecorations.push(...createDecorationsForStackFrame(candidateStackFrame, isSessionFocused));\n" ], "file_path": "src/vs/workbench/contrib/debug/browser/callStackEditorContribution.ts", "type": "replace", "edit_start_line_idx": 141 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { SignatureHelpProvider, SignatureHelp, SignatureInformation, CancellationToken, TextDocument, Position, workspace } from 'vscode'; import phpGlobals = require('./phpGlobals'); import phpGlobalFunctions = require('./phpGlobalFunctions'); const _NL = '\n'.charCodeAt(0); const _TAB = '\t'.charCodeAt(0); const _WSB = ' '.charCodeAt(0); const _LBracket = '['.charCodeAt(0); const _RBracket = ']'.charCodeAt(0); const _LCurly = '{'.charCodeAt(0); const _RCurly = '}'.charCodeAt(0); const _LParent = '('.charCodeAt(0); const _RParent = ')'.charCodeAt(0); const _Comma = ','.charCodeAt(0); const _Quote = '\''.charCodeAt(0); const _DQuote = '"'.charCodeAt(0); const _USC = '_'.charCodeAt(0); const _a = 'a'.charCodeAt(0); const _z = 'z'.charCodeAt(0); const _A = 'A'.charCodeAt(0); const _Z = 'Z'.charCodeAt(0); const _0 = '0'.charCodeAt(0); const _9 = '9'.charCodeAt(0); const BOF = 0; class BackwardIterator { private lineNumber: number; private offset: number; private line: string; private model: TextDocument; constructor(model: TextDocument, offset: number, lineNumber: number) { this.lineNumber = lineNumber; this.offset = offset; this.line = model.lineAt(this.lineNumber).text; this.model = model; } public hasNext(): boolean { return this.lineNumber >= 0; } public next(): number { if (this.offset < 0) { if (this.lineNumber > 0) { this.lineNumber--; this.line = this.model.lineAt(this.lineNumber).text; this.offset = this.line.length - 1; return _NL; } this.lineNumber = -1; return BOF; } let ch = this.line.charCodeAt(this.offset); this.offset--; return ch; } } export default class PHPSignatureHelpProvider implements SignatureHelpProvider { public provideSignatureHelp(document: TextDocument, position: Position, _token: CancellationToken): Promise<SignatureHelp> | null { let enable = workspace.getConfiguration('php').get<boolean>('suggest.basic', true); if (!enable) { return null; } let iterator = new BackwardIterator(document, position.character - 1, position.line); let paramCount = this.readArguments(iterator); if (paramCount < 0) { return null; } let ident = this.readIdent(iterator); if (!ident) { return null; } let entry = phpGlobalFunctions.globalfunctions[ident] || phpGlobals.keywords[ident]; if (!entry || !entry.signature) { return null; } let paramsString = entry.signature.substring(0, entry.signature.lastIndexOf(')') + 1); let signatureInfo = new SignatureInformation(ident + paramsString, entry.description); let re = /\w*\s+\&?\$[\w_\.]+|void/g; let match: RegExpExecArray | null = null; while ((match = re.exec(paramsString)) !== null) { signatureInfo.parameters.push({ label: match[0], documentation: '' }); } let ret = new SignatureHelp(); ret.signatures.push(signatureInfo); ret.activeSignature = 0; ret.activeParameter = Math.min(paramCount, signatureInfo.parameters.length - 1); return Promise.resolve(ret); } private readArguments(iterator: BackwardIterator): number { let parentNesting = 0; let bracketNesting = 0; let curlyNesting = 0; let paramCount = 0; while (iterator.hasNext()) { let ch = iterator.next(); switch (ch) { case _LParent: parentNesting--; if (parentNesting < 0) { return paramCount; } break; case _RParent: parentNesting++; break; case _LCurly: curlyNesting--; break; case _RCurly: curlyNesting++; break; case _LBracket: bracketNesting--; break; case _RBracket: bracketNesting++; break; case _DQuote: case _Quote: while (iterator.hasNext() && ch !== iterator.next()) { // find the closing quote or double quote } break; case _Comma: if (!parentNesting && !bracketNesting && !curlyNesting) { paramCount++; } break; } } return -1; } private isIdentPart(ch: number): boolean { if (ch === _USC || // _ ch >= _a && ch <= _z || // a-z ch >= _A && ch <= _Z || // A-Z ch >= _0 && ch <= _9 || // 0/9 ch >= 0x80 && ch <= 0xFFFF) { // nonascii return true; } return false; } private readIdent(iterator: BackwardIterator): string { let identStarted = false; let ident = ''; while (iterator.hasNext()) { let ch = iterator.next(); if (!identStarted && (ch === _WSB || ch === _TAB || ch === _NL)) { continue; } if (this.isIdentPart(ch)) { identStarted = true; ident = String.fromCharCode(ch) + ident; } else if (identStarted) { return ident; } } return ident; } }
extensions/php-language-features/src/features/signatureHelpProvider.ts
0
https://github.com/microsoft/vscode/commit/f554a745505474ba031a79f5ab4a5c9d1ed3af39
[ 0.0001747859932947904, 0.0001723477034829557, 0.00016784244508016855, 0.0001726318005239591, 0.0000019885792426066473 ]
{ "id": 4, "code_window": [ "\t\t\t\t\t\tstackFrames.push(callStack[0]);\n", "\t\t\t\t\t}\n", "\n", "\t\t\t\t\tstackFrames.forEach(candidateStackFrame => {\n", "\t\t\t\t\t\tif (candidateStackFrame && this.uriIdentityService.extUri.isEqual(candidateStackFrame.source.uri, this.editor.getModel()?.uri)) {\n", "\t\t\t\t\t\t\tdecorations.push(...createDecorationsForStackFrame(candidateStackFrame, this.topStackFrameRange, isSessionFocused));\n", "\t\t\t\t\t\t}\n", "\t\t\t\t\t});\n", "\t\t\t\t}\n", "\t\t\t});\n", "\t\t});\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\t\t\t\tdecorations.push(...createDecorationsForStackFrame(candidateStackFrame, isSessionFocused));\n" ], "file_path": "src/vs/workbench/contrib/debug/browser/callStackEditorContribution.ts", "type": "replace", "edit_start_line_idx": 141 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as assert from 'assert'; import * as vscode from 'vscode'; import { closeAllEditors, pathEquals } from '../utils'; import { join } from 'path'; suite('vscode API - workspace', () => { teardown(closeAllEditors); test('rootPath', () => { assert.ok(pathEquals(vscode.workspace.rootPath!, join(__dirname, '../../testWorkspace'))); }); test('workspaceFile', () => { assert.ok(pathEquals(vscode.workspace.workspaceFile!.fsPath, join(__dirname, '../../testworkspace.code-workspace'))); }); test('workspaceFolders', () => { assert.equal(vscode.workspace.workspaceFolders!.length, 2); assert.ok(pathEquals(vscode.workspace.workspaceFolders![0].uri.fsPath, join(__dirname, '../../testWorkspace'))); assert.ok(pathEquals(vscode.workspace.workspaceFolders![1].uri.fsPath, join(__dirname, '../../testWorkspace2'))); assert.ok(pathEquals(vscode.workspace.workspaceFolders![1].name, 'Test Workspace 2')); }); test('getWorkspaceFolder', () => { const folder = vscode.workspace.getWorkspaceFolder(vscode.Uri.file(join(__dirname, '../../testWorkspace2/far.js'))); assert.ok(!!folder); if (folder) { assert.ok(pathEquals(folder.uri.fsPath, join(__dirname, '../../testWorkspace2'))); } }); });
extensions/vscode-api-tests/src/workspace-tests/workspace.test.ts
0
https://github.com/microsoft/vscode/commit/f554a745505474ba031a79f5ab4a5c9d1ed3af39
[ 0.00017391139408573508, 0.00017206226766575128, 0.00016961165238171816, 0.00017236301209777594, 0.0000015572142046949011 ]
{ "id": 5, "code_window": [ "\ttest('decorations', () => {\n", "\t\tconst session = createMockSession(model);\n", "\t\tmodel.addSession(session);\n", "\t\tconst { firstStackFrame, secondStackFrame } = createTwoStackFrames(session);\n", "\t\tlet decorations = createDecorationsForStackFrame(firstStackFrame, firstStackFrame.range, true);\n", "\t\tassert.strictEqual(decorations.length, 2);\n", "\t\tassert.deepStrictEqual(decorations[0].range, new Range(1, 2, 1, 1));\n", "\t\tassert.strictEqual(decorations[0].options.glyphMarginClassName, ThemeIcon.asClassName(debugStackframe));\n", "\t\tassert.deepStrictEqual(decorations[1].range, new Range(1, Constants.MAX_SAFE_SMALL_INTEGER, 1, 1));\n", "\t\tassert.strictEqual(decorations[1].options.className, 'debug-top-stack-frame-line');\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tlet decorations = createDecorationsForStackFrame(firstStackFrame, true);\n", "\t\tassert.strictEqual(decorations.length, 3);\n" ], "file_path": "src/vs/workbench/contrib/debug/test/browser/callStack.test.ts", "type": "replace", "edit_start_line_idx": 313 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as assert from 'assert'; import { DebugModel, StackFrame, Thread } from 'vs/workbench/contrib/debug/common/debugModel'; import * as sinon from 'sinon'; import { MockRawSession, createMockDebugModel, mockUriIdentityService } from 'vs/workbench/contrib/debug/test/browser/mockDebug'; import { Source } from 'vs/workbench/contrib/debug/common/debugSource'; import { DebugSession } from 'vs/workbench/contrib/debug/browser/debugSession'; import { Range } from 'vs/editor/common/core/range'; import { IDebugSessionOptions, State, IDebugService } from 'vs/workbench/contrib/debug/common/debug'; import { NullOpenerService } from 'vs/platform/opener/common/opener'; import { createDecorationsForStackFrame } from 'vs/workbench/contrib/debug/browser/callStackEditorContribution'; import { Constants } from 'vs/base/common/uint'; import { getContext, getContextForContributedActions, getSpecificSourceName } from 'vs/workbench/contrib/debug/browser/callStackView'; import { getStackFrameThreadAndSessionToFocus } from 'vs/workbench/contrib/debug/browser/debugService'; import { generateUuid } from 'vs/base/common/uuid'; import { debugStackframe, debugStackframeFocused } from 'vs/workbench/contrib/debug/browser/debugIcons'; import { ThemeIcon } from 'vs/platform/theme/common/themeService'; import { TestConfigurationService } from 'vs/platform/configuration/test/common/testConfigurationService'; const mockWorkspaceContextService = { getWorkspace: () => { return { folders: [] }; } } as any; export function createMockSession(model: DebugModel, name = 'mockSession', options?: IDebugSessionOptions): DebugSession { return new DebugSession(generateUuid(), { resolved: { name, type: 'node', request: 'launch' }, unresolved: undefined }, undefined!, model, options, { getViewModel(): any { return { updateViews(): void { // noop } }; } } as IDebugService, undefined!, undefined!, new TestConfigurationService({ debug: { console: { collapseIdenticalLines: true } } }), undefined!, mockWorkspaceContextService, undefined!, undefined!, NullOpenerService, undefined!, undefined!, mockUriIdentityService, undefined!); } function createTwoStackFrames(session: DebugSession): { firstStackFrame: StackFrame, secondStackFrame: StackFrame } { let firstStackFrame: StackFrame; let secondStackFrame: StackFrame; const thread = new class extends Thread { public getCallStack(): StackFrame[] { return [firstStackFrame, secondStackFrame]; } }(session, 'mockthread', 1); const firstSource = new Source({ name: 'internalModule.js', path: 'a/b/c/d/internalModule.js', sourceReference: 10, }, 'aDebugSessionId', mockUriIdentityService); const secondSource = new Source({ name: 'internalModule.js', path: 'z/x/c/d/internalModule.js', sourceReference: 11, }, 'aDebugSessionId', mockUriIdentityService); firstStackFrame = new StackFrame(thread, 0, firstSource, 'app.js', 'normal', { startLineNumber: 1, startColumn: 1, endLineNumber: 1, endColumn: 10 }, 0, true); secondStackFrame = new StackFrame(thread, 1, secondSource, 'app2.js', 'normal', { startLineNumber: 1, startColumn: 1, endLineNumber: 1, endColumn: 10 }, 1, true); return { firstStackFrame, secondStackFrame }; } suite('Debug - CallStack', () => { let model: DebugModel; let rawSession: MockRawSession; setup(() => { model = createMockDebugModel(); rawSession = new MockRawSession(); }); // Threads test('threads simple', () => { const threadId = 1; const threadName = 'firstThread'; const session = createMockSession(model); model.addSession(session); assert.strictEqual(model.getSessions(true).length, 1); model.rawUpdate({ sessionId: session.getId(), threads: [{ id: threadId, name: threadName }] }); assert.strictEqual(session.getThread(threadId)!.name, threadName); model.clearThreads(session.getId(), true); assert.strictEqual(session.getThread(threadId), undefined); assert.strictEqual(model.getSessions(true).length, 1); }); test('threads multiple wtih allThreadsStopped', async () => { const threadId1 = 1; const threadName1 = 'firstThread'; const threadId2 = 2; const threadName2 = 'secondThread'; const stoppedReason = 'breakpoint'; // Add the threads const session = createMockSession(model); model.addSession(session); session['raw'] = <any>rawSession; model.rawUpdate({ sessionId: session.getId(), threads: [{ id: threadId1, name: threadName1 }] }); // Stopped event with all threads stopped model.rawUpdate({ sessionId: session.getId(), threads: [{ id: threadId1, name: threadName1 }, { id: threadId2, name: threadName2 }], stoppedDetails: { reason: stoppedReason, threadId: 1, allThreadsStopped: true }, }); const thread1 = session.getThread(threadId1)!; const thread2 = session.getThread(threadId2)!; // at the beginning, callstacks are obtainable but not available assert.strictEqual(session.getAllThreads().length, 2); assert.strictEqual(thread1.name, threadName1); assert.strictEqual(thread1.stopped, true); assert.strictEqual(thread1.getCallStack().length, 0); assert.strictEqual(thread1.stoppedDetails!.reason, stoppedReason); assert.strictEqual(thread2.name, threadName2); assert.strictEqual(thread2.stopped, true); assert.strictEqual(thread2.getCallStack().length, 0); assert.strictEqual(thread2.stoppedDetails!.reason, undefined); // after calling getCallStack, the callstack becomes available // and results in a request for the callstack in the debug adapter await thread1.fetchCallStack(); assert.notStrictEqual(thread1.getCallStack().length, 0); await thread2.fetchCallStack(); assert.notStrictEqual(thread2.getCallStack().length, 0); // calling multiple times getCallStack doesn't result in multiple calls // to the debug adapter await thread1.fetchCallStack(); await thread2.fetchCallStack(); // clearing the callstack results in the callstack not being available thread1.clearCallStack(); assert.strictEqual(thread1.stopped, true); assert.strictEqual(thread1.getCallStack().length, 0); thread2.clearCallStack(); assert.strictEqual(thread2.stopped, true); assert.strictEqual(thread2.getCallStack().length, 0); model.clearThreads(session.getId(), true); assert.strictEqual(session.getThread(threadId1), undefined); assert.strictEqual(session.getThread(threadId2), undefined); assert.strictEqual(session.getAllThreads().length, 0); }); test('threads mutltiple without allThreadsStopped', async () => { const sessionStub = sinon.spy(rawSession, 'stackTrace'); const stoppedThreadId = 1; const stoppedThreadName = 'stoppedThread'; const runningThreadId = 2; const runningThreadName = 'runningThread'; const stoppedReason = 'breakpoint'; const session = createMockSession(model); model.addSession(session); session['raw'] = <any>rawSession; // Add the threads model.rawUpdate({ sessionId: session.getId(), threads: [{ id: stoppedThreadId, name: stoppedThreadName }] }); // Stopped event with only one thread stopped model.rawUpdate({ sessionId: session.getId(), threads: [{ id: 1, name: stoppedThreadName }, { id: runningThreadId, name: runningThreadName }], stoppedDetails: { reason: stoppedReason, threadId: 1, allThreadsStopped: false } }); const stoppedThread = session.getThread(stoppedThreadId)!; const runningThread = session.getThread(runningThreadId)!; // the callstack for the stopped thread is obtainable but not available // the callstack for the running thread is not obtainable nor available assert.strictEqual(stoppedThread.name, stoppedThreadName); assert.strictEqual(stoppedThread.stopped, true); assert.strictEqual(session.getAllThreads().length, 2); assert.strictEqual(stoppedThread.getCallStack().length, 0); assert.strictEqual(stoppedThread.stoppedDetails!.reason, stoppedReason); assert.strictEqual(runningThread.name, runningThreadName); assert.strictEqual(runningThread.stopped, false); assert.strictEqual(runningThread.getCallStack().length, 0); assert.strictEqual(runningThread.stoppedDetails, undefined); // after calling getCallStack, the callstack becomes available // and results in a request for the callstack in the debug adapter await stoppedThread.fetchCallStack(); assert.notStrictEqual(stoppedThread.getCallStack().length, 0); assert.strictEqual(runningThread.getCallStack().length, 0); assert.strictEqual(sessionStub.callCount, 1); // calling getCallStack on the running thread returns empty array // and does not return in a request for the callstack in the debug // adapter await runningThread.fetchCallStack(); assert.strictEqual(runningThread.getCallStack().length, 0); assert.strictEqual(sessionStub.callCount, 1); // clearing the callstack results in the callstack not being available stoppedThread.clearCallStack(); assert.strictEqual(stoppedThread.stopped, true); assert.strictEqual(stoppedThread.getCallStack().length, 0); model.clearThreads(session.getId(), true); assert.strictEqual(session.getThread(stoppedThreadId), undefined); assert.strictEqual(session.getThread(runningThreadId), undefined); assert.strictEqual(session.getAllThreads().length, 0); }); test('stack frame get specific source name', () => { const session = createMockSession(model); model.addSession(session); const { firstStackFrame, secondStackFrame } = createTwoStackFrames(session); assert.strictEqual(getSpecificSourceName(firstStackFrame), '.../b/c/d/internalModule.js'); assert.strictEqual(getSpecificSourceName(secondStackFrame), '.../x/c/d/internalModule.js'); }); test('stack frame toString()', () => { const session = createMockSession(model); const thread = new Thread(session, 'mockthread', 1); const firstSource = new Source({ name: 'internalModule.js', path: 'a/b/c/d/internalModule.js', sourceReference: 10, }, 'aDebugSessionId', mockUriIdentityService); const stackFrame = new StackFrame(thread, 1, firstSource, 'app', 'normal', { startLineNumber: 1, startColumn: 1, endLineNumber: 1, endColumn: 10 }, 1, true); assert.strictEqual(stackFrame.toString(), 'app (internalModule.js:1)'); const secondSource = new Source(undefined, 'aDebugSessionId', mockUriIdentityService); const stackFrame2 = new StackFrame(thread, 2, secondSource, 'module', 'normal', { startLineNumber: undefined!, startColumn: undefined!, endLineNumber: undefined!, endColumn: undefined! }, 2, true); assert.strictEqual(stackFrame2.toString(), 'module'); }); test('debug child sessions are added in correct order', () => { const session = createMockSession(model); model.addSession(session); const secondSession = createMockSession(model, 'mockSession2'); model.addSession(secondSession); const firstChild = createMockSession(model, 'firstChild', { parentSession: session }); model.addSession(firstChild); const secondChild = createMockSession(model, 'secondChild', { parentSession: session }); model.addSession(secondChild); const thirdSession = createMockSession(model, 'mockSession3'); model.addSession(thirdSession); const anotherChild = createMockSession(model, 'secondChild', { parentSession: secondSession }); model.addSession(anotherChild); const sessions = model.getSessions(); assert.strictEqual(sessions[0].getId(), session.getId()); assert.strictEqual(sessions[1].getId(), firstChild.getId()); assert.strictEqual(sessions[2].getId(), secondChild.getId()); assert.strictEqual(sessions[3].getId(), secondSession.getId()); assert.strictEqual(sessions[4].getId(), anotherChild.getId()); assert.strictEqual(sessions[5].getId(), thirdSession.getId()); }); test('decorations', () => { const session = createMockSession(model); model.addSession(session); const { firstStackFrame, secondStackFrame } = createTwoStackFrames(session); let decorations = createDecorationsForStackFrame(firstStackFrame, firstStackFrame.range, true); assert.strictEqual(decorations.length, 2); assert.deepStrictEqual(decorations[0].range, new Range(1, 2, 1, 1)); assert.strictEqual(decorations[0].options.glyphMarginClassName, ThemeIcon.asClassName(debugStackframe)); assert.deepStrictEqual(decorations[1].range, new Range(1, Constants.MAX_SAFE_SMALL_INTEGER, 1, 1)); assert.strictEqual(decorations[1].options.className, 'debug-top-stack-frame-line'); assert.strictEqual(decorations[1].options.isWholeLine, true); decorations = createDecorationsForStackFrame(secondStackFrame, firstStackFrame.range, true); assert.strictEqual(decorations.length, 2); assert.deepStrictEqual(decorations[0].range, new Range(1, 2, 1, 1)); assert.strictEqual(decorations[0].options.glyphMarginClassName, ThemeIcon.asClassName(debugStackframeFocused)); assert.deepStrictEqual(decorations[1].range, new Range(1, Constants.MAX_SAFE_SMALL_INTEGER, 1, 1)); assert.strictEqual(decorations[1].options.className, 'debug-focused-stack-frame-line'); assert.strictEqual(decorations[1].options.isWholeLine, true); decorations = createDecorationsForStackFrame(firstStackFrame, new Range(1, 5, 1, 6), true); assert.strictEqual(decorations.length, 3); assert.deepStrictEqual(decorations[0].range, new Range(1, 2, 1, 1)); assert.strictEqual(decorations[0].options.glyphMarginClassName, ThemeIcon.asClassName(debugStackframe)); assert.deepStrictEqual(decorations[1].range, new Range(1, Constants.MAX_SAFE_SMALL_INTEGER, 1, 1)); assert.strictEqual(decorations[1].options.className, 'debug-top-stack-frame-line'); assert.strictEqual(decorations[1].options.isWholeLine, true); // Inline decoration gets rendered in this case assert.strictEqual(decorations[2].options.beforeContentClassName, 'debug-top-stack-frame-column'); assert.deepStrictEqual(decorations[2].range, new Range(1, Constants.MAX_SAFE_SMALL_INTEGER, 1, 1)); }); test('contexts', () => { const session = createMockSession(model); model.addSession(session); const { firstStackFrame, secondStackFrame } = createTwoStackFrames(session); let context = getContext(firstStackFrame); assert.strictEqual(context.sessionId, firstStackFrame.thread.session.getId()); assert.strictEqual(context.threadId, firstStackFrame.thread.getId()); assert.strictEqual(context.frameId, firstStackFrame.getId()); context = getContext(secondStackFrame.thread); assert.strictEqual(context.sessionId, secondStackFrame.thread.session.getId()); assert.strictEqual(context.threadId, secondStackFrame.thread.getId()); assert.strictEqual(context.frameId, undefined); context = getContext(session); assert.strictEqual(context.sessionId, session.getId()); assert.strictEqual(context.threadId, undefined); assert.strictEqual(context.frameId, undefined); let contributedContext = getContextForContributedActions(firstStackFrame); assert.strictEqual(contributedContext, firstStackFrame.source.raw.path); contributedContext = getContextForContributedActions(firstStackFrame.thread); assert.strictEqual(contributedContext, firstStackFrame.thread.threadId); contributedContext = getContextForContributedActions(session); assert.strictEqual(contributedContext, session.getId()); }); test('focusStackFrameThreadAndSesion', () => { const threadId1 = 1; const threadName1 = 'firstThread'; const threadId2 = 2; const threadName2 = 'secondThread'; const stoppedReason = 'breakpoint'; // Add the threads const session = new class extends DebugSession { get state(): State { return State.Stopped; } }(generateUuid(), { resolved: { name: 'stoppedSession', type: 'node', request: 'launch' }, unresolved: undefined }, undefined!, model, undefined, undefined!, undefined!, undefined!, undefined!, undefined!, mockWorkspaceContextService, undefined!, undefined!, NullOpenerService, undefined!, undefined!, mockUriIdentityService, undefined!); const runningSession = createMockSession(model); model.addSession(runningSession); model.addSession(session); session['raw'] = <any>rawSession; model.rawUpdate({ sessionId: session.getId(), threads: [{ id: threadId1, name: threadName1 }] }); // Stopped event with all threads stopped model.rawUpdate({ sessionId: session.getId(), threads: [{ id: threadId1, name: threadName1 }, { id: threadId2, name: threadName2 }], stoppedDetails: { reason: stoppedReason, threadId: 1, allThreadsStopped: true }, }); const thread = session.getThread(threadId1)!; const runningThread = session.getThread(threadId2); let toFocus = getStackFrameThreadAndSessionToFocus(model, undefined); // Verify stopped session and stopped thread get focused assert.deepStrictEqual(toFocus, { stackFrame: undefined, thread: thread, session: session }); toFocus = getStackFrameThreadAndSessionToFocus(model, undefined, undefined, runningSession); assert.deepStrictEqual(toFocus, { stackFrame: undefined, thread: undefined, session: runningSession }); toFocus = getStackFrameThreadAndSessionToFocus(model, undefined, thread); assert.deepStrictEqual(toFocus, { stackFrame: undefined, thread: thread, session: session }); toFocus = getStackFrameThreadAndSessionToFocus(model, undefined, runningThread); assert.deepStrictEqual(toFocus, { stackFrame: undefined, thread: runningThread, session: session }); const stackFrame = new StackFrame(thread, 5, undefined!, 'stackframename2', undefined, undefined!, 1, true); toFocus = getStackFrameThreadAndSessionToFocus(model, stackFrame); assert.deepStrictEqual(toFocus, { stackFrame: stackFrame, thread: thread, session: session }); }); });
src/vs/workbench/contrib/debug/test/browser/callStack.test.ts
1
https://github.com/microsoft/vscode/commit/f554a745505474ba031a79f5ab4a5c9d1ed3af39
[ 0.9988564252853394, 0.14307557046413422, 0.00016353705723304302, 0.001168635324575007, 0.3359576463699341 ]
{ "id": 5, "code_window": [ "\ttest('decorations', () => {\n", "\t\tconst session = createMockSession(model);\n", "\t\tmodel.addSession(session);\n", "\t\tconst { firstStackFrame, secondStackFrame } = createTwoStackFrames(session);\n", "\t\tlet decorations = createDecorationsForStackFrame(firstStackFrame, firstStackFrame.range, true);\n", "\t\tassert.strictEqual(decorations.length, 2);\n", "\t\tassert.deepStrictEqual(decorations[0].range, new Range(1, 2, 1, 1));\n", "\t\tassert.strictEqual(decorations[0].options.glyphMarginClassName, ThemeIcon.asClassName(debugStackframe));\n", "\t\tassert.deepStrictEqual(decorations[1].range, new Range(1, Constants.MAX_SAFE_SMALL_INTEGER, 1, 1));\n", "\t\tassert.strictEqual(decorations[1].options.className, 'debug-top-stack-frame-line');\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tlet decorations = createDecorationsForStackFrame(firstStackFrame, true);\n", "\t\tassert.strictEqual(decorations.length, 3);\n" ], "file_path": "src/vs/workbench/contrib/debug/test/browser/callStack.test.ts", "type": "replace", "edit_start_line_idx": 313 }
{ "displayName": "Merge Conflict", "description": "Highlighting and commands for inline merge conflicts.", "command.category": "Merge Conflict", "command.accept.all-current": "Accept All Current", "command.accept.all-incoming": "Accept All Incoming", "command.accept.all-both": "Accept All Both", "command.accept.current": "Accept Current", "command.accept.incoming": "Accept Incoming", "command.accept.selection": "Accept Selection", "command.accept.both": "Accept Both", "command.next": "Next Conflict", "command.previous": "Previous Conflict", "command.compare": "Compare Current Conflict", "config.title": "Merge Conflict", "config.autoNavigateNextConflictEnabled": "Whether to automatically navigate to the next merge conflict after resolving a merge conflict.", "config.codeLensEnabled": "Create a CodeLens for merge conflict blocks within editor.", "config.decoratorsEnabled": "Create decorators for merge conflict blocks within editor.", "config.diffViewPosition": "Controls where the diff view should be opened when comparing changes in merge conflicts.", "config.diffViewPosition.current": "Open the diff view in the current editor group.", "config.diffViewPosition.beside": "Open the diff view next to the current editor group.", "config.diffViewPosition.below": "Open the diff view below the current editor group." }
extensions/merge-conflict/package.nls.json
0
https://github.com/microsoft/vscode/commit/f554a745505474ba031a79f5ab4a5c9d1ed3af39
[ 0.00017450223094783723, 0.00017249347001779824, 0.00017062465485651046, 0.0001723535096971318, 0.0000015861041902098805 ]
{ "id": 5, "code_window": [ "\ttest('decorations', () => {\n", "\t\tconst session = createMockSession(model);\n", "\t\tmodel.addSession(session);\n", "\t\tconst { firstStackFrame, secondStackFrame } = createTwoStackFrames(session);\n", "\t\tlet decorations = createDecorationsForStackFrame(firstStackFrame, firstStackFrame.range, true);\n", "\t\tassert.strictEqual(decorations.length, 2);\n", "\t\tassert.deepStrictEqual(decorations[0].range, new Range(1, 2, 1, 1));\n", "\t\tassert.strictEqual(decorations[0].options.glyphMarginClassName, ThemeIcon.asClassName(debugStackframe));\n", "\t\tassert.deepStrictEqual(decorations[1].range, new Range(1, Constants.MAX_SAFE_SMALL_INTEGER, 1, 1));\n", "\t\tassert.strictEqual(decorations[1].options.className, 'debug-top-stack-frame-line');\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tlet decorations = createDecorationsForStackFrame(firstStackFrame, true);\n", "\t\tassert.strictEqual(decorations.length, 3);\n" ], "file_path": "src/vs/workbench/contrib/debug/test/browser/callStack.test.ts", "type": "replace", "edit_start_line_idx": 313 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { IDisposable, IDisposableTracker, setDisposableTracker } from 'vs/base/common/lifecycle'; class DisposableTracker implements IDisposableTracker { allDisposables: [IDisposable, string][] = []; trackDisposable(x: IDisposable): void { this.allDisposables.push([x, new Error().stack!]); } markTracked(x: IDisposable): void { for (let idx = 0; idx < this.allDisposables.length; idx++) { if (this.allDisposables[idx][0] === x) { this.allDisposables.splice(idx, 1); return; } } } } let currentTracker: DisposableTracker | null = null; export function beginTrackingDisposables(): void { currentTracker = new DisposableTracker(); setDisposableTracker(currentTracker); } export function endTrackingDisposables(): void { if (currentTracker) { setDisposableTracker(null); console.log(currentTracker!.allDisposables.map(e => `${e[0]}\n${e[1]}`).join('\n\n')); currentTracker = null; } } export function beginLoggingFS(withStacks: boolean = false): void { if ((<any>self).beginLoggingFS) { (<any>self).beginLoggingFS(withStacks); } } export function endLoggingFS(): void { if ((<any>self).endLoggingFS) { (<any>self).endLoggingFS(); } }
src/vs/base/test/common/troubleshooting.ts
0
https://github.com/microsoft/vscode/commit/f554a745505474ba031a79f5ab4a5c9d1ed3af39
[ 0.00017474917694926262, 0.00017154325905721635, 0.0001671457866905257, 0.00017188610217999667, 0.0000024567125365138054 ]
{ "id": 5, "code_window": [ "\ttest('decorations', () => {\n", "\t\tconst session = createMockSession(model);\n", "\t\tmodel.addSession(session);\n", "\t\tconst { firstStackFrame, secondStackFrame } = createTwoStackFrames(session);\n", "\t\tlet decorations = createDecorationsForStackFrame(firstStackFrame, firstStackFrame.range, true);\n", "\t\tassert.strictEqual(decorations.length, 2);\n", "\t\tassert.deepStrictEqual(decorations[0].range, new Range(1, 2, 1, 1));\n", "\t\tassert.strictEqual(decorations[0].options.glyphMarginClassName, ThemeIcon.asClassName(debugStackframe));\n", "\t\tassert.deepStrictEqual(decorations[1].range, new Range(1, Constants.MAX_SAFE_SMALL_INTEGER, 1, 1));\n", "\t\tassert.strictEqual(decorations[1].options.className, 'debug-top-stack-frame-line');\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tlet decorations = createDecorationsForStackFrame(firstStackFrame, true);\n", "\t\tassert.strictEqual(decorations.length, 3);\n" ], "file_path": "src/vs/workbench/contrib/debug/test/browser/callStack.test.ts", "type": "replace", "edit_start_line_idx": 313 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as assert from 'assert'; import { ITreeNode, ITreeFilter, TreeVisibility } from 'vs/base/browser/ui/tree/tree'; import { ObjectTreeModel } from 'vs/base/browser/ui/tree/objectTreeModel'; import { IList } from 'vs/base/browser/ui/tree/indexTreeModel'; function toList<T>(arr: T[]): IList<T> { return { splice(start: number, deleteCount: number, elements: T[]): void { // console.log(`splice (${start}, ${deleteCount}, ${elements.length} [${elements.join(', ')}] )`); // debugging arr.splice(start, deleteCount, ...elements); }, updateElementHeight() { } }; } function toArray<T>(list: ITreeNode<T>[]): T[] { return list.map(i => i.element); } suite('ObjectTreeModel', function () { test('ctor', () => { const list: ITreeNode<number>[] = []; const model = new ObjectTreeModel<number>('test', toList(list)); assert(model); assert.equal(list.length, 0); assert.equal(model.size, 0); }); test('flat', () => { const list: ITreeNode<number>[] = []; const model = new ObjectTreeModel<number>('test', toList(list)); model.setChildren(null, [ { element: 0 }, { element: 1 }, { element: 2 } ]); assert.deepEqual(toArray(list), [0, 1, 2]); assert.equal(model.size, 3); model.setChildren(null, [ { element: 3 }, { element: 4 }, { element: 5 }, ]); assert.deepEqual(toArray(list), [3, 4, 5]); assert.equal(model.size, 3); model.setChildren(null); assert.deepEqual(toArray(list), []); assert.equal(model.size, 0); }); test('nested', () => { const list: ITreeNode<number>[] = []; const model = new ObjectTreeModel<number>('test', toList(list)); model.setChildren(null, [ { element: 0, children: [ { element: 10 }, { element: 11 }, { element: 12 }, ] }, { element: 1 }, { element: 2 } ]); assert.deepEqual(toArray(list), [0, 10, 11, 12, 1, 2]); assert.equal(model.size, 6); model.setChildren(12, [ { element: 120 }, { element: 121 } ]); assert.deepEqual(toArray(list), [0, 10, 11, 12, 120, 121, 1, 2]); assert.equal(model.size, 8); model.setChildren(0); assert.deepEqual(toArray(list), [0, 1, 2]); assert.equal(model.size, 3); model.setChildren(null); assert.deepEqual(toArray(list), []); assert.equal(model.size, 0); }); test('setChildren on collapsed node', () => { const list: ITreeNode<number>[] = []; const model = new ObjectTreeModel<number>('test', toList(list)); model.setChildren(null, [ { element: 0, collapsed: true } ]); assert.deepEqual(toArray(list), [0]); model.setChildren(0, [ { element: 1 }, { element: 2 } ]); assert.deepEqual(toArray(list), [0]); model.setCollapsed(0, false); assert.deepEqual(toArray(list), [0, 1, 2]); }); test('setChildren on expanded, unrevealed node', () => { const list: ITreeNode<number>[] = []; const model = new ObjectTreeModel<number>('test', toList(list)); model.setChildren(null, [ { element: 1, collapsed: true, children: [ { element: 11, collapsed: false } ] }, { element: 2 } ]); assert.deepEqual(toArray(list), [1, 2]); model.setChildren(11, [ { element: 111 }, { element: 112 } ]); assert.deepEqual(toArray(list), [1, 2]); model.setCollapsed(1, false); assert.deepEqual(toArray(list), [1, 11, 111, 112, 2]); }); test('collapse state is preserved with strict identity', () => { const list: ITreeNode<string>[] = []; const model = new ObjectTreeModel<string>('test', toList(list), { collapseByDefault: true }); const data = [{ element: 'father', children: [{ element: 'child' }] }]; model.setChildren(null, data); assert.deepEqual(toArray(list), ['father']); model.setCollapsed('father', false); assert.deepEqual(toArray(list), ['father', 'child']); model.setChildren(null, data); assert.deepEqual(toArray(list), ['father', 'child']); const data2 = [{ element: 'father', children: [{ element: 'child' }] }, { element: 'uncle' }]; model.setChildren(null, data2); assert.deepEqual(toArray(list), ['father', 'child', 'uncle']); model.setChildren(null, [{ element: 'uncle' }]); assert.deepEqual(toArray(list), ['uncle']); model.setChildren(null, data2); assert.deepEqual(toArray(list), ['father', 'uncle']); model.setChildren(null, data); assert.deepEqual(toArray(list), ['father']); }); test('sorter', () => { let compare: (a: string, b: string) => number = (a, b) => a < b ? -1 : 1; const list: ITreeNode<string>[] = []; const model = new ObjectTreeModel<string>('test', toList(list), { sorter: { compare(a, b) { return compare(a, b); } } }); const data = [ { element: 'cars', children: [{ element: 'sedan' }, { element: 'convertible' }, { element: 'compact' }] }, { element: 'airplanes', children: [{ element: 'passenger' }, { element: 'jet' }] }, { element: 'bicycles', children: [{ element: 'dutch' }, { element: 'mountain' }, { element: 'electric' }] }, ]; model.setChildren(null, data); assert.deepEqual(toArray(list), ['airplanes', 'jet', 'passenger', 'bicycles', 'dutch', 'electric', 'mountain', 'cars', 'compact', 'convertible', 'sedan']); }); test('resort', () => { let compare: (a: string, b: string) => number = () => 0; const list: ITreeNode<string>[] = []; const model = new ObjectTreeModel<string>('test', toList(list), { sorter: { compare(a, b) { return compare(a, b); } } }); const data = [ { element: 'cars', children: [{ element: 'sedan' }, { element: 'convertible' }, { element: 'compact' }] }, { element: 'airplanes', children: [{ element: 'passenger' }, { element: 'jet' }] }, { element: 'bicycles', children: [{ element: 'dutch' }, { element: 'mountain' }, { element: 'electric' }] }, ]; model.setChildren(null, data); assert.deepEqual(toArray(list), ['cars', 'sedan', 'convertible', 'compact', 'airplanes', 'passenger', 'jet', 'bicycles', 'dutch', 'mountain', 'electric']); // lexicographical compare = (a, b) => a < b ? -1 : 1; // non-recursive model.resort(null, false); assert.deepEqual(toArray(list), ['airplanes', 'passenger', 'jet', 'bicycles', 'dutch', 'mountain', 'electric', 'cars', 'sedan', 'convertible', 'compact']); // recursive model.resort(); assert.deepEqual(toArray(list), ['airplanes', 'jet', 'passenger', 'bicycles', 'dutch', 'electric', 'mountain', 'cars', 'compact', 'convertible', 'sedan']); // reverse compare = (a, b) => a < b ? 1 : -1; // scoped model.resort('cars'); assert.deepEqual(toArray(list), ['airplanes', 'jet', 'passenger', 'bicycles', 'dutch', 'electric', 'mountain', 'cars', 'sedan', 'convertible', 'compact']); // recursive model.resort(); assert.deepEqual(toArray(list), ['cars', 'sedan', 'convertible', 'compact', 'bicycles', 'mountain', 'electric', 'dutch', 'airplanes', 'passenger', 'jet']); }); test('expandTo', () => { const list: ITreeNode<number>[] = []; const model = new ObjectTreeModel<number>('test', toList(list), { collapseByDefault: true }); model.setChildren(null, [ { element: 0, children: [ { element: 10, children: [{ element: 100, children: [{ element: 1000 }] }] }, { element: 11 }, { element: 12 }, ] }, { element: 1 }, { element: 2 } ]); assert.deepEqual(toArray(list), [0, 1, 2]); model.expandTo(1000); assert.deepEqual(toArray(list), [0, 10, 100, 1000, 11, 12, 1, 2]); }); test('issue #95641', () => { const list: ITreeNode<string>[] = []; let fn = (_: string) => true; const filter = new class implements ITreeFilter<string> { filter(element: string, parentVisibility: TreeVisibility): TreeVisibility { if (element === 'file') { return TreeVisibility.Recurse; } return fn(element) ? TreeVisibility.Visible : parentVisibility; } }; const model = new ObjectTreeModel<string>('test', toList(list), { filter }); model.setChildren(null, [{ element: 'file', children: [{ element: 'hello' }] }]); assert.deepEqual(toArray(list), ['file', 'hello']); fn = (el: string) => el === 'world'; model.refilter(); assert.deepEqual(toArray(list), []); model.setChildren('file', [{ element: 'world' }]); assert.deepEqual(toArray(list), ['file', 'world']); model.setChildren('file', [{ element: 'hello' }]); assert.deepEqual(toArray(list), []); model.setChildren('file', [{ element: 'world' }]); assert.deepEqual(toArray(list), ['file', 'world']); }); });
src/vs/base/test/browser/ui/tree/objectTreeModel.test.ts
0
https://github.com/microsoft/vscode/commit/f554a745505474ba031a79f5ab4a5c9d1ed3af39
[ 0.0016543925739824772, 0.0003771937917917967, 0.00016517013136763126, 0.00020645654876716435, 0.00042545757605694234 ]
{ "id": 6, "code_window": [ "\t\tassert.strictEqual(decorations[1].options.className, 'debug-top-stack-frame-line');\n", "\t\tassert.strictEqual(decorations[1].options.isWholeLine, true);\n", "\n", "\t\tdecorations = createDecorationsForStackFrame(secondStackFrame, firstStackFrame.range, true);\n", "\t\tassert.strictEqual(decorations.length, 2);\n", "\t\tassert.deepStrictEqual(decorations[0].range, new Range(1, 2, 1, 1));\n", "\t\tassert.strictEqual(decorations[0].options.glyphMarginClassName, ThemeIcon.asClassName(debugStackframeFocused));\n", "\t\tassert.deepStrictEqual(decorations[1].range, new Range(1, Constants.MAX_SAFE_SMALL_INTEGER, 1, 1));\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tdecorations = createDecorationsForStackFrame(secondStackFrame, true);\n" ], "file_path": "src/vs/workbench/contrib/debug/test/browser/callStack.test.ts", "type": "replace", "edit_start_line_idx": 321 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as assert from 'assert'; import { DebugModel, StackFrame, Thread } from 'vs/workbench/contrib/debug/common/debugModel'; import * as sinon from 'sinon'; import { MockRawSession, createMockDebugModel, mockUriIdentityService } from 'vs/workbench/contrib/debug/test/browser/mockDebug'; import { Source } from 'vs/workbench/contrib/debug/common/debugSource'; import { DebugSession } from 'vs/workbench/contrib/debug/browser/debugSession'; import { Range } from 'vs/editor/common/core/range'; import { IDebugSessionOptions, State, IDebugService } from 'vs/workbench/contrib/debug/common/debug'; import { NullOpenerService } from 'vs/platform/opener/common/opener'; import { createDecorationsForStackFrame } from 'vs/workbench/contrib/debug/browser/callStackEditorContribution'; import { Constants } from 'vs/base/common/uint'; import { getContext, getContextForContributedActions, getSpecificSourceName } from 'vs/workbench/contrib/debug/browser/callStackView'; import { getStackFrameThreadAndSessionToFocus } from 'vs/workbench/contrib/debug/browser/debugService'; import { generateUuid } from 'vs/base/common/uuid'; import { debugStackframe, debugStackframeFocused } from 'vs/workbench/contrib/debug/browser/debugIcons'; import { ThemeIcon } from 'vs/platform/theme/common/themeService'; import { TestConfigurationService } from 'vs/platform/configuration/test/common/testConfigurationService'; const mockWorkspaceContextService = { getWorkspace: () => { return { folders: [] }; } } as any; export function createMockSession(model: DebugModel, name = 'mockSession', options?: IDebugSessionOptions): DebugSession { return new DebugSession(generateUuid(), { resolved: { name, type: 'node', request: 'launch' }, unresolved: undefined }, undefined!, model, options, { getViewModel(): any { return { updateViews(): void { // noop } }; } } as IDebugService, undefined!, undefined!, new TestConfigurationService({ debug: { console: { collapseIdenticalLines: true } } }), undefined!, mockWorkspaceContextService, undefined!, undefined!, NullOpenerService, undefined!, undefined!, mockUriIdentityService, undefined!); } function createTwoStackFrames(session: DebugSession): { firstStackFrame: StackFrame, secondStackFrame: StackFrame } { let firstStackFrame: StackFrame; let secondStackFrame: StackFrame; const thread = new class extends Thread { public getCallStack(): StackFrame[] { return [firstStackFrame, secondStackFrame]; } }(session, 'mockthread', 1); const firstSource = new Source({ name: 'internalModule.js', path: 'a/b/c/d/internalModule.js', sourceReference: 10, }, 'aDebugSessionId', mockUriIdentityService); const secondSource = new Source({ name: 'internalModule.js', path: 'z/x/c/d/internalModule.js', sourceReference: 11, }, 'aDebugSessionId', mockUriIdentityService); firstStackFrame = new StackFrame(thread, 0, firstSource, 'app.js', 'normal', { startLineNumber: 1, startColumn: 1, endLineNumber: 1, endColumn: 10 }, 0, true); secondStackFrame = new StackFrame(thread, 1, secondSource, 'app2.js', 'normal', { startLineNumber: 1, startColumn: 1, endLineNumber: 1, endColumn: 10 }, 1, true); return { firstStackFrame, secondStackFrame }; } suite('Debug - CallStack', () => { let model: DebugModel; let rawSession: MockRawSession; setup(() => { model = createMockDebugModel(); rawSession = new MockRawSession(); }); // Threads test('threads simple', () => { const threadId = 1; const threadName = 'firstThread'; const session = createMockSession(model); model.addSession(session); assert.strictEqual(model.getSessions(true).length, 1); model.rawUpdate({ sessionId: session.getId(), threads: [{ id: threadId, name: threadName }] }); assert.strictEqual(session.getThread(threadId)!.name, threadName); model.clearThreads(session.getId(), true); assert.strictEqual(session.getThread(threadId), undefined); assert.strictEqual(model.getSessions(true).length, 1); }); test('threads multiple wtih allThreadsStopped', async () => { const threadId1 = 1; const threadName1 = 'firstThread'; const threadId2 = 2; const threadName2 = 'secondThread'; const stoppedReason = 'breakpoint'; // Add the threads const session = createMockSession(model); model.addSession(session); session['raw'] = <any>rawSession; model.rawUpdate({ sessionId: session.getId(), threads: [{ id: threadId1, name: threadName1 }] }); // Stopped event with all threads stopped model.rawUpdate({ sessionId: session.getId(), threads: [{ id: threadId1, name: threadName1 }, { id: threadId2, name: threadName2 }], stoppedDetails: { reason: stoppedReason, threadId: 1, allThreadsStopped: true }, }); const thread1 = session.getThread(threadId1)!; const thread2 = session.getThread(threadId2)!; // at the beginning, callstacks are obtainable but not available assert.strictEqual(session.getAllThreads().length, 2); assert.strictEqual(thread1.name, threadName1); assert.strictEqual(thread1.stopped, true); assert.strictEqual(thread1.getCallStack().length, 0); assert.strictEqual(thread1.stoppedDetails!.reason, stoppedReason); assert.strictEqual(thread2.name, threadName2); assert.strictEqual(thread2.stopped, true); assert.strictEqual(thread2.getCallStack().length, 0); assert.strictEqual(thread2.stoppedDetails!.reason, undefined); // after calling getCallStack, the callstack becomes available // and results in a request for the callstack in the debug adapter await thread1.fetchCallStack(); assert.notStrictEqual(thread1.getCallStack().length, 0); await thread2.fetchCallStack(); assert.notStrictEqual(thread2.getCallStack().length, 0); // calling multiple times getCallStack doesn't result in multiple calls // to the debug adapter await thread1.fetchCallStack(); await thread2.fetchCallStack(); // clearing the callstack results in the callstack not being available thread1.clearCallStack(); assert.strictEqual(thread1.stopped, true); assert.strictEqual(thread1.getCallStack().length, 0); thread2.clearCallStack(); assert.strictEqual(thread2.stopped, true); assert.strictEqual(thread2.getCallStack().length, 0); model.clearThreads(session.getId(), true); assert.strictEqual(session.getThread(threadId1), undefined); assert.strictEqual(session.getThread(threadId2), undefined); assert.strictEqual(session.getAllThreads().length, 0); }); test('threads mutltiple without allThreadsStopped', async () => { const sessionStub = sinon.spy(rawSession, 'stackTrace'); const stoppedThreadId = 1; const stoppedThreadName = 'stoppedThread'; const runningThreadId = 2; const runningThreadName = 'runningThread'; const stoppedReason = 'breakpoint'; const session = createMockSession(model); model.addSession(session); session['raw'] = <any>rawSession; // Add the threads model.rawUpdate({ sessionId: session.getId(), threads: [{ id: stoppedThreadId, name: stoppedThreadName }] }); // Stopped event with only one thread stopped model.rawUpdate({ sessionId: session.getId(), threads: [{ id: 1, name: stoppedThreadName }, { id: runningThreadId, name: runningThreadName }], stoppedDetails: { reason: stoppedReason, threadId: 1, allThreadsStopped: false } }); const stoppedThread = session.getThread(stoppedThreadId)!; const runningThread = session.getThread(runningThreadId)!; // the callstack for the stopped thread is obtainable but not available // the callstack for the running thread is not obtainable nor available assert.strictEqual(stoppedThread.name, stoppedThreadName); assert.strictEqual(stoppedThread.stopped, true); assert.strictEqual(session.getAllThreads().length, 2); assert.strictEqual(stoppedThread.getCallStack().length, 0); assert.strictEqual(stoppedThread.stoppedDetails!.reason, stoppedReason); assert.strictEqual(runningThread.name, runningThreadName); assert.strictEqual(runningThread.stopped, false); assert.strictEqual(runningThread.getCallStack().length, 0); assert.strictEqual(runningThread.stoppedDetails, undefined); // after calling getCallStack, the callstack becomes available // and results in a request for the callstack in the debug adapter await stoppedThread.fetchCallStack(); assert.notStrictEqual(stoppedThread.getCallStack().length, 0); assert.strictEqual(runningThread.getCallStack().length, 0); assert.strictEqual(sessionStub.callCount, 1); // calling getCallStack on the running thread returns empty array // and does not return in a request for the callstack in the debug // adapter await runningThread.fetchCallStack(); assert.strictEqual(runningThread.getCallStack().length, 0); assert.strictEqual(sessionStub.callCount, 1); // clearing the callstack results in the callstack not being available stoppedThread.clearCallStack(); assert.strictEqual(stoppedThread.stopped, true); assert.strictEqual(stoppedThread.getCallStack().length, 0); model.clearThreads(session.getId(), true); assert.strictEqual(session.getThread(stoppedThreadId), undefined); assert.strictEqual(session.getThread(runningThreadId), undefined); assert.strictEqual(session.getAllThreads().length, 0); }); test('stack frame get specific source name', () => { const session = createMockSession(model); model.addSession(session); const { firstStackFrame, secondStackFrame } = createTwoStackFrames(session); assert.strictEqual(getSpecificSourceName(firstStackFrame), '.../b/c/d/internalModule.js'); assert.strictEqual(getSpecificSourceName(secondStackFrame), '.../x/c/d/internalModule.js'); }); test('stack frame toString()', () => { const session = createMockSession(model); const thread = new Thread(session, 'mockthread', 1); const firstSource = new Source({ name: 'internalModule.js', path: 'a/b/c/d/internalModule.js', sourceReference: 10, }, 'aDebugSessionId', mockUriIdentityService); const stackFrame = new StackFrame(thread, 1, firstSource, 'app', 'normal', { startLineNumber: 1, startColumn: 1, endLineNumber: 1, endColumn: 10 }, 1, true); assert.strictEqual(stackFrame.toString(), 'app (internalModule.js:1)'); const secondSource = new Source(undefined, 'aDebugSessionId', mockUriIdentityService); const stackFrame2 = new StackFrame(thread, 2, secondSource, 'module', 'normal', { startLineNumber: undefined!, startColumn: undefined!, endLineNumber: undefined!, endColumn: undefined! }, 2, true); assert.strictEqual(stackFrame2.toString(), 'module'); }); test('debug child sessions are added in correct order', () => { const session = createMockSession(model); model.addSession(session); const secondSession = createMockSession(model, 'mockSession2'); model.addSession(secondSession); const firstChild = createMockSession(model, 'firstChild', { parentSession: session }); model.addSession(firstChild); const secondChild = createMockSession(model, 'secondChild', { parentSession: session }); model.addSession(secondChild); const thirdSession = createMockSession(model, 'mockSession3'); model.addSession(thirdSession); const anotherChild = createMockSession(model, 'secondChild', { parentSession: secondSession }); model.addSession(anotherChild); const sessions = model.getSessions(); assert.strictEqual(sessions[0].getId(), session.getId()); assert.strictEqual(sessions[1].getId(), firstChild.getId()); assert.strictEqual(sessions[2].getId(), secondChild.getId()); assert.strictEqual(sessions[3].getId(), secondSession.getId()); assert.strictEqual(sessions[4].getId(), anotherChild.getId()); assert.strictEqual(sessions[5].getId(), thirdSession.getId()); }); test('decorations', () => { const session = createMockSession(model); model.addSession(session); const { firstStackFrame, secondStackFrame } = createTwoStackFrames(session); let decorations = createDecorationsForStackFrame(firstStackFrame, firstStackFrame.range, true); assert.strictEqual(decorations.length, 2); assert.deepStrictEqual(decorations[0].range, new Range(1, 2, 1, 1)); assert.strictEqual(decorations[0].options.glyphMarginClassName, ThemeIcon.asClassName(debugStackframe)); assert.deepStrictEqual(decorations[1].range, new Range(1, Constants.MAX_SAFE_SMALL_INTEGER, 1, 1)); assert.strictEqual(decorations[1].options.className, 'debug-top-stack-frame-line'); assert.strictEqual(decorations[1].options.isWholeLine, true); decorations = createDecorationsForStackFrame(secondStackFrame, firstStackFrame.range, true); assert.strictEqual(decorations.length, 2); assert.deepStrictEqual(decorations[0].range, new Range(1, 2, 1, 1)); assert.strictEqual(decorations[0].options.glyphMarginClassName, ThemeIcon.asClassName(debugStackframeFocused)); assert.deepStrictEqual(decorations[1].range, new Range(1, Constants.MAX_SAFE_SMALL_INTEGER, 1, 1)); assert.strictEqual(decorations[1].options.className, 'debug-focused-stack-frame-line'); assert.strictEqual(decorations[1].options.isWholeLine, true); decorations = createDecorationsForStackFrame(firstStackFrame, new Range(1, 5, 1, 6), true); assert.strictEqual(decorations.length, 3); assert.deepStrictEqual(decorations[0].range, new Range(1, 2, 1, 1)); assert.strictEqual(decorations[0].options.glyphMarginClassName, ThemeIcon.asClassName(debugStackframe)); assert.deepStrictEqual(decorations[1].range, new Range(1, Constants.MAX_SAFE_SMALL_INTEGER, 1, 1)); assert.strictEqual(decorations[1].options.className, 'debug-top-stack-frame-line'); assert.strictEqual(decorations[1].options.isWholeLine, true); // Inline decoration gets rendered in this case assert.strictEqual(decorations[2].options.beforeContentClassName, 'debug-top-stack-frame-column'); assert.deepStrictEqual(decorations[2].range, new Range(1, Constants.MAX_SAFE_SMALL_INTEGER, 1, 1)); }); test('contexts', () => { const session = createMockSession(model); model.addSession(session); const { firstStackFrame, secondStackFrame } = createTwoStackFrames(session); let context = getContext(firstStackFrame); assert.strictEqual(context.sessionId, firstStackFrame.thread.session.getId()); assert.strictEqual(context.threadId, firstStackFrame.thread.getId()); assert.strictEqual(context.frameId, firstStackFrame.getId()); context = getContext(secondStackFrame.thread); assert.strictEqual(context.sessionId, secondStackFrame.thread.session.getId()); assert.strictEqual(context.threadId, secondStackFrame.thread.getId()); assert.strictEqual(context.frameId, undefined); context = getContext(session); assert.strictEqual(context.sessionId, session.getId()); assert.strictEqual(context.threadId, undefined); assert.strictEqual(context.frameId, undefined); let contributedContext = getContextForContributedActions(firstStackFrame); assert.strictEqual(contributedContext, firstStackFrame.source.raw.path); contributedContext = getContextForContributedActions(firstStackFrame.thread); assert.strictEqual(contributedContext, firstStackFrame.thread.threadId); contributedContext = getContextForContributedActions(session); assert.strictEqual(contributedContext, session.getId()); }); test('focusStackFrameThreadAndSesion', () => { const threadId1 = 1; const threadName1 = 'firstThread'; const threadId2 = 2; const threadName2 = 'secondThread'; const stoppedReason = 'breakpoint'; // Add the threads const session = new class extends DebugSession { get state(): State { return State.Stopped; } }(generateUuid(), { resolved: { name: 'stoppedSession', type: 'node', request: 'launch' }, unresolved: undefined }, undefined!, model, undefined, undefined!, undefined!, undefined!, undefined!, undefined!, mockWorkspaceContextService, undefined!, undefined!, NullOpenerService, undefined!, undefined!, mockUriIdentityService, undefined!); const runningSession = createMockSession(model); model.addSession(runningSession); model.addSession(session); session['raw'] = <any>rawSession; model.rawUpdate({ sessionId: session.getId(), threads: [{ id: threadId1, name: threadName1 }] }); // Stopped event with all threads stopped model.rawUpdate({ sessionId: session.getId(), threads: [{ id: threadId1, name: threadName1 }, { id: threadId2, name: threadName2 }], stoppedDetails: { reason: stoppedReason, threadId: 1, allThreadsStopped: true }, }); const thread = session.getThread(threadId1)!; const runningThread = session.getThread(threadId2); let toFocus = getStackFrameThreadAndSessionToFocus(model, undefined); // Verify stopped session and stopped thread get focused assert.deepStrictEqual(toFocus, { stackFrame: undefined, thread: thread, session: session }); toFocus = getStackFrameThreadAndSessionToFocus(model, undefined, undefined, runningSession); assert.deepStrictEqual(toFocus, { stackFrame: undefined, thread: undefined, session: runningSession }); toFocus = getStackFrameThreadAndSessionToFocus(model, undefined, thread); assert.deepStrictEqual(toFocus, { stackFrame: undefined, thread: thread, session: session }); toFocus = getStackFrameThreadAndSessionToFocus(model, undefined, runningThread); assert.deepStrictEqual(toFocus, { stackFrame: undefined, thread: runningThread, session: session }); const stackFrame = new StackFrame(thread, 5, undefined!, 'stackframename2', undefined, undefined!, 1, true); toFocus = getStackFrameThreadAndSessionToFocus(model, stackFrame); assert.deepStrictEqual(toFocus, { stackFrame: stackFrame, thread: thread, session: session }); }); });
src/vs/workbench/contrib/debug/test/browser/callStack.test.ts
1
https://github.com/microsoft/vscode/commit/f554a745505474ba031a79f5ab4a5c9d1ed3af39
[ 0.9980496168136597, 0.06761574000120163, 0.00016236981900874525, 0.0001715757098281756, 0.2483929693698883 ]
{ "id": 6, "code_window": [ "\t\tassert.strictEqual(decorations[1].options.className, 'debug-top-stack-frame-line');\n", "\t\tassert.strictEqual(decorations[1].options.isWholeLine, true);\n", "\n", "\t\tdecorations = createDecorationsForStackFrame(secondStackFrame, firstStackFrame.range, true);\n", "\t\tassert.strictEqual(decorations.length, 2);\n", "\t\tassert.deepStrictEqual(decorations[0].range, new Range(1, 2, 1, 1));\n", "\t\tassert.strictEqual(decorations[0].options.glyphMarginClassName, ThemeIcon.asClassName(debugStackframeFocused));\n", "\t\tassert.deepStrictEqual(decorations[1].range, new Range(1, Constants.MAX_SAFE_SMALL_INTEGER, 1, 1));\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tdecorations = createDecorationsForStackFrame(secondStackFrame, true);\n" ], "file_path": "src/vs/workbench/contrib/debug/test/browser/callStack.test.ts", "type": "replace", "edit_start_line_idx": 321 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { URI } from 'vs/base/common/uri'; import { IDisposable } from 'vs/base/common/lifecycle'; import { Registry } from 'vs/platform/registry/common/platform'; import { IConfigurationRegistry, Extensions as ConfigurationExtensions, ConfigurationScope, getScopes } from 'vs/platform/configuration/common/configurationRegistry'; import { IWorkspaceContextService, WorkbenchState } from 'vs/platform/workspace/common/workspace'; import { MainThreadConfigurationShape, MainContext, ExtHostContext, IExtHostContext, IConfigurationInitData } from '../common/extHost.protocol'; import { extHostNamedCustomer } from 'vs/workbench/api/common/extHostCustomers'; import { ConfigurationTarget, IConfigurationService, IConfigurationOverrides } from 'vs/platform/configuration/common/configuration'; import { IEnvironmentService } from 'vs/platform/environment/common/environment'; @extHostNamedCustomer(MainContext.MainThreadConfiguration) export class MainThreadConfiguration implements MainThreadConfigurationShape { private readonly _configurationListener: IDisposable; constructor( extHostContext: IExtHostContext, @IWorkspaceContextService private readonly _workspaceContextService: IWorkspaceContextService, @IConfigurationService private readonly configurationService: IConfigurationService, @IEnvironmentService private readonly _environmentService: IEnvironmentService, ) { const proxy = extHostContext.getProxy(ExtHostContext.ExtHostConfiguration); proxy.$initializeConfiguration(this._getConfigurationData()); this._configurationListener = configurationService.onDidChangeConfiguration(e => { proxy.$acceptConfigurationChanged(this._getConfigurationData(), e.change); }); } private _getConfigurationData(): IConfigurationInitData { const configurationData: IConfigurationInitData = { ...(this.configurationService.getConfigurationData()!), configurationScopes: [] }; // Send configurations scopes only in development mode. if (!this._environmentService.isBuilt || this._environmentService.isExtensionDevelopment) { configurationData.configurationScopes = getScopes(); } return configurationData; } public dispose(): void { this._configurationListener.dispose(); } $updateConfigurationOption(target: ConfigurationTarget | null, key: string, value: any, overrides: IConfigurationOverrides | undefined, scopeToLanguage: boolean | undefined): Promise<void> { overrides = { resource: overrides?.resource ? URI.revive(overrides.resource) : undefined, overrideIdentifier: overrides?.overrideIdentifier }; return this.writeConfiguration(target, key, value, overrides, scopeToLanguage); } $removeConfigurationOption(target: ConfigurationTarget | null, key: string, overrides: IConfigurationOverrides | undefined, scopeToLanguage: boolean | undefined): Promise<void> { overrides = { resource: overrides?.resource ? URI.revive(overrides.resource) : undefined, overrideIdentifier: overrides?.overrideIdentifier }; return this.writeConfiguration(target, key, undefined, overrides, scopeToLanguage); } private writeConfiguration(target: ConfigurationTarget | null, key: string, value: any, overrides: IConfigurationOverrides, scopeToLanguage: boolean | undefined): Promise<void> { target = target !== null && target !== undefined ? target : this.deriveConfigurationTarget(key, overrides); const configurationValue = this.configurationService.inspect(key, overrides); switch (target) { case ConfigurationTarget.MEMORY: return this._updateValue(key, value, target, configurationValue?.memory?.override, overrides, scopeToLanguage); case ConfigurationTarget.WORKSPACE_FOLDER: return this._updateValue(key, value, target, configurationValue?.workspaceFolder?.override, overrides, scopeToLanguage); case ConfigurationTarget.WORKSPACE: return this._updateValue(key, value, target, configurationValue?.workspace?.override, overrides, scopeToLanguage); case ConfigurationTarget.USER_REMOTE: return this._updateValue(key, value, target, configurationValue?.userRemote?.override, overrides, scopeToLanguage); default: return this._updateValue(key, value, target, configurationValue?.userLocal?.override, overrides, scopeToLanguage); } } private _updateValue(key: string, value: any, configurationTarget: ConfigurationTarget, overriddenValue: any | undefined, overrides: IConfigurationOverrides, scopeToLanguage: boolean | undefined): Promise<void> { overrides = scopeToLanguage === true ? overrides : scopeToLanguage === false ? { resource: overrides.resource } : overrides.overrideIdentifier && overriddenValue !== undefined ? overrides : { resource: overrides.resource }; return this.configurationService.updateValue(key, value, overrides, configurationTarget, true); } private deriveConfigurationTarget(key: string, overrides: IConfigurationOverrides): ConfigurationTarget { if (overrides.resource && this._workspaceContextService.getWorkbenchState() === WorkbenchState.WORKSPACE) { const configurationProperties = Registry.as<IConfigurationRegistry>(ConfigurationExtensions.Configuration).getConfigurationProperties(); if (configurationProperties[key] && (configurationProperties[key].scope === ConfigurationScope.RESOURCE || configurationProperties[key].scope === ConfigurationScope.LANGUAGE_OVERRIDABLE)) { return ConfigurationTarget.WORKSPACE_FOLDER; } } return ConfigurationTarget.WORKSPACE; } }
src/vs/workbench/api/browser/mainThreadConfiguration.ts
0
https://github.com/microsoft/vscode/commit/f554a745505474ba031a79f5ab4a5c9d1ed3af39
[ 0.00017618920537643135, 0.00017290822870563716, 0.00016848639643285424, 0.00017318909522145987, 0.0000024633040993649047 ]
{ "id": 6, "code_window": [ "\t\tassert.strictEqual(decorations[1].options.className, 'debug-top-stack-frame-line');\n", "\t\tassert.strictEqual(decorations[1].options.isWholeLine, true);\n", "\n", "\t\tdecorations = createDecorationsForStackFrame(secondStackFrame, firstStackFrame.range, true);\n", "\t\tassert.strictEqual(decorations.length, 2);\n", "\t\tassert.deepStrictEqual(decorations[0].range, new Range(1, 2, 1, 1));\n", "\t\tassert.strictEqual(decorations[0].options.glyphMarginClassName, ThemeIcon.asClassName(debugStackframeFocused));\n", "\t\tassert.deepStrictEqual(decorations[1].range, new Range(1, Constants.MAX_SAFE_SMALL_INTEGER, 1, 1));\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tdecorations = createDecorationsForStackFrame(secondStackFrame, true);\n" ], "file_path": "src/vs/workbench/contrib/debug/test/browser/callStack.test.ts", "type": "replace", "edit_start_line_idx": 321 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import 'mocha'; import * as assert from 'assert'; import * as path from 'path'; import { URI } from 'vscode-uri'; import { TextDocument, CompletionList, TextEdit } from 'vscode-languageserver-types'; import { WorkspaceFolder } from 'vscode-languageserver-protocol'; import { getCSSLanguageService, LanguageServiceOptions, getSCSSLanguageService } from 'vscode-css-languageservice'; import { getNodeFSRequestService } from '../node/nodeFs'; import { getDocumentContext } from '../utils/documentContext'; export interface ItemDescription { label: string; resultText?: string; } suite('Completions', () => { let assertCompletion = function (completions: CompletionList, expected: ItemDescription, document: TextDocument, _offset: number) { let matches = completions.items.filter(completion => { return completion.label === expected.label; }); assert.equal(matches.length, 1, `${expected.label} should only existing once: Actual: ${completions.items.map(c => c.label).join(', ')}`); let match = matches[0]; if (expected.resultText && TextEdit.is(match.textEdit)) { assert.equal(TextDocument.applyEdits(document, [match.textEdit]), expected.resultText); } }; async function assertCompletions(value: string, expected: { count?: number, items?: ItemDescription[] }, testUri: string, workspaceFolders?: WorkspaceFolder[], lang: string = 'css'): Promise<any> { const offset = value.indexOf('|'); value = value.substr(0, offset) + value.substr(offset + 1); const document = TextDocument.create(testUri, lang, 0, value); const position = document.positionAt(offset); if (!workspaceFolders) { workspaceFolders = [{ name: 'x', uri: testUri.substr(0, testUri.lastIndexOf('/')) }]; } const lsOptions: LanguageServiceOptions = { fileSystemProvider: getNodeFSRequestService() }; const cssLanguageService = lang === 'scss' ? getSCSSLanguageService(lsOptions) : getCSSLanguageService(lsOptions); const context = getDocumentContext(testUri, workspaceFolders); const stylesheet = cssLanguageService.parseStylesheet(document); let list = await cssLanguageService.doComplete2(document, position, stylesheet, context); if (expected.count) { assert.equal(list.items.length, expected.count); } if (expected.items) { for (let item of expected.items) { assertCompletion(list, item, document, offset); } } } test('CSS url() Path completion', async function () { let testUri = URI.file(path.resolve(__dirname, '../../test/pathCompletionFixtures/about/about.css')).toString(); let folders = [{ name: 'x', uri: URI.file(path.resolve(__dirname, '../../test')).toString() }]; await assertCompletions('html { background-image: url("./|")', { items: [ { label: 'about.html', resultText: 'html { background-image: url("./about.html")' } ] }, testUri, folders); await assertCompletions(`html { background-image: url('../|')`, { items: [ { label: 'about/', resultText: `html { background-image: url('../about/')` }, { label: 'index.html', resultText: `html { background-image: url('../index.html')` }, { label: 'src/', resultText: `html { background-image: url('../src/')` } ] }, testUri, folders); await assertCompletions(`html { background-image: url('../src/a|')`, { items: [ { label: 'feature.js', resultText: `html { background-image: url('../src/feature.js')` }, { label: 'data/', resultText: `html { background-image: url('../src/data/')` }, { label: 'test.js', resultText: `html { background-image: url('../src/test.js')` } ] }, testUri, folders); await assertCompletions(`html { background-image: url('../src/data/f|.asar')`, { items: [ { label: 'foo.asar', resultText: `html { background-image: url('../src/data/foo.asar')` } ] }, testUri, folders); await assertCompletions(`html { background-image: url('|')`, { items: [ { label: 'about.html', resultText: `html { background-image: url('about.html')` }, ] }, testUri, folders); await assertCompletions(`html { background-image: url('/|')`, { items: [ { label: 'pathCompletionFixtures/', resultText: `html { background-image: url('/pathCompletionFixtures/')` } ] }, testUri, folders); await assertCompletions(`html { background-image: url('/pathCompletionFixtures/|')`, { items: [ { label: 'about/', resultText: `html { background-image: url('/pathCompletionFixtures/about/')` }, { label: 'index.html', resultText: `html { background-image: url('/pathCompletionFixtures/index.html')` }, { label: 'src/', resultText: `html { background-image: url('/pathCompletionFixtures/src/')` } ] }, testUri, folders); await assertCompletions(`html { background-image: url("/|")`, { items: [ { label: 'pathCompletionFixtures/', resultText: `html { background-image: url("/pathCompletionFixtures/")` } ] }, testUri, folders); }); test('CSS url() Path Completion - Unquoted url', async function () { let testUri = URI.file(path.resolve(__dirname, '../../test/pathCompletionFixtures/about/about.css')).toString(); let folders = [{ name: 'x', uri: URI.file(path.resolve(__dirname, '../../test')).toString() }]; await assertCompletions('html { background-image: url(./|)', { items: [ { label: 'about.html', resultText: 'html { background-image: url(./about.html)' } ] }, testUri, folders); await assertCompletions('html { background-image: url(./a|)', { items: [ { label: 'about.html', resultText: 'html { background-image: url(./about.html)' } ] }, testUri, folders); await assertCompletions('html { background-image: url(../|src/)', { items: [ { label: 'about/', resultText: 'html { background-image: url(../about/)' } ] }, testUri, folders); await assertCompletions('html { background-image: url(../s|rc/)', { items: [ { label: 'about/', resultText: 'html { background-image: url(../about/)' } ] }, testUri, folders); }); test('CSS @import Path completion', async function () { let testUri = URI.file(path.resolve(__dirname, '../../test/pathCompletionFixtures/about/about.css')).toString(); let folders = [{ name: 'x', uri: URI.file(path.resolve(__dirname, '../../test')).toString() }]; await assertCompletions(`@import './|'`, { items: [ { label: 'about.html', resultText: `@import './about.html'` }, ] }, testUri, folders); await assertCompletions(`@import '../|'`, { items: [ { label: 'about/', resultText: `@import '../about/'` }, { label: 'scss/', resultText: `@import '../scss/'` }, { label: 'index.html', resultText: `@import '../index.html'` }, { label: 'src/', resultText: `@import '../src/'` } ] }, testUri, folders); }); /** * For SCSS, `@import 'foo';` can be used for importing partial file `_foo.scss` */ test('SCSS @import Path completion', async function () { let testCSSUri = URI.file(path.resolve(__dirname, '../../test/pathCompletionFixtures/about/about.css')).toString(); let folders = [{ name: 'x', uri: URI.file(path.resolve(__dirname, '../../test')).toString() }]; /** * We are in a CSS file, so no special treatment for SCSS partial files */ await assertCompletions(`@import '../scss/|'`, { items: [ { label: 'main.scss', resultText: `@import '../scss/main.scss'` }, { label: '_foo.scss', resultText: `@import '../scss/_foo.scss'` } ] }, testCSSUri, folders); let testSCSSUri = URI.file(path.resolve(__dirname, '../../test/pathCompletionFixtures/scss/main.scss')).toString(); await assertCompletions(`@import './|'`, { items: [ { label: '_foo.scss', resultText: `@import './foo'` } ] }, testSCSSUri, folders, 'scss'); }); test('Completion should ignore files/folders starting with dot', async function () { let testUri = URI.file(path.resolve(__dirname, '../../test/pathCompletionFixtures/about/about.css')).toString(); let folders = [{ name: 'x', uri: URI.file(path.resolve(__dirname, '../../test')).toString() }]; await assertCompletions('html { background-image: url("../|")', { count: 4 }, testUri, folders); }); });
extensions/css-language-features/server/src/test/completion.test.ts
0
https://github.com/microsoft/vscode/commit/f554a745505474ba031a79f5ab4a5c9d1ed3af39
[ 0.00017653997929301113, 0.00017402494268026203, 0.00017010807641781867, 0.00017420464428141713, 0.000001974313818209339 ]
{ "id": 6, "code_window": [ "\t\tassert.strictEqual(decorations[1].options.className, 'debug-top-stack-frame-line');\n", "\t\tassert.strictEqual(decorations[1].options.isWholeLine, true);\n", "\n", "\t\tdecorations = createDecorationsForStackFrame(secondStackFrame, firstStackFrame.range, true);\n", "\t\tassert.strictEqual(decorations.length, 2);\n", "\t\tassert.deepStrictEqual(decorations[0].range, new Range(1, 2, 1, 1));\n", "\t\tassert.strictEqual(decorations[0].options.glyphMarginClassName, ThemeIcon.asClassName(debugStackframeFocused));\n", "\t\tassert.deepStrictEqual(decorations[1].range, new Range(1, Constants.MAX_SAFE_SMALL_INTEGER, 1, 1));\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tdecorations = createDecorationsForStackFrame(secondStackFrame, true);\n" ], "file_path": "src/vs/workbench/contrib/debug/test/browser/callStack.test.ts", "type": "replace", "edit_start_line_idx": 321 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // a webpack loader that bundles all library definitions (d.ts) for the embedded JavaScript engine. const path = require('path'); const fs = require('fs'); const TYPESCRIPT_LIB_SOURCE = path.join(__dirname, '../../../node_modules/typescript/lib'); const JQUERY_DTS = path.join(__dirname, '../lib/jquery.d.ts'); module.exports = function () { function getFileName(name) { return (name === '' ? 'lib.d.ts' : `lib.${name}.d.ts`); } function readLibFile(name) { var srcPath = path.join(TYPESCRIPT_LIB_SOURCE, getFileName(name)); return fs.readFileSync(srcPath).toString(); } var queue = []; var in_queue = {}; var enqueue = function (name) { if (in_queue[name]) { return; } in_queue[name] = true; queue.push(name); }; enqueue('es6'); var result = []; while (queue.length > 0) { var name = queue.shift(); var contents = readLibFile(name); var lines = contents.split(/\r\n|\r|\n/); var outputLines = []; for (let i = 0; i < lines.length; i++) { let m = lines[i].match(/\/\/\/\s*<reference\s*lib="([^"]+)"/); if (m) { enqueue(m[1]); } outputLines.push(lines[i]); } result.push({ name: getFileName(name), output: `"${escapeText(outputLines.join('\n'))}"` }); } const jquerySource = fs.readFileSync(JQUERY_DTS).toString(); var lines = jquerySource.split(/\r\n|\r|\n/); result.push({ name: 'jquery', output: `"${escapeText(lines.join('\n'))}"` }); strResult = `\nconst libs : { [name:string]: string; } = {\n` for (let i = result.length - 1; i >= 0; i--) { strResult += `"${result[i].name}": ${result[i].output},\n`; } strResult += `\n};` strResult += `export function loadLibrary(name: string) : string {\n return libs[name] || ''; \n}`; return strResult; } /** * Escape text such that it can be used in a javascript string enclosed by double quotes (") */ function escapeText(text) { // See http://www.javascriptkit.com/jsref/escapesequence.shtml var _backspace = '\b'.charCodeAt(0); var _formFeed = '\f'.charCodeAt(0); var _newLine = '\n'.charCodeAt(0); var _nullChar = 0; var _carriageReturn = '\r'.charCodeAt(0); var _tab = '\t'.charCodeAt(0); var _verticalTab = '\v'.charCodeAt(0); var _backslash = '\\'.charCodeAt(0); var _doubleQuote = '"'.charCodeAt(0); var startPos = 0, chrCode, replaceWith = null, resultPieces = []; for (var i = 0, len = text.length; i < len; i++) { chrCode = text.charCodeAt(i); switch (chrCode) { case _backspace: replaceWith = '\\b'; break; case _formFeed: replaceWith = '\\f'; break; case _newLine: replaceWith = '\\n'; break; case _nullChar: replaceWith = '\\0'; break; case _carriageReturn: replaceWith = '\\r'; break; case _tab: replaceWith = '\\t'; break; case _verticalTab: replaceWith = '\\v'; break; case _backslash: replaceWith = '\\\\'; break; case _doubleQuote: replaceWith = '\\"'; break; } if (replaceWith !== null) { resultPieces.push(text.substring(startPos, i)); resultPieces.push(replaceWith); startPos = i + 1; replaceWith = null; } } resultPieces.push(text.substring(startPos, len)); return resultPieces.join(''); }
extensions/html-language-features/server/build/javaScriptLibraryLoader.js
0
https://github.com/microsoft/vscode/commit/f554a745505474ba031a79f5ab4a5c9d1ed3af39
[ 0.0001770332019077614, 0.00017126044258475304, 0.00016470931586809456, 0.00017177725385408849, 0.0000035642756301967893 ]
{ "id": 7, "code_window": [ "\t\tassert.strictEqual(decorations[1].options.className, 'debug-focused-stack-frame-line');\n", "\t\tassert.strictEqual(decorations[1].options.isWholeLine, true);\n", "\n", "\t\tdecorations = createDecorationsForStackFrame(firstStackFrame, new Range(1, 5, 1, 6), true);\n", "\t\tassert.strictEqual(decorations.length, 3);\n", "\t\tassert.deepStrictEqual(decorations[0].range, new Range(1, 2, 1, 1));\n", "\t\tassert.strictEqual(decorations[0].options.glyphMarginClassName, ThemeIcon.asClassName(debugStackframe));\n", "\t\tassert.deepStrictEqual(decorations[1].range, new Range(1, Constants.MAX_SAFE_SMALL_INTEGER, 1, 1));\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tdecorations = createDecorationsForStackFrame(firstStackFrame, true);\n" ], "file_path": "src/vs/workbench/contrib/debug/test/browser/callStack.test.ts", "type": "replace", "edit_start_line_idx": 329 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Constants } from 'vs/base/common/uint'; import { Range, IRange } from 'vs/editor/common/core/range'; import { TrackedRangeStickiness, IModelDeltaDecoration, IModelDecorationOptions, OverviewRulerLane } from 'vs/editor/common/model'; import { IDebugService, IStackFrame } from 'vs/workbench/contrib/debug/common/debug'; import { registerThemingParticipant, themeColorFromId, ThemeIcon } from 'vs/platform/theme/common/themeService'; import { registerColor } from 'vs/platform/theme/common/colorRegistry'; import { localize } from 'vs/nls'; import { Event } from 'vs/base/common/event'; import { IDisposable, dispose } from 'vs/base/common/lifecycle'; import { IEditorContribution } from 'vs/editor/common/editorCommon'; import { ICodeEditor } from 'vs/editor/browser/editorBrowser'; import { distinct } from 'vs/base/common/arrays'; import { IUriIdentityService } from 'vs/workbench/services/uriIdentity/common/uriIdentity'; import { debugStackframe, debugStackframeFocused } from 'vs/workbench/contrib/debug/browser/debugIcons'; const topStackFrameColor = registerColor('editor.stackFrameHighlightBackground', { dark: '#ffff0033', light: '#ffff6673', hc: '#ffff0033' }, localize('topStackFrameLineHighlight', 'Background color for the highlight of line at the top stack frame position.')); const focusedStackFrameColor = registerColor('editor.focusedStackFrameHighlightBackground', { dark: '#7abd7a4d', light: '#cee7ce73', hc: '#7abd7a4d' }, localize('focusedStackFrameLineHighlight', 'Background color for the highlight of line at focused stack frame position.')); const stickiness = TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges; // we need a separate decoration for glyph margin, since we do not want it on each line of a multi line statement. const TOP_STACK_FRAME_MARGIN: IModelDecorationOptions = { glyphMarginClassName: ThemeIcon.asClassName(debugStackframe), stickiness, overviewRuler: { position: OverviewRulerLane.Full, color: themeColorFromId(topStackFrameColor) } }; const FOCUSED_STACK_FRAME_MARGIN: IModelDecorationOptions = { glyphMarginClassName: ThemeIcon.asClassName(debugStackframeFocused), stickiness, overviewRuler: { position: OverviewRulerLane.Full, color: themeColorFromId(focusedStackFrameColor) } }; const TOP_STACK_FRAME_DECORATION: IModelDecorationOptions = { isWholeLine: true, className: 'debug-top-stack-frame-line', stickiness }; const TOP_STACK_FRAME_INLINE_DECORATION: IModelDecorationOptions = { beforeContentClassName: 'debug-top-stack-frame-column' }; const FOCUSED_STACK_FRAME_DECORATION: IModelDecorationOptions = { isWholeLine: true, className: 'debug-focused-stack-frame-line', stickiness }; export function createDecorationsForStackFrame(stackFrame: IStackFrame, topStackFrameRange: IRange | undefined, isFocusedSession: boolean): IModelDeltaDecoration[] { // only show decorations for the currently focused thread. const result: IModelDeltaDecoration[] = []; const columnUntilEOLRange = new Range(stackFrame.range.startLineNumber, stackFrame.range.startColumn, stackFrame.range.startLineNumber, Constants.MAX_SAFE_SMALL_INTEGER); const range = new Range(stackFrame.range.startLineNumber, stackFrame.range.startColumn, stackFrame.range.startLineNumber, stackFrame.range.startColumn + 1); // compute how to decorate the editor. Different decorations are used if this is a top stack frame, focused stack frame, // an exception or a stack frame that did not change the line number (we only decorate the columns, not the whole line). const topStackFrame = stackFrame.thread.getTopStackFrame(); if (stackFrame.getId() === topStackFrame?.getId()) { if (isFocusedSession) { result.push({ options: TOP_STACK_FRAME_MARGIN, range }); } result.push({ options: TOP_STACK_FRAME_DECORATION, range: columnUntilEOLRange }); if (topStackFrameRange && topStackFrameRange.startLineNumber === stackFrame.range.startLineNumber && topStackFrameRange.startColumn !== stackFrame.range.startColumn) { result.push({ options: TOP_STACK_FRAME_INLINE_DECORATION, range: columnUntilEOLRange }); } topStackFrameRange = columnUntilEOLRange; } else { if (isFocusedSession) { result.push({ options: FOCUSED_STACK_FRAME_MARGIN, range }); } result.push({ options: FOCUSED_STACK_FRAME_DECORATION, range: columnUntilEOLRange }); } return result; } export class CallStackEditorContribution implements IEditorContribution { private toDispose: IDisposable[] = []; private decorationIds: string[] = []; private topStackFrameRange: Range | undefined; constructor( private readonly editor: ICodeEditor, @IDebugService private readonly debugService: IDebugService, @IUriIdentityService private readonly uriIdentityService: IUriIdentityService ) { const setDecorations = () => this.decorationIds = this.editor.deltaDecorations(this.decorationIds, this.createCallStackDecorations()); this.toDispose.push(Event.any(this.debugService.getViewModel().onDidFocusStackFrame, this.debugService.getModel().onDidChangeCallStack)(() => { setDecorations(); })); this.toDispose.push(this.editor.onDidChangeModel(e => { if (e.newModelUrl) { setDecorations(); } })); } private createCallStackDecorations(): IModelDeltaDecoration[] { const focusedStackFrame = this.debugService.getViewModel().focusedStackFrame; const decorations: IModelDeltaDecoration[] = []; this.debugService.getModel().getSessions().forEach(s => { const isSessionFocused = s === focusedStackFrame?.thread.session; s.getAllThreads().forEach(t => { if (t.stopped) { const callStack = t.getCallStack(); const stackFrames: IStackFrame[] = []; if (callStack.length > 0) { // Always decorate top stack frame, and decorate focused stack frame if it is not the top stack frame if (focusedStackFrame && !focusedStackFrame.equals(callStack[0])) { stackFrames.push(focusedStackFrame); } stackFrames.push(callStack[0]); } stackFrames.forEach(candidateStackFrame => { if (candidateStackFrame && this.uriIdentityService.extUri.isEqual(candidateStackFrame.source.uri, this.editor.getModel()?.uri)) { decorations.push(...createDecorationsForStackFrame(candidateStackFrame, this.topStackFrameRange, isSessionFocused)); } }); } }); }); // Deduplicate same decorations so colors do not stack #109045 return distinct(decorations, d => `${d.options.className} ${d.options.glyphMarginClassName} ${d.range.startLineNumber} ${d.range.startColumn}`); } dispose(): void { this.editor.deltaDecorations(this.decorationIds, []); this.toDispose = dispose(this.toDispose); } } registerThemingParticipant((theme, collector) => { const topStackFrame = theme.getColor(topStackFrameColor); if (topStackFrame) { collector.addRule(`.monaco-editor .view-overlays .debug-top-stack-frame-line { background: ${topStackFrame}; }`); } const focusedStackFrame = theme.getColor(focusedStackFrameColor); if (focusedStackFrame) { collector.addRule(`.monaco-editor .view-overlays .debug-focused-stack-frame-line { background: ${focusedStackFrame}; }`); } });
src/vs/workbench/contrib/debug/browser/callStackEditorContribution.ts
1
https://github.com/microsoft/vscode/commit/f554a745505474ba031a79f5ab4a5c9d1ed3af39
[ 0.9968830943107605, 0.06262198835611343, 0.0001636413944652304, 0.001274215872399509, 0.23370428383350372 ]
{ "id": 7, "code_window": [ "\t\tassert.strictEqual(decorations[1].options.className, 'debug-focused-stack-frame-line');\n", "\t\tassert.strictEqual(decorations[1].options.isWholeLine, true);\n", "\n", "\t\tdecorations = createDecorationsForStackFrame(firstStackFrame, new Range(1, 5, 1, 6), true);\n", "\t\tassert.strictEqual(decorations.length, 3);\n", "\t\tassert.deepStrictEqual(decorations[0].range, new Range(1, 2, 1, 1));\n", "\t\tassert.strictEqual(decorations[0].options.glyphMarginClassName, ThemeIcon.asClassName(debugStackframe));\n", "\t\tassert.deepStrictEqual(decorations[1].range, new Range(1, Constants.MAX_SAFE_SMALL_INTEGER, 1, 1));\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tdecorations = createDecorationsForStackFrame(firstStackFrame, true);\n" ], "file_path": "src/vs/workbench/contrib/debug/test/browser/callStack.test.ts", "type": "replace", "edit_start_line_idx": 329 }
# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. # yarn lockfile v1
extensions/css/yarn.lock
0
https://github.com/microsoft/vscode/commit/f554a745505474ba031a79f5ab4a5c9d1ed3af39
[ 0.00016587230493314564, 0.00016587230493314564, 0.00016587230493314564, 0.00016587230493314564, 0 ]
{ "id": 7, "code_window": [ "\t\tassert.strictEqual(decorations[1].options.className, 'debug-focused-stack-frame-line');\n", "\t\tassert.strictEqual(decorations[1].options.isWholeLine, true);\n", "\n", "\t\tdecorations = createDecorationsForStackFrame(firstStackFrame, new Range(1, 5, 1, 6), true);\n", "\t\tassert.strictEqual(decorations.length, 3);\n", "\t\tassert.deepStrictEqual(decorations[0].range, new Range(1, 2, 1, 1));\n", "\t\tassert.strictEqual(decorations[0].options.glyphMarginClassName, ThemeIcon.asClassName(debugStackframe));\n", "\t\tassert.deepStrictEqual(decorations[1].range, new Range(1, Constants.MAX_SAFE_SMALL_INTEGER, 1, 1));\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tdecorations = createDecorationsForStackFrame(firstStackFrame, true);\n" ], "file_path": "src/vs/workbench/contrib/debug/test/browser/callStack.test.ts", "type": "replace", "edit_start_line_idx": 329 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as assert from 'assert'; import { getDomainsOfRemotes, getRemotes } from 'vs/platform/extensionManagement/common/configRemotes'; suite('Config Remotes', () => { const allowedDomains = [ 'github.com', 'github2.com', 'github3.com', 'example.com', 'example2.com', 'example3.com', 'server.org', 'server2.org', ]; test('HTTPS remotes', function () { assert.deepStrictEqual(getDomainsOfRemotes(remote('https://github.com/microsoft/vscode.git'), allowedDomains), ['github.com']); assert.deepStrictEqual(getDomainsOfRemotes(remote('https://git.example.com/gitproject.git'), allowedDomains), ['example.com']); assert.deepStrictEqual(getDomainsOfRemotes(remote('https://[email protected]/username/repository.git'), allowedDomains), ['github2.com']); assert.deepStrictEqual(getDomainsOfRemotes(remote('https://username:[email protected]/username/repository.git'), allowedDomains), ['github3.com']); assert.deepStrictEqual(getDomainsOfRemotes(remote('https://username:[email protected]:1234/username/repository.git'), allowedDomains), ['example2.com']); assert.deepStrictEqual(getDomainsOfRemotes(remote('https://example3.com:1234/username/repository.git'), allowedDomains), ['example3.com']); }); test('SSH remotes', function () { assert.deepStrictEqual(getDomainsOfRemotes(remote('ssh://[email protected]/project.git'), allowedDomains), ['server.org']); }); test('SCP-like remotes', function () { assert.deepStrictEqual(getDomainsOfRemotes(remote('[email protected]:microsoft/vscode.git'), allowedDomains), ['github.com']); assert.deepStrictEqual(getDomainsOfRemotes(remote('[email protected]:project.git'), allowedDomains), ['server.org']); assert.deepStrictEqual(getDomainsOfRemotes(remote('git.server2.org:project.git'), allowedDomains), ['server2.org']); }); test('Local remotes', function () { assert.deepStrictEqual(getDomainsOfRemotes(remote('/opt/git/project.git'), allowedDomains), []); assert.deepStrictEqual(getDomainsOfRemotes(remote('file:///opt/git/project.git'), allowedDomains), []); }); test('Multiple remotes', function () { const config = ['https://github.com/microsoft/vscode.git', 'https://git.example.com/gitproject.git'].map(remote).join(''); assert.deepStrictEqual(getDomainsOfRemotes(config, allowedDomains).sort(), ['example.com', 'github.com']); }); test('Non allowed domains are anonymized', () => { const config = ['https://github.com/microsoft/vscode.git', 'https://git.foobar.com/gitproject.git'].map(remote).join(''); assert.deepStrictEqual(getDomainsOfRemotes(config, allowedDomains).sort(), ['aaaaaa.aaa', 'github.com']); }); test('HTTPS remotes to be hashed', function () { assert.deepStrictEqual(getRemotes(remote('https://github.com/microsoft/vscode.git')), ['github.com/microsoft/vscode.git']); assert.deepStrictEqual(getRemotes(remote('https://git.example.com/gitproject.git')), ['git.example.com/gitproject.git']); assert.deepStrictEqual(getRemotes(remote('https://[email protected]/username/repository.git')), ['github2.com/username/repository.git']); assert.deepStrictEqual(getRemotes(remote('https://username:[email protected]/username/repository.git')), ['github3.com/username/repository.git']); assert.deepStrictEqual(getRemotes(remote('https://username:[email protected]:1234/username/repository.git')), ['example2.com/username/repository.git']); assert.deepStrictEqual(getRemotes(remote('https://example3.com:1234/username/repository.git')), ['example3.com/username/repository.git']); // Strip .git assert.deepStrictEqual(getRemotes(remote('https://github.com/microsoft/vscode.git'), true), ['github.com/microsoft/vscode']); assert.deepStrictEqual(getRemotes(remote('https://git.example.com/gitproject.git'), true), ['git.example.com/gitproject']); assert.deepStrictEqual(getRemotes(remote('https://[email protected]/username/repository.git'), true), ['github2.com/username/repository']); assert.deepStrictEqual(getRemotes(remote('https://username:[email protected]/username/repository.git'), true), ['github3.com/username/repository']); assert.deepStrictEqual(getRemotes(remote('https://username:[email protected]:1234/username/repository.git'), true), ['example2.com/username/repository']); assert.deepStrictEqual(getRemotes(remote('https://example3.com:1234/username/repository.git'), true), ['example3.com/username/repository']); // Compare Striped .git with no .git assert.deepStrictEqual(getRemotes(remote('https://github.com/microsoft/vscode.git'), true), getRemotes(remote('https://github.com/microsoft/vscode'))); assert.deepStrictEqual(getRemotes(remote('https://git.example.com/gitproject.git'), true), getRemotes(remote('https://git.example.com/gitproject'))); assert.deepStrictEqual(getRemotes(remote('https://[email protected]/username/repository.git'), true), getRemotes(remote('https://[email protected]/username/repository'))); assert.deepStrictEqual(getRemotes(remote('https://username:[email protected]/username/repository.git'), true), getRemotes(remote('https://username:[email protected]/username/repository'))); assert.deepStrictEqual(getRemotes(remote('https://username:[email protected]:1234/username/repository.git'), true), getRemotes(remote('https://username:[email protected]:1234/username/repository'))); assert.deepStrictEqual(getRemotes(remote('https://example3.com:1234/username/repository.git'), true), getRemotes(remote('https://example3.com:1234/username/repository'))); }); test('SSH remotes to be hashed', function () { assert.deepStrictEqual(getRemotes(remote('ssh://[email protected]/project.git')), ['git.server.org/project.git']); // Strip .git assert.deepStrictEqual(getRemotes(remote('ssh://[email protected]/project.git'), true), ['git.server.org/project']); // Compare Striped .git with no .git assert.deepStrictEqual(getRemotes(remote('ssh://[email protected]/project.git'), true), getRemotes(remote('ssh://[email protected]/project'))); }); test('SCP-like remotes to be hashed', function () { assert.deepStrictEqual(getRemotes(remote('[email protected]:microsoft/vscode.git')), ['github.com/microsoft/vscode.git']); assert.deepStrictEqual(getRemotes(remote('[email protected]:project.git')), ['git.server.org/project.git']); assert.deepStrictEqual(getRemotes(remote('git.server2.org:project.git')), ['git.server2.org/project.git']); // Strip .git assert.deepStrictEqual(getRemotes(remote('[email protected]:microsoft/vscode.git'), true), ['github.com/microsoft/vscode']); assert.deepStrictEqual(getRemotes(remote('[email protected]:project.git'), true), ['git.server.org/project']); assert.deepStrictEqual(getRemotes(remote('git.server2.org:project.git'), true), ['git.server2.org/project']); // Compare Striped .git with no .git assert.deepStrictEqual(getRemotes(remote('[email protected]:microsoft/vscode.git'), true), getRemotes(remote('[email protected]:microsoft/vscode'))); assert.deepStrictEqual(getRemotes(remote('[email protected]:project.git'), true), getRemotes(remote('[email protected]:project'))); assert.deepStrictEqual(getRemotes(remote('git.server2.org:project.git'), true), getRemotes(remote('git.server2.org:project'))); }); test('Local remotes to be hashed', function () { assert.deepStrictEqual(getRemotes(remote('/opt/git/project.git')), []); assert.deepStrictEqual(getRemotes(remote('file:///opt/git/project.git')), []); }); test('Multiple remotes to be hashed', function () { const config = ['https://github.com/microsoft/vscode.git', 'https://git.example.com/gitproject.git'].map(remote).join(' '); assert.deepStrictEqual(getRemotes(config), ['github.com/microsoft/vscode.git', 'git.example.com/gitproject.git']); // Strip .git assert.deepStrictEqual(getRemotes(config, true), ['github.com/microsoft/vscode', 'git.example.com/gitproject']); // Compare Striped .git with no .git const noDotGitConfig = ['https://github.com/microsoft/vscode', 'https://git.example.com/gitproject'].map(remote).join(' '); assert.deepStrictEqual(getRemotes(config, true), getRemotes(noDotGitConfig)); }); function remote(url: string): string { return `[remote "origin"] url = ${url} fetch = +refs/heads/*:refs/remotes/origin/* `; } });
src/vs/platform/extensionManagement/test/common/configRemotes.test.ts
0
https://github.com/microsoft/vscode/commit/f554a745505474ba031a79f5ab4a5c9d1ed3af39
[ 0.0015627110842615366, 0.0002693498972803354, 0.00016405117639806122, 0.00017054557974915951, 0.0003587250830605626 ]
{ "id": 7, "code_window": [ "\t\tassert.strictEqual(decorations[1].options.className, 'debug-focused-stack-frame-line');\n", "\t\tassert.strictEqual(decorations[1].options.isWholeLine, true);\n", "\n", "\t\tdecorations = createDecorationsForStackFrame(firstStackFrame, new Range(1, 5, 1, 6), true);\n", "\t\tassert.strictEqual(decorations.length, 3);\n", "\t\tassert.deepStrictEqual(decorations[0].range, new Range(1, 2, 1, 1));\n", "\t\tassert.strictEqual(decorations[0].options.glyphMarginClassName, ThemeIcon.asClassName(debugStackframe));\n", "\t\tassert.deepStrictEqual(decorations[1].range, new Range(1, Constants.MAX_SAFE_SMALL_INTEGER, 1, 1));\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tdecorations = createDecorationsForStackFrame(firstStackFrame, true);\n" ], "file_path": "src/vs/workbench/contrib/debug/test/browser/callStack.test.ts", "type": "replace", "edit_start_line_idx": 329 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { IListVirtualDelegate } from 'vs/base/browser/ui/list/list'; import { IDataSource, ITreeRenderer } from 'vs/base/browser/ui/tree/tree'; import { CancellationToken } from 'vs/base/common/cancellation'; import { Event } from 'vs/base/common/event'; import { FuzzyScore } from 'vs/base/common/filters'; import { IDisposable } from 'vs/base/common/lifecycle'; import { IEditorOptions } from 'vs/platform/editor/common/editor'; import { createDecorator } from 'vs/platform/instantiation/common/instantiation'; import { IWorkbenchDataTreeOptions } from 'vs/platform/list/browser/listService'; import { IEditorPane } from 'vs/workbench/common/editor'; export const IOutlineService = createDecorator<IOutlineService>('IOutlineService'); export const enum OutlineTarget { OutlinePane = 1, Breadcrumbs = 2, QuickPick = 4 } export interface IOutlineService { _serviceBrand: undefined; onDidChange: Event<void>; canCreateOutline(editor: IEditorPane): boolean; createOutline(editor: IEditorPane, target: OutlineTarget, token: CancellationToken): Promise<IOutline<any> | undefined>; registerOutlineCreator(creator: IOutlineCreator<any, any>): IDisposable; } export interface IOutlineCreator<P extends IEditorPane, E> { matches(candidate: IEditorPane): candidate is P; createOutline(editor: P, target: OutlineTarget, token: CancellationToken): Promise<IOutline<E> | undefined>; } export interface IBreadcrumbsDataSource<E> { getBreadcrumbElements(): readonly E[]; } export interface IOutlineComparator<E> { compareByPosition(a: E, b: E): number; compareByType(a: E, b: E): number; compareByName(a: E, b: E): number; } export interface IQuickPickOutlineElement<E> { readonly element: E; readonly label: string; readonly iconClasses?: string[]; readonly ariaLabel?: string; readonly description?: string; } export interface IQuickPickDataSource<E> { getQuickPickElements(): IQuickPickOutlineElement<E>[]; } export interface IOutlineListConfig<E> { readonly breadcrumbsDataSource: IBreadcrumbsDataSource<E>; readonly treeDataSource: IDataSource<IOutline<E>, E>; readonly delegate: IListVirtualDelegate<E>; readonly renderers: ITreeRenderer<E, FuzzyScore, any>[]; readonly comparator: IOutlineComparator<E>; readonly options: IWorkbenchDataTreeOptions<E, FuzzyScore>; readonly quickPickDataSource: IQuickPickDataSource<E>; } export interface OutlineChangeEvent { affectOnlyActiveElement?: true } export interface IOutline<E> { readonly config: IOutlineListConfig<E>; readonly outlineKind: string; readonly isEmpty: boolean; readonly activeElement: E | undefined; readonly onDidChange: Event<OutlineChangeEvent>; reveal(entry: E, options: IEditorOptions, sideBySide: boolean): Promise<void> | void; preview(entry: E): IDisposable; captureViewState(): IDisposable; dispose(): void; } export const enum OutlineConfigKeys { 'icons' = 'outline.icons', 'problemsEnabled' = 'outline.problems.enabled', 'problemsColors' = 'outline.problems.colors', 'problemsBadges' = 'outline.problems.badges' }
src/vs/workbench/services/outline/browser/outline.ts
0
https://github.com/microsoft/vscode/commit/f554a745505474ba031a79f5ab4a5c9d1ed3af39
[ 0.0001739102299325168, 0.00016998262435663491, 0.00016388889343943447, 0.00017095118528231978, 0.000003205893335689325 ]
{ "id": 0, "code_window": [ "import { provide, inject, ref, Ref, InjectionKey } from 'vue'\n", "import { expectType } from './utils'\n", "\n", "provide('foo', 123)\n", "provide(123, 123)\n", "\n", "const key: InjectionKey<number> = Symbol()\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "// non-symbol keys\n" ], "file_path": "packages/dts-test/inject.test-d.ts", "type": "add", "edit_start_line_idx": 3 }
import { isFunction } from '@vue/shared' import { currentInstance } from './component' import { currentRenderingInstance } from './componentRenderContext' import { currentApp } from './apiCreateApp' import { warn } from './warning' export interface InjectionKey<T> extends Symbol {} export function provide<T extends InjectionKey<any>>( key: T | string | number, value: T extends InjectionKey<infer V> ? V : any ) { if (!currentInstance) { if (__DEV__) { warn(`provide() can only be used inside setup().`) } } else { let provides = currentInstance.provides // by default an instance inherits its parent's provides object // but when it needs to provide values of its own, it creates its // own provides object using parent provides object as prototype. // this way in `inject` we can simply look up injections from direct // parent and let the prototype chain do the work. const parentProvides = currentInstance.parent && currentInstance.parent.provides if (parentProvides === provides) { provides = currentInstance.provides = Object.create(parentProvides) } // TS doesn't allow symbol as index type provides[key as string] = value } } export function inject<T>(key: InjectionKey<T> | string): T | undefined export function inject<T>( key: InjectionKey<T> | string, defaultValue: T, treatDefaultAsFactory?: false ): T export function inject<T>( key: InjectionKey<T> | string, defaultValue: T | (() => T), treatDefaultAsFactory: true ): T export function inject( key: InjectionKey<any> | string, defaultValue?: unknown, treatDefaultAsFactory = false ) { // fallback to `currentRenderingInstance` so that this can be called in // a functional component const instance = currentInstance || currentRenderingInstance // also support looking up from app-level provides w/ `app.runWithContext()` if (instance || currentApp) { // #2400 // to support `app.use` plugins, // fallback to appContext's `provides` if the instance is at root const provides = instance ? instance.parent == null ? instance.vnode.appContext && instance.vnode.appContext.provides : instance.parent.provides : currentApp!._context.provides if (provides && (key as string | symbol) in provides) { // TS doesn't allow symbol as index type return provides[key as string] } else if (arguments.length > 1) { return treatDefaultAsFactory && isFunction(defaultValue) ? defaultValue.call(instance && instance.proxy) : defaultValue } else if (__DEV__) { warn(`injection "${String(key)}" not found.`) } } else if (__DEV__) { warn(`inject() can only be used inside setup() or functional components.`) } } /** * Returns true if `inject()` can be used without warning about being called in the wrong place (e.g. outside of * setup()). This is used by libraries that want to use `inject()` internally without triggering a warning to the end * user. One example is `useRoute()` in `vue-router`. */ export function hasInjectionContext(): boolean { return !!(currentInstance || currentRenderingInstance || currentApp) }
packages/runtime-core/src/apiInject.ts
1
https://github.com/vuejs/core/commit/038cd830d5b34b47d7e7e1c61f0973d27cd8b915
[ 0.9953820109367371, 0.33154425024986267, 0.0006327369483187795, 0.004152002744376659, 0.4634842872619629 ]
{ "id": 0, "code_window": [ "import { provide, inject, ref, Ref, InjectionKey } from 'vue'\n", "import { expectType } from './utils'\n", "\n", "provide('foo', 123)\n", "provide(123, 123)\n", "\n", "const key: InjectionKey<number> = Symbol()\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "// non-symbol keys\n" ], "file_path": "packages/dts-test/inject.test-d.ts", "type": "add", "edit_start_line_idx": 3 }
import { isArray, isObject, isPromise } from '@vue/shared' import { defineAsyncComponent } from '../apiAsyncComponent' import { Component } from '../component' import { isVNode } from '../vnode' interface LegacyAsyncOptions { component: Promise<Component> loading?: Component error?: Component delay?: number timeout?: number } type LegacyAsyncReturnValue = Promise<Component> | LegacyAsyncOptions type LegacyAsyncComponent = ( resolve?: (res: LegacyAsyncReturnValue) => void, reject?: (reason?: any) => void ) => LegacyAsyncReturnValue | undefined const normalizedAsyncComponentMap = new Map<LegacyAsyncComponent, Component>() export function convertLegacyAsyncComponent(comp: LegacyAsyncComponent) { if (normalizedAsyncComponentMap.has(comp)) { return normalizedAsyncComponentMap.get(comp)! } // we have to call the function here due to how v2's API won't expose the // options until we call it let resolve: (res: LegacyAsyncReturnValue) => void let reject: (reason?: any) => void const fallbackPromise = new Promise<Component>((r, rj) => { ;(resolve = r), (reject = rj) }) const res = comp(resolve!, reject!) let converted: Component if (isPromise(res)) { converted = defineAsyncComponent(() => res) } else if (isObject(res) && !isVNode(res) && !isArray(res)) { converted = defineAsyncComponent({ loader: () => res.component, loadingComponent: res.loading, errorComponent: res.error, delay: res.delay, timeout: res.timeout }) } else if (res == null) { converted = defineAsyncComponent(() => fallbackPromise) } else { converted = comp as any // probably a v3 functional comp } normalizedAsyncComponentMap.set(comp, converted) return converted }
packages/runtime-core/src/compat/componentAsync.ts
0
https://github.com/vuejs/core/commit/038cd830d5b34b47d7e7e1c61f0973d27cd8b915
[ 0.00017688405932858586, 0.0001718306593829766, 0.00016465689986944199, 0.0001740381121635437, 0.000005195598987484118 ]
{ "id": 0, "code_window": [ "import { provide, inject, ref, Ref, InjectionKey } from 'vue'\n", "import { expectType } from './utils'\n", "\n", "provide('foo', 123)\n", "provide(123, 123)\n", "\n", "const key: InjectionKey<number> = Symbol()\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "// non-symbol keys\n" ], "file_path": "packages/dts-test/inject.test-d.ts", "type": "add", "edit_start_line_idx": 3 }
// @ts-check import fs from 'node:fs' import chalk from 'chalk' import { createRequire } from 'node:module' const require = createRequire(import.meta.url) export const targets = fs.readdirSync('packages').filter(f => { if (!fs.statSync(`packages/${f}`).isDirectory()) { return false } const pkg = require(`../packages/${f}/package.json`) if (pkg.private && !pkg.buildOptions) { return false } return true }) export function fuzzyMatchTarget(partialTargets, includeAllMatching) { const matched = [] partialTargets.forEach(partialTarget => { for (const target of targets) { if (target.match(partialTarget)) { matched.push(target) if (!includeAllMatching) { break } } } }) if (matched.length) { return matched } else { console.log() console.error( ` ${chalk.bgRed.white(' ERROR ')} ${chalk.red( `Target ${chalk.underline(partialTargets)} not found!` )}` ) console.log() process.exit(1) } }
scripts/utils.js
0
https://github.com/vuejs/core/commit/038cd830d5b34b47d7e7e1c61f0973d27cd8b915
[ 0.0001781212631613016, 0.00017558809486217797, 0.00017297730664722621, 0.00017532713536638767, 0.0000016627294598947628 ]
{ "id": 0, "code_window": [ "import { provide, inject, ref, Ref, InjectionKey } from 'vue'\n", "import { expectType } from './utils'\n", "\n", "provide('foo', 123)\n", "provide(123, 123)\n", "\n", "const key: InjectionKey<number> = Symbol()\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "// non-symbol keys\n" ], "file_path": "packages/dts-test/inject.test-d.ts", "type": "add", "edit_start_line_idx": 3 }
import { isReactive, isReadonly, isRef, Ref, toRaw } from '@vue/reactivity' import { EMPTY_OBJ, extend, isArray, isFunction, isObject } from '@vue/shared' import { isShallow } from '../../reactivity/src/reactive' import { ComponentInternalInstance, ComponentOptions } from './component' import { ComponentPublicInstance } from './componentPublicInstance' export function initCustomFormatter() { /* eslint-disable no-restricted-globals */ if (!__DEV__ || typeof window === 'undefined') { return } const vueStyle = { style: 'color:#3ba776' } const numberStyle = { style: 'color:#0b1bc9' } const stringStyle = { style: 'color:#b62e24' } const keywordStyle = { style: 'color:#9d288c' } // custom formatter for Chrome // https://www.mattzeunert.com/2016/02/19/custom-chrome-devtools-object-formatters.html const formatter = { header(obj: unknown) { // TODO also format ComponentPublicInstance & ctx.slots/attrs in setup if (!isObject(obj)) { return null } if (obj.__isVue) { return ['div', vueStyle, `VueInstance`] } else if (isRef(obj)) { return [ 'div', {}, ['span', vueStyle, genRefFlag(obj)], '<', formatValue(obj.value), `>` ] } else if (isReactive(obj)) { return [ 'div', {}, ['span', vueStyle, isShallow(obj) ? 'ShallowReactive' : 'Reactive'], '<', formatValue(obj), `>${isReadonly(obj) ? ` (readonly)` : ``}` ] } else if (isReadonly(obj)) { return [ 'div', {}, ['span', vueStyle, isShallow(obj) ? 'ShallowReadonly' : 'Readonly'], '<', formatValue(obj), '>' ] } return null }, hasBody(obj: unknown) { return obj && (obj as any).__isVue }, body(obj: unknown) { if (obj && (obj as any).__isVue) { return [ 'div', {}, ...formatInstance((obj as ComponentPublicInstance).$) ] } } } function formatInstance(instance: ComponentInternalInstance) { const blocks = [] if (instance.type.props && instance.props) { blocks.push(createInstanceBlock('props', toRaw(instance.props))) } if (instance.setupState !== EMPTY_OBJ) { blocks.push(createInstanceBlock('setup', instance.setupState)) } if (instance.data !== EMPTY_OBJ) { blocks.push(createInstanceBlock('data', toRaw(instance.data))) } const computed = extractKeys(instance, 'computed') if (computed) { blocks.push(createInstanceBlock('computed', computed)) } const injected = extractKeys(instance, 'inject') if (injected) { blocks.push(createInstanceBlock('injected', injected)) } blocks.push([ 'div', {}, [ 'span', { style: keywordStyle.style + ';opacity:0.66' }, '$ (internal): ' ], ['object', { object: instance }] ]) return blocks } function createInstanceBlock(type: string, target: any) { target = extend({}, target) if (!Object.keys(target).length) { return ['span', {}] } return [ 'div', { style: 'line-height:1.25em;margin-bottom:0.6em' }, [ 'div', { style: 'color:#476582' }, type ], [ 'div', { style: 'padding-left:1.25em' }, ...Object.keys(target).map(key => { return [ 'div', {}, ['span', keywordStyle, key + ': '], formatValue(target[key], false) ] }) ] ] } function formatValue(v: unknown, asRaw = true) { if (typeof v === 'number') { return ['span', numberStyle, v] } else if (typeof v === 'string') { return ['span', stringStyle, JSON.stringify(v)] } else if (typeof v === 'boolean') { return ['span', keywordStyle, v] } else if (isObject(v)) { return ['object', { object: asRaw ? toRaw(v) : v }] } else { return ['span', stringStyle, String(v)] } } function extractKeys(instance: ComponentInternalInstance, type: string) { const Comp = instance.type if (isFunction(Comp)) { return } const extracted: Record<string, any> = {} for (const key in instance.ctx) { if (isKeyOfType(Comp, key, type)) { extracted[key] = instance.ctx[key] } } return extracted } function isKeyOfType(Comp: ComponentOptions, key: string, type: string) { const opts = Comp[type] if ( (isArray(opts) && opts.includes(key)) || (isObject(opts) && key in opts) ) { return true } if (Comp.extends && isKeyOfType(Comp.extends, key, type)) { return true } if (Comp.mixins && Comp.mixins.some(m => isKeyOfType(m, key, type))) { return true } } function genRefFlag(v: Ref) { if (isShallow(v)) { return `ShallowRef` } if ((v as any).effect) { return `ComputedRef` } return `Ref` } if ((window as any).devtoolsFormatters) { ;(window as any).devtoolsFormatters.push(formatter) } else { ;(window as any).devtoolsFormatters = [formatter] } }
packages/runtime-core/src/customFormatter.ts
0
https://github.com/vuejs/core/commit/038cd830d5b34b47d7e7e1c61f0973d27cd8b915
[ 0.4288543164730072, 0.02164299227297306, 0.00016490874986629933, 0.00017304695211350918, 0.09342077374458313 ]
{ "id": 1, "code_window": [ "const key: InjectionKey<number> = Symbol()\n", "\n", "provide(key, 1)\n", "// @ts-expect-error\n", "provide(key, 'foo')\n", "\n", "expectType<number | undefined>(inject(key))\n", "expectType<number>(inject(key, 1))\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "// @ts-expect-error\n", "provide(key, null)\n" ], "file_path": "packages/dts-test/inject.test-d.ts", "type": "add", "edit_start_line_idx": 11 }
import { provide, inject, ref, Ref, InjectionKey } from 'vue' import { expectType } from './utils' provide('foo', 123) provide(123, 123) const key: InjectionKey<number> = Symbol() provide(key, 1) // @ts-expect-error provide(key, 'foo') expectType<number | undefined>(inject(key)) expectType<number>(inject(key, 1)) expectType<number>(inject(key, () => 1, true /* treatDefaultAsFactory */)) expectType<() => number>(inject('foo', () => 1)) expectType<() => number>(inject('foo', () => 1, false)) expectType<number>(inject('foo', () => 1, true)) // #8201 type Cube = { size: number } const injectionKeyRef = Symbol('key') as InjectionKey<Ref<Cube>> // @ts-expect-error provide(injectionKeyRef, ref({}))
packages/dts-test/inject.test-d.ts
1
https://github.com/vuejs/core/commit/038cd830d5b34b47d7e7e1c61f0973d27cd8b915
[ 0.9968591928482056, 0.9769031405448914, 0.9448096752166748, 0.9890403747558594, 0.022916855290532112 ]
{ "id": 1, "code_window": [ "const key: InjectionKey<number> = Symbol()\n", "\n", "provide(key, 1)\n", "// @ts-expect-error\n", "provide(key, 'foo')\n", "\n", "expectType<number | undefined>(inject(key))\n", "expectType<number>(inject(key, 1))\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "// @ts-expect-error\n", "provide(key, null)\n" ], "file_path": "packages/dts-test/inject.test-d.ts", "type": "add", "edit_start_line_idx": 11 }
export * from '@vue/server-renderer'
packages/vue/server-renderer/index.d.ts
0
https://github.com/vuejs/core/commit/038cd830d5b34b47d7e7e1c61f0973d27cd8b915
[ 0.00017640183796174824, 0.00017640183796174824, 0.00017640183796174824, 0.00017640183796174824, 0 ]
{ "id": 1, "code_window": [ "const key: InjectionKey<number> = Symbol()\n", "\n", "provide(key, 1)\n", "// @ts-expect-error\n", "provide(key, 'foo')\n", "\n", "expectType<number | undefined>(inject(key))\n", "expectType<number>(inject(key, 1))\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "// @ts-expect-error\n", "provide(key, null)\n" ], "file_path": "packages/dts-test/inject.test-d.ts", "type": "add", "edit_start_line_idx": 11 }
'use strict' if (process.env.NODE_ENV === 'production') { module.exports = require('./dist/vue.cjs.prod.js') } else { module.exports = require('./dist/vue.cjs.js') }
packages/vue-compat/index.js
0
https://github.com/vuejs/core/commit/038cd830d5b34b47d7e7e1c61f0973d27cd8b915
[ 0.00017827996634878218, 0.00017827996634878218, 0.00017827996634878218, 0.00017827996634878218, 0 ]
{ "id": 1, "code_window": [ "const key: InjectionKey<number> = Symbol()\n", "\n", "provide(key, 1)\n", "// @ts-expect-error\n", "provide(key, 'foo')\n", "\n", "expectType<number | undefined>(inject(key))\n", "expectType<number>(inject(key, 1))\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "// @ts-expect-error\n", "provide(key, null)\n" ], "file_path": "packages/dts-test/inject.test-d.ts", "type": "add", "edit_start_line_idx": 11 }
import { vi } from 'vitest' import { baseParse as parse, transform, PlainElementNode, CompilerOptions } from '@vue/compiler-core' import { transformVText } from '../../src/transforms/vText' import { transformElement } from '../../../compiler-core/src/transforms/transformElement' import { createObjectMatcher, genFlagText } from '../../../compiler-core/__tests__/testUtils' import { PatchFlags } from '@vue/shared' import { DOMErrorCodes } from '../../src/errors' function transformWithVText(template: string, options: CompilerOptions = {}) { const ast = parse(template) transform(ast, { nodeTransforms: [transformElement], directiveTransforms: { text: transformVText }, ...options }) return ast } describe('compiler: v-text transform', () => { it('should convert v-text to textContent', () => { const ast = transformWithVText(`<div v-text="test"/>`) expect((ast.children[0] as PlainElementNode).codegenNode).toMatchObject({ tag: `"div"`, props: createObjectMatcher({ textContent: { arguments: [{ content: 'test' }] } }), children: undefined, patchFlag: genFlagText(PatchFlags.PROPS), dynamicProps: `["textContent"]` }) }) it('should raise error and ignore children when v-text is present', () => { const onError = vi.fn() const ast = transformWithVText(`<div v-text="test">hello</div>`, { onError }) expect(onError.mock.calls).toMatchObject([ [{ code: DOMErrorCodes.X_V_TEXT_WITH_CHILDREN }] ]) expect((ast.children[0] as PlainElementNode).codegenNode).toMatchObject({ tag: `"div"`, props: createObjectMatcher({ textContent: { arguments: [{ content: 'test' }] } }), children: undefined, // <-- children should have been removed patchFlag: genFlagText(PatchFlags.PROPS), dynamicProps: `["textContent"]` }) }) it('should raise error if has no expression', () => { const onError = vi.fn() transformWithVText(`<div v-text></div>`, { onError }) expect(onError.mock.calls).toMatchObject([ [{ code: DOMErrorCodes.X_V_TEXT_NO_EXPRESSION }] ]) }) })
packages/compiler-dom/__tests__/transforms/vText.spec.ts
0
https://github.com/vuejs/core/commit/038cd830d5b34b47d7e7e1c61f0973d27cd8b915
[ 0.00017900305101647973, 0.00017645442858338356, 0.00017428073624614626, 0.00017639742873143405, 0.000001369100345982588 ]
{ "id": 2, "code_window": [ "\n", "// @ts-expect-error\n", "provide(injectionKeyRef, ref({}))\n" ], "labels": [ "keep", "keep", "add" ], "after_edit": [ "\n", "// naive-ui: explicit provide type parameter\n", "provide<Cube>('cube', { size: 123 })\n", "provide<Cube>(123, { size: 123 })\n", "provide<Cube>(injectionKeyRef, { size: 123 })\n", "\n", "// @ts-expect-error\n", "provide<Cube>('cube', { size: 'foo' })\n", "// @ts-expect-error\n", "provide<Cube>(123, { size: 'foo' })" ], "file_path": "packages/dts-test/inject.test-d.ts", "type": "add", "edit_start_line_idx": 29 }
import { isFunction } from '@vue/shared' import { currentInstance } from './component' import { currentRenderingInstance } from './componentRenderContext' import { currentApp } from './apiCreateApp' import { warn } from './warning' export interface InjectionKey<T> extends Symbol {} export function provide<T extends InjectionKey<any>>( key: T | string | number, value: T extends InjectionKey<infer V> ? V : any ) { if (!currentInstance) { if (__DEV__) { warn(`provide() can only be used inside setup().`) } } else { let provides = currentInstance.provides // by default an instance inherits its parent's provides object // but when it needs to provide values of its own, it creates its // own provides object using parent provides object as prototype. // this way in `inject` we can simply look up injections from direct // parent and let the prototype chain do the work. const parentProvides = currentInstance.parent && currentInstance.parent.provides if (parentProvides === provides) { provides = currentInstance.provides = Object.create(parentProvides) } // TS doesn't allow symbol as index type provides[key as string] = value } } export function inject<T>(key: InjectionKey<T> | string): T | undefined export function inject<T>( key: InjectionKey<T> | string, defaultValue: T, treatDefaultAsFactory?: false ): T export function inject<T>( key: InjectionKey<T> | string, defaultValue: T | (() => T), treatDefaultAsFactory: true ): T export function inject( key: InjectionKey<any> | string, defaultValue?: unknown, treatDefaultAsFactory = false ) { // fallback to `currentRenderingInstance` so that this can be called in // a functional component const instance = currentInstance || currentRenderingInstance // also support looking up from app-level provides w/ `app.runWithContext()` if (instance || currentApp) { // #2400 // to support `app.use` plugins, // fallback to appContext's `provides` if the instance is at root const provides = instance ? instance.parent == null ? instance.vnode.appContext && instance.vnode.appContext.provides : instance.parent.provides : currentApp!._context.provides if (provides && (key as string | symbol) in provides) { // TS doesn't allow symbol as index type return provides[key as string] } else if (arguments.length > 1) { return treatDefaultAsFactory && isFunction(defaultValue) ? defaultValue.call(instance && instance.proxy) : defaultValue } else if (__DEV__) { warn(`injection "${String(key)}" not found.`) } } else if (__DEV__) { warn(`inject() can only be used inside setup() or functional components.`) } } /** * Returns true if `inject()` can be used without warning about being called in the wrong place (e.g. outside of * setup()). This is used by libraries that want to use `inject()` internally without triggering a warning to the end * user. One example is `useRoute()` in `vue-router`. */ export function hasInjectionContext(): boolean { return !!(currentInstance || currentRenderingInstance || currentApp) }
packages/runtime-core/src/apiInject.ts
1
https://github.com/vuejs/core/commit/038cd830d5b34b47d7e7e1c61f0973d27cd8b915
[ 0.997914731502533, 0.33123868703842163, 0.0003170193813275546, 0.0018928770441561937, 0.4670445919036865 ]
{ "id": 2, "code_window": [ "\n", "// @ts-expect-error\n", "provide(injectionKeyRef, ref({}))\n" ], "labels": [ "keep", "keep", "add" ], "after_edit": [ "\n", "// naive-ui: explicit provide type parameter\n", "provide<Cube>('cube', { size: 123 })\n", "provide<Cube>(123, { size: 123 })\n", "provide<Cube>(injectionKeyRef, { size: 123 })\n", "\n", "// @ts-expect-error\n", "provide<Cube>('cube', { size: 'foo' })\n", "// @ts-expect-error\n", "provide<Cube>(123, { size: 'foo' })" ], "file_path": "packages/dts-test/inject.test-d.ts", "type": "add", "edit_start_line_idx": 29 }
import { NodeTransform, TransformContext } from '../transform' import { NodeTypes, CallExpression, createCallExpression, ExpressionNode, SlotOutletNode, createFunctionExpression } from '../ast' import { isSlotOutlet, isStaticArgOf, isStaticExp } from '../utils' import { buildProps, PropsExpression } from './transformElement' import { createCompilerError, ErrorCodes } from '../errors' import { RENDER_SLOT } from '../runtimeHelpers' import { camelize } from '@vue/shared' export const transformSlotOutlet: NodeTransform = (node, context) => { if (isSlotOutlet(node)) { const { children, loc } = node const { slotName, slotProps } = processSlotOutlet(node, context) const slotArgs: CallExpression['arguments'] = [ context.prefixIdentifiers ? `_ctx.$slots` : `$slots`, slotName, '{}', 'undefined', 'true' ] let expectedLen = 2 if (slotProps) { slotArgs[2] = slotProps expectedLen = 3 } if (children.length) { slotArgs[3] = createFunctionExpression([], children, false, false, loc) expectedLen = 4 } if (context.scopeId && !context.slotted) { expectedLen = 5 } slotArgs.splice(expectedLen) // remove unused arguments node.codegenNode = createCallExpression( context.helper(RENDER_SLOT), slotArgs, loc ) } } interface SlotOutletProcessResult { slotName: string | ExpressionNode slotProps: PropsExpression | undefined } export function processSlotOutlet( node: SlotOutletNode, context: TransformContext ): SlotOutletProcessResult { let slotName: string | ExpressionNode = `"default"` let slotProps: PropsExpression | undefined = undefined const nonNameProps = [] for (let i = 0; i < node.props.length; i++) { const p = node.props[i] if (p.type === NodeTypes.ATTRIBUTE) { if (p.value) { if (p.name === 'name') { slotName = JSON.stringify(p.value.content) } else { p.name = camelize(p.name) nonNameProps.push(p) } } } else { if (p.name === 'bind' && isStaticArgOf(p.arg, 'name')) { if (p.exp) slotName = p.exp } else { if (p.name === 'bind' && p.arg && isStaticExp(p.arg)) { p.arg.content = camelize(p.arg.content) } nonNameProps.push(p) } } } if (nonNameProps.length > 0) { const { props, directives } = buildProps( node, context, nonNameProps, false, false ) slotProps = props if (directives.length) { context.onError( createCompilerError( ErrorCodes.X_V_SLOT_UNEXPECTED_DIRECTIVE_ON_SLOT_OUTLET, directives[0].loc ) ) } } return { slotName, slotProps } }
packages/compiler-core/src/transforms/transformSlotOutlet.ts
0
https://github.com/vuejs/core/commit/038cd830d5b34b47d7e7e1c61f0973d27cd8b915
[ 0.0001779601734597236, 0.00017008949362207204, 0.00016772531671449542, 0.0001691366487648338, 0.0000027322971618559677 ]
{ "id": 2, "code_window": [ "\n", "// @ts-expect-error\n", "provide(injectionKeyRef, ref({}))\n" ], "labels": [ "keep", "keep", "add" ], "after_edit": [ "\n", "// naive-ui: explicit provide type parameter\n", "provide<Cube>('cube', { size: 123 })\n", "provide<Cube>(123, { size: 123 })\n", "provide<Cube>(injectionKeyRef, { size: 123 })\n", "\n", "// @ts-expect-error\n", "provide<Cube>('cube', { size: 'foo' })\n", "// @ts-expect-error\n", "provide<Cube>(123, { size: 'foo' })" ], "file_path": "packages/dts-test/inject.test-d.ts", "type": "add", "edit_start_line_idx": 29 }
# dts-test Tests Typescript types to ensure the types remain as expected. - This directory is included in the root `tsconfig.json`, where package imports are aliased to `src` directories, so in IDEs and the `pnpm check` script the types are validated against source code. - When running `tsc` with `packages/dts-test/tsconfig.test.json`, packages are resolved using using normal `node` resolution, so the types are validated against actual **built** types. This requires the types to be built first via `pnpm build-types`.
packages/dts-test/README.md
0
https://github.com/vuejs/core/commit/038cd830d5b34b47d7e7e1c61f0973d27cd8b915
[ 0.00016860757023096085, 0.00016860757023096085, 0.00016860757023096085, 0.00016860757023096085, 0 ]
{ "id": 2, "code_window": [ "\n", "// @ts-expect-error\n", "provide(injectionKeyRef, ref({}))\n" ], "labels": [ "keep", "keep", "add" ], "after_edit": [ "\n", "// naive-ui: explicit provide type parameter\n", "provide<Cube>('cube', { size: 123 })\n", "provide<Cube>(123, { size: 123 })\n", "provide<Cube>(injectionKeyRef, { size: 123 })\n", "\n", "// @ts-expect-error\n", "provide<Cube>('cube', { size: 'foo' })\n", "// @ts-expect-error\n", "provide<Cube>(123, { size: 'foo' })" ], "file_path": "packages/dts-test/inject.test-d.ts", "type": "add", "edit_start_line_idx": 29 }
import { AppConfig } from '../apiCreateApp' import { DeprecationTypes, softAssertCompatEnabled, warnDeprecation } from './compatConfig' import { isCopyingConfig } from './global' import { internalOptionMergeStrats } from '../componentOptions' // legacy config warnings export type LegacyConfig = { /** * @deprecated `config.silent` option has been removed */ silent?: boolean /** * @deprecated use __VUE_PROD_DEVTOOLS__ compile-time feature flag instead * https://github.com/vuejs/core/tree/main/packages/vue#bundler-build-feature-flags */ devtools?: boolean /** * @deprecated use `config.isCustomElement` instead * https://v3-migration.vuejs.org/breaking-changes/global-api.html#config-ignoredelements-is-now-config-iscustomelement */ ignoredElements?: (string | RegExp)[] /** * @deprecated * https://v3-migration.vuejs.org/breaking-changes/keycode-modifiers.html */ keyCodes?: Record<string, number | number[]> /** * @deprecated * https://v3-migration.vuejs.org/breaking-changes/global-api.html#config-productiontip-removed */ productionTip?: boolean } // dev only export function installLegacyConfigWarnings(config: AppConfig) { const legacyConfigOptions: Record<string, DeprecationTypes> = { silent: DeprecationTypes.CONFIG_SILENT, devtools: DeprecationTypes.CONFIG_DEVTOOLS, ignoredElements: DeprecationTypes.CONFIG_IGNORED_ELEMENTS, keyCodes: DeprecationTypes.CONFIG_KEY_CODES, productionTip: DeprecationTypes.CONFIG_PRODUCTION_TIP } Object.keys(legacyConfigOptions).forEach(key => { let val = (config as any)[key] Object.defineProperty(config, key, { enumerable: true, get() { return val }, set(newVal) { if (!isCopyingConfig) { warnDeprecation(legacyConfigOptions[key], null) } val = newVal } }) }) } export function installLegacyOptionMergeStrats(config: AppConfig) { config.optionMergeStrategies = new Proxy({} as any, { get(target, key) { if (key in target) { return target[key] } if ( key in internalOptionMergeStrats && softAssertCompatEnabled( DeprecationTypes.CONFIG_OPTION_MERGE_STRATS, null ) ) { return internalOptionMergeStrats[ key as keyof typeof internalOptionMergeStrats ] } } }) }
packages/runtime-core/src/compat/globalConfig.ts
0
https://github.com/vuejs/core/commit/038cd830d5b34b47d7e7e1c61f0973d27cd8b915
[ 0.0001739778817864135, 0.00016999435320030898, 0.00016712555952835828, 0.0001690457429504022, 0.0000023274237719306257 ]
{ "id": 3, "code_window": [ "import { warn } from './warning'\n", "\n", "export interface InjectionKey<T> extends Symbol {}\n", "\n", "export function provide<T extends InjectionKey<any>>(\n", " key: T | string | number,\n", " value: T extends InjectionKey<infer V> ? V : any\n", ") {\n", " if (!currentInstance) {\n", " if (__DEV__) {\n", " warn(`provide() can only be used inside setup().`)\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "export function provide<T, K = InjectionKey<T> | string | number>(\n", " key: K,\n", " value: K extends InjectionKey<infer V> ? V : T\n" ], "file_path": "packages/runtime-core/src/apiInject.ts", "type": "replace", "edit_start_line_idx": 8 }
import { isFunction } from '@vue/shared' import { currentInstance } from './component' import { currentRenderingInstance } from './componentRenderContext' import { currentApp } from './apiCreateApp' import { warn } from './warning' export interface InjectionKey<T> extends Symbol {} export function provide<T extends InjectionKey<any>>( key: T | string | number, value: T extends InjectionKey<infer V> ? V : any ) { if (!currentInstance) { if (__DEV__) { warn(`provide() can only be used inside setup().`) } } else { let provides = currentInstance.provides // by default an instance inherits its parent's provides object // but when it needs to provide values of its own, it creates its // own provides object using parent provides object as prototype. // this way in `inject` we can simply look up injections from direct // parent and let the prototype chain do the work. const parentProvides = currentInstance.parent && currentInstance.parent.provides if (parentProvides === provides) { provides = currentInstance.provides = Object.create(parentProvides) } // TS doesn't allow symbol as index type provides[key as string] = value } } export function inject<T>(key: InjectionKey<T> | string): T | undefined export function inject<T>( key: InjectionKey<T> | string, defaultValue: T, treatDefaultAsFactory?: false ): T export function inject<T>( key: InjectionKey<T> | string, defaultValue: T | (() => T), treatDefaultAsFactory: true ): T export function inject( key: InjectionKey<any> | string, defaultValue?: unknown, treatDefaultAsFactory = false ) { // fallback to `currentRenderingInstance` so that this can be called in // a functional component const instance = currentInstance || currentRenderingInstance // also support looking up from app-level provides w/ `app.runWithContext()` if (instance || currentApp) { // #2400 // to support `app.use` plugins, // fallback to appContext's `provides` if the instance is at root const provides = instance ? instance.parent == null ? instance.vnode.appContext && instance.vnode.appContext.provides : instance.parent.provides : currentApp!._context.provides if (provides && (key as string | symbol) in provides) { // TS doesn't allow symbol as index type return provides[key as string] } else if (arguments.length > 1) { return treatDefaultAsFactory && isFunction(defaultValue) ? defaultValue.call(instance && instance.proxy) : defaultValue } else if (__DEV__) { warn(`injection "${String(key)}" not found.`) } } else if (__DEV__) { warn(`inject() can only be used inside setup() or functional components.`) } } /** * Returns true if `inject()` can be used without warning about being called in the wrong place (e.g. outside of * setup()). This is used by libraries that want to use `inject()` internally without triggering a warning to the end * user. One example is `useRoute()` in `vue-router`. */ export function hasInjectionContext(): boolean { return !!(currentInstance || currentRenderingInstance || currentApp) }
packages/runtime-core/src/apiInject.ts
1
https://github.com/vuejs/core/commit/038cd830d5b34b47d7e7e1c61f0973d27cd8b915
[ 0.9988883137702942, 0.6432350277900696, 0.0005734993610531092, 0.9095539450645447, 0.45173799991607666 ]
{ "id": 3, "code_window": [ "import { warn } from './warning'\n", "\n", "export interface InjectionKey<T> extends Symbol {}\n", "\n", "export function provide<T extends InjectionKey<any>>(\n", " key: T | string | number,\n", " value: T extends InjectionKey<infer V> ? V : any\n", ") {\n", " if (!currentInstance) {\n", " if (__DEV__) {\n", " warn(`provide() can only be used inside setup().`)\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "export function provide<T, K = InjectionKey<T> | string | number>(\n", " key: K,\n", " value: K extends InjectionKey<infer V> ? V : T\n" ], "file_path": "packages/runtime-core/src/apiInject.ts", "type": "replace", "edit_start_line_idx": 8 }
'use strict' if (process.env.NODE_ENV === 'production') { module.exports = require('./dist/runtime-dom.cjs.prod.js') } else { module.exports = require('./dist/runtime-dom.cjs.js') }
packages/runtime-dom/index.js
0
https://github.com/vuejs/core/commit/038cd830d5b34b47d7e7e1c61f0973d27cd8b915
[ 0.00016817645519040525, 0.00016817645519040525, 0.00016817645519040525, 0.00016817645519040525, 0 ]
{ "id": 3, "code_window": [ "import { warn } from './warning'\n", "\n", "export interface InjectionKey<T> extends Symbol {}\n", "\n", "export function provide<T extends InjectionKey<any>>(\n", " key: T | string | number,\n", " value: T extends InjectionKey<infer V> ? V : any\n", ") {\n", " if (!currentInstance) {\n", " if (__DEV__) {\n", " warn(`provide() can only be used inside setup().`)\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "export function provide<T, K = InjectionKey<T> | string | number>(\n", " key: K,\n", " value: K extends InjectionKey<infer V> ? V : T\n" ], "file_path": "packages/runtime-core/src/apiInject.ts", "type": "replace", "edit_start_line_idx": 8 }
import { SimpleExpressionNode } from './ast' import { TransformContext } from './transform' import { createCompilerError, ErrorCodes } from './errors' // these keywords should not appear inside expressions, but operators like // 'typeof', 'instanceof', and 'in' are allowed const prohibitedKeywordRE = new RegExp( '\\b' + ( 'arguments,await,break,case,catch,class,const,continue,debugger,default,' + 'delete,do,else,export,extends,finally,for,function,if,import,let,new,' + 'return,super,switch,throw,try,var,void,while,with,yield' ) .split(',') .join('\\b|\\b') + '\\b' ) // strip strings in expressions const stripStringRE = /'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|`(?:[^`\\]|\\.)*\$\{|\}(?:[^`\\]|\\.)*`|`(?:[^`\\]|\\.)*`/g /** * Validate a non-prefixed expression. * This is only called when using the in-browser runtime compiler since it * doesn't prefix expressions. */ export function validateBrowserExpression( node: SimpleExpressionNode, context: TransformContext, asParams = false, asRawStatements = false ) { const exp = node.content // empty expressions are validated per-directive since some directives // do allow empty expressions. if (!exp.trim()) { return } try { new Function( asRawStatements ? ` ${exp} ` : `return ${asParams ? `(${exp}) => {}` : `(${exp})`}` ) } catch (e: any) { let message = e.message const keywordMatch = exp .replace(stripStringRE, '') .match(prohibitedKeywordRE) if (keywordMatch) { message = `avoid using JavaScript keyword as property name: "${keywordMatch[0]}"` } context.onError( createCompilerError( ErrorCodes.X_INVALID_EXPRESSION, node.loc, undefined, message ) ) } }
packages/compiler-core/src/validateExpression.ts
0
https://github.com/vuejs/core/commit/038cd830d5b34b47d7e7e1c61f0973d27cd8b915
[ 0.00026299298042431474, 0.0001856764283729717, 0.0001657143875490874, 0.00016751994553487748, 0.0000335280601575505 ]
{ "id": 3, "code_window": [ "import { warn } from './warning'\n", "\n", "export interface InjectionKey<T> extends Symbol {}\n", "\n", "export function provide<T extends InjectionKey<any>>(\n", " key: T | string | number,\n", " value: T extends InjectionKey<infer V> ? V : any\n", ") {\n", " if (!currentInstance) {\n", " if (__DEV__) {\n", " warn(`provide() can only be used inside setup().`)\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "export function provide<T, K = InjectionKey<T> | string | number>(\n", " key: K,\n", " value: K extends InjectionKey<infer V> ? V : T\n" ], "file_path": "packages/runtime-core/src/apiInject.ts", "type": "replace", "edit_start_line_idx": 8 }
import { render, h, nodeOps } from '@vue/runtime-test' import { useCssModule } from '../../src/helpers/useCssModule' describe('useCssModule', () => { function mountWithModule(modules: any, name?: string) { let res render( h({ render() {}, __cssModules: modules, setup() { res = useCssModule(name) } }), nodeOps.createElement('div') ) return res } test('basic usage', () => { const modules = { $style: { red: 'red' } } expect(mountWithModule(modules)).toMatchObject(modules.$style) }) test('basic usage', () => { const modules = { foo: { red: 'red' } } expect(mountWithModule(modules, 'foo')).toMatchObject(modules.foo) }) test('warn out of setup usage', () => { useCssModule() expect('must be called inside setup').toHaveBeenWarned() }) test('warn missing injection', () => { mountWithModule(undefined) expect('instance does not have CSS modules').toHaveBeenWarned() }) test('warn missing injection', () => { mountWithModule({ $style: { red: 'red' } }, 'foo') expect('instance does not have CSS module named "foo"').toHaveBeenWarned() }) })
packages/runtime-dom/__tests__/helpers/useCssModule.spec.ts
0
https://github.com/vuejs/core/commit/038cd830d5b34b47d7e7e1c61f0973d27cd8b915
[ 0.0002283759822603315, 0.0001812063856050372, 0.0001664844312472269, 0.00017282778571825475, 0.00002126190702256281 ]
{ "id": 0, "code_window": [ "import { deepClone, equals } from 'vs/base/common/objects';\n", "import { DebugSession } from 'vs/workbench/contrib/debug/browser/debugSession';\n", "import { dispose, IDisposable } from 'vs/base/common/lifecycle';\n", "import { IDebugService, State, IDebugSession, CONTEXT_DEBUG_TYPE, CONTEXT_DEBUG_STATE, CONTEXT_IN_DEBUG_MODE, IThread, IDebugConfiguration, VIEWLET_ID, REPL_ID, IConfig, ILaunch, IViewModel, IConfigurationManager, IDebugModel, IEnablement, IBreakpoint, IBreakpointData, ICompound, IGlobalConfig, IStackFrame, AdapterEndEvent, getStateLabel, IDebugSessionOptions, CONTEXT_DEBUG_UX } from 'vs/workbench/contrib/debug/common/debug';\n", "import { isExtensionHostDebugging } from 'vs/workbench/contrib/debug/common/debugUtils';\n", "import { isErrorWithActions, createErrorWithActions } from 'vs/base/common/errorsWithActions';\n", "import { RunOnceScheduler } from 'vs/base/common/async';\n", "import { IExtensionHostDebugService } from 'vs/platform/debug/common/extensionHostDebug';\n", "import { isCodeEditor } from 'vs/editor/browser/editorBrowser';\n", "import { CancellationTokenSource } from 'vs/base/common/cancellation';\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { getExtensionHostDebugSession } from 'vs/workbench/contrib/debug/common/debugUtils';\n" ], "file_path": "src/vs/workbench/contrib/debug/browser/debugService.ts", "type": "replace", "edit_start_line_idx": 43 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { equalsIgnoreCase } from 'vs/base/common/strings'; import { IConfig, IDebuggerContribution, IDebugSession } from 'vs/workbench/contrib/debug/common/debug'; import { URI as uri } from 'vs/base/common/uri'; import { isAbsolute } from 'vs/base/common/path'; import { deepClone } from 'vs/base/common/objects'; const _formatPIIRegexp = /{([^}]+)}/g; export function formatPII(value: string, excludePII: boolean, args: { [key: string]: string }): string { return value.replace(_formatPIIRegexp, function (match, group) { if (excludePII && group.length > 0 && group[0] !== '_') { return match; } return args && args.hasOwnProperty(group) ? args[group] : match; }); } export function isSessionAttach(session: IDebugSession): boolean { return !session.parentSession && session.configuration.request === 'attach' && !isExtensionHostDebugging(session.configuration); } export function isExtensionHostDebugging(config: IConfig) { if (!config.type) { return false; } const type = config.type === 'vslsShare' ? (<any>config).adapterProxy.configuration.type : config.type; return equalsIgnoreCase(type, 'extensionhost') || equalsIgnoreCase(type, 'pwa-extensionhost'); } // only a debugger contributions with a label, program, or runtime attribute is considered a "defining" or "main" debugger contribution export function isDebuggerMainContribution(dbg: IDebuggerContribution) { return dbg.type && (dbg.label || dbg.program || dbg.runtime); } export function getExactExpressionStartAndEnd(lineContent: string, looseStart: number, looseEnd: number): { start: number, end: number } { let matchingExpression: string | undefined = undefined; let startOffset = 0; // Some example supported expressions: myVar.prop, a.b.c.d, myVar?.prop, myVar->prop, MyClass::StaticProp, *myVar // Match any character except a set of characters which often break interesting sub-expressions let expression: RegExp = /([^()\[\]{}<>\s+\-/%~#^;=|,`!]|\->)+/g; let result: RegExpExecArray | null = null; // First find the full expression under the cursor while (result = expression.exec(lineContent)) { let start = result.index + 1; let end = start + result[0].length; if (start <= looseStart && end >= looseEnd) { matchingExpression = result[0]; startOffset = start; break; } } // If there are non-word characters after the cursor, we want to truncate the expression then. // For example in expression 'a.b.c.d', if the focus was under 'b', 'a.b' would be evaluated. if (matchingExpression) { let subExpression: RegExp = /\w+/g; let subExpressionResult: RegExpExecArray | null = null; while (subExpressionResult = subExpression.exec(matchingExpression)) { let subEnd = subExpressionResult.index + 1 + startOffset + subExpressionResult[0].length; if (subEnd >= looseEnd) { break; } } if (subExpressionResult) { matchingExpression = matchingExpression.substring(0, subExpression.lastIndex); } } return matchingExpression ? { start: startOffset, end: startOffset + matchingExpression.length - 1 } : { start: 0, end: 0 }; } // RFC 2396, Appendix A: https://www.ietf.org/rfc/rfc2396.txt const _schemePattern = /^[a-zA-Z][a-zA-Z0-9\+\-\.]+:/; export function isUri(s: string | undefined): boolean { // heuristics: a valid uri starts with a scheme and // the scheme has at least 2 characters so that it doesn't look like a drive letter. return !!(s && s.match(_schemePattern)); } function stringToUri(path: string): string { if (typeof path === 'string') { if (isUri(path)) { return <string><unknown>uri.parse(path); } else { // assume path if (isAbsolute(path)) { return <string><unknown>uri.file(path); } else { // leave relative path as is } } } return path; } function uriToString(path: string): string { if (typeof path === 'object') { const u = uri.revive(path); if (u.scheme === 'file') { return u.fsPath; } else { return u.toString(); } } return path; } // path hooks helpers interface PathContainer { path?: string; } export function convertToDAPaths(message: DebugProtocol.ProtocolMessage, toUri: boolean): DebugProtocol.ProtocolMessage { const fixPath = toUri ? stringToUri : uriToString; // since we modify Source.paths in the message in place, we need to make a copy of it (see #61129) const msg = deepClone(message); convertPaths(msg, (toDA: boolean, source: PathContainer | undefined) => { if (toDA && source) { source.path = source.path ? fixPath(source.path) : undefined; } }); return msg; } export function convertToVSCPaths(message: DebugProtocol.ProtocolMessage, toUri: boolean): DebugProtocol.ProtocolMessage { const fixPath = toUri ? stringToUri : uriToString; // since we modify Source.paths in the message in place, we need to make a copy of it (see #61129) const msg = deepClone(message); convertPaths(msg, (toDA: boolean, source: PathContainer | undefined) => { if (!toDA && source) { source.path = source.path ? fixPath(source.path) : undefined; } }); return msg; } function convertPaths(msg: DebugProtocol.ProtocolMessage, fixSourcePath: (toDA: boolean, source: PathContainer | undefined) => void): void { switch (msg.type) { case 'event': const event = <DebugProtocol.Event>msg; switch (event.event) { case 'output': fixSourcePath(false, (<DebugProtocol.OutputEvent>event).body.source); break; case 'loadedSource': fixSourcePath(false, (<DebugProtocol.LoadedSourceEvent>event).body.source); break; case 'breakpoint': fixSourcePath(false, (<DebugProtocol.BreakpointEvent>event).body.breakpoint.source); break; default: break; } break; case 'request': const request = <DebugProtocol.Request>msg; switch (request.command) { case 'setBreakpoints': fixSourcePath(true, (<DebugProtocol.SetBreakpointsArguments>request.arguments).source); break; case 'breakpointLocations': fixSourcePath(true, (<DebugProtocol.BreakpointLocationsArguments>request.arguments).source); break; case 'source': fixSourcePath(true, (<DebugProtocol.SourceArguments>request.arguments).source); break; case 'gotoTargets': fixSourcePath(true, (<DebugProtocol.GotoTargetsArguments>request.arguments).source); break; case 'launchVSCode': request.arguments.args.forEach((arg: PathContainer | undefined) => fixSourcePath(false, arg)); break; default: break; } break; case 'response': const response = <DebugProtocol.Response>msg; if (response.success) { switch (response.command) { case 'stackTrace': (<DebugProtocol.StackTraceResponse>response).body.stackFrames.forEach(frame => fixSourcePath(false, frame.source)); break; case 'loadedSources': (<DebugProtocol.LoadedSourcesResponse>response).body.sources.forEach(source => fixSourcePath(false, source)); break; case 'scopes': (<DebugProtocol.ScopesResponse>response).body.scopes.forEach(scope => fixSourcePath(false, scope.source)); break; case 'setFunctionBreakpoints': (<DebugProtocol.SetFunctionBreakpointsResponse>response).body.breakpoints.forEach(bp => fixSourcePath(false, bp.source)); break; case 'setBreakpoints': (<DebugProtocol.SetBreakpointsResponse>response).body.breakpoints.forEach(bp => fixSourcePath(false, bp.source)); break; default: break; } } break; } }
src/vs/workbench/contrib/debug/common/debugUtils.ts
1
https://github.com/microsoft/vscode/commit/88e80b9a18b2cc3de0ca3a02977c3e2d4b088a60
[ 0.00389864481985569, 0.0003403332957532257, 0.00016091349243652076, 0.00017136911628767848, 0.0007591327885165811 ]
{ "id": 0, "code_window": [ "import { deepClone, equals } from 'vs/base/common/objects';\n", "import { DebugSession } from 'vs/workbench/contrib/debug/browser/debugSession';\n", "import { dispose, IDisposable } from 'vs/base/common/lifecycle';\n", "import { IDebugService, State, IDebugSession, CONTEXT_DEBUG_TYPE, CONTEXT_DEBUG_STATE, CONTEXT_IN_DEBUG_MODE, IThread, IDebugConfiguration, VIEWLET_ID, REPL_ID, IConfig, ILaunch, IViewModel, IConfigurationManager, IDebugModel, IEnablement, IBreakpoint, IBreakpointData, ICompound, IGlobalConfig, IStackFrame, AdapterEndEvent, getStateLabel, IDebugSessionOptions, CONTEXT_DEBUG_UX } from 'vs/workbench/contrib/debug/common/debug';\n", "import { isExtensionHostDebugging } from 'vs/workbench/contrib/debug/common/debugUtils';\n", "import { isErrorWithActions, createErrorWithActions } from 'vs/base/common/errorsWithActions';\n", "import { RunOnceScheduler } from 'vs/base/common/async';\n", "import { IExtensionHostDebugService } from 'vs/platform/debug/common/extensionHostDebug';\n", "import { isCodeEditor } from 'vs/editor/browser/editorBrowser';\n", "import { CancellationTokenSource } from 'vs/base/common/cancellation';\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { getExtensionHostDebugSession } from 'vs/workbench/contrib/debug/common/debugUtils';\n" ], "file_path": "src/vs/workbench/contrib/debug/browser/debugService.ts", "type": "replace", "edit_start_line_idx": 43 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as assert from 'assert'; import { TokenizationResult2 } from 'vs/editor/common/core/token'; import { ColorId, FontStyle, IState, LanguageIdentifier, MetadataConsts, TokenizationRegistry } from 'vs/editor/common/modes'; import { tokenizeLineToHTML, tokenizeToString } from 'vs/editor/common/modes/textToHtmlTokenizer'; import { ViewLineToken, ViewLineTokens } from 'vs/editor/test/common/core/viewLineToken'; import { MockMode } from 'vs/editor/test/common/mocks/mockMode'; suite('Editor Modes - textToHtmlTokenizer', () => { function toStr(pieces: { className: string; text: string }[]): string { let resultArr = pieces.map((t) => `<span class="${t.className}">${t.text}</span>`); return resultArr.join(''); } test('TextToHtmlTokenizer 1', () => { let mode = new Mode(); let support = TokenizationRegistry.get(mode.getId())!; let actual = tokenizeToString('.abc..def...gh', support); let expected = [ { className: 'mtk7', text: '.' }, { className: 'mtk9', text: 'abc' }, { className: 'mtk7', text: '..' }, { className: 'mtk9', text: 'def' }, { className: 'mtk7', text: '...' }, { className: 'mtk9', text: 'gh' }, ]; let expectedStr = `<div class="monaco-tokenized-source">${toStr(expected)}</div>`; assert.equal(actual, expectedStr); mode.dispose(); }); test('TextToHtmlTokenizer 2', () => { let mode = new Mode(); let support = TokenizationRegistry.get(mode.getId())!; let actual = tokenizeToString('.abc..def...gh\n.abc..def...gh', support); let expected1 = [ { className: 'mtk7', text: '.' }, { className: 'mtk9', text: 'abc' }, { className: 'mtk7', text: '..' }, { className: 'mtk9', text: 'def' }, { className: 'mtk7', text: '...' }, { className: 'mtk9', text: 'gh' }, ]; let expected2 = [ { className: 'mtk7', text: '.' }, { className: 'mtk9', text: 'abc' }, { className: 'mtk7', text: '..' }, { className: 'mtk9', text: 'def' }, { className: 'mtk7', text: '...' }, { className: 'mtk9', text: 'gh' }, ]; let expectedStr1 = toStr(expected1); let expectedStr2 = toStr(expected2); let expectedStr = `<div class="monaco-tokenized-source">${expectedStr1}<br/>${expectedStr2}</div>`; assert.equal(actual, expectedStr); mode.dispose(); }); test('tokenizeLineToHTML', () => { const text = 'Ciao hello world!'; const lineTokens = new ViewLineTokens([ new ViewLineToken( 4, ( (3 << MetadataConsts.FOREGROUND_OFFSET) | ((FontStyle.Bold | FontStyle.Italic) << MetadataConsts.FONT_STYLE_OFFSET) ) >>> 0 ), new ViewLineToken( 5, ( (1 << MetadataConsts.FOREGROUND_OFFSET) ) >>> 0 ), new ViewLineToken( 10, ( (4 << MetadataConsts.FOREGROUND_OFFSET) ) >>> 0 ), new ViewLineToken( 11, ( (1 << MetadataConsts.FOREGROUND_OFFSET) ) >>> 0 ), new ViewLineToken( 17, ( (5 << MetadataConsts.FOREGROUND_OFFSET) | ((FontStyle.Underline) << MetadataConsts.FONT_STYLE_OFFSET) ) >>> 0 ) ]); const colorMap = [null!, '#000000', '#ffffff', '#ff0000', '#00ff00', '#0000ff']; assert.equal( tokenizeLineToHTML(text, lineTokens, colorMap, 0, 17, 4, true), [ '<div>', '<span style="color: #ff0000;font-style: italic;font-weight: bold;">Ciao</span>', '<span style="color: #000000;">&#160;</span>', '<span style="color: #00ff00;">hello</span>', '<span style="color: #000000;">&#160;</span>', '<span style="color: #0000ff;text-decoration: underline;">world!</span>', '</div>' ].join('') ); assert.equal( tokenizeLineToHTML(text, lineTokens, colorMap, 0, 12, 4, true), [ '<div>', '<span style="color: #ff0000;font-style: italic;font-weight: bold;">Ciao</span>', '<span style="color: #000000;">&#160;</span>', '<span style="color: #00ff00;">hello</span>', '<span style="color: #000000;">&#160;</span>', '<span style="color: #0000ff;text-decoration: underline;">w</span>', '</div>' ].join('') ); assert.equal( tokenizeLineToHTML(text, lineTokens, colorMap, 0, 11, 4, true), [ '<div>', '<span style="color: #ff0000;font-style: italic;font-weight: bold;">Ciao</span>', '<span style="color: #000000;">&#160;</span>', '<span style="color: #00ff00;">hello</span>', '<span style="color: #000000;">&#160;</span>', '</div>' ].join('') ); assert.equal( tokenizeLineToHTML(text, lineTokens, colorMap, 1, 11, 4, true), [ '<div>', '<span style="color: #ff0000;font-style: italic;font-weight: bold;">iao</span>', '<span style="color: #000000;">&#160;</span>', '<span style="color: #00ff00;">hello</span>', '<span style="color: #000000;">&#160;</span>', '</div>' ].join('') ); assert.equal( tokenizeLineToHTML(text, lineTokens, colorMap, 4, 11, 4, true), [ '<div>', '<span style="color: #000000;">&#160;</span>', '<span style="color: #00ff00;">hello</span>', '<span style="color: #000000;">&#160;</span>', '</div>' ].join('') ); assert.equal( tokenizeLineToHTML(text, lineTokens, colorMap, 5, 11, 4, true), [ '<div>', '<span style="color: #00ff00;">hello</span>', '<span style="color: #000000;">&#160;</span>', '</div>' ].join('') ); assert.equal( tokenizeLineToHTML(text, lineTokens, colorMap, 5, 10, 4, true), [ '<div>', '<span style="color: #00ff00;">hello</span>', '</div>' ].join('') ); assert.equal( tokenizeLineToHTML(text, lineTokens, colorMap, 6, 9, 4, true), [ '<div>', '<span style="color: #00ff00;">ell</span>', '</div>' ].join('') ); }); test('tokenizeLineToHTML handle spaces #35954', () => { const text = ' Ciao hello world!'; const lineTokens = new ViewLineTokens([ new ViewLineToken( 2, ( (1 << MetadataConsts.FOREGROUND_OFFSET) ) >>> 0 ), new ViewLineToken( 6, ( (3 << MetadataConsts.FOREGROUND_OFFSET) | ((FontStyle.Bold | FontStyle.Italic) << MetadataConsts.FONT_STYLE_OFFSET) ) >>> 0 ), new ViewLineToken( 9, ( (1 << MetadataConsts.FOREGROUND_OFFSET) ) >>> 0 ), new ViewLineToken( 14, ( (4 << MetadataConsts.FOREGROUND_OFFSET) ) >>> 0 ), new ViewLineToken( 15, ( (1 << MetadataConsts.FOREGROUND_OFFSET) ) >>> 0 ), new ViewLineToken( 21, ( (5 << MetadataConsts.FOREGROUND_OFFSET) | ((FontStyle.Underline) << MetadataConsts.FONT_STYLE_OFFSET) ) >>> 0 ) ]); const colorMap = [null!, '#000000', '#ffffff', '#ff0000', '#00ff00', '#0000ff']; assert.equal( tokenizeLineToHTML(text, lineTokens, colorMap, 0, 21, 4, true), [ '<div>', '<span style="color: #000000;">&#160;&#160;</span>', '<span style="color: #ff0000;font-style: italic;font-weight: bold;">Ciao</span>', '<span style="color: #000000;">&#160;&#160;&#160;</span>', '<span style="color: #00ff00;">hello</span>', '<span style="color: #000000;">&#160;</span>', '<span style="color: #0000ff;text-decoration: underline;">world!</span>', '</div>' ].join('') ); assert.equal( tokenizeLineToHTML(text, lineTokens, colorMap, 0, 17, 4, true), [ '<div>', '<span style="color: #000000;">&#160;&#160;</span>', '<span style="color: #ff0000;font-style: italic;font-weight: bold;">Ciao</span>', '<span style="color: #000000;">&#160;&#160;&#160;</span>', '<span style="color: #00ff00;">hello</span>', '<span style="color: #000000;">&#160;</span>', '<span style="color: #0000ff;text-decoration: underline;">wo</span>', '</div>' ].join('') ); assert.equal( tokenizeLineToHTML(text, lineTokens, colorMap, 0, 3, 4, true), [ '<div>', '<span style="color: #000000;">&#160;&#160;</span>', '<span style="color: #ff0000;font-style: italic;font-weight: bold;">C</span>', '</div>' ].join('') ); }); }); class Mode extends MockMode { private static readonly _id = new LanguageIdentifier('textToHtmlTokenizerMode', 3); constructor() { super(Mode._id); this._register(TokenizationRegistry.register(this.getId(), { getInitialState: (): IState => null!, tokenize: undefined!, tokenize2: (line: string, state: IState): TokenizationResult2 => { let tokensArr: number[] = []; let prevColor: ColorId = -1; for (let i = 0; i < line.length; i++) { let colorId = line.charAt(i) === '.' ? 7 : 9; if (prevColor !== colorId) { tokensArr.push(i); tokensArr.push(( colorId << MetadataConsts.FOREGROUND_OFFSET ) >>> 0); } prevColor = colorId; } let tokens = new Uint32Array(tokensArr.length); for (let i = 0; i < tokens.length; i++) { tokens[i] = tokensArr[i]; } return new TokenizationResult2(tokens, null!); } })); } }
src/vs/editor/test/common/modes/textToHtmlTokenizer.test.ts
0
https://github.com/microsoft/vscode/commit/88e80b9a18b2cc3de0ca3a02977c3e2d4b088a60
[ 0.00018486508633941412, 0.00017397623741999269, 0.00016809436783660203, 0.0001739939907565713, 0.00000285060673377302 ]
{ "id": 0, "code_window": [ "import { deepClone, equals } from 'vs/base/common/objects';\n", "import { DebugSession } from 'vs/workbench/contrib/debug/browser/debugSession';\n", "import { dispose, IDisposable } from 'vs/base/common/lifecycle';\n", "import { IDebugService, State, IDebugSession, CONTEXT_DEBUG_TYPE, CONTEXT_DEBUG_STATE, CONTEXT_IN_DEBUG_MODE, IThread, IDebugConfiguration, VIEWLET_ID, REPL_ID, IConfig, ILaunch, IViewModel, IConfigurationManager, IDebugModel, IEnablement, IBreakpoint, IBreakpointData, ICompound, IGlobalConfig, IStackFrame, AdapterEndEvent, getStateLabel, IDebugSessionOptions, CONTEXT_DEBUG_UX } from 'vs/workbench/contrib/debug/common/debug';\n", "import { isExtensionHostDebugging } from 'vs/workbench/contrib/debug/common/debugUtils';\n", "import { isErrorWithActions, createErrorWithActions } from 'vs/base/common/errorsWithActions';\n", "import { RunOnceScheduler } from 'vs/base/common/async';\n", "import { IExtensionHostDebugService } from 'vs/platform/debug/common/extensionHostDebug';\n", "import { isCodeEditor } from 'vs/editor/browser/editorBrowser';\n", "import { CancellationTokenSource } from 'vs/base/common/cancellation';\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { getExtensionHostDebugSession } from 'vs/workbench/contrib/debug/common/debugUtils';\n" ], "file_path": "src/vs/workbench/contrib/debug/browser/debugService.ts", "type": "replace", "edit_start_line_idx": 43 }
/*! ***************************************************************************** Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ ///////////////////////////// /// WorkerGlobalScope APIs ///////////////////////////// // These are only available in a Web Worker declare function importScripts(...urls: string[]): void;
src/typings/lib.webworker.importscripts.d.ts
0
https://github.com/microsoft/vscode/commit/88e80b9a18b2cc3de0ca3a02977c3e2d4b088a60
[ 0.00023231552040670067, 0.00019390403758734465, 0.0001708369527477771, 0.00017855963960755616, 0.00002734339068410918 ]
{ "id": 0, "code_window": [ "import { deepClone, equals } from 'vs/base/common/objects';\n", "import { DebugSession } from 'vs/workbench/contrib/debug/browser/debugSession';\n", "import { dispose, IDisposable } from 'vs/base/common/lifecycle';\n", "import { IDebugService, State, IDebugSession, CONTEXT_DEBUG_TYPE, CONTEXT_DEBUG_STATE, CONTEXT_IN_DEBUG_MODE, IThread, IDebugConfiguration, VIEWLET_ID, REPL_ID, IConfig, ILaunch, IViewModel, IConfigurationManager, IDebugModel, IEnablement, IBreakpoint, IBreakpointData, ICompound, IGlobalConfig, IStackFrame, AdapterEndEvent, getStateLabel, IDebugSessionOptions, CONTEXT_DEBUG_UX } from 'vs/workbench/contrib/debug/common/debug';\n", "import { isExtensionHostDebugging } from 'vs/workbench/contrib/debug/common/debugUtils';\n", "import { isErrorWithActions, createErrorWithActions } from 'vs/base/common/errorsWithActions';\n", "import { RunOnceScheduler } from 'vs/base/common/async';\n", "import { IExtensionHostDebugService } from 'vs/platform/debug/common/extensionHostDebug';\n", "import { isCodeEditor } from 'vs/editor/browser/editorBrowser';\n", "import { CancellationTokenSource } from 'vs/base/common/cancellation';\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { getExtensionHostDebugSession } from 'vs/workbench/contrib/debug/common/debugUtils';\n" ], "file_path": "src/vs/workbench/contrib/debug/browser/debugService.ts", "type": "replace", "edit_start_line_idx": 43 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as assert from 'assert'; import { Emitter, Event } from 'vs/base/common/event'; import { GridNode, isGridBranchNode } from 'vs/base/browser/ui/grid/gridview'; import { IView } from 'vs/base/browser/ui/grid/grid'; export class TestView implements IView { private readonly _onDidChange = new Emitter<{ width: number; height: number; } | undefined>(); readonly onDidChange = this._onDidChange.event; get minimumWidth(): number { return this._minimumWidth; } set minimumWidth(size: number) { this._minimumWidth = size; this._onDidChange.fire(undefined); } get maximumWidth(): number { return this._maximumWidth; } set maximumWidth(size: number) { this._maximumWidth = size; this._onDidChange.fire(undefined); } get minimumHeight(): number { return this._minimumHeight; } set minimumHeight(size: number) { this._minimumHeight = size; this._onDidChange.fire(undefined); } get maximumHeight(): number { return this._maximumHeight; } set maximumHeight(size: number) { this._maximumHeight = size; this._onDidChange.fire(undefined); } private _element: HTMLElement = document.createElement('div'); get element(): HTMLElement { this._onDidGetElement.fire(); return this._element; } private readonly _onDidGetElement = new Emitter<void>(); readonly onDidGetElement = this._onDidGetElement.event; private _width = 0; get width(): number { return this._width; } private _height = 0; get height(): number { return this._height; } get size(): [number, number] { return [this.width, this.height]; } private readonly _onDidLayout = new Emitter<{ width: number; height: number; }>(); readonly onDidLayout: Event<{ width: number; height: number; }> = this._onDidLayout.event; private readonly _onDidFocus = new Emitter<void>(); readonly onDidFocus: Event<void> = this._onDidFocus.event; constructor( private _minimumWidth: number, private _maximumWidth: number, private _minimumHeight: number, private _maximumHeight: number ) { assert(_minimumWidth <= _maximumWidth, 'gridview view minimum width must be <= maximum width'); assert(_minimumHeight <= _maximumHeight, 'gridview view minimum height must be <= maximum height'); } layout(width: number, height: number): void { this._width = width; this._height = height; this._onDidLayout.fire({ width, height }); } focus(): void { this._onDidFocus.fire(); } dispose(): void { this._onDidChange.dispose(); this._onDidGetElement.dispose(); this._onDidLayout.dispose(); this._onDidFocus.dispose(); } } export function nodesToArrays(node: GridNode): any { if (isGridBranchNode(node)) { return node.children.map(nodesToArrays); } else { return node.view; } }
src/vs/base/test/browser/ui/grid/util.ts
0
https://github.com/microsoft/vscode/commit/88e80b9a18b2cc3de0ca3a02977c3e2d4b088a60
[ 0.00017620179278310388, 0.0001723627356113866, 0.00016816747665870935, 0.00017340552585665137, 0.000003111440037173452 ]
{ "id": 1, "code_window": [ "\t\t\tif (adapterExitEvent.error) {\n", "\t\t\t\tthis.notificationService.error(nls.localize('debugAdapterCrash', \"Debug adapter process has terminated unexpectedly ({0})\", adapterExitEvent.error.message || adapterExitEvent.error.toString()));\n", "\t\t\t}\n", "\n", "\t\t\t// 'Run without debugging' mode VSCode must terminate the extension host. More details: #3905\n", "\t\t\tif (isExtensionHostDebugging(session.configuration) && session.state === State.Running && session.configuration.noDebug) {\n", "\t\t\t\tthis.extensionHostDebugService.close(session.getId());\n", "\t\t\t}\n", "\n", "\t\t\tthis.telemetryDebugSessionStop(session, adapterExitEvent);\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tconst extensionDebugSession = getExtensionHostDebugSession(session);\n", "\t\t\tif (extensionDebugSession && extensionDebugSession.state === State.Running && extensionDebugSession.configuration.noDebug) {\n", "\t\t\t\tthis.extensionHostDebugService.close(extensionDebugSession.getId());\n" ], "file_path": "src/vs/workbench/contrib/debug/browser/debugService.ts", "type": "replace", "edit_start_line_idx": 541 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as nls from 'vs/nls'; import { Event, Emitter } from 'vs/base/common/event'; import { URI as uri } from 'vs/base/common/uri'; import { first, distinct } from 'vs/base/common/arrays'; import * as errors from 'vs/base/common/errors'; import severity from 'vs/base/common/severity'; import * as aria from 'vs/base/browser/ui/aria/aria'; import { IContextKeyService, IContextKey } from 'vs/platform/contextkey/common/contextkey'; import { IMarkerService } from 'vs/platform/markers/common/markers'; import { ILifecycleService } from 'vs/platform/lifecycle/common/lifecycle'; import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { FileChangesEvent, FileChangeType, IFileService } from 'vs/platform/files/common/files'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage'; import { DebugModel, ExceptionBreakpoint, FunctionBreakpoint, Breakpoint, Expression, DataBreakpoint } from 'vs/workbench/contrib/debug/common/debugModel'; import { ViewModel } from 'vs/workbench/contrib/debug/common/debugViewModel'; import * as debugactions from 'vs/workbench/contrib/debug/browser/debugActions'; import { ConfigurationManager } from 'vs/workbench/contrib/debug/browser/debugConfigurationManager'; import Constants from 'vs/workbench/contrib/markers/browser/constants'; import { ITaskService, ITaskSummary } from 'vs/workbench/contrib/tasks/common/taskService'; import { VIEWLET_ID as EXPLORER_VIEWLET_ID } from 'vs/workbench/contrib/files/common/files'; import { IViewletService } from 'vs/workbench/services/viewlet/browser/viewlet'; import { IPanelService } from 'vs/workbench/services/panel/common/panelService'; import { IWorkbenchLayoutService, Parts } from 'vs/workbench/services/layout/browser/layoutService'; import { ITextFileService } from 'vs/workbench/services/textfile/common/textfiles'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IWorkspaceContextService, WorkbenchState, IWorkspaceFolder, IWorkspace } from 'vs/platform/workspace/common/workspace'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { parse, getFirstFrame } from 'vs/base/common/console'; import { TaskEvent, TaskEventKind, TaskIdentifier } from 'vs/workbench/contrib/tasks/common/tasks'; import { IDialogService } from 'vs/platform/dialogs/common/dialogs'; import { INotificationService } from 'vs/platform/notification/common/notification'; import { IAction } from 'vs/base/common/actions'; import { deepClone, equals } from 'vs/base/common/objects'; import { DebugSession } from 'vs/workbench/contrib/debug/browser/debugSession'; import { dispose, IDisposable } from 'vs/base/common/lifecycle'; import { IDebugService, State, IDebugSession, CONTEXT_DEBUG_TYPE, CONTEXT_DEBUG_STATE, CONTEXT_IN_DEBUG_MODE, IThread, IDebugConfiguration, VIEWLET_ID, REPL_ID, IConfig, ILaunch, IViewModel, IConfigurationManager, IDebugModel, IEnablement, IBreakpoint, IBreakpointData, ICompound, IGlobalConfig, IStackFrame, AdapterEndEvent, getStateLabel, IDebugSessionOptions, CONTEXT_DEBUG_UX } from 'vs/workbench/contrib/debug/common/debug'; import { isExtensionHostDebugging } from 'vs/workbench/contrib/debug/common/debugUtils'; import { isErrorWithActions, createErrorWithActions } from 'vs/base/common/errorsWithActions'; import { RunOnceScheduler } from 'vs/base/common/async'; import { IExtensionHostDebugService } from 'vs/platform/debug/common/extensionHostDebug'; import { isCodeEditor } from 'vs/editor/browser/editorBrowser'; import { CancellationTokenSource } from 'vs/base/common/cancellation'; import { withUndefinedAsNull } from 'vs/base/common/types'; const DEBUG_BREAKPOINTS_KEY = 'debug.breakpoint'; const DEBUG_FUNCTION_BREAKPOINTS_KEY = 'debug.functionbreakpoint'; const DEBUG_DATA_BREAKPOINTS_KEY = 'debug.databreakpoint'; const DEBUG_EXCEPTION_BREAKPOINTS_KEY = 'debug.exceptionbreakpoint'; const DEBUG_WATCH_EXPRESSIONS_KEY = 'debug.watchexpressions'; function once(match: (e: TaskEvent) => boolean, event: Event<TaskEvent>): Event<TaskEvent> { return (listener, thisArgs = null, disposables?) => { const result = event(e => { if (match(e)) { result.dispose(); return listener.call(thisArgs, e); } }, null, disposables); return result; }; } const enum TaskRunResult { Failure, Success } export class DebugService implements IDebugService { _serviceBrand: undefined; private readonly _onDidChangeState: Emitter<State>; private readonly _onDidNewSession: Emitter<IDebugSession>; private readonly _onWillNewSession: Emitter<IDebugSession>; private readonly _onDidEndSession: Emitter<IDebugSession>; private model: DebugModel; private viewModel: ViewModel; private configurationManager: ConfigurationManager; private toDispose: IDisposable[]; private debugType: IContextKey<string>; private debugState: IContextKey<string>; private inDebugMode: IContextKey<boolean>; private debugUx: IContextKey<string>; private breakpointsToSendOnResourceSaved: Set<string>; private initializing = false; private previousState: State | undefined; private initCancellationToken: CancellationTokenSource | undefined; constructor( @IStorageService private readonly storageService: IStorageService, @IEditorService private readonly editorService: IEditorService, @ITextFileService private readonly textFileService: ITextFileService, @IViewletService private readonly viewletService: IViewletService, @IPanelService private readonly panelService: IPanelService, @INotificationService private readonly notificationService: INotificationService, @IDialogService private readonly dialogService: IDialogService, @IWorkbenchLayoutService private readonly layoutService: IWorkbenchLayoutService, @ITelemetryService private readonly telemetryService: ITelemetryService, @IWorkspaceContextService private readonly contextService: IWorkspaceContextService, @IContextKeyService contextKeyService: IContextKeyService, @ILifecycleService private readonly lifecycleService: ILifecycleService, @IInstantiationService private readonly instantiationService: IInstantiationService, @IExtensionService private readonly extensionService: IExtensionService, @IMarkerService private readonly markerService: IMarkerService, @ITaskService private readonly taskService: ITaskService, @IFileService private readonly fileService: IFileService, @IConfigurationService private readonly configurationService: IConfigurationService, @IExtensionHostDebugService private readonly extensionHostDebugService: IExtensionHostDebugService ) { this.toDispose = []; this.breakpointsToSendOnResourceSaved = new Set<string>(); this._onDidChangeState = new Emitter<State>(); this._onDidNewSession = new Emitter<IDebugSession>(); this._onWillNewSession = new Emitter<IDebugSession>(); this._onDidEndSession = new Emitter<IDebugSession>(); this.configurationManager = this.instantiationService.createInstance(ConfigurationManager); this.toDispose.push(this.configurationManager); this.debugType = CONTEXT_DEBUG_TYPE.bindTo(contextKeyService); this.debugState = CONTEXT_DEBUG_STATE.bindTo(contextKeyService); this.inDebugMode = CONTEXT_IN_DEBUG_MODE.bindTo(contextKeyService); this.debugUx = CONTEXT_DEBUG_UX.bindTo(contextKeyService); this.debugUx.set(!!this.configurationManager.selectedConfiguration.name ? 'default' : 'simple'); this.model = new DebugModel(this.loadBreakpoints(), this.loadFunctionBreakpoints(), this.loadExceptionBreakpoints(), this.loadDataBreakpoints(), this.loadWatchExpressions(), this.textFileService); this.toDispose.push(this.model); this.viewModel = new ViewModel(contextKeyService); this.toDispose.push(this.fileService.onFileChanges(e => this.onFileChanges(e))); this.lifecycleService.onShutdown(this.dispose, this); this.toDispose.push(this.extensionHostDebugService.onAttachSession(event => { const session = this.model.getSession(event.sessionId, true); if (session) { // EH was started in debug mode -> attach to it session.configuration.request = 'attach'; session.configuration.port = event.port; session.setSubId(event.subId); this.launchOrAttachToSession(session); } })); this.toDispose.push(this.extensionHostDebugService.onTerminateSession(event => { const session = this.model.getSession(event.sessionId); if (session && session.subId === event.subId) { session.disconnect(); } })); this.toDispose.push(this.extensionHostDebugService.onLogToSession(event => { const session = this.model.getSession(event.sessionId, true); if (session) { // extension logged output -> show it in REPL const sev = event.log.severity === 'warn' ? severity.Warning : event.log.severity === 'error' ? severity.Error : severity.Info; const { args, stack } = parse(event.log); const frame = !!stack ? getFirstFrame(stack) : undefined; session.logToRepl(sev, args, frame); } })); this.toDispose.push(this.viewModel.onDidFocusStackFrame(() => { this.onStateChange(); })); this.toDispose.push(this.viewModel.onDidFocusSession(() => { this.onStateChange(); })); this.toDispose.push(this.configurationManager.onDidSelectConfiguration(() => { this.debugUx.set(!!(this.state !== State.Inactive || this.configurationManager.selectedConfiguration.name) ? 'default' : 'simple'); })); } getModel(): IDebugModel { return this.model; } getViewModel(): IViewModel { return this.viewModel; } getConfigurationManager(): IConfigurationManager { return this.configurationManager; } sourceIsNotAvailable(uri: uri): void { this.model.sourceIsNotAvailable(uri); } dispose(): void { this.toDispose = dispose(this.toDispose); } //---- state management get state(): State { const focusedSession = this.viewModel.focusedSession; if (focusedSession) { return focusedSession.state; } return this.initializing ? State.Initializing : State.Inactive; } private startInitializingState() { if (!this.initializing) { this.initializing = true; this.onStateChange(); } } private endInitializingState() { if (this.initCancellationToken) { this.initCancellationToken.cancel(); this.initCancellationToken = undefined; } if (this.initializing) { this.initializing = false; this.onStateChange(); } } private onStateChange(): void { const state = this.state; if (this.previousState !== state) { this.debugState.set(getStateLabel(state)); this.inDebugMode.set(state !== State.Inactive); // Only show the simple ux if debug is not yet started and if no launch.json exists this.debugUx.set(((state !== State.Inactive && state !== State.Initializing) || this.configurationManager.selectedConfiguration.name) ? 'default' : 'simple'); this.previousState = state; this._onDidChangeState.fire(state); } } get onDidChangeState(): Event<State> { return this._onDidChangeState.event; } get onDidNewSession(): Event<IDebugSession> { return this._onDidNewSession.event; } get onWillNewSession(): Event<IDebugSession> { return this._onWillNewSession.event; } get onDidEndSession(): Event<IDebugSession> { return this._onDidEndSession.event; } //---- life cycle management /** * main entry point * properly manages compounds, checks for errors and handles the initializing state. */ async startDebugging(launch: ILaunch | undefined, configOrName?: IConfig | string, options?: IDebugSessionOptions): Promise<boolean> { this.startInitializingState(); try { // make sure to save all files and that the configuration is up to date await this.extensionService.activateByEvent('onDebug'); await this.editorService.saveAll(); await this.configurationService.reloadConfiguration(launch ? launch.workspace : undefined); await this.extensionService.whenInstalledExtensionsRegistered(); let config: IConfig | undefined; let compound: ICompound | undefined; if (!configOrName) { configOrName = this.configurationManager.selectedConfiguration.name; } if (typeof configOrName === 'string' && launch) { config = launch.getConfiguration(configOrName); compound = launch.getCompound(configOrName); const sessions = this.model.getSessions(); const alreadyRunningMessage = nls.localize('configurationAlreadyRunning', "There is already a debug configuration \"{0}\" running.", configOrName); if (sessions.some(s => s.configuration.name === configOrName && (!launch || !launch.workspace || !s.root || s.root.uri.toString() === launch.workspace.uri.toString()))) { throw new Error(alreadyRunningMessage); } if (compound && compound.configurations && sessions.some(p => compound!.configurations.indexOf(p.configuration.name) !== -1)) { throw new Error(alreadyRunningMessage); } } else if (typeof configOrName !== 'string') { config = configOrName; } if (compound) { // we are starting a compound debug, first do some error checking and than start each configuration in the compound if (!compound.configurations) { throw new Error(nls.localize({ key: 'compoundMustHaveConfigurations', comment: ['compound indicates a "compounds" configuration item', '"configurations" is an attribute and should not be localized'] }, "Compound must have \"configurations\" attribute set in order to start multiple configurations.")); } if (compound.preLaunchTask) { const taskResult = await this.runTaskAndCheckErrors(launch?.workspace || this.contextService.getWorkspace(), compound.preLaunchTask); if (taskResult === TaskRunResult.Failure) { this.endInitializingState(); return false; } } const values = await Promise.all(compound.configurations.map(configData => { const name = typeof configData === 'string' ? configData : configData.name; if (name === compound!.name) { return Promise.resolve(false); } let launchForName: ILaunch | undefined; if (typeof configData === 'string') { const launchesContainingName = this.configurationManager.getLaunches().filter(l => !!l.getConfiguration(name)); if (launchesContainingName.length === 1) { launchForName = launchesContainingName[0]; } else if (launch && launchesContainingName.length > 1 && launchesContainingName.indexOf(launch) >= 0) { // If there are multiple launches containing the configuration give priority to the configuration in the current launch launchForName = launch; } else { throw new Error(launchesContainingName.length === 0 ? nls.localize('noConfigurationNameInWorkspace', "Could not find launch configuration '{0}' in the workspace.", name) : nls.localize('multipleConfigurationNamesInWorkspace', "There are multiple launch configurations '{0}' in the workspace. Use folder name to qualify the configuration.", name)); } } else if (configData.folder) { const launchesMatchingConfigData = this.configurationManager.getLaunches().filter(l => l.workspace && l.workspace.name === configData.folder && !!l.getConfiguration(configData.name)); if (launchesMatchingConfigData.length === 1) { launchForName = launchesMatchingConfigData[0]; } else { throw new Error(nls.localize('noFolderWithName', "Can not find folder with name '{0}' for configuration '{1}' in compound '{2}'.", configData.folder, configData.name, compound!.name)); } } return this.createSession(launchForName, launchForName!.getConfiguration(name), options); })); const result = values.every(success => !!success); // Compound launch is a success only if each configuration launched successfully this.endInitializingState(); return result; } if (configOrName && !config) { const message = !!launch ? nls.localize('configMissing', "Configuration '{0}' is missing in 'launch.json'.", typeof configOrName === 'string' ? configOrName : JSON.stringify(configOrName)) : nls.localize('launchJsonDoesNotExist', "'launch.json' does not exist."); throw new Error(message); } const result = await this.createSession(launch, config, options); this.endInitializingState(); return result; } catch (err) { // make sure to get out of initializing state, and propagate the result this.endInitializingState(); return Promise.reject(err); } } /** * gets the debugger for the type, resolves configurations by providers, substitutes variables and runs prelaunch tasks */ private async createSession(launch: ILaunch | undefined, config: IConfig | undefined, options?: IDebugSessionOptions): Promise<boolean> { // We keep the debug type in a separate variable 'type' so that a no-folder config has no attributes. // Storing the type in the config would break extensions that assume that the no-folder case is indicated by an empty config. let type: string | undefined; if (config) { type = config.type; } else { // a no-folder workspace has no launch.config config = Object.create(null); } const unresolvedConfig = deepClone(config); if (options && options.noDebug) { config!.noDebug = true; } if (!type) { const guess = await this.configurationManager.guessDebugger(); if (guess) { type = guess.type; } } this.initCancellationToken = new CancellationTokenSource(); const configByProviders = await this.configurationManager.resolveConfigurationByProviders(launch && launch.workspace ? launch.workspace.uri : undefined, type, config!, this.initCancellationToken.token); // a falsy config indicates an aborted launch if (configByProviders && configByProviders.type) { try { const resolvedConfig = await this.substituteVariables(launch, configByProviders); if (!resolvedConfig) { // User canceled resolving of interactive variables, silently return return false; } if (!this.configurationManager.getDebugger(resolvedConfig.type) || (configByProviders.request !== 'attach' && configByProviders.request !== 'launch')) { let message: string; if (configByProviders.request !== 'attach' && configByProviders.request !== 'launch') { message = configByProviders.request ? nls.localize('debugRequestNotSupported', "Attribute '{0}' has an unsupported value '{1}' in the chosen debug configuration.", 'request', configByProviders.request) : nls.localize('debugRequesMissing', "Attribute '{0}' is missing from the chosen debug configuration.", 'request'); } else { message = resolvedConfig.type ? nls.localize('debugTypeNotSupported', "Configured debug type '{0}' is not supported.", resolvedConfig.type) : nls.localize('debugTypeMissing', "Missing property 'type' for the chosen launch configuration."); } await this.showError(message); return false; } const workspace = launch ? launch.workspace : this.contextService.getWorkspace(); const taskResult = await this.runTaskAndCheckErrors(workspace, resolvedConfig.preLaunchTask); if (taskResult === TaskRunResult.Success) { return this.doCreateSession(launch?.workspace, { resolved: resolvedConfig, unresolved: unresolvedConfig }, options); } return false; } catch (err) { if (err && err.message) { await this.showError(err.message); } else if (this.contextService.getWorkbenchState() === WorkbenchState.EMPTY) { await this.showError(nls.localize('noFolderWorkspaceDebugError', "The active file can not be debugged. Make sure it is saved and that you have a debug extension installed for that file type.")); } if (launch) { await launch.openConfigFile(false, true, undefined, this.initCancellationToken ? this.initCancellationToken.token : undefined); } return false; } } if (launch && type && configByProviders === null) { // show launch.json only for "config" being "null". await launch.openConfigFile(false, true, type, this.initCancellationToken ? this.initCancellationToken.token : undefined); } return false; } /** * instantiates the new session, initializes the session, registers session listeners and reports telemetry */ private async doCreateSession(root: IWorkspaceFolder | undefined, configuration: { resolved: IConfig, unresolved: IConfig | undefined }, options?: IDebugSessionOptions): Promise<boolean> { const session = this.instantiationService.createInstance(DebugSession, configuration, root, this.model, options); this.model.addSession(session); // register listeners as the very first thing! this.registerSessionListeners(session); // since the Session is now properly registered under its ID and hooked, we can announce it // this event doesn't go to extensions this._onWillNewSession.fire(session); const openDebug = this.configurationService.getValue<IDebugConfiguration>('debug').openDebug; // Open debug viewlet based on the visibility of the side bar and openDebug setting. Do not open for 'run without debug' if (!configuration.resolved.noDebug && (openDebug === 'openOnSessionStart' || (openDebug === 'openOnFirstSessionStart' && this.viewModel.firstSessionStart))) { await this.viewletService.openViewlet(VIEWLET_ID); } try { await this.launchOrAttachToSession(session); const internalConsoleOptions = session.configuration.internalConsoleOptions || this.configurationService.getValue<IDebugConfiguration>('debug').internalConsoleOptions; if (internalConsoleOptions === 'openOnSessionStart' || (this.viewModel.firstSessionStart && internalConsoleOptions === 'openOnFirstSessionStart')) { this.panelService.openPanel(REPL_ID, false); } this.viewModel.firstSessionStart = false; const showSubSessions = this.configurationService.getValue<IDebugConfiguration>('debug').showSubSessionsInToolBar; const sessions = this.model.getSessions(); const shownSessions = showSubSessions ? sessions : sessions.filter(s => !s.parentSession); if (shownSessions.length > 1) { this.viewModel.setMultiSessionView(true); } // since the initialized response has arrived announce the new Session (including extensions) this._onDidNewSession.fire(session); await this.telemetryDebugSessionStart(root, session.configuration.type); return true; } catch (error) { if (errors.isPromiseCanceledError(error)) { // don't show 'canceled' error messages to the user #7906 return false; } // Show the repl if some error got logged there #5870 if (session && session.getReplElements().length > 0) { this.panelService.openPanel(REPL_ID, false); } if (session.configuration && session.configuration.request === 'attach' && session.configuration.__autoAttach) { // ignore attach timeouts in auto attach mode return false; } const errorMessage = error instanceof Error ? error.message : error; await this.showError(errorMessage, isErrorWithActions(error) ? error.actions : []); return false; } } private async launchOrAttachToSession(session: IDebugSession, forceFocus = false): Promise<void> { const dbgr = this.configurationManager.getDebugger(session.configuration.type); try { await session.initialize(dbgr!); await session.launchOrAttach(session.configuration); if (forceFocus || !this.viewModel.focusedSession) { await this.focusStackFrame(undefined, undefined, session); } } catch (err) { session.shutdown(); return Promise.reject(err); } } private registerSessionListeners(session: IDebugSession): void { const sessionRunningScheduler = new RunOnceScheduler(() => { // Do not immediatly defocus the stack frame if the session is running if (session.state === State.Running && this.viewModel.focusedSession === session) { this.viewModel.setFocus(undefined, this.viewModel.focusedThread, session, false); } }, 200); this.toDispose.push(session.onDidChangeState(() => { if (session.state === State.Running && this.viewModel.focusedSession === session) { sessionRunningScheduler.schedule(); } if (session === this.viewModel.focusedSession) { this.onStateChange(); } })); this.toDispose.push(session.onDidEndAdapter(async adapterExitEvent => { if (adapterExitEvent.error) { this.notificationService.error(nls.localize('debugAdapterCrash', "Debug adapter process has terminated unexpectedly ({0})", adapterExitEvent.error.message || adapterExitEvent.error.toString())); } // 'Run without debugging' mode VSCode must terminate the extension host. More details: #3905 if (isExtensionHostDebugging(session.configuration) && session.state === State.Running && session.configuration.noDebug) { this.extensionHostDebugService.close(session.getId()); } this.telemetryDebugSessionStop(session, adapterExitEvent); if (session.configuration.postDebugTask) { try { await this.runTask(session.root, session.configuration.postDebugTask); } catch (err) { this.notificationService.error(err); } } session.shutdown(); this.endInitializingState(); this._onDidEndSession.fire(session); const focusedSession = this.viewModel.focusedSession; if (focusedSession && focusedSession.getId() === session.getId()) { await this.focusStackFrame(undefined); } if (this.model.getSessions().length === 0) { this.viewModel.setMultiSessionView(false); if (this.layoutService.isVisible(Parts.SIDEBAR_PART) && this.configurationService.getValue<IDebugConfiguration>('debug').openExplorerOnEnd) { this.viewletService.openViewlet(EXPLORER_VIEWLET_ID); } // Data breakpoints that can not be persisted should be cleared when a session ends const dataBreakpoints = this.model.getDataBreakpoints().filter(dbp => !dbp.canPersist); dataBreakpoints.forEach(dbp => this.model.removeDataBreakpoints(dbp.getId())); } })); } async restartSession(session: IDebugSession, restartData?: any): Promise<any> { await this.editorService.saveAll(); const isAutoRestart = !!restartData; const runTasks: () => Promise<TaskRunResult> = async () => { if (isAutoRestart) { // Do not run preLaunch and postDebug tasks for automatic restarts return Promise.resolve(TaskRunResult.Success); } await this.runTask(session.root, session.configuration.postDebugTask); return this.runTaskAndCheckErrors(session.root, session.configuration.preLaunchTask); }; if (isExtensionHostDebugging(session.configuration)) { const taskResult = await runTasks(); if (taskResult === TaskRunResult.Success) { this.extensionHostDebugService.reload(session.getId()); } return; } if (session.capabilities.supportsRestartRequest) { const taskResult = await runTasks(); if (taskResult === TaskRunResult.Success) { await session.restart(); } return; } const shouldFocus = !!this.viewModel.focusedSession && session.getId() === this.viewModel.focusedSession.getId(); // If the restart is automatic -> disconnect, otherwise -> terminate #55064 if (isAutoRestart) { await session.disconnect(true); } else { await session.terminate(true); } return new Promise<void>((c, e) => { setTimeout(async () => { const taskResult = await runTasks(); if (taskResult !== TaskRunResult.Success) { return; } // Read the configuration again if a launch.json has been changed, if not just use the inmemory configuration let needsToSubstitute = false; let unresolved: IConfig | undefined; const launch = session.root ? this.configurationManager.getLaunch(session.root.uri) : undefined; if (launch) { unresolved = launch.getConfiguration(session.configuration.name); if (unresolved && !equals(unresolved, session.unresolvedConfiguration)) { // Take the type from the session since the debug extension might overwrite it #21316 unresolved.type = session.configuration.type; unresolved.noDebug = session.configuration.noDebug; needsToSubstitute = true; } } let resolved: IConfig | undefined | null = session.configuration; if (launch && needsToSubstitute && unresolved) { this.initCancellationToken = new CancellationTokenSource(); const resolvedByProviders = await this.configurationManager.resolveConfigurationByProviders(launch.workspace ? launch.workspace.uri : undefined, unresolved.type, unresolved, this.initCancellationToken.token); if (resolvedByProviders) { resolved = await this.substituteVariables(launch, resolvedByProviders); } else { resolved = resolvedByProviders; } } if (!resolved) { return c(undefined); } session.setConfiguration({ resolved, unresolved }); session.configuration.__restart = restartData; try { await this.launchOrAttachToSession(session, shouldFocus); this._onDidNewSession.fire(session); c(undefined); } catch (error) { e(error); } }, 300); }); } stopSession(session: IDebugSession): Promise<any> { if (session) { return session.terminate(); } const sessions = this.model.getSessions(); if (sessions.length === 0) { this.endInitializingState(); } return Promise.all(sessions.map(s => s.terminate())); } private async substituteVariables(launch: ILaunch | undefined, config: IConfig): Promise<IConfig | undefined> { const dbg = this.configurationManager.getDebugger(config.type); if (dbg) { let folder: IWorkspaceFolder | undefined = undefined; if (launch && launch.workspace) { folder = launch.workspace; } else { const folders = this.contextService.getWorkspace().folders; if (folders.length === 1) { folder = folders[0]; } } try { return await dbg.substituteVariables(folder, config); } catch (err) { this.showError(err.message); return undefined; // bail out } } return Promise.resolve(config); } private async showError(message: string, errorActions: ReadonlyArray<IAction> = []): Promise<void> { const configureAction = this.instantiationService.createInstance(debugactions.ConfigureAction, debugactions.ConfigureAction.ID, debugactions.ConfigureAction.LABEL); const actions = [...errorActions, configureAction]; const { choice } = await this.dialogService.show(severity.Error, message, actions.map(a => a.label).concat(nls.localize('cancel', "Cancel")), { cancelId: actions.length }); if (choice < actions.length) { return actions[choice].run(); } return undefined; } //---- task management private async runTaskAndCheckErrors(root: IWorkspaceFolder | IWorkspace | undefined, taskId: string | TaskIdentifier | undefined): Promise<TaskRunResult> { try { const taskSummary = await this.runTask(root, taskId); const errorCount = taskId ? this.markerService.getStatistics().errors : 0; const successExitCode = taskSummary && taskSummary.exitCode === 0; const failureExitCode = taskSummary && taskSummary.exitCode !== 0; const onTaskErrors = this.configurationService.getValue<IDebugConfiguration>('debug').onTaskErrors; if (successExitCode || onTaskErrors === 'debugAnyway' || (errorCount === 0 && !failureExitCode)) { return TaskRunResult.Success; } if (onTaskErrors === 'showErrors') { this.panelService.openPanel(Constants.MARKERS_PANEL_ID); return Promise.resolve(TaskRunResult.Failure); } const taskLabel = typeof taskId === 'string' ? taskId : taskId ? taskId.name : ''; const message = errorCount > 1 ? nls.localize('preLaunchTaskErrors', "Errors exist after running preLaunchTask '{0}'.", taskLabel) : errorCount === 1 ? nls.localize('preLaunchTaskError', "Error exists after running preLaunchTask '{0}'.", taskLabel) : nls.localize('preLaunchTaskExitCode', "The preLaunchTask '{0}' terminated with exit code {1}.", taskLabel, taskSummary ? taskSummary.exitCode : 0); const result = await this.dialogService.show(severity.Warning, message, [nls.localize('debugAnyway', "Debug Anyway"), nls.localize('showErrors', "Show Errors"), nls.localize('cancel', "Cancel")], { checkbox: { label: nls.localize('remember', "Remember my choice in user settings"), }, cancelId: 2 }); if (result.choice === 2) { return Promise.resolve(TaskRunResult.Failure); } const debugAnyway = result.choice === 0; if (result.checkboxChecked) { this.configurationService.updateValue('debug.onTaskErrors', debugAnyway ? 'debugAnyway' : 'showErrors'); } if (debugAnyway) { return TaskRunResult.Success; } this.panelService.openPanel(Constants.MARKERS_PANEL_ID); return Promise.resolve(TaskRunResult.Failure); } catch (err) { await this.showError(err.message, [this.taskService.configureAction()]); return TaskRunResult.Failure; } } private async runTask(root: IWorkspace | IWorkspaceFolder | undefined, taskId: string | TaskIdentifier | undefined): Promise<ITaskSummary | null> { if (!taskId) { return Promise.resolve(null); } if (!root) { return Promise.reject(new Error(nls.localize('invalidTaskReference', "Task '{0}' can not be referenced from a launch configuration that is in a different workspace folder.", typeof taskId === 'string' ? taskId : taskId.type))); } // run a task before starting a debug session const task = await this.taskService.getTask(root, taskId); if (!task) { const errorMessage = typeof taskId === 'string' ? nls.localize('DebugTaskNotFoundWithTaskId', "Could not find the task '{0}'.", taskId) : nls.localize('DebugTaskNotFound', "Could not find the specified task."); return Promise.reject(createErrorWithActions(errorMessage)); } // If a task is missing the problem matcher the promise will never complete, so we need to have a workaround #35340 let taskStarted = false; const inactivePromise: Promise<ITaskSummary | null> = new Promise((c, e) => once(e => { // When a task isBackground it will go inactive when it is safe to launch. // But when a background task is terminated by the user, it will also fire an inactive event. // This means that we will not get to see the real exit code from running the task (undefined when terminated by the user). // Catch the ProcessEnded event here, which occurs before inactive, and capture the exit code to prevent this. return (e.kind === TaskEventKind.Inactive || (e.kind === TaskEventKind.ProcessEnded && e.exitCode === undefined)) && e.taskId === task._id; }, this.taskService.onDidStateChange)(e => { taskStarted = true; c(e.kind === TaskEventKind.ProcessEnded ? { exitCode: e.exitCode } : null); })); const promise: Promise<ITaskSummary | null> = this.taskService.getActiveTasks().then(async (tasks): Promise<ITaskSummary | null> => { if (tasks.filter(t => t._id === task._id).length) { // Check that the task isn't busy and if it is, wait for it const busyTasks = await this.taskService.getBusyTasks(); if (busyTasks.filter(t => t._id === task._id).length) { taskStarted = true; return inactivePromise; } // task is already running and isn't busy - nothing to do. return Promise.resolve(null); } once(e => ((e.kind === TaskEventKind.Active) || (e.kind === TaskEventKind.DependsOnStarted)) && e.taskId === task._id, this.taskService.onDidStateChange)(() => { // Task is active, so everything seems to be fine, no need to prompt after 10 seconds // Use case being a slow running task should not be prompted even though it takes more than 10 seconds taskStarted = true; }); const taskPromise = this.taskService.run(task); if (task.configurationProperties.isBackground) { return inactivePromise; } return taskPromise.then(withUndefinedAsNull); }); return new Promise((c, e) => { promise.then(result => { taskStarted = true; c(result); }, error => e(error)); setTimeout(() => { if (!taskStarted) { const errorMessage = typeof taskId === 'string' ? nls.localize('taskNotTrackedWithTaskId', "The specified task cannot be tracked.") : nls.localize('taskNotTracked', "The task '{0}' cannot be tracked.", JSON.stringify(taskId)); e({ severity: severity.Error, message: errorMessage }); } }, 10000); }); } //---- focus management async focusStackFrame(stackFrame: IStackFrame | undefined, thread?: IThread, session?: IDebugSession, explicit?: boolean): Promise<void> { if (!session) { if (stackFrame || thread) { session = stackFrame ? stackFrame.thread.session : thread!.session; } else { const sessions = this.model.getSessions(); const stoppedSession = sessions.filter(s => s.state === State.Stopped).shift(); session = stoppedSession || (sessions.length ? sessions[0] : undefined); } } if (!thread) { if (stackFrame) { thread = stackFrame.thread; } else { const threads = session ? session.getAllThreads() : undefined; const stoppedThread = threads && threads.filter(t => t.stopped).shift(); thread = stoppedThread || (threads && threads.length ? threads[0] : undefined); } } if (!stackFrame) { if (thread) { const callStack = thread.getCallStack(); stackFrame = first(callStack, sf => !!(sf && sf.source && sf.source.available && sf.source.presentationHint !== 'deemphasize'), undefined); } } if (stackFrame) { const editor = await stackFrame.openInEditor(this.editorService, true); if (editor) { const control = editor.getControl(); if (stackFrame && isCodeEditor(control) && control.hasModel()) { const model = control.getModel(); if (stackFrame.range.startLineNumber <= model.getLineCount()) { const lineContent = control.getModel().getLineContent(stackFrame.range.startLineNumber); aria.alert(nls.localize('debuggingPaused', "Debugging paused {0}, {1} {2} {3}", thread && thread.stoppedDetails ? `, reason ${thread.stoppedDetails.reason}` : '', stackFrame.source ? stackFrame.source.name : '', stackFrame.range.startLineNumber, lineContent)); } } } } if (session) { this.debugType.set(session.configuration.type); } else { this.debugType.reset(); } this.viewModel.setFocus(stackFrame, thread, session, !!explicit); } //---- watches addWatchExpression(name: string): void { const we = this.model.addWatchExpression(name); this.viewModel.setSelectedExpression(we); this.storeWatchExpressions(); } renameWatchExpression(id: string, newName: string): void { this.model.renameWatchExpression(id, newName); this.storeWatchExpressions(); } moveWatchExpression(id: string, position: number): void { this.model.moveWatchExpression(id, position); this.storeWatchExpressions(); } removeWatchExpressions(id?: string): void { this.model.removeWatchExpressions(id); this.storeWatchExpressions(); } //---- breakpoints async enableOrDisableBreakpoints(enable: boolean, breakpoint?: IEnablement): Promise<void> { if (breakpoint) { this.model.setEnablement(breakpoint, enable); if (breakpoint instanceof Breakpoint) { await this.sendBreakpoints(breakpoint.uri); } else if (breakpoint instanceof FunctionBreakpoint) { await this.sendFunctionBreakpoints(); } else if (breakpoint instanceof DataBreakpoint) { await this.sendDataBreakpoints(); } else { await this.sendExceptionBreakpoints(); } } else { this.model.enableOrDisableAllBreakpoints(enable); await this.sendAllBreakpoints(); } this.storeBreakpoints(); } async addBreakpoints(uri: uri, rawBreakpoints: IBreakpointData[], context: string): Promise<IBreakpoint[]> { const breakpoints = this.model.addBreakpoints(uri, rawBreakpoints); breakpoints.forEach(bp => aria.status(nls.localize('breakpointAdded', "Added breakpoint, line {0}, file {1}", bp.lineNumber, uri.fsPath))); breakpoints.forEach(bp => this.telemetryDebugAddBreakpoint(bp, context)); await this.sendBreakpoints(uri); this.storeBreakpoints(); return breakpoints; } async updateBreakpoints(uri: uri, data: Map<string, DebugProtocol.Breakpoint>, sendOnResourceSaved: boolean): Promise<void> { this.model.updateBreakpoints(data); if (sendOnResourceSaved) { this.breakpointsToSendOnResourceSaved.add(uri.toString()); } else { await this.sendBreakpoints(uri); } this.storeBreakpoints(); } async removeBreakpoints(id?: string): Promise<void> { const toRemove = this.model.getBreakpoints().filter(bp => !id || bp.getId() === id); toRemove.forEach(bp => aria.status(nls.localize('breakpointRemoved', "Removed breakpoint, line {0}, file {1}", bp.lineNumber, bp.uri.fsPath))); const urisToClear = distinct(toRemove, bp => bp.uri.toString()).map(bp => bp.uri); this.model.removeBreakpoints(toRemove); await Promise.all(urisToClear.map(uri => this.sendBreakpoints(uri))); this.storeBreakpoints(); } setBreakpointsActivated(activated: boolean): Promise<void> { this.model.setBreakpointsActivated(activated); return this.sendAllBreakpoints(); } addFunctionBreakpoint(name?: string, id?: string): void { const newFunctionBreakpoint = this.model.addFunctionBreakpoint(name || '', id); this.viewModel.setSelectedFunctionBreakpoint(newFunctionBreakpoint); } async renameFunctionBreakpoint(id: string, newFunctionName: string): Promise<void> { this.model.renameFunctionBreakpoint(id, newFunctionName); await this.sendFunctionBreakpoints(); this.storeBreakpoints(); } async removeFunctionBreakpoints(id?: string): Promise<void> { this.model.removeFunctionBreakpoints(id); await this.sendFunctionBreakpoints(); this.storeBreakpoints(); } async addDataBreakpoint(label: string, dataId: string, canPersist: boolean): Promise<void> { this.model.addDataBreakpoint(label, dataId, canPersist); await this.sendDataBreakpoints(); this.storeBreakpoints(); } async removeDataBreakpoints(id?: string): Promise<void> { this.model.removeDataBreakpoints(id); await this.sendDataBreakpoints(); this.storeBreakpoints(); } async sendAllBreakpoints(session?: IDebugSession): Promise<any> { await Promise.all(distinct(this.model.getBreakpoints(), bp => bp.uri.toString()).map(bp => this.sendBreakpoints(bp.uri, false, session))); await this.sendFunctionBreakpoints(session); await this.sendDataBreakpoints(session); // send exception breakpoints at the end since some debug adapters rely on the order await this.sendExceptionBreakpoints(session); } private sendBreakpoints(modelUri: uri, sourceModified = false, session?: IDebugSession): Promise<void> { const breakpointsToSend = this.model.getBreakpoints({ uri: modelUri, enabledOnly: true }); return this.sendToOneOrAllSessions(session, s => s.sendBreakpoints(modelUri, breakpointsToSend, sourceModified) ); } private sendFunctionBreakpoints(session?: IDebugSession): Promise<void> { const breakpointsToSend = this.model.getFunctionBreakpoints().filter(fbp => fbp.enabled && this.model.areBreakpointsActivated()); return this.sendToOneOrAllSessions(session, s => { return s.capabilities.supportsFunctionBreakpoints ? s.sendFunctionBreakpoints(breakpointsToSend) : Promise.resolve(undefined); }); } private sendDataBreakpoints(session?: IDebugSession): Promise<void> { const breakpointsToSend = this.model.getDataBreakpoints().filter(fbp => fbp.enabled && this.model.areBreakpointsActivated()); return this.sendToOneOrAllSessions(session, s => { return s.capabilities.supportsDataBreakpoints ? s.sendDataBreakpoints(breakpointsToSend) : Promise.resolve(undefined); }); } private sendExceptionBreakpoints(session?: IDebugSession): Promise<void> { const enabledExceptionBps = this.model.getExceptionBreakpoints().filter(exb => exb.enabled); return this.sendToOneOrAllSessions(session, s => { return s.sendExceptionBreakpoints(enabledExceptionBps); }); } private async sendToOneOrAllSessions(session: IDebugSession | undefined, send: (session: IDebugSession) => Promise<void>): Promise<void> { if (session) { await send(session); } else { await Promise.all(this.model.getSessions().map(s => send(s))); } } private onFileChanges(fileChangesEvent: FileChangesEvent): void { const toRemove = this.model.getBreakpoints().filter(bp => fileChangesEvent.contains(bp.uri, FileChangeType.DELETED)); if (toRemove.length) { this.model.removeBreakpoints(toRemove); } fileChangesEvent.getUpdated().forEach(event => { if (this.breakpointsToSendOnResourceSaved.delete(event.resource.toString())) { this.sendBreakpoints(event.resource, true); } }); } private loadBreakpoints(): Breakpoint[] { let result: Breakpoint[] | undefined; try { result = JSON.parse(this.storageService.get(DEBUG_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((breakpoint: any) => { return new Breakpoint(uri.parse(breakpoint.uri.external || breakpoint.source.uri.external), breakpoint.lineNumber, breakpoint.column, breakpoint.enabled, breakpoint.condition, breakpoint.hitCondition, breakpoint.logMessage, breakpoint.adapterData, this.textFileService); }); } catch (e) { } return result || []; } private loadFunctionBreakpoints(): FunctionBreakpoint[] { let result: FunctionBreakpoint[] | undefined; try { result = JSON.parse(this.storageService.get(DEBUG_FUNCTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((fb: any) => { return new FunctionBreakpoint(fb.name, fb.enabled, fb.hitCondition, fb.condition, fb.logMessage); }); } catch (e) { } return result || []; } private loadExceptionBreakpoints(): ExceptionBreakpoint[] { let result: ExceptionBreakpoint[] | undefined; try { result = JSON.parse(this.storageService.get(DEBUG_EXCEPTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((exBreakpoint: any) => { return new ExceptionBreakpoint(exBreakpoint.filter, exBreakpoint.label, exBreakpoint.enabled); }); } catch (e) { } return result || []; } private loadDataBreakpoints(): DataBreakpoint[] { let result: DataBreakpoint[] | undefined; try { result = JSON.parse(this.storageService.get(DEBUG_DATA_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((dbp: any) => { return new DataBreakpoint(dbp.label, dbp.dataId, true, dbp.enabled, dbp.hitCondition, dbp.condition, dbp.logMessage); }); } catch (e) { } return result || []; } private loadWatchExpressions(): Expression[] { let result: Expression[] | undefined; try { result = JSON.parse(this.storageService.get(DEBUG_WATCH_EXPRESSIONS_KEY, StorageScope.WORKSPACE, '[]')).map((watchStoredData: { name: string, id: string }) => { return new Expression(watchStoredData.name, watchStoredData.id); }); } catch (e) { } return result || []; } private storeWatchExpressions(): void { const watchExpressions = this.model.getWatchExpressions(); if (watchExpressions.length) { this.storageService.store(DEBUG_WATCH_EXPRESSIONS_KEY, JSON.stringify(watchExpressions.map(we => ({ name: we.name, id: we.getId() }))), StorageScope.WORKSPACE); } else { this.storageService.remove(DEBUG_WATCH_EXPRESSIONS_KEY, StorageScope.WORKSPACE); } } private storeBreakpoints(): void { const breakpoints = this.model.getBreakpoints(); if (breakpoints.length) { this.storageService.store(DEBUG_BREAKPOINTS_KEY, JSON.stringify(breakpoints), StorageScope.WORKSPACE); } else { this.storageService.remove(DEBUG_BREAKPOINTS_KEY, StorageScope.WORKSPACE); } const functionBreakpoints = this.model.getFunctionBreakpoints(); if (functionBreakpoints.length) { this.storageService.store(DEBUG_FUNCTION_BREAKPOINTS_KEY, JSON.stringify(functionBreakpoints), StorageScope.WORKSPACE); } else { this.storageService.remove(DEBUG_FUNCTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE); } const dataBreakpoints = this.model.getDataBreakpoints().filter(dbp => dbp.canPersist); if (dataBreakpoints.length) { this.storageService.store(DEBUG_DATA_BREAKPOINTS_KEY, JSON.stringify(dataBreakpoints), StorageScope.WORKSPACE); } else { this.storageService.remove(DEBUG_DATA_BREAKPOINTS_KEY, StorageScope.WORKSPACE); } const exceptionBreakpoints = this.model.getExceptionBreakpoints(); if (exceptionBreakpoints.length) { this.storageService.store(DEBUG_EXCEPTION_BREAKPOINTS_KEY, JSON.stringify(exceptionBreakpoints), StorageScope.WORKSPACE); } else { this.storageService.remove(DEBUG_EXCEPTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE); } } //---- telemetry private telemetryDebugSessionStart(root: IWorkspaceFolder | undefined, type: string): Promise<void> { const dbgr = this.configurationManager.getDebugger(type); if (!dbgr) { return Promise.resolve(); } const extension = dbgr.getMainExtensionDescriptor(); /* __GDPR__ "debugSessionStart" : { "type": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "breakpointCount": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "exceptionBreakpoints": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "watchExpressionsCount": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "extensionName": { "classification": "PublicNonPersonalData", "purpose": "FeatureInsight" }, "isBuiltin": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true}, "launchJsonExists": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true } } */ return this.telemetryService.publicLog('debugSessionStart', { type: type, breakpointCount: this.model.getBreakpoints().length, exceptionBreakpoints: this.model.getExceptionBreakpoints(), watchExpressionsCount: this.model.getWatchExpressions().length, extensionName: extension.identifier.value, isBuiltin: extension.isBuiltin, launchJsonExists: root && !!this.configurationService.getValue<IGlobalConfig>('launch', { resource: root.uri }) }); } private telemetryDebugSessionStop(session: IDebugSession, adapterExitEvent: AdapterEndEvent): Promise<any> { const breakpoints = this.model.getBreakpoints(); /* __GDPR__ "debugSessionStop" : { "type" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "success": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "sessionLengthInSeconds": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "breakpointCount": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "watchExpressionsCount": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true } } */ return this.telemetryService.publicLog('debugSessionStop', { type: session && session.configuration.type, success: adapterExitEvent.emittedStopped || breakpoints.length === 0, sessionLengthInSeconds: adapterExitEvent.sessionLengthInSeconds, breakpointCount: breakpoints.length, watchExpressionsCount: this.model.getWatchExpressions().length }); } private telemetryDebugAddBreakpoint(breakpoint: IBreakpoint, context: string): Promise<any> { /* __GDPR__ "debugAddBreakpoint" : { "context": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "hasCondition": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "hasHitCondition": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "hasLogMessage": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true } } */ return this.telemetryService.publicLog('debugAddBreakpoint', { context: context, hasCondition: !!breakpoint.condition, hasHitCondition: !!breakpoint.hitCondition, hasLogMessage: !!breakpoint.logMessage }); } }
src/vs/workbench/contrib/debug/browser/debugService.ts
1
https://github.com/microsoft/vscode/commit/88e80b9a18b2cc3de0ca3a02977c3e2d4b088a60
[ 0.9891855716705322, 0.009602746926248074, 0.00016137106285896152, 0.0001700302236713469, 0.08963412046432495 ]
{ "id": 1, "code_window": [ "\t\t\tif (adapterExitEvent.error) {\n", "\t\t\t\tthis.notificationService.error(nls.localize('debugAdapterCrash', \"Debug adapter process has terminated unexpectedly ({0})\", adapterExitEvent.error.message || adapterExitEvent.error.toString()));\n", "\t\t\t}\n", "\n", "\t\t\t// 'Run without debugging' mode VSCode must terminate the extension host. More details: #3905\n", "\t\t\tif (isExtensionHostDebugging(session.configuration) && session.state === State.Running && session.configuration.noDebug) {\n", "\t\t\t\tthis.extensionHostDebugService.close(session.getId());\n", "\t\t\t}\n", "\n", "\t\t\tthis.telemetryDebugSessionStop(session, adapterExitEvent);\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tconst extensionDebugSession = getExtensionHostDebugSession(session);\n", "\t\t\tif (extensionDebugSession && extensionDebugSession.state === State.Running && extensionDebugSession.configuration.noDebug) {\n", "\t\t\t\tthis.extensionHostDebugService.close(extensionDebugSession.getId());\n" ], "file_path": "src/vs/workbench/contrib/debug/browser/debugService.ts", "type": "replace", "edit_start_line_idx": 541 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ /* ---------- DiffEditor ---------- */ .monaco-diff-editor .diffOverview { z-index: 9; } /* colors not externalized: using transparancy on background */ .monaco-diff-editor.vs .diffOverview { background: rgba(0, 0, 0, 0.03); } .monaco-diff-editor.vs-dark .diffOverview { background: rgba(255, 255, 255, 0.01); } .monaco-diff-editor .diffViewport { box-shadow: inset 0px 0px 1px 0px #B9B9B9; background: rgba(0, 0, 0, 0.10); } .monaco-diff-editor.vs-dark .diffViewport, .monaco-diff-editor.hc-black .diffViewport { background: rgba(255, 255, 255, 0.10); } .monaco-scrollable-element.modified-in-monaco-diff-editor.vs .scrollbar { background: rgba(0,0,0,0); } .monaco-scrollable-element.modified-in-monaco-diff-editor.vs-dark .scrollbar { background: rgba(0,0,0,0); } .monaco-scrollable-element.modified-in-monaco-diff-editor.hc-black .scrollbar { background: none; } .monaco-scrollable-element.modified-in-monaco-diff-editor .slider { z-index: 10; } .modified-in-monaco-diff-editor .slider.active { background: rgba(171, 171, 171, .4); } .modified-in-monaco-diff-editor.hc-black .slider.active { background: none; } /* ---------- Diff ---------- */ .monaco-editor .insert-sign, .monaco-diff-editor .insert-sign, .monaco-editor .delete-sign, .monaco-diff-editor .delete-sign { background-size: 60%; opacity: 0.7; background-repeat: no-repeat; background-position: 75% center; background-size: 11px 11px; } .monaco-editor.hc-black .insert-sign, .monaco-diff-editor.hc-black .insert-sign, .monaco-editor.hc-black .delete-sign, .monaco-diff-editor.hc-black .delete-sign { opacity: 1; } .monaco-editor .insert-sign, .monaco-diff-editor .insert-sign { background-image: url('addition-light.svg'); } .monaco-editor .delete-sign, .monaco-diff-editor .delete-sign { background-image: url('deletion-light.svg'); } .monaco-editor.vs-dark .insert-sign, .monaco-diff-editor.vs-dark .insert-sign, .monaco-editor.hc-black .insert-sign, .monaco-diff-editor.hc-black .insert-sign { background-image: url('addition-dark.svg'); } .monaco-editor.vs-dark .delete-sign, .monaco-diff-editor.vs-dark .delete-sign, .monaco-editor.hc-black .delete-sign, .monaco-diff-editor.hc-black .delete-sign { background-image: url('deletion-dark.svg'); } .monaco-editor .inline-deleted-margin-view-zone { text-align: right; } .monaco-editor .inline-added-margin-view-zone { text-align: right; } .monaco-editor .diagonal-fill { background: url('diagonal-fill.png'); } .monaco-editor.vs-dark .diagonal-fill { opacity: 0.2; } .monaco-editor.hc-black .diagonal-fill { background: none; } /* ---------- Inline Diff ---------- */ .monaco-editor .view-zones .view-lines .view-line span { display: inline-block; } .monaco-editor .margin-view-zones .inline-deleted-margin-view-zone .lightbulb-glyph { background: url('lightbulb-light.svg') center center no-repeat; } .monaco-editor.vs-dark .margin-view-zones .inline-deleted-margin-view-zone .lightbulb-glyph, .monaco-editor.hc-dark .margin-view-zones .inline-deleted-margin-view-zone .lightbulb-glyph { background: url('lightbulb-dark.svg') center center no-repeat; } .monaco-editor .margin-view-zones .lightbulb-glyph:hover { cursor: pointer; }
src/vs/editor/browser/widget/media/diffEditor.css
0
https://github.com/microsoft/vscode/commit/88e80b9a18b2cc3de0ca3a02977c3e2d4b088a60
[ 0.00017580222629476339, 0.0001736362901283428, 0.0001704005990177393, 0.00017349168774671853, 0.0000014462383433055948 ]
{ "id": 1, "code_window": [ "\t\t\tif (adapterExitEvent.error) {\n", "\t\t\t\tthis.notificationService.error(nls.localize('debugAdapterCrash', \"Debug adapter process has terminated unexpectedly ({0})\", adapterExitEvent.error.message || adapterExitEvent.error.toString()));\n", "\t\t\t}\n", "\n", "\t\t\t// 'Run without debugging' mode VSCode must terminate the extension host. More details: #3905\n", "\t\t\tif (isExtensionHostDebugging(session.configuration) && session.state === State.Running && session.configuration.noDebug) {\n", "\t\t\t\tthis.extensionHostDebugService.close(session.getId());\n", "\t\t\t}\n", "\n", "\t\t\tthis.telemetryDebugSessionStop(session, adapterExitEvent);\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tconst extensionDebugSession = getExtensionHostDebugSession(session);\n", "\t\t\tif (extensionDebugSession && extensionDebugSession.state === State.Running && extensionDebugSession.configuration.noDebug) {\n", "\t\t\t\tthis.extensionHostDebugService.close(extensionDebugSession.getId());\n" ], "file_path": "src/vs/workbench/contrib/debug/browser/debugService.ts", "type": "replace", "edit_start_line_idx": 541 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as path from 'path'; import * as vscode from 'vscode'; class File implements vscode.FileStat { type: vscode.FileType; ctime: number; mtime: number; size: number; name: string; data?: Uint8Array; constructor(name: string) { this.type = vscode.FileType.File; this.ctime = Date.now(); this.mtime = Date.now(); this.size = 0; this.name = name; } } class Directory implements vscode.FileStat { type: vscode.FileType; ctime: number; mtime: number; size: number; name: string; entries: Map<string, File | Directory>; constructor(name: string) { this.type = vscode.FileType.Directory; this.ctime = Date.now(); this.mtime = Date.now(); this.size = 0; this.name = name; this.entries = new Map(); } } export type Entry = File | Directory; export class MemFS implements vscode.FileSystemProvider { readonly scheme = 'fake-fs'; readonly root = new Directory(''); // --- manage file metadata stat(uri: vscode.Uri): vscode.FileStat { return this._lookup(uri, false); } readDirectory(uri: vscode.Uri): [string, vscode.FileType][] { const entry = this._lookupAsDirectory(uri, false); let result: [string, vscode.FileType][] = []; for (const [name, child] of entry.entries) { result.push([name, child.type]); } return result; } // --- manage file contents readFile(uri: vscode.Uri): Uint8Array { const data = this._lookupAsFile(uri, false).data; if (data) { return data; } throw vscode.FileSystemError.FileNotFound(); } writeFile(uri: vscode.Uri, content: Uint8Array, options: { create: boolean, overwrite: boolean }): void { let basename = path.posix.basename(uri.path); let parent = this._lookupParentDirectory(uri); let entry = parent.entries.get(basename); if (entry instanceof Directory) { throw vscode.FileSystemError.FileIsADirectory(uri); } if (!entry && !options.create) { throw vscode.FileSystemError.FileNotFound(uri); } if (entry && options.create && !options.overwrite) { throw vscode.FileSystemError.FileExists(uri); } if (!entry) { entry = new File(basename); parent.entries.set(basename, entry); this._fireSoon({ type: vscode.FileChangeType.Created, uri }); } entry.mtime = Date.now(); entry.size = content.byteLength; entry.data = content; this._fireSoon({ type: vscode.FileChangeType.Changed, uri }); } // --- manage files/folders rename(oldUri: vscode.Uri, newUri: vscode.Uri, options: { overwrite: boolean }): void { if (!options.overwrite && this._lookup(newUri, true)) { throw vscode.FileSystemError.FileExists(newUri); } let entry = this._lookup(oldUri, false); let oldParent = this._lookupParentDirectory(oldUri); let newParent = this._lookupParentDirectory(newUri); let newName = path.posix.basename(newUri.path); oldParent.entries.delete(entry.name); entry.name = newName; newParent.entries.set(newName, entry); this._fireSoon( { type: vscode.FileChangeType.Deleted, uri: oldUri }, { type: vscode.FileChangeType.Created, uri: newUri } ); } delete(uri: vscode.Uri): void { let dirname = uri.with({ path: path.posix.dirname(uri.path) }); let basename = path.posix.basename(uri.path); let parent = this._lookupAsDirectory(dirname, false); if (!parent.entries.has(basename)) { throw vscode.FileSystemError.FileNotFound(uri); } parent.entries.delete(basename); parent.mtime = Date.now(); parent.size -= 1; this._fireSoon({ type: vscode.FileChangeType.Changed, uri: dirname }, { uri, type: vscode.FileChangeType.Deleted }); } createDirectory(uri: vscode.Uri): void { let basename = path.posix.basename(uri.path); let dirname = uri.with({ path: path.posix.dirname(uri.path) }); let parent = this._lookupAsDirectory(dirname, false); let entry = new Directory(basename); parent.entries.set(entry.name, entry); parent.mtime = Date.now(); parent.size += 1; this._fireSoon({ type: vscode.FileChangeType.Changed, uri: dirname }, { type: vscode.FileChangeType.Created, uri }); } // --- lookup private _lookup(uri: vscode.Uri, silent: false): Entry; private _lookup(uri: vscode.Uri, silent: boolean): Entry | undefined; private _lookup(uri: vscode.Uri, silent: boolean): Entry | undefined { let parts = uri.path.split('/'); let entry: Entry = this.root; for (const part of parts) { if (!part) { continue; } let child: Entry | undefined; if (entry instanceof Directory) { child = entry.entries.get(part); } if (!child) { if (!silent) { throw vscode.FileSystemError.FileNotFound(uri); } else { return undefined; } } entry = child; } return entry; } private _lookupAsDirectory(uri: vscode.Uri, silent: boolean): Directory { let entry = this._lookup(uri, silent); if (entry instanceof Directory) { return entry; } throw vscode.FileSystemError.FileNotADirectory(uri); } private _lookupAsFile(uri: vscode.Uri, silent: boolean): File { let entry = this._lookup(uri, silent); if (entry instanceof File) { return entry; } throw vscode.FileSystemError.FileIsADirectory(uri); } private _lookupParentDirectory(uri: vscode.Uri): Directory { const dirname = uri.with({ path: path.posix.dirname(uri.path) }); return this._lookupAsDirectory(dirname, false); } // --- manage file events private _emitter = new vscode.EventEmitter<vscode.FileChangeEvent[]>(); private _bufferedEvents: vscode.FileChangeEvent[] = []; private _fireSoonHandle?: NodeJS.Timer; readonly onDidChangeFile: vscode.Event<vscode.FileChangeEvent[]> = this._emitter.event; watch(_resource: vscode.Uri): vscode.Disposable { // ignore, fires for all changes... return new vscode.Disposable(() => { }); } private _fireSoon(...events: vscode.FileChangeEvent[]): void { this._bufferedEvents.push(...events); if (this._fireSoonHandle) { clearTimeout(this._fireSoonHandle); } this._fireSoonHandle = setTimeout(() => { this._emitter.fire(this._bufferedEvents); this._bufferedEvents.length = 0; }, 5); } }
extensions/vscode-api-tests/src/memfs.ts
0
https://github.com/microsoft/vscode/commit/88e80b9a18b2cc3de0ca3a02977c3e2d4b088a60
[ 0.00017533516802359372, 0.00017197550914715976, 0.00016753640375100076, 0.00017259904416278005, 0.000002294316573170363 ]
{ "id": 1, "code_window": [ "\t\t\tif (adapterExitEvent.error) {\n", "\t\t\t\tthis.notificationService.error(nls.localize('debugAdapterCrash', \"Debug adapter process has terminated unexpectedly ({0})\", adapterExitEvent.error.message || adapterExitEvent.error.toString()));\n", "\t\t\t}\n", "\n", "\t\t\t// 'Run without debugging' mode VSCode must terminate the extension host. More details: #3905\n", "\t\t\tif (isExtensionHostDebugging(session.configuration) && session.state === State.Running && session.configuration.noDebug) {\n", "\t\t\t\tthis.extensionHostDebugService.close(session.getId());\n", "\t\t\t}\n", "\n", "\t\t\tthis.telemetryDebugSessionStop(session, adapterExitEvent);\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tconst extensionDebugSession = getExtensionHostDebugSession(session);\n", "\t\t\tif (extensionDebugSession && extensionDebugSession.state === State.Running && extensionDebugSession.configuration.noDebug) {\n", "\t\t\t\tthis.extensionHostDebugService.close(extensionDebugSession.getId());\n" ], "file_path": "src/vs/workbench/contrib/debug/browser/debugService.ts", "type": "replace", "edit_start_line_idx": 541 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { localize } from 'vs/nls'; import { join, basename } from 'vs/base/common/path'; import { forEach } from 'vs/base/common/collections'; import { Disposable } from 'vs/base/common/lifecycle'; import { match } from 'vs/base/common/glob'; import * as json from 'vs/base/common/json'; import { IExtensionManagementService, IExtensionGalleryService, EXTENSION_IDENTIFIER_PATTERN, InstallOperation, ILocalExtension } from 'vs/platform/extensionManagement/common/extensionManagement'; import { IExtensionTipsService, ExtensionRecommendationReason, IExtensionsConfigContent, RecommendationChangeNotification, IExtensionRecommendation, ExtensionRecommendationSource, IExtensionEnablementService, EnablementState } from 'vs/workbench/services/extensionManagement/common/extensionManagement'; import { IModelService } from 'vs/editor/common/services/modelService'; import { ITextModel } from 'vs/editor/common/model'; import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { ShowRecommendedExtensionsAction, InstallWorkspaceRecommendedExtensionsAction, InstallRecommendedExtensionAction } from 'vs/workbench/contrib/extensions/browser/extensionsActions'; import Severity from 'vs/base/common/severity'; import { IWorkspaceContextService, IWorkspaceFolder, IWorkspace, IWorkspaceFoldersChangeEvent, WorkbenchState } from 'vs/platform/workspace/common/workspace'; import { IFileService } from 'vs/platform/files/common/files'; import { IExtensionsConfiguration, ConfigurationKey, ShowRecommendationsOnlyOnDemandKey, IExtensionsViewlet, IExtensionsWorkbenchService, EXTENSIONS_CONFIG } from 'vs/workbench/contrib/extensions/common/extensions'; import { IConfigurationService, ConfigurationTarget } from 'vs/platform/configuration/common/configuration'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { flatten, distinct, shuffle, coalesce } from 'vs/base/common/arrays'; import { guessMimeTypes, MIME_UNKNOWN } from 'vs/base/common/mime'; import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions'; import { IRequestService, asJson } from 'vs/platform/request/common/request'; import { isNumber } from 'vs/base/common/types'; import { IViewletService } from 'vs/workbench/services/viewlet/browser/viewlet'; import { INotificationService } from 'vs/platform/notification/common/notification'; import { Emitter, Event } from 'vs/base/common/event'; import { assign } from 'vs/base/common/objects'; import { URI } from 'vs/base/common/uri'; import { areSameExtensions } from 'vs/platform/extensionManagement/common/extensionManagementUtil'; import { IExperimentService, ExperimentActionType, ExperimentState } from 'vs/workbench/contrib/experiments/common/experimentService'; import { CancellationToken } from 'vs/base/common/cancellation'; import { ExtensionType } from 'vs/platform/extensions/common/extensions'; import { extname } from 'vs/base/common/resources'; import { IExeBasedExtensionTip, IProductService } from 'vs/platform/product/common/productService'; import { timeout } from 'vs/base/common/async'; import { IWorkspaceTagsService } from 'vs/workbench/contrib/tags/common/workspaceTags'; import { setImmediate, isWeb } from 'vs/base/common/platform'; import { platform, env as processEnv } from 'vs/base/common/process'; import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService'; const milliSecondsInADay = 1000 * 60 * 60 * 24; const choiceNever = localize('neverShowAgain', "Don't Show Again"); const searchMarketplace = localize('searchMarketplace', "Search Marketplace"); const processedFileExtensions: string[] = []; interface IDynamicWorkspaceRecommendations { remoteSet: string[]; recommendations: string[]; } function caseInsensitiveGet<T>(obj: { [key: string]: T }, key: string): T | undefined { if (!obj) { return undefined; } for (const _key in obj) { if (Object.hasOwnProperty.call(obj, _key) && _key.toLowerCase() === key.toLowerCase()) { return obj[_key]; } } return undefined; } export class ExtensionTipsService extends Disposable implements IExtensionTipsService { _serviceBrand: undefined; private _fileBasedRecommendations: { [id: string]: { recommendedTime: number, sources: ExtensionRecommendationSource[] }; } = Object.create(null); private _exeBasedRecommendations: { [id: string]: IExeBasedExtensionTip; } = Object.create(null); private _importantExeBasedRecommendations: { [id: string]: IExeBasedExtensionTip; } = Object.create(null); private _availableRecommendations: { [pattern: string]: string[] } = Object.create(null); private _allWorkspaceRecommendedExtensions: IExtensionRecommendation[] = []; private _dynamicWorkspaceRecommendations: string[] = []; private _experimentalRecommendations: { [id: string]: string } = Object.create(null); private _allIgnoredRecommendations: string[] = []; private _globallyIgnoredRecommendations: string[] = []; private _workspaceIgnoredRecommendations: string[] = []; private _extensionsRecommendationsUrl: string | undefined; public loadWorkspaceConfigPromise: Promise<void>; private proactiveRecommendationsFetched: boolean = false; private readonly _onRecommendationChange = this._register(new Emitter<RecommendationChangeNotification>()); onRecommendationChange: Event<RecommendationChangeNotification> = this._onRecommendationChange.event; private sessionSeed: number; constructor( @IExtensionGalleryService private readonly _galleryService: IExtensionGalleryService, @IModelService private readonly _modelService: IModelService, @IStorageService private readonly storageService: IStorageService, @IExtensionManagementService private readonly extensionsService: IExtensionManagementService, @IExtensionEnablementService private readonly extensionEnablementService: IExtensionEnablementService, @IInstantiationService private readonly instantiationService: IInstantiationService, @IFileService private readonly fileService: IFileService, @IWorkspaceContextService private readonly contextService: IWorkspaceContextService, @IConfigurationService private readonly configurationService: IConfigurationService, @ITelemetryService private readonly telemetryService: ITelemetryService, @IWorkbenchEnvironmentService private readonly environmentService: IWorkbenchEnvironmentService, @IExtensionService private readonly extensionService: IExtensionService, @IRequestService private readonly requestService: IRequestService, @IViewletService private readonly viewletService: IViewletService, @INotificationService private readonly notificationService: INotificationService, @IExtensionManagementService private readonly extensionManagementService: IExtensionManagementService, @IExtensionsWorkbenchService private readonly extensionWorkbenchService: IExtensionsWorkbenchService, @IExperimentService private readonly experimentService: IExperimentService, @IWorkspaceTagsService private readonly workspaceTagsService: IWorkspaceTagsService, @IProductService private readonly productService: IProductService ) { super(); if (!this.isEnabled()) { this.sessionSeed = 0; this.loadWorkspaceConfigPromise = Promise.resolve(); return; } if (this.productService.extensionsGallery && this.productService.extensionsGallery.recommendationsUrl) { this._extensionsRecommendationsUrl = this.productService.extensionsGallery.recommendationsUrl; } this.sessionSeed = +new Date(); let globallyIgnored = <string[]>JSON.parse(this.storageService.get('extensionsAssistant/ignored_recommendations', StorageScope.GLOBAL, '[]')); this._globallyIgnoredRecommendations = globallyIgnored.map(id => id.toLowerCase()); this.fetchCachedDynamicWorkspaceRecommendations(); this.fetchFileBasedRecommendations(); this.fetchExperimentalRecommendations(); if (!this.configurationService.getValue<boolean>(ShowRecommendationsOnlyOnDemandKey)) { this.fetchProactiveRecommendations(true); } this.loadWorkspaceConfigPromise = this.getWorkspaceRecommendations().then(() => { this.promptWorkspaceRecommendations(); this._register(this._modelService.onModelAdded(this.promptFiletypeBasedRecommendations, this)); this._modelService.getModels().forEach(model => this.promptFiletypeBasedRecommendations(model)); }); this._register(this.contextService.onDidChangeWorkspaceFolders(e => this.onWorkspaceFoldersChanged(e))); this._register(this.configurationService.onDidChangeConfiguration(e => { if (!this.proactiveRecommendationsFetched && !this.configurationService.getValue<boolean>(ShowRecommendationsOnlyOnDemandKey)) { this.fetchProactiveRecommendations(); } })); this._register(this.extensionManagementService.onDidInstallExtension(e => { if (e.gallery && e.operation === InstallOperation.Install) { const extRecommendations = this.getAllRecommendationsWithReason() || {}; const recommendationReason = extRecommendations[e.gallery.identifier.id.toLowerCase()]; if (recommendationReason) { /* __GDPR__ "extensionGallery:install:recommendations" : { "recommendationReason": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "${include}": [ "${GalleryExtensionTelemetryData}" ] } */ this.telemetryService.publicLog('extensionGallery:install:recommendations', assign(e.gallery.telemetryData, { recommendationReason: recommendationReason.reasonId })); } } })); } private isEnabled(): boolean { return this._galleryService.isEnabled() && !this.environmentService.extensionDevelopmentLocationURI; } getAllRecommendationsWithReason(): { [id: string]: { reasonId: ExtensionRecommendationReason, reasonText: string }; } { let output: { [id: string]: { reasonId: ExtensionRecommendationReason, reasonText: string }; } = Object.create(null); if (!this.proactiveRecommendationsFetched) { return output; } forEach(this._experimentalRecommendations, entry => output[entry.key.toLowerCase()] = { reasonId: ExtensionRecommendationReason.Experimental, reasonText: entry.value }); if (this.contextService.getWorkspace().folders && this.contextService.getWorkspace().folders.length === 1) { const currentRepo = this.contextService.getWorkspace().folders[0].name; this._dynamicWorkspaceRecommendations.forEach(id => output[id.toLowerCase()] = { reasonId: ExtensionRecommendationReason.DynamicWorkspace, reasonText: localize('dynamicWorkspaceRecommendation', "This extension may interest you because it's popular among users of the {0} repository.", currentRepo) }); } forEach(this._exeBasedRecommendations, entry => output[entry.key.toLowerCase()] = { reasonId: ExtensionRecommendationReason.Executable, reasonText: localize('exeBasedRecommendation', "This extension is recommended because you have {0} installed.", entry.value.friendlyName) }); forEach(this._fileBasedRecommendations, entry => output[entry.key.toLowerCase()] = { reasonId: ExtensionRecommendationReason.File, reasonText: localize('fileBasedRecommendation', "This extension is recommended based on the files you recently opened.") }); this._allWorkspaceRecommendedExtensions.forEach(({ extensionId }) => output[extensionId.toLowerCase()] = { reasonId: ExtensionRecommendationReason.Workspace, reasonText: localize('workspaceRecommendation', "This extension is recommended by users of the current workspace.") }); for (const id of this._allIgnoredRecommendations) { delete output[id]; } return output; } getAllIgnoredRecommendations(): { global: string[], workspace: string[] } { return { global: this._globallyIgnoredRecommendations, workspace: this._workspaceIgnoredRecommendations }; } toggleIgnoredRecommendation(extensionId: string, shouldIgnore: boolean) { const lowerId = extensionId.toLowerCase(); if (shouldIgnore) { const reason = this.getAllRecommendationsWithReason()[lowerId]; if (reason && reason.reasonId) { /* __GDPR__ "extensionsRecommendations:ignoreRecommendation" : { "recommendationReason": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "extensionId": { "classification": "PublicNonPersonalData", "purpose": "FeatureInsight" } } */ this.telemetryService.publicLog('extensionsRecommendations:ignoreRecommendation', { id: extensionId, recommendationReason: reason.reasonId }); } } this._globallyIgnoredRecommendations = shouldIgnore ? distinct([...this._globallyIgnoredRecommendations, lowerId].map(id => id.toLowerCase())) : this._globallyIgnoredRecommendations.filter(id => id !== lowerId); this.storageService.store('extensionsAssistant/ignored_recommendations', JSON.stringify(this._globallyIgnoredRecommendations), StorageScope.GLOBAL); this._allIgnoredRecommendations = distinct([...this._globallyIgnoredRecommendations, ...this._workspaceIgnoredRecommendations]); this._onRecommendationChange.fire({ extensionId: extensionId, isRecommended: !shouldIgnore }); } getKeymapRecommendations(): IExtensionRecommendation[] { return (this.productService.keymapExtensionTips || []) .filter(extensionId => this.isExtensionAllowedToBeRecommended(extensionId)) .map(extensionId => (<IExtensionRecommendation>{ extensionId, sources: ['application'] })); } //#region workspaceRecommendations getWorkspaceRecommendations(): Promise<IExtensionRecommendation[]> { if (!this.isEnabled()) { return Promise.resolve([]); } return this.fetchWorkspaceRecommendations() .then(() => this._allWorkspaceRecommendedExtensions.filter(rec => this.isExtensionAllowedToBeRecommended(rec.extensionId))); } /** * Parse all extensions.json files, fetch workspace recommendations, filter out invalid and unwanted ones */ private fetchWorkspaceRecommendations(): Promise<void> { if (!this.isEnabled) { return Promise.resolve(undefined); } return this.fetchExtensionRecommendationContents() .then(result => this.validateExtensions(result.map(({ contents }) => contents)) .then(({ invalidExtensions, message }) => { if (invalidExtensions.length > 0 && this.notificationService) { this.notificationService.warn(`The below ${invalidExtensions.length} extension(s) in workspace recommendations have issues:\n${message}`); } const seenUnWantedRecommendations: { [id: string]: boolean } = {}; this._allWorkspaceRecommendedExtensions = []; this._workspaceIgnoredRecommendations = []; for (const contentsBySource of result) { if (contentsBySource.contents.unwantedRecommendations) { for (const r of contentsBySource.contents.unwantedRecommendations) { const unwantedRecommendation = r.toLowerCase(); if (!seenUnWantedRecommendations[unwantedRecommendation] && invalidExtensions.indexOf(unwantedRecommendation) === -1) { this._workspaceIgnoredRecommendations.push(unwantedRecommendation); seenUnWantedRecommendations[unwantedRecommendation] = true; } } } if (contentsBySource.contents.recommendations) { for (const r of contentsBySource.contents.recommendations) { const extensionId = r.toLowerCase(); if (invalidExtensions.indexOf(extensionId) === -1) { let recommendation = this._allWorkspaceRecommendedExtensions.filter(r => r.extensionId === extensionId)[0]; if (!recommendation) { recommendation = { extensionId, sources: [] }; this._allWorkspaceRecommendedExtensions.push(recommendation); } if (recommendation.sources.indexOf(contentsBySource.source) === -1) { recommendation.sources.push(contentsBySource.source); } } } } } this._allIgnoredRecommendations = distinct([...this._globallyIgnoredRecommendations, ...this._workspaceIgnoredRecommendations]); })); } /** * Parse all extensions.json files, fetch workspace recommendations */ private fetchExtensionRecommendationContents(): Promise<{ contents: IExtensionsConfigContent, source: ExtensionRecommendationSource }[]> { const workspace = this.contextService.getWorkspace(); return Promise.all<{ contents: IExtensionsConfigContent, source: ExtensionRecommendationSource } | null>([ this.resolveWorkspaceExtensionConfig(workspace).then(contents => contents ? { contents, source: workspace } : null), ...workspace.folders.map(workspaceFolder => this.resolveWorkspaceFolderExtensionConfig(workspaceFolder).then(contents => contents ? { contents, source: workspaceFolder } : null)) ]).then(contents => coalesce(contents)); } /** * Parse the extensions.json file for given workspace and return the recommendations */ private resolveWorkspaceExtensionConfig(workspace: IWorkspace): Promise<IExtensionsConfigContent | null> { if (!workspace.configuration) { return Promise.resolve(null); } return Promise.resolve(this.fileService.readFile(workspace.configuration) .then(content => <IExtensionsConfigContent>(json.parse(content.value.toString())['extensions']), err => null)); } /** * Parse the extensions.json files for given workspace folder and return the recommendations */ private resolveWorkspaceFolderExtensionConfig(workspaceFolder: IWorkspaceFolder): Promise<IExtensionsConfigContent | null> { const extensionsJsonUri = workspaceFolder.toResource(EXTENSIONS_CONFIG); return Promise.resolve(this.fileService.resolve(extensionsJsonUri) .then(() => this.fileService.readFile(extensionsJsonUri)) .then(content => <IExtensionsConfigContent>json.parse(content.value.toString()), err => null)); } /** * Validate the extensions.json file contents using regex and querying the gallery */ private async validateExtensions(contents: IExtensionsConfigContent[]): Promise<{ invalidExtensions: string[], message: string }> { const extensionsContent: IExtensionsConfigContent = { recommendations: distinct(flatten(contents.map(content => content.recommendations || []))), unwantedRecommendations: distinct(flatten(contents.map(content => content.unwantedRecommendations || []))) }; const regEx = new RegExp(EXTENSION_IDENTIFIER_PATTERN); const invalidExtensions: string[] = []; let message = ''; const regexFilter = (ids: string[]) => { return ids.filter((element, position) => { if (ids.indexOf(element) !== position) { // This is a duplicate entry, it doesn't hurt anybody // but it shouldn't be sent in the gallery query return false; } else if (!regEx.test(element)) { invalidExtensions.push(element.toLowerCase()); message += `${element} (bad format) Expected: <provider>.<name>\n`; return false; } return true; }); }; const filteredWanted = regexFilter(extensionsContent.recommendations || []).map(x => x.toLowerCase()); if (filteredWanted.length) { try { let validRecommendations = (await this._galleryService.query({ names: filteredWanted, pageSize: filteredWanted.length }, CancellationToken.None)).firstPage .map(extension => extension.identifier.id.toLowerCase()); if (validRecommendations.length !== filteredWanted.length) { filteredWanted.forEach(element => { if (validRecommendations.indexOf(element.toLowerCase()) === -1) { invalidExtensions.push(element.toLowerCase()); message += `${element} (not found in marketplace)\n`; } }); } } catch (e) { console.warn('Error querying extensions gallery', e); } } return { invalidExtensions, message }; } private onWorkspaceFoldersChanged(event: IWorkspaceFoldersChangeEvent): void { if (event.added.length) { const oldWorkspaceRecommended = this._allWorkspaceRecommendedExtensions; this.getWorkspaceRecommendations() .then(currentWorkspaceRecommended => { // Suggest only if at least one of the newly added recommendations was not suggested before if (currentWorkspaceRecommended.some(current => oldWorkspaceRecommended.every(old => current.extensionId !== old.extensionId))) { this.promptWorkspaceRecommendations(); } }); } this._dynamicWorkspaceRecommendations = []; } /** * Prompt the user to install workspace recommendations if there are any not already installed */ private promptWorkspaceRecommendations(): void { const storageKey = 'extensionsAssistant/workspaceRecommendationsIgnore'; const config = this.configurationService.getValue<IExtensionsConfiguration>(ConfigurationKey); const filteredRecs = this._allWorkspaceRecommendedExtensions.filter(rec => this.isExtensionAllowedToBeRecommended(rec.extensionId)); if (filteredRecs.length === 0 || config.ignoreRecommendations || config.showRecommendationsOnlyOnDemand || this.storageService.getBoolean(storageKey, StorageScope.WORKSPACE, false)) { return; } this.extensionsService.getInstalled(ExtensionType.User).then(local => { local = local.filter(l => this.extensionEnablementService.getEnablementState(l) !== EnablementState.DisabledByExtensionKind); // Filter extensions disabled by kind const recommendations = filteredRecs.filter(({ extensionId }) => local.every(local => !areSameExtensions({ id: extensionId }, local.identifier))); if (!recommendations.length) { return Promise.resolve(undefined); } return new Promise<void>(c => { this.notificationService.prompt( Severity.Info, localize('workspaceRecommended', "This workspace has extension recommendations."), [{ label: localize('installAll', "Install All"), run: () => { /* __GDPR__ "extensionWorkspaceRecommendations:popup" : { "userReaction" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" } } */ this.telemetryService.publicLog('extensionWorkspaceRecommendations:popup', { userReaction: 'install' }); const installAllAction = this.instantiationService.createInstance(InstallWorkspaceRecommendedExtensionsAction, InstallWorkspaceRecommendedExtensionsAction.ID, localize('installAll', "Install All"), recommendations); installAllAction.run(); installAllAction.dispose(); c(undefined); } }, { label: localize('showRecommendations', "Show Recommendations"), run: () => { /* __GDPR__ "extensionWorkspaceRecommendations:popup" : { "userReaction" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" } } */ this.telemetryService.publicLog('extensionWorkspaceRecommendations:popup', { userReaction: 'show' }); const showAction = this.instantiationService.createInstance(ShowRecommendedExtensionsAction, ShowRecommendedExtensionsAction.ID, localize('showRecommendations', "Show Recommendations")); showAction.run(); showAction.dispose(); c(undefined); } }, { label: choiceNever, isSecondary: true, run: () => { /* __GDPR__ "extensionWorkspaceRecommendations:popup" : { "userReaction" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" } } */ this.telemetryService.publicLog('extensionWorkspaceRecommendations:popup', { userReaction: 'neverShowAgain' }); this.storageService.store(storageKey, true, StorageScope.WORKSPACE); c(undefined); } }], { sticky: true, onCancel: () => { /* __GDPR__ "extensionWorkspaceRecommendations:popup" : { "userReaction" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" } } */ this.telemetryService.publicLog('extensionWorkspaceRecommendations:popup', { userReaction: 'cancelled' }); c(undefined); } } ); }); }); } //#endregion //#region important exe based extension private async promptForImportantExeBasedExtension(): Promise<boolean> { let recommendationsToSuggest = Object.keys(this._importantExeBasedRecommendations); const installed = await this.extensionManagementService.getInstalled(ExtensionType.User); recommendationsToSuggest = this.filterInstalled(recommendationsToSuggest, installed, (extensionId) => { const tip = this._importantExeBasedRecommendations[extensionId]; /* __GDPR__ "exeExtensionRecommendations:alreadyInstalled" : { "extensionId": { "classification": "PublicNonPersonalData", "purpose": "FeatureInsight" }, "exeName": { "classification": "PublicNonPersonalData", "purpose": "FeatureInsight" } } */ this.telemetryService.publicLog('exeExtensionRecommendations:alreadyInstalled', { extensionId, exeName: basename(tip.windowsPath!) }); }); if (recommendationsToSuggest.length === 0) { return false; } const storageKey = 'extensionsAssistant/workspaceRecommendationsIgnore'; const config = this.configurationService.getValue<IExtensionsConfiguration>(ConfigurationKey); if (config.ignoreRecommendations || config.showRecommendationsOnlyOnDemand || this.storageService.getBoolean(storageKey, StorageScope.WORKSPACE, false)) { return false; } recommendationsToSuggest = this.filterIgnoredOrNotAllowed(recommendationsToSuggest); if (recommendationsToSuggest.length === 0) { return false; } const extensionId = recommendationsToSuggest[0]; const tip = this._importantExeBasedRecommendations[extensionId]; const message = localize('exeRecommended', "The '{0}' extension is recommended as you have {1} installed on your system.", tip.friendlyName!, tip.exeFriendlyName || basename(tip.windowsPath!)); this.notificationService.prompt(Severity.Info, message, [{ label: localize('install', 'Install'), run: () => { /* __GDPR__ "exeExtensionRecommendations:popup" : { "userReaction" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "extensionId": { "classification": "PublicNonPersonalData", "purpose": "FeatureInsight" } } */ this.telemetryService.publicLog('exeExtensionRecommendations:popup', { userReaction: 'install', extensionId }); this.instantiationService.createInstance(InstallRecommendedExtensionAction, extensionId).run(); } }, { label: localize('showRecommendations', "Show Recommendations"), run: () => { /* __GDPR__ "exeExtensionRecommendations:popup" : { "userReaction" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "extensionId": { "classification": "PublicNonPersonalData", "purpose": "FeatureInsight" } } */ this.telemetryService.publicLog('exeExtensionRecommendations:popup', { userReaction: 'show', extensionId }); const recommendationsAction = this.instantiationService.createInstance(ShowRecommendedExtensionsAction, ShowRecommendedExtensionsAction.ID, localize('showRecommendations', "Show Recommendations")); recommendationsAction.run(); recommendationsAction.dispose(); } }, { label: choiceNever, isSecondary: true, run: () => { this.addToImportantRecommendationsIgnore(extensionId); /* __GDPR__ "exeExtensionRecommendations:popup" : { "userReaction" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "extensionId": { "classification": "PublicNonPersonalData", "purpose": "FeatureInsight" } } */ this.telemetryService.publicLog('exeExtensionRecommendations:popup', { userReaction: 'neverShowAgain', extensionId }); this.notificationService.prompt( Severity.Info, localize('ignoreExtensionRecommendations', "Do you want to ignore all extension recommendations?"), [{ label: localize('ignoreAll', "Yes, Ignore All"), run: () => this.setIgnoreRecommendationsConfig(true) }, { label: localize('no', "No"), run: () => this.setIgnoreRecommendationsConfig(false) }] ); } }], { sticky: true, onCancel: () => { /* __GDPR__ "exeExtensionRecommendations:popup" : { "userReaction" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "extensionId": { "classification": "PublicNonPersonalData", "purpose": "FeatureInsight" } } */ this.telemetryService.publicLog('exeExtensionRecommendations:popup', { userReaction: 'cancelled', extensionId }); } } ); return true; } //#region fileBasedRecommendations getFileBasedRecommendations(): IExtensionRecommendation[] { return Object.keys(this._fileBasedRecommendations) .sort((a, b) => { if (this._fileBasedRecommendations[a].recommendedTime === this._fileBasedRecommendations[b].recommendedTime) { if (!this.productService.extensionImportantTips || caseInsensitiveGet(this.productService.extensionImportantTips, a)) { return -1; } if (caseInsensitiveGet(this.productService.extensionImportantTips, b)) { return 1; } } return this._fileBasedRecommendations[a].recommendedTime > this._fileBasedRecommendations[b].recommendedTime ? -1 : 1; }) .filter(extensionId => this.isExtensionAllowedToBeRecommended(extensionId)) .map(extensionId => (<IExtensionRecommendation>{ extensionId, sources: this._fileBasedRecommendations[extensionId].sources })); } /** * Parse all file based recommendations from this.productService.extensionTips * Retire existing recommendations if they are older than a week or are not part of this.productService.extensionTips anymore */ private fetchFileBasedRecommendations() { const extensionTips = this.productService.extensionTips; if (!extensionTips) { return; } // group ids by pattern, like {**/*.md} -> [ext.foo1, ext.bar2] this._availableRecommendations = Object.create(null); forEach(extensionTips, entry => { let { key: id, value: pattern } = entry; let ids = this._availableRecommendations[pattern]; if (!ids) { this._availableRecommendations[pattern] = [id.toLowerCase()]; } else { ids.push(id.toLowerCase()); } }); if (this.productService.extensionImportantTips) { forEach(this.productService.extensionImportantTips, entry => { let { key: id, value } = entry; const { pattern } = value; let ids = this._availableRecommendations[pattern]; if (!ids) { this._availableRecommendations[pattern] = [id.toLowerCase()]; } else { ids.push(id.toLowerCase()); } }); } const allRecommendations: string[] = flatten((Object.keys(this._availableRecommendations).map(key => this._availableRecommendations[key]))); // retrieve ids of previous recommendations const storedRecommendationsJson = JSON.parse(this.storageService.get('extensionsAssistant/recommendations', StorageScope.GLOBAL, '[]')); if (Array.isArray<string>(storedRecommendationsJson)) { for (let id of <string[]>storedRecommendationsJson) { if (allRecommendations.indexOf(id) > -1) { this._fileBasedRecommendations[id.toLowerCase()] = { recommendedTime: Date.now(), sources: ['cached'] }; } } } else { const now = Date.now(); forEach(storedRecommendationsJson, entry => { if (typeof entry.value === 'number') { const diff = (now - entry.value) / milliSecondsInADay; if (diff <= 7 && allRecommendations.indexOf(entry.key) > -1) { this._fileBasedRecommendations[entry.key.toLowerCase()] = { recommendedTime: entry.value, sources: ['cached'] }; } } }); } } /** * Prompt the user to either install the recommended extension for the file type in the current editor model * or prompt to search the marketplace if it has extensions that can support the file type */ private promptFiletypeBasedRecommendations(model: ITextModel): void { const uri = model.uri; if (!uri || !this.fileService.canHandleResource(uri)) { return; } let fileExtension = extname(uri); if (fileExtension) { if (processedFileExtensions.indexOf(fileExtension) > -1) { return; } processedFileExtensions.push(fileExtension); } // re-schedule this bit of the operation to be off the critical path - in case glob-match is slow setImmediate(async () => { let recommendationsToSuggest: string[] = []; const now = Date.now(); forEach(this._availableRecommendations, entry => { let { key: pattern, value: ids } = entry; if (match(pattern, model.uri.toString())) { for (let id of ids) { if (this.productService.extensionImportantTips && caseInsensitiveGet(this.productService.extensionImportantTips, id)) { recommendationsToSuggest.push(id); } const filedBasedRecommendation = this._fileBasedRecommendations[id.toLowerCase()] || { recommendedTime: now, sources: [] }; filedBasedRecommendation.recommendedTime = now; if (!filedBasedRecommendation.sources.some(s => s instanceof URI && s.toString() === model.uri.toString())) { filedBasedRecommendation.sources.push(model.uri); } this._fileBasedRecommendations[id.toLowerCase()] = filedBasedRecommendation; } } }); this.storageService.store( 'extensionsAssistant/recommendations', JSON.stringify(Object.keys(this._fileBasedRecommendations).reduce((result, key) => { result[key] = this._fileBasedRecommendations[key].recommendedTime; return result; }, {} as { [key: string]: any })), StorageScope.GLOBAL ); const config = this.configurationService.getValue<IExtensionsConfiguration>(ConfigurationKey); if (config.ignoreRecommendations || config.showRecommendationsOnlyOnDemand) { return; } const installed = await this.extensionManagementService.getInstalled(ExtensionType.User); if (await this.promptRecommendedExtensionForFileType(recommendationsToSuggest, installed)) { return; } if (fileExtension) { fileExtension = fileExtension.substr(1); // Strip the dot } if (!fileExtension) { return; } await this.extensionService.whenInstalledExtensionsRegistered(); const mimeTypes = guessMimeTypes(uri); if (mimeTypes.length !== 1 || mimeTypes[0] !== MIME_UNKNOWN) { return; } this.promptRecommendedExtensionForFileExtension(fileExtension, installed); }); } private async promptRecommendedExtensionForFileType(recommendationsToSuggest: string[], installed: ILocalExtension[]): Promise<boolean> { recommendationsToSuggest = this.filterIgnoredOrNotAllowed(recommendationsToSuggest); if (recommendationsToSuggest.length === 0) { return false; } recommendationsToSuggest = this.filterInstalled(recommendationsToSuggest, installed); if (recommendationsToSuggest.length === 0) { return false; } const id = recommendationsToSuggest[0]; const entry = this.productService.extensionImportantTips ? caseInsensitiveGet(this.productService.extensionImportantTips, id) : undefined; if (!entry) { return false; } const name = entry.name; let message = localize('reallyRecommended2', "The '{0}' extension is recommended for this file type.", name); if (entry.isExtensionPack) { message = localize('reallyRecommendedExtensionPack', "The '{0}' extension pack is recommended for this file type.", name); } this.notificationService.prompt(Severity.Info, message, [{ label: localize('install', 'Install'), run: () => { /* __GDPR__ "extensionRecommendations:popup" : { "userReaction" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "extensionId": { "classification": "PublicNonPersonalData", "purpose": "FeatureInsight" } } */ this.telemetryService.publicLog('extensionRecommendations:popup', { userReaction: 'install', extensionId: name }); this.instantiationService.createInstance(InstallRecommendedExtensionAction, id).run(); } }, { label: localize('showRecommendations', "Show Recommendations"), run: () => { /* __GDPR__ "extensionRecommendations:popup" : { "userReaction" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "extensionId": { "classification": "PublicNonPersonalData", "purpose": "FeatureInsight" } } */ this.telemetryService.publicLog('extensionRecommendations:popup', { userReaction: 'show', extensionId: name }); const recommendationsAction = this.instantiationService.createInstance(ShowRecommendedExtensionsAction, ShowRecommendedExtensionsAction.ID, localize('showRecommendations', "Show Recommendations")); recommendationsAction.run(); recommendationsAction.dispose(); } }, { label: choiceNever, isSecondary: true, run: () => { this.addToImportantRecommendationsIgnore(id); /* __GDPR__ "extensionRecommendations:popup" : { "userReaction" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "extensionId": { "classification": "PublicNonPersonalData", "purpose": "FeatureInsight" } } */ this.telemetryService.publicLog('extensionRecommendations:popup', { userReaction: 'neverShowAgain', extensionId: name }); this.notificationService.prompt( Severity.Info, localize('ignoreExtensionRecommendations', "Do you want to ignore all extension recommendations?"), [{ label: localize('ignoreAll', "Yes, Ignore All"), run: () => this.setIgnoreRecommendationsConfig(true) }, { label: localize('no', "No"), run: () => this.setIgnoreRecommendationsConfig(false) }] ); } }], { sticky: true, onCancel: () => { /* __GDPR__ "extensionRecommendations:popup" : { "userReaction" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "extensionId": { "classification": "PublicNonPersonalData", "purpose": "FeatureInsight" } } */ this.telemetryService.publicLog('extensionRecommendations:popup', { userReaction: 'cancelled', extensionId: name }); } } ); return true; } private async promptRecommendedExtensionForFileExtension(fileExtension: string, installed: ILocalExtension[]): Promise<void> { const fileExtensionSuggestionIgnoreList = <string[]>JSON.parse(this.storageService.get('extensionsAssistant/fileExtensionsSuggestionIgnore', StorageScope.GLOBAL, '[]')); if (fileExtensionSuggestionIgnoreList.indexOf(fileExtension) > -1) { return; } const text = `ext:${fileExtension}`; const pager = await this.extensionWorkbenchService.queryGallery({ text, pageSize: 100 }, CancellationToken.None); if (pager.firstPage.length === 0) { return; } const installedExtensionsIds = installed.reduce((result, i) => { result.add(i.identifier.id.toLowerCase()); return result; }, new Set<string>()); if (pager.firstPage.some(e => installedExtensionsIds.has(e.identifier.id.toLowerCase()))) { return; } this.notificationService.prompt( Severity.Info, localize('showLanguageExtensions', "The Marketplace has extensions that can help with '.{0}' files", fileExtension), [{ label: searchMarketplace, run: () => { /* __GDPR__ "fileExtensionSuggestion:popup" : { "userReaction" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "fileExtension": { "classification": "PublicNonPersonalData", "purpose": "FeatureInsight" } } */ this.telemetryService.publicLog('fileExtensionSuggestion:popup', { userReaction: 'ok', fileExtension: fileExtension }); this.viewletService.openViewlet('workbench.view.extensions', true) .then(viewlet => viewlet as IExtensionsViewlet) .then(viewlet => { viewlet.search(`ext:${fileExtension}`); viewlet.focus(); }); } }, { label: localize('dontShowAgainExtension', "Don't Show Again for '.{0}' files", fileExtension), run: () => { fileExtensionSuggestionIgnoreList.push(fileExtension); this.storageService.store( 'extensionsAssistant/fileExtensionsSuggestionIgnore', JSON.stringify(fileExtensionSuggestionIgnoreList), StorageScope.GLOBAL ); /* __GDPR__ "fileExtensionSuggestion:popup" : { "userReaction" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "fileExtension": { "classification": "PublicNonPersonalData", "purpose": "FeatureInsight" } } */ this.telemetryService.publicLog('fileExtensionSuggestion:popup', { userReaction: 'neverShowAgain', fileExtension: fileExtension }); } }], { sticky: true, onCancel: () => { /* __GDPR__ "fileExtensionSuggestion:popup" : { "userReaction" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "fileExtension": { "classification": "PublicNonPersonalData", "purpose": "FeatureInsight" } } */ this.telemetryService.publicLog('fileExtensionSuggestion:popup', { userReaction: 'cancelled', fileExtension: fileExtension }); } } ); } private filterIgnoredOrNotAllowed(recommendationsToSuggest: string[]): string[] { const importantRecommendationsIgnoreList = <string[]>JSON.parse(this.storageService.get('extensionsAssistant/importantRecommendationsIgnore', StorageScope.GLOBAL, '[]')); return recommendationsToSuggest.filter(id => { if (importantRecommendationsIgnoreList.indexOf(id) !== -1) { return false; } if (!this.isExtensionAllowedToBeRecommended(id)) { return false; } return true; }); } private filterInstalled(recommendationsToSuggest: string[], installed: ILocalExtension[], onAlreadyInstalled?: (id: string) => void): string[] { const installedExtensionsIds = installed.reduce((result, i) => { result.add(i.identifier.id.toLowerCase()); return result; }, new Set<string>()); return recommendationsToSuggest.filter(id => { if (installedExtensionsIds.has(id.toLowerCase())) { if (onAlreadyInstalled) { onAlreadyInstalled(id); } return false; } return true; }); } private addToImportantRecommendationsIgnore(id: string) { const importantRecommendationsIgnoreList = <string[]>JSON.parse(this.storageService.get('extensionsAssistant/importantRecommendationsIgnore', StorageScope.GLOBAL, '[]')); importantRecommendationsIgnoreList.push(id); this.storageService.store( 'extensionsAssistant/importantRecommendationsIgnore', JSON.stringify(importantRecommendationsIgnoreList), StorageScope.GLOBAL ); } private setIgnoreRecommendationsConfig(configVal: boolean) { this.configurationService.updateValue('extensions.ignoreRecommendations', configVal, ConfigurationTarget.USER); if (configVal) { const ignoreWorkspaceRecommendationsStorageKey = 'extensionsAssistant/workspaceRecommendationsIgnore'; this.storageService.store(ignoreWorkspaceRecommendationsStorageKey, true, StorageScope.WORKSPACE); } } //#endregion //#region otherRecommendations getOtherRecommendations(): Promise<IExtensionRecommendation[]> { return this.fetchProactiveRecommendations().then(() => { const others = distinct([ ...Object.keys(this._exeBasedRecommendations), ...this._dynamicWorkspaceRecommendations, ...Object.keys(this._experimentalRecommendations), ]).filter(extensionId => this.isExtensionAllowedToBeRecommended(extensionId)); shuffle(others, this.sessionSeed); return others.map(extensionId => { const sources: ExtensionRecommendationSource[] = []; if (this._exeBasedRecommendations[extensionId]) { sources.push('executable'); } if (this._dynamicWorkspaceRecommendations.indexOf(extensionId) !== -1) { sources.push('dynamic'); } return (<IExtensionRecommendation>{ extensionId, sources }); }); }); } private fetchProactiveRecommendations(calledDuringStartup?: boolean): Promise<void> { let fetchPromise = Promise.resolve<any>(undefined); if (!this.proactiveRecommendationsFetched) { this.proactiveRecommendationsFetched = true; // Executable based recommendations carry out a lot of file stats, delay the resolution so that the startup is not affected // 10 sec for regular extensions // 3 secs for important const importantExeBasedRecommendations = timeout(calledDuringStartup ? 3000 : 0).then(_ => this.fetchExecutableRecommendations(true)); importantExeBasedRecommendations.then(_ => this.promptForImportantExeBasedExtension()); fetchPromise = timeout(calledDuringStartup ? 10000 : 0).then(_ => Promise.all([this.fetchDynamicWorkspaceRecommendations(), this.fetchExecutableRecommendations(false), importantExeBasedRecommendations])); } return fetchPromise; } /** * If user has any of the tools listed in this.productService.exeBasedExtensionTips, fetch corresponding recommendations */ private async fetchExecutableRecommendations(important: boolean): Promise<void> { if (isWeb || !this.productService.exeBasedExtensionTips) { return; } const foundExecutables: Set<string> = new Set<string>(); const findExecutable = (exeName: string, tip: IExeBasedExtensionTip, path: string) => { return this.fileService.exists(URI.file(path)).then(exists => { if (exists && !foundExecutables.has(exeName)) { foundExecutables.add(exeName); (tip['recommendations'] || []).forEach(extensionId => { if (tip.friendlyName) { if (important) { this._importantExeBasedRecommendations[extensionId.toLowerCase()] = tip; } this._exeBasedRecommendations[extensionId.toLowerCase()] = tip; } }); } }); }; const promises: Promise<void>[] = []; // Loop through recommended extensions forEach(this.productService.exeBasedExtensionTips, entry => { if (typeof entry.value !== 'object' || !Array.isArray(entry.value['recommendations'])) { return; } if (important !== !!entry.value.important) { return; } const exeName = entry.key; if (platform === 'win32') { let windowsPath = entry.value['windowsPath']; if (!windowsPath || typeof windowsPath !== 'string') { return; } windowsPath = windowsPath.replace('%USERPROFILE%', processEnv['USERPROFILE']!) .replace('%ProgramFiles(x86)%', processEnv['ProgramFiles(x86)']!) .replace('%ProgramFiles%', processEnv['ProgramFiles']!) .replace('%APPDATA%', processEnv['APPDATA']!) .replace('%WINDIR%', processEnv['WINDIR']!); promises.push(findExecutable(exeName, entry.value, windowsPath)); } else { promises.push(findExecutable(exeName, entry.value, join('/usr/local/bin', exeName))); promises.push(findExecutable(exeName, entry.value, join(this.environmentService.userHome, exeName))); } }); await Promise.all(promises); } /** * Fetch extensions used by others on the same workspace as recommendations from cache */ private fetchCachedDynamicWorkspaceRecommendations() { if (this.contextService.getWorkbenchState() !== WorkbenchState.FOLDER) { return; } const storageKey = 'extensionsAssistant/dynamicWorkspaceRecommendations'; let storedRecommendationsJson: { [key: string]: any } = {}; try { storedRecommendationsJson = JSON.parse(this.storageService.get(storageKey, StorageScope.WORKSPACE, '{}')); } catch (e) { this.storageService.remove(storageKey, StorageScope.WORKSPACE); } if (Array.isArray(storedRecommendationsJson['recommendations']) && isNumber(storedRecommendationsJson['timestamp']) && storedRecommendationsJson['timestamp'] > 0 && (Date.now() - storedRecommendationsJson['timestamp']) / milliSecondsInADay < 14) { this._dynamicWorkspaceRecommendations = storedRecommendationsJson['recommendations']; /* __GDPR__ "dynamicWorkspaceRecommendations" : { "count" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "cache" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true } } */ this.telemetryService.publicLog('dynamicWorkspaceRecommendations', { count: this._dynamicWorkspaceRecommendations.length, cache: 1 }); } } /** * Fetch extensions used by others on the same workspace as recommendations from recommendation service */ private fetchDynamicWorkspaceRecommendations(): Promise<void> { if (this.contextService.getWorkbenchState() !== WorkbenchState.FOLDER || !this.fileService.canHandleResource(this.contextService.getWorkspace().folders[0].uri) || this._dynamicWorkspaceRecommendations.length || !this._extensionsRecommendationsUrl) { return Promise.resolve(undefined); } const storageKey = 'extensionsAssistant/dynamicWorkspaceRecommendations'; const workspaceUri = this.contextService.getWorkspace().folders[0].uri; return Promise.all([this.workspaceTagsService.getHashedRemotesFromUri(workspaceUri, false), this.workspaceTagsService.getHashedRemotesFromUri(workspaceUri, true)]).then(([hashedRemotes1, hashedRemotes2]) => { const hashedRemotes = (hashedRemotes1 || []).concat(hashedRemotes2 || []); if (!hashedRemotes.length) { return undefined; } return this.requestService.request({ type: 'GET', url: this._extensionsRecommendationsUrl }, CancellationToken.None).then(context => { if (context.res.statusCode !== 200) { return Promise.resolve(undefined); } return asJson(context).then((result: { [key: string]: any } | null) => { if (!result) { return; } const allRecommendations: IDynamicWorkspaceRecommendations[] = Array.isArray(result['workspaceRecommendations']) ? result['workspaceRecommendations'] : []; if (!allRecommendations.length) { return; } let foundRemote = false; for (let i = 0; i < hashedRemotes.length && !foundRemote; i++) { for (let j = 0; j < allRecommendations.length && !foundRemote; j++) { if (Array.isArray(allRecommendations[j].remoteSet) && allRecommendations[j].remoteSet.indexOf(hashedRemotes[i]) > -1) { foundRemote = true; this._dynamicWorkspaceRecommendations = allRecommendations[j].recommendations.filter(id => this.isExtensionAllowedToBeRecommended(id)) || []; this.storageService.store(storageKey, JSON.stringify({ recommendations: this._dynamicWorkspaceRecommendations, timestamp: Date.now() }), StorageScope.WORKSPACE); /* __GDPR__ "dynamicWorkspaceRecommendations" : { "count" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "cache" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true } } */ this.telemetryService.publicLog('dynamicWorkspaceRecommendations', { count: this._dynamicWorkspaceRecommendations.length, cache: 0 }); } } } }); }); }); } /** * Fetch extension recommendations from currently running experiments */ private fetchExperimentalRecommendations() { this.experimentService.getExperimentsByType(ExperimentActionType.AddToRecommendations).then(experiments => { (experiments || []).forEach(experiment => { const action = experiment.action; if (action && experiment.state === ExperimentState.Run && action.properties && Array.isArray(action.properties.recommendations) && action.properties.recommendationReason) { action.properties.recommendations.forEach((id: string) => { this._experimentalRecommendations[id] = action.properties.recommendationReason; }); } }); }); } //#endregion private isExtensionAllowedToBeRecommended(id: string): boolean { return this._allIgnoredRecommendations.indexOf(id.toLowerCase()) === -1; } }
src/vs/workbench/contrib/extensions/browser/extensionTipsService.ts
0
https://github.com/microsoft/vscode/commit/88e80b9a18b2cc3de0ca3a02977c3e2d4b088a60
[ 0.001483364263549447, 0.00019170762971043587, 0.0001618046371731907, 0.00016912877617869526, 0.0001554834161652252 ]
{ "id": 2, "code_window": [ "\t\t\tawait this.runTask(session.root, session.configuration.postDebugTask);\n", "\t\t\treturn this.runTaskAndCheckErrors(session.root, session.configuration.preLaunchTask);\n", "\t\t};\n", "\n", "\t\tif (isExtensionHostDebugging(session.configuration)) {\n", "\t\t\tconst taskResult = await runTasks();\n", "\t\t\tif (taskResult === TaskRunResult.Success) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ "\t\tconst extensionDebugSession = getExtensionHostDebugSession(session);\n", "\t\tif (extensionDebugSession) {\n" ], "file_path": "src/vs/workbench/contrib/debug/browser/debugService.ts", "type": "replace", "edit_start_line_idx": 592 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as nls from 'vs/nls'; import { Event, Emitter } from 'vs/base/common/event'; import { URI as uri } from 'vs/base/common/uri'; import { first, distinct } from 'vs/base/common/arrays'; import * as errors from 'vs/base/common/errors'; import severity from 'vs/base/common/severity'; import * as aria from 'vs/base/browser/ui/aria/aria'; import { IContextKeyService, IContextKey } from 'vs/platform/contextkey/common/contextkey'; import { IMarkerService } from 'vs/platform/markers/common/markers'; import { ILifecycleService } from 'vs/platform/lifecycle/common/lifecycle'; import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { FileChangesEvent, FileChangeType, IFileService } from 'vs/platform/files/common/files'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage'; import { DebugModel, ExceptionBreakpoint, FunctionBreakpoint, Breakpoint, Expression, DataBreakpoint } from 'vs/workbench/contrib/debug/common/debugModel'; import { ViewModel } from 'vs/workbench/contrib/debug/common/debugViewModel'; import * as debugactions from 'vs/workbench/contrib/debug/browser/debugActions'; import { ConfigurationManager } from 'vs/workbench/contrib/debug/browser/debugConfigurationManager'; import Constants from 'vs/workbench/contrib/markers/browser/constants'; import { ITaskService, ITaskSummary } from 'vs/workbench/contrib/tasks/common/taskService'; import { VIEWLET_ID as EXPLORER_VIEWLET_ID } from 'vs/workbench/contrib/files/common/files'; import { IViewletService } from 'vs/workbench/services/viewlet/browser/viewlet'; import { IPanelService } from 'vs/workbench/services/panel/common/panelService'; import { IWorkbenchLayoutService, Parts } from 'vs/workbench/services/layout/browser/layoutService'; import { ITextFileService } from 'vs/workbench/services/textfile/common/textfiles'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IWorkspaceContextService, WorkbenchState, IWorkspaceFolder, IWorkspace } from 'vs/platform/workspace/common/workspace'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { parse, getFirstFrame } from 'vs/base/common/console'; import { TaskEvent, TaskEventKind, TaskIdentifier } from 'vs/workbench/contrib/tasks/common/tasks'; import { IDialogService } from 'vs/platform/dialogs/common/dialogs'; import { INotificationService } from 'vs/platform/notification/common/notification'; import { IAction } from 'vs/base/common/actions'; import { deepClone, equals } from 'vs/base/common/objects'; import { DebugSession } from 'vs/workbench/contrib/debug/browser/debugSession'; import { dispose, IDisposable } from 'vs/base/common/lifecycle'; import { IDebugService, State, IDebugSession, CONTEXT_DEBUG_TYPE, CONTEXT_DEBUG_STATE, CONTEXT_IN_DEBUG_MODE, IThread, IDebugConfiguration, VIEWLET_ID, REPL_ID, IConfig, ILaunch, IViewModel, IConfigurationManager, IDebugModel, IEnablement, IBreakpoint, IBreakpointData, ICompound, IGlobalConfig, IStackFrame, AdapterEndEvent, getStateLabel, IDebugSessionOptions, CONTEXT_DEBUG_UX } from 'vs/workbench/contrib/debug/common/debug'; import { isExtensionHostDebugging } from 'vs/workbench/contrib/debug/common/debugUtils'; import { isErrorWithActions, createErrorWithActions } from 'vs/base/common/errorsWithActions'; import { RunOnceScheduler } from 'vs/base/common/async'; import { IExtensionHostDebugService } from 'vs/platform/debug/common/extensionHostDebug'; import { isCodeEditor } from 'vs/editor/browser/editorBrowser'; import { CancellationTokenSource } from 'vs/base/common/cancellation'; import { withUndefinedAsNull } from 'vs/base/common/types'; const DEBUG_BREAKPOINTS_KEY = 'debug.breakpoint'; const DEBUG_FUNCTION_BREAKPOINTS_KEY = 'debug.functionbreakpoint'; const DEBUG_DATA_BREAKPOINTS_KEY = 'debug.databreakpoint'; const DEBUG_EXCEPTION_BREAKPOINTS_KEY = 'debug.exceptionbreakpoint'; const DEBUG_WATCH_EXPRESSIONS_KEY = 'debug.watchexpressions'; function once(match: (e: TaskEvent) => boolean, event: Event<TaskEvent>): Event<TaskEvent> { return (listener, thisArgs = null, disposables?) => { const result = event(e => { if (match(e)) { result.dispose(); return listener.call(thisArgs, e); } }, null, disposables); return result; }; } const enum TaskRunResult { Failure, Success } export class DebugService implements IDebugService { _serviceBrand: undefined; private readonly _onDidChangeState: Emitter<State>; private readonly _onDidNewSession: Emitter<IDebugSession>; private readonly _onWillNewSession: Emitter<IDebugSession>; private readonly _onDidEndSession: Emitter<IDebugSession>; private model: DebugModel; private viewModel: ViewModel; private configurationManager: ConfigurationManager; private toDispose: IDisposable[]; private debugType: IContextKey<string>; private debugState: IContextKey<string>; private inDebugMode: IContextKey<boolean>; private debugUx: IContextKey<string>; private breakpointsToSendOnResourceSaved: Set<string>; private initializing = false; private previousState: State | undefined; private initCancellationToken: CancellationTokenSource | undefined; constructor( @IStorageService private readonly storageService: IStorageService, @IEditorService private readonly editorService: IEditorService, @ITextFileService private readonly textFileService: ITextFileService, @IViewletService private readonly viewletService: IViewletService, @IPanelService private readonly panelService: IPanelService, @INotificationService private readonly notificationService: INotificationService, @IDialogService private readonly dialogService: IDialogService, @IWorkbenchLayoutService private readonly layoutService: IWorkbenchLayoutService, @ITelemetryService private readonly telemetryService: ITelemetryService, @IWorkspaceContextService private readonly contextService: IWorkspaceContextService, @IContextKeyService contextKeyService: IContextKeyService, @ILifecycleService private readonly lifecycleService: ILifecycleService, @IInstantiationService private readonly instantiationService: IInstantiationService, @IExtensionService private readonly extensionService: IExtensionService, @IMarkerService private readonly markerService: IMarkerService, @ITaskService private readonly taskService: ITaskService, @IFileService private readonly fileService: IFileService, @IConfigurationService private readonly configurationService: IConfigurationService, @IExtensionHostDebugService private readonly extensionHostDebugService: IExtensionHostDebugService ) { this.toDispose = []; this.breakpointsToSendOnResourceSaved = new Set<string>(); this._onDidChangeState = new Emitter<State>(); this._onDidNewSession = new Emitter<IDebugSession>(); this._onWillNewSession = new Emitter<IDebugSession>(); this._onDidEndSession = new Emitter<IDebugSession>(); this.configurationManager = this.instantiationService.createInstance(ConfigurationManager); this.toDispose.push(this.configurationManager); this.debugType = CONTEXT_DEBUG_TYPE.bindTo(contextKeyService); this.debugState = CONTEXT_DEBUG_STATE.bindTo(contextKeyService); this.inDebugMode = CONTEXT_IN_DEBUG_MODE.bindTo(contextKeyService); this.debugUx = CONTEXT_DEBUG_UX.bindTo(contextKeyService); this.debugUx.set(!!this.configurationManager.selectedConfiguration.name ? 'default' : 'simple'); this.model = new DebugModel(this.loadBreakpoints(), this.loadFunctionBreakpoints(), this.loadExceptionBreakpoints(), this.loadDataBreakpoints(), this.loadWatchExpressions(), this.textFileService); this.toDispose.push(this.model); this.viewModel = new ViewModel(contextKeyService); this.toDispose.push(this.fileService.onFileChanges(e => this.onFileChanges(e))); this.lifecycleService.onShutdown(this.dispose, this); this.toDispose.push(this.extensionHostDebugService.onAttachSession(event => { const session = this.model.getSession(event.sessionId, true); if (session) { // EH was started in debug mode -> attach to it session.configuration.request = 'attach'; session.configuration.port = event.port; session.setSubId(event.subId); this.launchOrAttachToSession(session); } })); this.toDispose.push(this.extensionHostDebugService.onTerminateSession(event => { const session = this.model.getSession(event.sessionId); if (session && session.subId === event.subId) { session.disconnect(); } })); this.toDispose.push(this.extensionHostDebugService.onLogToSession(event => { const session = this.model.getSession(event.sessionId, true); if (session) { // extension logged output -> show it in REPL const sev = event.log.severity === 'warn' ? severity.Warning : event.log.severity === 'error' ? severity.Error : severity.Info; const { args, stack } = parse(event.log); const frame = !!stack ? getFirstFrame(stack) : undefined; session.logToRepl(sev, args, frame); } })); this.toDispose.push(this.viewModel.onDidFocusStackFrame(() => { this.onStateChange(); })); this.toDispose.push(this.viewModel.onDidFocusSession(() => { this.onStateChange(); })); this.toDispose.push(this.configurationManager.onDidSelectConfiguration(() => { this.debugUx.set(!!(this.state !== State.Inactive || this.configurationManager.selectedConfiguration.name) ? 'default' : 'simple'); })); } getModel(): IDebugModel { return this.model; } getViewModel(): IViewModel { return this.viewModel; } getConfigurationManager(): IConfigurationManager { return this.configurationManager; } sourceIsNotAvailable(uri: uri): void { this.model.sourceIsNotAvailable(uri); } dispose(): void { this.toDispose = dispose(this.toDispose); } //---- state management get state(): State { const focusedSession = this.viewModel.focusedSession; if (focusedSession) { return focusedSession.state; } return this.initializing ? State.Initializing : State.Inactive; } private startInitializingState() { if (!this.initializing) { this.initializing = true; this.onStateChange(); } } private endInitializingState() { if (this.initCancellationToken) { this.initCancellationToken.cancel(); this.initCancellationToken = undefined; } if (this.initializing) { this.initializing = false; this.onStateChange(); } } private onStateChange(): void { const state = this.state; if (this.previousState !== state) { this.debugState.set(getStateLabel(state)); this.inDebugMode.set(state !== State.Inactive); // Only show the simple ux if debug is not yet started and if no launch.json exists this.debugUx.set(((state !== State.Inactive && state !== State.Initializing) || this.configurationManager.selectedConfiguration.name) ? 'default' : 'simple'); this.previousState = state; this._onDidChangeState.fire(state); } } get onDidChangeState(): Event<State> { return this._onDidChangeState.event; } get onDidNewSession(): Event<IDebugSession> { return this._onDidNewSession.event; } get onWillNewSession(): Event<IDebugSession> { return this._onWillNewSession.event; } get onDidEndSession(): Event<IDebugSession> { return this._onDidEndSession.event; } //---- life cycle management /** * main entry point * properly manages compounds, checks for errors and handles the initializing state. */ async startDebugging(launch: ILaunch | undefined, configOrName?: IConfig | string, options?: IDebugSessionOptions): Promise<boolean> { this.startInitializingState(); try { // make sure to save all files and that the configuration is up to date await this.extensionService.activateByEvent('onDebug'); await this.editorService.saveAll(); await this.configurationService.reloadConfiguration(launch ? launch.workspace : undefined); await this.extensionService.whenInstalledExtensionsRegistered(); let config: IConfig | undefined; let compound: ICompound | undefined; if (!configOrName) { configOrName = this.configurationManager.selectedConfiguration.name; } if (typeof configOrName === 'string' && launch) { config = launch.getConfiguration(configOrName); compound = launch.getCompound(configOrName); const sessions = this.model.getSessions(); const alreadyRunningMessage = nls.localize('configurationAlreadyRunning', "There is already a debug configuration \"{0}\" running.", configOrName); if (sessions.some(s => s.configuration.name === configOrName && (!launch || !launch.workspace || !s.root || s.root.uri.toString() === launch.workspace.uri.toString()))) { throw new Error(alreadyRunningMessage); } if (compound && compound.configurations && sessions.some(p => compound!.configurations.indexOf(p.configuration.name) !== -1)) { throw new Error(alreadyRunningMessage); } } else if (typeof configOrName !== 'string') { config = configOrName; } if (compound) { // we are starting a compound debug, first do some error checking and than start each configuration in the compound if (!compound.configurations) { throw new Error(nls.localize({ key: 'compoundMustHaveConfigurations', comment: ['compound indicates a "compounds" configuration item', '"configurations" is an attribute and should not be localized'] }, "Compound must have \"configurations\" attribute set in order to start multiple configurations.")); } if (compound.preLaunchTask) { const taskResult = await this.runTaskAndCheckErrors(launch?.workspace || this.contextService.getWorkspace(), compound.preLaunchTask); if (taskResult === TaskRunResult.Failure) { this.endInitializingState(); return false; } } const values = await Promise.all(compound.configurations.map(configData => { const name = typeof configData === 'string' ? configData : configData.name; if (name === compound!.name) { return Promise.resolve(false); } let launchForName: ILaunch | undefined; if (typeof configData === 'string') { const launchesContainingName = this.configurationManager.getLaunches().filter(l => !!l.getConfiguration(name)); if (launchesContainingName.length === 1) { launchForName = launchesContainingName[0]; } else if (launch && launchesContainingName.length > 1 && launchesContainingName.indexOf(launch) >= 0) { // If there are multiple launches containing the configuration give priority to the configuration in the current launch launchForName = launch; } else { throw new Error(launchesContainingName.length === 0 ? nls.localize('noConfigurationNameInWorkspace', "Could not find launch configuration '{0}' in the workspace.", name) : nls.localize('multipleConfigurationNamesInWorkspace', "There are multiple launch configurations '{0}' in the workspace. Use folder name to qualify the configuration.", name)); } } else if (configData.folder) { const launchesMatchingConfigData = this.configurationManager.getLaunches().filter(l => l.workspace && l.workspace.name === configData.folder && !!l.getConfiguration(configData.name)); if (launchesMatchingConfigData.length === 1) { launchForName = launchesMatchingConfigData[0]; } else { throw new Error(nls.localize('noFolderWithName', "Can not find folder with name '{0}' for configuration '{1}' in compound '{2}'.", configData.folder, configData.name, compound!.name)); } } return this.createSession(launchForName, launchForName!.getConfiguration(name), options); })); const result = values.every(success => !!success); // Compound launch is a success only if each configuration launched successfully this.endInitializingState(); return result; } if (configOrName && !config) { const message = !!launch ? nls.localize('configMissing', "Configuration '{0}' is missing in 'launch.json'.", typeof configOrName === 'string' ? configOrName : JSON.stringify(configOrName)) : nls.localize('launchJsonDoesNotExist', "'launch.json' does not exist."); throw new Error(message); } const result = await this.createSession(launch, config, options); this.endInitializingState(); return result; } catch (err) { // make sure to get out of initializing state, and propagate the result this.endInitializingState(); return Promise.reject(err); } } /** * gets the debugger for the type, resolves configurations by providers, substitutes variables and runs prelaunch tasks */ private async createSession(launch: ILaunch | undefined, config: IConfig | undefined, options?: IDebugSessionOptions): Promise<boolean> { // We keep the debug type in a separate variable 'type' so that a no-folder config has no attributes. // Storing the type in the config would break extensions that assume that the no-folder case is indicated by an empty config. let type: string | undefined; if (config) { type = config.type; } else { // a no-folder workspace has no launch.config config = Object.create(null); } const unresolvedConfig = deepClone(config); if (options && options.noDebug) { config!.noDebug = true; } if (!type) { const guess = await this.configurationManager.guessDebugger(); if (guess) { type = guess.type; } } this.initCancellationToken = new CancellationTokenSource(); const configByProviders = await this.configurationManager.resolveConfigurationByProviders(launch && launch.workspace ? launch.workspace.uri : undefined, type, config!, this.initCancellationToken.token); // a falsy config indicates an aborted launch if (configByProviders && configByProviders.type) { try { const resolvedConfig = await this.substituteVariables(launch, configByProviders); if (!resolvedConfig) { // User canceled resolving of interactive variables, silently return return false; } if (!this.configurationManager.getDebugger(resolvedConfig.type) || (configByProviders.request !== 'attach' && configByProviders.request !== 'launch')) { let message: string; if (configByProviders.request !== 'attach' && configByProviders.request !== 'launch') { message = configByProviders.request ? nls.localize('debugRequestNotSupported', "Attribute '{0}' has an unsupported value '{1}' in the chosen debug configuration.", 'request', configByProviders.request) : nls.localize('debugRequesMissing', "Attribute '{0}' is missing from the chosen debug configuration.", 'request'); } else { message = resolvedConfig.type ? nls.localize('debugTypeNotSupported', "Configured debug type '{0}' is not supported.", resolvedConfig.type) : nls.localize('debugTypeMissing', "Missing property 'type' for the chosen launch configuration."); } await this.showError(message); return false; } const workspace = launch ? launch.workspace : this.contextService.getWorkspace(); const taskResult = await this.runTaskAndCheckErrors(workspace, resolvedConfig.preLaunchTask); if (taskResult === TaskRunResult.Success) { return this.doCreateSession(launch?.workspace, { resolved: resolvedConfig, unresolved: unresolvedConfig }, options); } return false; } catch (err) { if (err && err.message) { await this.showError(err.message); } else if (this.contextService.getWorkbenchState() === WorkbenchState.EMPTY) { await this.showError(nls.localize('noFolderWorkspaceDebugError', "The active file can not be debugged. Make sure it is saved and that you have a debug extension installed for that file type.")); } if (launch) { await launch.openConfigFile(false, true, undefined, this.initCancellationToken ? this.initCancellationToken.token : undefined); } return false; } } if (launch && type && configByProviders === null) { // show launch.json only for "config" being "null". await launch.openConfigFile(false, true, type, this.initCancellationToken ? this.initCancellationToken.token : undefined); } return false; } /** * instantiates the new session, initializes the session, registers session listeners and reports telemetry */ private async doCreateSession(root: IWorkspaceFolder | undefined, configuration: { resolved: IConfig, unresolved: IConfig | undefined }, options?: IDebugSessionOptions): Promise<boolean> { const session = this.instantiationService.createInstance(DebugSession, configuration, root, this.model, options); this.model.addSession(session); // register listeners as the very first thing! this.registerSessionListeners(session); // since the Session is now properly registered under its ID and hooked, we can announce it // this event doesn't go to extensions this._onWillNewSession.fire(session); const openDebug = this.configurationService.getValue<IDebugConfiguration>('debug').openDebug; // Open debug viewlet based on the visibility of the side bar and openDebug setting. Do not open for 'run without debug' if (!configuration.resolved.noDebug && (openDebug === 'openOnSessionStart' || (openDebug === 'openOnFirstSessionStart' && this.viewModel.firstSessionStart))) { await this.viewletService.openViewlet(VIEWLET_ID); } try { await this.launchOrAttachToSession(session); const internalConsoleOptions = session.configuration.internalConsoleOptions || this.configurationService.getValue<IDebugConfiguration>('debug').internalConsoleOptions; if (internalConsoleOptions === 'openOnSessionStart' || (this.viewModel.firstSessionStart && internalConsoleOptions === 'openOnFirstSessionStart')) { this.panelService.openPanel(REPL_ID, false); } this.viewModel.firstSessionStart = false; const showSubSessions = this.configurationService.getValue<IDebugConfiguration>('debug').showSubSessionsInToolBar; const sessions = this.model.getSessions(); const shownSessions = showSubSessions ? sessions : sessions.filter(s => !s.parentSession); if (shownSessions.length > 1) { this.viewModel.setMultiSessionView(true); } // since the initialized response has arrived announce the new Session (including extensions) this._onDidNewSession.fire(session); await this.telemetryDebugSessionStart(root, session.configuration.type); return true; } catch (error) { if (errors.isPromiseCanceledError(error)) { // don't show 'canceled' error messages to the user #7906 return false; } // Show the repl if some error got logged there #5870 if (session && session.getReplElements().length > 0) { this.panelService.openPanel(REPL_ID, false); } if (session.configuration && session.configuration.request === 'attach' && session.configuration.__autoAttach) { // ignore attach timeouts in auto attach mode return false; } const errorMessage = error instanceof Error ? error.message : error; await this.showError(errorMessage, isErrorWithActions(error) ? error.actions : []); return false; } } private async launchOrAttachToSession(session: IDebugSession, forceFocus = false): Promise<void> { const dbgr = this.configurationManager.getDebugger(session.configuration.type); try { await session.initialize(dbgr!); await session.launchOrAttach(session.configuration); if (forceFocus || !this.viewModel.focusedSession) { await this.focusStackFrame(undefined, undefined, session); } } catch (err) { session.shutdown(); return Promise.reject(err); } } private registerSessionListeners(session: IDebugSession): void { const sessionRunningScheduler = new RunOnceScheduler(() => { // Do not immediatly defocus the stack frame if the session is running if (session.state === State.Running && this.viewModel.focusedSession === session) { this.viewModel.setFocus(undefined, this.viewModel.focusedThread, session, false); } }, 200); this.toDispose.push(session.onDidChangeState(() => { if (session.state === State.Running && this.viewModel.focusedSession === session) { sessionRunningScheduler.schedule(); } if (session === this.viewModel.focusedSession) { this.onStateChange(); } })); this.toDispose.push(session.onDidEndAdapter(async adapterExitEvent => { if (adapterExitEvent.error) { this.notificationService.error(nls.localize('debugAdapterCrash', "Debug adapter process has terminated unexpectedly ({0})", adapterExitEvent.error.message || adapterExitEvent.error.toString())); } // 'Run without debugging' mode VSCode must terminate the extension host. More details: #3905 if (isExtensionHostDebugging(session.configuration) && session.state === State.Running && session.configuration.noDebug) { this.extensionHostDebugService.close(session.getId()); } this.telemetryDebugSessionStop(session, adapterExitEvent); if (session.configuration.postDebugTask) { try { await this.runTask(session.root, session.configuration.postDebugTask); } catch (err) { this.notificationService.error(err); } } session.shutdown(); this.endInitializingState(); this._onDidEndSession.fire(session); const focusedSession = this.viewModel.focusedSession; if (focusedSession && focusedSession.getId() === session.getId()) { await this.focusStackFrame(undefined); } if (this.model.getSessions().length === 0) { this.viewModel.setMultiSessionView(false); if (this.layoutService.isVisible(Parts.SIDEBAR_PART) && this.configurationService.getValue<IDebugConfiguration>('debug').openExplorerOnEnd) { this.viewletService.openViewlet(EXPLORER_VIEWLET_ID); } // Data breakpoints that can not be persisted should be cleared when a session ends const dataBreakpoints = this.model.getDataBreakpoints().filter(dbp => !dbp.canPersist); dataBreakpoints.forEach(dbp => this.model.removeDataBreakpoints(dbp.getId())); } })); } async restartSession(session: IDebugSession, restartData?: any): Promise<any> { await this.editorService.saveAll(); const isAutoRestart = !!restartData; const runTasks: () => Promise<TaskRunResult> = async () => { if (isAutoRestart) { // Do not run preLaunch and postDebug tasks for automatic restarts return Promise.resolve(TaskRunResult.Success); } await this.runTask(session.root, session.configuration.postDebugTask); return this.runTaskAndCheckErrors(session.root, session.configuration.preLaunchTask); }; if (isExtensionHostDebugging(session.configuration)) { const taskResult = await runTasks(); if (taskResult === TaskRunResult.Success) { this.extensionHostDebugService.reload(session.getId()); } return; } if (session.capabilities.supportsRestartRequest) { const taskResult = await runTasks(); if (taskResult === TaskRunResult.Success) { await session.restart(); } return; } const shouldFocus = !!this.viewModel.focusedSession && session.getId() === this.viewModel.focusedSession.getId(); // If the restart is automatic -> disconnect, otherwise -> terminate #55064 if (isAutoRestart) { await session.disconnect(true); } else { await session.terminate(true); } return new Promise<void>((c, e) => { setTimeout(async () => { const taskResult = await runTasks(); if (taskResult !== TaskRunResult.Success) { return; } // Read the configuration again if a launch.json has been changed, if not just use the inmemory configuration let needsToSubstitute = false; let unresolved: IConfig | undefined; const launch = session.root ? this.configurationManager.getLaunch(session.root.uri) : undefined; if (launch) { unresolved = launch.getConfiguration(session.configuration.name); if (unresolved && !equals(unresolved, session.unresolvedConfiguration)) { // Take the type from the session since the debug extension might overwrite it #21316 unresolved.type = session.configuration.type; unresolved.noDebug = session.configuration.noDebug; needsToSubstitute = true; } } let resolved: IConfig | undefined | null = session.configuration; if (launch && needsToSubstitute && unresolved) { this.initCancellationToken = new CancellationTokenSource(); const resolvedByProviders = await this.configurationManager.resolveConfigurationByProviders(launch.workspace ? launch.workspace.uri : undefined, unresolved.type, unresolved, this.initCancellationToken.token); if (resolvedByProviders) { resolved = await this.substituteVariables(launch, resolvedByProviders); } else { resolved = resolvedByProviders; } } if (!resolved) { return c(undefined); } session.setConfiguration({ resolved, unresolved }); session.configuration.__restart = restartData; try { await this.launchOrAttachToSession(session, shouldFocus); this._onDidNewSession.fire(session); c(undefined); } catch (error) { e(error); } }, 300); }); } stopSession(session: IDebugSession): Promise<any> { if (session) { return session.terminate(); } const sessions = this.model.getSessions(); if (sessions.length === 0) { this.endInitializingState(); } return Promise.all(sessions.map(s => s.terminate())); } private async substituteVariables(launch: ILaunch | undefined, config: IConfig): Promise<IConfig | undefined> { const dbg = this.configurationManager.getDebugger(config.type); if (dbg) { let folder: IWorkspaceFolder | undefined = undefined; if (launch && launch.workspace) { folder = launch.workspace; } else { const folders = this.contextService.getWorkspace().folders; if (folders.length === 1) { folder = folders[0]; } } try { return await dbg.substituteVariables(folder, config); } catch (err) { this.showError(err.message); return undefined; // bail out } } return Promise.resolve(config); } private async showError(message: string, errorActions: ReadonlyArray<IAction> = []): Promise<void> { const configureAction = this.instantiationService.createInstance(debugactions.ConfigureAction, debugactions.ConfigureAction.ID, debugactions.ConfigureAction.LABEL); const actions = [...errorActions, configureAction]; const { choice } = await this.dialogService.show(severity.Error, message, actions.map(a => a.label).concat(nls.localize('cancel', "Cancel")), { cancelId: actions.length }); if (choice < actions.length) { return actions[choice].run(); } return undefined; } //---- task management private async runTaskAndCheckErrors(root: IWorkspaceFolder | IWorkspace | undefined, taskId: string | TaskIdentifier | undefined): Promise<TaskRunResult> { try { const taskSummary = await this.runTask(root, taskId); const errorCount = taskId ? this.markerService.getStatistics().errors : 0; const successExitCode = taskSummary && taskSummary.exitCode === 0; const failureExitCode = taskSummary && taskSummary.exitCode !== 0; const onTaskErrors = this.configurationService.getValue<IDebugConfiguration>('debug').onTaskErrors; if (successExitCode || onTaskErrors === 'debugAnyway' || (errorCount === 0 && !failureExitCode)) { return TaskRunResult.Success; } if (onTaskErrors === 'showErrors') { this.panelService.openPanel(Constants.MARKERS_PANEL_ID); return Promise.resolve(TaskRunResult.Failure); } const taskLabel = typeof taskId === 'string' ? taskId : taskId ? taskId.name : ''; const message = errorCount > 1 ? nls.localize('preLaunchTaskErrors', "Errors exist after running preLaunchTask '{0}'.", taskLabel) : errorCount === 1 ? nls.localize('preLaunchTaskError', "Error exists after running preLaunchTask '{0}'.", taskLabel) : nls.localize('preLaunchTaskExitCode', "The preLaunchTask '{0}' terminated with exit code {1}.", taskLabel, taskSummary ? taskSummary.exitCode : 0); const result = await this.dialogService.show(severity.Warning, message, [nls.localize('debugAnyway', "Debug Anyway"), nls.localize('showErrors', "Show Errors"), nls.localize('cancel', "Cancel")], { checkbox: { label: nls.localize('remember', "Remember my choice in user settings"), }, cancelId: 2 }); if (result.choice === 2) { return Promise.resolve(TaskRunResult.Failure); } const debugAnyway = result.choice === 0; if (result.checkboxChecked) { this.configurationService.updateValue('debug.onTaskErrors', debugAnyway ? 'debugAnyway' : 'showErrors'); } if (debugAnyway) { return TaskRunResult.Success; } this.panelService.openPanel(Constants.MARKERS_PANEL_ID); return Promise.resolve(TaskRunResult.Failure); } catch (err) { await this.showError(err.message, [this.taskService.configureAction()]); return TaskRunResult.Failure; } } private async runTask(root: IWorkspace | IWorkspaceFolder | undefined, taskId: string | TaskIdentifier | undefined): Promise<ITaskSummary | null> { if (!taskId) { return Promise.resolve(null); } if (!root) { return Promise.reject(new Error(nls.localize('invalidTaskReference', "Task '{0}' can not be referenced from a launch configuration that is in a different workspace folder.", typeof taskId === 'string' ? taskId : taskId.type))); } // run a task before starting a debug session const task = await this.taskService.getTask(root, taskId); if (!task) { const errorMessage = typeof taskId === 'string' ? nls.localize('DebugTaskNotFoundWithTaskId', "Could not find the task '{0}'.", taskId) : nls.localize('DebugTaskNotFound', "Could not find the specified task."); return Promise.reject(createErrorWithActions(errorMessage)); } // If a task is missing the problem matcher the promise will never complete, so we need to have a workaround #35340 let taskStarted = false; const inactivePromise: Promise<ITaskSummary | null> = new Promise((c, e) => once(e => { // When a task isBackground it will go inactive when it is safe to launch. // But when a background task is terminated by the user, it will also fire an inactive event. // This means that we will not get to see the real exit code from running the task (undefined when terminated by the user). // Catch the ProcessEnded event here, which occurs before inactive, and capture the exit code to prevent this. return (e.kind === TaskEventKind.Inactive || (e.kind === TaskEventKind.ProcessEnded && e.exitCode === undefined)) && e.taskId === task._id; }, this.taskService.onDidStateChange)(e => { taskStarted = true; c(e.kind === TaskEventKind.ProcessEnded ? { exitCode: e.exitCode } : null); })); const promise: Promise<ITaskSummary | null> = this.taskService.getActiveTasks().then(async (tasks): Promise<ITaskSummary | null> => { if (tasks.filter(t => t._id === task._id).length) { // Check that the task isn't busy and if it is, wait for it const busyTasks = await this.taskService.getBusyTasks(); if (busyTasks.filter(t => t._id === task._id).length) { taskStarted = true; return inactivePromise; } // task is already running and isn't busy - nothing to do. return Promise.resolve(null); } once(e => ((e.kind === TaskEventKind.Active) || (e.kind === TaskEventKind.DependsOnStarted)) && e.taskId === task._id, this.taskService.onDidStateChange)(() => { // Task is active, so everything seems to be fine, no need to prompt after 10 seconds // Use case being a slow running task should not be prompted even though it takes more than 10 seconds taskStarted = true; }); const taskPromise = this.taskService.run(task); if (task.configurationProperties.isBackground) { return inactivePromise; } return taskPromise.then(withUndefinedAsNull); }); return new Promise((c, e) => { promise.then(result => { taskStarted = true; c(result); }, error => e(error)); setTimeout(() => { if (!taskStarted) { const errorMessage = typeof taskId === 'string' ? nls.localize('taskNotTrackedWithTaskId', "The specified task cannot be tracked.") : nls.localize('taskNotTracked', "The task '{0}' cannot be tracked.", JSON.stringify(taskId)); e({ severity: severity.Error, message: errorMessage }); } }, 10000); }); } //---- focus management async focusStackFrame(stackFrame: IStackFrame | undefined, thread?: IThread, session?: IDebugSession, explicit?: boolean): Promise<void> { if (!session) { if (stackFrame || thread) { session = stackFrame ? stackFrame.thread.session : thread!.session; } else { const sessions = this.model.getSessions(); const stoppedSession = sessions.filter(s => s.state === State.Stopped).shift(); session = stoppedSession || (sessions.length ? sessions[0] : undefined); } } if (!thread) { if (stackFrame) { thread = stackFrame.thread; } else { const threads = session ? session.getAllThreads() : undefined; const stoppedThread = threads && threads.filter(t => t.stopped).shift(); thread = stoppedThread || (threads && threads.length ? threads[0] : undefined); } } if (!stackFrame) { if (thread) { const callStack = thread.getCallStack(); stackFrame = first(callStack, sf => !!(sf && sf.source && sf.source.available && sf.source.presentationHint !== 'deemphasize'), undefined); } } if (stackFrame) { const editor = await stackFrame.openInEditor(this.editorService, true); if (editor) { const control = editor.getControl(); if (stackFrame && isCodeEditor(control) && control.hasModel()) { const model = control.getModel(); if (stackFrame.range.startLineNumber <= model.getLineCount()) { const lineContent = control.getModel().getLineContent(stackFrame.range.startLineNumber); aria.alert(nls.localize('debuggingPaused', "Debugging paused {0}, {1} {2} {3}", thread && thread.stoppedDetails ? `, reason ${thread.stoppedDetails.reason}` : '', stackFrame.source ? stackFrame.source.name : '', stackFrame.range.startLineNumber, lineContent)); } } } } if (session) { this.debugType.set(session.configuration.type); } else { this.debugType.reset(); } this.viewModel.setFocus(stackFrame, thread, session, !!explicit); } //---- watches addWatchExpression(name: string): void { const we = this.model.addWatchExpression(name); this.viewModel.setSelectedExpression(we); this.storeWatchExpressions(); } renameWatchExpression(id: string, newName: string): void { this.model.renameWatchExpression(id, newName); this.storeWatchExpressions(); } moveWatchExpression(id: string, position: number): void { this.model.moveWatchExpression(id, position); this.storeWatchExpressions(); } removeWatchExpressions(id?: string): void { this.model.removeWatchExpressions(id); this.storeWatchExpressions(); } //---- breakpoints async enableOrDisableBreakpoints(enable: boolean, breakpoint?: IEnablement): Promise<void> { if (breakpoint) { this.model.setEnablement(breakpoint, enable); if (breakpoint instanceof Breakpoint) { await this.sendBreakpoints(breakpoint.uri); } else if (breakpoint instanceof FunctionBreakpoint) { await this.sendFunctionBreakpoints(); } else if (breakpoint instanceof DataBreakpoint) { await this.sendDataBreakpoints(); } else { await this.sendExceptionBreakpoints(); } } else { this.model.enableOrDisableAllBreakpoints(enable); await this.sendAllBreakpoints(); } this.storeBreakpoints(); } async addBreakpoints(uri: uri, rawBreakpoints: IBreakpointData[], context: string): Promise<IBreakpoint[]> { const breakpoints = this.model.addBreakpoints(uri, rawBreakpoints); breakpoints.forEach(bp => aria.status(nls.localize('breakpointAdded', "Added breakpoint, line {0}, file {1}", bp.lineNumber, uri.fsPath))); breakpoints.forEach(bp => this.telemetryDebugAddBreakpoint(bp, context)); await this.sendBreakpoints(uri); this.storeBreakpoints(); return breakpoints; } async updateBreakpoints(uri: uri, data: Map<string, DebugProtocol.Breakpoint>, sendOnResourceSaved: boolean): Promise<void> { this.model.updateBreakpoints(data); if (sendOnResourceSaved) { this.breakpointsToSendOnResourceSaved.add(uri.toString()); } else { await this.sendBreakpoints(uri); } this.storeBreakpoints(); } async removeBreakpoints(id?: string): Promise<void> { const toRemove = this.model.getBreakpoints().filter(bp => !id || bp.getId() === id); toRemove.forEach(bp => aria.status(nls.localize('breakpointRemoved', "Removed breakpoint, line {0}, file {1}", bp.lineNumber, bp.uri.fsPath))); const urisToClear = distinct(toRemove, bp => bp.uri.toString()).map(bp => bp.uri); this.model.removeBreakpoints(toRemove); await Promise.all(urisToClear.map(uri => this.sendBreakpoints(uri))); this.storeBreakpoints(); } setBreakpointsActivated(activated: boolean): Promise<void> { this.model.setBreakpointsActivated(activated); return this.sendAllBreakpoints(); } addFunctionBreakpoint(name?: string, id?: string): void { const newFunctionBreakpoint = this.model.addFunctionBreakpoint(name || '', id); this.viewModel.setSelectedFunctionBreakpoint(newFunctionBreakpoint); } async renameFunctionBreakpoint(id: string, newFunctionName: string): Promise<void> { this.model.renameFunctionBreakpoint(id, newFunctionName); await this.sendFunctionBreakpoints(); this.storeBreakpoints(); } async removeFunctionBreakpoints(id?: string): Promise<void> { this.model.removeFunctionBreakpoints(id); await this.sendFunctionBreakpoints(); this.storeBreakpoints(); } async addDataBreakpoint(label: string, dataId: string, canPersist: boolean): Promise<void> { this.model.addDataBreakpoint(label, dataId, canPersist); await this.sendDataBreakpoints(); this.storeBreakpoints(); } async removeDataBreakpoints(id?: string): Promise<void> { this.model.removeDataBreakpoints(id); await this.sendDataBreakpoints(); this.storeBreakpoints(); } async sendAllBreakpoints(session?: IDebugSession): Promise<any> { await Promise.all(distinct(this.model.getBreakpoints(), bp => bp.uri.toString()).map(bp => this.sendBreakpoints(bp.uri, false, session))); await this.sendFunctionBreakpoints(session); await this.sendDataBreakpoints(session); // send exception breakpoints at the end since some debug adapters rely on the order await this.sendExceptionBreakpoints(session); } private sendBreakpoints(modelUri: uri, sourceModified = false, session?: IDebugSession): Promise<void> { const breakpointsToSend = this.model.getBreakpoints({ uri: modelUri, enabledOnly: true }); return this.sendToOneOrAllSessions(session, s => s.sendBreakpoints(modelUri, breakpointsToSend, sourceModified) ); } private sendFunctionBreakpoints(session?: IDebugSession): Promise<void> { const breakpointsToSend = this.model.getFunctionBreakpoints().filter(fbp => fbp.enabled && this.model.areBreakpointsActivated()); return this.sendToOneOrAllSessions(session, s => { return s.capabilities.supportsFunctionBreakpoints ? s.sendFunctionBreakpoints(breakpointsToSend) : Promise.resolve(undefined); }); } private sendDataBreakpoints(session?: IDebugSession): Promise<void> { const breakpointsToSend = this.model.getDataBreakpoints().filter(fbp => fbp.enabled && this.model.areBreakpointsActivated()); return this.sendToOneOrAllSessions(session, s => { return s.capabilities.supportsDataBreakpoints ? s.sendDataBreakpoints(breakpointsToSend) : Promise.resolve(undefined); }); } private sendExceptionBreakpoints(session?: IDebugSession): Promise<void> { const enabledExceptionBps = this.model.getExceptionBreakpoints().filter(exb => exb.enabled); return this.sendToOneOrAllSessions(session, s => { return s.sendExceptionBreakpoints(enabledExceptionBps); }); } private async sendToOneOrAllSessions(session: IDebugSession | undefined, send: (session: IDebugSession) => Promise<void>): Promise<void> { if (session) { await send(session); } else { await Promise.all(this.model.getSessions().map(s => send(s))); } } private onFileChanges(fileChangesEvent: FileChangesEvent): void { const toRemove = this.model.getBreakpoints().filter(bp => fileChangesEvent.contains(bp.uri, FileChangeType.DELETED)); if (toRemove.length) { this.model.removeBreakpoints(toRemove); } fileChangesEvent.getUpdated().forEach(event => { if (this.breakpointsToSendOnResourceSaved.delete(event.resource.toString())) { this.sendBreakpoints(event.resource, true); } }); } private loadBreakpoints(): Breakpoint[] { let result: Breakpoint[] | undefined; try { result = JSON.parse(this.storageService.get(DEBUG_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((breakpoint: any) => { return new Breakpoint(uri.parse(breakpoint.uri.external || breakpoint.source.uri.external), breakpoint.lineNumber, breakpoint.column, breakpoint.enabled, breakpoint.condition, breakpoint.hitCondition, breakpoint.logMessage, breakpoint.adapterData, this.textFileService); }); } catch (e) { } return result || []; } private loadFunctionBreakpoints(): FunctionBreakpoint[] { let result: FunctionBreakpoint[] | undefined; try { result = JSON.parse(this.storageService.get(DEBUG_FUNCTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((fb: any) => { return new FunctionBreakpoint(fb.name, fb.enabled, fb.hitCondition, fb.condition, fb.logMessage); }); } catch (e) { } return result || []; } private loadExceptionBreakpoints(): ExceptionBreakpoint[] { let result: ExceptionBreakpoint[] | undefined; try { result = JSON.parse(this.storageService.get(DEBUG_EXCEPTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((exBreakpoint: any) => { return new ExceptionBreakpoint(exBreakpoint.filter, exBreakpoint.label, exBreakpoint.enabled); }); } catch (e) { } return result || []; } private loadDataBreakpoints(): DataBreakpoint[] { let result: DataBreakpoint[] | undefined; try { result = JSON.parse(this.storageService.get(DEBUG_DATA_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((dbp: any) => { return new DataBreakpoint(dbp.label, dbp.dataId, true, dbp.enabled, dbp.hitCondition, dbp.condition, dbp.logMessage); }); } catch (e) { } return result || []; } private loadWatchExpressions(): Expression[] { let result: Expression[] | undefined; try { result = JSON.parse(this.storageService.get(DEBUG_WATCH_EXPRESSIONS_KEY, StorageScope.WORKSPACE, '[]')).map((watchStoredData: { name: string, id: string }) => { return new Expression(watchStoredData.name, watchStoredData.id); }); } catch (e) { } return result || []; } private storeWatchExpressions(): void { const watchExpressions = this.model.getWatchExpressions(); if (watchExpressions.length) { this.storageService.store(DEBUG_WATCH_EXPRESSIONS_KEY, JSON.stringify(watchExpressions.map(we => ({ name: we.name, id: we.getId() }))), StorageScope.WORKSPACE); } else { this.storageService.remove(DEBUG_WATCH_EXPRESSIONS_KEY, StorageScope.WORKSPACE); } } private storeBreakpoints(): void { const breakpoints = this.model.getBreakpoints(); if (breakpoints.length) { this.storageService.store(DEBUG_BREAKPOINTS_KEY, JSON.stringify(breakpoints), StorageScope.WORKSPACE); } else { this.storageService.remove(DEBUG_BREAKPOINTS_KEY, StorageScope.WORKSPACE); } const functionBreakpoints = this.model.getFunctionBreakpoints(); if (functionBreakpoints.length) { this.storageService.store(DEBUG_FUNCTION_BREAKPOINTS_KEY, JSON.stringify(functionBreakpoints), StorageScope.WORKSPACE); } else { this.storageService.remove(DEBUG_FUNCTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE); } const dataBreakpoints = this.model.getDataBreakpoints().filter(dbp => dbp.canPersist); if (dataBreakpoints.length) { this.storageService.store(DEBUG_DATA_BREAKPOINTS_KEY, JSON.stringify(dataBreakpoints), StorageScope.WORKSPACE); } else { this.storageService.remove(DEBUG_DATA_BREAKPOINTS_KEY, StorageScope.WORKSPACE); } const exceptionBreakpoints = this.model.getExceptionBreakpoints(); if (exceptionBreakpoints.length) { this.storageService.store(DEBUG_EXCEPTION_BREAKPOINTS_KEY, JSON.stringify(exceptionBreakpoints), StorageScope.WORKSPACE); } else { this.storageService.remove(DEBUG_EXCEPTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE); } } //---- telemetry private telemetryDebugSessionStart(root: IWorkspaceFolder | undefined, type: string): Promise<void> { const dbgr = this.configurationManager.getDebugger(type); if (!dbgr) { return Promise.resolve(); } const extension = dbgr.getMainExtensionDescriptor(); /* __GDPR__ "debugSessionStart" : { "type": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "breakpointCount": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "exceptionBreakpoints": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "watchExpressionsCount": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "extensionName": { "classification": "PublicNonPersonalData", "purpose": "FeatureInsight" }, "isBuiltin": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true}, "launchJsonExists": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true } } */ return this.telemetryService.publicLog('debugSessionStart', { type: type, breakpointCount: this.model.getBreakpoints().length, exceptionBreakpoints: this.model.getExceptionBreakpoints(), watchExpressionsCount: this.model.getWatchExpressions().length, extensionName: extension.identifier.value, isBuiltin: extension.isBuiltin, launchJsonExists: root && !!this.configurationService.getValue<IGlobalConfig>('launch', { resource: root.uri }) }); } private telemetryDebugSessionStop(session: IDebugSession, adapterExitEvent: AdapterEndEvent): Promise<any> { const breakpoints = this.model.getBreakpoints(); /* __GDPR__ "debugSessionStop" : { "type" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "success": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "sessionLengthInSeconds": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "breakpointCount": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "watchExpressionsCount": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true } } */ return this.telemetryService.publicLog('debugSessionStop', { type: session && session.configuration.type, success: adapterExitEvent.emittedStopped || breakpoints.length === 0, sessionLengthInSeconds: adapterExitEvent.sessionLengthInSeconds, breakpointCount: breakpoints.length, watchExpressionsCount: this.model.getWatchExpressions().length }); } private telemetryDebugAddBreakpoint(breakpoint: IBreakpoint, context: string): Promise<any> { /* __GDPR__ "debugAddBreakpoint" : { "context": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "hasCondition": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "hasHitCondition": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "hasLogMessage": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true } } */ return this.telemetryService.publicLog('debugAddBreakpoint', { context: context, hasCondition: !!breakpoint.condition, hasHitCondition: !!breakpoint.hitCondition, hasLogMessage: !!breakpoint.logMessage }); } }
src/vs/workbench/contrib/debug/browser/debugService.ts
1
https://github.com/microsoft/vscode/commit/88e80b9a18b2cc3de0ca3a02977c3e2d4b088a60
[ 0.9979815483093262, 0.06431598961353302, 0.00016178256191778928, 0.0001742370513966307, 0.23383186757564545 ]
{ "id": 2, "code_window": [ "\t\t\tawait this.runTask(session.root, session.configuration.postDebugTask);\n", "\t\t\treturn this.runTaskAndCheckErrors(session.root, session.configuration.preLaunchTask);\n", "\t\t};\n", "\n", "\t\tif (isExtensionHostDebugging(session.configuration)) {\n", "\t\t\tconst taskResult = await runTasks();\n", "\t\t\tif (taskResult === TaskRunResult.Success) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ "\t\tconst extensionDebugSession = getExtensionHostDebugSession(session);\n", "\t\tif (extensionDebugSession) {\n" ], "file_path": "src/vs/workbench/contrib/debug/browser/debugService.ts", "type": "replace", "edit_start_line_idx": 592 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { URI } from 'vs/base/common/uri'; import { regExpFlags } from 'vs/base/common/strings'; export function stringify(obj: any): string { return JSON.stringify(obj, replacer); } export function parse(text: string): any { let data = JSON.parse(text); data = revive(data); return data; } export interface MarshalledObject { $mid: number; } function replacer(key: string, value: any): any { // URI is done via toJSON-member if (value instanceof RegExp) { return { $mid: 2, source: value.source, flags: regExpFlags(value), }; } return value; } export function revive(obj: any, depth = 0): any { if (!obj || depth > 200) { return obj; } if (typeof obj === 'object') { switch ((<MarshalledObject>obj).$mid) { case 1: return URI.revive(obj); case 2: return new RegExp(obj.source, obj.flags); } // walk object (or array) for (let key in obj) { if (Object.hasOwnProperty.call(obj, key)) { obj[key] = revive(obj[key], depth + 1); } } } return obj; }
src/vs/base/common/marshalling.ts
0
https://github.com/microsoft/vscode/commit/88e80b9a18b2cc3de0ca3a02977c3e2d4b088a60
[ 0.00017434588517062366, 0.00017333135474473238, 0.0001729062496451661, 0.00017316390585619956, 4.776872515321884e-7 ]
{ "id": 2, "code_window": [ "\t\t\tawait this.runTask(session.root, session.configuration.postDebugTask);\n", "\t\t\treturn this.runTaskAndCheckErrors(session.root, session.configuration.preLaunchTask);\n", "\t\t};\n", "\n", "\t\tif (isExtensionHostDebugging(session.configuration)) {\n", "\t\t\tconst taskResult = await runTasks();\n", "\t\t\tif (taskResult === TaskRunResult.Success) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ "\t\tconst extensionDebugSession = getExtensionHostDebugSession(session);\n", "\t\tif (extensionDebugSession) {\n" ], "file_path": "src/vs/workbench/contrib/debug/browser/debugService.ts", "type": "replace", "edit_start_line_idx": 592 }
{ "version": "2.0.0", "tasks": [ { "type": "npm", "script": "watch", "label": "Build VS Code", "group": { "kind": "build", "isDefault": true }, "isBackground": true, "presentation": { "reveal": "never" }, "problemMatcher": { "owner": "typescript", "applyTo": "closedDocuments", "fileLocation": [ "absolute" ], "pattern": { "regexp": "Error: ([^(]+)\\((\\d+|\\d+,\\d+|\\d+,\\d+,\\d+,\\d+)\\): (.*)$", "file": 1, "location": 2, "message": 3 }, "background": { "beginsPattern": "Starting compilation", "endsPattern": "Finished compilation" } } }, { "type": "npm", "script": "strict-function-types-watch", "label": "TS - Strict Function Types", "isBackground": true, "presentation": { "reveal": "never" }, "problemMatcher": { "base": "$tsc-watch", "owner": "typescript-function-types", "applyTo": "allDocuments" } }, { "type": "gulp", "task": "tslint", "label": "Run tslint", "problemMatcher": [ "$tslint5" ] }, { "label": "Run tests", "type": "shell", "command": "./scripts/test.sh", "windows": { "command": ".\\scripts\\test.bat" }, "group": "test", "presentation": { "echo": true, "reveal": "always" } }, { "label": "Run Dev", "type": "shell", "command": "./scripts/code.sh", "windows": { "command": ".\\scripts\\code.bat" }, "problemMatcher": [] }, { "type": "npm", "script": "electron", "label": "Download electron" }, { "type": "gulp", "task": "hygiene", "problemMatcher": [] }, { "type": "shell", "command": "yarn web -- --no-launch", "label": "Run web", "isBackground": true, // This section to make error go away when launching the debug config "problemMatcher": { "pattern": { "regexp": "" }, "background": { "beginsPattern": ".*node .*", "endsPattern": "Web UI available at .*" } }, "presentation": { "reveal": "never" } }, ] }
.vscode/tasks.json
0
https://github.com/microsoft/vscode/commit/88e80b9a18b2cc3de0ca3a02977c3e2d4b088a60
[ 0.00017511093756183982, 0.00017255364218726754, 0.00016534284804947674, 0.00017292058328166604, 0.0000024703488179511623 ]
{ "id": 2, "code_window": [ "\t\t\tawait this.runTask(session.root, session.configuration.postDebugTask);\n", "\t\t\treturn this.runTaskAndCheckErrors(session.root, session.configuration.preLaunchTask);\n", "\t\t};\n", "\n", "\t\tif (isExtensionHostDebugging(session.configuration)) {\n", "\t\t\tconst taskResult = await runTasks();\n", "\t\t\tif (taskResult === TaskRunResult.Success) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ "\t\tconst extensionDebugSession = getExtensionHostDebugSession(session);\n", "\t\tif (extensionDebugSession) {\n" ], "file_path": "src/vs/workbench/contrib/debug/browser/debugService.ts", "type": "replace", "edit_start_line_idx": 592 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ .monaco-editor .lightbulb-glyph, .monaco-editor .codicon-lightbulb { display: flex; align-items: center; justify-content: center; height: 16px; width: 20px; padding-left: 2px; } .monaco-editor .lightbulb-glyph:hover, .monaco-editor .codicon-lightbulb:hover { cursor: pointer; /* transform: scale(1.3, 1.3); */ }
src/vs/editor/contrib/codeAction/lightBulbWidget.css
0
https://github.com/microsoft/vscode/commit/88e80b9a18b2cc3de0ca3a02977c3e2d4b088a60
[ 0.00017610285431146622, 0.00017321431369055063, 0.00016994513862300664, 0.00017359494813717902, 0.0000025282440674345708 ]
{ "id": 3, "code_window": [ "\t\t\tconst taskResult = await runTasks();\n", "\t\t\tif (taskResult === TaskRunResult.Success) {\n", "\t\t\t\tthis.extensionHostDebugService.reload(session.getId());\n", "\t\t\t}\n", "\n", "\t\t\treturn;\n", "\t\t}\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tthis.extensionHostDebugService.reload(extensionDebugSession.getId());\n" ], "file_path": "src/vs/workbench/contrib/debug/browser/debugService.ts", "type": "replace", "edit_start_line_idx": 595 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { equalsIgnoreCase } from 'vs/base/common/strings'; import { IConfig, IDebuggerContribution, IDebugSession } from 'vs/workbench/contrib/debug/common/debug'; import { URI as uri } from 'vs/base/common/uri'; import { isAbsolute } from 'vs/base/common/path'; import { deepClone } from 'vs/base/common/objects'; const _formatPIIRegexp = /{([^}]+)}/g; export function formatPII(value: string, excludePII: boolean, args: { [key: string]: string }): string { return value.replace(_formatPIIRegexp, function (match, group) { if (excludePII && group.length > 0 && group[0] !== '_') { return match; } return args && args.hasOwnProperty(group) ? args[group] : match; }); } export function isSessionAttach(session: IDebugSession): boolean { return !session.parentSession && session.configuration.request === 'attach' && !isExtensionHostDebugging(session.configuration); } export function isExtensionHostDebugging(config: IConfig) { if (!config.type) { return false; } const type = config.type === 'vslsShare' ? (<any>config).adapterProxy.configuration.type : config.type; return equalsIgnoreCase(type, 'extensionhost') || equalsIgnoreCase(type, 'pwa-extensionhost'); } // only a debugger contributions with a label, program, or runtime attribute is considered a "defining" or "main" debugger contribution export function isDebuggerMainContribution(dbg: IDebuggerContribution) { return dbg.type && (dbg.label || dbg.program || dbg.runtime); } export function getExactExpressionStartAndEnd(lineContent: string, looseStart: number, looseEnd: number): { start: number, end: number } { let matchingExpression: string | undefined = undefined; let startOffset = 0; // Some example supported expressions: myVar.prop, a.b.c.d, myVar?.prop, myVar->prop, MyClass::StaticProp, *myVar // Match any character except a set of characters which often break interesting sub-expressions let expression: RegExp = /([^()\[\]{}<>\s+\-/%~#^;=|,`!]|\->)+/g; let result: RegExpExecArray | null = null; // First find the full expression under the cursor while (result = expression.exec(lineContent)) { let start = result.index + 1; let end = start + result[0].length; if (start <= looseStart && end >= looseEnd) { matchingExpression = result[0]; startOffset = start; break; } } // If there are non-word characters after the cursor, we want to truncate the expression then. // For example in expression 'a.b.c.d', if the focus was under 'b', 'a.b' would be evaluated. if (matchingExpression) { let subExpression: RegExp = /\w+/g; let subExpressionResult: RegExpExecArray | null = null; while (subExpressionResult = subExpression.exec(matchingExpression)) { let subEnd = subExpressionResult.index + 1 + startOffset + subExpressionResult[0].length; if (subEnd >= looseEnd) { break; } } if (subExpressionResult) { matchingExpression = matchingExpression.substring(0, subExpression.lastIndex); } } return matchingExpression ? { start: startOffset, end: startOffset + matchingExpression.length - 1 } : { start: 0, end: 0 }; } // RFC 2396, Appendix A: https://www.ietf.org/rfc/rfc2396.txt const _schemePattern = /^[a-zA-Z][a-zA-Z0-9\+\-\.]+:/; export function isUri(s: string | undefined): boolean { // heuristics: a valid uri starts with a scheme and // the scheme has at least 2 characters so that it doesn't look like a drive letter. return !!(s && s.match(_schemePattern)); } function stringToUri(path: string): string { if (typeof path === 'string') { if (isUri(path)) { return <string><unknown>uri.parse(path); } else { // assume path if (isAbsolute(path)) { return <string><unknown>uri.file(path); } else { // leave relative path as is } } } return path; } function uriToString(path: string): string { if (typeof path === 'object') { const u = uri.revive(path); if (u.scheme === 'file') { return u.fsPath; } else { return u.toString(); } } return path; } // path hooks helpers interface PathContainer { path?: string; } export function convertToDAPaths(message: DebugProtocol.ProtocolMessage, toUri: boolean): DebugProtocol.ProtocolMessage { const fixPath = toUri ? stringToUri : uriToString; // since we modify Source.paths in the message in place, we need to make a copy of it (see #61129) const msg = deepClone(message); convertPaths(msg, (toDA: boolean, source: PathContainer | undefined) => { if (toDA && source) { source.path = source.path ? fixPath(source.path) : undefined; } }); return msg; } export function convertToVSCPaths(message: DebugProtocol.ProtocolMessage, toUri: boolean): DebugProtocol.ProtocolMessage { const fixPath = toUri ? stringToUri : uriToString; // since we modify Source.paths in the message in place, we need to make a copy of it (see #61129) const msg = deepClone(message); convertPaths(msg, (toDA: boolean, source: PathContainer | undefined) => { if (!toDA && source) { source.path = source.path ? fixPath(source.path) : undefined; } }); return msg; } function convertPaths(msg: DebugProtocol.ProtocolMessage, fixSourcePath: (toDA: boolean, source: PathContainer | undefined) => void): void { switch (msg.type) { case 'event': const event = <DebugProtocol.Event>msg; switch (event.event) { case 'output': fixSourcePath(false, (<DebugProtocol.OutputEvent>event).body.source); break; case 'loadedSource': fixSourcePath(false, (<DebugProtocol.LoadedSourceEvent>event).body.source); break; case 'breakpoint': fixSourcePath(false, (<DebugProtocol.BreakpointEvent>event).body.breakpoint.source); break; default: break; } break; case 'request': const request = <DebugProtocol.Request>msg; switch (request.command) { case 'setBreakpoints': fixSourcePath(true, (<DebugProtocol.SetBreakpointsArguments>request.arguments).source); break; case 'breakpointLocations': fixSourcePath(true, (<DebugProtocol.BreakpointLocationsArguments>request.arguments).source); break; case 'source': fixSourcePath(true, (<DebugProtocol.SourceArguments>request.arguments).source); break; case 'gotoTargets': fixSourcePath(true, (<DebugProtocol.GotoTargetsArguments>request.arguments).source); break; case 'launchVSCode': request.arguments.args.forEach((arg: PathContainer | undefined) => fixSourcePath(false, arg)); break; default: break; } break; case 'response': const response = <DebugProtocol.Response>msg; if (response.success) { switch (response.command) { case 'stackTrace': (<DebugProtocol.StackTraceResponse>response).body.stackFrames.forEach(frame => fixSourcePath(false, frame.source)); break; case 'loadedSources': (<DebugProtocol.LoadedSourcesResponse>response).body.sources.forEach(source => fixSourcePath(false, source)); break; case 'scopes': (<DebugProtocol.ScopesResponse>response).body.scopes.forEach(scope => fixSourcePath(false, scope.source)); break; case 'setFunctionBreakpoints': (<DebugProtocol.SetFunctionBreakpointsResponse>response).body.breakpoints.forEach(bp => fixSourcePath(false, bp.source)); break; case 'setBreakpoints': (<DebugProtocol.SetBreakpointsResponse>response).body.breakpoints.forEach(bp => fixSourcePath(false, bp.source)); break; default: break; } } break; } }
src/vs/workbench/contrib/debug/common/debugUtils.ts
1
https://github.com/microsoft/vscode/commit/88e80b9a18b2cc3de0ca3a02977c3e2d4b088a60
[ 0.004159762058407068, 0.0003446493938099593, 0.00016458106983918697, 0.00017179154383484274, 0.0008133922819979489 ]
{ "id": 3, "code_window": [ "\t\t\tconst taskResult = await runTasks();\n", "\t\t\tif (taskResult === TaskRunResult.Success) {\n", "\t\t\t\tthis.extensionHostDebugService.reload(session.getId());\n", "\t\t\t}\n", "\n", "\t\t\treturn;\n", "\t\t}\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tthis.extensionHostDebugService.reload(extensionDebugSession.getId());\n" ], "file_path": "src/vs/workbench/contrib/debug/browser/debugService.ts", "type": "replace", "edit_start_line_idx": 595 }
{ "comments": { "lineComment": "//", "blockComment": [ "/*", "*/" ] }, "brackets": [ ["{", "}"], ["[", "]"], ["(", ")"] ], "autoClosingPairs": [ ["{", "}"], ["[", "]"], ["(", ")"], { "open": "`", "close": "`", "notIn": ["string"]}, { "open": "\"", "close": "\"", "notIn": ["string"]}, { "open": "'", "close": "'", "notIn": ["string", "comment"]} ], "surroundingPairs": [ ["{", "}"], ["[", "]"], ["(", ")"], ["\"", "\""], ["'", "'"], ["`", "`"] ], "indentationRules": { "increaseIndentPattern": "^.*(\\bcase\\b.*:|\\bdefault\\b:|(\\b(func|if|else|switch|select|for|struct)\\b.*)?{[^}\"'`]*|\\([^)\"'`]*)$", "decreaseIndentPattern": "^\\s*(\\bcase\\b.*:|\\bdefault\\b:|}[)}]*[),]?|\\)[,]?)$" }, "folding": { "markers": { "start": "^\\s*//\\s*#?region\\b", "end": "^\\s*//\\s*#?endregion\\b" } } }
extensions/go/language-configuration.json
0
https://github.com/microsoft/vscode/commit/88e80b9a18b2cc3de0ca3a02977c3e2d4b088a60
[ 0.00017522936104796827, 0.0001731300144456327, 0.0001708019117359072, 0.00017324439249932766, 0.0000018651770687938551 ]
{ "id": 3, "code_window": [ "\t\t\tconst taskResult = await runTasks();\n", "\t\t\tif (taskResult === TaskRunResult.Success) {\n", "\t\t\t\tthis.extensionHostDebugService.reload(session.getId());\n", "\t\t\t}\n", "\n", "\t\t\treturn;\n", "\t\t}\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tthis.extensionHostDebugService.reload(extensionDebugSession.getId());\n" ], "file_path": "src/vs/workbench/contrib/debug/browser/debugService.ts", "type": "replace", "edit_start_line_idx": 595 }
cgmanifest.json
extensions/theme-tomorrow-night-blue/.vscodeignore
0
https://github.com/microsoft/vscode/commit/88e80b9a18b2cc3de0ca3a02977c3e2d4b088a60
[ 0.00017693718837108463, 0.00017693718837108463, 0.00017693718837108463, 0.00017693718837108463, 0 ]
{ "id": 3, "code_window": [ "\t\t\tconst taskResult = await runTasks();\n", "\t\t\tif (taskResult === TaskRunResult.Success) {\n", "\t\t\t\tthis.extensionHostDebugService.reload(session.getId());\n", "\t\t\t}\n", "\n", "\t\t\treturn;\n", "\t\t}\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tthis.extensionHostDebugService.reload(extensionDebugSession.getId());\n" ], "file_path": "src/vs/workbench/contrib/debug/browser/debugService.ts", "type": "replace", "edit_start_line_idx": 595 }
{ "extends": "../../shared.tsconfig.json", "compilerOptions": { "outDir": "./out" }, "include": [ "src/**/*" ] }
extensions/html-language-features/client/tsconfig.json
0
https://github.com/microsoft/vscode/commit/88e80b9a18b2cc3de0ca3a02977c3e2d4b088a60
[ 0.00017463222320657223, 0.00017463222320657223, 0.00017463222320657223, 0.00017463222320657223, 0 ]
{ "id": 4, "code_window": [ " * Licensed under the MIT License. See License.txt in the project root for license information.\n", " *--------------------------------------------------------------------------------------------*/\n", "\n", "import { equalsIgnoreCase } from 'vs/base/common/strings';\n", "import { IConfig, IDebuggerContribution, IDebugSession } from 'vs/workbench/contrib/debug/common/debug';\n", "import { URI as uri } from 'vs/base/common/uri';\n", "import { isAbsolute } from 'vs/base/common/path';\n", "import { deepClone } from 'vs/base/common/objects';\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { IDebuggerContribution, IDebugSession } from 'vs/workbench/contrib/debug/common/debug';\n" ], "file_path": "src/vs/workbench/contrib/debug/common/debugUtils.ts", "type": "replace", "edit_start_line_idx": 6 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as nls from 'vs/nls'; import { Event, Emitter } from 'vs/base/common/event'; import { URI as uri } from 'vs/base/common/uri'; import { first, distinct } from 'vs/base/common/arrays'; import * as errors from 'vs/base/common/errors'; import severity from 'vs/base/common/severity'; import * as aria from 'vs/base/browser/ui/aria/aria'; import { IContextKeyService, IContextKey } from 'vs/platform/contextkey/common/contextkey'; import { IMarkerService } from 'vs/platform/markers/common/markers'; import { ILifecycleService } from 'vs/platform/lifecycle/common/lifecycle'; import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { FileChangesEvent, FileChangeType, IFileService } from 'vs/platform/files/common/files'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage'; import { DebugModel, ExceptionBreakpoint, FunctionBreakpoint, Breakpoint, Expression, DataBreakpoint } from 'vs/workbench/contrib/debug/common/debugModel'; import { ViewModel } from 'vs/workbench/contrib/debug/common/debugViewModel'; import * as debugactions from 'vs/workbench/contrib/debug/browser/debugActions'; import { ConfigurationManager } from 'vs/workbench/contrib/debug/browser/debugConfigurationManager'; import Constants from 'vs/workbench/contrib/markers/browser/constants'; import { ITaskService, ITaskSummary } from 'vs/workbench/contrib/tasks/common/taskService'; import { VIEWLET_ID as EXPLORER_VIEWLET_ID } from 'vs/workbench/contrib/files/common/files'; import { IViewletService } from 'vs/workbench/services/viewlet/browser/viewlet'; import { IPanelService } from 'vs/workbench/services/panel/common/panelService'; import { IWorkbenchLayoutService, Parts } from 'vs/workbench/services/layout/browser/layoutService'; import { ITextFileService } from 'vs/workbench/services/textfile/common/textfiles'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IWorkspaceContextService, WorkbenchState, IWorkspaceFolder, IWorkspace } from 'vs/platform/workspace/common/workspace'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { parse, getFirstFrame } from 'vs/base/common/console'; import { TaskEvent, TaskEventKind, TaskIdentifier } from 'vs/workbench/contrib/tasks/common/tasks'; import { IDialogService } from 'vs/platform/dialogs/common/dialogs'; import { INotificationService } from 'vs/platform/notification/common/notification'; import { IAction } from 'vs/base/common/actions'; import { deepClone, equals } from 'vs/base/common/objects'; import { DebugSession } from 'vs/workbench/contrib/debug/browser/debugSession'; import { dispose, IDisposable } from 'vs/base/common/lifecycle'; import { IDebugService, State, IDebugSession, CONTEXT_DEBUG_TYPE, CONTEXT_DEBUG_STATE, CONTEXT_IN_DEBUG_MODE, IThread, IDebugConfiguration, VIEWLET_ID, REPL_ID, IConfig, ILaunch, IViewModel, IConfigurationManager, IDebugModel, IEnablement, IBreakpoint, IBreakpointData, ICompound, IGlobalConfig, IStackFrame, AdapterEndEvent, getStateLabel, IDebugSessionOptions, CONTEXT_DEBUG_UX } from 'vs/workbench/contrib/debug/common/debug'; import { isExtensionHostDebugging } from 'vs/workbench/contrib/debug/common/debugUtils'; import { isErrorWithActions, createErrorWithActions } from 'vs/base/common/errorsWithActions'; import { RunOnceScheduler } from 'vs/base/common/async'; import { IExtensionHostDebugService } from 'vs/platform/debug/common/extensionHostDebug'; import { isCodeEditor } from 'vs/editor/browser/editorBrowser'; import { CancellationTokenSource } from 'vs/base/common/cancellation'; import { withUndefinedAsNull } from 'vs/base/common/types'; const DEBUG_BREAKPOINTS_KEY = 'debug.breakpoint'; const DEBUG_FUNCTION_BREAKPOINTS_KEY = 'debug.functionbreakpoint'; const DEBUG_DATA_BREAKPOINTS_KEY = 'debug.databreakpoint'; const DEBUG_EXCEPTION_BREAKPOINTS_KEY = 'debug.exceptionbreakpoint'; const DEBUG_WATCH_EXPRESSIONS_KEY = 'debug.watchexpressions'; function once(match: (e: TaskEvent) => boolean, event: Event<TaskEvent>): Event<TaskEvent> { return (listener, thisArgs = null, disposables?) => { const result = event(e => { if (match(e)) { result.dispose(); return listener.call(thisArgs, e); } }, null, disposables); return result; }; } const enum TaskRunResult { Failure, Success } export class DebugService implements IDebugService { _serviceBrand: undefined; private readonly _onDidChangeState: Emitter<State>; private readonly _onDidNewSession: Emitter<IDebugSession>; private readonly _onWillNewSession: Emitter<IDebugSession>; private readonly _onDidEndSession: Emitter<IDebugSession>; private model: DebugModel; private viewModel: ViewModel; private configurationManager: ConfigurationManager; private toDispose: IDisposable[]; private debugType: IContextKey<string>; private debugState: IContextKey<string>; private inDebugMode: IContextKey<boolean>; private debugUx: IContextKey<string>; private breakpointsToSendOnResourceSaved: Set<string>; private initializing = false; private previousState: State | undefined; private initCancellationToken: CancellationTokenSource | undefined; constructor( @IStorageService private readonly storageService: IStorageService, @IEditorService private readonly editorService: IEditorService, @ITextFileService private readonly textFileService: ITextFileService, @IViewletService private readonly viewletService: IViewletService, @IPanelService private readonly panelService: IPanelService, @INotificationService private readonly notificationService: INotificationService, @IDialogService private readonly dialogService: IDialogService, @IWorkbenchLayoutService private readonly layoutService: IWorkbenchLayoutService, @ITelemetryService private readonly telemetryService: ITelemetryService, @IWorkspaceContextService private readonly contextService: IWorkspaceContextService, @IContextKeyService contextKeyService: IContextKeyService, @ILifecycleService private readonly lifecycleService: ILifecycleService, @IInstantiationService private readonly instantiationService: IInstantiationService, @IExtensionService private readonly extensionService: IExtensionService, @IMarkerService private readonly markerService: IMarkerService, @ITaskService private readonly taskService: ITaskService, @IFileService private readonly fileService: IFileService, @IConfigurationService private readonly configurationService: IConfigurationService, @IExtensionHostDebugService private readonly extensionHostDebugService: IExtensionHostDebugService ) { this.toDispose = []; this.breakpointsToSendOnResourceSaved = new Set<string>(); this._onDidChangeState = new Emitter<State>(); this._onDidNewSession = new Emitter<IDebugSession>(); this._onWillNewSession = new Emitter<IDebugSession>(); this._onDidEndSession = new Emitter<IDebugSession>(); this.configurationManager = this.instantiationService.createInstance(ConfigurationManager); this.toDispose.push(this.configurationManager); this.debugType = CONTEXT_DEBUG_TYPE.bindTo(contextKeyService); this.debugState = CONTEXT_DEBUG_STATE.bindTo(contextKeyService); this.inDebugMode = CONTEXT_IN_DEBUG_MODE.bindTo(contextKeyService); this.debugUx = CONTEXT_DEBUG_UX.bindTo(contextKeyService); this.debugUx.set(!!this.configurationManager.selectedConfiguration.name ? 'default' : 'simple'); this.model = new DebugModel(this.loadBreakpoints(), this.loadFunctionBreakpoints(), this.loadExceptionBreakpoints(), this.loadDataBreakpoints(), this.loadWatchExpressions(), this.textFileService); this.toDispose.push(this.model); this.viewModel = new ViewModel(contextKeyService); this.toDispose.push(this.fileService.onFileChanges(e => this.onFileChanges(e))); this.lifecycleService.onShutdown(this.dispose, this); this.toDispose.push(this.extensionHostDebugService.onAttachSession(event => { const session = this.model.getSession(event.sessionId, true); if (session) { // EH was started in debug mode -> attach to it session.configuration.request = 'attach'; session.configuration.port = event.port; session.setSubId(event.subId); this.launchOrAttachToSession(session); } })); this.toDispose.push(this.extensionHostDebugService.onTerminateSession(event => { const session = this.model.getSession(event.sessionId); if (session && session.subId === event.subId) { session.disconnect(); } })); this.toDispose.push(this.extensionHostDebugService.onLogToSession(event => { const session = this.model.getSession(event.sessionId, true); if (session) { // extension logged output -> show it in REPL const sev = event.log.severity === 'warn' ? severity.Warning : event.log.severity === 'error' ? severity.Error : severity.Info; const { args, stack } = parse(event.log); const frame = !!stack ? getFirstFrame(stack) : undefined; session.logToRepl(sev, args, frame); } })); this.toDispose.push(this.viewModel.onDidFocusStackFrame(() => { this.onStateChange(); })); this.toDispose.push(this.viewModel.onDidFocusSession(() => { this.onStateChange(); })); this.toDispose.push(this.configurationManager.onDidSelectConfiguration(() => { this.debugUx.set(!!(this.state !== State.Inactive || this.configurationManager.selectedConfiguration.name) ? 'default' : 'simple'); })); } getModel(): IDebugModel { return this.model; } getViewModel(): IViewModel { return this.viewModel; } getConfigurationManager(): IConfigurationManager { return this.configurationManager; } sourceIsNotAvailable(uri: uri): void { this.model.sourceIsNotAvailable(uri); } dispose(): void { this.toDispose = dispose(this.toDispose); } //---- state management get state(): State { const focusedSession = this.viewModel.focusedSession; if (focusedSession) { return focusedSession.state; } return this.initializing ? State.Initializing : State.Inactive; } private startInitializingState() { if (!this.initializing) { this.initializing = true; this.onStateChange(); } } private endInitializingState() { if (this.initCancellationToken) { this.initCancellationToken.cancel(); this.initCancellationToken = undefined; } if (this.initializing) { this.initializing = false; this.onStateChange(); } } private onStateChange(): void { const state = this.state; if (this.previousState !== state) { this.debugState.set(getStateLabel(state)); this.inDebugMode.set(state !== State.Inactive); // Only show the simple ux if debug is not yet started and if no launch.json exists this.debugUx.set(((state !== State.Inactive && state !== State.Initializing) || this.configurationManager.selectedConfiguration.name) ? 'default' : 'simple'); this.previousState = state; this._onDidChangeState.fire(state); } } get onDidChangeState(): Event<State> { return this._onDidChangeState.event; } get onDidNewSession(): Event<IDebugSession> { return this._onDidNewSession.event; } get onWillNewSession(): Event<IDebugSession> { return this._onWillNewSession.event; } get onDidEndSession(): Event<IDebugSession> { return this._onDidEndSession.event; } //---- life cycle management /** * main entry point * properly manages compounds, checks for errors and handles the initializing state. */ async startDebugging(launch: ILaunch | undefined, configOrName?: IConfig | string, options?: IDebugSessionOptions): Promise<boolean> { this.startInitializingState(); try { // make sure to save all files and that the configuration is up to date await this.extensionService.activateByEvent('onDebug'); await this.editorService.saveAll(); await this.configurationService.reloadConfiguration(launch ? launch.workspace : undefined); await this.extensionService.whenInstalledExtensionsRegistered(); let config: IConfig | undefined; let compound: ICompound | undefined; if (!configOrName) { configOrName = this.configurationManager.selectedConfiguration.name; } if (typeof configOrName === 'string' && launch) { config = launch.getConfiguration(configOrName); compound = launch.getCompound(configOrName); const sessions = this.model.getSessions(); const alreadyRunningMessage = nls.localize('configurationAlreadyRunning', "There is already a debug configuration \"{0}\" running.", configOrName); if (sessions.some(s => s.configuration.name === configOrName && (!launch || !launch.workspace || !s.root || s.root.uri.toString() === launch.workspace.uri.toString()))) { throw new Error(alreadyRunningMessage); } if (compound && compound.configurations && sessions.some(p => compound!.configurations.indexOf(p.configuration.name) !== -1)) { throw new Error(alreadyRunningMessage); } } else if (typeof configOrName !== 'string') { config = configOrName; } if (compound) { // we are starting a compound debug, first do some error checking and than start each configuration in the compound if (!compound.configurations) { throw new Error(nls.localize({ key: 'compoundMustHaveConfigurations', comment: ['compound indicates a "compounds" configuration item', '"configurations" is an attribute and should not be localized'] }, "Compound must have \"configurations\" attribute set in order to start multiple configurations.")); } if (compound.preLaunchTask) { const taskResult = await this.runTaskAndCheckErrors(launch?.workspace || this.contextService.getWorkspace(), compound.preLaunchTask); if (taskResult === TaskRunResult.Failure) { this.endInitializingState(); return false; } } const values = await Promise.all(compound.configurations.map(configData => { const name = typeof configData === 'string' ? configData : configData.name; if (name === compound!.name) { return Promise.resolve(false); } let launchForName: ILaunch | undefined; if (typeof configData === 'string') { const launchesContainingName = this.configurationManager.getLaunches().filter(l => !!l.getConfiguration(name)); if (launchesContainingName.length === 1) { launchForName = launchesContainingName[0]; } else if (launch && launchesContainingName.length > 1 && launchesContainingName.indexOf(launch) >= 0) { // If there are multiple launches containing the configuration give priority to the configuration in the current launch launchForName = launch; } else { throw new Error(launchesContainingName.length === 0 ? nls.localize('noConfigurationNameInWorkspace', "Could not find launch configuration '{0}' in the workspace.", name) : nls.localize('multipleConfigurationNamesInWorkspace', "There are multiple launch configurations '{0}' in the workspace. Use folder name to qualify the configuration.", name)); } } else if (configData.folder) { const launchesMatchingConfigData = this.configurationManager.getLaunches().filter(l => l.workspace && l.workspace.name === configData.folder && !!l.getConfiguration(configData.name)); if (launchesMatchingConfigData.length === 1) { launchForName = launchesMatchingConfigData[0]; } else { throw new Error(nls.localize('noFolderWithName', "Can not find folder with name '{0}' for configuration '{1}' in compound '{2}'.", configData.folder, configData.name, compound!.name)); } } return this.createSession(launchForName, launchForName!.getConfiguration(name), options); })); const result = values.every(success => !!success); // Compound launch is a success only if each configuration launched successfully this.endInitializingState(); return result; } if (configOrName && !config) { const message = !!launch ? nls.localize('configMissing', "Configuration '{0}' is missing in 'launch.json'.", typeof configOrName === 'string' ? configOrName : JSON.stringify(configOrName)) : nls.localize('launchJsonDoesNotExist', "'launch.json' does not exist."); throw new Error(message); } const result = await this.createSession(launch, config, options); this.endInitializingState(); return result; } catch (err) { // make sure to get out of initializing state, and propagate the result this.endInitializingState(); return Promise.reject(err); } } /** * gets the debugger for the type, resolves configurations by providers, substitutes variables and runs prelaunch tasks */ private async createSession(launch: ILaunch | undefined, config: IConfig | undefined, options?: IDebugSessionOptions): Promise<boolean> { // We keep the debug type in a separate variable 'type' so that a no-folder config has no attributes. // Storing the type in the config would break extensions that assume that the no-folder case is indicated by an empty config. let type: string | undefined; if (config) { type = config.type; } else { // a no-folder workspace has no launch.config config = Object.create(null); } const unresolvedConfig = deepClone(config); if (options && options.noDebug) { config!.noDebug = true; } if (!type) { const guess = await this.configurationManager.guessDebugger(); if (guess) { type = guess.type; } } this.initCancellationToken = new CancellationTokenSource(); const configByProviders = await this.configurationManager.resolveConfigurationByProviders(launch && launch.workspace ? launch.workspace.uri : undefined, type, config!, this.initCancellationToken.token); // a falsy config indicates an aborted launch if (configByProviders && configByProviders.type) { try { const resolvedConfig = await this.substituteVariables(launch, configByProviders); if (!resolvedConfig) { // User canceled resolving of interactive variables, silently return return false; } if (!this.configurationManager.getDebugger(resolvedConfig.type) || (configByProviders.request !== 'attach' && configByProviders.request !== 'launch')) { let message: string; if (configByProviders.request !== 'attach' && configByProviders.request !== 'launch') { message = configByProviders.request ? nls.localize('debugRequestNotSupported', "Attribute '{0}' has an unsupported value '{1}' in the chosen debug configuration.", 'request', configByProviders.request) : nls.localize('debugRequesMissing', "Attribute '{0}' is missing from the chosen debug configuration.", 'request'); } else { message = resolvedConfig.type ? nls.localize('debugTypeNotSupported', "Configured debug type '{0}' is not supported.", resolvedConfig.type) : nls.localize('debugTypeMissing', "Missing property 'type' for the chosen launch configuration."); } await this.showError(message); return false; } const workspace = launch ? launch.workspace : this.contextService.getWorkspace(); const taskResult = await this.runTaskAndCheckErrors(workspace, resolvedConfig.preLaunchTask); if (taskResult === TaskRunResult.Success) { return this.doCreateSession(launch?.workspace, { resolved: resolvedConfig, unresolved: unresolvedConfig }, options); } return false; } catch (err) { if (err && err.message) { await this.showError(err.message); } else if (this.contextService.getWorkbenchState() === WorkbenchState.EMPTY) { await this.showError(nls.localize('noFolderWorkspaceDebugError', "The active file can not be debugged. Make sure it is saved and that you have a debug extension installed for that file type.")); } if (launch) { await launch.openConfigFile(false, true, undefined, this.initCancellationToken ? this.initCancellationToken.token : undefined); } return false; } } if (launch && type && configByProviders === null) { // show launch.json only for "config" being "null". await launch.openConfigFile(false, true, type, this.initCancellationToken ? this.initCancellationToken.token : undefined); } return false; } /** * instantiates the new session, initializes the session, registers session listeners and reports telemetry */ private async doCreateSession(root: IWorkspaceFolder | undefined, configuration: { resolved: IConfig, unresolved: IConfig | undefined }, options?: IDebugSessionOptions): Promise<boolean> { const session = this.instantiationService.createInstance(DebugSession, configuration, root, this.model, options); this.model.addSession(session); // register listeners as the very first thing! this.registerSessionListeners(session); // since the Session is now properly registered under its ID and hooked, we can announce it // this event doesn't go to extensions this._onWillNewSession.fire(session); const openDebug = this.configurationService.getValue<IDebugConfiguration>('debug').openDebug; // Open debug viewlet based on the visibility of the side bar and openDebug setting. Do not open for 'run without debug' if (!configuration.resolved.noDebug && (openDebug === 'openOnSessionStart' || (openDebug === 'openOnFirstSessionStart' && this.viewModel.firstSessionStart))) { await this.viewletService.openViewlet(VIEWLET_ID); } try { await this.launchOrAttachToSession(session); const internalConsoleOptions = session.configuration.internalConsoleOptions || this.configurationService.getValue<IDebugConfiguration>('debug').internalConsoleOptions; if (internalConsoleOptions === 'openOnSessionStart' || (this.viewModel.firstSessionStart && internalConsoleOptions === 'openOnFirstSessionStart')) { this.panelService.openPanel(REPL_ID, false); } this.viewModel.firstSessionStart = false; const showSubSessions = this.configurationService.getValue<IDebugConfiguration>('debug').showSubSessionsInToolBar; const sessions = this.model.getSessions(); const shownSessions = showSubSessions ? sessions : sessions.filter(s => !s.parentSession); if (shownSessions.length > 1) { this.viewModel.setMultiSessionView(true); } // since the initialized response has arrived announce the new Session (including extensions) this._onDidNewSession.fire(session); await this.telemetryDebugSessionStart(root, session.configuration.type); return true; } catch (error) { if (errors.isPromiseCanceledError(error)) { // don't show 'canceled' error messages to the user #7906 return false; } // Show the repl if some error got logged there #5870 if (session && session.getReplElements().length > 0) { this.panelService.openPanel(REPL_ID, false); } if (session.configuration && session.configuration.request === 'attach' && session.configuration.__autoAttach) { // ignore attach timeouts in auto attach mode return false; } const errorMessage = error instanceof Error ? error.message : error; await this.showError(errorMessage, isErrorWithActions(error) ? error.actions : []); return false; } } private async launchOrAttachToSession(session: IDebugSession, forceFocus = false): Promise<void> { const dbgr = this.configurationManager.getDebugger(session.configuration.type); try { await session.initialize(dbgr!); await session.launchOrAttach(session.configuration); if (forceFocus || !this.viewModel.focusedSession) { await this.focusStackFrame(undefined, undefined, session); } } catch (err) { session.shutdown(); return Promise.reject(err); } } private registerSessionListeners(session: IDebugSession): void { const sessionRunningScheduler = new RunOnceScheduler(() => { // Do not immediatly defocus the stack frame if the session is running if (session.state === State.Running && this.viewModel.focusedSession === session) { this.viewModel.setFocus(undefined, this.viewModel.focusedThread, session, false); } }, 200); this.toDispose.push(session.onDidChangeState(() => { if (session.state === State.Running && this.viewModel.focusedSession === session) { sessionRunningScheduler.schedule(); } if (session === this.viewModel.focusedSession) { this.onStateChange(); } })); this.toDispose.push(session.onDidEndAdapter(async adapterExitEvent => { if (adapterExitEvent.error) { this.notificationService.error(nls.localize('debugAdapterCrash', "Debug adapter process has terminated unexpectedly ({0})", adapterExitEvent.error.message || adapterExitEvent.error.toString())); } // 'Run without debugging' mode VSCode must terminate the extension host. More details: #3905 if (isExtensionHostDebugging(session.configuration) && session.state === State.Running && session.configuration.noDebug) { this.extensionHostDebugService.close(session.getId()); } this.telemetryDebugSessionStop(session, adapterExitEvent); if (session.configuration.postDebugTask) { try { await this.runTask(session.root, session.configuration.postDebugTask); } catch (err) { this.notificationService.error(err); } } session.shutdown(); this.endInitializingState(); this._onDidEndSession.fire(session); const focusedSession = this.viewModel.focusedSession; if (focusedSession && focusedSession.getId() === session.getId()) { await this.focusStackFrame(undefined); } if (this.model.getSessions().length === 0) { this.viewModel.setMultiSessionView(false); if (this.layoutService.isVisible(Parts.SIDEBAR_PART) && this.configurationService.getValue<IDebugConfiguration>('debug').openExplorerOnEnd) { this.viewletService.openViewlet(EXPLORER_VIEWLET_ID); } // Data breakpoints that can not be persisted should be cleared when a session ends const dataBreakpoints = this.model.getDataBreakpoints().filter(dbp => !dbp.canPersist); dataBreakpoints.forEach(dbp => this.model.removeDataBreakpoints(dbp.getId())); } })); } async restartSession(session: IDebugSession, restartData?: any): Promise<any> { await this.editorService.saveAll(); const isAutoRestart = !!restartData; const runTasks: () => Promise<TaskRunResult> = async () => { if (isAutoRestart) { // Do not run preLaunch and postDebug tasks for automatic restarts return Promise.resolve(TaskRunResult.Success); } await this.runTask(session.root, session.configuration.postDebugTask); return this.runTaskAndCheckErrors(session.root, session.configuration.preLaunchTask); }; if (isExtensionHostDebugging(session.configuration)) { const taskResult = await runTasks(); if (taskResult === TaskRunResult.Success) { this.extensionHostDebugService.reload(session.getId()); } return; } if (session.capabilities.supportsRestartRequest) { const taskResult = await runTasks(); if (taskResult === TaskRunResult.Success) { await session.restart(); } return; } const shouldFocus = !!this.viewModel.focusedSession && session.getId() === this.viewModel.focusedSession.getId(); // If the restart is automatic -> disconnect, otherwise -> terminate #55064 if (isAutoRestart) { await session.disconnect(true); } else { await session.terminate(true); } return new Promise<void>((c, e) => { setTimeout(async () => { const taskResult = await runTasks(); if (taskResult !== TaskRunResult.Success) { return; } // Read the configuration again if a launch.json has been changed, if not just use the inmemory configuration let needsToSubstitute = false; let unresolved: IConfig | undefined; const launch = session.root ? this.configurationManager.getLaunch(session.root.uri) : undefined; if (launch) { unresolved = launch.getConfiguration(session.configuration.name); if (unresolved && !equals(unresolved, session.unresolvedConfiguration)) { // Take the type from the session since the debug extension might overwrite it #21316 unresolved.type = session.configuration.type; unresolved.noDebug = session.configuration.noDebug; needsToSubstitute = true; } } let resolved: IConfig | undefined | null = session.configuration; if (launch && needsToSubstitute && unresolved) { this.initCancellationToken = new CancellationTokenSource(); const resolvedByProviders = await this.configurationManager.resolveConfigurationByProviders(launch.workspace ? launch.workspace.uri : undefined, unresolved.type, unresolved, this.initCancellationToken.token); if (resolvedByProviders) { resolved = await this.substituteVariables(launch, resolvedByProviders); } else { resolved = resolvedByProviders; } } if (!resolved) { return c(undefined); } session.setConfiguration({ resolved, unresolved }); session.configuration.__restart = restartData; try { await this.launchOrAttachToSession(session, shouldFocus); this._onDidNewSession.fire(session); c(undefined); } catch (error) { e(error); } }, 300); }); } stopSession(session: IDebugSession): Promise<any> { if (session) { return session.terminate(); } const sessions = this.model.getSessions(); if (sessions.length === 0) { this.endInitializingState(); } return Promise.all(sessions.map(s => s.terminate())); } private async substituteVariables(launch: ILaunch | undefined, config: IConfig): Promise<IConfig | undefined> { const dbg = this.configurationManager.getDebugger(config.type); if (dbg) { let folder: IWorkspaceFolder | undefined = undefined; if (launch && launch.workspace) { folder = launch.workspace; } else { const folders = this.contextService.getWorkspace().folders; if (folders.length === 1) { folder = folders[0]; } } try { return await dbg.substituteVariables(folder, config); } catch (err) { this.showError(err.message); return undefined; // bail out } } return Promise.resolve(config); } private async showError(message: string, errorActions: ReadonlyArray<IAction> = []): Promise<void> { const configureAction = this.instantiationService.createInstance(debugactions.ConfigureAction, debugactions.ConfigureAction.ID, debugactions.ConfigureAction.LABEL); const actions = [...errorActions, configureAction]; const { choice } = await this.dialogService.show(severity.Error, message, actions.map(a => a.label).concat(nls.localize('cancel', "Cancel")), { cancelId: actions.length }); if (choice < actions.length) { return actions[choice].run(); } return undefined; } //---- task management private async runTaskAndCheckErrors(root: IWorkspaceFolder | IWorkspace | undefined, taskId: string | TaskIdentifier | undefined): Promise<TaskRunResult> { try { const taskSummary = await this.runTask(root, taskId); const errorCount = taskId ? this.markerService.getStatistics().errors : 0; const successExitCode = taskSummary && taskSummary.exitCode === 0; const failureExitCode = taskSummary && taskSummary.exitCode !== 0; const onTaskErrors = this.configurationService.getValue<IDebugConfiguration>('debug').onTaskErrors; if (successExitCode || onTaskErrors === 'debugAnyway' || (errorCount === 0 && !failureExitCode)) { return TaskRunResult.Success; } if (onTaskErrors === 'showErrors') { this.panelService.openPanel(Constants.MARKERS_PANEL_ID); return Promise.resolve(TaskRunResult.Failure); } const taskLabel = typeof taskId === 'string' ? taskId : taskId ? taskId.name : ''; const message = errorCount > 1 ? nls.localize('preLaunchTaskErrors', "Errors exist after running preLaunchTask '{0}'.", taskLabel) : errorCount === 1 ? nls.localize('preLaunchTaskError', "Error exists after running preLaunchTask '{0}'.", taskLabel) : nls.localize('preLaunchTaskExitCode', "The preLaunchTask '{0}' terminated with exit code {1}.", taskLabel, taskSummary ? taskSummary.exitCode : 0); const result = await this.dialogService.show(severity.Warning, message, [nls.localize('debugAnyway', "Debug Anyway"), nls.localize('showErrors', "Show Errors"), nls.localize('cancel', "Cancel")], { checkbox: { label: nls.localize('remember', "Remember my choice in user settings"), }, cancelId: 2 }); if (result.choice === 2) { return Promise.resolve(TaskRunResult.Failure); } const debugAnyway = result.choice === 0; if (result.checkboxChecked) { this.configurationService.updateValue('debug.onTaskErrors', debugAnyway ? 'debugAnyway' : 'showErrors'); } if (debugAnyway) { return TaskRunResult.Success; } this.panelService.openPanel(Constants.MARKERS_PANEL_ID); return Promise.resolve(TaskRunResult.Failure); } catch (err) { await this.showError(err.message, [this.taskService.configureAction()]); return TaskRunResult.Failure; } } private async runTask(root: IWorkspace | IWorkspaceFolder | undefined, taskId: string | TaskIdentifier | undefined): Promise<ITaskSummary | null> { if (!taskId) { return Promise.resolve(null); } if (!root) { return Promise.reject(new Error(nls.localize('invalidTaskReference', "Task '{0}' can not be referenced from a launch configuration that is in a different workspace folder.", typeof taskId === 'string' ? taskId : taskId.type))); } // run a task before starting a debug session const task = await this.taskService.getTask(root, taskId); if (!task) { const errorMessage = typeof taskId === 'string' ? nls.localize('DebugTaskNotFoundWithTaskId', "Could not find the task '{0}'.", taskId) : nls.localize('DebugTaskNotFound', "Could not find the specified task."); return Promise.reject(createErrorWithActions(errorMessage)); } // If a task is missing the problem matcher the promise will never complete, so we need to have a workaround #35340 let taskStarted = false; const inactivePromise: Promise<ITaskSummary | null> = new Promise((c, e) => once(e => { // When a task isBackground it will go inactive when it is safe to launch. // But when a background task is terminated by the user, it will also fire an inactive event. // This means that we will not get to see the real exit code from running the task (undefined when terminated by the user). // Catch the ProcessEnded event here, which occurs before inactive, and capture the exit code to prevent this. return (e.kind === TaskEventKind.Inactive || (e.kind === TaskEventKind.ProcessEnded && e.exitCode === undefined)) && e.taskId === task._id; }, this.taskService.onDidStateChange)(e => { taskStarted = true; c(e.kind === TaskEventKind.ProcessEnded ? { exitCode: e.exitCode } : null); })); const promise: Promise<ITaskSummary | null> = this.taskService.getActiveTasks().then(async (tasks): Promise<ITaskSummary | null> => { if (tasks.filter(t => t._id === task._id).length) { // Check that the task isn't busy and if it is, wait for it const busyTasks = await this.taskService.getBusyTasks(); if (busyTasks.filter(t => t._id === task._id).length) { taskStarted = true; return inactivePromise; } // task is already running and isn't busy - nothing to do. return Promise.resolve(null); } once(e => ((e.kind === TaskEventKind.Active) || (e.kind === TaskEventKind.DependsOnStarted)) && e.taskId === task._id, this.taskService.onDidStateChange)(() => { // Task is active, so everything seems to be fine, no need to prompt after 10 seconds // Use case being a slow running task should not be prompted even though it takes more than 10 seconds taskStarted = true; }); const taskPromise = this.taskService.run(task); if (task.configurationProperties.isBackground) { return inactivePromise; } return taskPromise.then(withUndefinedAsNull); }); return new Promise((c, e) => { promise.then(result => { taskStarted = true; c(result); }, error => e(error)); setTimeout(() => { if (!taskStarted) { const errorMessage = typeof taskId === 'string' ? nls.localize('taskNotTrackedWithTaskId', "The specified task cannot be tracked.") : nls.localize('taskNotTracked', "The task '{0}' cannot be tracked.", JSON.stringify(taskId)); e({ severity: severity.Error, message: errorMessage }); } }, 10000); }); } //---- focus management async focusStackFrame(stackFrame: IStackFrame | undefined, thread?: IThread, session?: IDebugSession, explicit?: boolean): Promise<void> { if (!session) { if (stackFrame || thread) { session = stackFrame ? stackFrame.thread.session : thread!.session; } else { const sessions = this.model.getSessions(); const stoppedSession = sessions.filter(s => s.state === State.Stopped).shift(); session = stoppedSession || (sessions.length ? sessions[0] : undefined); } } if (!thread) { if (stackFrame) { thread = stackFrame.thread; } else { const threads = session ? session.getAllThreads() : undefined; const stoppedThread = threads && threads.filter(t => t.stopped).shift(); thread = stoppedThread || (threads && threads.length ? threads[0] : undefined); } } if (!stackFrame) { if (thread) { const callStack = thread.getCallStack(); stackFrame = first(callStack, sf => !!(sf && sf.source && sf.source.available && sf.source.presentationHint !== 'deemphasize'), undefined); } } if (stackFrame) { const editor = await stackFrame.openInEditor(this.editorService, true); if (editor) { const control = editor.getControl(); if (stackFrame && isCodeEditor(control) && control.hasModel()) { const model = control.getModel(); if (stackFrame.range.startLineNumber <= model.getLineCount()) { const lineContent = control.getModel().getLineContent(stackFrame.range.startLineNumber); aria.alert(nls.localize('debuggingPaused', "Debugging paused {0}, {1} {2} {3}", thread && thread.stoppedDetails ? `, reason ${thread.stoppedDetails.reason}` : '', stackFrame.source ? stackFrame.source.name : '', stackFrame.range.startLineNumber, lineContent)); } } } } if (session) { this.debugType.set(session.configuration.type); } else { this.debugType.reset(); } this.viewModel.setFocus(stackFrame, thread, session, !!explicit); } //---- watches addWatchExpression(name: string): void { const we = this.model.addWatchExpression(name); this.viewModel.setSelectedExpression(we); this.storeWatchExpressions(); } renameWatchExpression(id: string, newName: string): void { this.model.renameWatchExpression(id, newName); this.storeWatchExpressions(); } moveWatchExpression(id: string, position: number): void { this.model.moveWatchExpression(id, position); this.storeWatchExpressions(); } removeWatchExpressions(id?: string): void { this.model.removeWatchExpressions(id); this.storeWatchExpressions(); } //---- breakpoints async enableOrDisableBreakpoints(enable: boolean, breakpoint?: IEnablement): Promise<void> { if (breakpoint) { this.model.setEnablement(breakpoint, enable); if (breakpoint instanceof Breakpoint) { await this.sendBreakpoints(breakpoint.uri); } else if (breakpoint instanceof FunctionBreakpoint) { await this.sendFunctionBreakpoints(); } else if (breakpoint instanceof DataBreakpoint) { await this.sendDataBreakpoints(); } else { await this.sendExceptionBreakpoints(); } } else { this.model.enableOrDisableAllBreakpoints(enable); await this.sendAllBreakpoints(); } this.storeBreakpoints(); } async addBreakpoints(uri: uri, rawBreakpoints: IBreakpointData[], context: string): Promise<IBreakpoint[]> { const breakpoints = this.model.addBreakpoints(uri, rawBreakpoints); breakpoints.forEach(bp => aria.status(nls.localize('breakpointAdded', "Added breakpoint, line {0}, file {1}", bp.lineNumber, uri.fsPath))); breakpoints.forEach(bp => this.telemetryDebugAddBreakpoint(bp, context)); await this.sendBreakpoints(uri); this.storeBreakpoints(); return breakpoints; } async updateBreakpoints(uri: uri, data: Map<string, DebugProtocol.Breakpoint>, sendOnResourceSaved: boolean): Promise<void> { this.model.updateBreakpoints(data); if (sendOnResourceSaved) { this.breakpointsToSendOnResourceSaved.add(uri.toString()); } else { await this.sendBreakpoints(uri); } this.storeBreakpoints(); } async removeBreakpoints(id?: string): Promise<void> { const toRemove = this.model.getBreakpoints().filter(bp => !id || bp.getId() === id); toRemove.forEach(bp => aria.status(nls.localize('breakpointRemoved', "Removed breakpoint, line {0}, file {1}", bp.lineNumber, bp.uri.fsPath))); const urisToClear = distinct(toRemove, bp => bp.uri.toString()).map(bp => bp.uri); this.model.removeBreakpoints(toRemove); await Promise.all(urisToClear.map(uri => this.sendBreakpoints(uri))); this.storeBreakpoints(); } setBreakpointsActivated(activated: boolean): Promise<void> { this.model.setBreakpointsActivated(activated); return this.sendAllBreakpoints(); } addFunctionBreakpoint(name?: string, id?: string): void { const newFunctionBreakpoint = this.model.addFunctionBreakpoint(name || '', id); this.viewModel.setSelectedFunctionBreakpoint(newFunctionBreakpoint); } async renameFunctionBreakpoint(id: string, newFunctionName: string): Promise<void> { this.model.renameFunctionBreakpoint(id, newFunctionName); await this.sendFunctionBreakpoints(); this.storeBreakpoints(); } async removeFunctionBreakpoints(id?: string): Promise<void> { this.model.removeFunctionBreakpoints(id); await this.sendFunctionBreakpoints(); this.storeBreakpoints(); } async addDataBreakpoint(label: string, dataId: string, canPersist: boolean): Promise<void> { this.model.addDataBreakpoint(label, dataId, canPersist); await this.sendDataBreakpoints(); this.storeBreakpoints(); } async removeDataBreakpoints(id?: string): Promise<void> { this.model.removeDataBreakpoints(id); await this.sendDataBreakpoints(); this.storeBreakpoints(); } async sendAllBreakpoints(session?: IDebugSession): Promise<any> { await Promise.all(distinct(this.model.getBreakpoints(), bp => bp.uri.toString()).map(bp => this.sendBreakpoints(bp.uri, false, session))); await this.sendFunctionBreakpoints(session); await this.sendDataBreakpoints(session); // send exception breakpoints at the end since some debug adapters rely on the order await this.sendExceptionBreakpoints(session); } private sendBreakpoints(modelUri: uri, sourceModified = false, session?: IDebugSession): Promise<void> { const breakpointsToSend = this.model.getBreakpoints({ uri: modelUri, enabledOnly: true }); return this.sendToOneOrAllSessions(session, s => s.sendBreakpoints(modelUri, breakpointsToSend, sourceModified) ); } private sendFunctionBreakpoints(session?: IDebugSession): Promise<void> { const breakpointsToSend = this.model.getFunctionBreakpoints().filter(fbp => fbp.enabled && this.model.areBreakpointsActivated()); return this.sendToOneOrAllSessions(session, s => { return s.capabilities.supportsFunctionBreakpoints ? s.sendFunctionBreakpoints(breakpointsToSend) : Promise.resolve(undefined); }); } private sendDataBreakpoints(session?: IDebugSession): Promise<void> { const breakpointsToSend = this.model.getDataBreakpoints().filter(fbp => fbp.enabled && this.model.areBreakpointsActivated()); return this.sendToOneOrAllSessions(session, s => { return s.capabilities.supportsDataBreakpoints ? s.sendDataBreakpoints(breakpointsToSend) : Promise.resolve(undefined); }); } private sendExceptionBreakpoints(session?: IDebugSession): Promise<void> { const enabledExceptionBps = this.model.getExceptionBreakpoints().filter(exb => exb.enabled); return this.sendToOneOrAllSessions(session, s => { return s.sendExceptionBreakpoints(enabledExceptionBps); }); } private async sendToOneOrAllSessions(session: IDebugSession | undefined, send: (session: IDebugSession) => Promise<void>): Promise<void> { if (session) { await send(session); } else { await Promise.all(this.model.getSessions().map(s => send(s))); } } private onFileChanges(fileChangesEvent: FileChangesEvent): void { const toRemove = this.model.getBreakpoints().filter(bp => fileChangesEvent.contains(bp.uri, FileChangeType.DELETED)); if (toRemove.length) { this.model.removeBreakpoints(toRemove); } fileChangesEvent.getUpdated().forEach(event => { if (this.breakpointsToSendOnResourceSaved.delete(event.resource.toString())) { this.sendBreakpoints(event.resource, true); } }); } private loadBreakpoints(): Breakpoint[] { let result: Breakpoint[] | undefined; try { result = JSON.parse(this.storageService.get(DEBUG_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((breakpoint: any) => { return new Breakpoint(uri.parse(breakpoint.uri.external || breakpoint.source.uri.external), breakpoint.lineNumber, breakpoint.column, breakpoint.enabled, breakpoint.condition, breakpoint.hitCondition, breakpoint.logMessage, breakpoint.adapterData, this.textFileService); }); } catch (e) { } return result || []; } private loadFunctionBreakpoints(): FunctionBreakpoint[] { let result: FunctionBreakpoint[] | undefined; try { result = JSON.parse(this.storageService.get(DEBUG_FUNCTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((fb: any) => { return new FunctionBreakpoint(fb.name, fb.enabled, fb.hitCondition, fb.condition, fb.logMessage); }); } catch (e) { } return result || []; } private loadExceptionBreakpoints(): ExceptionBreakpoint[] { let result: ExceptionBreakpoint[] | undefined; try { result = JSON.parse(this.storageService.get(DEBUG_EXCEPTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((exBreakpoint: any) => { return new ExceptionBreakpoint(exBreakpoint.filter, exBreakpoint.label, exBreakpoint.enabled); }); } catch (e) { } return result || []; } private loadDataBreakpoints(): DataBreakpoint[] { let result: DataBreakpoint[] | undefined; try { result = JSON.parse(this.storageService.get(DEBUG_DATA_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((dbp: any) => { return new DataBreakpoint(dbp.label, dbp.dataId, true, dbp.enabled, dbp.hitCondition, dbp.condition, dbp.logMessage); }); } catch (e) { } return result || []; } private loadWatchExpressions(): Expression[] { let result: Expression[] | undefined; try { result = JSON.parse(this.storageService.get(DEBUG_WATCH_EXPRESSIONS_KEY, StorageScope.WORKSPACE, '[]')).map((watchStoredData: { name: string, id: string }) => { return new Expression(watchStoredData.name, watchStoredData.id); }); } catch (e) { } return result || []; } private storeWatchExpressions(): void { const watchExpressions = this.model.getWatchExpressions(); if (watchExpressions.length) { this.storageService.store(DEBUG_WATCH_EXPRESSIONS_KEY, JSON.stringify(watchExpressions.map(we => ({ name: we.name, id: we.getId() }))), StorageScope.WORKSPACE); } else { this.storageService.remove(DEBUG_WATCH_EXPRESSIONS_KEY, StorageScope.WORKSPACE); } } private storeBreakpoints(): void { const breakpoints = this.model.getBreakpoints(); if (breakpoints.length) { this.storageService.store(DEBUG_BREAKPOINTS_KEY, JSON.stringify(breakpoints), StorageScope.WORKSPACE); } else { this.storageService.remove(DEBUG_BREAKPOINTS_KEY, StorageScope.WORKSPACE); } const functionBreakpoints = this.model.getFunctionBreakpoints(); if (functionBreakpoints.length) { this.storageService.store(DEBUG_FUNCTION_BREAKPOINTS_KEY, JSON.stringify(functionBreakpoints), StorageScope.WORKSPACE); } else { this.storageService.remove(DEBUG_FUNCTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE); } const dataBreakpoints = this.model.getDataBreakpoints().filter(dbp => dbp.canPersist); if (dataBreakpoints.length) { this.storageService.store(DEBUG_DATA_BREAKPOINTS_KEY, JSON.stringify(dataBreakpoints), StorageScope.WORKSPACE); } else { this.storageService.remove(DEBUG_DATA_BREAKPOINTS_KEY, StorageScope.WORKSPACE); } const exceptionBreakpoints = this.model.getExceptionBreakpoints(); if (exceptionBreakpoints.length) { this.storageService.store(DEBUG_EXCEPTION_BREAKPOINTS_KEY, JSON.stringify(exceptionBreakpoints), StorageScope.WORKSPACE); } else { this.storageService.remove(DEBUG_EXCEPTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE); } } //---- telemetry private telemetryDebugSessionStart(root: IWorkspaceFolder | undefined, type: string): Promise<void> { const dbgr = this.configurationManager.getDebugger(type); if (!dbgr) { return Promise.resolve(); } const extension = dbgr.getMainExtensionDescriptor(); /* __GDPR__ "debugSessionStart" : { "type": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "breakpointCount": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "exceptionBreakpoints": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "watchExpressionsCount": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "extensionName": { "classification": "PublicNonPersonalData", "purpose": "FeatureInsight" }, "isBuiltin": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true}, "launchJsonExists": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true } } */ return this.telemetryService.publicLog('debugSessionStart', { type: type, breakpointCount: this.model.getBreakpoints().length, exceptionBreakpoints: this.model.getExceptionBreakpoints(), watchExpressionsCount: this.model.getWatchExpressions().length, extensionName: extension.identifier.value, isBuiltin: extension.isBuiltin, launchJsonExists: root && !!this.configurationService.getValue<IGlobalConfig>('launch', { resource: root.uri }) }); } private telemetryDebugSessionStop(session: IDebugSession, adapterExitEvent: AdapterEndEvent): Promise<any> { const breakpoints = this.model.getBreakpoints(); /* __GDPR__ "debugSessionStop" : { "type" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "success": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "sessionLengthInSeconds": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "breakpointCount": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "watchExpressionsCount": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true } } */ return this.telemetryService.publicLog('debugSessionStop', { type: session && session.configuration.type, success: adapterExitEvent.emittedStopped || breakpoints.length === 0, sessionLengthInSeconds: adapterExitEvent.sessionLengthInSeconds, breakpointCount: breakpoints.length, watchExpressionsCount: this.model.getWatchExpressions().length }); } private telemetryDebugAddBreakpoint(breakpoint: IBreakpoint, context: string): Promise<any> { /* __GDPR__ "debugAddBreakpoint" : { "context": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "hasCondition": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "hasHitCondition": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "hasLogMessage": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true } } */ return this.telemetryService.publicLog('debugAddBreakpoint', { context: context, hasCondition: !!breakpoint.condition, hasHitCondition: !!breakpoint.hitCondition, hasLogMessage: !!breakpoint.logMessage }); } }
src/vs/workbench/contrib/debug/browser/debugService.ts
1
https://github.com/microsoft/vscode/commit/88e80b9a18b2cc3de0ca3a02977c3e2d4b088a60
[ 0.00022890834952704608, 0.00017090605979319662, 0.0001612756896065548, 0.0001713186502456665, 0.000006711228706990369 ]
{ "id": 4, "code_window": [ " * Licensed under the MIT License. See License.txt in the project root for license information.\n", " *--------------------------------------------------------------------------------------------*/\n", "\n", "import { equalsIgnoreCase } from 'vs/base/common/strings';\n", "import { IConfig, IDebuggerContribution, IDebugSession } from 'vs/workbench/contrib/debug/common/debug';\n", "import { URI as uri } from 'vs/base/common/uri';\n", "import { isAbsolute } from 'vs/base/common/path';\n", "import { deepClone } from 'vs/base/common/objects';\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { IDebuggerContribution, IDebugSession } from 'vs/workbench/contrib/debug/common/debug';\n" ], "file_path": "src/vs/workbench/contrib/debug/common/debugUtils.ts", "type": "replace", "edit_start_line_idx": 6 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as vscode from 'vscode'; export interface WebviewResourceProvider { asWebviewUri(resource: vscode.Uri): vscode.Uri; readonly cspSource: string; } export function normalizeResource( base: vscode.Uri, resource: vscode.Uri ): vscode.Uri { // If we have a windows path and are loading a workspace with an authority, // make sure we use a unc path with an explicit localhost authority. // // Otherwise, the `<base>` rule will insert the authority into the resolved resource // URI incorrectly. if (base.authority && !resource.authority) { const driveMatch = resource.path.match(/^\/(\w):\//); if (driveMatch) { return vscode.Uri.file(`\\\\localhost\\${driveMatch[1]}$\\${resource.fsPath.replace(/^\w:\\/, '')}`).with({ fragment: resource.fragment, query: resource.query }); } } return resource; }
extensions/markdown-language-features/src/util/resources.ts
0
https://github.com/microsoft/vscode/commit/88e80b9a18b2cc3de0ca3a02977c3e2d4b088a60
[ 0.0001738558494253084, 0.00016795496048871428, 0.0001621779811102897, 0.00016789298388175666, 0.000004302467459638137 ]
{ "id": 4, "code_window": [ " * Licensed under the MIT License. See License.txt in the project root for license information.\n", " *--------------------------------------------------------------------------------------------*/\n", "\n", "import { equalsIgnoreCase } from 'vs/base/common/strings';\n", "import { IConfig, IDebuggerContribution, IDebugSession } from 'vs/workbench/contrib/debug/common/debug';\n", "import { URI as uri } from 'vs/base/common/uri';\n", "import { isAbsolute } from 'vs/base/common/path';\n", "import { deepClone } from 'vs/base/common/objects';\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { IDebuggerContribution, IDebugSession } from 'vs/workbench/contrib/debug/common/debug';\n" ], "file_path": "src/vs/workbench/contrib/debug/common/debugUtils.ts", "type": "replace", "edit_start_line_idx": 6 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as assert from 'assert'; import * as vscode from 'vscode'; import { createRandomFile } from '../utils'; suite('workspace-event', () => { const disposables: vscode.Disposable[] = []; teardown(() => { for (const dispo of disposables) { dispo.dispose(); } disposables.length = 0; }); test('onWillCreate/onDidCreate', async function () { const base = await createRandomFile(); const newUri = base.with({ path: base.path + '-foo' }); let onWillCreate: vscode.FileWillCreateEvent | undefined; let onDidCreate: vscode.FileCreateEvent | undefined; disposables.push(vscode.workspace.onWillCreateFiles(e => onWillCreate = e)); disposables.push(vscode.workspace.onDidCreateFiles(e => onDidCreate = e)); const edit = new vscode.WorkspaceEdit(); edit.createFile(newUri); const success = await vscode.workspace.applyEdit(edit); assert.ok(success); assert.ok(onWillCreate); assert.equal(onWillCreate?.files.length, 1); assert.equal(onWillCreate?.files[0].toString(), newUri.toString()); assert.ok(onDidCreate); assert.equal(onDidCreate?.files.length, 1); assert.equal(onDidCreate?.files[0].toString(), newUri.toString()); }); test('onWillCreate/onDidCreate, make changes, edit another file', async function () { const base = await createRandomFile(); const baseDoc = await vscode.workspace.openTextDocument(base); const newUri = base.with({ path: base.path + '-foo' }); disposables.push(vscode.workspace.onWillCreateFiles(e => { const ws = new vscode.WorkspaceEdit(); ws.insert(base, new vscode.Position(0, 0), 'HALLO_NEW'); e.waitUntil(Promise.resolve(ws)); })); const edit = new vscode.WorkspaceEdit(); edit.createFile(newUri); const success = await vscode.workspace.applyEdit(edit); assert.ok(success); assert.equal(baseDoc.getText(), 'HALLO_NEW'); }); test('onWillCreate/onDidCreate, make changes, edit new file fails', async function () { const base = await createRandomFile(); const newUri = base.with({ path: base.path + '-foo' }); disposables.push(vscode.workspace.onWillCreateFiles(e => { const ws = new vscode.WorkspaceEdit(); ws.insert(e.files[0], new vscode.Position(0, 0), 'nope'); e.waitUntil(Promise.resolve(ws)); })); const edit = new vscode.WorkspaceEdit(); edit.createFile(newUri); const success = await vscode.workspace.applyEdit(edit); assert.ok(success); assert.equal((await vscode.workspace.fs.readFile(newUri)).toString(), ''); assert.equal((await vscode.workspace.openTextDocument(newUri)).getText(), ''); }); test('onWillDelete/onDidDelete', async function () { const base = await createRandomFile(); let onWilldelete: vscode.FileWillDeleteEvent | undefined; let onDiddelete: vscode.FileDeleteEvent | undefined; disposables.push(vscode.workspace.onWillDeleteFiles(e => onWilldelete = e)); disposables.push(vscode.workspace.onDidDeleteFiles(e => onDiddelete = e)); const edit = new vscode.WorkspaceEdit(); edit.deleteFile(base); const success = await vscode.workspace.applyEdit(edit); assert.ok(success); assert.ok(onWilldelete); assert.equal(onWilldelete?.files.length, 1); assert.equal(onWilldelete?.files[0].toString(), base.toString()); assert.ok(onDiddelete); assert.equal(onDiddelete?.files.length, 1); assert.equal(onDiddelete?.files[0].toString(), base.toString()); }); test('onWillDelete/onDidDelete, make changes', async function () { const base = await createRandomFile(); const newUri = base.with({ path: base.path + '-NEW' }); disposables.push(vscode.workspace.onWillDeleteFiles(e => { const edit = new vscode.WorkspaceEdit(); edit.createFile(newUri); edit.insert(newUri, new vscode.Position(0, 0), 'hahah'); e.waitUntil(Promise.resolve(edit)); })); const edit = new vscode.WorkspaceEdit(); edit.deleteFile(base); const success = await vscode.workspace.applyEdit(edit); assert.ok(success); }); test('onWillDelete/onDidDelete, make changes, del another file', async function () { const base = await createRandomFile(); const base2 = await createRandomFile(); disposables.push(vscode.workspace.onWillDeleteFiles(e => { if (e.files[0].toString() === base.toString()) { const edit = new vscode.WorkspaceEdit(); edit.deleteFile(base2); e.waitUntil(Promise.resolve(edit)); } })); const edit = new vscode.WorkspaceEdit(); edit.deleteFile(base); const success = await vscode.workspace.applyEdit(edit); assert.ok(success); }); test('onWillDelete/onDidDelete, make changes, double delete', async function () { const base = await createRandomFile(); let once = true; disposables.push(vscode.workspace.onWillDeleteFiles(e => { assert.ok(once); once = false; const edit = new vscode.WorkspaceEdit(); edit.deleteFile(e.files[0]); e.waitUntil(Promise.resolve(edit)); })); const edit = new vscode.WorkspaceEdit(); edit.deleteFile(base); const success = await vscode.workspace.applyEdit(edit); assert.ok(!success); }); test('onWillRename/onDidRename', async function () { const oldUri = await createRandomFile(); const newUri = oldUri.with({ path: oldUri.path + '-NEW' }); let onWillRename: vscode.FileWillRenameEvent | undefined; let onDidRename: vscode.FileRenameEvent | undefined; disposables.push(vscode.workspace.onWillRenameFiles(e => onWillRename = e)); disposables.push(vscode.workspace.onDidRenameFiles(e => onDidRename = e)); const edit = new vscode.WorkspaceEdit(); edit.renameFile(oldUri, newUri); const success = await vscode.workspace.applyEdit(edit); assert.ok(success); assert.ok(onWillRename); assert.equal(onWillRename?.files.length, 1); assert.equal(onWillRename?.files[0].oldUri.toString(), oldUri.toString()); assert.equal(onWillRename?.files[0].newUri.toString(), newUri.toString()); assert.ok(onDidRename); assert.equal(onDidRename?.files.length, 1); assert.equal(onDidRename?.files[0].oldUri.toString(), oldUri.toString()); assert.equal(onDidRename?.files[0].newUri.toString(), newUri.toString()); }); test('onWillRename - make changes', async function () { const oldUri = await createRandomFile('BAR'); const newUri = oldUri.with({ path: oldUri.path + '-NEW' }); const anotherFile = await createRandomFile('BAR'); let onWillRename: vscode.FileWillRenameEvent | undefined; disposables.push(vscode.workspace.onWillRenameFiles(e => { onWillRename = e; const edit = new vscode.WorkspaceEdit(); edit.insert(e.files[0].oldUri, new vscode.Position(0, 0), 'FOO'); edit.replace(anotherFile, new vscode.Range(0, 0, 0, 3), 'FARBOO'); e.waitUntil(Promise.resolve(edit)); })); const edit = new vscode.WorkspaceEdit(); edit.renameFile(oldUri, newUri); const success = await vscode.workspace.applyEdit(edit); assert.ok(success); assert.ok(onWillRename); assert.equal(onWillRename?.files.length, 1); assert.equal(onWillRename?.files[0].oldUri.toString(), oldUri.toString()); assert.equal(onWillRename?.files[0].newUri.toString(), newUri.toString()); assert.equal((await vscode.workspace.openTextDocument(newUri)).getText(), 'FOOBAR'); assert.equal((await vscode.workspace.openTextDocument(anotherFile)).getText(), 'FARBOO'); }); });
extensions/vscode-api-tests/src/singlefolder-tests/workspace.event.test.ts
0
https://github.com/microsoft/vscode/commit/88e80b9a18b2cc3de0ca3a02977c3e2d4b088a60
[ 0.0001781844621291384, 0.00017502431001048535, 0.00016533888992853463, 0.00017568541807122529, 0.0000028706826924462803 ]
{ "id": 4, "code_window": [ " * Licensed under the MIT License. See License.txt in the project root for license information.\n", " *--------------------------------------------------------------------------------------------*/\n", "\n", "import { equalsIgnoreCase } from 'vs/base/common/strings';\n", "import { IConfig, IDebuggerContribution, IDebugSession } from 'vs/workbench/contrib/debug/common/debug';\n", "import { URI as uri } from 'vs/base/common/uri';\n", "import { isAbsolute } from 'vs/base/common/path';\n", "import { deepClone } from 'vs/base/common/objects';\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { IDebuggerContribution, IDebugSession } from 'vs/workbench/contrib/debug/common/debug';\n" ], "file_path": "src/vs/workbench/contrib/debug/common/debugUtils.ts", "type": "replace", "edit_start_line_idx": 6 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ //@ts-check 'use strict'; const withDefaults = require('../../shared.webpack.config'); const path = require('path'); var webpack = require('webpack'); const config = withDefaults({ context: path.join(__dirname), entry: { extension: './src/jsonServerMain.ts', }, output: { filename: 'jsonServerMain.js', path: path.join(__dirname, 'dist') } }); // add plugin, don't replace inherited config.plugins.push(new webpack.IgnorePlugin(/vertx/)); // request-light dependency module.exports = config;
extensions/json-language-features/server/extension.webpack.config.js
0
https://github.com/microsoft/vscode/commit/88e80b9a18b2cc3de0ca3a02977c3e2d4b088a60
[ 0.0001717366831144318, 0.00016913836589083076, 0.00016566619160585105, 0.00017001223750412464, 0.0000025541403374518268 ]
{ "id": 5, "code_window": [ "\t});\n", "}\n", "\n", "export function isSessionAttach(session: IDebugSession): boolean {\n", "\treturn !session.parentSession && session.configuration.request === 'attach' && !isExtensionHostDebugging(session.configuration);\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ "\treturn !session.parentSession && session.configuration.request === 'attach' && !getExtensionHostDebugSession(session);\n" ], "file_path": "src/vs/workbench/contrib/debug/common/debugUtils.ts", "type": "replace", "edit_start_line_idx": 26 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as nls from 'vs/nls'; import { Event, Emitter } from 'vs/base/common/event'; import { URI as uri } from 'vs/base/common/uri'; import { first, distinct } from 'vs/base/common/arrays'; import * as errors from 'vs/base/common/errors'; import severity from 'vs/base/common/severity'; import * as aria from 'vs/base/browser/ui/aria/aria'; import { IContextKeyService, IContextKey } from 'vs/platform/contextkey/common/contextkey'; import { IMarkerService } from 'vs/platform/markers/common/markers'; import { ILifecycleService } from 'vs/platform/lifecycle/common/lifecycle'; import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { FileChangesEvent, FileChangeType, IFileService } from 'vs/platform/files/common/files'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage'; import { DebugModel, ExceptionBreakpoint, FunctionBreakpoint, Breakpoint, Expression, DataBreakpoint } from 'vs/workbench/contrib/debug/common/debugModel'; import { ViewModel } from 'vs/workbench/contrib/debug/common/debugViewModel'; import * as debugactions from 'vs/workbench/contrib/debug/browser/debugActions'; import { ConfigurationManager } from 'vs/workbench/contrib/debug/browser/debugConfigurationManager'; import Constants from 'vs/workbench/contrib/markers/browser/constants'; import { ITaskService, ITaskSummary } from 'vs/workbench/contrib/tasks/common/taskService'; import { VIEWLET_ID as EXPLORER_VIEWLET_ID } from 'vs/workbench/contrib/files/common/files'; import { IViewletService } from 'vs/workbench/services/viewlet/browser/viewlet'; import { IPanelService } from 'vs/workbench/services/panel/common/panelService'; import { IWorkbenchLayoutService, Parts } from 'vs/workbench/services/layout/browser/layoutService'; import { ITextFileService } from 'vs/workbench/services/textfile/common/textfiles'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IWorkspaceContextService, WorkbenchState, IWorkspaceFolder, IWorkspace } from 'vs/platform/workspace/common/workspace'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { parse, getFirstFrame } from 'vs/base/common/console'; import { TaskEvent, TaskEventKind, TaskIdentifier } from 'vs/workbench/contrib/tasks/common/tasks'; import { IDialogService } from 'vs/platform/dialogs/common/dialogs'; import { INotificationService } from 'vs/platform/notification/common/notification'; import { IAction } from 'vs/base/common/actions'; import { deepClone, equals } from 'vs/base/common/objects'; import { DebugSession } from 'vs/workbench/contrib/debug/browser/debugSession'; import { dispose, IDisposable } from 'vs/base/common/lifecycle'; import { IDebugService, State, IDebugSession, CONTEXT_DEBUG_TYPE, CONTEXT_DEBUG_STATE, CONTEXT_IN_DEBUG_MODE, IThread, IDebugConfiguration, VIEWLET_ID, REPL_ID, IConfig, ILaunch, IViewModel, IConfigurationManager, IDebugModel, IEnablement, IBreakpoint, IBreakpointData, ICompound, IGlobalConfig, IStackFrame, AdapterEndEvent, getStateLabel, IDebugSessionOptions, CONTEXT_DEBUG_UX } from 'vs/workbench/contrib/debug/common/debug'; import { isExtensionHostDebugging } from 'vs/workbench/contrib/debug/common/debugUtils'; import { isErrorWithActions, createErrorWithActions } from 'vs/base/common/errorsWithActions'; import { RunOnceScheduler } from 'vs/base/common/async'; import { IExtensionHostDebugService } from 'vs/platform/debug/common/extensionHostDebug'; import { isCodeEditor } from 'vs/editor/browser/editorBrowser'; import { CancellationTokenSource } from 'vs/base/common/cancellation'; import { withUndefinedAsNull } from 'vs/base/common/types'; const DEBUG_BREAKPOINTS_KEY = 'debug.breakpoint'; const DEBUG_FUNCTION_BREAKPOINTS_KEY = 'debug.functionbreakpoint'; const DEBUG_DATA_BREAKPOINTS_KEY = 'debug.databreakpoint'; const DEBUG_EXCEPTION_BREAKPOINTS_KEY = 'debug.exceptionbreakpoint'; const DEBUG_WATCH_EXPRESSIONS_KEY = 'debug.watchexpressions'; function once(match: (e: TaskEvent) => boolean, event: Event<TaskEvent>): Event<TaskEvent> { return (listener, thisArgs = null, disposables?) => { const result = event(e => { if (match(e)) { result.dispose(); return listener.call(thisArgs, e); } }, null, disposables); return result; }; } const enum TaskRunResult { Failure, Success } export class DebugService implements IDebugService { _serviceBrand: undefined; private readonly _onDidChangeState: Emitter<State>; private readonly _onDidNewSession: Emitter<IDebugSession>; private readonly _onWillNewSession: Emitter<IDebugSession>; private readonly _onDidEndSession: Emitter<IDebugSession>; private model: DebugModel; private viewModel: ViewModel; private configurationManager: ConfigurationManager; private toDispose: IDisposable[]; private debugType: IContextKey<string>; private debugState: IContextKey<string>; private inDebugMode: IContextKey<boolean>; private debugUx: IContextKey<string>; private breakpointsToSendOnResourceSaved: Set<string>; private initializing = false; private previousState: State | undefined; private initCancellationToken: CancellationTokenSource | undefined; constructor( @IStorageService private readonly storageService: IStorageService, @IEditorService private readonly editorService: IEditorService, @ITextFileService private readonly textFileService: ITextFileService, @IViewletService private readonly viewletService: IViewletService, @IPanelService private readonly panelService: IPanelService, @INotificationService private readonly notificationService: INotificationService, @IDialogService private readonly dialogService: IDialogService, @IWorkbenchLayoutService private readonly layoutService: IWorkbenchLayoutService, @ITelemetryService private readonly telemetryService: ITelemetryService, @IWorkspaceContextService private readonly contextService: IWorkspaceContextService, @IContextKeyService contextKeyService: IContextKeyService, @ILifecycleService private readonly lifecycleService: ILifecycleService, @IInstantiationService private readonly instantiationService: IInstantiationService, @IExtensionService private readonly extensionService: IExtensionService, @IMarkerService private readonly markerService: IMarkerService, @ITaskService private readonly taskService: ITaskService, @IFileService private readonly fileService: IFileService, @IConfigurationService private readonly configurationService: IConfigurationService, @IExtensionHostDebugService private readonly extensionHostDebugService: IExtensionHostDebugService ) { this.toDispose = []; this.breakpointsToSendOnResourceSaved = new Set<string>(); this._onDidChangeState = new Emitter<State>(); this._onDidNewSession = new Emitter<IDebugSession>(); this._onWillNewSession = new Emitter<IDebugSession>(); this._onDidEndSession = new Emitter<IDebugSession>(); this.configurationManager = this.instantiationService.createInstance(ConfigurationManager); this.toDispose.push(this.configurationManager); this.debugType = CONTEXT_DEBUG_TYPE.bindTo(contextKeyService); this.debugState = CONTEXT_DEBUG_STATE.bindTo(contextKeyService); this.inDebugMode = CONTEXT_IN_DEBUG_MODE.bindTo(contextKeyService); this.debugUx = CONTEXT_DEBUG_UX.bindTo(contextKeyService); this.debugUx.set(!!this.configurationManager.selectedConfiguration.name ? 'default' : 'simple'); this.model = new DebugModel(this.loadBreakpoints(), this.loadFunctionBreakpoints(), this.loadExceptionBreakpoints(), this.loadDataBreakpoints(), this.loadWatchExpressions(), this.textFileService); this.toDispose.push(this.model); this.viewModel = new ViewModel(contextKeyService); this.toDispose.push(this.fileService.onFileChanges(e => this.onFileChanges(e))); this.lifecycleService.onShutdown(this.dispose, this); this.toDispose.push(this.extensionHostDebugService.onAttachSession(event => { const session = this.model.getSession(event.sessionId, true); if (session) { // EH was started in debug mode -> attach to it session.configuration.request = 'attach'; session.configuration.port = event.port; session.setSubId(event.subId); this.launchOrAttachToSession(session); } })); this.toDispose.push(this.extensionHostDebugService.onTerminateSession(event => { const session = this.model.getSession(event.sessionId); if (session && session.subId === event.subId) { session.disconnect(); } })); this.toDispose.push(this.extensionHostDebugService.onLogToSession(event => { const session = this.model.getSession(event.sessionId, true); if (session) { // extension logged output -> show it in REPL const sev = event.log.severity === 'warn' ? severity.Warning : event.log.severity === 'error' ? severity.Error : severity.Info; const { args, stack } = parse(event.log); const frame = !!stack ? getFirstFrame(stack) : undefined; session.logToRepl(sev, args, frame); } })); this.toDispose.push(this.viewModel.onDidFocusStackFrame(() => { this.onStateChange(); })); this.toDispose.push(this.viewModel.onDidFocusSession(() => { this.onStateChange(); })); this.toDispose.push(this.configurationManager.onDidSelectConfiguration(() => { this.debugUx.set(!!(this.state !== State.Inactive || this.configurationManager.selectedConfiguration.name) ? 'default' : 'simple'); })); } getModel(): IDebugModel { return this.model; } getViewModel(): IViewModel { return this.viewModel; } getConfigurationManager(): IConfigurationManager { return this.configurationManager; } sourceIsNotAvailable(uri: uri): void { this.model.sourceIsNotAvailable(uri); } dispose(): void { this.toDispose = dispose(this.toDispose); } //---- state management get state(): State { const focusedSession = this.viewModel.focusedSession; if (focusedSession) { return focusedSession.state; } return this.initializing ? State.Initializing : State.Inactive; } private startInitializingState() { if (!this.initializing) { this.initializing = true; this.onStateChange(); } } private endInitializingState() { if (this.initCancellationToken) { this.initCancellationToken.cancel(); this.initCancellationToken = undefined; } if (this.initializing) { this.initializing = false; this.onStateChange(); } } private onStateChange(): void { const state = this.state; if (this.previousState !== state) { this.debugState.set(getStateLabel(state)); this.inDebugMode.set(state !== State.Inactive); // Only show the simple ux if debug is not yet started and if no launch.json exists this.debugUx.set(((state !== State.Inactive && state !== State.Initializing) || this.configurationManager.selectedConfiguration.name) ? 'default' : 'simple'); this.previousState = state; this._onDidChangeState.fire(state); } } get onDidChangeState(): Event<State> { return this._onDidChangeState.event; } get onDidNewSession(): Event<IDebugSession> { return this._onDidNewSession.event; } get onWillNewSession(): Event<IDebugSession> { return this._onWillNewSession.event; } get onDidEndSession(): Event<IDebugSession> { return this._onDidEndSession.event; } //---- life cycle management /** * main entry point * properly manages compounds, checks for errors and handles the initializing state. */ async startDebugging(launch: ILaunch | undefined, configOrName?: IConfig | string, options?: IDebugSessionOptions): Promise<boolean> { this.startInitializingState(); try { // make sure to save all files and that the configuration is up to date await this.extensionService.activateByEvent('onDebug'); await this.editorService.saveAll(); await this.configurationService.reloadConfiguration(launch ? launch.workspace : undefined); await this.extensionService.whenInstalledExtensionsRegistered(); let config: IConfig | undefined; let compound: ICompound | undefined; if (!configOrName) { configOrName = this.configurationManager.selectedConfiguration.name; } if (typeof configOrName === 'string' && launch) { config = launch.getConfiguration(configOrName); compound = launch.getCompound(configOrName); const sessions = this.model.getSessions(); const alreadyRunningMessage = nls.localize('configurationAlreadyRunning', "There is already a debug configuration \"{0}\" running.", configOrName); if (sessions.some(s => s.configuration.name === configOrName && (!launch || !launch.workspace || !s.root || s.root.uri.toString() === launch.workspace.uri.toString()))) { throw new Error(alreadyRunningMessage); } if (compound && compound.configurations && sessions.some(p => compound!.configurations.indexOf(p.configuration.name) !== -1)) { throw new Error(alreadyRunningMessage); } } else if (typeof configOrName !== 'string') { config = configOrName; } if (compound) { // we are starting a compound debug, first do some error checking and than start each configuration in the compound if (!compound.configurations) { throw new Error(nls.localize({ key: 'compoundMustHaveConfigurations', comment: ['compound indicates a "compounds" configuration item', '"configurations" is an attribute and should not be localized'] }, "Compound must have \"configurations\" attribute set in order to start multiple configurations.")); } if (compound.preLaunchTask) { const taskResult = await this.runTaskAndCheckErrors(launch?.workspace || this.contextService.getWorkspace(), compound.preLaunchTask); if (taskResult === TaskRunResult.Failure) { this.endInitializingState(); return false; } } const values = await Promise.all(compound.configurations.map(configData => { const name = typeof configData === 'string' ? configData : configData.name; if (name === compound!.name) { return Promise.resolve(false); } let launchForName: ILaunch | undefined; if (typeof configData === 'string') { const launchesContainingName = this.configurationManager.getLaunches().filter(l => !!l.getConfiguration(name)); if (launchesContainingName.length === 1) { launchForName = launchesContainingName[0]; } else if (launch && launchesContainingName.length > 1 && launchesContainingName.indexOf(launch) >= 0) { // If there are multiple launches containing the configuration give priority to the configuration in the current launch launchForName = launch; } else { throw new Error(launchesContainingName.length === 0 ? nls.localize('noConfigurationNameInWorkspace', "Could not find launch configuration '{0}' in the workspace.", name) : nls.localize('multipleConfigurationNamesInWorkspace', "There are multiple launch configurations '{0}' in the workspace. Use folder name to qualify the configuration.", name)); } } else if (configData.folder) { const launchesMatchingConfigData = this.configurationManager.getLaunches().filter(l => l.workspace && l.workspace.name === configData.folder && !!l.getConfiguration(configData.name)); if (launchesMatchingConfigData.length === 1) { launchForName = launchesMatchingConfigData[0]; } else { throw new Error(nls.localize('noFolderWithName', "Can not find folder with name '{0}' for configuration '{1}' in compound '{2}'.", configData.folder, configData.name, compound!.name)); } } return this.createSession(launchForName, launchForName!.getConfiguration(name), options); })); const result = values.every(success => !!success); // Compound launch is a success only if each configuration launched successfully this.endInitializingState(); return result; } if (configOrName && !config) { const message = !!launch ? nls.localize('configMissing', "Configuration '{0}' is missing in 'launch.json'.", typeof configOrName === 'string' ? configOrName : JSON.stringify(configOrName)) : nls.localize('launchJsonDoesNotExist', "'launch.json' does not exist."); throw new Error(message); } const result = await this.createSession(launch, config, options); this.endInitializingState(); return result; } catch (err) { // make sure to get out of initializing state, and propagate the result this.endInitializingState(); return Promise.reject(err); } } /** * gets the debugger for the type, resolves configurations by providers, substitutes variables and runs prelaunch tasks */ private async createSession(launch: ILaunch | undefined, config: IConfig | undefined, options?: IDebugSessionOptions): Promise<boolean> { // We keep the debug type in a separate variable 'type' so that a no-folder config has no attributes. // Storing the type in the config would break extensions that assume that the no-folder case is indicated by an empty config. let type: string | undefined; if (config) { type = config.type; } else { // a no-folder workspace has no launch.config config = Object.create(null); } const unresolvedConfig = deepClone(config); if (options && options.noDebug) { config!.noDebug = true; } if (!type) { const guess = await this.configurationManager.guessDebugger(); if (guess) { type = guess.type; } } this.initCancellationToken = new CancellationTokenSource(); const configByProviders = await this.configurationManager.resolveConfigurationByProviders(launch && launch.workspace ? launch.workspace.uri : undefined, type, config!, this.initCancellationToken.token); // a falsy config indicates an aborted launch if (configByProviders && configByProviders.type) { try { const resolvedConfig = await this.substituteVariables(launch, configByProviders); if (!resolvedConfig) { // User canceled resolving of interactive variables, silently return return false; } if (!this.configurationManager.getDebugger(resolvedConfig.type) || (configByProviders.request !== 'attach' && configByProviders.request !== 'launch')) { let message: string; if (configByProviders.request !== 'attach' && configByProviders.request !== 'launch') { message = configByProviders.request ? nls.localize('debugRequestNotSupported', "Attribute '{0}' has an unsupported value '{1}' in the chosen debug configuration.", 'request', configByProviders.request) : nls.localize('debugRequesMissing', "Attribute '{0}' is missing from the chosen debug configuration.", 'request'); } else { message = resolvedConfig.type ? nls.localize('debugTypeNotSupported', "Configured debug type '{0}' is not supported.", resolvedConfig.type) : nls.localize('debugTypeMissing', "Missing property 'type' for the chosen launch configuration."); } await this.showError(message); return false; } const workspace = launch ? launch.workspace : this.contextService.getWorkspace(); const taskResult = await this.runTaskAndCheckErrors(workspace, resolvedConfig.preLaunchTask); if (taskResult === TaskRunResult.Success) { return this.doCreateSession(launch?.workspace, { resolved: resolvedConfig, unresolved: unresolvedConfig }, options); } return false; } catch (err) { if (err && err.message) { await this.showError(err.message); } else if (this.contextService.getWorkbenchState() === WorkbenchState.EMPTY) { await this.showError(nls.localize('noFolderWorkspaceDebugError', "The active file can not be debugged. Make sure it is saved and that you have a debug extension installed for that file type.")); } if (launch) { await launch.openConfigFile(false, true, undefined, this.initCancellationToken ? this.initCancellationToken.token : undefined); } return false; } } if (launch && type && configByProviders === null) { // show launch.json only for "config" being "null". await launch.openConfigFile(false, true, type, this.initCancellationToken ? this.initCancellationToken.token : undefined); } return false; } /** * instantiates the new session, initializes the session, registers session listeners and reports telemetry */ private async doCreateSession(root: IWorkspaceFolder | undefined, configuration: { resolved: IConfig, unresolved: IConfig | undefined }, options?: IDebugSessionOptions): Promise<boolean> { const session = this.instantiationService.createInstance(DebugSession, configuration, root, this.model, options); this.model.addSession(session); // register listeners as the very first thing! this.registerSessionListeners(session); // since the Session is now properly registered under its ID and hooked, we can announce it // this event doesn't go to extensions this._onWillNewSession.fire(session); const openDebug = this.configurationService.getValue<IDebugConfiguration>('debug').openDebug; // Open debug viewlet based on the visibility of the side bar and openDebug setting. Do not open for 'run without debug' if (!configuration.resolved.noDebug && (openDebug === 'openOnSessionStart' || (openDebug === 'openOnFirstSessionStart' && this.viewModel.firstSessionStart))) { await this.viewletService.openViewlet(VIEWLET_ID); } try { await this.launchOrAttachToSession(session); const internalConsoleOptions = session.configuration.internalConsoleOptions || this.configurationService.getValue<IDebugConfiguration>('debug').internalConsoleOptions; if (internalConsoleOptions === 'openOnSessionStart' || (this.viewModel.firstSessionStart && internalConsoleOptions === 'openOnFirstSessionStart')) { this.panelService.openPanel(REPL_ID, false); } this.viewModel.firstSessionStart = false; const showSubSessions = this.configurationService.getValue<IDebugConfiguration>('debug').showSubSessionsInToolBar; const sessions = this.model.getSessions(); const shownSessions = showSubSessions ? sessions : sessions.filter(s => !s.parentSession); if (shownSessions.length > 1) { this.viewModel.setMultiSessionView(true); } // since the initialized response has arrived announce the new Session (including extensions) this._onDidNewSession.fire(session); await this.telemetryDebugSessionStart(root, session.configuration.type); return true; } catch (error) { if (errors.isPromiseCanceledError(error)) { // don't show 'canceled' error messages to the user #7906 return false; } // Show the repl if some error got logged there #5870 if (session && session.getReplElements().length > 0) { this.panelService.openPanel(REPL_ID, false); } if (session.configuration && session.configuration.request === 'attach' && session.configuration.__autoAttach) { // ignore attach timeouts in auto attach mode return false; } const errorMessage = error instanceof Error ? error.message : error; await this.showError(errorMessage, isErrorWithActions(error) ? error.actions : []); return false; } } private async launchOrAttachToSession(session: IDebugSession, forceFocus = false): Promise<void> { const dbgr = this.configurationManager.getDebugger(session.configuration.type); try { await session.initialize(dbgr!); await session.launchOrAttach(session.configuration); if (forceFocus || !this.viewModel.focusedSession) { await this.focusStackFrame(undefined, undefined, session); } } catch (err) { session.shutdown(); return Promise.reject(err); } } private registerSessionListeners(session: IDebugSession): void { const sessionRunningScheduler = new RunOnceScheduler(() => { // Do not immediatly defocus the stack frame if the session is running if (session.state === State.Running && this.viewModel.focusedSession === session) { this.viewModel.setFocus(undefined, this.viewModel.focusedThread, session, false); } }, 200); this.toDispose.push(session.onDidChangeState(() => { if (session.state === State.Running && this.viewModel.focusedSession === session) { sessionRunningScheduler.schedule(); } if (session === this.viewModel.focusedSession) { this.onStateChange(); } })); this.toDispose.push(session.onDidEndAdapter(async adapterExitEvent => { if (adapterExitEvent.error) { this.notificationService.error(nls.localize('debugAdapterCrash', "Debug adapter process has terminated unexpectedly ({0})", adapterExitEvent.error.message || adapterExitEvent.error.toString())); } // 'Run without debugging' mode VSCode must terminate the extension host. More details: #3905 if (isExtensionHostDebugging(session.configuration) && session.state === State.Running && session.configuration.noDebug) { this.extensionHostDebugService.close(session.getId()); } this.telemetryDebugSessionStop(session, adapterExitEvent); if (session.configuration.postDebugTask) { try { await this.runTask(session.root, session.configuration.postDebugTask); } catch (err) { this.notificationService.error(err); } } session.shutdown(); this.endInitializingState(); this._onDidEndSession.fire(session); const focusedSession = this.viewModel.focusedSession; if (focusedSession && focusedSession.getId() === session.getId()) { await this.focusStackFrame(undefined); } if (this.model.getSessions().length === 0) { this.viewModel.setMultiSessionView(false); if (this.layoutService.isVisible(Parts.SIDEBAR_PART) && this.configurationService.getValue<IDebugConfiguration>('debug').openExplorerOnEnd) { this.viewletService.openViewlet(EXPLORER_VIEWLET_ID); } // Data breakpoints that can not be persisted should be cleared when a session ends const dataBreakpoints = this.model.getDataBreakpoints().filter(dbp => !dbp.canPersist); dataBreakpoints.forEach(dbp => this.model.removeDataBreakpoints(dbp.getId())); } })); } async restartSession(session: IDebugSession, restartData?: any): Promise<any> { await this.editorService.saveAll(); const isAutoRestart = !!restartData; const runTasks: () => Promise<TaskRunResult> = async () => { if (isAutoRestart) { // Do not run preLaunch and postDebug tasks for automatic restarts return Promise.resolve(TaskRunResult.Success); } await this.runTask(session.root, session.configuration.postDebugTask); return this.runTaskAndCheckErrors(session.root, session.configuration.preLaunchTask); }; if (isExtensionHostDebugging(session.configuration)) { const taskResult = await runTasks(); if (taskResult === TaskRunResult.Success) { this.extensionHostDebugService.reload(session.getId()); } return; } if (session.capabilities.supportsRestartRequest) { const taskResult = await runTasks(); if (taskResult === TaskRunResult.Success) { await session.restart(); } return; } const shouldFocus = !!this.viewModel.focusedSession && session.getId() === this.viewModel.focusedSession.getId(); // If the restart is automatic -> disconnect, otherwise -> terminate #55064 if (isAutoRestart) { await session.disconnect(true); } else { await session.terminate(true); } return new Promise<void>((c, e) => { setTimeout(async () => { const taskResult = await runTasks(); if (taskResult !== TaskRunResult.Success) { return; } // Read the configuration again if a launch.json has been changed, if not just use the inmemory configuration let needsToSubstitute = false; let unresolved: IConfig | undefined; const launch = session.root ? this.configurationManager.getLaunch(session.root.uri) : undefined; if (launch) { unresolved = launch.getConfiguration(session.configuration.name); if (unresolved && !equals(unresolved, session.unresolvedConfiguration)) { // Take the type from the session since the debug extension might overwrite it #21316 unresolved.type = session.configuration.type; unresolved.noDebug = session.configuration.noDebug; needsToSubstitute = true; } } let resolved: IConfig | undefined | null = session.configuration; if (launch && needsToSubstitute && unresolved) { this.initCancellationToken = new CancellationTokenSource(); const resolvedByProviders = await this.configurationManager.resolveConfigurationByProviders(launch.workspace ? launch.workspace.uri : undefined, unresolved.type, unresolved, this.initCancellationToken.token); if (resolvedByProviders) { resolved = await this.substituteVariables(launch, resolvedByProviders); } else { resolved = resolvedByProviders; } } if (!resolved) { return c(undefined); } session.setConfiguration({ resolved, unresolved }); session.configuration.__restart = restartData; try { await this.launchOrAttachToSession(session, shouldFocus); this._onDidNewSession.fire(session); c(undefined); } catch (error) { e(error); } }, 300); }); } stopSession(session: IDebugSession): Promise<any> { if (session) { return session.terminate(); } const sessions = this.model.getSessions(); if (sessions.length === 0) { this.endInitializingState(); } return Promise.all(sessions.map(s => s.terminate())); } private async substituteVariables(launch: ILaunch | undefined, config: IConfig): Promise<IConfig | undefined> { const dbg = this.configurationManager.getDebugger(config.type); if (dbg) { let folder: IWorkspaceFolder | undefined = undefined; if (launch && launch.workspace) { folder = launch.workspace; } else { const folders = this.contextService.getWorkspace().folders; if (folders.length === 1) { folder = folders[0]; } } try { return await dbg.substituteVariables(folder, config); } catch (err) { this.showError(err.message); return undefined; // bail out } } return Promise.resolve(config); } private async showError(message: string, errorActions: ReadonlyArray<IAction> = []): Promise<void> { const configureAction = this.instantiationService.createInstance(debugactions.ConfigureAction, debugactions.ConfigureAction.ID, debugactions.ConfigureAction.LABEL); const actions = [...errorActions, configureAction]; const { choice } = await this.dialogService.show(severity.Error, message, actions.map(a => a.label).concat(nls.localize('cancel', "Cancel")), { cancelId: actions.length }); if (choice < actions.length) { return actions[choice].run(); } return undefined; } //---- task management private async runTaskAndCheckErrors(root: IWorkspaceFolder | IWorkspace | undefined, taskId: string | TaskIdentifier | undefined): Promise<TaskRunResult> { try { const taskSummary = await this.runTask(root, taskId); const errorCount = taskId ? this.markerService.getStatistics().errors : 0; const successExitCode = taskSummary && taskSummary.exitCode === 0; const failureExitCode = taskSummary && taskSummary.exitCode !== 0; const onTaskErrors = this.configurationService.getValue<IDebugConfiguration>('debug').onTaskErrors; if (successExitCode || onTaskErrors === 'debugAnyway' || (errorCount === 0 && !failureExitCode)) { return TaskRunResult.Success; } if (onTaskErrors === 'showErrors') { this.panelService.openPanel(Constants.MARKERS_PANEL_ID); return Promise.resolve(TaskRunResult.Failure); } const taskLabel = typeof taskId === 'string' ? taskId : taskId ? taskId.name : ''; const message = errorCount > 1 ? nls.localize('preLaunchTaskErrors', "Errors exist after running preLaunchTask '{0}'.", taskLabel) : errorCount === 1 ? nls.localize('preLaunchTaskError', "Error exists after running preLaunchTask '{0}'.", taskLabel) : nls.localize('preLaunchTaskExitCode', "The preLaunchTask '{0}' terminated with exit code {1}.", taskLabel, taskSummary ? taskSummary.exitCode : 0); const result = await this.dialogService.show(severity.Warning, message, [nls.localize('debugAnyway', "Debug Anyway"), nls.localize('showErrors', "Show Errors"), nls.localize('cancel', "Cancel")], { checkbox: { label: nls.localize('remember', "Remember my choice in user settings"), }, cancelId: 2 }); if (result.choice === 2) { return Promise.resolve(TaskRunResult.Failure); } const debugAnyway = result.choice === 0; if (result.checkboxChecked) { this.configurationService.updateValue('debug.onTaskErrors', debugAnyway ? 'debugAnyway' : 'showErrors'); } if (debugAnyway) { return TaskRunResult.Success; } this.panelService.openPanel(Constants.MARKERS_PANEL_ID); return Promise.resolve(TaskRunResult.Failure); } catch (err) { await this.showError(err.message, [this.taskService.configureAction()]); return TaskRunResult.Failure; } } private async runTask(root: IWorkspace | IWorkspaceFolder | undefined, taskId: string | TaskIdentifier | undefined): Promise<ITaskSummary | null> { if (!taskId) { return Promise.resolve(null); } if (!root) { return Promise.reject(new Error(nls.localize('invalidTaskReference', "Task '{0}' can not be referenced from a launch configuration that is in a different workspace folder.", typeof taskId === 'string' ? taskId : taskId.type))); } // run a task before starting a debug session const task = await this.taskService.getTask(root, taskId); if (!task) { const errorMessage = typeof taskId === 'string' ? nls.localize('DebugTaskNotFoundWithTaskId', "Could not find the task '{0}'.", taskId) : nls.localize('DebugTaskNotFound', "Could not find the specified task."); return Promise.reject(createErrorWithActions(errorMessage)); } // If a task is missing the problem matcher the promise will never complete, so we need to have a workaround #35340 let taskStarted = false; const inactivePromise: Promise<ITaskSummary | null> = new Promise((c, e) => once(e => { // When a task isBackground it will go inactive when it is safe to launch. // But when a background task is terminated by the user, it will also fire an inactive event. // This means that we will not get to see the real exit code from running the task (undefined when terminated by the user). // Catch the ProcessEnded event here, which occurs before inactive, and capture the exit code to prevent this. return (e.kind === TaskEventKind.Inactive || (e.kind === TaskEventKind.ProcessEnded && e.exitCode === undefined)) && e.taskId === task._id; }, this.taskService.onDidStateChange)(e => { taskStarted = true; c(e.kind === TaskEventKind.ProcessEnded ? { exitCode: e.exitCode } : null); })); const promise: Promise<ITaskSummary | null> = this.taskService.getActiveTasks().then(async (tasks): Promise<ITaskSummary | null> => { if (tasks.filter(t => t._id === task._id).length) { // Check that the task isn't busy and if it is, wait for it const busyTasks = await this.taskService.getBusyTasks(); if (busyTasks.filter(t => t._id === task._id).length) { taskStarted = true; return inactivePromise; } // task is already running and isn't busy - nothing to do. return Promise.resolve(null); } once(e => ((e.kind === TaskEventKind.Active) || (e.kind === TaskEventKind.DependsOnStarted)) && e.taskId === task._id, this.taskService.onDidStateChange)(() => { // Task is active, so everything seems to be fine, no need to prompt after 10 seconds // Use case being a slow running task should not be prompted even though it takes more than 10 seconds taskStarted = true; }); const taskPromise = this.taskService.run(task); if (task.configurationProperties.isBackground) { return inactivePromise; } return taskPromise.then(withUndefinedAsNull); }); return new Promise((c, e) => { promise.then(result => { taskStarted = true; c(result); }, error => e(error)); setTimeout(() => { if (!taskStarted) { const errorMessage = typeof taskId === 'string' ? nls.localize('taskNotTrackedWithTaskId', "The specified task cannot be tracked.") : nls.localize('taskNotTracked', "The task '{0}' cannot be tracked.", JSON.stringify(taskId)); e({ severity: severity.Error, message: errorMessage }); } }, 10000); }); } //---- focus management async focusStackFrame(stackFrame: IStackFrame | undefined, thread?: IThread, session?: IDebugSession, explicit?: boolean): Promise<void> { if (!session) { if (stackFrame || thread) { session = stackFrame ? stackFrame.thread.session : thread!.session; } else { const sessions = this.model.getSessions(); const stoppedSession = sessions.filter(s => s.state === State.Stopped).shift(); session = stoppedSession || (sessions.length ? sessions[0] : undefined); } } if (!thread) { if (stackFrame) { thread = stackFrame.thread; } else { const threads = session ? session.getAllThreads() : undefined; const stoppedThread = threads && threads.filter(t => t.stopped).shift(); thread = stoppedThread || (threads && threads.length ? threads[0] : undefined); } } if (!stackFrame) { if (thread) { const callStack = thread.getCallStack(); stackFrame = first(callStack, sf => !!(sf && sf.source && sf.source.available && sf.source.presentationHint !== 'deemphasize'), undefined); } } if (stackFrame) { const editor = await stackFrame.openInEditor(this.editorService, true); if (editor) { const control = editor.getControl(); if (stackFrame && isCodeEditor(control) && control.hasModel()) { const model = control.getModel(); if (stackFrame.range.startLineNumber <= model.getLineCount()) { const lineContent = control.getModel().getLineContent(stackFrame.range.startLineNumber); aria.alert(nls.localize('debuggingPaused', "Debugging paused {0}, {1} {2} {3}", thread && thread.stoppedDetails ? `, reason ${thread.stoppedDetails.reason}` : '', stackFrame.source ? stackFrame.source.name : '', stackFrame.range.startLineNumber, lineContent)); } } } } if (session) { this.debugType.set(session.configuration.type); } else { this.debugType.reset(); } this.viewModel.setFocus(stackFrame, thread, session, !!explicit); } //---- watches addWatchExpression(name: string): void { const we = this.model.addWatchExpression(name); this.viewModel.setSelectedExpression(we); this.storeWatchExpressions(); } renameWatchExpression(id: string, newName: string): void { this.model.renameWatchExpression(id, newName); this.storeWatchExpressions(); } moveWatchExpression(id: string, position: number): void { this.model.moveWatchExpression(id, position); this.storeWatchExpressions(); } removeWatchExpressions(id?: string): void { this.model.removeWatchExpressions(id); this.storeWatchExpressions(); } //---- breakpoints async enableOrDisableBreakpoints(enable: boolean, breakpoint?: IEnablement): Promise<void> { if (breakpoint) { this.model.setEnablement(breakpoint, enable); if (breakpoint instanceof Breakpoint) { await this.sendBreakpoints(breakpoint.uri); } else if (breakpoint instanceof FunctionBreakpoint) { await this.sendFunctionBreakpoints(); } else if (breakpoint instanceof DataBreakpoint) { await this.sendDataBreakpoints(); } else { await this.sendExceptionBreakpoints(); } } else { this.model.enableOrDisableAllBreakpoints(enable); await this.sendAllBreakpoints(); } this.storeBreakpoints(); } async addBreakpoints(uri: uri, rawBreakpoints: IBreakpointData[], context: string): Promise<IBreakpoint[]> { const breakpoints = this.model.addBreakpoints(uri, rawBreakpoints); breakpoints.forEach(bp => aria.status(nls.localize('breakpointAdded', "Added breakpoint, line {0}, file {1}", bp.lineNumber, uri.fsPath))); breakpoints.forEach(bp => this.telemetryDebugAddBreakpoint(bp, context)); await this.sendBreakpoints(uri); this.storeBreakpoints(); return breakpoints; } async updateBreakpoints(uri: uri, data: Map<string, DebugProtocol.Breakpoint>, sendOnResourceSaved: boolean): Promise<void> { this.model.updateBreakpoints(data); if (sendOnResourceSaved) { this.breakpointsToSendOnResourceSaved.add(uri.toString()); } else { await this.sendBreakpoints(uri); } this.storeBreakpoints(); } async removeBreakpoints(id?: string): Promise<void> { const toRemove = this.model.getBreakpoints().filter(bp => !id || bp.getId() === id); toRemove.forEach(bp => aria.status(nls.localize('breakpointRemoved', "Removed breakpoint, line {0}, file {1}", bp.lineNumber, bp.uri.fsPath))); const urisToClear = distinct(toRemove, bp => bp.uri.toString()).map(bp => bp.uri); this.model.removeBreakpoints(toRemove); await Promise.all(urisToClear.map(uri => this.sendBreakpoints(uri))); this.storeBreakpoints(); } setBreakpointsActivated(activated: boolean): Promise<void> { this.model.setBreakpointsActivated(activated); return this.sendAllBreakpoints(); } addFunctionBreakpoint(name?: string, id?: string): void { const newFunctionBreakpoint = this.model.addFunctionBreakpoint(name || '', id); this.viewModel.setSelectedFunctionBreakpoint(newFunctionBreakpoint); } async renameFunctionBreakpoint(id: string, newFunctionName: string): Promise<void> { this.model.renameFunctionBreakpoint(id, newFunctionName); await this.sendFunctionBreakpoints(); this.storeBreakpoints(); } async removeFunctionBreakpoints(id?: string): Promise<void> { this.model.removeFunctionBreakpoints(id); await this.sendFunctionBreakpoints(); this.storeBreakpoints(); } async addDataBreakpoint(label: string, dataId: string, canPersist: boolean): Promise<void> { this.model.addDataBreakpoint(label, dataId, canPersist); await this.sendDataBreakpoints(); this.storeBreakpoints(); } async removeDataBreakpoints(id?: string): Promise<void> { this.model.removeDataBreakpoints(id); await this.sendDataBreakpoints(); this.storeBreakpoints(); } async sendAllBreakpoints(session?: IDebugSession): Promise<any> { await Promise.all(distinct(this.model.getBreakpoints(), bp => bp.uri.toString()).map(bp => this.sendBreakpoints(bp.uri, false, session))); await this.sendFunctionBreakpoints(session); await this.sendDataBreakpoints(session); // send exception breakpoints at the end since some debug adapters rely on the order await this.sendExceptionBreakpoints(session); } private sendBreakpoints(modelUri: uri, sourceModified = false, session?: IDebugSession): Promise<void> { const breakpointsToSend = this.model.getBreakpoints({ uri: modelUri, enabledOnly: true }); return this.sendToOneOrAllSessions(session, s => s.sendBreakpoints(modelUri, breakpointsToSend, sourceModified) ); } private sendFunctionBreakpoints(session?: IDebugSession): Promise<void> { const breakpointsToSend = this.model.getFunctionBreakpoints().filter(fbp => fbp.enabled && this.model.areBreakpointsActivated()); return this.sendToOneOrAllSessions(session, s => { return s.capabilities.supportsFunctionBreakpoints ? s.sendFunctionBreakpoints(breakpointsToSend) : Promise.resolve(undefined); }); } private sendDataBreakpoints(session?: IDebugSession): Promise<void> { const breakpointsToSend = this.model.getDataBreakpoints().filter(fbp => fbp.enabled && this.model.areBreakpointsActivated()); return this.sendToOneOrAllSessions(session, s => { return s.capabilities.supportsDataBreakpoints ? s.sendDataBreakpoints(breakpointsToSend) : Promise.resolve(undefined); }); } private sendExceptionBreakpoints(session?: IDebugSession): Promise<void> { const enabledExceptionBps = this.model.getExceptionBreakpoints().filter(exb => exb.enabled); return this.sendToOneOrAllSessions(session, s => { return s.sendExceptionBreakpoints(enabledExceptionBps); }); } private async sendToOneOrAllSessions(session: IDebugSession | undefined, send: (session: IDebugSession) => Promise<void>): Promise<void> { if (session) { await send(session); } else { await Promise.all(this.model.getSessions().map(s => send(s))); } } private onFileChanges(fileChangesEvent: FileChangesEvent): void { const toRemove = this.model.getBreakpoints().filter(bp => fileChangesEvent.contains(bp.uri, FileChangeType.DELETED)); if (toRemove.length) { this.model.removeBreakpoints(toRemove); } fileChangesEvent.getUpdated().forEach(event => { if (this.breakpointsToSendOnResourceSaved.delete(event.resource.toString())) { this.sendBreakpoints(event.resource, true); } }); } private loadBreakpoints(): Breakpoint[] { let result: Breakpoint[] | undefined; try { result = JSON.parse(this.storageService.get(DEBUG_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((breakpoint: any) => { return new Breakpoint(uri.parse(breakpoint.uri.external || breakpoint.source.uri.external), breakpoint.lineNumber, breakpoint.column, breakpoint.enabled, breakpoint.condition, breakpoint.hitCondition, breakpoint.logMessage, breakpoint.adapterData, this.textFileService); }); } catch (e) { } return result || []; } private loadFunctionBreakpoints(): FunctionBreakpoint[] { let result: FunctionBreakpoint[] | undefined; try { result = JSON.parse(this.storageService.get(DEBUG_FUNCTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((fb: any) => { return new FunctionBreakpoint(fb.name, fb.enabled, fb.hitCondition, fb.condition, fb.logMessage); }); } catch (e) { } return result || []; } private loadExceptionBreakpoints(): ExceptionBreakpoint[] { let result: ExceptionBreakpoint[] | undefined; try { result = JSON.parse(this.storageService.get(DEBUG_EXCEPTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((exBreakpoint: any) => { return new ExceptionBreakpoint(exBreakpoint.filter, exBreakpoint.label, exBreakpoint.enabled); }); } catch (e) { } return result || []; } private loadDataBreakpoints(): DataBreakpoint[] { let result: DataBreakpoint[] | undefined; try { result = JSON.parse(this.storageService.get(DEBUG_DATA_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((dbp: any) => { return new DataBreakpoint(dbp.label, dbp.dataId, true, dbp.enabled, dbp.hitCondition, dbp.condition, dbp.logMessage); }); } catch (e) { } return result || []; } private loadWatchExpressions(): Expression[] { let result: Expression[] | undefined; try { result = JSON.parse(this.storageService.get(DEBUG_WATCH_EXPRESSIONS_KEY, StorageScope.WORKSPACE, '[]')).map((watchStoredData: { name: string, id: string }) => { return new Expression(watchStoredData.name, watchStoredData.id); }); } catch (e) { } return result || []; } private storeWatchExpressions(): void { const watchExpressions = this.model.getWatchExpressions(); if (watchExpressions.length) { this.storageService.store(DEBUG_WATCH_EXPRESSIONS_KEY, JSON.stringify(watchExpressions.map(we => ({ name: we.name, id: we.getId() }))), StorageScope.WORKSPACE); } else { this.storageService.remove(DEBUG_WATCH_EXPRESSIONS_KEY, StorageScope.WORKSPACE); } } private storeBreakpoints(): void { const breakpoints = this.model.getBreakpoints(); if (breakpoints.length) { this.storageService.store(DEBUG_BREAKPOINTS_KEY, JSON.stringify(breakpoints), StorageScope.WORKSPACE); } else { this.storageService.remove(DEBUG_BREAKPOINTS_KEY, StorageScope.WORKSPACE); } const functionBreakpoints = this.model.getFunctionBreakpoints(); if (functionBreakpoints.length) { this.storageService.store(DEBUG_FUNCTION_BREAKPOINTS_KEY, JSON.stringify(functionBreakpoints), StorageScope.WORKSPACE); } else { this.storageService.remove(DEBUG_FUNCTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE); } const dataBreakpoints = this.model.getDataBreakpoints().filter(dbp => dbp.canPersist); if (dataBreakpoints.length) { this.storageService.store(DEBUG_DATA_BREAKPOINTS_KEY, JSON.stringify(dataBreakpoints), StorageScope.WORKSPACE); } else { this.storageService.remove(DEBUG_DATA_BREAKPOINTS_KEY, StorageScope.WORKSPACE); } const exceptionBreakpoints = this.model.getExceptionBreakpoints(); if (exceptionBreakpoints.length) { this.storageService.store(DEBUG_EXCEPTION_BREAKPOINTS_KEY, JSON.stringify(exceptionBreakpoints), StorageScope.WORKSPACE); } else { this.storageService.remove(DEBUG_EXCEPTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE); } } //---- telemetry private telemetryDebugSessionStart(root: IWorkspaceFolder | undefined, type: string): Promise<void> { const dbgr = this.configurationManager.getDebugger(type); if (!dbgr) { return Promise.resolve(); } const extension = dbgr.getMainExtensionDescriptor(); /* __GDPR__ "debugSessionStart" : { "type": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "breakpointCount": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "exceptionBreakpoints": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "watchExpressionsCount": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "extensionName": { "classification": "PublicNonPersonalData", "purpose": "FeatureInsight" }, "isBuiltin": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true}, "launchJsonExists": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true } } */ return this.telemetryService.publicLog('debugSessionStart', { type: type, breakpointCount: this.model.getBreakpoints().length, exceptionBreakpoints: this.model.getExceptionBreakpoints(), watchExpressionsCount: this.model.getWatchExpressions().length, extensionName: extension.identifier.value, isBuiltin: extension.isBuiltin, launchJsonExists: root && !!this.configurationService.getValue<IGlobalConfig>('launch', { resource: root.uri }) }); } private telemetryDebugSessionStop(session: IDebugSession, adapterExitEvent: AdapterEndEvent): Promise<any> { const breakpoints = this.model.getBreakpoints(); /* __GDPR__ "debugSessionStop" : { "type" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "success": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "sessionLengthInSeconds": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "breakpointCount": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "watchExpressionsCount": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true } } */ return this.telemetryService.publicLog('debugSessionStop', { type: session && session.configuration.type, success: adapterExitEvent.emittedStopped || breakpoints.length === 0, sessionLengthInSeconds: adapterExitEvent.sessionLengthInSeconds, breakpointCount: breakpoints.length, watchExpressionsCount: this.model.getWatchExpressions().length }); } private telemetryDebugAddBreakpoint(breakpoint: IBreakpoint, context: string): Promise<any> { /* __GDPR__ "debugAddBreakpoint" : { "context": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "hasCondition": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "hasHitCondition": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "hasLogMessage": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true } } */ return this.telemetryService.publicLog('debugAddBreakpoint', { context: context, hasCondition: !!breakpoint.condition, hasHitCondition: !!breakpoint.hitCondition, hasLogMessage: !!breakpoint.logMessage }); } }
src/vs/workbench/contrib/debug/browser/debugService.ts
1
https://github.com/microsoft/vscode/commit/88e80b9a18b2cc3de0ca3a02977c3e2d4b088a60
[ 0.9645591378211975, 0.021950026974081993, 0.00016416447761002928, 0.00017412859597243369, 0.12940405309200287 ]
{ "id": 5, "code_window": [ "\t});\n", "}\n", "\n", "export function isSessionAttach(session: IDebugSession): boolean {\n", "\treturn !session.parentSession && session.configuration.request === 'attach' && !isExtensionHostDebugging(session.configuration);\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ "\treturn !session.parentSession && session.configuration.request === 'attach' && !getExtensionHostDebugSession(session);\n" ], "file_path": "src/vs/workbench/contrib/debug/common/debugUtils.ts", "type": "replace", "edit_start_line_idx": 26 }
{ "extends": "../shared.tsconfig.json", "compilerOptions": { "outDir": "./out" }, "include": [ "src/**/*" ] }
extensions/npm/tsconfig.json
0
https://github.com/microsoft/vscode/commit/88e80b9a18b2cc3de0ca3a02977c3e2d4b088a60
[ 0.00017035056953318417, 0.00017035056953318417, 0.00017035056953318417, 0.00017035056953318417, 0 ]
{ "id": 5, "code_window": [ "\t});\n", "}\n", "\n", "export function isSessionAttach(session: IDebugSession): boolean {\n", "\treturn !session.parentSession && session.configuration.request === 'attach' && !isExtensionHostDebugging(session.configuration);\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ "\treturn !session.parentSession && session.configuration.request === 'attach' && !getExtensionHostDebugSession(session);\n" ], "file_path": "src/vs/workbench/contrib/debug/common/debugUtils.ts", "type": "replace", "edit_start_line_idx": 26 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { escape } from 'vs/base/common/strings'; import { localize } from 'vs/nls'; export default () => ` <div class="welcomePageContainer"> <div class="welcomePage"> <div class="title"> <h1 class="caption">${escape(localize('welcomePage.vscode', "Visual Studio Code"))}</h1> <p class="subtitle detail">${escape(localize({ key: 'welcomePage.editingEvolved', comment: ['Shown as subtitle on the Welcome page.'] }, "Editing evolved"))}</p> </div> <div class="row"> <div class="splash"> <div class="section start"> <h2 class="caption">${escape(localize('welcomePage.start', "Start"))}</h2> <ul> <li><a href="command:workbench.action.files.newUntitledFile">${escape(localize('welcomePage.newFile', "New file"))}</a></li> <li class="mac-only"><a href="command:workbench.action.files.openFileFolder">${escape(localize('welcomePage.openFolder', "Open folder..."))}</a></li> <li class="windows-only linux-only"><a href="command:workbench.action.files.openFolder">${escape(localize('welcomePage.openFolder', "Open folder..."))}</a></li> <li><a href="command:workbench.action.addRootFolder">${escape(localize('welcomePage.addWorkspaceFolder', "Add workspace folder..."))}</a></li> </ul> </div> <div class="section recent"> <h2 class="caption">${escape(localize('welcomePage.recent', "Recent"))}</h2> <ul class="list"> <!-- Filled programmatically --> <li class="moreRecent"><a href="command:workbench.action.openRecent">${escape(localize('welcomePage.moreRecent', "More..."))}</a><span class="path detail if_shortcut" data-command="workbench.action.openRecent">(<span class="shortcut" data-command="workbench.action.openRecent"></span>)</span></li> </ul> <p class="none detail">${escape(localize('welcomePage.noRecentFolders', "No recent folders"))}</p> </div> <div class="section help"> <h2 class="caption">${escape(localize('welcomePage.help', "Help"))}</h2> <ul> <li class="keybindingsReferenceLink"><a href="command:workbench.action.keybindingsReference">${escape(localize('welcomePage.keybindingsCheatsheet', "Printable keyboard cheatsheet"))}</a></li> <li><a href="command:workbench.action.openIntroductoryVideosUrl">${escape(localize('welcomePage.introductoryVideos', "Introductory videos"))}</a></li> <li><a href="command:workbench.action.openTipsAndTricksUrl">${escape(localize('welcomePage.tipsAndTricks', "Tips and Tricks"))}</a></li> <li><a href="command:workbench.action.openDocumentationUrl">${escape(localize('welcomePage.productDocumentation', "Product documentation"))}</a></li> <li><a href="https://github.com/Microsoft/vscode">${escape(localize('welcomePage.gitHubRepository', "GitHub repository"))}</a></li> <li><a href="http://stackoverflow.com/questions/tagged/vscode?sort=votes&pageSize=50">${escape(localize('welcomePage.stackOverflow', "Stack Overflow"))}</a></li> <li><a href="command:workbench.action.openNewsletterSignupUrl">${escape(localize('welcomePage.newsletterSignup', "Join our Newsletter"))}</a></li> </ul> </div> <p class="showOnStartup"><input type="checkbox" id="showOnStartup" class="checkbox"> <label class="caption" for="showOnStartup">${escape(localize('welcomePage.showOnStartup', "Show welcome page on startup"))}</label></p> </div> <div class="commands"> <div class="section customize"> <h2 class="caption">${escape(localize('welcomePage.customize', "Customize"))}</h2> <div class="list"> <div class="item showLanguageExtensions"><button role="group" data-href="command:workbench.extensions.action.showLanguageExtensions"><h3 class="caption">${escape(localize('welcomePage.installExtensionPacks', "Tools and languages"))}</h3> <span class="detail">${escape(localize('welcomePage.installExtensionPacksDescription', "Install support for {0} and {1}")) .replace('{0}', `<span class="extensionPackList"></span>`) .replace('{1}', `<a href="command:workbench.extensions.action.showLanguageExtensions" title="${localize('welcomePage.showLanguageExtensions', "Show more language extensions")}">${escape(localize('welcomePage.moreExtensions', "more"))}</a>`)} </span></button></div> <div class="item showRecommendedKeymapExtensions"><button role="group" data-href="command:workbench.extensions.action.showRecommendedKeymapExtensions"><h3 class="caption">${escape(localize('welcomePage.installKeymapDescription', "Settings and keybindings"))}</h3> <span class="detail">${escape(localize('welcomePage.installKeymapExtension', "Install the settings and keyboard shortcuts of {0} and {1}")) .replace('{0}', `<span class="keymapList"></span>`) .replace('{1}', `<a href="command:workbench.extensions.action.showRecommendedKeymapExtensions" title="${localize('welcomePage.showKeymapExtensions', "Show other keymap extensions")}">${escape(localize('welcomePage.others', "others"))}</a>`)} </span></button></div> <div class="item selectTheme"><button data-href="command:workbench.action.selectTheme"><h3 class="caption">${escape(localize('welcomePage.colorTheme', "Color theme"))}</h3> <span class="detail">${escape(localize('welcomePage.colorThemeDescription', "Make the editor and your code look the way you love"))}</span></button></div> </div> </div> <div class="section learn"> <h2 class="caption">${escape(localize('welcomePage.learn', "Learn"))}</h2> <div class="list"> <div class="item showCommands"><button data-href="command:workbench.action.showCommands"><h3 class="caption">${escape(localize('welcomePage.showCommands', "Find and run all commands"))}</h3> <span class="detail">${escape(localize('welcomePage.showCommandsDescription', "Rapidly access and search commands from the Command Palette ({0})")).replace('{0}', '<span class="shortcut" data-command="workbench.action.showCommands"></span>')}</span></button></div> <div class="item showInterfaceOverview"><button data-href="command:workbench.action.showInterfaceOverview"><h3 class="caption">${escape(localize('welcomePage.interfaceOverview', "Interface overview"))}</h3> <span class="detail">${escape(localize('welcomePage.interfaceOverviewDescription', "Get a visual overlay highlighting the major components of the UI"))}</span></button></div> <div class="item showInteractivePlayground"><button data-href="command:workbench.action.showInteractivePlayground"><h3 class="caption">${escape(localize('welcomePage.interactivePlayground', "Interactive playground"))}</h3> <span class="detail">${escape(localize('welcomePage.interactivePlaygroundDescription', "Try essential editor features out in a short walkthrough"))}</span></button></div> </div> </div> </div> </div> </div> </div> `;
src/vs/workbench/contrib/welcome/page/browser/vs_code_welcome_page.ts
0
https://github.com/microsoft/vscode/commit/88e80b9a18b2cc3de0ca3a02977c3e2d4b088a60
[ 0.00025786328478716314, 0.00018003857985604554, 0.0001649081241339445, 0.00016893137944862247, 0.000029549295504693873 ]
{ "id": 5, "code_window": [ "\t});\n", "}\n", "\n", "export function isSessionAttach(session: IDebugSession): boolean {\n", "\treturn !session.parentSession && session.configuration.request === 'attach' && !isExtensionHostDebugging(session.configuration);\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ "\treturn !session.parentSession && session.configuration.request === 'attach' && !getExtensionHostDebugSession(session);\n" ], "file_path": "src/vs/workbench/contrib/debug/common/debugUtils.ts", "type": "replace", "edit_start_line_idx": 26 }
{ "registrations": [ { "component": { "type": "git", "git": { "name": "atom/language-java", "repositoryUrl": "https://github.com/atom/language-java", "commitHash": "123beb50115b0bfb0db8f2325df6d05fb8a016a8" } }, "license": "MIT", "version": "0.31.3" } ], "version": 1 }
extensions/java/cgmanifest.json
0
https://github.com/microsoft/vscode/commit/88e80b9a18b2cc3de0ca3a02977c3e2d4b088a60
[ 0.0001731144147925079, 0.00017120662960223854, 0.00016929884441196918, 0.00017120662960223854, 0.000001907785190269351 ]
{ "id": 6, "code_window": [ "}\n", "\n", "export function isExtensionHostDebugging(config: IConfig) {\n", "\tif (!config.type) {\n", "\t\treturn false;\n", "\t}\n", "\n" ], "labels": [ "keep", "keep", "replace", "replace", "replace", "keep", "keep" ], "after_edit": [ "/**\n", " * Returns the session or any parent which is an extension host debug session.\n", " * Returns undefined if there's none.\n", " */\n", "export function getExtensionHostDebugSession(session: IDebugSession): IDebugSession | void {\n", "\tlet type = session.configuration.type;\n", "\tif (!type) {\n", "\t\treturn;\n" ], "file_path": "src/vs/workbench/contrib/debug/common/debugUtils.ts", "type": "replace", "edit_start_line_idx": 29 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as nls from 'vs/nls'; import { Event, Emitter } from 'vs/base/common/event'; import { URI as uri } from 'vs/base/common/uri'; import { first, distinct } from 'vs/base/common/arrays'; import * as errors from 'vs/base/common/errors'; import severity from 'vs/base/common/severity'; import * as aria from 'vs/base/browser/ui/aria/aria'; import { IContextKeyService, IContextKey } from 'vs/platform/contextkey/common/contextkey'; import { IMarkerService } from 'vs/platform/markers/common/markers'; import { ILifecycleService } from 'vs/platform/lifecycle/common/lifecycle'; import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { FileChangesEvent, FileChangeType, IFileService } from 'vs/platform/files/common/files'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage'; import { DebugModel, ExceptionBreakpoint, FunctionBreakpoint, Breakpoint, Expression, DataBreakpoint } from 'vs/workbench/contrib/debug/common/debugModel'; import { ViewModel } from 'vs/workbench/contrib/debug/common/debugViewModel'; import * as debugactions from 'vs/workbench/contrib/debug/browser/debugActions'; import { ConfigurationManager } from 'vs/workbench/contrib/debug/browser/debugConfigurationManager'; import Constants from 'vs/workbench/contrib/markers/browser/constants'; import { ITaskService, ITaskSummary } from 'vs/workbench/contrib/tasks/common/taskService'; import { VIEWLET_ID as EXPLORER_VIEWLET_ID } from 'vs/workbench/contrib/files/common/files'; import { IViewletService } from 'vs/workbench/services/viewlet/browser/viewlet'; import { IPanelService } from 'vs/workbench/services/panel/common/panelService'; import { IWorkbenchLayoutService, Parts } from 'vs/workbench/services/layout/browser/layoutService'; import { ITextFileService } from 'vs/workbench/services/textfile/common/textfiles'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IWorkspaceContextService, WorkbenchState, IWorkspaceFolder, IWorkspace } from 'vs/platform/workspace/common/workspace'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { parse, getFirstFrame } from 'vs/base/common/console'; import { TaskEvent, TaskEventKind, TaskIdentifier } from 'vs/workbench/contrib/tasks/common/tasks'; import { IDialogService } from 'vs/platform/dialogs/common/dialogs'; import { INotificationService } from 'vs/platform/notification/common/notification'; import { IAction } from 'vs/base/common/actions'; import { deepClone, equals } from 'vs/base/common/objects'; import { DebugSession } from 'vs/workbench/contrib/debug/browser/debugSession'; import { dispose, IDisposable } from 'vs/base/common/lifecycle'; import { IDebugService, State, IDebugSession, CONTEXT_DEBUG_TYPE, CONTEXT_DEBUG_STATE, CONTEXT_IN_DEBUG_MODE, IThread, IDebugConfiguration, VIEWLET_ID, REPL_ID, IConfig, ILaunch, IViewModel, IConfigurationManager, IDebugModel, IEnablement, IBreakpoint, IBreakpointData, ICompound, IGlobalConfig, IStackFrame, AdapterEndEvent, getStateLabel, IDebugSessionOptions, CONTEXT_DEBUG_UX } from 'vs/workbench/contrib/debug/common/debug'; import { isExtensionHostDebugging } from 'vs/workbench/contrib/debug/common/debugUtils'; import { isErrorWithActions, createErrorWithActions } from 'vs/base/common/errorsWithActions'; import { RunOnceScheduler } from 'vs/base/common/async'; import { IExtensionHostDebugService } from 'vs/platform/debug/common/extensionHostDebug'; import { isCodeEditor } from 'vs/editor/browser/editorBrowser'; import { CancellationTokenSource } from 'vs/base/common/cancellation'; import { withUndefinedAsNull } from 'vs/base/common/types'; const DEBUG_BREAKPOINTS_KEY = 'debug.breakpoint'; const DEBUG_FUNCTION_BREAKPOINTS_KEY = 'debug.functionbreakpoint'; const DEBUG_DATA_BREAKPOINTS_KEY = 'debug.databreakpoint'; const DEBUG_EXCEPTION_BREAKPOINTS_KEY = 'debug.exceptionbreakpoint'; const DEBUG_WATCH_EXPRESSIONS_KEY = 'debug.watchexpressions'; function once(match: (e: TaskEvent) => boolean, event: Event<TaskEvent>): Event<TaskEvent> { return (listener, thisArgs = null, disposables?) => { const result = event(e => { if (match(e)) { result.dispose(); return listener.call(thisArgs, e); } }, null, disposables); return result; }; } const enum TaskRunResult { Failure, Success } export class DebugService implements IDebugService { _serviceBrand: undefined; private readonly _onDidChangeState: Emitter<State>; private readonly _onDidNewSession: Emitter<IDebugSession>; private readonly _onWillNewSession: Emitter<IDebugSession>; private readonly _onDidEndSession: Emitter<IDebugSession>; private model: DebugModel; private viewModel: ViewModel; private configurationManager: ConfigurationManager; private toDispose: IDisposable[]; private debugType: IContextKey<string>; private debugState: IContextKey<string>; private inDebugMode: IContextKey<boolean>; private debugUx: IContextKey<string>; private breakpointsToSendOnResourceSaved: Set<string>; private initializing = false; private previousState: State | undefined; private initCancellationToken: CancellationTokenSource | undefined; constructor( @IStorageService private readonly storageService: IStorageService, @IEditorService private readonly editorService: IEditorService, @ITextFileService private readonly textFileService: ITextFileService, @IViewletService private readonly viewletService: IViewletService, @IPanelService private readonly panelService: IPanelService, @INotificationService private readonly notificationService: INotificationService, @IDialogService private readonly dialogService: IDialogService, @IWorkbenchLayoutService private readonly layoutService: IWorkbenchLayoutService, @ITelemetryService private readonly telemetryService: ITelemetryService, @IWorkspaceContextService private readonly contextService: IWorkspaceContextService, @IContextKeyService contextKeyService: IContextKeyService, @ILifecycleService private readonly lifecycleService: ILifecycleService, @IInstantiationService private readonly instantiationService: IInstantiationService, @IExtensionService private readonly extensionService: IExtensionService, @IMarkerService private readonly markerService: IMarkerService, @ITaskService private readonly taskService: ITaskService, @IFileService private readonly fileService: IFileService, @IConfigurationService private readonly configurationService: IConfigurationService, @IExtensionHostDebugService private readonly extensionHostDebugService: IExtensionHostDebugService ) { this.toDispose = []; this.breakpointsToSendOnResourceSaved = new Set<string>(); this._onDidChangeState = new Emitter<State>(); this._onDidNewSession = new Emitter<IDebugSession>(); this._onWillNewSession = new Emitter<IDebugSession>(); this._onDidEndSession = new Emitter<IDebugSession>(); this.configurationManager = this.instantiationService.createInstance(ConfigurationManager); this.toDispose.push(this.configurationManager); this.debugType = CONTEXT_DEBUG_TYPE.bindTo(contextKeyService); this.debugState = CONTEXT_DEBUG_STATE.bindTo(contextKeyService); this.inDebugMode = CONTEXT_IN_DEBUG_MODE.bindTo(contextKeyService); this.debugUx = CONTEXT_DEBUG_UX.bindTo(contextKeyService); this.debugUx.set(!!this.configurationManager.selectedConfiguration.name ? 'default' : 'simple'); this.model = new DebugModel(this.loadBreakpoints(), this.loadFunctionBreakpoints(), this.loadExceptionBreakpoints(), this.loadDataBreakpoints(), this.loadWatchExpressions(), this.textFileService); this.toDispose.push(this.model); this.viewModel = new ViewModel(contextKeyService); this.toDispose.push(this.fileService.onFileChanges(e => this.onFileChanges(e))); this.lifecycleService.onShutdown(this.dispose, this); this.toDispose.push(this.extensionHostDebugService.onAttachSession(event => { const session = this.model.getSession(event.sessionId, true); if (session) { // EH was started in debug mode -> attach to it session.configuration.request = 'attach'; session.configuration.port = event.port; session.setSubId(event.subId); this.launchOrAttachToSession(session); } })); this.toDispose.push(this.extensionHostDebugService.onTerminateSession(event => { const session = this.model.getSession(event.sessionId); if (session && session.subId === event.subId) { session.disconnect(); } })); this.toDispose.push(this.extensionHostDebugService.onLogToSession(event => { const session = this.model.getSession(event.sessionId, true); if (session) { // extension logged output -> show it in REPL const sev = event.log.severity === 'warn' ? severity.Warning : event.log.severity === 'error' ? severity.Error : severity.Info; const { args, stack } = parse(event.log); const frame = !!stack ? getFirstFrame(stack) : undefined; session.logToRepl(sev, args, frame); } })); this.toDispose.push(this.viewModel.onDidFocusStackFrame(() => { this.onStateChange(); })); this.toDispose.push(this.viewModel.onDidFocusSession(() => { this.onStateChange(); })); this.toDispose.push(this.configurationManager.onDidSelectConfiguration(() => { this.debugUx.set(!!(this.state !== State.Inactive || this.configurationManager.selectedConfiguration.name) ? 'default' : 'simple'); })); } getModel(): IDebugModel { return this.model; } getViewModel(): IViewModel { return this.viewModel; } getConfigurationManager(): IConfigurationManager { return this.configurationManager; } sourceIsNotAvailable(uri: uri): void { this.model.sourceIsNotAvailable(uri); } dispose(): void { this.toDispose = dispose(this.toDispose); } //---- state management get state(): State { const focusedSession = this.viewModel.focusedSession; if (focusedSession) { return focusedSession.state; } return this.initializing ? State.Initializing : State.Inactive; } private startInitializingState() { if (!this.initializing) { this.initializing = true; this.onStateChange(); } } private endInitializingState() { if (this.initCancellationToken) { this.initCancellationToken.cancel(); this.initCancellationToken = undefined; } if (this.initializing) { this.initializing = false; this.onStateChange(); } } private onStateChange(): void { const state = this.state; if (this.previousState !== state) { this.debugState.set(getStateLabel(state)); this.inDebugMode.set(state !== State.Inactive); // Only show the simple ux if debug is not yet started and if no launch.json exists this.debugUx.set(((state !== State.Inactive && state !== State.Initializing) || this.configurationManager.selectedConfiguration.name) ? 'default' : 'simple'); this.previousState = state; this._onDidChangeState.fire(state); } } get onDidChangeState(): Event<State> { return this._onDidChangeState.event; } get onDidNewSession(): Event<IDebugSession> { return this._onDidNewSession.event; } get onWillNewSession(): Event<IDebugSession> { return this._onWillNewSession.event; } get onDidEndSession(): Event<IDebugSession> { return this._onDidEndSession.event; } //---- life cycle management /** * main entry point * properly manages compounds, checks for errors and handles the initializing state. */ async startDebugging(launch: ILaunch | undefined, configOrName?: IConfig | string, options?: IDebugSessionOptions): Promise<boolean> { this.startInitializingState(); try { // make sure to save all files and that the configuration is up to date await this.extensionService.activateByEvent('onDebug'); await this.editorService.saveAll(); await this.configurationService.reloadConfiguration(launch ? launch.workspace : undefined); await this.extensionService.whenInstalledExtensionsRegistered(); let config: IConfig | undefined; let compound: ICompound | undefined; if (!configOrName) { configOrName = this.configurationManager.selectedConfiguration.name; } if (typeof configOrName === 'string' && launch) { config = launch.getConfiguration(configOrName); compound = launch.getCompound(configOrName); const sessions = this.model.getSessions(); const alreadyRunningMessage = nls.localize('configurationAlreadyRunning', "There is already a debug configuration \"{0}\" running.", configOrName); if (sessions.some(s => s.configuration.name === configOrName && (!launch || !launch.workspace || !s.root || s.root.uri.toString() === launch.workspace.uri.toString()))) { throw new Error(alreadyRunningMessage); } if (compound && compound.configurations && sessions.some(p => compound!.configurations.indexOf(p.configuration.name) !== -1)) { throw new Error(alreadyRunningMessage); } } else if (typeof configOrName !== 'string') { config = configOrName; } if (compound) { // we are starting a compound debug, first do some error checking and than start each configuration in the compound if (!compound.configurations) { throw new Error(nls.localize({ key: 'compoundMustHaveConfigurations', comment: ['compound indicates a "compounds" configuration item', '"configurations" is an attribute and should not be localized'] }, "Compound must have \"configurations\" attribute set in order to start multiple configurations.")); } if (compound.preLaunchTask) { const taskResult = await this.runTaskAndCheckErrors(launch?.workspace || this.contextService.getWorkspace(), compound.preLaunchTask); if (taskResult === TaskRunResult.Failure) { this.endInitializingState(); return false; } } const values = await Promise.all(compound.configurations.map(configData => { const name = typeof configData === 'string' ? configData : configData.name; if (name === compound!.name) { return Promise.resolve(false); } let launchForName: ILaunch | undefined; if (typeof configData === 'string') { const launchesContainingName = this.configurationManager.getLaunches().filter(l => !!l.getConfiguration(name)); if (launchesContainingName.length === 1) { launchForName = launchesContainingName[0]; } else if (launch && launchesContainingName.length > 1 && launchesContainingName.indexOf(launch) >= 0) { // If there are multiple launches containing the configuration give priority to the configuration in the current launch launchForName = launch; } else { throw new Error(launchesContainingName.length === 0 ? nls.localize('noConfigurationNameInWorkspace', "Could not find launch configuration '{0}' in the workspace.", name) : nls.localize('multipleConfigurationNamesInWorkspace', "There are multiple launch configurations '{0}' in the workspace. Use folder name to qualify the configuration.", name)); } } else if (configData.folder) { const launchesMatchingConfigData = this.configurationManager.getLaunches().filter(l => l.workspace && l.workspace.name === configData.folder && !!l.getConfiguration(configData.name)); if (launchesMatchingConfigData.length === 1) { launchForName = launchesMatchingConfigData[0]; } else { throw new Error(nls.localize('noFolderWithName', "Can not find folder with name '{0}' for configuration '{1}' in compound '{2}'.", configData.folder, configData.name, compound!.name)); } } return this.createSession(launchForName, launchForName!.getConfiguration(name), options); })); const result = values.every(success => !!success); // Compound launch is a success only if each configuration launched successfully this.endInitializingState(); return result; } if (configOrName && !config) { const message = !!launch ? nls.localize('configMissing', "Configuration '{0}' is missing in 'launch.json'.", typeof configOrName === 'string' ? configOrName : JSON.stringify(configOrName)) : nls.localize('launchJsonDoesNotExist', "'launch.json' does not exist."); throw new Error(message); } const result = await this.createSession(launch, config, options); this.endInitializingState(); return result; } catch (err) { // make sure to get out of initializing state, and propagate the result this.endInitializingState(); return Promise.reject(err); } } /** * gets the debugger for the type, resolves configurations by providers, substitutes variables and runs prelaunch tasks */ private async createSession(launch: ILaunch | undefined, config: IConfig | undefined, options?: IDebugSessionOptions): Promise<boolean> { // We keep the debug type in a separate variable 'type' so that a no-folder config has no attributes. // Storing the type in the config would break extensions that assume that the no-folder case is indicated by an empty config. let type: string | undefined; if (config) { type = config.type; } else { // a no-folder workspace has no launch.config config = Object.create(null); } const unresolvedConfig = deepClone(config); if (options && options.noDebug) { config!.noDebug = true; } if (!type) { const guess = await this.configurationManager.guessDebugger(); if (guess) { type = guess.type; } } this.initCancellationToken = new CancellationTokenSource(); const configByProviders = await this.configurationManager.resolveConfigurationByProviders(launch && launch.workspace ? launch.workspace.uri : undefined, type, config!, this.initCancellationToken.token); // a falsy config indicates an aborted launch if (configByProviders && configByProviders.type) { try { const resolvedConfig = await this.substituteVariables(launch, configByProviders); if (!resolvedConfig) { // User canceled resolving of interactive variables, silently return return false; } if (!this.configurationManager.getDebugger(resolvedConfig.type) || (configByProviders.request !== 'attach' && configByProviders.request !== 'launch')) { let message: string; if (configByProviders.request !== 'attach' && configByProviders.request !== 'launch') { message = configByProviders.request ? nls.localize('debugRequestNotSupported', "Attribute '{0}' has an unsupported value '{1}' in the chosen debug configuration.", 'request', configByProviders.request) : nls.localize('debugRequesMissing', "Attribute '{0}' is missing from the chosen debug configuration.", 'request'); } else { message = resolvedConfig.type ? nls.localize('debugTypeNotSupported', "Configured debug type '{0}' is not supported.", resolvedConfig.type) : nls.localize('debugTypeMissing', "Missing property 'type' for the chosen launch configuration."); } await this.showError(message); return false; } const workspace = launch ? launch.workspace : this.contextService.getWorkspace(); const taskResult = await this.runTaskAndCheckErrors(workspace, resolvedConfig.preLaunchTask); if (taskResult === TaskRunResult.Success) { return this.doCreateSession(launch?.workspace, { resolved: resolvedConfig, unresolved: unresolvedConfig }, options); } return false; } catch (err) { if (err && err.message) { await this.showError(err.message); } else if (this.contextService.getWorkbenchState() === WorkbenchState.EMPTY) { await this.showError(nls.localize('noFolderWorkspaceDebugError', "The active file can not be debugged. Make sure it is saved and that you have a debug extension installed for that file type.")); } if (launch) { await launch.openConfigFile(false, true, undefined, this.initCancellationToken ? this.initCancellationToken.token : undefined); } return false; } } if (launch && type && configByProviders === null) { // show launch.json only for "config" being "null". await launch.openConfigFile(false, true, type, this.initCancellationToken ? this.initCancellationToken.token : undefined); } return false; } /** * instantiates the new session, initializes the session, registers session listeners and reports telemetry */ private async doCreateSession(root: IWorkspaceFolder | undefined, configuration: { resolved: IConfig, unresolved: IConfig | undefined }, options?: IDebugSessionOptions): Promise<boolean> { const session = this.instantiationService.createInstance(DebugSession, configuration, root, this.model, options); this.model.addSession(session); // register listeners as the very first thing! this.registerSessionListeners(session); // since the Session is now properly registered under its ID and hooked, we can announce it // this event doesn't go to extensions this._onWillNewSession.fire(session); const openDebug = this.configurationService.getValue<IDebugConfiguration>('debug').openDebug; // Open debug viewlet based on the visibility of the side bar and openDebug setting. Do not open for 'run without debug' if (!configuration.resolved.noDebug && (openDebug === 'openOnSessionStart' || (openDebug === 'openOnFirstSessionStart' && this.viewModel.firstSessionStart))) { await this.viewletService.openViewlet(VIEWLET_ID); } try { await this.launchOrAttachToSession(session); const internalConsoleOptions = session.configuration.internalConsoleOptions || this.configurationService.getValue<IDebugConfiguration>('debug').internalConsoleOptions; if (internalConsoleOptions === 'openOnSessionStart' || (this.viewModel.firstSessionStart && internalConsoleOptions === 'openOnFirstSessionStart')) { this.panelService.openPanel(REPL_ID, false); } this.viewModel.firstSessionStart = false; const showSubSessions = this.configurationService.getValue<IDebugConfiguration>('debug').showSubSessionsInToolBar; const sessions = this.model.getSessions(); const shownSessions = showSubSessions ? sessions : sessions.filter(s => !s.parentSession); if (shownSessions.length > 1) { this.viewModel.setMultiSessionView(true); } // since the initialized response has arrived announce the new Session (including extensions) this._onDidNewSession.fire(session); await this.telemetryDebugSessionStart(root, session.configuration.type); return true; } catch (error) { if (errors.isPromiseCanceledError(error)) { // don't show 'canceled' error messages to the user #7906 return false; } // Show the repl if some error got logged there #5870 if (session && session.getReplElements().length > 0) { this.panelService.openPanel(REPL_ID, false); } if (session.configuration && session.configuration.request === 'attach' && session.configuration.__autoAttach) { // ignore attach timeouts in auto attach mode return false; } const errorMessage = error instanceof Error ? error.message : error; await this.showError(errorMessage, isErrorWithActions(error) ? error.actions : []); return false; } } private async launchOrAttachToSession(session: IDebugSession, forceFocus = false): Promise<void> { const dbgr = this.configurationManager.getDebugger(session.configuration.type); try { await session.initialize(dbgr!); await session.launchOrAttach(session.configuration); if (forceFocus || !this.viewModel.focusedSession) { await this.focusStackFrame(undefined, undefined, session); } } catch (err) { session.shutdown(); return Promise.reject(err); } } private registerSessionListeners(session: IDebugSession): void { const sessionRunningScheduler = new RunOnceScheduler(() => { // Do not immediatly defocus the stack frame if the session is running if (session.state === State.Running && this.viewModel.focusedSession === session) { this.viewModel.setFocus(undefined, this.viewModel.focusedThread, session, false); } }, 200); this.toDispose.push(session.onDidChangeState(() => { if (session.state === State.Running && this.viewModel.focusedSession === session) { sessionRunningScheduler.schedule(); } if (session === this.viewModel.focusedSession) { this.onStateChange(); } })); this.toDispose.push(session.onDidEndAdapter(async adapterExitEvent => { if (adapterExitEvent.error) { this.notificationService.error(nls.localize('debugAdapterCrash', "Debug adapter process has terminated unexpectedly ({0})", adapterExitEvent.error.message || adapterExitEvent.error.toString())); } // 'Run without debugging' mode VSCode must terminate the extension host. More details: #3905 if (isExtensionHostDebugging(session.configuration) && session.state === State.Running && session.configuration.noDebug) { this.extensionHostDebugService.close(session.getId()); } this.telemetryDebugSessionStop(session, adapterExitEvent); if (session.configuration.postDebugTask) { try { await this.runTask(session.root, session.configuration.postDebugTask); } catch (err) { this.notificationService.error(err); } } session.shutdown(); this.endInitializingState(); this._onDidEndSession.fire(session); const focusedSession = this.viewModel.focusedSession; if (focusedSession && focusedSession.getId() === session.getId()) { await this.focusStackFrame(undefined); } if (this.model.getSessions().length === 0) { this.viewModel.setMultiSessionView(false); if (this.layoutService.isVisible(Parts.SIDEBAR_PART) && this.configurationService.getValue<IDebugConfiguration>('debug').openExplorerOnEnd) { this.viewletService.openViewlet(EXPLORER_VIEWLET_ID); } // Data breakpoints that can not be persisted should be cleared when a session ends const dataBreakpoints = this.model.getDataBreakpoints().filter(dbp => !dbp.canPersist); dataBreakpoints.forEach(dbp => this.model.removeDataBreakpoints(dbp.getId())); } })); } async restartSession(session: IDebugSession, restartData?: any): Promise<any> { await this.editorService.saveAll(); const isAutoRestart = !!restartData; const runTasks: () => Promise<TaskRunResult> = async () => { if (isAutoRestart) { // Do not run preLaunch and postDebug tasks for automatic restarts return Promise.resolve(TaskRunResult.Success); } await this.runTask(session.root, session.configuration.postDebugTask); return this.runTaskAndCheckErrors(session.root, session.configuration.preLaunchTask); }; if (isExtensionHostDebugging(session.configuration)) { const taskResult = await runTasks(); if (taskResult === TaskRunResult.Success) { this.extensionHostDebugService.reload(session.getId()); } return; } if (session.capabilities.supportsRestartRequest) { const taskResult = await runTasks(); if (taskResult === TaskRunResult.Success) { await session.restart(); } return; } const shouldFocus = !!this.viewModel.focusedSession && session.getId() === this.viewModel.focusedSession.getId(); // If the restart is automatic -> disconnect, otherwise -> terminate #55064 if (isAutoRestart) { await session.disconnect(true); } else { await session.terminate(true); } return new Promise<void>((c, e) => { setTimeout(async () => { const taskResult = await runTasks(); if (taskResult !== TaskRunResult.Success) { return; } // Read the configuration again if a launch.json has been changed, if not just use the inmemory configuration let needsToSubstitute = false; let unresolved: IConfig | undefined; const launch = session.root ? this.configurationManager.getLaunch(session.root.uri) : undefined; if (launch) { unresolved = launch.getConfiguration(session.configuration.name); if (unresolved && !equals(unresolved, session.unresolvedConfiguration)) { // Take the type from the session since the debug extension might overwrite it #21316 unresolved.type = session.configuration.type; unresolved.noDebug = session.configuration.noDebug; needsToSubstitute = true; } } let resolved: IConfig | undefined | null = session.configuration; if (launch && needsToSubstitute && unresolved) { this.initCancellationToken = new CancellationTokenSource(); const resolvedByProviders = await this.configurationManager.resolveConfigurationByProviders(launch.workspace ? launch.workspace.uri : undefined, unresolved.type, unresolved, this.initCancellationToken.token); if (resolvedByProviders) { resolved = await this.substituteVariables(launch, resolvedByProviders); } else { resolved = resolvedByProviders; } } if (!resolved) { return c(undefined); } session.setConfiguration({ resolved, unresolved }); session.configuration.__restart = restartData; try { await this.launchOrAttachToSession(session, shouldFocus); this._onDidNewSession.fire(session); c(undefined); } catch (error) { e(error); } }, 300); }); } stopSession(session: IDebugSession): Promise<any> { if (session) { return session.terminate(); } const sessions = this.model.getSessions(); if (sessions.length === 0) { this.endInitializingState(); } return Promise.all(sessions.map(s => s.terminate())); } private async substituteVariables(launch: ILaunch | undefined, config: IConfig): Promise<IConfig | undefined> { const dbg = this.configurationManager.getDebugger(config.type); if (dbg) { let folder: IWorkspaceFolder | undefined = undefined; if (launch && launch.workspace) { folder = launch.workspace; } else { const folders = this.contextService.getWorkspace().folders; if (folders.length === 1) { folder = folders[0]; } } try { return await dbg.substituteVariables(folder, config); } catch (err) { this.showError(err.message); return undefined; // bail out } } return Promise.resolve(config); } private async showError(message: string, errorActions: ReadonlyArray<IAction> = []): Promise<void> { const configureAction = this.instantiationService.createInstance(debugactions.ConfigureAction, debugactions.ConfigureAction.ID, debugactions.ConfigureAction.LABEL); const actions = [...errorActions, configureAction]; const { choice } = await this.dialogService.show(severity.Error, message, actions.map(a => a.label).concat(nls.localize('cancel', "Cancel")), { cancelId: actions.length }); if (choice < actions.length) { return actions[choice].run(); } return undefined; } //---- task management private async runTaskAndCheckErrors(root: IWorkspaceFolder | IWorkspace | undefined, taskId: string | TaskIdentifier | undefined): Promise<TaskRunResult> { try { const taskSummary = await this.runTask(root, taskId); const errorCount = taskId ? this.markerService.getStatistics().errors : 0; const successExitCode = taskSummary && taskSummary.exitCode === 0; const failureExitCode = taskSummary && taskSummary.exitCode !== 0; const onTaskErrors = this.configurationService.getValue<IDebugConfiguration>('debug').onTaskErrors; if (successExitCode || onTaskErrors === 'debugAnyway' || (errorCount === 0 && !failureExitCode)) { return TaskRunResult.Success; } if (onTaskErrors === 'showErrors') { this.panelService.openPanel(Constants.MARKERS_PANEL_ID); return Promise.resolve(TaskRunResult.Failure); } const taskLabel = typeof taskId === 'string' ? taskId : taskId ? taskId.name : ''; const message = errorCount > 1 ? nls.localize('preLaunchTaskErrors', "Errors exist after running preLaunchTask '{0}'.", taskLabel) : errorCount === 1 ? nls.localize('preLaunchTaskError', "Error exists after running preLaunchTask '{0}'.", taskLabel) : nls.localize('preLaunchTaskExitCode', "The preLaunchTask '{0}' terminated with exit code {1}.", taskLabel, taskSummary ? taskSummary.exitCode : 0); const result = await this.dialogService.show(severity.Warning, message, [nls.localize('debugAnyway', "Debug Anyway"), nls.localize('showErrors', "Show Errors"), nls.localize('cancel', "Cancel")], { checkbox: { label: nls.localize('remember', "Remember my choice in user settings"), }, cancelId: 2 }); if (result.choice === 2) { return Promise.resolve(TaskRunResult.Failure); } const debugAnyway = result.choice === 0; if (result.checkboxChecked) { this.configurationService.updateValue('debug.onTaskErrors', debugAnyway ? 'debugAnyway' : 'showErrors'); } if (debugAnyway) { return TaskRunResult.Success; } this.panelService.openPanel(Constants.MARKERS_PANEL_ID); return Promise.resolve(TaskRunResult.Failure); } catch (err) { await this.showError(err.message, [this.taskService.configureAction()]); return TaskRunResult.Failure; } } private async runTask(root: IWorkspace | IWorkspaceFolder | undefined, taskId: string | TaskIdentifier | undefined): Promise<ITaskSummary | null> { if (!taskId) { return Promise.resolve(null); } if (!root) { return Promise.reject(new Error(nls.localize('invalidTaskReference', "Task '{0}' can not be referenced from a launch configuration that is in a different workspace folder.", typeof taskId === 'string' ? taskId : taskId.type))); } // run a task before starting a debug session const task = await this.taskService.getTask(root, taskId); if (!task) { const errorMessage = typeof taskId === 'string' ? nls.localize('DebugTaskNotFoundWithTaskId', "Could not find the task '{0}'.", taskId) : nls.localize('DebugTaskNotFound', "Could not find the specified task."); return Promise.reject(createErrorWithActions(errorMessage)); } // If a task is missing the problem matcher the promise will never complete, so we need to have a workaround #35340 let taskStarted = false; const inactivePromise: Promise<ITaskSummary | null> = new Promise((c, e) => once(e => { // When a task isBackground it will go inactive when it is safe to launch. // But when a background task is terminated by the user, it will also fire an inactive event. // This means that we will not get to see the real exit code from running the task (undefined when terminated by the user). // Catch the ProcessEnded event here, which occurs before inactive, and capture the exit code to prevent this. return (e.kind === TaskEventKind.Inactive || (e.kind === TaskEventKind.ProcessEnded && e.exitCode === undefined)) && e.taskId === task._id; }, this.taskService.onDidStateChange)(e => { taskStarted = true; c(e.kind === TaskEventKind.ProcessEnded ? { exitCode: e.exitCode } : null); })); const promise: Promise<ITaskSummary | null> = this.taskService.getActiveTasks().then(async (tasks): Promise<ITaskSummary | null> => { if (tasks.filter(t => t._id === task._id).length) { // Check that the task isn't busy and if it is, wait for it const busyTasks = await this.taskService.getBusyTasks(); if (busyTasks.filter(t => t._id === task._id).length) { taskStarted = true; return inactivePromise; } // task is already running and isn't busy - nothing to do. return Promise.resolve(null); } once(e => ((e.kind === TaskEventKind.Active) || (e.kind === TaskEventKind.DependsOnStarted)) && e.taskId === task._id, this.taskService.onDidStateChange)(() => { // Task is active, so everything seems to be fine, no need to prompt after 10 seconds // Use case being a slow running task should not be prompted even though it takes more than 10 seconds taskStarted = true; }); const taskPromise = this.taskService.run(task); if (task.configurationProperties.isBackground) { return inactivePromise; } return taskPromise.then(withUndefinedAsNull); }); return new Promise((c, e) => { promise.then(result => { taskStarted = true; c(result); }, error => e(error)); setTimeout(() => { if (!taskStarted) { const errorMessage = typeof taskId === 'string' ? nls.localize('taskNotTrackedWithTaskId', "The specified task cannot be tracked.") : nls.localize('taskNotTracked', "The task '{0}' cannot be tracked.", JSON.stringify(taskId)); e({ severity: severity.Error, message: errorMessage }); } }, 10000); }); } //---- focus management async focusStackFrame(stackFrame: IStackFrame | undefined, thread?: IThread, session?: IDebugSession, explicit?: boolean): Promise<void> { if (!session) { if (stackFrame || thread) { session = stackFrame ? stackFrame.thread.session : thread!.session; } else { const sessions = this.model.getSessions(); const stoppedSession = sessions.filter(s => s.state === State.Stopped).shift(); session = stoppedSession || (sessions.length ? sessions[0] : undefined); } } if (!thread) { if (stackFrame) { thread = stackFrame.thread; } else { const threads = session ? session.getAllThreads() : undefined; const stoppedThread = threads && threads.filter(t => t.stopped).shift(); thread = stoppedThread || (threads && threads.length ? threads[0] : undefined); } } if (!stackFrame) { if (thread) { const callStack = thread.getCallStack(); stackFrame = first(callStack, sf => !!(sf && sf.source && sf.source.available && sf.source.presentationHint !== 'deemphasize'), undefined); } } if (stackFrame) { const editor = await stackFrame.openInEditor(this.editorService, true); if (editor) { const control = editor.getControl(); if (stackFrame && isCodeEditor(control) && control.hasModel()) { const model = control.getModel(); if (stackFrame.range.startLineNumber <= model.getLineCount()) { const lineContent = control.getModel().getLineContent(stackFrame.range.startLineNumber); aria.alert(nls.localize('debuggingPaused', "Debugging paused {0}, {1} {2} {3}", thread && thread.stoppedDetails ? `, reason ${thread.stoppedDetails.reason}` : '', stackFrame.source ? stackFrame.source.name : '', stackFrame.range.startLineNumber, lineContent)); } } } } if (session) { this.debugType.set(session.configuration.type); } else { this.debugType.reset(); } this.viewModel.setFocus(stackFrame, thread, session, !!explicit); } //---- watches addWatchExpression(name: string): void { const we = this.model.addWatchExpression(name); this.viewModel.setSelectedExpression(we); this.storeWatchExpressions(); } renameWatchExpression(id: string, newName: string): void { this.model.renameWatchExpression(id, newName); this.storeWatchExpressions(); } moveWatchExpression(id: string, position: number): void { this.model.moveWatchExpression(id, position); this.storeWatchExpressions(); } removeWatchExpressions(id?: string): void { this.model.removeWatchExpressions(id); this.storeWatchExpressions(); } //---- breakpoints async enableOrDisableBreakpoints(enable: boolean, breakpoint?: IEnablement): Promise<void> { if (breakpoint) { this.model.setEnablement(breakpoint, enable); if (breakpoint instanceof Breakpoint) { await this.sendBreakpoints(breakpoint.uri); } else if (breakpoint instanceof FunctionBreakpoint) { await this.sendFunctionBreakpoints(); } else if (breakpoint instanceof DataBreakpoint) { await this.sendDataBreakpoints(); } else { await this.sendExceptionBreakpoints(); } } else { this.model.enableOrDisableAllBreakpoints(enable); await this.sendAllBreakpoints(); } this.storeBreakpoints(); } async addBreakpoints(uri: uri, rawBreakpoints: IBreakpointData[], context: string): Promise<IBreakpoint[]> { const breakpoints = this.model.addBreakpoints(uri, rawBreakpoints); breakpoints.forEach(bp => aria.status(nls.localize('breakpointAdded', "Added breakpoint, line {0}, file {1}", bp.lineNumber, uri.fsPath))); breakpoints.forEach(bp => this.telemetryDebugAddBreakpoint(bp, context)); await this.sendBreakpoints(uri); this.storeBreakpoints(); return breakpoints; } async updateBreakpoints(uri: uri, data: Map<string, DebugProtocol.Breakpoint>, sendOnResourceSaved: boolean): Promise<void> { this.model.updateBreakpoints(data); if (sendOnResourceSaved) { this.breakpointsToSendOnResourceSaved.add(uri.toString()); } else { await this.sendBreakpoints(uri); } this.storeBreakpoints(); } async removeBreakpoints(id?: string): Promise<void> { const toRemove = this.model.getBreakpoints().filter(bp => !id || bp.getId() === id); toRemove.forEach(bp => aria.status(nls.localize('breakpointRemoved', "Removed breakpoint, line {0}, file {1}", bp.lineNumber, bp.uri.fsPath))); const urisToClear = distinct(toRemove, bp => bp.uri.toString()).map(bp => bp.uri); this.model.removeBreakpoints(toRemove); await Promise.all(urisToClear.map(uri => this.sendBreakpoints(uri))); this.storeBreakpoints(); } setBreakpointsActivated(activated: boolean): Promise<void> { this.model.setBreakpointsActivated(activated); return this.sendAllBreakpoints(); } addFunctionBreakpoint(name?: string, id?: string): void { const newFunctionBreakpoint = this.model.addFunctionBreakpoint(name || '', id); this.viewModel.setSelectedFunctionBreakpoint(newFunctionBreakpoint); } async renameFunctionBreakpoint(id: string, newFunctionName: string): Promise<void> { this.model.renameFunctionBreakpoint(id, newFunctionName); await this.sendFunctionBreakpoints(); this.storeBreakpoints(); } async removeFunctionBreakpoints(id?: string): Promise<void> { this.model.removeFunctionBreakpoints(id); await this.sendFunctionBreakpoints(); this.storeBreakpoints(); } async addDataBreakpoint(label: string, dataId: string, canPersist: boolean): Promise<void> { this.model.addDataBreakpoint(label, dataId, canPersist); await this.sendDataBreakpoints(); this.storeBreakpoints(); } async removeDataBreakpoints(id?: string): Promise<void> { this.model.removeDataBreakpoints(id); await this.sendDataBreakpoints(); this.storeBreakpoints(); } async sendAllBreakpoints(session?: IDebugSession): Promise<any> { await Promise.all(distinct(this.model.getBreakpoints(), bp => bp.uri.toString()).map(bp => this.sendBreakpoints(bp.uri, false, session))); await this.sendFunctionBreakpoints(session); await this.sendDataBreakpoints(session); // send exception breakpoints at the end since some debug adapters rely on the order await this.sendExceptionBreakpoints(session); } private sendBreakpoints(modelUri: uri, sourceModified = false, session?: IDebugSession): Promise<void> { const breakpointsToSend = this.model.getBreakpoints({ uri: modelUri, enabledOnly: true }); return this.sendToOneOrAllSessions(session, s => s.sendBreakpoints(modelUri, breakpointsToSend, sourceModified) ); } private sendFunctionBreakpoints(session?: IDebugSession): Promise<void> { const breakpointsToSend = this.model.getFunctionBreakpoints().filter(fbp => fbp.enabled && this.model.areBreakpointsActivated()); return this.sendToOneOrAllSessions(session, s => { return s.capabilities.supportsFunctionBreakpoints ? s.sendFunctionBreakpoints(breakpointsToSend) : Promise.resolve(undefined); }); } private sendDataBreakpoints(session?: IDebugSession): Promise<void> { const breakpointsToSend = this.model.getDataBreakpoints().filter(fbp => fbp.enabled && this.model.areBreakpointsActivated()); return this.sendToOneOrAllSessions(session, s => { return s.capabilities.supportsDataBreakpoints ? s.sendDataBreakpoints(breakpointsToSend) : Promise.resolve(undefined); }); } private sendExceptionBreakpoints(session?: IDebugSession): Promise<void> { const enabledExceptionBps = this.model.getExceptionBreakpoints().filter(exb => exb.enabled); return this.sendToOneOrAllSessions(session, s => { return s.sendExceptionBreakpoints(enabledExceptionBps); }); } private async sendToOneOrAllSessions(session: IDebugSession | undefined, send: (session: IDebugSession) => Promise<void>): Promise<void> { if (session) { await send(session); } else { await Promise.all(this.model.getSessions().map(s => send(s))); } } private onFileChanges(fileChangesEvent: FileChangesEvent): void { const toRemove = this.model.getBreakpoints().filter(bp => fileChangesEvent.contains(bp.uri, FileChangeType.DELETED)); if (toRemove.length) { this.model.removeBreakpoints(toRemove); } fileChangesEvent.getUpdated().forEach(event => { if (this.breakpointsToSendOnResourceSaved.delete(event.resource.toString())) { this.sendBreakpoints(event.resource, true); } }); } private loadBreakpoints(): Breakpoint[] { let result: Breakpoint[] | undefined; try { result = JSON.parse(this.storageService.get(DEBUG_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((breakpoint: any) => { return new Breakpoint(uri.parse(breakpoint.uri.external || breakpoint.source.uri.external), breakpoint.lineNumber, breakpoint.column, breakpoint.enabled, breakpoint.condition, breakpoint.hitCondition, breakpoint.logMessage, breakpoint.adapterData, this.textFileService); }); } catch (e) { } return result || []; } private loadFunctionBreakpoints(): FunctionBreakpoint[] { let result: FunctionBreakpoint[] | undefined; try { result = JSON.parse(this.storageService.get(DEBUG_FUNCTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((fb: any) => { return new FunctionBreakpoint(fb.name, fb.enabled, fb.hitCondition, fb.condition, fb.logMessage); }); } catch (e) { } return result || []; } private loadExceptionBreakpoints(): ExceptionBreakpoint[] { let result: ExceptionBreakpoint[] | undefined; try { result = JSON.parse(this.storageService.get(DEBUG_EXCEPTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((exBreakpoint: any) => { return new ExceptionBreakpoint(exBreakpoint.filter, exBreakpoint.label, exBreakpoint.enabled); }); } catch (e) { } return result || []; } private loadDataBreakpoints(): DataBreakpoint[] { let result: DataBreakpoint[] | undefined; try { result = JSON.parse(this.storageService.get(DEBUG_DATA_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((dbp: any) => { return new DataBreakpoint(dbp.label, dbp.dataId, true, dbp.enabled, dbp.hitCondition, dbp.condition, dbp.logMessage); }); } catch (e) { } return result || []; } private loadWatchExpressions(): Expression[] { let result: Expression[] | undefined; try { result = JSON.parse(this.storageService.get(DEBUG_WATCH_EXPRESSIONS_KEY, StorageScope.WORKSPACE, '[]')).map((watchStoredData: { name: string, id: string }) => { return new Expression(watchStoredData.name, watchStoredData.id); }); } catch (e) { } return result || []; } private storeWatchExpressions(): void { const watchExpressions = this.model.getWatchExpressions(); if (watchExpressions.length) { this.storageService.store(DEBUG_WATCH_EXPRESSIONS_KEY, JSON.stringify(watchExpressions.map(we => ({ name: we.name, id: we.getId() }))), StorageScope.WORKSPACE); } else { this.storageService.remove(DEBUG_WATCH_EXPRESSIONS_KEY, StorageScope.WORKSPACE); } } private storeBreakpoints(): void { const breakpoints = this.model.getBreakpoints(); if (breakpoints.length) { this.storageService.store(DEBUG_BREAKPOINTS_KEY, JSON.stringify(breakpoints), StorageScope.WORKSPACE); } else { this.storageService.remove(DEBUG_BREAKPOINTS_KEY, StorageScope.WORKSPACE); } const functionBreakpoints = this.model.getFunctionBreakpoints(); if (functionBreakpoints.length) { this.storageService.store(DEBUG_FUNCTION_BREAKPOINTS_KEY, JSON.stringify(functionBreakpoints), StorageScope.WORKSPACE); } else { this.storageService.remove(DEBUG_FUNCTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE); } const dataBreakpoints = this.model.getDataBreakpoints().filter(dbp => dbp.canPersist); if (dataBreakpoints.length) { this.storageService.store(DEBUG_DATA_BREAKPOINTS_KEY, JSON.stringify(dataBreakpoints), StorageScope.WORKSPACE); } else { this.storageService.remove(DEBUG_DATA_BREAKPOINTS_KEY, StorageScope.WORKSPACE); } const exceptionBreakpoints = this.model.getExceptionBreakpoints(); if (exceptionBreakpoints.length) { this.storageService.store(DEBUG_EXCEPTION_BREAKPOINTS_KEY, JSON.stringify(exceptionBreakpoints), StorageScope.WORKSPACE); } else { this.storageService.remove(DEBUG_EXCEPTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE); } } //---- telemetry private telemetryDebugSessionStart(root: IWorkspaceFolder | undefined, type: string): Promise<void> { const dbgr = this.configurationManager.getDebugger(type); if (!dbgr) { return Promise.resolve(); } const extension = dbgr.getMainExtensionDescriptor(); /* __GDPR__ "debugSessionStart" : { "type": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "breakpointCount": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "exceptionBreakpoints": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "watchExpressionsCount": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "extensionName": { "classification": "PublicNonPersonalData", "purpose": "FeatureInsight" }, "isBuiltin": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true}, "launchJsonExists": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true } } */ return this.telemetryService.publicLog('debugSessionStart', { type: type, breakpointCount: this.model.getBreakpoints().length, exceptionBreakpoints: this.model.getExceptionBreakpoints(), watchExpressionsCount: this.model.getWatchExpressions().length, extensionName: extension.identifier.value, isBuiltin: extension.isBuiltin, launchJsonExists: root && !!this.configurationService.getValue<IGlobalConfig>('launch', { resource: root.uri }) }); } private telemetryDebugSessionStop(session: IDebugSession, adapterExitEvent: AdapterEndEvent): Promise<any> { const breakpoints = this.model.getBreakpoints(); /* __GDPR__ "debugSessionStop" : { "type" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "success": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "sessionLengthInSeconds": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "breakpointCount": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "watchExpressionsCount": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true } } */ return this.telemetryService.publicLog('debugSessionStop', { type: session && session.configuration.type, success: adapterExitEvent.emittedStopped || breakpoints.length === 0, sessionLengthInSeconds: adapterExitEvent.sessionLengthInSeconds, breakpointCount: breakpoints.length, watchExpressionsCount: this.model.getWatchExpressions().length }); } private telemetryDebugAddBreakpoint(breakpoint: IBreakpoint, context: string): Promise<any> { /* __GDPR__ "debugAddBreakpoint" : { "context": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "hasCondition": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "hasHitCondition": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "hasLogMessage": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true } } */ return this.telemetryService.publicLog('debugAddBreakpoint', { context: context, hasCondition: !!breakpoint.condition, hasHitCondition: !!breakpoint.hitCondition, hasLogMessage: !!breakpoint.logMessage }); } }
src/vs/workbench/contrib/debug/browser/debugService.ts
1
https://github.com/microsoft/vscode/commit/88e80b9a18b2cc3de0ca3a02977c3e2d4b088a60
[ 0.9992285966873169, 0.04035552218556404, 0.0001631643099244684, 0.000171594278072007, 0.1832427680492401 ]
{ "id": 6, "code_window": [ "}\n", "\n", "export function isExtensionHostDebugging(config: IConfig) {\n", "\tif (!config.type) {\n", "\t\treturn false;\n", "\t}\n", "\n" ], "labels": [ "keep", "keep", "replace", "replace", "replace", "keep", "keep" ], "after_edit": [ "/**\n", " * Returns the session or any parent which is an extension host debug session.\n", " * Returns undefined if there's none.\n", " */\n", "export function getExtensionHostDebugSession(session: IDebugSession): IDebugSession | void {\n", "\tlet type = session.configuration.type;\n", "\tif (!type) {\n", "\t\treturn;\n" ], "file_path": "src/vs/workbench/contrib/debug/common/debugUtils.ts", "type": "replace", "edit_start_line_idx": 29 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ export const empty = Object.freeze([]); export function equals<T>( a: ReadonlyArray<T>, b: ReadonlyArray<T>, itemEquals: (a: T, b: T) => boolean = (a, b) => a === b ): boolean { if (a === b) { return true; } if (a.length !== b.length) { return false; } return a.every((x, i) => itemEquals(x, b[i])); } export function flatten<T>(array: ReadonlyArray<T>[]): T[] { return Array.prototype.concat.apply([], array); } export function coalesce<T>(array: ReadonlyArray<T | undefined>): T[] { return <T[]>array.filter(e => !!e); }
extensions/typescript-language-features/src/utils/arrays.ts
0
https://github.com/microsoft/vscode/commit/88e80b9a18b2cc3de0ca3a02977c3e2d4b088a60
[ 0.00017229928926099092, 0.00016844649508129805, 0.00016509911802131683, 0.00016794104885775596, 0.000002961105337817571 ]
{ "id": 6, "code_window": [ "}\n", "\n", "export function isExtensionHostDebugging(config: IConfig) {\n", "\tif (!config.type) {\n", "\t\treturn false;\n", "\t}\n", "\n" ], "labels": [ "keep", "keep", "replace", "replace", "replace", "keep", "keep" ], "after_edit": [ "/**\n", " * Returns the session or any parent which is an extension host debug session.\n", " * Returns undefined if there's none.\n", " */\n", "export function getExtensionHostDebugSession(session: IDebugSession): IDebugSession | void {\n", "\tlet type = session.configuration.type;\n", "\tif (!type) {\n", "\t\treturn;\n" ], "file_path": "src/vs/workbench/contrib/debug/common/debugUtils.ts", "type": "replace", "edit_start_line_idx": 29 }
[ { "c": ".ssdsd", "t": "text.pug entity.other.attribute-name.class.pug", "r": { "dark_plus": "entity.other.attribute-name: #9CDCFE", "light_plus": "entity.other.attribute-name: #FF0000", "dark_vs": "entity.other.attribute-name: #9CDCFE", "light_vs": "entity.other.attribute-name: #FF0000", "hc_black": "entity.other.attribute-name: #9CDCFE" } }, { "c": " // asdsdas", "t": "text.pug string.comment.buffered.block.pug", "r": { "dark_plus": "string: #CE9178", "light_plus": "string.comment.buffered.block.pug: #0000FF", "dark_vs": "string: #CE9178", "light_vs": "string.comment.buffered.block.pug: #0000FF", "hc_black": "string: #CE9178" } } ]
extensions/pug/test/colorize-results/test-4287_pug.json
0
https://github.com/microsoft/vscode/commit/88e80b9a18b2cc3de0ca3a02977c3e2d4b088a60
[ 0.00017294516146648675, 0.00017180100257974118, 0.00016954664897639304, 0.00017291118274442852, 0.0000015941255924190045 ]
{ "id": 6, "code_window": [ "}\n", "\n", "export function isExtensionHostDebugging(config: IConfig) {\n", "\tif (!config.type) {\n", "\t\treturn false;\n", "\t}\n", "\n" ], "labels": [ "keep", "keep", "replace", "replace", "replace", "keep", "keep" ], "after_edit": [ "/**\n", " * Returns the session or any parent which is an extension host debug session.\n", " * Returns undefined if there's none.\n", " */\n", "export function getExtensionHostDebugSession(session: IDebugSession): IDebugSession | void {\n", "\tlet type = session.configuration.type;\n", "\tif (!type) {\n", "\t\treturn;\n" ], "file_path": "src/vs/workbench/contrib/debug/common/debugUtils.ts", "type": "replace", "edit_start_line_idx": 29 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import * as path from 'path'; import * as fs from 'fs'; /** * Returns the sha1 commit version of a repository or undefined in case of failure. */ export function getVersion(repo: string): string | undefined { const git = path.join(repo, '.git'); const headPath = path.join(git, 'HEAD'); let head: string; try { head = fs.readFileSync(headPath, 'utf8').trim(); } catch (e) { return undefined; } if (/^[0-9a-f]{40}$/i.test(head)) { return head; } const refMatch = /^ref: (.*)$/.exec(head); if (!refMatch) { return undefined; } const ref = refMatch[1]; const refPath = path.join(git, ref); try { return fs.readFileSync(refPath, 'utf8').trim(); } catch (e) { // noop } const packedRefsPath = path.join(git, 'packed-refs'); let refsRaw: string; try { refsRaw = fs.readFileSync(packedRefsPath, 'utf8').trim(); } catch (e) { return undefined; } const refsRegex = /^([0-9a-f]{40})\s+(.+)$/gm; let refsMatch: RegExpExecArray | null; let refs: { [ref: string]: string } = {}; while (refsMatch = refsRegex.exec(refsRaw)) { refs[refsMatch[2]] = refsMatch[1]; } return refs[ref]; }
build/lib/git.ts
0
https://github.com/microsoft/vscode/commit/88e80b9a18b2cc3de0ca3a02977c3e2d4b088a60
[ 0.00017802839283831418, 0.00017207373457495123, 0.00016714801313355565, 0.00017043814295902848, 0.0000036924247979186475 ]
{ "id": 7, "code_window": [ "\t}\n", "\n", "\tconst type = config.type === 'vslsShare'\n", "\t\t? (<any>config).adapterProxy.configuration.type\n", "\t\t: config.type;\n", "\n" ], "labels": [ "keep", "keep", "replace", "replace", "replace", "keep" ], "after_edit": [ "\tif (type === 'vslsShare') {\n", "\t\ttype = (<any>session.configuration).adapterProxy.configuration.type;\n", "\t}\n", "\n", "\tif (equalsIgnoreCase(type, 'extensionhost') || equalsIgnoreCase(type, 'pwa-extensionhost')) {\n", "\t\treturn session;\n", "\t}\n" ], "file_path": "src/vs/workbench/contrib/debug/common/debugUtils.ts", "type": "replace", "edit_start_line_idx": 34 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { equalsIgnoreCase } from 'vs/base/common/strings'; import { IConfig, IDebuggerContribution, IDebugSession } from 'vs/workbench/contrib/debug/common/debug'; import { URI as uri } from 'vs/base/common/uri'; import { isAbsolute } from 'vs/base/common/path'; import { deepClone } from 'vs/base/common/objects'; const _formatPIIRegexp = /{([^}]+)}/g; export function formatPII(value: string, excludePII: boolean, args: { [key: string]: string }): string { return value.replace(_formatPIIRegexp, function (match, group) { if (excludePII && group.length > 0 && group[0] !== '_') { return match; } return args && args.hasOwnProperty(group) ? args[group] : match; }); } export function isSessionAttach(session: IDebugSession): boolean { return !session.parentSession && session.configuration.request === 'attach' && !isExtensionHostDebugging(session.configuration); } export function isExtensionHostDebugging(config: IConfig) { if (!config.type) { return false; } const type = config.type === 'vslsShare' ? (<any>config).adapterProxy.configuration.type : config.type; return equalsIgnoreCase(type, 'extensionhost') || equalsIgnoreCase(type, 'pwa-extensionhost'); } // only a debugger contributions with a label, program, or runtime attribute is considered a "defining" or "main" debugger contribution export function isDebuggerMainContribution(dbg: IDebuggerContribution) { return dbg.type && (dbg.label || dbg.program || dbg.runtime); } export function getExactExpressionStartAndEnd(lineContent: string, looseStart: number, looseEnd: number): { start: number, end: number } { let matchingExpression: string | undefined = undefined; let startOffset = 0; // Some example supported expressions: myVar.prop, a.b.c.d, myVar?.prop, myVar->prop, MyClass::StaticProp, *myVar // Match any character except a set of characters which often break interesting sub-expressions let expression: RegExp = /([^()\[\]{}<>\s+\-/%~#^;=|,`!]|\->)+/g; let result: RegExpExecArray | null = null; // First find the full expression under the cursor while (result = expression.exec(lineContent)) { let start = result.index + 1; let end = start + result[0].length; if (start <= looseStart && end >= looseEnd) { matchingExpression = result[0]; startOffset = start; break; } } // If there are non-word characters after the cursor, we want to truncate the expression then. // For example in expression 'a.b.c.d', if the focus was under 'b', 'a.b' would be evaluated. if (matchingExpression) { let subExpression: RegExp = /\w+/g; let subExpressionResult: RegExpExecArray | null = null; while (subExpressionResult = subExpression.exec(matchingExpression)) { let subEnd = subExpressionResult.index + 1 + startOffset + subExpressionResult[0].length; if (subEnd >= looseEnd) { break; } } if (subExpressionResult) { matchingExpression = matchingExpression.substring(0, subExpression.lastIndex); } } return matchingExpression ? { start: startOffset, end: startOffset + matchingExpression.length - 1 } : { start: 0, end: 0 }; } // RFC 2396, Appendix A: https://www.ietf.org/rfc/rfc2396.txt const _schemePattern = /^[a-zA-Z][a-zA-Z0-9\+\-\.]+:/; export function isUri(s: string | undefined): boolean { // heuristics: a valid uri starts with a scheme and // the scheme has at least 2 characters so that it doesn't look like a drive letter. return !!(s && s.match(_schemePattern)); } function stringToUri(path: string): string { if (typeof path === 'string') { if (isUri(path)) { return <string><unknown>uri.parse(path); } else { // assume path if (isAbsolute(path)) { return <string><unknown>uri.file(path); } else { // leave relative path as is } } } return path; } function uriToString(path: string): string { if (typeof path === 'object') { const u = uri.revive(path); if (u.scheme === 'file') { return u.fsPath; } else { return u.toString(); } } return path; } // path hooks helpers interface PathContainer { path?: string; } export function convertToDAPaths(message: DebugProtocol.ProtocolMessage, toUri: boolean): DebugProtocol.ProtocolMessage { const fixPath = toUri ? stringToUri : uriToString; // since we modify Source.paths in the message in place, we need to make a copy of it (see #61129) const msg = deepClone(message); convertPaths(msg, (toDA: boolean, source: PathContainer | undefined) => { if (toDA && source) { source.path = source.path ? fixPath(source.path) : undefined; } }); return msg; } export function convertToVSCPaths(message: DebugProtocol.ProtocolMessage, toUri: boolean): DebugProtocol.ProtocolMessage { const fixPath = toUri ? stringToUri : uriToString; // since we modify Source.paths in the message in place, we need to make a copy of it (see #61129) const msg = deepClone(message); convertPaths(msg, (toDA: boolean, source: PathContainer | undefined) => { if (!toDA && source) { source.path = source.path ? fixPath(source.path) : undefined; } }); return msg; } function convertPaths(msg: DebugProtocol.ProtocolMessage, fixSourcePath: (toDA: boolean, source: PathContainer | undefined) => void): void { switch (msg.type) { case 'event': const event = <DebugProtocol.Event>msg; switch (event.event) { case 'output': fixSourcePath(false, (<DebugProtocol.OutputEvent>event).body.source); break; case 'loadedSource': fixSourcePath(false, (<DebugProtocol.LoadedSourceEvent>event).body.source); break; case 'breakpoint': fixSourcePath(false, (<DebugProtocol.BreakpointEvent>event).body.breakpoint.source); break; default: break; } break; case 'request': const request = <DebugProtocol.Request>msg; switch (request.command) { case 'setBreakpoints': fixSourcePath(true, (<DebugProtocol.SetBreakpointsArguments>request.arguments).source); break; case 'breakpointLocations': fixSourcePath(true, (<DebugProtocol.BreakpointLocationsArguments>request.arguments).source); break; case 'source': fixSourcePath(true, (<DebugProtocol.SourceArguments>request.arguments).source); break; case 'gotoTargets': fixSourcePath(true, (<DebugProtocol.GotoTargetsArguments>request.arguments).source); break; case 'launchVSCode': request.arguments.args.forEach((arg: PathContainer | undefined) => fixSourcePath(false, arg)); break; default: break; } break; case 'response': const response = <DebugProtocol.Response>msg; if (response.success) { switch (response.command) { case 'stackTrace': (<DebugProtocol.StackTraceResponse>response).body.stackFrames.forEach(frame => fixSourcePath(false, frame.source)); break; case 'loadedSources': (<DebugProtocol.LoadedSourcesResponse>response).body.sources.forEach(source => fixSourcePath(false, source)); break; case 'scopes': (<DebugProtocol.ScopesResponse>response).body.scopes.forEach(scope => fixSourcePath(false, scope.source)); break; case 'setFunctionBreakpoints': (<DebugProtocol.SetFunctionBreakpointsResponse>response).body.breakpoints.forEach(bp => fixSourcePath(false, bp.source)); break; case 'setBreakpoints': (<DebugProtocol.SetBreakpointsResponse>response).body.breakpoints.forEach(bp => fixSourcePath(false, bp.source)); break; default: break; } } break; } }
src/vs/workbench/contrib/debug/common/debugUtils.ts
1
https://github.com/microsoft/vscode/commit/88e80b9a18b2cc3de0ca3a02977c3e2d4b088a60
[ 0.9981459379196167, 0.04364163428544998, 0.00016676467203069478, 0.0001726555055938661, 0.20350125432014465 ]
{ "id": 7, "code_window": [ "\t}\n", "\n", "\tconst type = config.type === 'vslsShare'\n", "\t\t? (<any>config).adapterProxy.configuration.type\n", "\t\t: config.type;\n", "\n" ], "labels": [ "keep", "keep", "replace", "replace", "replace", "keep" ], "after_edit": [ "\tif (type === 'vslsShare') {\n", "\t\ttype = (<any>session.configuration).adapterProxy.configuration.type;\n", "\t}\n", "\n", "\tif (equalsIgnoreCase(type, 'extensionhost') || equalsIgnoreCase(type, 'pwa-extensionhost')) {\n", "\t\treturn session;\n", "\t}\n" ], "file_path": "src/vs/workbench/contrib/debug/common/debugUtils.ts", "type": "replace", "edit_start_line_idx": 34 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as assert from 'assert'; import { setUnexpectedErrorHandler, errorHandler } from 'vs/base/common/errors'; import { TestInstantiationService } from 'vs/platform/instantiation/test/common/instantiationServiceMock'; import { URI } from 'vs/base/common/uri'; import * as types from 'vs/workbench/api/common/extHostTypes'; import { TextModel as EditorModel } from 'vs/editor/common/model/textModel'; import { TestRPCProtocol } from './testRPCProtocol'; import { MarkerService } from 'vs/platform/markers/common/markerService'; import { IMarkerService } from 'vs/platform/markers/common/markers'; import { ICommandService, CommandsRegistry } from 'vs/platform/commands/common/commands'; import { IModelService } from 'vs/editor/common/services/modelService'; import { ExtHostLanguageFeatures } from 'vs/workbench/api/common/extHostLanguageFeatures'; import { MainThreadLanguageFeatures } from 'vs/workbench/api/browser/mainThreadLanguageFeatures'; import { ExtHostApiCommands } from 'vs/workbench/api/common/extHostApiCommands'; import { ExtHostCommands } from 'vs/workbench/api/common/extHostCommands'; import { MainThreadCommands } from 'vs/workbench/api/browser/mainThreadCommands'; import { ExtHostDocuments } from 'vs/workbench/api/common/extHostDocuments'; import { ExtHostDocumentsAndEditors } from 'vs/workbench/api/common/extHostDocumentsAndEditors'; import { MainContext, ExtHostContext } from 'vs/workbench/api/common/extHost.protocol'; import { ExtHostDiagnostics } from 'vs/workbench/api/common/extHostDiagnostics'; import * as vscode from 'vscode'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import 'vs/workbench/contrib/search/browser/search.contribution'; import { NullLogService } from 'vs/platform/log/common/log'; import { ITextModel } from 'vs/editor/common/model'; import { nullExtensionDescription } from 'vs/workbench/services/extensions/common/extensions'; import { dispose } from 'vs/base/common/lifecycle'; const defaultSelector = { scheme: 'far' }; const model: ITextModel = EditorModel.createFromString( [ 'This is the first line', 'This is the second line', 'This is the third line', ].join('\n'), undefined, undefined, URI.parse('far://testing/file.b')); let rpcProtocol: TestRPCProtocol; let extHost: ExtHostLanguageFeatures; let mainThread: MainThreadLanguageFeatures; let commands: ExtHostCommands; let disposables: vscode.Disposable[] = []; let originalErrorHandler: (e: any) => any; function assertRejects(fn: () => Promise<any>, message: string = 'Expected rejection') { return fn().then(() => assert.ok(false, message), _err => assert.ok(true)); } suite('ExtHostLanguageFeatureCommands', function () { suiteSetup(() => { originalErrorHandler = errorHandler.getUnexpectedErrorHandler(); setUnexpectedErrorHandler(() => { }); // Use IInstantiationService to get typechecking when instantiating let inst: IInstantiationService; { let instantiationService = new TestInstantiationService(); rpcProtocol = new TestRPCProtocol(); instantiationService.stub(ICommandService, { _serviceBrand: undefined, executeCommand(id: string, ...args: any): any { const command = CommandsRegistry.getCommands().get(id); if (!command) { return Promise.reject(new Error(id + ' NOT known')); } const { handler } = command; return Promise.resolve(instantiationService.invokeFunction(handler, ...args)); } }); instantiationService.stub(IMarkerService, new MarkerService()); instantiationService.stub(IModelService, <IModelService>{ _serviceBrand: undefined, getModel(): any { return model; }, createModel() { throw new Error(); }, updateModel() { throw new Error(); }, setMode() { throw new Error(); }, destroyModel() { throw new Error(); }, getModels() { throw new Error(); }, onModelAdded: undefined!, onModelModeChanged: undefined!, onModelRemoved: undefined!, getCreationOptions() { throw new Error(); } }); inst = instantiationService; } const extHostDocumentsAndEditors = new ExtHostDocumentsAndEditors(rpcProtocol); extHostDocumentsAndEditors.$acceptDocumentsAndEditorsDelta({ addedDocuments: [{ isDirty: false, versionId: model.getVersionId(), modeId: model.getLanguageIdentifier().language, uri: model.uri, lines: model.getValue().split(model.getEOL()), EOL: model.getEOL(), }] }); const extHostDocuments = new ExtHostDocuments(rpcProtocol, extHostDocumentsAndEditors); rpcProtocol.set(ExtHostContext.ExtHostDocuments, extHostDocuments); commands = new ExtHostCommands(rpcProtocol, new NullLogService()); rpcProtocol.set(ExtHostContext.ExtHostCommands, commands); rpcProtocol.set(MainContext.MainThreadCommands, inst.createInstance(MainThreadCommands, rpcProtocol)); ExtHostApiCommands.register(commands); const diagnostics = new ExtHostDiagnostics(rpcProtocol, new NullLogService()); rpcProtocol.set(ExtHostContext.ExtHostDiagnostics, diagnostics); extHost = new ExtHostLanguageFeatures(rpcProtocol, null, extHostDocuments, commands, diagnostics, new NullLogService()); rpcProtocol.set(ExtHostContext.ExtHostLanguageFeatures, extHost); mainThread = rpcProtocol.set(MainContext.MainThreadLanguageFeatures, inst.createInstance(MainThreadLanguageFeatures, rpcProtocol)); return rpcProtocol.sync(); }); suiteTeardown(() => { setUnexpectedErrorHandler(originalErrorHandler); model.dispose(); mainThread.dispose(); }); teardown(() => { disposables = dispose(disposables); return rpcProtocol.sync(); }); // --- workspace symbols test('WorkspaceSymbols, invalid arguments', function () { let promises = [ assertRejects(() => commands.executeCommand('vscode.executeWorkspaceSymbolProvider')), assertRejects(() => commands.executeCommand('vscode.executeWorkspaceSymbolProvider', null)), assertRejects(() => commands.executeCommand('vscode.executeWorkspaceSymbolProvider', undefined)), assertRejects(() => commands.executeCommand('vscode.executeWorkspaceSymbolProvider', true)) ]; return Promise.all(promises); }); test('WorkspaceSymbols, back and forth', function () { disposables.push(extHost.registerWorkspaceSymbolProvider(nullExtensionDescription, <vscode.WorkspaceSymbolProvider>{ provideWorkspaceSymbols(query): any { return [ new types.SymbolInformation(query, types.SymbolKind.Array, new types.Range(0, 0, 1, 1), URI.parse('far://testing/first')), new types.SymbolInformation(query, types.SymbolKind.Array, new types.Range(0, 0, 1, 1), URI.parse('far://testing/second')) ]; } })); disposables.push(extHost.registerWorkspaceSymbolProvider(nullExtensionDescription, <vscode.WorkspaceSymbolProvider>{ provideWorkspaceSymbols(query): any { return [ new types.SymbolInformation(query, types.SymbolKind.Array, new types.Range(0, 0, 1, 1), URI.parse('far://testing/first')) ]; } })); return rpcProtocol.sync().then(() => { return commands.executeCommand<vscode.SymbolInformation[]>('vscode.executeWorkspaceSymbolProvider', 'testing').then(value => { for (let info of value) { assert.ok(info instanceof types.SymbolInformation); assert.equal(info.name, 'testing'); assert.equal(info.kind, types.SymbolKind.Array); } assert.equal(value.length, 3); }); }); }); test('executeWorkspaceSymbolProvider should accept empty string, #39522', async function () { disposables.push(extHost.registerWorkspaceSymbolProvider(nullExtensionDescription, { provideWorkspaceSymbols(): vscode.SymbolInformation[] { return [new types.SymbolInformation('hello', types.SymbolKind.Array, new types.Range(0, 0, 0, 0), URI.parse('foo:bar')) as vscode.SymbolInformation]; } })); await rpcProtocol.sync(); let symbols = await commands.executeCommand<vscode.SymbolInformation[]>('vscode.executeWorkspaceSymbolProvider', ''); assert.equal(symbols.length, 1); await rpcProtocol.sync(); symbols = await commands.executeCommand<vscode.SymbolInformation[]>('vscode.executeWorkspaceSymbolProvider', '*'); assert.equal(symbols.length, 1); }); // --- definition test('Definition, invalid arguments', function () { let promises = [ assertRejects(() => commands.executeCommand('vscode.executeDefinitionProvider')), assertRejects(() => commands.executeCommand('vscode.executeDefinitionProvider', null)), assertRejects(() => commands.executeCommand('vscode.executeDefinitionProvider', undefined)), assertRejects(() => commands.executeCommand('vscode.executeDefinitionProvider', true, false)) ]; return Promise.all(promises); }); test('Definition, back and forth', function () { disposables.push(extHost.registerDefinitionProvider(nullExtensionDescription, defaultSelector, <vscode.DefinitionProvider>{ provideDefinition(doc: any): any { return new types.Location(doc.uri, new types.Range(0, 0, 0, 0)); } })); disposables.push(extHost.registerDefinitionProvider(nullExtensionDescription, defaultSelector, <vscode.DefinitionProvider>{ provideDefinition(doc: any): any { return [ new types.Location(doc.uri, new types.Range(0, 0, 0, 0)), new types.Location(doc.uri, new types.Range(0, 0, 0, 0)), new types.Location(doc.uri, new types.Range(0, 0, 0, 0)), ]; } })); return rpcProtocol.sync().then(() => { return commands.executeCommand<vscode.Location[]>('vscode.executeDefinitionProvider', model.uri, new types.Position(0, 0)).then(values => { assert.equal(values.length, 4); for (let v of values) { assert.ok(v.uri instanceof URI); assert.ok(v.range instanceof types.Range); } }); }); }); // --- declaration test('Declaration, back and forth', function () { disposables.push(extHost.registerDeclarationProvider(nullExtensionDescription, defaultSelector, <vscode.DeclarationProvider>{ provideDeclaration(doc: any): any { return new types.Location(doc.uri, new types.Range(0, 0, 0, 0)); } })); disposables.push(extHost.registerDeclarationProvider(nullExtensionDescription, defaultSelector, <vscode.DeclarationProvider>{ provideDeclaration(doc: any): any { return [ new types.Location(doc.uri, new types.Range(0, 0, 0, 0)), new types.Location(doc.uri, new types.Range(0, 0, 0, 0)), new types.Location(doc.uri, new types.Range(0, 0, 0, 0)), ]; } })); return rpcProtocol.sync().then(() => { return commands.executeCommand<vscode.Location[]>('vscode.executeDeclarationProvider', model.uri, new types.Position(0, 0)).then(values => { assert.equal(values.length, 4); for (let v of values) { assert.ok(v.uri instanceof URI); assert.ok(v.range instanceof types.Range); } }); }); }); // --- type definition test('Type Definition, invalid arguments', function () { const promises = [ assertRejects(() => commands.executeCommand('vscode.executeTypeDefinitionProvider')), assertRejects(() => commands.executeCommand('vscode.executeTypeDefinitionProvider', null)), assertRejects(() => commands.executeCommand('vscode.executeTypeDefinitionProvider', undefined)), assertRejects(() => commands.executeCommand('vscode.executeTypeDefinitionProvider', true, false)) ]; return Promise.all(promises); }); test('Type Definition, back and forth', function () { disposables.push(extHost.registerTypeDefinitionProvider(nullExtensionDescription, defaultSelector, <vscode.TypeDefinitionProvider>{ provideTypeDefinition(doc: any): any { return new types.Location(doc.uri, new types.Range(0, 0, 0, 0)); } })); disposables.push(extHost.registerTypeDefinitionProvider(nullExtensionDescription, defaultSelector, <vscode.TypeDefinitionProvider>{ provideTypeDefinition(doc: any): any { return [ new types.Location(doc.uri, new types.Range(0, 0, 0, 0)), new types.Location(doc.uri, new types.Range(0, 0, 0, 0)), new types.Location(doc.uri, new types.Range(0, 0, 0, 0)), ]; } })); return rpcProtocol.sync().then(() => { return commands.executeCommand<vscode.Location[]>('vscode.executeTypeDefinitionProvider', model.uri, new types.Position(0, 0)).then(values => { assert.equal(values.length, 4); for (const v of values) { assert.ok(v.uri instanceof URI); assert.ok(v.range instanceof types.Range); } }); }); }); // --- references test('reference search, back and forth', function () { disposables.push(extHost.registerReferenceProvider(nullExtensionDescription, defaultSelector, <vscode.ReferenceProvider>{ provideReferences() { return [ new types.Location(URI.parse('some:uri/path'), new types.Range(0, 1, 0, 5)) ]; } })); return commands.executeCommand<vscode.Location[]>('vscode.executeReferenceProvider', model.uri, new types.Position(0, 0)).then(values => { assert.equal(values.length, 1); let [first] = values; assert.equal(first.uri.toString(), 'some:uri/path'); assert.equal(first.range.start.line, 0); assert.equal(first.range.start.character, 1); assert.equal(first.range.end.line, 0); assert.equal(first.range.end.character, 5); }); }); // --- outline test('Outline, back and forth', function () { disposables.push(extHost.registerDocumentSymbolProvider(nullExtensionDescription, defaultSelector, <vscode.DocumentSymbolProvider>{ provideDocumentSymbols(): any { return [ new types.SymbolInformation('testing1', types.SymbolKind.Enum, new types.Range(1, 0, 1, 0)), new types.SymbolInformation('testing2', types.SymbolKind.Enum, new types.Range(0, 1, 0, 3)), ]; } })); return rpcProtocol.sync().then(() => { return commands.executeCommand<vscode.SymbolInformation[]>('vscode.executeDocumentSymbolProvider', model.uri).then(values => { assert.equal(values.length, 2); let [first, second] = values; assert.ok(first instanceof types.SymbolInformation); assert.ok(second instanceof types.SymbolInformation); assert.equal(first.name, 'testing2'); assert.equal(second.name, 'testing1'); }); }); }); test('vscode.executeDocumentSymbolProvider command only returns SymbolInformation[] rather than DocumentSymbol[] #57984', function () { disposables.push(extHost.registerDocumentSymbolProvider(nullExtensionDescription, defaultSelector, <vscode.DocumentSymbolProvider>{ provideDocumentSymbols(): any { return [ new types.SymbolInformation('SymbolInformation', types.SymbolKind.Enum, new types.Range(1, 0, 1, 0)) ]; } })); disposables.push(extHost.registerDocumentSymbolProvider(nullExtensionDescription, defaultSelector, <vscode.DocumentSymbolProvider>{ provideDocumentSymbols(): any { let root = new types.DocumentSymbol('DocumentSymbol', 'DocumentSymbol#detail', types.SymbolKind.Enum, new types.Range(1, 0, 1, 0), new types.Range(1, 0, 1, 0)); root.children = [new types.DocumentSymbol('DocumentSymbol#child', 'DocumentSymbol#detail#child', types.SymbolKind.Enum, new types.Range(1, 0, 1, 0), new types.Range(1, 0, 1, 0))]; return [root]; } })); return rpcProtocol.sync().then(() => { return commands.executeCommand<(vscode.SymbolInformation & vscode.DocumentSymbol)[]>('vscode.executeDocumentSymbolProvider', model.uri).then(values => { assert.equal(values.length, 2); let [first, second] = values; assert.ok(first instanceof types.SymbolInformation); assert.ok(!(first instanceof types.DocumentSymbol)); assert.ok(second instanceof types.SymbolInformation); assert.equal(first.name, 'DocumentSymbol'); assert.equal(first.children.length, 1); assert.equal(second.name, 'SymbolInformation'); }); }); }); // --- suggest test('Suggest, back and forth', function () { disposables.push(extHost.registerCompletionItemProvider(nullExtensionDescription, defaultSelector, <vscode.CompletionItemProvider>{ provideCompletionItems(): any { let a = new types.CompletionItem('item1'); let b = new types.CompletionItem('item2'); b.textEdit = types.TextEdit.replace(new types.Range(0, 4, 0, 8), 'foo'); // overwite after let c = new types.CompletionItem('item3'); c.textEdit = types.TextEdit.replace(new types.Range(0, 1, 0, 6), 'foobar'); // overwite before & after // snippet string! let d = new types.CompletionItem('item4'); d.range = new types.Range(0, 1, 0, 4);// overwite before d.insertText = new types.SnippetString('foo$0bar'); return [a, b, c, d]; } }, [])); return rpcProtocol.sync().then(() => { return commands.executeCommand<vscode.CompletionList>('vscode.executeCompletionItemProvider', model.uri, new types.Position(0, 4)).then(list => { assert.ok(list instanceof types.CompletionList); let values = list.items; assert.ok(Array.isArray(values)); assert.equal(values.length, 4); let [first, second, third, fourth] = values; assert.equal(first.label, 'item1'); assert.equal(first.textEdit, undefined);// no text edit, default ranges assert.ok(!types.Range.isRange(first.range)); assert.equal(second.label, 'item2'); assert.equal(second.textEdit!.newText, 'foo'); assert.equal(second.textEdit!.range.start.line, 0); assert.equal(second.textEdit!.range.start.character, 4); assert.equal(second.textEdit!.range.end.line, 0); assert.equal(second.textEdit!.range.end.character, 8); assert.equal(third.label, 'item3'); assert.equal(third.textEdit!.newText, 'foobar'); assert.equal(third.textEdit!.range.start.line, 0); assert.equal(third.textEdit!.range.start.character, 1); assert.equal(third.textEdit!.range.end.line, 0); assert.equal(third.textEdit!.range.end.character, 6); assert.equal(fourth.label, 'item4'); assert.equal(fourth.textEdit, undefined); const range: any = fourth.range!; assert.ok(types.Range.isRange(range)); assert.equal(range.start.line, 0); assert.equal(range.start.character, 1); assert.equal(range.end.line, 0); assert.equal(range.end.character, 4); assert.ok(fourth.insertText instanceof types.SnippetString); assert.equal((<types.SnippetString>fourth.insertText).value, 'foo$0bar'); }); }); }); test('Suggest, return CompletionList !array', function () { disposables.push(extHost.registerCompletionItemProvider(nullExtensionDescription, defaultSelector, <vscode.CompletionItemProvider>{ provideCompletionItems(): any { let a = new types.CompletionItem('item1'); let b = new types.CompletionItem('item2'); return new types.CompletionList(<any>[a, b], true); } }, [])); return rpcProtocol.sync().then(() => { return commands.executeCommand<vscode.CompletionList>('vscode.executeCompletionItemProvider', model.uri, new types.Position(0, 4)).then(list => { assert.ok(list instanceof types.CompletionList); assert.equal(list.isIncomplete, true); }); }); }); test('Suggest, resolve completion items', async function () { let resolveCount = 0; disposables.push(extHost.registerCompletionItemProvider(nullExtensionDescription, defaultSelector, <vscode.CompletionItemProvider>{ provideCompletionItems(): any { let a = new types.CompletionItem('item1'); let b = new types.CompletionItem('item2'); let c = new types.CompletionItem('item3'); let d = new types.CompletionItem('item4'); return new types.CompletionList([a, b, c, d], false); }, resolveCompletionItem(item) { resolveCount += 1; return item; } }, [])); await rpcProtocol.sync(); let list = await commands.executeCommand<vscode.CompletionList>( 'vscode.executeCompletionItemProvider', model.uri, new types.Position(0, 4), undefined, 2 // maxItemsToResolve ); assert.ok(list instanceof types.CompletionList); assert.equal(resolveCount, 2); }); test('"vscode.executeCompletionItemProvider" doesnot return a preselect field #53749', async function () { disposables.push(extHost.registerCompletionItemProvider(nullExtensionDescription, defaultSelector, <vscode.CompletionItemProvider>{ provideCompletionItems(): any { let a = new types.CompletionItem('item1'); a.preselect = true; let b = new types.CompletionItem('item2'); let c = new types.CompletionItem('item3'); c.preselect = true; let d = new types.CompletionItem('item4'); return new types.CompletionList([a, b, c, d], false); } }, [])); await rpcProtocol.sync(); let list = await commands.executeCommand<vscode.CompletionList>( 'vscode.executeCompletionItemProvider', model.uri, new types.Position(0, 4), undefined ); assert.ok(list instanceof types.CompletionList); assert.equal(list.items.length, 4); let [a, b, c, d] = list.items; assert.equal(a.preselect, true); assert.equal(b.preselect, undefined); assert.equal(c.preselect, true); assert.equal(d.preselect, undefined); }); test('executeCompletionItemProvider doesn\'t capture commitCharacters #58228', async function () { disposables.push(extHost.registerCompletionItemProvider(nullExtensionDescription, defaultSelector, <vscode.CompletionItemProvider>{ provideCompletionItems(): any { let a = new types.CompletionItem('item1'); a.commitCharacters = ['a', 'b']; let b = new types.CompletionItem('item2'); return new types.CompletionList([a, b], false); } }, [])); await rpcProtocol.sync(); let list = await commands.executeCommand<vscode.CompletionList>( 'vscode.executeCompletionItemProvider', model.uri, new types.Position(0, 4), undefined ); assert.ok(list instanceof types.CompletionList); assert.equal(list.items.length, 2); let [a, b] = list.items; assert.deepEqual(a.commitCharacters, ['a', 'b']); assert.equal(b.commitCharacters, undefined); }); // --- signatureHelp test('Parameter Hints, back and forth', async () => { disposables.push(extHost.registerSignatureHelpProvider(nullExtensionDescription, defaultSelector, new class implements vscode.SignatureHelpProvider { provideSignatureHelp(_document: vscode.TextDocument, _position: vscode.Position, _token: vscode.CancellationToken, context: vscode.SignatureHelpContext): vscode.SignatureHelp { return { activeSignature: 0, activeParameter: 1, signatures: [ { label: 'abc', documentation: `${context.triggerKind === 1 /* vscode.SignatureHelpTriggerKind.Invoke */ ? 'invoked' : 'unknown'} ${context.triggerCharacter}`, parameters: [] } ] }; } }, [])); await rpcProtocol.sync(); const firstValue = await commands.executeCommand<vscode.SignatureHelp>('vscode.executeSignatureHelpProvider', model.uri, new types.Position(0, 1), ','); assert.strictEqual(firstValue.activeSignature, 0); assert.strictEqual(firstValue.activeParameter, 1); assert.strictEqual(firstValue.signatures.length, 1); assert.strictEqual(firstValue.signatures[0].label, 'abc'); assert.strictEqual(firstValue.signatures[0].documentation, 'invoked ,'); }); // --- quickfix test('QuickFix, back and forth', function () { disposables.push(extHost.registerCodeActionProvider(nullExtensionDescription, defaultSelector, { provideCodeActions(): vscode.Command[] { return [{ command: 'testing', title: 'Title', arguments: [1, 2, true] }]; } })); return rpcProtocol.sync().then(() => { return commands.executeCommand<vscode.Command[]>('vscode.executeCodeActionProvider', model.uri, new types.Range(0, 0, 1, 1)).then(value => { assert.equal(value.length, 1); let [first] = value; assert.equal(first.title, 'Title'); assert.equal(first.command, 'testing'); assert.deepEqual(first.arguments, [1, 2, true]); }); }); }); test('vscode.executeCodeActionProvider results seem to be missing their `command` property #45124', function () { disposables.push(extHost.registerCodeActionProvider(nullExtensionDescription, defaultSelector, { provideCodeActions(document, range): vscode.CodeAction[] { return [{ command: { arguments: [document, range], command: 'command', title: 'command_title', }, kind: types.CodeActionKind.Empty.append('foo'), title: 'title', }]; } })); return rpcProtocol.sync().then(() => { return commands.executeCommand<vscode.CodeAction[]>('vscode.executeCodeActionProvider', model.uri, new types.Range(0, 0, 1, 1)).then(value => { assert.equal(value.length, 1); const [first] = value; assert.ok(first.command); assert.equal(first.command!.command, 'command'); assert.equal(first.command!.title, 'command_title'); assert.equal(first.kind!.value, 'foo'); assert.equal(first.title, 'title'); }); }); }); test('vscode.executeCodeActionProvider passes Range to provider although Selection is passed in #77997', function () { disposables.push(extHost.registerCodeActionProvider(nullExtensionDescription, defaultSelector, { provideCodeActions(document, rangeOrSelection): vscode.CodeAction[] { return [{ command: { arguments: [document, rangeOrSelection], command: 'command', title: 'command_title', }, kind: types.CodeActionKind.Empty.append('foo'), title: 'title', }]; } })); const selection = new types.Selection(0, 0, 1, 1); return rpcProtocol.sync().then(() => { return commands.executeCommand<vscode.CodeAction[]>('vscode.executeCodeActionProvider', model.uri, selection).then(value => { assert.equal(value.length, 1); const [first] = value; assert.ok(first.command); assert.ok(first.command!.arguments![1] instanceof types.Selection); assert.ok(first.command!.arguments![1].isEqual(selection)); }); }); }); test('vscode.executeCodeActionProvider results seem to be missing their `isPreferred` property #78098', function () { disposables.push(extHost.registerCodeActionProvider(nullExtensionDescription, defaultSelector, { provideCodeActions(document, rangeOrSelection): vscode.CodeAction[] { return [{ command: { arguments: [document, rangeOrSelection], command: 'command', title: 'command_title', }, kind: types.CodeActionKind.Empty.append('foo'), title: 'title', isPreferred: true }]; } })); const selection = new types.Selection(0, 0, 1, 1); return rpcProtocol.sync().then(() => { return commands.executeCommand<vscode.CodeAction[]>('vscode.executeCodeActionProvider', model.uri, selection).then(value => { assert.equal(value.length, 1); const [first] = value; assert.equal(first.isPreferred, true); }); }); }); // --- code lens test('CodeLens, back and forth', function () { const complexArg = { foo() { }, bar() { }, big: extHost }; disposables.push(extHost.registerCodeLensProvider(nullExtensionDescription, defaultSelector, <vscode.CodeLensProvider>{ provideCodeLenses(): any { return [new types.CodeLens(new types.Range(0, 0, 1, 1), { title: 'Title', command: 'cmd', arguments: [1, true, complexArg] })]; } })); return rpcProtocol.sync().then(() => { return commands.executeCommand<vscode.CodeLens[]>('vscode.executeCodeLensProvider', model.uri).then(value => { assert.equal(value.length, 1); const [first] = value; assert.equal(first.command!.title, 'Title'); assert.equal(first.command!.command, 'cmd'); assert.equal(first.command!.arguments![0], 1); assert.equal(first.command!.arguments![1], true); assert.equal(first.command!.arguments![2], complexArg); }); }); }); test('CodeLens, resolve', async function () { let resolveCount = 0; disposables.push(extHost.registerCodeLensProvider(nullExtensionDescription, defaultSelector, <vscode.CodeLensProvider>{ provideCodeLenses(): any { return [ new types.CodeLens(new types.Range(0, 0, 1, 1)), new types.CodeLens(new types.Range(0, 0, 1, 1)), new types.CodeLens(new types.Range(0, 0, 1, 1)), new types.CodeLens(new types.Range(0, 0, 1, 1), { title: 'Already resolved', command: 'fff' }) ]; }, resolveCodeLens(codeLens: types.CodeLens) { codeLens.command = { title: resolveCount.toString(), command: 'resolved' }; resolveCount += 1; return codeLens; } })); await rpcProtocol.sync(); let value = await commands.executeCommand<vscode.CodeLens[]>('vscode.executeCodeLensProvider', model.uri, 2); assert.equal(value.length, 3); // the resolve argument defines the number of results being returned assert.equal(resolveCount, 2); resolveCount = 0; value = await commands.executeCommand<vscode.CodeLens[]>('vscode.executeCodeLensProvider', model.uri); assert.equal(value.length, 4); assert.equal(resolveCount, 0); }); test('Links, back and forth', function () { disposables.push(extHost.registerDocumentLinkProvider(nullExtensionDescription, defaultSelector, <vscode.DocumentLinkProvider>{ provideDocumentLinks(): any { return [new types.DocumentLink(new types.Range(0, 0, 0, 20), URI.parse('foo:bar'))]; } })); return rpcProtocol.sync().then(() => { return commands.executeCommand<vscode.DocumentLink[]>('vscode.executeLinkProvider', model.uri).then(value => { assert.equal(value.length, 1); let [first] = value; assert.equal(first.target + '', 'foo:bar'); assert.equal(first.range.start.line, 0); assert.equal(first.range.start.character, 0); assert.equal(first.range.end.line, 0); assert.equal(first.range.end.character, 20); }); }); }); test('Color provider', function () { disposables.push(extHost.registerColorProvider(nullExtensionDescription, defaultSelector, <vscode.DocumentColorProvider>{ provideDocumentColors(): vscode.ColorInformation[] { return [new types.ColorInformation(new types.Range(0, 0, 0, 20), new types.Color(0.1, 0.2, 0.3, 0.4))]; }, provideColorPresentations(): vscode.ColorPresentation[] { const cp = new types.ColorPresentation('#ABC'); cp.textEdit = types.TextEdit.replace(new types.Range(1, 0, 1, 20), '#ABC'); cp.additionalTextEdits = [types.TextEdit.insert(new types.Position(2, 20), '*')]; return [cp]; } })); return rpcProtocol.sync().then(() => { return commands.executeCommand<vscode.ColorInformation[]>('vscode.executeDocumentColorProvider', model.uri).then(value => { assert.equal(value.length, 1); let [first] = value; assert.equal(first.color.red, 0.1); assert.equal(first.color.green, 0.2); assert.equal(first.color.blue, 0.3); assert.equal(first.color.alpha, 0.4); assert.equal(first.range.start.line, 0); assert.equal(first.range.start.character, 0); assert.equal(first.range.end.line, 0); assert.equal(first.range.end.character, 20); }); }).then(() => { const color = new types.Color(0.5, 0.6, 0.7, 0.8); const range = new types.Range(0, 0, 0, 20); return commands.executeCommand<vscode.ColorPresentation[]>('vscode.executeColorPresentationProvider', color, { uri: model.uri, range }).then(value => { assert.equal(value.length, 1); let [first] = value; assert.equal(first.label, '#ABC'); assert.equal(first.textEdit!.newText, '#ABC'); assert.equal(first.textEdit!.range.start.line, 1); assert.equal(first.textEdit!.range.start.character, 0); assert.equal(first.textEdit!.range.end.line, 1); assert.equal(first.textEdit!.range.end.character, 20); assert.equal(first.additionalTextEdits!.length, 1); assert.equal(first.additionalTextEdits![0].range.start.line, 2); assert.equal(first.additionalTextEdits![0].range.start.character, 20); assert.equal(first.additionalTextEdits![0].range.end.line, 2); assert.equal(first.additionalTextEdits![0].range.end.character, 20); }); }); }); test('"TypeError: e.onCancellationRequested is not a function" calling hover provider in Insiders #54174', function () { disposables.push(extHost.registerHoverProvider(nullExtensionDescription, defaultSelector, <vscode.HoverProvider>{ provideHover(): any { return new types.Hover('fofofofo'); } })); return rpcProtocol.sync().then(() => { return commands.executeCommand<vscode.Hover[]>('vscode.executeHoverProvider', model.uri, new types.Position(1, 1)).then(value => { assert.equal(value.length, 1); assert.equal(value[0].contents.length, 1); }); }); }); // --- selection ranges test('Selection Range, back and forth', async function () { disposables.push(extHost.registerSelectionRangeProvider(nullExtensionDescription, defaultSelector, <vscode.SelectionRangeProvider>{ provideSelectionRanges() { return [ new types.SelectionRange(new types.Range(0, 10, 0, 18), new types.SelectionRange(new types.Range(0, 2, 0, 20))), ]; } })); await rpcProtocol.sync(); let value = await commands.executeCommand<vscode.SelectionRange[]>('vscode.executeSelectionRangeProvider', model.uri, [new types.Position(0, 10)]); assert.equal(value.length, 1); assert.ok(value[0].parent); }); // --- call hierarcht test('CallHierarchy, back and forth', async function () { disposables.push(extHost.registerCallHierarchyProvider(nullExtensionDescription, defaultSelector, new class implements vscode.CallHierarchyProvider { prepareCallHierarchy(document: vscode.TextDocument, position: vscode.Position, ): vscode.ProviderResult<vscode.CallHierarchyItem> { return new types.CallHierarchyItem(types.SymbolKind.Constant, 'ROOT', 'ROOT', document.uri, new types.Range(0, 0, 0, 0), new types.Range(0, 0, 0, 0)); } provideCallHierarchyIncomingCalls(item: vscode.CallHierarchyItem, token: vscode.CancellationToken): vscode.ProviderResult<vscode.CallHierarchyIncomingCall[]> { return [new types.CallHierarchyIncomingCall( new types.CallHierarchyItem(types.SymbolKind.Constant, 'INCOMING', 'INCOMING', item.uri, new types.Range(0, 0, 0, 0), new types.Range(0, 0, 0, 0)), [new types.Range(0, 0, 0, 0)] )]; } provideCallHierarchyOutgoingCalls(item: vscode.CallHierarchyItem, token: vscode.CancellationToken): vscode.ProviderResult<vscode.CallHierarchyOutgoingCall[]> { return [new types.CallHierarchyOutgoingCall( new types.CallHierarchyItem(types.SymbolKind.Constant, 'OUTGOING', 'OUTGOING', item.uri, new types.Range(0, 0, 0, 0), new types.Range(0, 0, 0, 0)), [new types.Range(0, 0, 0, 0)] )]; } })); await rpcProtocol.sync(); const root = await commands.executeCommand<vscode.CallHierarchyItem[]>('vscode.prepareCallHierarchy', model.uri, new types.Position(0, 0)); assert.ok(Array.isArray(root)); assert.equal(root.length, 1); assert.equal(root[0].name, 'ROOT'); const incoming = await commands.executeCommand<vscode.CallHierarchyIncomingCall[]>('vscode.provideIncomingCalls', root[0]); assert.equal(incoming.length, 1); assert.equal(incoming[0].from.name, 'INCOMING'); const outgoing = await commands.executeCommand<vscode.CallHierarchyOutgoingCall[]>('vscode.provideOutgoingCalls', root[0]); assert.equal(outgoing.length, 1); assert.equal(outgoing[0].to.name, 'OUTGOING'); }); });
src/vs/workbench/test/electron-browser/api/extHostApiCommands.test.ts
0
https://github.com/microsoft/vscode/commit/88e80b9a18b2cc3de0ca3a02977c3e2d4b088a60
[ 0.00020457438949961215, 0.0001721071166684851, 0.00016346907068509609, 0.0001722821907605976, 0.000005408133347373223 ]
{ "id": 7, "code_window": [ "\t}\n", "\n", "\tconst type = config.type === 'vslsShare'\n", "\t\t? (<any>config).adapterProxy.configuration.type\n", "\t\t: config.type;\n", "\n" ], "labels": [ "keep", "keep", "replace", "replace", "replace", "keep" ], "after_edit": [ "\tif (type === 'vslsShare') {\n", "\t\ttype = (<any>session.configuration).adapterProxy.configuration.type;\n", "\t}\n", "\n", "\tif (equalsIgnoreCase(type, 'extensionhost') || equalsIgnoreCase(type, 'pwa-extensionhost')) {\n", "\t\treturn session;\n", "\t}\n" ], "file_path": "src/vs/workbench/contrib/debug/common/debugUtils.ts", "type": "replace", "edit_start_line_idx": 34 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import 'vs/css!./media/notificationsList'; import { addClass, isAncestor, trackFocus } from 'vs/base/browser/dom'; import { WorkbenchList } from 'vs/platform/list/browser/listService'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IListOptions } from 'vs/base/browser/ui/list/listWidget'; import { Themable, NOTIFICATIONS_LINKS, NOTIFICATIONS_BACKGROUND, NOTIFICATIONS_FOREGROUND, NOTIFICATIONS_ERROR_ICON_FOREGROUND, NOTIFICATIONS_WARNING_ICON_FOREGROUND, NOTIFICATIONS_INFO_ICON_FOREGROUND } from 'vs/workbench/common/theme'; import { IThemeService, registerThemingParticipant, ITheme, ICssStyleCollector } from 'vs/platform/theme/common/themeService'; import { contrastBorder, focusBorder } from 'vs/platform/theme/common/colorRegistry'; import { INotificationViewItem } from 'vs/workbench/common/notifications'; import { NotificationsListDelegate, NotificationRenderer } from 'vs/workbench/browser/parts/notifications/notificationsViewer'; import { NotificationActionRunner, CopyNotificationMessageAction } from 'vs/workbench/browser/parts/notifications/notificationsActions'; import { NotificationFocusedContext } from 'vs/workbench/browser/parts/notifications/notificationsCommands'; import { IContextMenuService } from 'vs/platform/contextview/browser/contextView'; import { assertIsDefined, assertAllDefined } from 'vs/base/common/types'; export class NotificationsList extends Themable { private listContainer: HTMLElement | undefined; private list: WorkbenchList<INotificationViewItem> | undefined; private viewModel: INotificationViewItem[]; private isVisible: boolean | undefined; constructor( private container: HTMLElement, private options: IListOptions<INotificationViewItem>, @IInstantiationService private readonly instantiationService: IInstantiationService, @IThemeService themeService: IThemeService, @IContextMenuService private readonly contextMenuService: IContextMenuService ) { super(themeService); this.viewModel = []; } show(focus?: boolean): void { if (this.isVisible) { if (focus) { const list = assertIsDefined(this.list); list.domFocus(); } return; // already visible } // Lazily create if showing for the first time if (!this.list) { this.createNotificationsList(); } // Make visible this.isVisible = true; // Focus if (focus) { const list = assertIsDefined(this.list); list.domFocus(); } } private createNotificationsList(): void { // List Container this.listContainer = document.createElement('div'); addClass(this.listContainer, 'notifications-list-container'); const actionRunner = this._register(this.instantiationService.createInstance(NotificationActionRunner)); // Notification Renderer const renderer = this.instantiationService.createInstance(NotificationRenderer, actionRunner); // List const list = this.list = this._register(this.instantiationService.createInstance<typeof WorkbenchList, WorkbenchList<INotificationViewItem>>( WorkbenchList, 'NotificationsList', this.listContainer, new NotificationsListDelegate(this.listContainer), [renderer], { ...this.options, setRowLineHeight: false, horizontalScrolling: false, overrideStyles: { listBackground: NOTIFICATIONS_BACKGROUND } } )); // Context menu to copy message const copyAction = this._register(this.instantiationService.createInstance(CopyNotificationMessageAction, CopyNotificationMessageAction.ID, CopyNotificationMessageAction.LABEL)); this._register((list.onContextMenu(e => { if (!e.element) { return; } this.contextMenuService.showContextMenu({ getAnchor: () => e.anchor, getActions: () => [copyAction], getActionsContext: () => e.element, actionRunner }); }))); // Toggle on double click this._register((list.onMouseDblClick(event => (event.element as INotificationViewItem).toggle()))); // Clear focus when DOM focus moves out // Use document.hasFocus() to not clear the focus when the entire window lost focus // This ensures that when the focus comes back, the notification is still focused const listFocusTracker = this._register(trackFocus(list.getHTMLElement())); this._register(listFocusTracker.onDidBlur(() => { if (document.hasFocus()) { list.setFocus([]); } })); // Context key NotificationFocusedContext.bindTo(list.contextKeyService); // Only allow for focus in notifications, as the // selection is too strong over the contents of // the notification this._register(list.onSelectionChange(e => { if (e.indexes.length > 0) { list.setSelection([]); } })); this.container.appendChild(this.listContainer); this.updateStyles(); } updateNotificationsList(start: number, deleteCount: number, items: INotificationViewItem[] = []) { const [list, listContainer] = assertAllDefined(this.list, this.listContainer); const listHasDOMFocus = isAncestor(document.activeElement, listContainer); // Remember focus and relative top of that item const focusedIndex = list.getFocus()[0]; const focusedItem = this.viewModel[focusedIndex]; let focusRelativeTop: number | null = null; if (typeof focusedIndex === 'number') { focusRelativeTop = list.getRelativeTop(focusedIndex); } // Update view model this.viewModel.splice(start, deleteCount, ...items); // Update list list.splice(start, deleteCount, items); list.layout(); // Hide if no more notifications to show if (this.viewModel.length === 0) { this.hide(); } // Otherwise restore focus if we had else if (typeof focusedIndex === 'number') { let indexToFocus = 0; if (focusedItem) { let indexToFocusCandidate = this.viewModel.indexOf(focusedItem); if (indexToFocusCandidate === -1) { indexToFocusCandidate = focusedIndex - 1; // item could have been removed } if (indexToFocusCandidate < this.viewModel.length && indexToFocusCandidate >= 0) { indexToFocus = indexToFocusCandidate; } } if (typeof focusRelativeTop === 'number') { list.reveal(indexToFocus, focusRelativeTop); } list.setFocus([indexToFocus]); } // Restore DOM focus if we had focus before if (listHasDOMFocus) { list.domFocus(); } } hide(): void { if (!this.isVisible || !this.list) { return; // already hidden } // Hide this.isVisible = false; // Clear list this.list.splice(0, this.viewModel.length); // Clear view model this.viewModel = []; } focusFirst(): void { if (!this.isVisible || !this.list) { return; // hidden } this.list.focusFirst(); this.list.domFocus(); } hasFocus(): boolean { if (!this.isVisible || !this.listContainer) { return false; // hidden } return isAncestor(document.activeElement, this.listContainer); } protected updateStyles(): void { if (this.listContainer) { const foreground = this.getColor(NOTIFICATIONS_FOREGROUND); this.listContainer.style.color = foreground ? foreground : null; const background = this.getColor(NOTIFICATIONS_BACKGROUND); this.listContainer.style.background = background ? background : ''; const outlineColor = this.getColor(contrastBorder); this.listContainer.style.outlineColor = outlineColor ? outlineColor : ''; } } layout(width: number, maxHeight?: number): void { if (this.listContainer && this.list) { this.listContainer.style.width = `${width}px`; if (typeof maxHeight === 'number') { this.list.getHTMLElement().style.maxHeight = `${maxHeight}px`; } this.list.layout(); } } dispose(): void { this.hide(); super.dispose(); } } registerThemingParticipant((theme: ITheme, collector: ICssStyleCollector) => { const linkColor = theme.getColor(NOTIFICATIONS_LINKS); if (linkColor) { collector.addRule(`.monaco-workbench .notifications-list-container .notification-list-item .notification-list-item-message a { color: ${linkColor}; }`); } const focusOutline = theme.getColor(focusBorder); if (focusOutline) { collector.addRule(` .monaco-workbench .notifications-list-container .notification-list-item .notification-list-item-message a:focus { outline-color: ${focusOutline}; }`); } // Notification Error Icon const notificationErrorIconForegroundColor = theme.getColor(NOTIFICATIONS_ERROR_ICON_FOREGROUND); if (notificationErrorIconForegroundColor) { collector.addRule(` .monaco-workbench .notifications-center .codicon-error, .monaco-workbench .notifications-toasts .codicon-error { color: ${notificationErrorIconForegroundColor}; }`); } // Notification Warning Icon const notificationWarningIconForegroundColor = theme.getColor(NOTIFICATIONS_WARNING_ICON_FOREGROUND); if (notificationWarningIconForegroundColor) { collector.addRule(` .monaco-workbench .notifications-center .codicon-warning, .monaco-workbench .notifications-toasts .codicon-warning { color: ${notificationWarningIconForegroundColor}; }`); } // Notification Info Icon const notificationInfoIconForegroundColor = theme.getColor(NOTIFICATIONS_INFO_ICON_FOREGROUND); if (notificationInfoIconForegroundColor) { collector.addRule(` .monaco-workbench .notifications-center .codicon-info, .monaco-workbench .notifications-toasts .codicon-info { color: ${notificationInfoIconForegroundColor}; }`); } });
src/vs/workbench/browser/parts/notifications/notificationsList.ts
0
https://github.com/microsoft/vscode/commit/88e80b9a18b2cc3de0ca3a02977c3e2d4b088a60
[ 0.002517279237508774, 0.00027861102716997266, 0.00016577822680119425, 0.00017115430091507733, 0.00044346562935970724 ]
{ "id": 7, "code_window": [ "\t}\n", "\n", "\tconst type = config.type === 'vslsShare'\n", "\t\t? (<any>config).adapterProxy.configuration.type\n", "\t\t: config.type;\n", "\n" ], "labels": [ "keep", "keep", "replace", "replace", "replace", "keep" ], "after_edit": [ "\tif (type === 'vslsShare') {\n", "\t\ttype = (<any>session.configuration).adapterProxy.configuration.type;\n", "\t}\n", "\n", "\tif (equalsIgnoreCase(type, 'extensionhost') || equalsIgnoreCase(type, 'pwa-extensionhost')) {\n", "\t\treturn session;\n", "\t}\n" ], "file_path": "src/vs/workbench/contrib/debug/common/debugUtils.ts", "type": "replace", "edit_start_line_idx": 34 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Event } from 'vs/base/common/event'; import { Disposable, IDisposable } from 'vs/base/common/lifecycle'; import { IScrollPosition, ScrollEvent, Scrollable, ScrollbarVisibility } from 'vs/base/common/scrollable'; import { ConfigurationChangedEvent, EditorOption } from 'vs/editor/common/config/editorOptions'; import * as editorCommon from 'vs/editor/common/editorCommon'; import { LinesLayout, IEditorWhitespace, IWhitespaceChangeAccessor } from 'vs/editor/common/viewLayout/linesLayout'; import { IPartialViewLinesViewportData } from 'vs/editor/common/viewLayout/viewLinesViewportData'; import { IViewLayout, IViewWhitespaceViewportData, Viewport } from 'vs/editor/common/viewModel/viewModel'; const SMOOTH_SCROLLING_TIME = 125; export class ViewLayout extends Disposable implements IViewLayout { private readonly _configuration: editorCommon.IConfiguration; private readonly _linesLayout: LinesLayout; public readonly scrollable: Scrollable; public readonly onDidScroll: Event<ScrollEvent>; constructor(configuration: editorCommon.IConfiguration, lineCount: number, scheduleAtNextAnimationFrame: (callback: () => void) => IDisposable) { super(); this._configuration = configuration; const options = this._configuration.options; const layoutInfo = options.get(EditorOption.layoutInfo); this._linesLayout = new LinesLayout(lineCount, options.get(EditorOption.lineHeight)); this.scrollable = this._register(new Scrollable(0, scheduleAtNextAnimationFrame)); this._configureSmoothScrollDuration(); this.scrollable.setScrollDimensions({ width: layoutInfo.contentWidth, height: layoutInfo.contentHeight }); this.onDidScroll = this.scrollable.onScroll; this._updateHeight(); } public dispose(): void { super.dispose(); } public onHeightMaybeChanged(): void { this._updateHeight(); } private _configureSmoothScrollDuration(): void { this.scrollable.setSmoothScrollDuration(this._configuration.options.get(EditorOption.smoothScrolling) ? SMOOTH_SCROLLING_TIME : 0); } // ---- begin view event handlers public onConfigurationChanged(e: ConfigurationChangedEvent): void { const options = this._configuration.options; if (e.hasChanged(EditorOption.lineHeight)) { this._linesLayout.setLineHeight(options.get(EditorOption.lineHeight)); } if (e.hasChanged(EditorOption.layoutInfo)) { const layoutInfo = options.get(EditorOption.layoutInfo); const width = layoutInfo.contentWidth; const height = layoutInfo.contentHeight; const scrollDimensions = this.scrollable.getScrollDimensions(); const scrollWidth = scrollDimensions.scrollWidth; const scrollHeight = this._getTotalHeight(width, height, scrollWidth); this.scrollable.setScrollDimensions({ width: width, height: height, scrollHeight: scrollHeight }); } else { this._updateHeight(); } if (e.hasChanged(EditorOption.smoothScrolling)) { this._configureSmoothScrollDuration(); } } public onFlushed(lineCount: number): void { this._linesLayout.onFlushed(lineCount); } public onLinesDeleted(fromLineNumber: number, toLineNumber: number): void { this._linesLayout.onLinesDeleted(fromLineNumber, toLineNumber); } public onLinesInserted(fromLineNumber: number, toLineNumber: number): void { this._linesLayout.onLinesInserted(fromLineNumber, toLineNumber); } // ---- end view event handlers private _getHorizontalScrollbarHeight(width: number, scrollWidth: number): number { const options = this._configuration.options; const scrollbar = options.get(EditorOption.scrollbar); if (scrollbar.horizontal === ScrollbarVisibility.Hidden) { // horizontal scrollbar not visible return 0; } if (width >= scrollWidth) { // horizontal scrollbar not visible return 0; } return scrollbar.horizontalScrollbarSize; } private _getTotalHeight(width: number, height: number, scrollWidth: number): number { const options = this._configuration.options; let result = this._linesLayout.getLinesTotalHeight(); if (options.get(EditorOption.scrollBeyondLastLine)) { result += height - options.get(EditorOption.lineHeight); } else { result += this._getHorizontalScrollbarHeight(width, scrollWidth); } return Math.max(height, result); } private _updateHeight(): void { const scrollDimensions = this.scrollable.getScrollDimensions(); const width = scrollDimensions.width; const height = scrollDimensions.height; const scrollWidth = scrollDimensions.scrollWidth; const scrollHeight = this._getTotalHeight(width, height, scrollWidth); this.scrollable.setScrollDimensions({ scrollHeight: scrollHeight }); } // ---- Layouting logic public getCurrentViewport(): Viewport { const scrollDimensions = this.scrollable.getScrollDimensions(); const currentScrollPosition = this.scrollable.getCurrentScrollPosition(); return new Viewport( currentScrollPosition.scrollTop, currentScrollPosition.scrollLeft, scrollDimensions.width, scrollDimensions.height ); } public getFutureViewport(): Viewport { const scrollDimensions = this.scrollable.getScrollDimensions(); const currentScrollPosition = this.scrollable.getFutureScrollPosition(); return new Viewport( currentScrollPosition.scrollTop, currentScrollPosition.scrollLeft, scrollDimensions.width, scrollDimensions.height ); } private _computeScrollWidth(maxLineWidth: number, viewportWidth: number): number { const options = this._configuration.options; const wrappingInfo = options.get(EditorOption.wrappingInfo); let isViewportWrapping = wrappingInfo.isViewportWrapping; if (!isViewportWrapping) { const extraHorizontalSpace = options.get(EditorOption.scrollBeyondLastColumn) * options.get(EditorOption.fontInfo).typicalHalfwidthCharacterWidth; const whitespaceMinWidth = this._linesLayout.getWhitespaceMinWidth(); return Math.max(maxLineWidth + extraHorizontalSpace, viewportWidth, whitespaceMinWidth); } return Math.max(maxLineWidth, viewportWidth); } public onMaxLineWidthChanged(maxLineWidth: number): void { let newScrollWidth = this._computeScrollWidth(maxLineWidth, this.getCurrentViewport().width); this.scrollable.setScrollDimensions({ scrollWidth: newScrollWidth }); // The height might depend on the fact that there is a horizontal scrollbar or not this._updateHeight(); } // ---- view state public saveState(): { scrollTop: number; scrollTopWithoutViewZones: number; scrollLeft: number; } { const currentScrollPosition = this.scrollable.getFutureScrollPosition(); let scrollTop = currentScrollPosition.scrollTop; let firstLineNumberInViewport = this._linesLayout.getLineNumberAtOrAfterVerticalOffset(scrollTop); let whitespaceAboveFirstLine = this._linesLayout.getWhitespaceAccumulatedHeightBeforeLineNumber(firstLineNumberInViewport); return { scrollTop: scrollTop, scrollTopWithoutViewZones: scrollTop - whitespaceAboveFirstLine, scrollLeft: currentScrollPosition.scrollLeft }; } // ---- IVerticalLayoutProvider public changeWhitespace<T>(callback: (accessor: IWhitespaceChangeAccessor) => T): T { return this._linesLayout.changeWhitespace(callback); } public getVerticalOffsetForLineNumber(lineNumber: number): number { return this._linesLayout.getVerticalOffsetForLineNumber(lineNumber); } public isAfterLines(verticalOffset: number): boolean { return this._linesLayout.isAfterLines(verticalOffset); } public getLineNumberAtVerticalOffset(verticalOffset: number): number { return this._linesLayout.getLineNumberAtOrAfterVerticalOffset(verticalOffset); } public getWhitespaceAtVerticalOffset(verticalOffset: number): IViewWhitespaceViewportData | null { return this._linesLayout.getWhitespaceAtVerticalOffset(verticalOffset); } public getLinesViewportData(): IPartialViewLinesViewportData { const visibleBox = this.getCurrentViewport(); return this._linesLayout.getLinesViewportData(visibleBox.top, visibleBox.top + visibleBox.height); } public getLinesViewportDataAtScrollTop(scrollTop: number): IPartialViewLinesViewportData { // do some minimal validations on scrollTop const scrollDimensions = this.scrollable.getScrollDimensions(); if (scrollTop + scrollDimensions.height > scrollDimensions.scrollHeight) { scrollTop = scrollDimensions.scrollHeight - scrollDimensions.height; } if (scrollTop < 0) { scrollTop = 0; } return this._linesLayout.getLinesViewportData(scrollTop, scrollTop + scrollDimensions.height); } public getWhitespaceViewportData(): IViewWhitespaceViewportData[] { const visibleBox = this.getCurrentViewport(); return this._linesLayout.getWhitespaceViewportData(visibleBox.top, visibleBox.top + visibleBox.height); } public getWhitespaces(): IEditorWhitespace[] { return this._linesLayout.getWhitespaces(); } // ---- IScrollingProvider public getScrollWidth(): number { const scrollDimensions = this.scrollable.getScrollDimensions(); return scrollDimensions.scrollWidth; } public getScrollHeight(): number { const scrollDimensions = this.scrollable.getScrollDimensions(); return scrollDimensions.scrollHeight; } public getCurrentScrollLeft(): number { const currentScrollPosition = this.scrollable.getCurrentScrollPosition(); return currentScrollPosition.scrollLeft; } public getCurrentScrollTop(): number { const currentScrollPosition = this.scrollable.getCurrentScrollPosition(); return currentScrollPosition.scrollTop; } public validateScrollPosition(scrollPosition: editorCommon.INewScrollPosition): IScrollPosition { return this.scrollable.validateScrollPosition(scrollPosition); } public setScrollPositionNow(position: editorCommon.INewScrollPosition): void { this.scrollable.setScrollPositionNow(position); } public setScrollPositionSmooth(position: editorCommon.INewScrollPosition): void { this.scrollable.setScrollPositionSmooth(position); } public deltaScrollNow(deltaScrollLeft: number, deltaScrollTop: number): void { const currentScrollPosition = this.scrollable.getCurrentScrollPosition(); this.scrollable.setScrollPositionNow({ scrollLeft: currentScrollPosition.scrollLeft + deltaScrollLeft, scrollTop: currentScrollPosition.scrollTop + deltaScrollTop }); } }
src/vs/editor/common/viewLayout/viewLayout.ts
0
https://github.com/microsoft/vscode/commit/88e80b9a18b2cc3de0ca3a02977c3e2d4b088a60
[ 0.00038104661507532, 0.0001817978627514094, 0.00016587831487413496, 0.00016948490520007908, 0.00004257094406057149 ]
{ "id": 8, "code_window": [ "\n", "\treturn equalsIgnoreCase(type, 'extensionhost') || equalsIgnoreCase(type, 'pwa-extensionhost');\n", "}\n", "\n", "// only a debugger contributions with a label, program, or runtime attribute is considered a \"defining\" or \"main\" debugger contribution\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\treturn session.parentSession ? getExtensionHostDebugSession(session.parentSession) : undefined;\n" ], "file_path": "src/vs/workbench/contrib/debug/common/debugUtils.ts", "type": "replace", "edit_start_line_idx": 38 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { equalsIgnoreCase } from 'vs/base/common/strings'; import { IConfig, IDebuggerContribution, IDebugSession } from 'vs/workbench/contrib/debug/common/debug'; import { URI as uri } from 'vs/base/common/uri'; import { isAbsolute } from 'vs/base/common/path'; import { deepClone } from 'vs/base/common/objects'; const _formatPIIRegexp = /{([^}]+)}/g; export function formatPII(value: string, excludePII: boolean, args: { [key: string]: string }): string { return value.replace(_formatPIIRegexp, function (match, group) { if (excludePII && group.length > 0 && group[0] !== '_') { return match; } return args && args.hasOwnProperty(group) ? args[group] : match; }); } export function isSessionAttach(session: IDebugSession): boolean { return !session.parentSession && session.configuration.request === 'attach' && !isExtensionHostDebugging(session.configuration); } export function isExtensionHostDebugging(config: IConfig) { if (!config.type) { return false; } const type = config.type === 'vslsShare' ? (<any>config).adapterProxy.configuration.type : config.type; return equalsIgnoreCase(type, 'extensionhost') || equalsIgnoreCase(type, 'pwa-extensionhost'); } // only a debugger contributions with a label, program, or runtime attribute is considered a "defining" or "main" debugger contribution export function isDebuggerMainContribution(dbg: IDebuggerContribution) { return dbg.type && (dbg.label || dbg.program || dbg.runtime); } export function getExactExpressionStartAndEnd(lineContent: string, looseStart: number, looseEnd: number): { start: number, end: number } { let matchingExpression: string | undefined = undefined; let startOffset = 0; // Some example supported expressions: myVar.prop, a.b.c.d, myVar?.prop, myVar->prop, MyClass::StaticProp, *myVar // Match any character except a set of characters which often break interesting sub-expressions let expression: RegExp = /([^()\[\]{}<>\s+\-/%~#^;=|,`!]|\->)+/g; let result: RegExpExecArray | null = null; // First find the full expression under the cursor while (result = expression.exec(lineContent)) { let start = result.index + 1; let end = start + result[0].length; if (start <= looseStart && end >= looseEnd) { matchingExpression = result[0]; startOffset = start; break; } } // If there are non-word characters after the cursor, we want to truncate the expression then. // For example in expression 'a.b.c.d', if the focus was under 'b', 'a.b' would be evaluated. if (matchingExpression) { let subExpression: RegExp = /\w+/g; let subExpressionResult: RegExpExecArray | null = null; while (subExpressionResult = subExpression.exec(matchingExpression)) { let subEnd = subExpressionResult.index + 1 + startOffset + subExpressionResult[0].length; if (subEnd >= looseEnd) { break; } } if (subExpressionResult) { matchingExpression = matchingExpression.substring(0, subExpression.lastIndex); } } return matchingExpression ? { start: startOffset, end: startOffset + matchingExpression.length - 1 } : { start: 0, end: 0 }; } // RFC 2396, Appendix A: https://www.ietf.org/rfc/rfc2396.txt const _schemePattern = /^[a-zA-Z][a-zA-Z0-9\+\-\.]+:/; export function isUri(s: string | undefined): boolean { // heuristics: a valid uri starts with a scheme and // the scheme has at least 2 characters so that it doesn't look like a drive letter. return !!(s && s.match(_schemePattern)); } function stringToUri(path: string): string { if (typeof path === 'string') { if (isUri(path)) { return <string><unknown>uri.parse(path); } else { // assume path if (isAbsolute(path)) { return <string><unknown>uri.file(path); } else { // leave relative path as is } } } return path; } function uriToString(path: string): string { if (typeof path === 'object') { const u = uri.revive(path); if (u.scheme === 'file') { return u.fsPath; } else { return u.toString(); } } return path; } // path hooks helpers interface PathContainer { path?: string; } export function convertToDAPaths(message: DebugProtocol.ProtocolMessage, toUri: boolean): DebugProtocol.ProtocolMessage { const fixPath = toUri ? stringToUri : uriToString; // since we modify Source.paths in the message in place, we need to make a copy of it (see #61129) const msg = deepClone(message); convertPaths(msg, (toDA: boolean, source: PathContainer | undefined) => { if (toDA && source) { source.path = source.path ? fixPath(source.path) : undefined; } }); return msg; } export function convertToVSCPaths(message: DebugProtocol.ProtocolMessage, toUri: boolean): DebugProtocol.ProtocolMessage { const fixPath = toUri ? stringToUri : uriToString; // since we modify Source.paths in the message in place, we need to make a copy of it (see #61129) const msg = deepClone(message); convertPaths(msg, (toDA: boolean, source: PathContainer | undefined) => { if (!toDA && source) { source.path = source.path ? fixPath(source.path) : undefined; } }); return msg; } function convertPaths(msg: DebugProtocol.ProtocolMessage, fixSourcePath: (toDA: boolean, source: PathContainer | undefined) => void): void { switch (msg.type) { case 'event': const event = <DebugProtocol.Event>msg; switch (event.event) { case 'output': fixSourcePath(false, (<DebugProtocol.OutputEvent>event).body.source); break; case 'loadedSource': fixSourcePath(false, (<DebugProtocol.LoadedSourceEvent>event).body.source); break; case 'breakpoint': fixSourcePath(false, (<DebugProtocol.BreakpointEvent>event).body.breakpoint.source); break; default: break; } break; case 'request': const request = <DebugProtocol.Request>msg; switch (request.command) { case 'setBreakpoints': fixSourcePath(true, (<DebugProtocol.SetBreakpointsArguments>request.arguments).source); break; case 'breakpointLocations': fixSourcePath(true, (<DebugProtocol.BreakpointLocationsArguments>request.arguments).source); break; case 'source': fixSourcePath(true, (<DebugProtocol.SourceArguments>request.arguments).source); break; case 'gotoTargets': fixSourcePath(true, (<DebugProtocol.GotoTargetsArguments>request.arguments).source); break; case 'launchVSCode': request.arguments.args.forEach((arg: PathContainer | undefined) => fixSourcePath(false, arg)); break; default: break; } break; case 'response': const response = <DebugProtocol.Response>msg; if (response.success) { switch (response.command) { case 'stackTrace': (<DebugProtocol.StackTraceResponse>response).body.stackFrames.forEach(frame => fixSourcePath(false, frame.source)); break; case 'loadedSources': (<DebugProtocol.LoadedSourcesResponse>response).body.sources.forEach(source => fixSourcePath(false, source)); break; case 'scopes': (<DebugProtocol.ScopesResponse>response).body.scopes.forEach(scope => fixSourcePath(false, scope.source)); break; case 'setFunctionBreakpoints': (<DebugProtocol.SetFunctionBreakpointsResponse>response).body.breakpoints.forEach(bp => fixSourcePath(false, bp.source)); break; case 'setBreakpoints': (<DebugProtocol.SetBreakpointsResponse>response).body.breakpoints.forEach(bp => fixSourcePath(false, bp.source)); break; default: break; } } break; } }
src/vs/workbench/contrib/debug/common/debugUtils.ts
1
https://github.com/microsoft/vscode/commit/88e80b9a18b2cc3de0ca3a02977c3e2d4b088a60
[ 0.6156694889068604, 0.028421519324183464, 0.00016488941037096083, 0.00017082226986531168, 0.12538254261016846 ]
{ "id": 8, "code_window": [ "\n", "\treturn equalsIgnoreCase(type, 'extensionhost') || equalsIgnoreCase(type, 'pwa-extensionhost');\n", "}\n", "\n", "// only a debugger contributions with a label, program, or runtime attribute is considered a \"defining\" or \"main\" debugger contribution\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\treturn session.parentSession ? getExtensionHostDebugSession(session.parentSession) : undefined;\n" ], "file_path": "src/vs/workbench/contrib/debug/common/debugUtils.ts", "type": "replace", "edit_start_line_idx": 38 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as nls from 'vs/nls'; import { EmmetEditorAction } from 'vs/workbench/contrib/emmet/browser/emmetActions'; import { registerEditorAction } from 'vs/editor/browser/editorExtensions'; import { EditorContextKeys } from 'vs/editor/common/editorContextKeys'; import { KeyCode } from 'vs/base/common/keyCodes'; import { ContextKeyExpr } from 'vs/platform/contextkey/common/contextkey'; import { KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry'; import { MenuId } from 'vs/platform/actions/common/actions'; class ExpandAbbreviationAction extends EmmetEditorAction { constructor() { super({ id: 'editor.emmet.action.expandAbbreviation', label: nls.localize('expandAbbreviationAction', "Emmet: Expand Abbreviation"), alias: 'Emmet: Expand Abbreviation', precondition: EditorContextKeys.writable, actionName: 'expand_abbreviation', kbOpts: { primary: KeyCode.Tab, kbExpr: ContextKeyExpr.and( EditorContextKeys.editorTextFocus, EditorContextKeys.tabDoesNotMoveFocus, ContextKeyExpr.has('config.emmet.triggerExpansionOnTab') ), weight: KeybindingWeight.EditorContrib }, menuOpts: { menuId: MenuId.MenubarEditMenu, group: '5_insert', title: nls.localize({ key: 'miEmmetExpandAbbreviation', comment: ['&& denotes a mnemonic'] }, "Emmet: E&&xpand Abbreviation"), order: 3 } }); } } registerEditorAction(ExpandAbbreviationAction);
src/vs/workbench/contrib/emmet/browser/actions/expandAbbreviation.ts
0
https://github.com/microsoft/vscode/commit/88e80b9a18b2cc3de0ca3a02977c3e2d4b088a60
[ 0.0001753286342136562, 0.00017322196799796075, 0.00017182284500449896, 0.00017297301383223385, 0.0000012011942089884542 ]
{ "id": 8, "code_window": [ "\n", "\treturn equalsIgnoreCase(type, 'extensionhost') || equalsIgnoreCase(type, 'pwa-extensionhost');\n", "}\n", "\n", "// only a debugger contributions with a label, program, or runtime attribute is considered a \"defining\" or \"main\" debugger contribution\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\treturn session.parentSession ? getExtensionHostDebugSession(session.parentSession) : undefined;\n" ], "file_path": "src/vs/workbench/contrib/debug/common/debugUtils.ts", "type": "replace", "edit_start_line_idx": 38 }
[{ "c": "<", "t": "text.html.php meta.embedded.block.html meta.tag.metadata.script.start.html punctuation.definition.tag.begin.html", "r": { "dark_plus": "punctuation.definition.tag: #808080", "light_plus": "punctuation.definition.tag: #800000", "dark_vs": "punctuation.definition.tag: #808080", "light_vs": "punctuation.definition.tag: #800000", "hc_black": "punctuation.definition.tag: #808080" } }, { "c": "script", "t": "text.html.php meta.embedded.block.html meta.tag.metadata.script.start.html entity.name.tag.html", "r": { "dark_plus": "entity.name.tag: #569CD6", "light_plus": "entity.name.tag: #800000", "dark_vs": "entity.name.tag: #569CD6", "light_vs": "entity.name.tag: #800000", "hc_black": "entity.name.tag: #569CD6" } }, { "c": ">", "t": "text.html.php meta.embedded.block.html meta.tag.metadata.script.start.html punctuation.definition.tag.end.html", "r": { "dark_plus": "punctuation.definition.tag: #808080", "light_plus": "punctuation.definition.tag: #800000", "dark_vs": "punctuation.definition.tag: #808080", "light_vs": "punctuation.definition.tag: #800000", "hc_black": "punctuation.definition.tag: #808080" } }, { "c": " ", "t": "text.html.php meta.embedded.block.html source.js", "r": { "dark_plus": "meta.embedded: #D4D4D4", "light_plus": "meta.embedded: #000000", "dark_vs": "meta.embedded: #D4D4D4", "light_vs": "meta.embedded: #000000", "hc_black": "meta.embedded: #FFFFFF" } }, { "c": "...", "t": "text.html.php meta.embedded.block.html source.js keyword.operator.spread.js", "r": { "dark_plus": "keyword.operator: #D4D4D4", "light_plus": "keyword.operator: #000000", "dark_vs": "keyword.operator: #D4D4D4", "light_vs": "keyword.operator: #000000", "hc_black": "keyword.operator: #D4D4D4" } }, { "c": " ", "t": "text.html.php meta.embedded.block.html source.js", "r": { "dark_plus": "meta.embedded: #D4D4D4", "light_plus": "meta.embedded: #000000", "dark_vs": "meta.embedded: #D4D4D4", "light_vs": "meta.embedded: #000000", "hc_black": "meta.embedded: #FFFFFF" } }, { "c": "<?php", "t": "text.html.php meta.embedded.block.html source.js meta.embedded.block.php punctuation.section.embedded.begin.php", "r": { "dark_plus": "punctuation.section.embedded.begin.php: #569CD6", "light_plus": "punctuation.section.embedded.begin.php: #800000", "dark_vs": "punctuation.section.embedded.begin.php: #569CD6", "light_vs": "punctuation.section.embedded.begin.php: #800000", "hc_black": "punctuation.section.embedded: #569CD6" } }, { "c": " ", "t": "text.html.php meta.embedded.block.html source.js meta.embedded.block.php source.php", "r": { "dark_plus": "meta.embedded: #D4D4D4", "light_plus": "meta.embedded: #000000", "dark_vs": "meta.embedded: #D4D4D4", "light_vs": "meta.embedded: #000000", "hc_black": "meta.embedded: #FFFFFF" } }, { "c": "foreach", "t": "text.html.php meta.embedded.block.html source.js meta.embedded.block.php source.php keyword.control.foreach.php", "r": { "dark_plus": "keyword.control: #C586C0", "light_plus": "keyword.control: #AF00DB", "dark_vs": "keyword.control: #569CD6", "light_vs": "keyword.control: #0000FF", "hc_black": "keyword.control: #C586C0" } }, { "c": "(", "t": "text.html.php meta.embedded.block.html source.js meta.embedded.block.php source.php punctuation.definition.begin.bracket.round.php", "r": { "dark_plus": "meta.embedded: #D4D4D4", "light_plus": "meta.embedded: #000000", "dark_vs": "meta.embedded: #D4D4D4", "light_vs": "meta.embedded: #000000", "hc_black": "meta.embedded: #FFFFFF" } }, { "c": "$", "t": "text.html.php meta.embedded.block.html source.js meta.embedded.block.php source.php variable.other.php punctuation.definition.variable.php", "r": { "dark_plus": "variable: #9CDCFE", "light_plus": "variable: #001080", "dark_vs": "meta.embedded: #D4D4D4", "light_vs": "meta.embedded: #000000", "hc_black": "variable: #9CDCFE" } }, { "c": "actID", "t": "text.html.php meta.embedded.block.html source.js meta.embedded.block.php source.php variable.other.php", "r": { "dark_plus": "variable: #9CDCFE", "light_plus": "variable: #001080", "dark_vs": "meta.embedded: #D4D4D4", "light_vs": "meta.embedded: #000000", "hc_black": "variable: #9CDCFE" } }, { "c": " ", "t": "text.html.php meta.embedded.block.html source.js meta.embedded.block.php source.php", "r": { "dark_plus": "meta.embedded: #D4D4D4", "light_plus": "meta.embedded: #000000", "dark_vs": "meta.embedded: #D4D4D4", "light_vs": "meta.embedded: #000000", "hc_black": "meta.embedded: #FFFFFF" } }, { "c": "AS", "t": "text.html.php meta.embedded.block.html source.js meta.embedded.block.php source.php keyword.operator.logical.php", "r": { "dark_plus": "keyword.operator: #D4D4D4", "light_plus": "keyword.operator: #000000", "dark_vs": "keyword.operator: #D4D4D4", "light_vs": "keyword.operator: #000000", "hc_black": "keyword.operator: #D4D4D4" } }, { "c": " ", "t": "text.html.php meta.embedded.block.html source.js meta.embedded.block.php source.php", "r": { "dark_plus": "meta.embedded: #D4D4D4", "light_plus": "meta.embedded: #000000", "dark_vs": "meta.embedded: #D4D4D4", "light_vs": "meta.embedded: #000000", "hc_black": "meta.embedded: #FFFFFF" } }, { "c": "$", "t": "text.html.php meta.embedded.block.html source.js meta.embedded.block.php source.php variable.other.php punctuation.definition.variable.php", "r": { "dark_plus": "variable: #9CDCFE", "light_plus": "variable: #001080", "dark_vs": "meta.embedded: #D4D4D4", "light_vs": "meta.embedded: #000000", "hc_black": "variable: #9CDCFE" } }, { "c": "act", "t": "text.html.php meta.embedded.block.html source.js meta.embedded.block.php source.php variable.other.php", "r": { "dark_plus": "variable: #9CDCFE", "light_plus": "variable: #001080", "dark_vs": "meta.embedded: #D4D4D4", "light_vs": "meta.embedded: #000000", "hc_black": "variable: #9CDCFE" } }, { "c": ")", "t": "text.html.php meta.embedded.block.html source.js meta.embedded.block.php source.php punctuation.definition.end.bracket.round.php", "r": { "dark_plus": "meta.embedded: #D4D4D4", "light_plus": "meta.embedded: #000000", "dark_vs": "meta.embedded: #D4D4D4", "light_vs": "meta.embedded: #000000", "hc_black": "meta.embedded: #FFFFFF" } }, { "c": " ", "t": "text.html.php meta.embedded.block.html source.js meta.embedded.block.php source.php", "r": { "dark_plus": "meta.embedded: #D4D4D4", "light_plus": "meta.embedded: #000000", "dark_vs": "meta.embedded: #D4D4D4", "light_vs": "meta.embedded: #000000", "hc_black": "meta.embedded: #FFFFFF" } }, { "c": "{", "t": "text.html.php meta.embedded.block.html source.js meta.embedded.block.php source.php punctuation.definition.begin.bracket.curly.php", "r": { "dark_plus": "meta.embedded: #D4D4D4", "light_plus": "meta.embedded: #000000", "dark_vs": "meta.embedded: #D4D4D4", "light_vs": "meta.embedded: #000000", "hc_black": "meta.embedded: #FFFFFF" } }, { "c": " ", "t": "text.html.php meta.embedded.block.html source.js meta.embedded.block.php source.php", "r": { "dark_plus": "meta.embedded: #D4D4D4", "light_plus": "meta.embedded: #000000", "dark_vs": "meta.embedded: #D4D4D4", "light_vs": "meta.embedded: #000000", "hc_black": "meta.embedded: #FFFFFF" } }, { "c": "echo", "t": "text.html.php meta.embedded.block.html source.js meta.embedded.block.php source.php support.function.construct.output.php", "r": { "dark_plus": "support.function: #DCDCAA", "light_plus": "support.function: #795E26", "dark_vs": "meta.embedded: #D4D4D4", "light_vs": "meta.embedded: #000000", "hc_black": "support.function: #DCDCAA" } }, { "c": " ", "t": "text.html.php meta.embedded.block.html source.js meta.embedded.block.php source.php", "r": { "dark_plus": "meta.embedded: #D4D4D4", "light_plus": "meta.embedded: #000000", "dark_vs": "meta.embedded: #D4D4D4", "light_vs": "meta.embedded: #000000", "hc_black": "meta.embedded: #FFFFFF" } }, { "c": "'", "t": "text.html.php meta.embedded.block.html source.js meta.embedded.block.php source.php string.quoted.single.php punctuation.definition.string.begin.php", "r": { "dark_plus": "string: #CE9178", "light_plus": "string: #A31515", "dark_vs": "string: #CE9178", "light_vs": "string: #A31515", "hc_black": "string: #CE9178" } }, { "c": "divNames.push(", "t": "text.html.php meta.embedded.block.html source.js meta.embedded.block.php source.php string.quoted.single.php", "r": { "dark_plus": "string: #CE9178", "light_plus": "string: #A31515", "dark_vs": "string: #CE9178", "light_vs": "string: #A31515", "hc_black": "string: #CE9178" } }, { "c": "\\'", "t": "text.html.php meta.embedded.block.html source.js meta.embedded.block.php source.php string.quoted.single.php constant.character.escape.php", "r": { "dark_plus": "constant.character.escape: #D7BA7D", "light_plus": "constant.character.escape: #FF0000", "dark_vs": "string: #CE9178", "light_vs": "string: #A31515", "hc_black": "constant.character: #569CD6" } }, { "c": "[nid=", "t": "text.html.php meta.embedded.block.html source.js meta.embedded.block.php source.php string.quoted.single.php", "r": { "dark_plus": "string: #CE9178", "light_plus": "string: #A31515", "dark_vs": "string: #CE9178", "light_vs": "string: #A31515", "hc_black": "string: #CE9178" } }, { "c": "'", "t": "text.html.php meta.embedded.block.html source.js meta.embedded.block.php source.php string.quoted.single.php punctuation.definition.string.end.php", "r": { "dark_plus": "string: #CE9178", "light_plus": "string: #A31515", "dark_vs": "string: #CE9178", "light_vs": "string: #A31515", "hc_black": "string: #CE9178" } }, { "c": ".", "t": "text.html.php meta.embedded.block.html source.js meta.embedded.block.php source.php keyword.operator.string.php", "r": { "dark_plus": "keyword.operator: #D4D4D4", "light_plus": "keyword.operator: #000000", "dark_vs": "keyword.operator: #D4D4D4", "light_vs": "keyword.operator: #000000", "hc_black": "keyword.operator: #D4D4D4" } }, { "c": "$", "t": "text.html.php meta.embedded.block.html source.js meta.embedded.block.php source.php variable.other.php punctuation.definition.variable.php", "r": { "dark_plus": "variable: #9CDCFE", "light_plus": "variable: #001080", "dark_vs": "meta.embedded: #D4D4D4", "light_vs": "meta.embedded: #000000", "hc_black": "variable: #9CDCFE" } }, { "c": "act", "t": "text.html.php meta.embedded.block.html source.js meta.embedded.block.php source.php variable.other.php", "r": { "dark_plus": "variable: #9CDCFE", "light_plus": "variable: #001080", "dark_vs": "meta.embedded: #D4D4D4", "light_vs": "meta.embedded: #000000", "hc_black": "variable: #9CDCFE" } }, { "c": ".", "t": "text.html.php meta.embedded.block.html source.js meta.embedded.block.php source.php keyword.operator.string.php", "r": { "dark_plus": "keyword.operator: #D4D4D4", "light_plus": "keyword.operator: #000000", "dark_vs": "keyword.operator: #D4D4D4", "light_vs": "keyword.operator: #000000", "hc_black": "keyword.operator: #D4D4D4" } }, { "c": "'", "t": "text.html.php meta.embedded.block.html source.js meta.embedded.block.php source.php string.quoted.single.php punctuation.definition.string.begin.php", "r": { "dark_plus": "string: #CE9178", "light_plus": "string: #A31515", "dark_vs": "string: #CE9178", "light_vs": "string: #A31515", "hc_black": "string: #CE9178" } }, { "c": "]", "t": "text.html.php meta.embedded.block.html source.js meta.embedded.block.php source.php string.quoted.single.php", "r": { "dark_plus": "string: #CE9178", "light_plus": "string: #A31515", "dark_vs": "string: #CE9178", "light_vs": "string: #A31515", "hc_black": "string: #CE9178" } }, { "c": "\\'", "t": "text.html.php meta.embedded.block.html source.js meta.embedded.block.php source.php string.quoted.single.php constant.character.escape.php", "r": { "dark_plus": "constant.character.escape: #D7BA7D", "light_plus": "constant.character.escape: #FF0000", "dark_vs": "string: #CE9178", "light_vs": "string: #A31515", "hc_black": "constant.character: #569CD6" } }, { "c": ");", "t": "text.html.php meta.embedded.block.html source.js meta.embedded.block.php source.php string.quoted.single.php", "r": { "dark_plus": "string: #CE9178", "light_plus": "string: #A31515", "dark_vs": "string: #CE9178", "light_vs": "string: #A31515", "hc_black": "string: #CE9178" } }, { "c": "'", "t": "text.html.php meta.embedded.block.html source.js meta.embedded.block.php source.php string.quoted.single.php punctuation.definition.string.end.php", "r": { "dark_plus": "string: #CE9178", "light_plus": "string: #A31515", "dark_vs": "string: #CE9178", "light_vs": "string: #A31515", "hc_black": "string: #CE9178" } }, { "c": ";", "t": "text.html.php meta.embedded.block.html source.js meta.embedded.block.php source.php punctuation.terminator.expression.php", "r": { "dark_plus": "meta.embedded: #D4D4D4", "light_plus": "meta.embedded: #000000", "dark_vs": "meta.embedded: #D4D4D4", "light_vs": "meta.embedded: #000000", "hc_black": "meta.embedded: #FFFFFF" } }, { "c": " ", "t": "text.html.php meta.embedded.block.html source.js meta.embedded.block.php source.php", "r": { "dark_plus": "meta.embedded: #D4D4D4", "light_plus": "meta.embedded: #000000", "dark_vs": "meta.embedded: #D4D4D4", "light_vs": "meta.embedded: #000000", "hc_black": "meta.embedded: #FFFFFF" } }, { "c": "}", "t": "text.html.php meta.embedded.block.html source.js meta.embedded.block.php source.php punctuation.definition.end.bracket.curly.php", "r": { "dark_plus": "meta.embedded: #D4D4D4", "light_plus": "meta.embedded: #000000", "dark_vs": "meta.embedded: #D4D4D4", "light_vs": "meta.embedded: #000000", "hc_black": "meta.embedded: #FFFFFF" } }, { "c": " ", "t": "text.html.php meta.embedded.block.html source.js meta.embedded.block.php source.php", "r": { "dark_plus": "meta.embedded: #D4D4D4", "light_plus": "meta.embedded: #000000", "dark_vs": "meta.embedded: #D4D4D4", "light_vs": "meta.embedded: #000000", "hc_black": "meta.embedded: #FFFFFF" } }, { "c": "?", "t": "text.html.php meta.embedded.block.html source.js meta.embedded.block.php punctuation.section.embedded.end.php source.php", "r": { "dark_plus": "punctuation.section.embedded.end.php: #569CD6", "light_plus": "punctuation.section.embedded.end.php: #800000", "dark_vs": "punctuation.section.embedded.end.php: #569CD6", "light_vs": "punctuation.section.embedded.end.php: #800000", "hc_black": "punctuation.section.embedded: #569CD6" } }, { "c": ">", "t": "text.html.php meta.embedded.block.html source.js meta.embedded.block.php punctuation.section.embedded.end.php", "r": { "dark_plus": "punctuation.section.embedded.end.php: #569CD6", "light_plus": "punctuation.section.embedded.end.php: #800000", "dark_vs": "punctuation.section.embedded.end.php: #569CD6", "light_vs": "punctuation.section.embedded.end.php: #800000", "hc_black": "punctuation.section.embedded: #569CD6" } }, { "c": " ", "t": "text.html.php meta.embedded.block.html source.js", "r": { "dark_plus": "meta.embedded: #D4D4D4", "light_plus": "meta.embedded: #000000", "dark_vs": "meta.embedded: #D4D4D4", "light_vs": "meta.embedded: #000000", "hc_black": "meta.embedded: #FFFFFF" } }, { "c": "...", "t": "text.html.php meta.embedded.block.html source.js keyword.operator.spread.js", "r": { "dark_plus": "keyword.operator: #D4D4D4", "light_plus": "keyword.operator: #000000", "dark_vs": "keyword.operator: #D4D4D4", "light_vs": "keyword.operator: #000000", "hc_black": "keyword.operator: #D4D4D4" } }, { "c": "<", "t": "text.html.php meta.embedded.block.html meta.tag.metadata.script.end.html punctuation.definition.tag.begin.html source.js", "r": { "dark_plus": "punctuation.definition.tag: #808080", "light_plus": "punctuation.definition.tag: #800000", "dark_vs": "punctuation.definition.tag: #808080", "light_vs": "punctuation.definition.tag: #800000", "hc_black": "punctuation.definition.tag: #808080" } }, { "c": "/", "t": "text.html.php meta.embedded.block.html meta.tag.metadata.script.end.html punctuation.definition.tag.begin.html", "r": { "dark_plus": "punctuation.definition.tag: #808080", "light_plus": "punctuation.definition.tag: #800000", "dark_vs": "punctuation.definition.tag: #808080", "light_vs": "punctuation.definition.tag: #800000", "hc_black": "punctuation.definition.tag: #808080" } }, { "c": "script", "t": "text.html.php meta.embedded.block.html meta.tag.metadata.script.end.html entity.name.tag.html", "r": { "dark_plus": "entity.name.tag: #569CD6", "light_plus": "entity.name.tag: #800000", "dark_vs": "entity.name.tag: #569CD6", "light_vs": "entity.name.tag: #800000", "hc_black": "entity.name.tag: #569CD6" } }, { "c": ">", "t": "text.html.php meta.embedded.block.html meta.tag.metadata.script.end.html punctuation.definition.tag.end.html", "r": { "dark_plus": "punctuation.definition.tag: #808080", "light_plus": "punctuation.definition.tag: #800000", "dark_vs": "punctuation.definition.tag: #808080", "light_vs": "punctuation.definition.tag: #800000", "hc_black": "punctuation.definition.tag: #808080" } } ]
extensions/php/test/colorize-results/issue-28354_php.json
0
https://github.com/microsoft/vscode/commit/88e80b9a18b2cc3de0ca3a02977c3e2d4b088a60
[ 0.00017389928689226508, 0.0001713163946988061, 0.00016882779891602695, 0.00017142713477369398, 0.0000013458770808938425 ]
{ "id": 8, "code_window": [ "\n", "\treturn equalsIgnoreCase(type, 'extensionhost') || equalsIgnoreCase(type, 'pwa-extensionhost');\n", "}\n", "\n", "// only a debugger contributions with a label, program, or runtime attribute is considered a \"defining\" or \"main\" debugger contribution\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\treturn session.parentSession ? getExtensionHostDebugSession(session.parentSession) : undefined;\n" ], "file_path": "src/vs/workbench/contrib/debug/common/debugUtils.ts", "type": "replace", "edit_start_line_idx": 38 }
.yarnrc
build/lib/watch/.gitignore
0
https://github.com/microsoft/vscode/commit/88e80b9a18b2cc3de0ca3a02977c3e2d4b088a60
[ 0.0001740827865432948, 0.0001740827865432948, 0.0001740827865432948, 0.0001740827865432948, 0 ]
{ "id": 0, "code_window": [ "\n", " function getConstructSignatureDefinition(): DefinitionInfo[] | undefined {\n", " // Applicable only if we are in a new expression, or we are on a constructor declaration\n", " // and in either case the symbol has a construct signature definition, i.e. class\n", " if (isNewExpressionTarget(node) || node.kind === SyntaxKind.ConstructorKeyword && symbol.flags & SymbolFlags.Class) {\n", " const cls = find(symbol.declarations, isClassLike) || Debug.fail(\"Expected declaration to have at least one class-like declaration\");\n", " return getSignatureDefinition(cls.members, /*selectConstructors*/ true);\n", " }\n", " }\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " if (symbol.flags & SymbolFlags.Class && (isNewExpressionTarget(node) || node.kind === SyntaxKind.ConstructorKeyword)) {\n" ], "file_path": "src/services/goToDefinition.ts", "type": "replace", "edit_start_line_idx": 193 }
/// <reference path='fourslash.ts' /> ////class C2 { ////} ////let I: { //// /*constructSignature*/new(): C2; ////}; ////let C = new [|/*invokeExpression*/I|](); verify.goToDefinition("invokeExpression", "constructSignature");
tests/cases/fourslash/goToDefinitionNewExpressionTargetNotClass.ts
1
https://github.com/microsoft/TypeScript/commit/dab0dbe6f04db3f8f70ffa4573e3cd4c7e7fe18f
[ 0.00032302047475241125, 0.0002451493055559695, 0.00016727812180761248, 0.0002451493055559695, 0.00007787117647239938 ]
{ "id": 0, "code_window": [ "\n", " function getConstructSignatureDefinition(): DefinitionInfo[] | undefined {\n", " // Applicable only if we are in a new expression, or we are on a constructor declaration\n", " // and in either case the symbol has a construct signature definition, i.e. class\n", " if (isNewExpressionTarget(node) || node.kind === SyntaxKind.ConstructorKeyword && symbol.flags & SymbolFlags.Class) {\n", " const cls = find(symbol.declarations, isClassLike) || Debug.fail(\"Expected declaration to have at least one class-like declaration\");\n", " return getSignatureDefinition(cls.members, /*selectConstructors*/ true);\n", " }\n", " }\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " if (symbol.flags & SymbolFlags.Class && (isNewExpressionTarget(node) || node.kind === SyntaxKind.ConstructorKeyword)) {\n" ], "file_path": "src/services/goToDefinition.ts", "type": "replace", "edit_start_line_idx": 193 }
class C { x: string; } var c = new C(); var r = C; class D<T,U> { x: T; y: U; } var d = new D(); var d2 = new D<string, number>(); var r2 = D;
tests/cases/conformance/classes/members/constructorFunctionTypes/classWithNoConstructorOrBaseClass.ts
0
https://github.com/microsoft/TypeScript/commit/dab0dbe6f04db3f8f70ffa4573e3cd4c7e7fe18f
[ 0.00017147324979305267, 0.00016755989054217935, 0.00016364654584322125, 0.00016755989054217935, 0.000003913351974915713 ]
{ "id": 0, "code_window": [ "\n", " function getConstructSignatureDefinition(): DefinitionInfo[] | undefined {\n", " // Applicable only if we are in a new expression, or we are on a constructor declaration\n", " // and in either case the symbol has a construct signature definition, i.e. class\n", " if (isNewExpressionTarget(node) || node.kind === SyntaxKind.ConstructorKeyword && symbol.flags & SymbolFlags.Class) {\n", " const cls = find(symbol.declarations, isClassLike) || Debug.fail(\"Expected declaration to have at least one class-like declaration\");\n", " return getSignatureDefinition(cls.members, /*selectConstructors*/ true);\n", " }\n", " }\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " if (symbol.flags & SymbolFlags.Class && (isNewExpressionTarget(node) || node.kind === SyntaxKind.ConstructorKeyword)) {\n" ], "file_path": "src/services/goToDefinition.ts", "type": "replace", "edit_start_line_idx": 193 }
/// <reference path="fourslash.ts"/> //// goTo.bof(); edit.insert("module M {\n"); // indentation on newline after "module {" verify.indentationIs(4);
tests/cases/fourslash/moduleIndent.ts
0
https://github.com/microsoft/TypeScript/commit/dab0dbe6f04db3f8f70ffa4573e3cd4c7e7fe18f
[ 0.00017435071640647948, 0.00017435071640647948, 0.00017435071640647948, 0.00017435071640647948, 0 ]
{ "id": 0, "code_window": [ "\n", " function getConstructSignatureDefinition(): DefinitionInfo[] | undefined {\n", " // Applicable only if we are in a new expression, or we are on a constructor declaration\n", " // and in either case the symbol has a construct signature definition, i.e. class\n", " if (isNewExpressionTarget(node) || node.kind === SyntaxKind.ConstructorKeyword && symbol.flags & SymbolFlags.Class) {\n", " const cls = find(symbol.declarations, isClassLike) || Debug.fail(\"Expected declaration to have at least one class-like declaration\");\n", " return getSignatureDefinition(cls.members, /*selectConstructors*/ true);\n", " }\n", " }\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " if (symbol.flags & SymbolFlags.Class && (isNewExpressionTarget(node) || node.kind === SyntaxKind.ConstructorKeyword)) {\n" ], "file_path": "src/services/goToDefinition.ts", "type": "replace", "edit_start_line_idx": 193 }
//// [typeParameterConstraints1.ts] function foo1<T extends any>(test: T) { } function foo2<T extends number>(test: T) { } function foo3<T extends string>(test: T) { } function foo4<T extends Date>(test: T) { } // valid function foo5<T extends RegExp>(test: T) { } // valid function foo6<T extends hm>(test: T) { } function foo7<T extends Object>(test: T) { } // valid function foo8<T extends "">(test: T) { } function foo9<T extends 1 > (test: T) { } function foo10<T extends (1)> (test: T) { } function foo11<T extends null> (test: T) { } function foo12<T extends undefined>(test: T) { } function foo13<T extends void>(test: T) { } //// [typeParameterConstraints1.js] function foo1(test) { } function foo2(test) { } function foo3(test) { } function foo4(test) { } // valid function foo5(test) { } // valid function foo6(test) { } function foo7(test) { } // valid function foo8(test) { } function foo9(test) { } function foo10(test) { } function foo11(test) { } function foo12(test) { } function foo13(test) { }
tests/baselines/reference/typeParameterConstraints1.js
0
https://github.com/microsoft/TypeScript/commit/dab0dbe6f04db3f8f70ffa4573e3cd4c7e7fe18f
[ 0.00017567236500326544, 0.00017370108980685472, 0.00017122163262683898, 0.0001742093008942902, 0.0000018521980109653668 ]
{ "id": 1, "code_window": [ "////let I: {\n", "//// /*constructSignature*/new(): C2;\n", "////};\n", "////let C = new [|/*invokeExpression*/I|]();\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "////new [|/*invokeExpression1*/I|]();\n", "////let /*symbolDeclaration*/I2: {\n", "////};\n", "////new [|/*invokeExpression2*/I2|]();\n" ], "file_path": "tests/cases/fourslash/goToDefinitionNewExpressionTargetNotClass.ts", "type": "replace", "edit_start_line_idx": 7 }
/* @internal */ namespace ts.GoToDefinition { export function getDefinitionAtPosition(program: Program, sourceFile: SourceFile, position: number): DefinitionInfo[] { const reference = getReferenceAtPosition(sourceFile, position, program); if (reference) { return [getDefinitionInfoForFileReference(reference.fileName, reference.file.fileName)]; } const node = getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); if (node === sourceFile) { return undefined; } // Labels if (isJumpStatementTarget(node)) { const labelName = (<Identifier>node).text; const label = getTargetLabel((<BreakOrContinueStatement>node.parent), labelName); return label ? [createDefinitionInfoFromName(label, ScriptElementKind.label, labelName, /*containerName*/ undefined)] : undefined; } const typeChecker = program.getTypeChecker(); const calledDeclaration = tryGetSignatureDeclaration(typeChecker, node); if (calledDeclaration) { return [createDefinitionFromSignatureDeclaration(typeChecker, calledDeclaration)]; } let symbol = typeChecker.getSymbolAtLocation(node); // Could not find a symbol e.g. node is string or number keyword, // or the symbol was an internal symbol and does not have a declaration e.g. undefined symbol if (!symbol) { return undefined; } // If this is an alias, and the request came at the declaration location // get the aliased symbol instead. This allows for goto def on an import e.g. // import {A, B} from "mod"; // to jump to the implementation directly. if (symbol.flags & SymbolFlags.Alias && shouldSkipAlias(node, symbol.declarations[0])) { const aliased = typeChecker.getAliasedSymbol(symbol); if (aliased.declarations) { symbol = aliased; } } // Because name in short-hand property assignment has two different meanings: property name and property value, // using go-to-definition at such position should go to the variable declaration of the property value rather than // go to the declaration of the property name (in this case stay at the same position). However, if go-to-definition // is performed at the location of property access, we would like to go to definition of the property in the short-hand // assignment. This case and others are handled by the following code. if (node.parent.kind === SyntaxKind.ShorthandPropertyAssignment) { const shorthandSymbol = typeChecker.getShorthandAssignmentValueSymbol(symbol.valueDeclaration); if (!shorthandSymbol) { return []; } const shorthandDeclarations = shorthandSymbol.getDeclarations(); const shorthandSymbolKind = SymbolDisplay.getSymbolKind(typeChecker, shorthandSymbol, node); const shorthandSymbolName = typeChecker.symbolToString(shorthandSymbol); const shorthandContainerName = typeChecker.symbolToString(symbol.parent, node); return map(shorthandDeclarations, declaration => createDefinitionInfo(declaration, shorthandSymbolKind, shorthandSymbolName, shorthandContainerName)); } // If the node is the name of a BindingElement within an ObjectBindingPattern instead of just returning the // declaration the symbol (which is itself), we should try to get to the original type of the ObjectBindingPattern // and return the property declaration for the referenced property. // For example: // import('./foo').then(({ b/*goto*/ar }) => undefined); => should get use to the declaration in file "./foo" // // function bar<T>(onfulfilled: (value: T) => void) { //....} // interface Test { // pr/*destination*/op1: number // } // bar<Test>(({pr/*goto*/op1})=>{}); if (isPropertyName(node) && isBindingElement(node.parent) && isObjectBindingPattern(node.parent.parent) && (node === (node.parent.propertyName || node.parent.name))) { const type = typeChecker.getTypeAtLocation(node.parent.parent); if (type) { const propSymbols = getPropertySymbolsFromType(type, node); if (propSymbols) { return flatMap(propSymbols, propSymbol => getDefinitionFromSymbol(typeChecker, propSymbol, node)); } } } // If the current location we want to find its definition is in an object literal, try to get the contextual type for the // object literal, lookup the property symbol in the contextual type, and use this for goto-definition. // For example // interface Props{ // /*first*/prop1: number // prop2: boolean // } // function Foo(arg: Props) {} // Foo( { pr/*1*/op1: 10, prop2: true }) const element = getContainingObjectLiteralElement(node); if (element && typeChecker.getContextualType(element.parent as Expression)) { return flatMap(getPropertySymbolsFromContextualType(typeChecker, element), propertySymbol => getDefinitionFromSymbol(typeChecker, propertySymbol, node)); } return getDefinitionFromSymbol(typeChecker, symbol, node); } export function getReferenceAtPosition(sourceFile: SourceFile, position: number, program: Program): { fileName: string, file: SourceFile } | undefined { const referencePath = findReferenceInPosition(sourceFile.referencedFiles, position); if (referencePath) { const file = tryResolveScriptReference(program, sourceFile, referencePath); return file && { fileName: referencePath.fileName, file }; } const typeReferenceDirective = findReferenceInPosition(sourceFile.typeReferenceDirectives, position); if (typeReferenceDirective) { const reference = program.getResolvedTypeReferenceDirectives().get(typeReferenceDirective.fileName); const file = reference && program.getSourceFile(reference.resolvedFileName); return file && { fileName: typeReferenceDirective.fileName, file }; } return undefined; } /// Goto type export function getTypeDefinitionAtPosition(typeChecker: TypeChecker, sourceFile: SourceFile, position: number): DefinitionInfo[] { const node = getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); if (node === sourceFile) { return undefined; } const symbol = typeChecker.getSymbolAtLocation(node); const type = symbol && typeChecker.getTypeOfSymbolAtLocation(symbol, node); if (!type) { return undefined; } if (type.flags & TypeFlags.Union && !(type.flags & TypeFlags.Enum)) { return flatMap((<UnionType>type).types, t => t.symbol && getDefinitionFromSymbol(typeChecker, t.symbol, node)); } return type.symbol && getDefinitionFromSymbol(typeChecker, type.symbol, node); } export function getDefinitionAndBoundSpan(program: Program, sourceFile: SourceFile, position: number): DefinitionInfoAndBoundSpan { const definitions = getDefinitionAtPosition(program, sourceFile, position); if (!definitions || definitions.length === 0) { return undefined; } // Check if position is on triple slash reference. const comment = findReferenceInPosition(sourceFile.referencedFiles, position) || findReferenceInPosition(sourceFile.typeReferenceDirectives, position); if (comment) { return { definitions, textSpan: createTextSpanFromBounds(comment.pos, comment.end) }; } const node = getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); const textSpan = createTextSpan(node.getStart(), node.getWidth()); return { definitions, textSpan }; } // Go to the original declaration for cases: // // (1) when the aliased symbol was declared in the location(parent). // (2) when the aliased symbol is originating from an import. // function shouldSkipAlias(node: Node, declaration: Node): boolean { if (node.kind !== SyntaxKind.Identifier) { return false; } if (node.parent === declaration) { return true; } switch (declaration.kind) { case SyntaxKind.ImportClause: case SyntaxKind.ImportEqualsDeclaration: return true; case SyntaxKind.ImportSpecifier: return declaration.parent.kind === SyntaxKind.NamedImports; default: return false; } } function getDefinitionFromSymbol(typeChecker: TypeChecker, symbol: Symbol, node: Node): DefinitionInfo[] { const { symbolName, symbolKind, containerName } = getSymbolInfo(typeChecker, symbol, node); return getConstructSignatureDefinition() || getCallSignatureDefinition() || map(symbol.declarations, declaration => createDefinitionInfo(declaration, symbolKind, symbolName, containerName)); function getConstructSignatureDefinition(): DefinitionInfo[] | undefined { // Applicable only if we are in a new expression, or we are on a constructor declaration // and in either case the symbol has a construct signature definition, i.e. class if (isNewExpressionTarget(node) || node.kind === SyntaxKind.ConstructorKeyword && symbol.flags & SymbolFlags.Class) { const cls = find(symbol.declarations, isClassLike) || Debug.fail("Expected declaration to have at least one class-like declaration"); return getSignatureDefinition(cls.members, /*selectConstructors*/ true); } } function getCallSignatureDefinition(): DefinitionInfo[] | undefined { return isCallExpressionTarget(node) || isNewExpressionTarget(node) || isNameOfFunctionDeclaration(node) ? getSignatureDefinition(symbol.declarations, /*selectConstructors*/ false) : undefined; } function getSignatureDefinition(signatureDeclarations: ReadonlyArray<Declaration> | undefined, selectConstructors: boolean): DefinitionInfo[] | undefined { if (!signatureDeclarations) { return undefined; } const declarations = signatureDeclarations.filter(selectConstructors ? isConstructorDeclaration : isSignatureDeclaration); return declarations.length ? [createDefinitionInfo(find(declarations, d => !!(<FunctionLikeDeclaration>d).body) || last(declarations), symbolKind, symbolName, containerName)] : undefined; } } function isSignatureDeclaration(node: Node): boolean { switch (node.kind) { case ts.SyntaxKind.Constructor: case ts.SyntaxKind.ConstructSignature: case ts.SyntaxKind.FunctionDeclaration: case ts.SyntaxKind.MethodDeclaration: case ts.SyntaxKind.MethodSignature: return true; default: return false; } } /** Creates a DefinitionInfo from a Declaration, using the declaration's name if possible. */ function createDefinitionInfo(node: Declaration, symbolKind: ScriptElementKind, symbolName: string, containerName: string): DefinitionInfo { return createDefinitionInfoFromName(getNameOfDeclaration(node) || node, symbolKind, symbolName, containerName); } /** Creates a DefinitionInfo directly from the name of a declaration. */ function createDefinitionInfoFromName(name: Node, symbolKind: ScriptElementKind, symbolName: string, containerName: string): DefinitionInfo { const sourceFile = name.getSourceFile(); return { fileName: sourceFile.fileName, textSpan: createTextSpanFromNode(name, sourceFile), kind: symbolKind, name: symbolName, containerKind: undefined, containerName }; } function getSymbolInfo(typeChecker: TypeChecker, symbol: Symbol, node: Node) { return { symbolName: typeChecker.symbolToString(symbol), // Do not get scoped name, just the name of the symbol symbolKind: SymbolDisplay.getSymbolKind(typeChecker, symbol, node), containerName: symbol.parent ? typeChecker.symbolToString(symbol.parent, node) : "" }; } function createDefinitionFromSignatureDeclaration(typeChecker: TypeChecker, decl: SignatureDeclaration): DefinitionInfo { const { symbolName, symbolKind, containerName } = getSymbolInfo(typeChecker, decl.symbol, decl); return createDefinitionInfo(decl, symbolKind, symbolName, containerName); } export function findReferenceInPosition(refs: ReadonlyArray<FileReference>, pos: number): FileReference { for (const ref of refs) { if (ref.pos <= pos && pos <= ref.end) { return ref; } } return undefined; } function getDefinitionInfoForFileReference(name: string, targetFileName: string): DefinitionInfo { return { fileName: targetFileName, textSpan: createTextSpanFromBounds(0, 0), kind: ScriptElementKind.scriptElement, name, containerName: undefined, containerKind: undefined }; } /** Returns a CallLikeExpression where `node` is the target being invoked. */ function getAncestorCallLikeExpression(node: Node): CallLikeExpression | undefined { const target = climbPastManyPropertyAccesses(node); const callLike = target.parent; return callLike && isCallLikeExpression(callLike) && getInvokedExpression(callLike) === target && callLike; } function climbPastManyPropertyAccesses(node: Node): Node { return isRightSideOfPropertyAccess(node) ? climbPastManyPropertyAccesses(node.parent) : node; } function tryGetSignatureDeclaration(typeChecker: TypeChecker, node: Node): SignatureDeclaration | undefined { const callLike = getAncestorCallLikeExpression(node); const signature = callLike && typeChecker.getResolvedSignature(callLike); if (signature) { const decl = signature.declaration; if (decl && isSignatureDeclaration(decl)) { return decl; } } // Don't go to a function type, go to the value having that type. return undefined; } }
src/services/goToDefinition.ts
1
https://github.com/microsoft/TypeScript/commit/dab0dbe6f04db3f8f70ffa4573e3cd4c7e7fe18f
[ 0.003070480190217495, 0.0003725634014699608, 0.00016606156714260578, 0.00017279779422096908, 0.0005668351659551263 ]
{ "id": 1, "code_window": [ "////let I: {\n", "//// /*constructSignature*/new(): C2;\n", "////};\n", "////let C = new [|/*invokeExpression*/I|]();\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "////new [|/*invokeExpression1*/I|]();\n", "////let /*symbolDeclaration*/I2: {\n", "////};\n", "////new [|/*invokeExpression2*/I2|]();\n" ], "file_path": "tests/cases/fourslash/goToDefinitionNewExpressionTargetNotClass.ts", "type": "replace", "edit_start_line_idx": 7 }
=== tests/cases/conformance/es6/Symbols/symbolProperty6.ts === class C { >C : Symbol(C, Decl(symbolProperty6.ts, 0, 0)) [Symbol.iterator] = 0; >Symbol.iterator : Symbol(SymbolConstructor.iterator, Decl(lib.es2015.iterable.d.ts, --, --)) >Symbol : Symbol(Symbol, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.symbol.d.ts, --, --), Decl(lib.es2015.symbol.d.ts, --, --)) >iterator : Symbol(SymbolConstructor.iterator, Decl(lib.es2015.iterable.d.ts, --, --)) [Symbol.unscopables]: number; >Symbol.unscopables : Symbol(SymbolConstructor.unscopables, Decl(lib.es2015.symbol.wellknown.d.ts, --, --)) >Symbol : Symbol(Symbol, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.symbol.d.ts, --, --), Decl(lib.es2015.symbol.d.ts, --, --)) >unscopables : Symbol(SymbolConstructor.unscopables, Decl(lib.es2015.symbol.wellknown.d.ts, --, --)) [Symbol.toPrimitive]() { } >Symbol.toPrimitive : Symbol(SymbolConstructor.toPrimitive, Decl(lib.es2015.symbol.wellknown.d.ts, --, --)) >Symbol : Symbol(Symbol, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.symbol.d.ts, --, --), Decl(lib.es2015.symbol.d.ts, --, --)) >toPrimitive : Symbol(SymbolConstructor.toPrimitive, Decl(lib.es2015.symbol.wellknown.d.ts, --, --)) get [Symbol.toStringTag]() { >Symbol.toStringTag : Symbol(SymbolConstructor.toStringTag, Decl(lib.es2015.symbol.wellknown.d.ts, --, --)) >Symbol : Symbol(Symbol, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.symbol.d.ts, --, --), Decl(lib.es2015.symbol.d.ts, --, --)) >toStringTag : Symbol(SymbolConstructor.toStringTag, Decl(lib.es2015.symbol.wellknown.d.ts, --, --)) return 0; } }
tests/baselines/reference/symbolProperty6.symbols
0
https://github.com/microsoft/TypeScript/commit/dab0dbe6f04db3f8f70ffa4573e3cd4c7e7fe18f
[ 0.0510898157954216, 0.01714547537267208, 0.00017237734573427588, 0.0001742358726914972, 0.02400227077305317 ]
{ "id": 1, "code_window": [ "////let I: {\n", "//// /*constructSignature*/new(): C2;\n", "////};\n", "////let C = new [|/*invokeExpression*/I|]();\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "////new [|/*invokeExpression1*/I|]();\n", "////let /*symbolDeclaration*/I2: {\n", "////};\n", "////new [|/*invokeExpression2*/I2|]();\n" ], "file_path": "tests/cases/fourslash/goToDefinitionNewExpressionTargetNotClass.ts", "type": "replace", "edit_start_line_idx": 7 }
//// [taggedTemplateStringsWithOverloadResolution2.ts] function foo1(strs: TemplateStringsArray, x: number): string; function foo1(strs: string[], x: number): number; function foo1(...stuff: any[]): any { return undefined; } var a = foo1 `${1}`; var b = foo1([], 1); function foo2(strs: string[], x: number): number; function foo2(strs: TemplateStringsArray, x: number): string; function foo2(...stuff: any[]): any { return undefined; } var c = foo2 `${1}`; var d = foo2([], 1); //// [taggedTemplateStringsWithOverloadResolution2.js] var __makeTemplateObject = (this && this.__makeTemplateObject) || function (cooked, raw) { if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } return cooked; }; function foo1() { var stuff = []; for (var _i = 0; _i < arguments.length; _i++) { stuff[_i] = arguments[_i]; } return undefined; } var a = foo1(__makeTemplateObject(["", ""], ["", ""]), 1); var b = foo1([], 1); function foo2() { var stuff = []; for (var _i = 0; _i < arguments.length; _i++) { stuff[_i] = arguments[_i]; } return undefined; } var c = foo2(__makeTemplateObject(["", ""], ["", ""]), 1); var d = foo2([], 1);
tests/baselines/reference/taggedTemplateStringsWithOverloadResolution2.js
0
https://github.com/microsoft/TypeScript/commit/dab0dbe6f04db3f8f70ffa4573e3cd4c7e7fe18f
[ 0.0002666539803612977, 0.00019000365864485502, 0.000168128521181643, 0.0001716838014544919, 0.00003835239840555005 ]
{ "id": 1, "code_window": [ "////let I: {\n", "//// /*constructSignature*/new(): C2;\n", "////};\n", "////let C = new [|/*invokeExpression*/I|]();\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "////new [|/*invokeExpression1*/I|]();\n", "////let /*symbolDeclaration*/I2: {\n", "////};\n", "////new [|/*invokeExpression2*/I2|]();\n" ], "file_path": "tests/cases/fourslash/goToDefinitionNewExpressionTargetNotClass.ts", "type": "replace", "edit_start_line_idx": 7 }
/// <reference path='fourslash.ts'/> ////interface I { //// property1: number; //// property2: string; ////} //// ////var foo: I; ////var { property1/**/ } = foo; goTo.marker(); verify.completionListContains("property1"); verify.not.completionListAllowsNewIdentifier();
tests/cases/fourslash/completionListInObjectBindingPattern05.ts
0
https://github.com/microsoft/TypeScript/commit/dab0dbe6f04db3f8f70ffa4573e3cd4c7e7fe18f
[ 0.004256176762282848, 0.002216607565060258, 0.0001770382805261761, 0.002216607565060258, 0.0020395691972225904 ]
{ "id": 2, "code_window": [ "\n", "verify.goToDefinition(\"invokeExpression\", \"constructSignature\");\n" ], "labels": [ "keep", "replace" ], "after_edit": [ "verify.goToDefinition({\n", " invokeExpression1: \"constructSignature\",\n", " invokeExpression2: \"symbolDeclaration\"\n", "});" ], "file_path": "tests/cases/fourslash/goToDefinitionNewExpressionTargetNotClass.ts", "type": "replace", "edit_start_line_idx": 9 }
/// <reference path='fourslash.ts' /> ////class C2 { ////} ////let I: { //// /*constructSignature*/new(): C2; ////}; ////let C = new [|/*invokeExpression*/I|](); verify.goToDefinition("invokeExpression", "constructSignature");
tests/cases/fourslash/goToDefinitionNewExpressionTargetNotClass.ts
1
https://github.com/microsoft/TypeScript/commit/dab0dbe6f04db3f8f70ffa4573e3cd4c7e7fe18f
[ 0.162870854139328, 0.08152532577514648, 0.00017979933181777596, 0.08152532577514648, 0.08134552836418152 ]
{ "id": 2, "code_window": [ "\n", "verify.goToDefinition(\"invokeExpression\", \"constructSignature\");\n" ], "labels": [ "keep", "replace" ], "after_edit": [ "verify.goToDefinition({\n", " invokeExpression1: \"constructSignature\",\n", " invokeExpression2: \"symbolDeclaration\"\n", "});" ], "file_path": "tests/cases/fourslash/goToDefinitionNewExpressionTargetNotClass.ts", "type": "replace", "edit_start_line_idx": 9 }
=== tests/cases/conformance/es6/destructuring/destructuringParameterDeclaration1ES5.ts === // A parameter declaration may specify either an identifier or a binding pattern. // The identifiers specified in parameter declarations and binding patterns // in a parameter list must be unique within that parameter list. // If the declaration includes a type annotation, the parameter is of that type function a1([a, b, [[c]]]: [number, number, string[][]]) { } >a1 : ([a, b, [[c]]]: [number, number, string[][]]) => void >a : number >b : number >c : string function a2(o: { x: number, a: number }) { } >a2 : (o: { x: number; a: number; }) => void >o : { x: number; a: number; } >x : number >a : number function a3({j, k, l: {m, n}, q: [a, b, c]}: { j: number, k: string, l: { m: boolean, n: number }, q: (number|string)[] }) { }; >a3 : ({ j, k, l: { m, n }, q: [a, b, c] }: { j: number; k: string; l: { m: boolean; n: number; }; q: (string | number)[]; }) => void >j : number >k : string >l : any >m : boolean >n : number >q : any >a : string | number >b : string | number >c : string | number >j : number >k : string >l : { m: boolean; n: number; } >m : boolean >n : number >q : (string | number)[] function a4({x, a}: { x: number, a: number }) { } >a4 : ({ x, a }: { x: number; a: number; }) => void >x : number >a : number >x : number >a : number a1([1, 2, [["world"]]]); >a1([1, 2, [["world"]]]) : void >a1 : ([a, b, [[c]]]: [number, number, string[][]]) => void >[1, 2, [["world"]]] : [number, number, string[][]] >1 : 1 >2 : 2 >[["world"]] : string[][] >["world"] : string[] >"world" : "world" a1([1, 2, [["world"]], 3]); >a1([1, 2, [["world"]], 3]) : void >a1 : ([a, b, [[c]]]: [number, number, string[][]]) => void >[1, 2, [["world"]], 3] : (number | string[][])[] >1 : 1 >2 : 2 >[["world"]] : string[][] >["world"] : string[] >"world" : "world" >3 : 3 // If the declaration includes an initializer expression (which is permitted only // when the parameter list occurs in conjunction with a function body), // the parameter type is the widened form (section 3.11) of the type of the initializer expression. function b1(z = [undefined, null]) { }; >b1 : (z?: any[]) => void >z : any[] >[undefined, null] : null[] >undefined : undefined >null : null function b2(z = null, o = { x: 0, y: undefined }) { } >b2 : (z?: any, o?: { x: number; y: any; }) => void >z : any >null : null >o : { x: number; y: any; } >{ x: 0, y: undefined } : { x: number; y: undefined; } >x : number >0 : 0 >y : undefined >undefined : undefined function b3({z: {x, y: {j}}} = { z: { x: "hi", y: { j: 1 } } }) { } >b3 : ({ z: { x, y: { j } } }?: { z: { x: string; y: { j: number; }; }; }) => void >z : any >x : string >y : any >j : number >{ z: { x: "hi", y: { j: 1 } } } : { z: { x: string; y: { j: number; }; }; } >z : { x: string; y: { j: number; }; } >{ x: "hi", y: { j: 1 } } : { x: string; y: { j: number; }; } >x : string >"hi" : "hi" >y : { j: number; } >{ j: 1 } : { j: number; } >j : number >1 : 1 interface F1 { >F1 : F1 b5(z, y, [, a, b], {p, m: { q, r}}); >b5 : (z: any, y: any, [, a, b]: [any, any, any], { p, m: { q, r } }: { p: any; m: { q: any; r: any; }; }) => any >z : any >y : any > : undefined >a : any >b : any >p : any >m : any >q : any >r : any } function b6([a, z, y] = [undefined, null, undefined]) { } >b6 : ([a, z, y]?: [any, any, any]) => void >a : any >z : any >y : any >[undefined, null, undefined] : [undefined, null, undefined] >undefined : undefined >null : null >undefined : undefined function b7([[a], b, [[c, d]]] = [[undefined], undefined, [[undefined, undefined]]]) { } >b7 : ([[a], b, [[c, d]]]?: [[any], any, [[any, any]]]) => void >a : any >b : any >c : any >d : any >[[undefined], undefined, [[undefined, undefined]]] : [[undefined], undefined, [[undefined, undefined]]] >[undefined] : [undefined] >undefined : undefined >undefined : undefined >[[undefined, undefined]] : [[undefined, undefined]] >[undefined, undefined] : [undefined, undefined] >undefined : undefined >undefined : undefined b1([1, 2, 3]); // z is widen to the type any[] >b1([1, 2, 3]) : void >b1 : (z?: any[]) => void >[1, 2, 3] : number[] >1 : 1 >2 : 2 >3 : 3 b2("string", { x: 200, y: "string" }); >b2("string", { x: 200, y: "string" }) : void >b2 : (z?: any, o?: { x: number; y: any; }) => void >"string" : "string" >{ x: 200, y: "string" } : { x: number; y: string; } >x : number >200 : 200 >y : string >"string" : "string" b2("string", { x: 200, y: true }); >b2("string", { x: 200, y: true }) : void >b2 : (z?: any, o?: { x: number; y: any; }) => void >"string" : "string" >{ x: 200, y: true } : { x: number; y: boolean; } >x : number >200 : 200 >y : boolean >true : true b6(["string", 1, 2]); // Shouldn't be an error >b6(["string", 1, 2]) : void >b6 : ([a, z, y]?: [any, any, any]) => void >["string", 1, 2] : [string, number, number] >"string" : "string" >1 : 1 >2 : 2 b7([["string"], 1, [[true, false]]]); // Shouldn't be an error >b7([["string"], 1, [[true, false]]]) : void >b7 : ([[a], b, [[c, d]]]?: [[any], any, [[any, any]]]) => void >[["string"], 1, [[true, false]]] : [[string], number, [[boolean, boolean]]] >["string"] : [string] >"string" : "string" >1 : 1 >[[true, false]] : [[boolean, boolean]] >[true, false] : [boolean, boolean] >true : true >false : false // If the declaration specifies a binding pattern, the parameter type is the implied type of that binding pattern (section 5.1.3) enum Foo { a } >Foo : Foo >a : Foo function c0({z: {x, y: {j}}}) { } >c0 : ({ z: { x, y: { j } } }: { z: { x: any; y: { j: any; }; }; }) => void >z : any >x : any >y : any >j : any function c1({z} = { z: 10 }) { } >c1 : ({ z }?: { z: number; }) => void >z : number >{ z: 10 } : { z: number; } >z : number >10 : 10 function c2({z = 10}) { } >c2 : ({ z }: { z?: number; }) => void >z : number >10 : 10 function c3({b}: { b: number|string} = { b: "hello" }) { } >c3 : ({ b }?: { b: string | number; }) => void >b : string | number >b : string | number >{ b: "hello" } : { b: string; } >b : string >"hello" : "hello" function c5([a, b, [[c]]]) { } >c5 : ([a, b, [[c]]]: [any, any, [[any]]]) => void >a : any >b : any >c : any function c6([a, b, [[c=1]]]) { } >c6 : ([a, b, [[c]]]: [any, any, [[number]]]) => void >a : any >b : any >c : number >1 : 1 c0({z : { x: 1, y: { j: "world" } }}); // Implied type is { z: {x: any, y: {j: any}} } >c0({z : { x: 1, y: { j: "world" } }}) : void >c0 : ({ z: { x, y: { j } } }: { z: { x: any; y: { j: any; }; }; }) => void >{z : { x: 1, y: { j: "world" } }} : { z: { x: number; y: { j: string; }; }; } >z : { x: number; y: { j: string; }; } >{ x: 1, y: { j: "world" } } : { x: number; y: { j: string; }; } >x : number >1 : 1 >y : { j: string; } >{ j: "world" } : { j: string; } >j : string >"world" : "world" c0({z : { x: "string", y: { j: true } }}); // Implied type is { z: {x: any, y: {j: any}} } >c0({z : { x: "string", y: { j: true } }}) : void >c0 : ({ z: { x, y: { j } } }: { z: { x: any; y: { j: any; }; }; }) => void >{z : { x: "string", y: { j: true } }} : { z: { x: string; y: { j: boolean; }; }; } >z : { x: string; y: { j: boolean; }; } >{ x: "string", y: { j: true } } : { x: string; y: { j: boolean; }; } >x : string >"string" : "string" >y : { j: boolean; } >{ j: true } : { j: boolean; } >j : boolean >true : true c1(); // Implied type is {z:number}? >c1() : void >c1 : ({ z }?: { z: number; }) => void c1({ z: 1 }) // Implied type is {z:number}? >c1({ z: 1 }) : void >c1 : ({ z }?: { z: number; }) => void >{ z: 1 } : { z: number; } >z : number >1 : 1 c2({}); // Implied type is {z?: number} >c2({}) : void >c2 : ({ z }: { z?: number; }) => void >{} : {} c2({z:1}); // Implied type is {z?: number} >c2({z:1}) : void >c2 : ({ z }: { z?: number; }) => void >{z:1} : { z: number; } >z : number >1 : 1 c3({ b: 1 }); // Implied type is { b: number|string }. >c3({ b: 1 }) : void >c3 : ({ b }?: { b: string | number; }) => void >{ b: 1 } : { b: number; } >b : number >1 : 1 c5([1, 2, [["string"]]]); // Implied type is is [any, any, [[any]]] >c5([1, 2, [["string"]]]) : void >c5 : ([a, b, [[c]]]: [any, any, [[any]]]) => void >[1, 2, [["string"]]] : [number, number, [[string]]] >1 : 1 >2 : 2 >[["string"]] : [[string]] >["string"] : [string] >"string" : "string" c5([1, 2, [["string"]], false, true]); // Implied type is is [any, any, [[any]]] >c5([1, 2, [["string"]], false, true]) : void >c5 : ([a, b, [[c]]]: [any, any, [[any]]]) => void >[1, 2, [["string"]], false, true] : (number | boolean | string[][])[] >1 : 1 >2 : 2 >[["string"]] : string[][] >["string"] : string[] >"string" : "string" >false : false >true : true // A parameter can be marked optional by following its name or binding pattern with a question mark (?) // or by including an initializer. function d0(x?) { } >d0 : (x?: any) => void >x : any function d0(x = 10) { } >d0 : (x?: any) => void >x : number >10 : 10 interface F2 { >F2 : F2 d3([a, b, c]?); >d3 : ([a, b, c]?: [any, any, any]) => any >a : any >b : any >c : any d4({x, y, z}?); >d4 : ({ x, y, z }?: { x: any; y: any; z: any; }) => any >x : any >y : any >z : any e0([a, b, c]); >e0 : ([a, b, c]: [any, any, any]) => any >a : any >b : any >c : any } class C2 implements F2 { >C2 : C2 >F2 : F2 constructor() { } d3() { } >d3 : () => void d4() { } >d4 : () => void e0([a, b, c]) { } >e0 : ([a, b, c]: [any, any, any]) => void >a : any >b : any >c : any } class C3 implements F2 { >C3 : C3 >F2 : F2 d3([a, b, c]) { } >d3 : ([a, b, c]: [any, any, any]) => void >a : any >b : any >c : any d4({x, y, z}) { } >d4 : ({ x, y, z }: { x: any; y: any; z: any; }) => void >x : any >y : any >z : any e0([a, b, c]) { } >e0 : ([a, b, c]: [any, any, any]) => void >a : any >b : any >c : any } function d5({x, y} = { x: 1, y: 2 }) { } >d5 : ({ x, y }?: { x: number; y: number; }) => void >x : number >y : number >{ x: 1, y: 2 } : { x: number; y: number; } >x : number >1 : 1 >y : number >2 : 2 d5(); // Parameter is optional as its declaration included an initializer >d5() : void >d5 : ({ x, y }?: { x: number; y: number; }) => void // Destructuring parameter declarations do not permit type annotations on the individual binding patterns, // as such annotations would conflict with the already established meaning of colons in object literals. // Type annotations must instead be written on the top- level parameter declaration function e1({x: number}) { } // x has type any NOT number >e1 : ({ x: number }: { x: any; }) => void >x : any >number : any function e2({x}: { x: number }) { } // x is type number >e2 : ({ x }: { x: number; }) => void >x : number >x : number function e3({x}: { x?: number }) { } // x is an optional with type number >e3 : ({ x }: { x?: number; }) => void >x : number >x : number function e4({x: [number,string,any] }) { } // x has type [any, any, any] >e4 : ({ x: [number, string, any] }: { x: [any, any, any]; }) => void >x : any >number : any >string : any >any : any function e5({x: [a, b, c]}: { x: [number, number, number] }) { } // x has type [any, any, any] >e5 : ({ x: [a, b, c] }: { x: [number, number, number]; }) => void >x : any >a : number >b : number >c : number >x : [number, number, number]
tests/baselines/reference/destructuringParameterDeclaration1ES5.types
0
https://github.com/microsoft/TypeScript/commit/dab0dbe6f04db3f8f70ffa4573e3cd4c7e7fe18f
[ 0.00017513615603093058, 0.00017003236280288547, 0.00016524670354556292, 0.00017003956600092351, 0.0000021683260911231628 ]
{ "id": 2, "code_window": [ "\n", "verify.goToDefinition(\"invokeExpression\", \"constructSignature\");\n" ], "labels": [ "keep", "replace" ], "after_edit": [ "verify.goToDefinition({\n", " invokeExpression1: \"constructSignature\",\n", " invokeExpression2: \"symbolDeclaration\"\n", "});" ], "file_path": "tests/cases/fourslash/goToDefinitionNewExpressionTargetNotClass.ts", "type": "replace", "edit_start_line_idx": 9 }
{"version":3,"file":"m2.js","sourceRoot":"","sources":["m2.ts"],"names":[],"mappings":";;;IAAW,QAAA,KAAK,GAAG,EAAE,CAAC;IACtB;QAAA;QAEA,CAAC;QAAD,YAAC;IAAD,CAAC,AAFD,IAEC;IAFY,sBAAK;IAIP,QAAA,YAAY,GAAG,IAAI,KAAK,EAAE,CAAC;IACtC;QACI,MAAM,CAAC,oBAAY,CAAC;IACxB,CAAC;IAFD,sBAEC"}
tests/baselines/reference/project/sourcemapMixedSubfolderNoOutdir/amd/ref/m2.js.map
0
https://github.com/microsoft/TypeScript/commit/dab0dbe6f04db3f8f70ffa4573e3cd4c7e7fe18f
[ 0.0001659843255765736, 0.0001659843255765736, 0.0001659843255765736, 0.0001659843255765736, 0 ]
{ "id": 2, "code_window": [ "\n", "verify.goToDefinition(\"invokeExpression\", \"constructSignature\");\n" ], "labels": [ "keep", "replace" ], "after_edit": [ "verify.goToDefinition({\n", " invokeExpression1: \"constructSignature\",\n", " invokeExpression2: \"symbolDeclaration\"\n", "});" ], "file_path": "tests/cases/fourslash/goToDefinitionNewExpressionTargetNotClass.ts", "type": "replace", "edit_start_line_idx": 9 }
//// [sourceMapValidationForIn.js.map] {"version":3,"file":"sourceMapValidationForIn.js","sourceRoot":"","sources":["sourceMapValidationForIn.ts"],"names":[],"mappings":"AAAA,GAAG,CAAC,CAAC,IAAI,CAAC,IAAI,MAAM,CAAC,CAAC,CAAC;IACnB,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC;AACD,GAAG,CAAC,CAAC,CAAC,IAAI,MAAM,CAAC,CAAC,CAAC;IACf,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC;AACD,GAAG,CAAC,CAAC,IAAI,EAAE,IAAI,MAAM,CAAC,CACtB,CAAC;IACG,OAAO,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;AACrB,CAAC;AACD,GAAG,CAAC,CAAC,CAAC,IAAI,MAAM,CAAC,CACjB,CAAC;IACG,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC"}
tests/baselines/reference/sourceMapValidationForIn.js.map
0
https://github.com/microsoft/TypeScript/commit/dab0dbe6f04db3f8f70ffa4573e3cd4c7e7fe18f
[ 0.00016744344611652195, 0.00016744344611652195, 0.00016744344611652195, 0.00016744344611652195, 0 ]
{ "id": 0, "code_window": [ " onStoryChange = id => {\n", " const { api } = this.props;\n", " const list = api.getParameters(id, PARAM_KEY);\n", " const picked = list.filter(res => res.picked);\n", " console.log({ list });\n", "\n", " if (list) {\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep" ], "after_edit": [], "file_path": "addons/cssresources/src/css-resource-panel.js", "type": "replace", "edit_start_line_idx": 36 }
import { chromeDark, chromeLight } from 'react-inspector'; import { dark as darkSyntax, light as lightSyntax } from './syntaxhighlighter/themes'; import { Brand } from './logo/logo'; export const baseFonts = { fontFamily: '-apple-system, ".SFNSText-Regular", "San Francisco", BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen", "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue", "Lucida Grande", "Arial", sans-serif', color: '#444', WebkitFontSmoothing: 'antialiased', }; export const monoFonts = { fontFamily: '"Operator Mono", "Fira Code Retina", "Fira Code", "FiraCode-Retina", "Andale Mono", "Lucida Console", Consolas, Monaco, monospace', color: '#444', WebkitFontSmoothing: 'antialiased', }; export const normal = { // mainBackground: '#f6f9fc', mainBackground: '#f6f9fc linear-gradient(to bottom right, rgba(0,0,0,0), rgba(0,0,0,0.1))', mainBorder: '1px solid rgba(0,0,0,0.1)', mainBorderColor: 'rgba(0,0,0,0.1)', mainBorderRadius: 4, mainFill: 'rgba(255,255,255,0.89)', barFill: 'rgba(255,255,255,1)', asideFill: 'transparent', barSelectedColor: 'rgba(0,0,0,0.1)', inputFill: 'transparent', mainTextFace: baseFonts.fontFamily, mainTextColor: baseFonts.color, dimmedTextColor: 'rgba(0,0,0,0.4)', highlightColor: '#9fdaff', menuHighlightColor: '#1ea7fd', successColor: '#09833a', failColor: '#d53535', warnColor: 'orange', mainTextSize: 13, monoTextFace: monoFonts.fontFamily, layoutMargin: 10, overlayBackground: 'linear-gradient(to bottom right, rgba(233, 233, 233, 0.6), rgba(255, 255, 255, 0.8))', brand: Brand, code: lightSyntax, addonActionsTheme: { ...chromeLight, BASE_FONT_FAMILY: monoFonts.fontFamily, BASE_BACKGROUND_COLOR: 'transparent', }, }; export const dark = { mainBackground: '#112 linear-gradient(to right, #112, #333)', mainBorder: '1px solid rgba(255,255,255,0.1)', mainBorderColor: 'rgba(255,255,255,0.1)', mainBorderRadius: 4, mainFill: 'rgba(255,255,255,0.1)', barFill: 'rgba(0,0,0,1)', asideFill: 'linear-gradient(to right, rgba(0,0,0,0) 0%,rgba(0,0,0,0) 50%,rgba(0,0,0,0.5) 100%)', asideSelected: { color: '#9fdaff', }, barSelectedColor: 'rgba(255,255,255,0.4)', inputFill: 'rgba(0,0,0,1)', mainTextFace: baseFonts.fontFamily, mainTextColor: '#efefef', dimmedTextColor: 'rgba(255,255,255,0.4)', highlightColor: '#9fdaff', menuHighlightColor: '#1ea7fd', successColor: '#0edf62', failColor: '#ff3f3f', warnColor: 'orange', mainTextSize: 13, monoTextFace: monoFonts.fontFamily, layoutMargin: 10, overlayBackground: 'linear-gradient(to bottom right, rgba(17, 17, 34, 0.6), rgba(51, 51, 51, 0.8))', // brand: { // width: '100%', // height: 40, // backgroundSize: 'contain', // backgroundRepeat: 'no-repeat', // backgroundPosition: '0 0', // backgroundImage: logo, // }, code: darkSyntax, addonActionsTheme: { ...chromeDark, BASE_FONT_FAMILY: monoFonts.fontFamily, BASE_BACKGROUND_COLOR: 'transparent', }, };
lib/components/src/theme.js
1
https://github.com/storybookjs/storybook/commit/7c3b15dec6c7cd4e27ebdddeff77e1b949fbe19e
[ 0.00017961135017685592, 0.00017637763812672347, 0.00017385037790518254, 0.0001760775048751384, 0.0000020692552880063886 ]
{ "id": 0, "code_window": [ " onStoryChange = id => {\n", " const { api } = this.props;\n", " const list = api.getParameters(id, PARAM_KEY);\n", " const picked = list.filter(res => res.picked);\n", " console.log({ list });\n", "\n", " if (list) {\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep" ], "after_edit": [], "file_path": "addons/cssresources/src/css-resource-panel.js", "type": "replace", "edit_start_line_idx": 36 }
<template> <div class="main"> <h1>Welcome to Storybook for Vue</h1> <p> This is a UI component dev environment for your vue app. </p> <p> We've added some basic stories inside the <code class="code">src/stories</code> directory. <br /> A story is a single state of one or more UI components. You can have as many stories as you want. <br /> (Basically a story is like a visual test case.) </p> <p> See these sample <a class="link" @click="goToButton">stories</a> for a component called <code class="code">Button</code> . </p> <p style="text-align:center"><img src="../logo.png" /></p> <p> Just like that, you can add your own components as stories. <br /> You can also edit those components and see changes right away. <br /> (Try editing the <code class="code">Button</code> component located at <code class="code">src/stories/Button.js</code>.) </p> <p> Usually we create stories with smaller UI components in the app.<br /> Have a look at the <a class="link" href="https://storybook.js.org/basics/writing-stories" target="_blank" > Writing Stories </a> section in our documentation. </p> <p class="note"> <b>NOTE:</b> <br /> Have a look at the <code class="code">.storybook/webpack.config.js</code> to add webpack loaders and plugins you are using in this project. </p> </div> </template> <script> export default { props: { goToButton: { default: () => () => null }, } } </script> <style> .main { margin: 15px; max-width: 600; line-height: 1.4; font-family: "Helvetica Neue", Helvetica, "Segoe UI", Arial, freesans, sans-serif; } .logo { width: 200; } .link { color: #1474f3; text-decoration: none; border-bottom: 1px solid #1474f3; padding-bottom: 2px; } .code { font-size: 15; font-weight: 600; padding: 2px 5px; border: 1px solid #eae9e9; border-radius: 4px; background-color: #f3f2f2; color: #3a3a3a; } .codeBlock { background-color: #f3f2f2; padding: 1px 10px; margin: 10px 0; } .note { opacity: 0.5; } </style>
examples/vue-kitchen-sink/src/stories/Welcome.vue
0
https://github.com/storybookjs/storybook/commit/7c3b15dec6c7cd4e27ebdddeff77e1b949fbe19e
[ 0.0001796490396372974, 0.00017326300439890474, 0.00016435461293440312, 0.00017200809088535607, 0.000004883331257587997 ]
{ "id": 0, "code_window": [ " onStoryChange = id => {\n", " const { api } = this.props;\n", " const list = api.getParameters(id, PARAM_KEY);\n", " const picked = list.filter(res => res.picked);\n", " console.log({ list });\n", "\n", " if (list) {\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep" ], "after_edit": [], "file_path": "addons/cssresources/src/css-resource-panel.js", "type": "replace", "edit_start_line_idx": 36 }
import { Provider } from '@storybook/ui'; import addons from '@storybook/addons'; import createChannel from '@storybook/channel-postmessage'; import Events from '@storybook/core-events'; export default class ReactProvider extends Provider { constructor() { super(); this.channel = createChannel({ page: 'manager' }); addons.setChannel(this.channel); this.channel.emit(Events.CHANNEL_CREATED); } getElements(type) { return addons.getElements(type); } handleAPI(api) { this.channel.on(Events.SET_STORIES, data => { api.setStories(data.stories); }); this.channel.on(Events.SELECT_STORY, ({ kind, story, ...rest }) => { api.selectStory(kind, story, rest); }); this.channel.on(Events.APPLY_SHORTCUT, data => { api.handleShortcut(data.event); }); addons.loadAddons(api); } }
lib/core/src/client/manager/provider.js
0
https://github.com/storybookjs/storybook/commit/7c3b15dec6c7cd4e27ebdddeff77e1b949fbe19e
[ 0.00047867445391602814, 0.00025125351385213435, 0.00017340238264296204, 0.00017646857304498553, 0.00013131176820024848 ]
{ "id": 0, "code_window": [ " onStoryChange = id => {\n", " const { api } = this.props;\n", " const list = api.getParameters(id, PARAM_KEY);\n", " const picked = list.filter(res => res.picked);\n", " console.log({ list });\n", "\n", " if (list) {\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep" ], "after_edit": [], "file_path": "addons/cssresources/src/css-resource-panel.js", "type": "replace", "edit_start_line_idx": 36 }
export function babelDefault(config) { return { ...config, presets: [ ...config.presets, require.resolve('@babel/preset-react'), require.resolve('@babel/preset-flow'), ], }; }
app/react/src/server/framework-preset-react.js
0
https://github.com/storybookjs/storybook/commit/7c3b15dec6c7cd4e27ebdddeff77e1b949fbe19e
[ 0.00017738179303705692, 0.00017676240531727672, 0.0001761430175974965, 0.00017676240531727672, 6.193877197802067e-7 ]
{ "id": 1, "code_window": [ "\n", " if (list) {\n", " this.setState({ list }, () => this.emit(picked));\n", " }\n", " };\n", "\n", " onChange = event => {\n" ], "labels": [ "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " const picked = list.filter(res => res.picked);\n" ], "file_path": "addons/cssresources/src/css-resource-panel.js", "type": "add", "edit_start_line_idx": 40 }
import { chromeDark, chromeLight } from 'react-inspector'; import { dark as darkSyntax, light as lightSyntax } from './syntaxhighlighter/themes'; import { Brand } from './logo/logo'; export const baseFonts = { fontFamily: '-apple-system, ".SFNSText-Regular", "San Francisco", BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen", "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue", "Lucida Grande", "Arial", sans-serif', color: '#444', WebkitFontSmoothing: 'antialiased', }; export const monoFonts = { fontFamily: '"Operator Mono", "Fira Code Retina", "Fira Code", "FiraCode-Retina", "Andale Mono", "Lucida Console", Consolas, Monaco, monospace', color: '#444', WebkitFontSmoothing: 'antialiased', }; export const normal = { // mainBackground: '#f6f9fc', mainBackground: '#f6f9fc linear-gradient(to bottom right, rgba(0,0,0,0), rgba(0,0,0,0.1))', mainBorder: '1px solid rgba(0,0,0,0.1)', mainBorderColor: 'rgba(0,0,0,0.1)', mainBorderRadius: 4, mainFill: 'rgba(255,255,255,0.89)', barFill: 'rgba(255,255,255,1)', asideFill: 'transparent', barSelectedColor: 'rgba(0,0,0,0.1)', inputFill: 'transparent', mainTextFace: baseFonts.fontFamily, mainTextColor: baseFonts.color, dimmedTextColor: 'rgba(0,0,0,0.4)', highlightColor: '#9fdaff', menuHighlightColor: '#1ea7fd', successColor: '#09833a', failColor: '#d53535', warnColor: 'orange', mainTextSize: 13, monoTextFace: monoFonts.fontFamily, layoutMargin: 10, overlayBackground: 'linear-gradient(to bottom right, rgba(233, 233, 233, 0.6), rgba(255, 255, 255, 0.8))', brand: Brand, code: lightSyntax, addonActionsTheme: { ...chromeLight, BASE_FONT_FAMILY: monoFonts.fontFamily, BASE_BACKGROUND_COLOR: 'transparent', }, }; export const dark = { mainBackground: '#112 linear-gradient(to right, #112, #333)', mainBorder: '1px solid rgba(255,255,255,0.1)', mainBorderColor: 'rgba(255,255,255,0.1)', mainBorderRadius: 4, mainFill: 'rgba(255,255,255,0.1)', barFill: 'rgba(0,0,0,1)', asideFill: 'linear-gradient(to right, rgba(0,0,0,0) 0%,rgba(0,0,0,0) 50%,rgba(0,0,0,0.5) 100%)', asideSelected: { color: '#9fdaff', }, barSelectedColor: 'rgba(255,255,255,0.4)', inputFill: 'rgba(0,0,0,1)', mainTextFace: baseFonts.fontFamily, mainTextColor: '#efefef', dimmedTextColor: 'rgba(255,255,255,0.4)', highlightColor: '#9fdaff', menuHighlightColor: '#1ea7fd', successColor: '#0edf62', failColor: '#ff3f3f', warnColor: 'orange', mainTextSize: 13, monoTextFace: monoFonts.fontFamily, layoutMargin: 10, overlayBackground: 'linear-gradient(to bottom right, rgba(17, 17, 34, 0.6), rgba(51, 51, 51, 0.8))', // brand: { // width: '100%', // height: 40, // backgroundSize: 'contain', // backgroundRepeat: 'no-repeat', // backgroundPosition: '0 0', // backgroundImage: logo, // }, code: darkSyntax, addonActionsTheme: { ...chromeDark, BASE_FONT_FAMILY: monoFonts.fontFamily, BASE_BACKGROUND_COLOR: 'transparent', }, };
lib/components/src/theme.js
1
https://github.com/storybookjs/storybook/commit/7c3b15dec6c7cd4e27ebdddeff77e1b949fbe19e
[ 0.00017479166854172945, 0.00017211220983881503, 0.0001681581634329632, 0.00017255678540095687, 0.0000021972289232508047 ]
{ "id": 1, "code_window": [ "\n", " if (list) {\n", " this.setState({ list }, () => this.emit(picked));\n", " }\n", " };\n", "\n", " onChange = event => {\n" ], "labels": [ "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " const picked = list.filter(res => res.picked);\n" ], "file_path": "addons/cssresources/src/css-resource-panel.js", "type": "add", "edit_start_line_idx": 40 }
/** @jsx m */ import m from 'mithril'; import { linkTo, hrefTo } from '@storybook/addon-links'; const Main = { view: vnode => ( <article style={{ margin: '15px', maxWidth: '600px', lineHeight: 1.4, fontFamily: '"Helvetica Neue", Helvetica, "Segoe UI", Arial, freesans, sans-serif', }} > {vnode.children} </article> ), }; const Title = { view: vnode => <h1>{vnode.children}</h1>, }; const Note = { view: vnode => ( <p style={{ opacity: 0.5, }} > {vnode.children} </p> ), }; const InlineCode = { view: vnode => ( <code style={{ fontSize: '15px', fontWeight: 600, padding: '2px 5px', border: '1px solid #eae9e9', borderRadius: '4px', backgroundColor: '#f3f2f2', color: '#3a3a3a', }} > {vnode.children} </code> ), }; const Link = { view: vnode => ( <a style={{ color: '#1474f3', textDecoration: 'none', borderBottom: '1px solid #1474f3', paddingBottom: '2px', }} {...vnode.attrs} > {vnode.children} </a> ), }; const NavButton = { view: vnode => ( <button type="button" style={{ borderTop: 'none', borderRight: 'none', borderLeft: 'none', backgroundColor: 'transparent', padding: 0, cursor: 'pointer', font: 'inherit', }} {...vnode.attrs} > {vnode.children} </button> ), }; const StoryLink = { oninit: vnode => { // eslint-disable-next-line no-param-reassign vnode.state.href = '/'; // eslint-disable-next-line no-param-reassign vnode.state.onclick = () => { linkTo(vnode.attrs.kind, vnode.attrs.story)(); return false; }; StoryLink.updateHref(vnode); }, updateHref: async vnode => { const href = await hrefTo(vnode.attrs.kind, vnode.attrs.story); // eslint-disable-next-line no-param-reassign vnode.state.href = href; m.redraw(); }, view: vnode => ( <a href={vnode.state.href} style={{ color: '#1474f3', textDecoration: 'none', borderBottom: '1px solid #1474f3', paddingBottom: '2px', }} onClick={vnode.state.onclick} > {vnode.children} </a> ), }; const Welcome = { view: vnode => ( <Main> <Title>Welcome to storybook</Title> <p>This is a UI component dev environment for your app.</p> <p> We've added some basic stories inside the <InlineCode>src/stories</InlineCode> directory. <br />A story is a single state of one or more UI components. You can have as many stories as you want. <br /> (Basically a story is like a visual test case.) </p> <p> See these sample{' '} {vnode.attrs.showApp ? ( <NavButton onclick={vnode.attrs.showApp}>stories</NavButton> ) : ( <StoryLink kind={vnode.attrs.showKind} story={vnode.attrs.showStory}> stories </StoryLink> )}{' '} for a component called <InlineCode>Button</InlineCode>. </p> <p> Just like that, you can add your own components as stories. <br /> You can also edit those components and see changes right away. <br /> (Try editing the <InlineCode>Button</InlineCode> stories located at{' '} <InlineCode>src/stories/index.js</InlineCode> .) </p> <p> Usually we create stories with smaller UI components in the app. <br /> Have a look at the{' '} <Link href="https://storybook.js.org/basics/writing-stories" target="_blank" rel="noopener noreferrer" > Writing Stories </Link>{' '} section in our documentation. </p> <Note> <b>NOTE:</b> <br /> Have a look at the <InlineCode>.storybook/webpack.config.js</InlineCode> to add webpack loaders and plugins you are using in this project. </Note> </Main> ), }; export default Welcome;
lib/cli/generators/MITHRIL/template/stories/Welcome.js
0
https://github.com/storybookjs/storybook/commit/7c3b15dec6c7cd4e27ebdddeff77e1b949fbe19e
[ 0.00017429818399250507, 0.00017041765386238694, 0.00016502295329701155, 0.00017100252443924546, 0.0000028325337098067394 ]
{ "id": 1, "code_window": [ "\n", " if (list) {\n", " this.setState({ list }, () => this.emit(picked));\n", " }\n", " };\n", "\n", " onChange = event => {\n" ], "labels": [ "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " const picked = list.filter(res => res.picked);\n" ], "file_path": "addons/cssresources/src/css-resource-panel.js", "type": "add", "edit_start_line_idx": 40 }
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 841.9 595.3"> <g fill="#61DAFB"> <path d="M666.3 296.5c0-32.5-40.7-63.3-103.1-82.4 14.4-63.6 8-114.2-20.2-130.4-6.5-3.8-14.1-5.6-22.4-5.6v22.3c4.6 0 8.3.9 11.4 2.6 13.6 7.8 19.5 37.5 14.9 75.7-1.1 9.4-2.9 19.3-5.1 29.4-19.6-4.8-41-8.5-63.5-10.9-13.5-18.5-27.5-35.3-41.6-50 32.6-30.3 63.2-46.9 84-46.9V78c-27.5 0-63.5 19.6-99.9 53.6-36.4-33.8-72.4-53.2-99.9-53.2v22.3c20.7 0 51.4 16.5 84 46.6-14 14.7-28 31.4-41.3 49.9-22.6 2.4-44 6.1-63.6 11-2.3-10-4-19.7-5.2-29-4.7-38.2 1.1-67.9 14.6-75.8 3-1.8 6.9-2.6 11.5-2.6V78.5c-8.4 0-16 1.8-22.6 5.6-28.1 16.2-34.4 66.7-19.9 130.1-62.2 19.2-102.7 49.9-102.7 82.3 0 32.5 40.7 63.3 103.1 82.4-14.4 63.6-8 114.2 20.2 130.4 6.5 3.8 14.1 5.6 22.5 5.6 27.5 0 63.5-19.6 99.9-53.6 36.4 33.8 72.4 53.2 99.9 53.2 8.4 0 16-1.8 22.6-5.6 28.1-16.2 34.4-66.7 19.9-130.1 62-19.1 102.5-49.9 102.5-82.3zm-130.2-66.7c-3.7 12.9-8.3 26.2-13.5 39.5-4.1-8-8.4-16-13.1-24-4.6-8-9.5-15.8-14.4-23.4 14.2 2.1 27.9 4.7 41 7.9zm-45.8 106.5c-7.8 13.5-15.8 26.3-24.1 38.2-14.9 1.3-30 2-45.2 2-15.1 0-30.2-.7-45-1.9-8.3-11.9-16.4-24.6-24.2-38-7.6-13.1-14.5-26.4-20.8-39.8 6.2-13.4 13.2-26.8 20.7-39.9 7.8-13.5 15.8-26.3 24.1-38.2 14.9-1.3 30-2 45.2-2 15.1 0 30.2.7 45 1.9 8.3 11.9 16.4 24.6 24.2 38 7.6 13.1 14.5 26.4 20.8 39.8-6.3 13.4-13.2 26.8-20.7 39.9zm32.3-13c5.4 13.4 10 26.8 13.8 39.8-13.1 3.2-26.9 5.9-41.2 8 4.9-7.7 9.8-15.6 14.4-23.7 4.6-8 8.9-16.1 13-24.1zM421.2 430c-9.3-9.6-18.6-20.3-27.8-32 9 .4 18.2.7 27.5.7 9.4 0 18.7-.2 27.8-.7-9 11.7-18.3 22.4-27.5 32zm-74.4-58.9c-14.2-2.1-27.9-4.7-41-7.9 3.7-12.9 8.3-26.2 13.5-39.5 4.1 8 8.4 16 13.1 24 4.7 8 9.5 15.8 14.4 23.4zM420.7 163c9.3 9.6 18.6 20.3 27.8 32-9-.4-18.2-.7-27.5-.7-9.4 0-18.7.2-27.8.7 9-11.7 18.3-22.4 27.5-32zm-74 58.9c-4.9 7.7-9.8 15.6-14.4 23.7-4.6 8-8.9 16-13 24-5.4-13.4-10-26.8-13.8-39.8 13.1-3.1 26.9-5.8 41.2-7.9zm-90.5 125.2c-35.4-15.1-58.3-34.9-58.3-50.6 0-15.7 22.9-35.6 58.3-50.6 8.6-3.7 18-7 27.7-10.1 5.7 19.6 13.2 40 22.5 60.9-9.2 20.8-16.6 41.1-22.2 60.6-9.9-3.1-19.3-6.5-28-10.2zM310 490c-13.6-7.8-19.5-37.5-14.9-75.7 1.1-9.4 2.9-19.3 5.1-29.4 19.6 4.8 41 8.5 63.5 10.9 13.5 18.5 27.5 35.3 41.6 50-32.6 30.3-63.2 46.9-84 46.9-4.5-.1-8.3-1-11.3-2.7zm237.2-76.2c4.7 38.2-1.1 67.9-14.6 75.8-3 1.8-6.9 2.6-11.5 2.6-20.7 0-51.4-16.5-84-46.6 14-14.7 28-31.4 41.3-49.9 22.6-2.4 44-6.1 63.6-11 2.3 10.1 4.1 19.8 5.2 29.1zm38.5-66.7c-8.6 3.7-18 7-27.7 10.1-5.7-19.6-13.2-40-22.5-60.9 9.2-20.8 16.6-41.1 22.2-60.6 9.9 3.1 19.3 6.5 28.1 10.2 35.4 15.1 58.3 34.9 58.3 50.6-.1 15.7-23 35.6-58.4 50.6zM320.8 78.4z"/> <circle cx="420.9" cy="296.5" r="45.7"/> <path d="M520.5 78.1z"/> </g> </svg>
lib/cli/test/fixtures/update_package_organisations/src/logo.svg
0
https://github.com/storybookjs/storybook/commit/7c3b15dec6c7cd4e27ebdddeff77e1b949fbe19e
[ 0.002794071100652218, 0.002794071100652218, 0.002794071100652218, 0.002794071100652218, 0 ]
{ "id": 1, "code_window": [ "\n", " if (list) {\n", " this.setState({ list }, () => this.emit(picked));\n", " }\n", " };\n", "\n", " onChange = event => {\n" ], "labels": [ "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " const picked = list.filter(res => res.picked);\n" ], "file_path": "addons/cssresources/src/css-resource-panel.js", "type": "add", "edit_start_line_idx": 40 }
<template> <div id="app"> <img src="./assets/logo.png"> <hello></hello> </div> </template> <script> import Hello from './components/Hello' export default { name: 'app', components: { Hello } } </script> <style> #app { font-family: 'Avenir', Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; margin-top: 60px; } </style>
lib/cli/test/fixtures/sfc_vue/src/App.vue
0
https://github.com/storybookjs/storybook/commit/7c3b15dec6c7cd4e27ebdddeff77e1b949fbe19e
[ 0.00017336914606858045, 0.00017070052854251117, 0.0001663106813794002, 0.00017242171452380717, 0.0000031280856092053 ]
{ "id": 2, "code_window": [ " monoTextFace: monoFonts.fontFamily,\n", " layoutMargin: 10,\n", " overlayBackground:\n", " 'linear-gradient(to bottom right, rgba(17, 17, 34, 0.6), rgba(51, 51, 51, 0.8))',\n", "\n", " // brand: {\n", " // width: '100%',\n", " // height: 40,\n", " // backgroundSize: 'contain',\n", " // backgroundRepeat: 'no-repeat',\n", " // backgroundPosition: '0 0',\n", " // backgroundImage: logo,\n", " // },\n", "\n", " code: darkSyntax,\n", "\n", " addonActionsTheme: {\n", " ...chromeDark,\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " brand: Brand,\n" ], "file_path": "lib/components/src/theme.js", "type": "replace", "edit_start_line_idx": 81 }
import { document } from 'global'; import React, { Component, Fragment } from 'react'; import PropTypes from 'prop-types'; import { SyntaxHighlighter } from '@storybook/components'; import { STORY_CHANGED } from '@storybook/core-events'; import EVENTS, { PARAM_KEY } from './constants'; const storybookIframe = 'storybook-preview-iframe'; export default class CssResourcePanel extends Component { constructor(props) { super(props); this.state = { list: [], }; } componentDidMount() { const { api } = this.props; this.iframe = document.getElementById(storybookIframe); if (!this.iframe) { throw new Error('Cannot find Storybook iframe'); } api.on(STORY_CHANGED, this.onStoryChange); } componentWillUnmount() { const { api } = this.props; api.off(STORY_CHANGED, this.onStoryChange); } onStoryChange = id => { const { api } = this.props; const list = api.getParameters(id, PARAM_KEY); const picked = list.filter(res => res.picked); console.log({ list }); if (list) { this.setState({ list }, () => this.emit(picked)); } }; onChange = event => { const { list: oldList } = this.state; const list = oldList.map(i => ({ ...i, picked: i.id === event.target.id ? event.target.checked : i.picked, })); this.setState({ list }, () => this.emit(list.filter(res => res.picked))); }; emit(list) { const { api } = this.props; api.emit(EVENTS.SET, list); } render() { const { list = [] } = this.state; const { active } = this.props; if (!active) { return null; } return ( <Fragment> {list && list.map(({ id, code, picked }) => ( <div key={id} style={{ padding: 10 }}> <label> <input type="checkbox" checked={picked} onChange={this.onChange} id={id} /> <span>#{id}</span> </label> {code ? <SyntaxHighlighter language="html">{code}</SyntaxHighlighter> : null} </div> ))} </Fragment> ); } } CssResourcePanel.propTypes = { active: PropTypes.bool.isRequired, channel: PropTypes.shape({ on: PropTypes.func, emit: PropTypes.func, removeListener: PropTypes.func, }).isRequired, api: PropTypes.shape({ onStory: PropTypes.func, getQueryParam: PropTypes.func, setQueryParams: PropTypes.func, }).isRequired, };
addons/cssresources/src/css-resource-panel.js
1
https://github.com/storybookjs/storybook/commit/7c3b15dec6c7cd4e27ebdddeff77e1b949fbe19e
[ 0.00017721594485919923, 0.00017359486082568765, 0.00016987661365419626, 0.00017347160610370338, 0.000002392767555647879 ]
{ "id": 2, "code_window": [ " monoTextFace: monoFonts.fontFamily,\n", " layoutMargin: 10,\n", " overlayBackground:\n", " 'linear-gradient(to bottom right, rgba(17, 17, 34, 0.6), rgba(51, 51, 51, 0.8))',\n", "\n", " // brand: {\n", " // width: '100%',\n", " // height: 40,\n", " // backgroundSize: 'contain',\n", " // backgroundRepeat: 'no-repeat',\n", " // backgroundPosition: '0 0',\n", " // backgroundImage: logo,\n", " // },\n", "\n", " code: darkSyntax,\n", "\n", " addonActionsTheme: {\n", " ...chromeDark,\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " brand: Brand,\n" ], "file_path": "lib/components/src/theme.js", "type": "replace", "edit_start_line_idx": 81 }
{ "name": "riot-fixture", "version": "1.0.0", "private": true, "description": "A riot.js project", "author": "hypnos <[email protected]>", "scripts": { "build:js": "cross-env NODE_ENV=production webpack", "dev": "cross-env NODE_ENV=development webpack" }, "dependencies": { "riot": "^3.11.2" }, "devDependencies": { "cross-env": "^5.2.0", "common-tags": "^1.8.0", "global": "^4.3.2", "style-loader": "^0.22.1", "css-loader": "^1.0.1", "raw-loader": "^0.5.1", "riot-hot-reload": "^1.0.0", "riot-compiler": "^3.5.1", "storybook-addon-jsx": "latest", "storybook-readme": "latest", "riot": "latest", "webpack": "latest", "webpack-cli": "latest", "webpack-bundle-analyzer": "latest", "packer-webpack-plugin": "latest", "babel-loader": "latest", "babel-preset-env": "latest", "babel-register": "latest" }, "peerDependencies": { "babel-loader": "^7.0.0 || ^8.0.0" } }
lib/cli/test/fixtures/riot/package.json
0
https://github.com/storybookjs/storybook/commit/7c3b15dec6c7cd4e27ebdddeff77e1b949fbe19e
[ 0.0001759506412781775, 0.00017406861297786236, 0.00017312713316641748, 0.000173598324181512, 0.000001109652771447145 ]
{ "id": 2, "code_window": [ " monoTextFace: monoFonts.fontFamily,\n", " layoutMargin: 10,\n", " overlayBackground:\n", " 'linear-gradient(to bottom right, rgba(17, 17, 34, 0.6), rgba(51, 51, 51, 0.8))',\n", "\n", " // brand: {\n", " // width: '100%',\n", " // height: 40,\n", " // backgroundSize: 'contain',\n", " // backgroundRepeat: 'no-repeat',\n", " // backgroundPosition: '0 0',\n", " // backgroundImage: logo,\n", " // },\n", "\n", " code: darkSyntax,\n", "\n", " addonActionsTheme: {\n", " ...chromeDark,\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " brand: Brand,\n" ], "file_path": "lib/components/src/theme.js", "type": "replace", "edit_start_line_idx": 81 }
{ "presets": [ ["@babel/preset-env", { "targets": { "node": 4 } }] ], "plugins": [ ["@babel/plugin-transform-runtime"] ] }
lib/cli/.babelrc
0
https://github.com/storybookjs/storybook/commit/7c3b15dec6c7cd4e27ebdddeff77e1b949fbe19e
[ 0.00017598872364033014, 0.0001745778281474486, 0.00017316693265456706, 0.0001745778281474486, 0.0000014108954928815365 ]
{ "id": 2, "code_window": [ " monoTextFace: monoFonts.fontFamily,\n", " layoutMargin: 10,\n", " overlayBackground:\n", " 'linear-gradient(to bottom right, rgba(17, 17, 34, 0.6), rgba(51, 51, 51, 0.8))',\n", "\n", " // brand: {\n", " // width: '100%',\n", " // height: 40,\n", " // backgroundSize: 'contain',\n", " // backgroundRepeat: 'no-repeat',\n", " // backgroundPosition: '0 0',\n", " // backgroundImage: logo,\n", " // },\n", "\n", " code: darkSyntax,\n", "\n", " addonActionsTheme: {\n", " ...chromeDark,\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " brand: Brand,\n" ], "file_path": "lib/components/src/theme.js", "type": "replace", "edit_start_line_idx": 81 }
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files. # dependencies /node_modules /.pnp .pnp.js # testing /coverage # production /build # misc .DS_Store .env.local .env.development.local .env.test.local .env.production.local npm-debug.log* yarn-debug.log* yarn-error.log*
lib/cli/test/fixtures/react_scripts_v2/.gitignore
0
https://github.com/storybookjs/storybook/commit/7c3b15dec6c7cd4e27ebdddeff77e1b949fbe19e
[ 0.0001759915758157149, 0.0001744580949889496, 0.00017353420844301581, 0.00017384854436386377, 0.0000010918915904767346 ]
{ "id": 0, "code_window": [ " - \"4\"\n", " - \"5\"\n", "script:\n", " - npm run check\n", "branches:\n", " only:\n", " - master" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " - npm run check:lib\n", " - npm run build\n", " - npm run check:examples\n" ], "file_path": ".travis.yml", "type": "replace", "edit_start_line_idx": 5 }
language: node_js node_js: - "4" - "5" script: - npm run check branches: only: - master
.travis.yml
1
https://github.com/reduxjs/redux/commit/2f11eafb628a908503f499fec2109a24efe96461
[ 0.9842907190322876, 0.9842907190322876, 0.9842907190322876, 0.9842907190322876, 0 ]
{ "id": 0, "code_window": [ " - \"4\"\n", " - \"5\"\n", "script:\n", " - npm run check\n", "branches:\n", " only:\n", " - master" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " - npm run check:lib\n", " - npm run build\n", " - npm run check:examples\n" ], "file_path": ".travis.yml", "type": "replace", "edit_start_line_idx": 5 }
/* eslint-disable no-console, no-use-before-define */ import path from 'path' import Express from 'express' import qs from 'qs' import webpack from 'webpack' import webpackDevMiddleware from 'webpack-dev-middleware' import webpackHotMiddleware from 'webpack-hot-middleware' import webpackConfig from '../webpack.config' import React from 'react' import { renderToString } from 'react-dom/server' import { Provider } from 'react-redux' import configureStore from '../common/store/configureStore' import App from '../common/containers/App' import { fetchCounter } from '../common/api/counter' const app = new Express() const port = 3000 // Use this middleware to set up hot module reloading via webpack. const compiler = webpack(webpackConfig) app.use(webpackDevMiddleware(compiler, { noInfo: true, publicPath: webpackConfig.output.publicPath })) app.use(webpackHotMiddleware(compiler)) // This is fired every time the server side receives a request app.use(handleRender) function handleRender(req, res) { // Query our mock API asynchronously fetchCounter(apiResult => { // Read the counter from the request, if provided const params = qs.parse(req.query) const counter = parseInt(params.counter, 10) || apiResult || 0 // Compile an initial state const initialState = { counter } // Create a new Redux store instance const store = configureStore(initialState) // Render the component to a string const html = renderToString( <Provider store={store}> <App /> </Provider> ) // Grab the initial state from our Redux store const finalState = store.getState() // Send the rendered page back to the client res.send(renderFullPage(html, finalState)) }) } function renderFullPage(html, initialState) { return ` <!doctype html> <html> <head> <title>Redux Universal Example</title> </head> <body> <div id="app">${html}</div> <script> window.__INITIAL_STATE__ = ${JSON.stringify(initialState)} </script> <script src="/static/bundle.js"></script> </body> </html> ` } app.listen(port, (error) => { if (error) { console.error(error) } else { console.info(`==> 🌎 Listening on port ${port}. Open up http://localhost:${port}/ in your browser.`) } })
examples/universal/server/server.js
0
https://github.com/reduxjs/redux/commit/2f11eafb628a908503f499fec2109a24efe96461
[ 0.0007071616128087044, 0.00023549106845166534, 0.00016617261280771345, 0.0001699273125268519, 0.00016772552044130862 ]