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": 6, "code_window": [ "\t\t// colorPickerHeader.domNode.style.width = 600 + 'px';\n", "\t\t// colorPickerHeader.domNode.style.height = 20 + 'px';\n", "\n", "\t\tconst colorPickerBody = colorPicker?.body as ColorPickerBody;\n", "\t\tcolorPickerBody.domNode.style.background = 'red';\n", "\t\tconst saturationBox = colorPickerBody.saturationBox;\n", "\t\tconst hueStrip = colorPickerBody.hueStrip;\n", "\t\tconst opacityStrip = colorPickerBody.opacityStrip;\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/editor/contrib/colorPicker/browser/standaloneColorPickerWidget.ts", "type": "replace", "edit_start_line_idx": 218 }
/*--------------------------------------------------------------------------------------------- * 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 { URI } from 'vs/base/common/uri'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { workbenchInstantiationService, TestServiceAccessor, TestInMemoryFileSystemProvider } from 'vs/workbench/test/browser/workbenchTestServices'; import { StoredFileWorkingCopy, IStoredFileWorkingCopy } from 'vs/workbench/services/workingCopy/common/storedFileWorkingCopy'; import { bufferToStream, VSBuffer } from 'vs/base/common/buffer'; import { TestStoredFileWorkingCopyModel, TestStoredFileWorkingCopyModelFactory } from 'vs/workbench/services/workingCopy/test/browser/storedFileWorkingCopy.test'; import { Schemas } from 'vs/base/common/network'; import { IFileWorkingCopyManager, FileWorkingCopyManager } from 'vs/workbench/services/workingCopy/common/fileWorkingCopyManager'; import { TestUntitledFileWorkingCopyModel, TestUntitledFileWorkingCopyModelFactory } from 'vs/workbench/services/workingCopy/test/browser/untitledFileWorkingCopy.test'; import { UntitledFileWorkingCopy } from 'vs/workbench/services/workingCopy/common/untitledFileWorkingCopy'; import { DisposableStore } from 'vs/base/common/lifecycle'; suite('FileWorkingCopyManager', () => { let disposables: DisposableStore; let instantiationService: IInstantiationService; let accessor: TestServiceAccessor; let manager: IFileWorkingCopyManager<TestStoredFileWorkingCopyModel, TestUntitledFileWorkingCopyModel>; setup(() => { disposables = new DisposableStore(); instantiationService = workbenchInstantiationService(undefined, disposables); accessor = instantiationService.createInstance(TestServiceAccessor); accessor.fileService.registerProvider(Schemas.file, new TestInMemoryFileSystemProvider()); accessor.fileService.registerProvider(Schemas.vscodeRemote, new TestInMemoryFileSystemProvider()); manager = new FileWorkingCopyManager( 'testFileWorkingCopyType', new TestStoredFileWorkingCopyModelFactory(), new TestUntitledFileWorkingCopyModelFactory(), accessor.fileService, accessor.lifecycleService, accessor.labelService, accessor.logService, accessor.workingCopyFileService, accessor.workingCopyBackupService, accessor.uriIdentityService, accessor.fileDialogService, accessor.filesConfigurationService, accessor.workingCopyService, accessor.notificationService, accessor.workingCopyEditorService, accessor.editorService, accessor.elevatedFileService, accessor.pathService, accessor.environmentService, accessor.dialogService, accessor.decorationsService ); }); teardown(() => { manager.dispose(); disposables.dispose(); }); test('onDidCreate, get, workingCopies', async () => { let createCounter = 0; manager.onDidCreate(e => { createCounter++; }); const fileUri = URI.file('/test.html'); assert.strictEqual(manager.workingCopies.length, 0); assert.strictEqual(manager.get(fileUri), undefined); const fileWorkingCopy = await manager.resolve(fileUri); const untitledFileWorkingCopy = await manager.resolve(); assert.strictEqual(manager.workingCopies.length, 2); assert.strictEqual(createCounter, 2); assert.strictEqual(manager.get(fileWorkingCopy.resource), fileWorkingCopy); assert.strictEqual(manager.get(untitledFileWorkingCopy.resource), untitledFileWorkingCopy); const sameFileWorkingCopy = await manager.resolve(fileUri); const sameUntitledFileWorkingCopy = await manager.resolve({ untitledResource: untitledFileWorkingCopy.resource }); assert.strictEqual(sameFileWorkingCopy, fileWorkingCopy); assert.strictEqual(sameUntitledFileWorkingCopy, untitledFileWorkingCopy); assert.strictEqual(manager.workingCopies.length, 2); assert.strictEqual(createCounter, 2); fileWorkingCopy.dispose(); untitledFileWorkingCopy.dispose(); }); test('resolve', async () => { const fileWorkingCopy = await manager.resolve(URI.file('/test.html')); assert.ok(fileWorkingCopy instanceof StoredFileWorkingCopy); assert.strictEqual(await manager.stored.resolve(fileWorkingCopy.resource), fileWorkingCopy); const untitledFileWorkingCopy = await manager.resolve(); assert.ok(untitledFileWorkingCopy instanceof UntitledFileWorkingCopy); assert.strictEqual(await manager.untitled.resolve({ untitledResource: untitledFileWorkingCopy.resource }), untitledFileWorkingCopy); assert.strictEqual(await manager.resolve(untitledFileWorkingCopy.resource), untitledFileWorkingCopy); fileWorkingCopy.dispose(); untitledFileWorkingCopy.dispose(); }); test('destroy', async () => { assert.strictEqual(accessor.workingCopyService.workingCopies.length, 0); await manager.resolve(URI.file('/test.html')); await manager.resolve({ contents: { value: bufferToStream(VSBuffer.fromString('Hello Untitled')) } }); assert.strictEqual(accessor.workingCopyService.workingCopies.length, 2); assert.strictEqual(manager.stored.workingCopies.length, 1); assert.strictEqual(manager.untitled.workingCopies.length, 1); await manager.destroy(); assert.strictEqual(accessor.workingCopyService.workingCopies.length, 0); assert.strictEqual(manager.stored.workingCopies.length, 0); assert.strictEqual(manager.untitled.workingCopies.length, 0); }); test('saveAs - file (same target, unresolved source, unresolved target)', () => { const source = URI.file('/path/source.txt'); return testSaveAsFile(source, source, false, false); }); test('saveAs - file (same target, different case, unresolved source, unresolved target)', async () => { const source = URI.file('/path/source.txt'); const target = URI.file('/path/SOURCE.txt'); return testSaveAsFile(source, target, false, false); }); test('saveAs - file (different target, unresolved source, unresolved target)', async () => { const source = URI.file('/path/source.txt'); const target = URI.file('/path/target.txt'); return testSaveAsFile(source, target, false, false); }); test('saveAs - file (same target, resolved source, unresolved target)', () => { const source = URI.file('/path/source.txt'); return testSaveAsFile(source, source, true, false); }); test('saveAs - file (same target, different case, resolved source, unresolved target)', async () => { const source = URI.file('/path/source.txt'); const target = URI.file('/path/SOURCE.txt'); return testSaveAsFile(source, target, true, false); }); test('saveAs - file (different target, resolved source, unresolved target)', async () => { const source = URI.file('/path/source.txt'); const target = URI.file('/path/target.txt'); return testSaveAsFile(source, target, true, false); }); test('saveAs - file (same target, unresolved source, resolved target)', () => { const source = URI.file('/path/source.txt'); return testSaveAsFile(source, source, false, true); }); test('saveAs - file (same target, different case, unresolved source, resolved target)', async () => { const source = URI.file('/path/source.txt'); const target = URI.file('/path/SOURCE.txt'); return testSaveAsFile(source, target, false, true); }); test('saveAs - file (different target, unresolved source, resolved target)', async () => { const source = URI.file('/path/source.txt'); const target = URI.file('/path/target.txt'); return testSaveAsFile(source, target, false, true); }); test('saveAs - file (same target, resolved source, resolved target)', () => { const source = URI.file('/path/source.txt'); return testSaveAsFile(source, source, true, true); }); test('saveAs - file (different target, resolved source, resolved target)', async () => { const source = URI.file('/path/source.txt'); const target = URI.file('/path/target.txt'); return testSaveAsFile(source, target, true, true); }); async function testSaveAsFile(source: URI, target: URI, resolveSource: boolean, resolveTarget: boolean) { let sourceWorkingCopy: IStoredFileWorkingCopy<TestStoredFileWorkingCopyModel> | undefined = undefined; if (resolveSource) { sourceWorkingCopy = await manager.resolve(source); sourceWorkingCopy.model?.updateContents('hello world'); assert.ok(sourceWorkingCopy.isDirty()); } let targetWorkingCopy: IStoredFileWorkingCopy<TestStoredFileWorkingCopyModel> | undefined = undefined; if (resolveTarget) { targetWorkingCopy = await manager.resolve(target); targetWorkingCopy.model?.updateContents('hello world'); assert.ok(targetWorkingCopy.isDirty()); } const result = await manager.saveAs(source, target); if (accessor.uriIdentityService.extUri.isEqual(source, target) && resolveSource) { // if the uris are considered equal (different case on macOS/Windows) // and the source is to be resolved, the resulting working copy resource // will be the source resource because we consider file working copies // the same in that case assert.strictEqual(source.toString(), result?.resource.toString()); } else { if (resolveSource || resolveTarget) { assert.strictEqual(target.toString(), result?.resource.toString()); } else { if (accessor.uriIdentityService.extUri.isEqual(source, target)) { assert.strictEqual(undefined, result); } else { assert.strictEqual(target.toString(), result?.resource.toString()); } } } if (resolveSource) { assert.strictEqual(sourceWorkingCopy?.isDirty(), false); } if (resolveTarget) { assert.strictEqual(targetWorkingCopy?.isDirty(), false); } } test('saveAs - untitled (without associated resource)', async () => { const workingCopy = await manager.resolve(); workingCopy.model?.updateContents('Simple Save As'); const target = URI.file('simple/file.txt'); accessor.fileDialogService.setPickFileToSave(target); const result = await manager.saveAs(workingCopy.resource, undefined); assert.strictEqual(result?.resource.toString(), target.toString()); assert.strictEqual((result?.model as TestStoredFileWorkingCopyModel).contents, 'Simple Save As'); assert.strictEqual(manager.untitled.get(workingCopy.resource), undefined); workingCopy.dispose(); }); test('saveAs - untitled (with associated resource)', async () => { const workingCopy = await manager.resolve({ associatedResource: { path: '/some/associated.txt' } }); workingCopy.model?.updateContents('Simple Save As with associated resource'); const target = URI.from({ scheme: Schemas.file, path: '/some/associated.txt' }); accessor.fileService.notExistsSet.set(target, true); const result = await manager.saveAs(workingCopy.resource, undefined); assert.strictEqual(result?.resource.toString(), target.toString()); assert.strictEqual((result?.model as TestStoredFileWorkingCopyModel).contents, 'Simple Save As with associated resource'); assert.strictEqual(manager.untitled.get(workingCopy.resource), undefined); workingCopy.dispose(); }); test('saveAs - untitled (target exists and is resolved)', async () => { const workingCopy = await manager.resolve(); workingCopy.model?.updateContents('Simple Save As'); const target = URI.file('simple/file.txt'); const targetFileWorkingCopy = await manager.resolve(target); accessor.fileDialogService.setPickFileToSave(target); const result = await manager.saveAs(workingCopy.resource, undefined); assert.strictEqual(result, targetFileWorkingCopy); assert.strictEqual((result?.model as TestStoredFileWorkingCopyModel).contents, 'Simple Save As'); assert.strictEqual(manager.untitled.get(workingCopy.resource), undefined); workingCopy.dispose(); }); });
src/vs/workbench/services/workingCopy/test/browser/fileWorkingCopyManager.test.ts
0
https://github.com/microsoft/vscode/commit/804da42af2a734debcbf4136fba989581bbab9f6
[ 0.00017686415230855346, 0.00017488034791313112, 0.0001726225600577891, 0.00017530891636852175, 0.0000011130427992611658 ]
{ "id": 6, "code_window": [ "\t\t// colorPickerHeader.domNode.style.width = 600 + 'px';\n", "\t\t// colorPickerHeader.domNode.style.height = 20 + 'px';\n", "\n", "\t\tconst colorPickerBody = colorPicker?.body as ColorPickerBody;\n", "\t\tcolorPickerBody.domNode.style.background = 'red';\n", "\t\tconst saturationBox = colorPickerBody.saturationBox;\n", "\t\tconst hueStrip = colorPickerBody.hueStrip;\n", "\t\tconst opacityStrip = colorPickerBody.opacityStrip;\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/editor/contrib/colorPicker/browser/standaloneColorPickerWidget.ts", "type": "replace", "edit_start_line_idx": 218 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { IAccessibilityService, AccessibilitySupport } from 'vs/platform/accessibility/common/accessibility'; import { isWindows, isLinux } from 'vs/base/common/platform'; import { INativeWorkbenchEnvironmentService } from 'vs/workbench/services/environment/electron-sandbox/environmentService'; import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { Registry } from 'vs/platform/registry/common/platform'; import { AccessibilityService } from 'vs/platform/accessibility/browser/accessibilityService'; import { InstantiationType, registerSingleton } from 'vs/platform/instantiation/common/extensions'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IJSONEditingService } from 'vs/workbench/services/configuration/common/jsonEditing'; import { IWorkbenchContribution, IWorkbenchContributionsRegistry, Extensions as WorkbenchExtensions } from 'vs/workbench/common/contributions'; import { LifecyclePhase } from 'vs/workbench/services/lifecycle/common/lifecycle'; import { INativeHostService } from 'vs/platform/native/common/native'; import { ILayoutService } from 'vs/platform/layout/browser/layoutService'; interface AccessibilityMetrics { enabled: boolean; } type AccessibilityMetricsClassification = { owner: 'isidorn'; comment: 'Helps gain an understanding of when accessibility features are being used'; enabled: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'Whether or not accessibility features are enabled' }; }; export class NativeAccessibilityService extends AccessibilityService implements IAccessibilityService { private didSendTelemetry = false; private shouldAlwaysUnderlineAccessKeys: boolean | undefined = undefined; constructor( @INativeWorkbenchEnvironmentService environmentService: INativeWorkbenchEnvironmentService, @IContextKeyService contextKeyService: IContextKeyService, @IConfigurationService configurationService: IConfigurationService, @ILayoutService _layoutService: ILayoutService, @ITelemetryService private readonly _telemetryService: ITelemetryService, @INativeHostService private readonly nativeHostService: INativeHostService ) { super(contextKeyService, _layoutService, configurationService); this.setAccessibilitySupport(environmentService.window.accessibilitySupport ? AccessibilitySupport.Enabled : AccessibilitySupport.Disabled); } override async alwaysUnderlineAccessKeys(): Promise<boolean> { if (!isWindows) { return false; } if (typeof this.shouldAlwaysUnderlineAccessKeys !== 'boolean') { const windowsKeyboardAccessibility = await this.nativeHostService.windowsGetStringRegKey('HKEY_CURRENT_USER', 'Control Panel\\Accessibility\\Keyboard Preference', 'On'); this.shouldAlwaysUnderlineAccessKeys = (windowsKeyboardAccessibility === '1'); } return this.shouldAlwaysUnderlineAccessKeys; } override setAccessibilitySupport(accessibilitySupport: AccessibilitySupport): void { super.setAccessibilitySupport(accessibilitySupport); if (!this.didSendTelemetry && accessibilitySupport === AccessibilitySupport.Enabled) { this._telemetryService.publicLog2<AccessibilityMetrics, AccessibilityMetricsClassification>('accessibility', { enabled: true }); this.didSendTelemetry = true; } } } registerSingleton(IAccessibilityService, NativeAccessibilityService, InstantiationType.Delayed); // On linux we do not automatically detect that a screen reader is detected, thus we have to implicitly notify the renderer to enable accessibility when user configures it in settings class LinuxAccessibilityContribution implements IWorkbenchContribution { constructor( @IJSONEditingService jsonEditingService: IJSONEditingService, @IAccessibilityService accessibilityService: IAccessibilityService, @INativeWorkbenchEnvironmentService environmentService: INativeWorkbenchEnvironmentService ) { const forceRendererAccessibility = () => { if (accessibilityService.isScreenReaderOptimized()) { jsonEditingService.write(environmentService.argvResource, [{ path: ['force-renderer-accessibility'], value: true }], true); } }; forceRendererAccessibility(); accessibilityService.onDidChangeScreenReaderOptimized(forceRendererAccessibility); } } if (isLinux) { Registry.as<IWorkbenchContributionsRegistry>(WorkbenchExtensions.Workbench).registerWorkbenchContribution(LinuxAccessibilityContribution, LifecyclePhase.Ready); }
src/vs/workbench/services/accessibility/electron-sandbox/accessibilityService.ts
0
https://github.com/microsoft/vscode/commit/804da42af2a734debcbf4136fba989581bbab9f6
[ 0.00017743509670253843, 0.00017252839461434633, 0.00016664307622704655, 0.00017201260197907686, 0.000002884179366446915 ]
{ "id": 0, "code_window": [ "\t\t\t}\n", "\t\t});\n", "\t}\n", "}\n", "\n", "export class Breakpoint implements debug.IBreakpoint {\n", "\n", "\tpublic lineNumber: number;\n", "\tpublic verified: boolean;\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "// TODO@Isidor breakpoint should not have a pointer to source. Source should live inside a stack frame\n" ], "file_path": "src/vs/workbench/parts/debug/common/debugModel.ts", "type": "add", "edit_start_line_idx": 561 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import nls = require('vs/nls'); import lifecycle = require('vs/base/common/lifecycle'); import { guessMimeTypes } from 'vs/base/common/mime'; import Event, { Emitter } from 'vs/base/common/event'; import * as strings from 'vs/base/common/strings'; import uuid = require('vs/base/common/uuid'); import uri from 'vs/base/common/uri'; import { Action } from 'vs/base/common/actions'; import arrays = require('vs/base/common/arrays'); import types = require('vs/base/common/types'); import errors = require('vs/base/common/errors'); import severity from 'vs/base/common/severity'; import { TPromise } from 'vs/base/common/winjs.base'; import aria = require('vs/base/browser/ui/aria/aria'); import { Client as TelemetryClient } from 'vs/base/parts/ipc/node/ipc.cp'; import editorbrowser = require('vs/editor/browser/editorBrowser'); 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/platform/extensions/common/extensions'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IFileService, FileChangesEvent, FileChangeType, EventType } from 'vs/platform/files/common/files'; import { IEventService } from 'vs/platform/event/common/event'; import { IMessageService, CloseAction } from 'vs/platform/message/common/message'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { TelemetryService } from 'vs/platform/telemetry/common/telemetryService'; import { TelemetryAppenderClient } from 'vs/platform/telemetry/common/telemetryIpc'; import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage'; import { IEditorGroupService } from 'vs/workbench/services/group/common/groupService'; import { asFileEditorInput } from 'vs/workbench/common/editor'; import debug = require('vs/workbench/parts/debug/common/debug'); import { RawDebugSession } from 'vs/workbench/parts/debug/electron-browser/rawDebugSession'; import model = require('vs/workbench/parts/debug/common/debugModel'); import { DebugStringEditorInput, DebugErrorEditorInput } from 'vs/workbench/parts/debug/browser/debugEditorInputs'; import viewmodel = require('vs/workbench/parts/debug/common/debugViewModel'); import debugactions = require('vs/workbench/parts/debug/browser/debugActions'); import { ConfigurationManager } from 'vs/workbench/parts/debug/node/debugConfigurationManager'; import { Source } from 'vs/workbench/parts/debug/common/debugSource'; import { ITaskService, TaskEvent, TaskType, TaskServiceEvents, ITaskSummary } from 'vs/workbench/parts/tasks/common/taskService'; import { TaskError, TaskErrors } from 'vs/workbench/parts/tasks/common/taskSystem'; import { VIEWLET_ID as EXPLORER_VIEWLET_ID } from 'vs/workbench/parts/files/common/files'; import { IViewletService } from 'vs/workbench/services/viewlet/common/viewletService'; import { IPanelService } from 'vs/workbench/services/panel/common/panelService'; import { IPartService } from 'vs/workbench/services/part/common/partService'; import { ITextFileService } from 'vs/workbench/services/textfile/common/textfiles'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace'; import { IWorkbenchEditorService } from 'vs/workbench/services/editor/common/editorService'; import { IWindowService, IBroadcast } from 'vs/workbench/services/window/electron-browser/windowService'; import { ILogEntry, EXTENSION_LOG_BROADCAST_CHANNEL, EXTENSION_ATTACH_BROADCAST_CHANNEL, EXTENSION_TERMINATE_BROADCAST_CHANNEL } from 'vs/workbench/services/extensions/electron-browser/extensionHost'; import { ipcRenderer as ipc } from 'electron'; const DEBUG_BREAKPOINTS_KEY = 'debug.breakpoint'; const DEBUG_BREAKPOINTS_ACTIVATED_KEY = 'debug.breakpointactivated'; const DEBUG_FUNCTION_BREAKPOINTS_KEY = 'debug.functionbreakpoint'; const DEBUG_EXCEPTION_BREAKPOINTS_KEY = 'debug.exceptionbreakpoint'; const DEBUG_WATCH_EXPRESSIONS_KEY = 'debug.watchexpressions'; const DEBUG_SELECTED_CONFIG_NAME_KEY = 'debug.selectedconfigname'; export class DebugService implements debug.IDebugService { public _serviceBrand: any; private sessionStates: { [id: string]: debug.State }; private _onDidChangeState: Emitter<void>; private model: model.Model; private viewModel: viewmodel.ViewModel; private configurationManager: ConfigurationManager; private customTelemetryService: ITelemetryService; private lastTaskEvent: TaskEvent; private toDispose: lifecycle.IDisposable[]; private toDisposeOnSessionEnd: { [id: string]: lifecycle.IDisposable[] }; private inDebugMode: IContextKey<boolean>; private breakpointsToSendOnResourceSaved: { [uri: string]: boolean }; constructor( @IStorageService private storageService: IStorageService, @IWorkbenchEditorService private editorService: IWorkbenchEditorService, @ITextFileService private textFileService: ITextFileService, @IViewletService private viewletService: IViewletService, @IPanelService private panelService: IPanelService, @IFileService private fileService: IFileService, @IMessageService private messageService: IMessageService, @IPartService private partService: IPartService, @IWindowService private windowService: IWindowService, @ITelemetryService private telemetryService: ITelemetryService, @IWorkspaceContextService private contextService: IWorkspaceContextService, @IContextKeyService contextKeyService: IContextKeyService, @IEditorGroupService private editorGroupService: IEditorGroupService, @IEventService eventService: IEventService, @ILifecycleService lifecycleService: ILifecycleService, @IInstantiationService private instantiationService: IInstantiationService, @IExtensionService private extensionService: IExtensionService, @IMarkerService private markerService: IMarkerService, @ITaskService private taskService: ITaskService, @IConfigurationService private configurationService: IConfigurationService ) { this.toDispose = []; this.toDisposeOnSessionEnd = {}; this.breakpointsToSendOnResourceSaved = {}; this._onDidChangeState = new Emitter<void>(); this.sessionStates = {}; this.configurationManager = this.instantiationService.createInstance(ConfigurationManager); this.inDebugMode = debug.CONTEXT_IN_DEBUG_MODE.bindTo(contextKeyService); this.model = new model.Model(this.loadBreakpoints(), this.storageService.getBoolean(DEBUG_BREAKPOINTS_ACTIVATED_KEY, StorageScope.WORKSPACE, true), this.loadFunctionBreakpoints(), this.loadExceptionBreakpoints(), this.loadWatchExpressions()); this.toDispose.push(this.model); this.viewModel = new viewmodel.ViewModel(this.storageService.get(DEBUG_SELECTED_CONFIG_NAME_KEY, StorageScope.WORKSPACE, null)); this.registerListeners(eventService, lifecycleService); } private registerListeners(eventService: IEventService, lifecycleService: ILifecycleService): void { this.toDispose.push(eventService.addListener2(EventType.FILE_CHANGES, (e: FileChangesEvent) => this.onFileChanges(e))); if (this.taskService) { this.toDispose.push(this.taskService.addListener2(TaskServiceEvents.Active, (e: TaskEvent) => { this.lastTaskEvent = e; })); this.toDispose.push(this.taskService.addListener2(TaskServiceEvents.Inactive, (e: TaskEvent) => { if (e.type === TaskType.SingleRun) { this.lastTaskEvent = null; } })); this.toDispose.push(this.taskService.addListener2(TaskServiceEvents.Terminated, (e: TaskEvent) => { this.lastTaskEvent = null; })); } lifecycleService.onShutdown(this.store, this); lifecycleService.onShutdown(this.dispose, this); this.toDispose.push(this.windowService.onBroadcast(this.onBroadcast, this)); } private onBroadcast(broadcast: IBroadcast): void { // attach: PH is ready to be attached to // TODO@Isidor this is a hack to just get any 'extensionHost' session. // Optimally the broadcast would contain the id of the session // We are only intersted if we have an active debug session for extensionHost const session = <RawDebugSession>this.model.getProcesses().map(p => p.session).filter(s => s.configuration.type === 'extensionHost').pop(); if (broadcast.channel === EXTENSION_ATTACH_BROADCAST_CHANNEL) { this.rawAttach(session, broadcast.payload.port); return; } if (broadcast.channel === EXTENSION_TERMINATE_BROADCAST_CHANNEL) { this.onSessionEnd(session); return; } // from this point on we require an active session if (!session) { return; } // a plugin logged output, show it inside the REPL if (broadcast.channel === EXTENSION_LOG_BROADCAST_CHANNEL) { let extensionOutput: ILogEntry = broadcast.payload; let sev = extensionOutput.severity === 'warn' ? severity.Warning : extensionOutput.severity === 'error' ? severity.Error : severity.Info; let args: any[] = []; try { let parsed = JSON.parse(extensionOutput.arguments); args.push(...Object.getOwnPropertyNames(parsed).map(o => parsed[o])); } catch (error) { args.push(extensionOutput.arguments); } // add output for each argument logged let simpleVals: any[] = []; for (let i = 0; i < args.length; i++) { let a = args[i]; // undefined gets printed as 'undefined' if (typeof a === 'undefined') { simpleVals.push('undefined'); } // null gets printed as 'null' else if (a === null) { simpleVals.push('null'); } // objects & arrays are special because we want to inspect them in the REPL else if (types.isObject(a) || Array.isArray(a)) { // flush any existing simple values logged if (simpleVals.length) { this.logToRepl(simpleVals.join(' '), sev); simpleVals = []; } // show object this.logToRepl(a, sev); } // string: watch out for % replacement directive // string substitution and formatting @ https://developer.chrome.com/devtools/docs/console else if (typeof a === 'string') { let buf = ''; for (let j = 0, len = a.length; j < len; j++) { if (a[j] === '%' && (a[j + 1] === 's' || a[j + 1] === 'i' || a[j + 1] === 'd')) { i++; // read over substitution buf += !types.isUndefinedOrNull(args[i]) ? args[i] : ''; // replace j++; // read over directive } else { buf += a[j]; } } simpleVals.push(buf); } // number or boolean is joined together else { simpleVals.push(a); } } // flush simple values if (simpleVals.length) { this.logToRepl(simpleVals.join(' '), sev); } } } private registerSessionListeners(session: RawDebugSession): void { this.toDisposeOnSessionEnd[session.getId()].push(session); this.toDisposeOnSessionEnd[session.getId()].push(session.onDidInitialize(event => { aria.status(nls.localize('debuggingStarted', "Debugging started.")); const sendConfigurationDone = () => { if (session && session.configuration.capabilities.supportsConfigurationDoneRequest) { session.configurationDone().done(null, e => { // Disconnect the debug session on configuration done error #10596 if (session) { session.disconnect().done(null, errors.onUnexpectedError); } this.messageService.show(severity.Error, e.message); }); } }; this.sendAllBreakpoints(session).done(sendConfigurationDone, sendConfigurationDone); })); this.toDisposeOnSessionEnd[session.getId()].push(session.onDidStop(event => { this.setStateAndEmit(session.getId(), debug.State.Stopped); const threadId = event.body.threadId; session.threads().then(response => { if (!response || !response.body || !response.body.threads) { return; } const rawThread = response.body.threads.filter(t => t.id === threadId).pop(); this.model.rawUpdate({ sessionId: session.getId(), thread: rawThread, threadId, stoppedDetails: event.body, allThreadsStopped: event.body.allThreadsStopped }); const process = this.model.getProcesses().filter(p => p.getId() === session.getId()).pop(); const thread = process && process.getThread(threadId); if (thread) { thread.getCallStack().then(callStack => { if (callStack.length > 0) { // focus first stack frame from top that has source location const stackFrameToFocus = arrays.first(callStack, sf => sf.source && sf.source.available, callStack[0]); this.setFocusedStackFrameAndEvaluate(stackFrameToFocus).done(null, errors.onUnexpectedError); this.windowService.getWindow().focus(); aria.alert(nls.localize('debuggingPaused', "Debugging paused, reason {0}, {1} {2}", event.body.reason, stackFrameToFocus.source ? stackFrameToFocus.source.name : '', stackFrameToFocus.lineNumber)); return this.openOrRevealSource(stackFrameToFocus.source, stackFrameToFocus.lineNumber, false, false); } else { this.setFocusedStackFrameAndEvaluate(null).done(null, errors.onUnexpectedError); } }); } }, errors.onUnexpectedError); })); this.toDisposeOnSessionEnd[session.getId()].push(session.onDidThread(event => { if (event.body.reason === 'started') { session.threads().done(response => { if (response && response.body && response.body.threads) { response.body.threads.forEach(thread => this.model.rawUpdate({ sessionId: session.getId(), threadId: thread.id, thread })); } }, errors.onUnexpectedError); } else if (event.body.reason === 'exited') { this.model.clearThreads(session.getId(), true, event.body.threadId); } })); this.toDisposeOnSessionEnd[session.getId()].push(session.onDidTerminateDebugee(event => { aria.status(nls.localize('debuggingStopped', "Debugging stopped.")); if (session && session.getId() === event.body.sessionId) { if (event.body && typeof event.body.restart === 'boolean' && event.body.restart) { const process = this.model.getProcesses().filter(p => p.getId() === session.getId()).pop(); this.restartProcess(process).done(null, err => this.messageService.show(severity.Error, err.message)); } else { session.disconnect().done(null, errors.onUnexpectedError); } } })); this.toDisposeOnSessionEnd[session.getId()].push(session.onDidContinued(event => { this.transitionToRunningState(session, event.body.allThreadsContinued ? undefined : event.body.threadId); })); this.toDisposeOnSessionEnd[session.getId()].push(session.onDidOutput(event => { if (event.body && event.body.category === 'telemetry') { // only log telemetry events from debug adapter if the adapter provided the telemetry key // and the user opted in telemetry if (this.customTelemetryService && this.telemetryService.isOptedIn) { this.customTelemetryService.publicLog(event.body.output, event.body.data); } } else if (event.body && typeof event.body.output === 'string' && event.body.output.length > 0) { this.onOutput(event); } })); this.toDisposeOnSessionEnd[session.getId()].push(session.onDidBreakpoint(event => { const id = event.body && event.body.breakpoint ? event.body.breakpoint.id : undefined; const breakpoint = this.model.getBreakpoints().filter(bp => bp.idFromAdapter === id).pop(); if (breakpoint) { this.model.updateBreakpoints({ [breakpoint.getId()]: event.body.breakpoint }); } else { const functionBreakpoint = this.model.getFunctionBreakpoints().filter(bp => bp.idFromAdapter === id).pop(); if (functionBreakpoint) { this.model.updateFunctionBreakpoints({ [functionBreakpoint.getId()]: event.body.breakpoint }); } } })); this.toDisposeOnSessionEnd[session.getId()].push(session.onDidExitAdapter(event => { // 'Run without debugging' mode VSCode must terminate the extension host. More details: #3905 if (session && session.configuration.type === 'extensionHost' && this.sessionStates[session.getId()] === debug.State.RunningNoDebug) { ipc.send('vscode:closeExtensionHostWindow', this.contextService.getWorkspace().resource.fsPath); } if (session && session.getId() === event.body.sessionId) { this.onSessionEnd(session); } })); } private onOutput(event: DebugProtocol.OutputEvent): void { const outputSeverity = event.body.category === 'stderr' ? severity.Error : event.body.category === 'console' ? severity.Warning : severity.Info; this.appendReplOutput(event.body.output, outputSeverity); } private loadBreakpoints(): debug.IBreakpoint[] { let result: debug.IBreakpoint[]; try { result = JSON.parse(this.storageService.get(DEBUG_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((breakpoint: any) => { return new model.Breakpoint(new Source(breakpoint.source.raw ? breakpoint.source.raw : { path: uri.parse(breakpoint.source.uri).fsPath, name: breakpoint.source.name }), breakpoint.desiredLineNumber || breakpoint.lineNumber, breakpoint.enabled, breakpoint.condition, breakpoint.hitCondition); }); } catch (e) { } return result || []; } private loadFunctionBreakpoints(): debug.IFunctionBreakpoint[] { let result: debug.IFunctionBreakpoint[]; try { result = JSON.parse(this.storageService.get(DEBUG_FUNCTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((fb: any) => { return new model.FunctionBreakpoint(fb.name, fb.enabled, fb.hitCondition); }); } catch (e) { } return result || []; } private loadExceptionBreakpoints(): debug.IExceptionBreakpoint[] { let result: debug.IExceptionBreakpoint[]; try { result = JSON.parse(this.storageService.get(DEBUG_EXCEPTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((exBreakpoint: any) => { return new model.ExceptionBreakpoint(exBreakpoint.filter || exBreakpoint.name, exBreakpoint.label, exBreakpoint.enabled); }); } catch (e) { } return result || []; } private loadWatchExpressions(): model.Expression[] { let result: model.Expression[]; try { result = JSON.parse(this.storageService.get(DEBUG_WATCH_EXPRESSIONS_KEY, StorageScope.WORKSPACE, '[]')).map((watchStoredData: { name: string, id: string }) => { return new model.Expression(watchStoredData.name, false, watchStoredData.id); }); } catch (e) { } return result || []; } public get state(): debug.State { if (!this.contextService.getWorkspace()) { return debug.State.Disabled; } const focusedProcess = this.viewModel.focusedProcess; if (focusedProcess) { return this.sessionStates[focusedProcess.getId()]; } const processes = this.model.getProcesses(); if (processes.length > 0) { return this.sessionStates[processes[0].getId()]; } return debug.State.Inactive; } public get onDidChangeState(): Event<void> { return this._onDidChangeState.event; } private setStateAndEmit(sessionId: string, newState: debug.State): void { this.sessionStates[sessionId] = newState; this._onDidChangeState.fire(); } public get enabled(): boolean { return !!this.contextService.getWorkspace(); } public setFocusedStackFrameAndEvaluate(focusedStackFrame: debug.IStackFrame): TPromise<void> { const processes = this.model.getProcesses(); const process = focusedStackFrame ? focusedStackFrame.thread.process : processes.length ? processes[0] : null; if (process && !focusedStackFrame) { const thread = process.getAllThreads().pop(); const callStack = thread ? thread.getCachedCallStack() : null; focusedStackFrame = callStack && callStack.length ? callStack[0] : null; } this.viewModel.setFocusedStackFrame(focusedStackFrame, process); this._onDidChangeState.fire(); if (focusedStackFrame) { return this.model.evaluateWatchExpressions(focusedStackFrame); } else { this.model.clearWatchExpressionValues(); return TPromise.as(null); } } public enableOrDisableBreakpoints(enable: boolean, breakpoint?: debug.IEnablement): TPromise<void> { if (breakpoint) { this.model.setEnablement(breakpoint, enable); if (breakpoint instanceof model.Breakpoint) { return this.sendBreakpoints((<model.Breakpoint>breakpoint).source.uri); } else if (breakpoint instanceof model.FunctionBreakpoint) { return this.sendFunctionBreakpoints(); } return this.sendExceptionBreakpoints(); } this.model.enableOrDisableAllBreakpoints(enable); return this.sendAllBreakpoints(); } public addBreakpoints(rawBreakpoints: debug.IRawBreakpoint[]): TPromise<void> { this.model.addBreakpoints(rawBreakpoints); const uris = arrays.distinct(rawBreakpoints, raw => raw.uri.toString()).map(raw => raw.uri); rawBreakpoints.forEach(rbp => aria.status(nls.localize('breakpointAdded', "Added breakpoint, line {0}, file {1}", rbp.lineNumber, rbp.uri.fsPath))); return TPromise.join(uris.map(uri => this.sendBreakpoints(uri))).then(() => void 0); } public removeBreakpoints(id?: string): TPromise<any> { 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.source.uri.fsPath))); const urisToClear = arrays.distinct(toRemove, bp => bp.source.uri.toString()).map(bp => bp.source.uri); this.model.removeBreakpoints(toRemove); return TPromise.join(urisToClear.map(uri => this.sendBreakpoints(uri))); } public setBreakpointsActivated(activated: boolean): TPromise<void> { this.model.setBreakpointsActivated(activated); return this.sendAllBreakpoints(); } public addFunctionBreakpoint(): void { this.model.addFunctionBreakpoint(''); } public renameFunctionBreakpoint(id: string, newFunctionName: string): TPromise<void> { this.model.updateFunctionBreakpoints({ [id]: { name: newFunctionName } }); return this.sendFunctionBreakpoints(); } public removeFunctionBreakpoints(id?: string): TPromise<void> { this.model.removeFunctionBreakpoints(id); return this.sendFunctionBreakpoints(); } public addReplExpression(name: string): TPromise<void> { this.telemetryService.publicLog('debugService/addReplExpression'); return this.model.addReplExpression(this.viewModel.focusedStackFrame, name) // Evaluate all watch expressions again since repl evaluation might have changed some. .then(() => this.setFocusedStackFrameAndEvaluate(this.viewModel.focusedStackFrame)); } public logToRepl(value: string | { [key: string]: any }, severity?: severity): void { this.model.logToRepl(value, severity); } public appendReplOutput(value: string, severity?: severity): void { this.model.appendReplOutput(value, severity); } public removeReplExpressions(): void { this.model.removeReplExpressions(); } public addWatchExpression(name: string): TPromise<void> { return this.model.addWatchExpression(this.viewModel.focusedStackFrame, name); } public renameWatchExpression(id: string, newName: string): TPromise<void> { return this.model.renameWatchExpression(this.viewModel.focusedStackFrame, id, newName); } public removeWatchExpressions(id?: string): void { this.model.removeWatchExpressions(id); } public createProcess(configurationOrName: debug.IConfig | string): TPromise<any> { this.removeReplExpressions(); const sessionId = uuid.generateUuid(); this.setStateAndEmit(sessionId, debug.State.Initializing); return this.textFileService.saveAll() // make sure all dirty files are saved .then(() => this.configurationService.reloadConfiguration() // make sure configuration is up to date .then(() => this.extensionService.onReady() .then(() => this.configurationManager.getConfiguration(configurationOrName) .then(configuration => { if (!configuration) { return this.configurationManager.openConfigFile(false).then(openend => { if (openend) { this.messageService.show(severity.Info, nls.localize('NewLaunchConfig', "Please set up the launch configuration file for your application.")); } }); } if (configuration.silentlyAbort) { return; } if (strings.equalsIgnoreCase(configuration.type, 'composite') && configuration.configurationNames) { return TPromise.join(configuration.configurationNames.map(name => this.createProcess(name))); } if (!this.configurationManager.getAdapter(configuration.type)) { return configuration.type ? TPromise.wrapError(new Error(nls.localize('debugTypeNotSupported', "Configured debug type '{0}' is not supported.", configuration.type))) : TPromise.wrapError(errors.create(nls.localize('debugTypeMissing', "Missing property 'type' for the chosen launch configuration."), { actions: [this.instantiationService.createInstance(debugactions.ConfigureAction, debugactions.ConfigureAction.ID, debugactions.ConfigureAction.LABEL), CloseAction] })); } return this.runPreLaunchTask(configuration.preLaunchTask).then((taskSummary: ITaskSummary) => { const errorCount = configuration.preLaunchTask ? this.markerService.getStatistics().errors : 0; const successExitCode = taskSummary && taskSummary.exitCode === 0; const failureExitCode = taskSummary && taskSummary.exitCode !== undefined && taskSummary.exitCode !== 0; if (successExitCode || (errorCount === 0 && !failureExitCode)) { return this.doCreateProcess(sessionId, configuration); } this.messageService.show(severity.Error, { message: errorCount > 1 ? nls.localize('preLaunchTaskErrors', "Build errors have been detected during preLaunchTask '{0}'.", configuration.preLaunchTask) : errorCount === 1 ? nls.localize('preLaunchTaskError', "Build error has been detected during preLaunchTask '{0}'.", configuration.preLaunchTask) : nls.localize('preLaunchTaskExitCode', "The preLaunchTask '{0}' terminated with exit code {1}.", configuration.preLaunchTask, taskSummary.exitCode), actions: [new Action('debug.continue', nls.localize('debugAnyway', "Debug Anyway"), null, true, () => { this.messageService.hideAll(); return this.doCreateProcess(sessionId, configuration); }), CloseAction] }); }, (err: TaskError) => { if (err.code !== TaskErrors.NotConfigured) { throw err; } this.messageService.show(err.severity, { message: err.message, actions: [this.taskService.configureAction(), CloseAction] }); }); })))); } private doCreateProcess(sessionId: string, configuration: debug.IExtHostConfig): TPromise<any> { return this.telemetryService.getTelemetryInfo().then(info => { const telemetryInfo: { [key: string]: string } = Object.create(null); telemetryInfo['common.vscodemachineid'] = info.machineId; telemetryInfo['common.vscodesessionid'] = info.sessionId; return telemetryInfo; }).then(data => { const adapter = this.configurationManager.getAdapter(configuration.type); const { aiKey, type } = adapter; const publisher = adapter.extensionDescription.publisher; this.customTelemetryService = null; let client: TelemetryClient; if (aiKey) { client = new TelemetryClient( uri.parse(require.toUrl('bootstrap')).fsPath, { serverName: 'Debug Telemetry', timeout: 1000 * 60 * 5, args: [`${publisher}.${type}`, JSON.stringify(data), aiKey], env: { ELECTRON_RUN_AS_NODE: 1, PIPE_LOGGING: 'true', AMD_ENTRYPOINT: 'vs/workbench/parts/debug/node/telemetryApp' } } ); const channel = client.getChannel('telemetryAppender'); const appender = new TelemetryAppenderClient(channel); this.customTelemetryService = new TelemetryService({ appender }, this.configurationService); } const session = this.instantiationService.createInstance(RawDebugSession, sessionId, configuration.debugServer, adapter, this.customTelemetryService); this.model.addProcess(configuration.name, session); this.toDisposeOnSessionEnd[session.getId()] = []; if (client) { this.toDisposeOnSessionEnd[session.getId()].push(client); } this.registerSessionListeners(session); return session.initialize({ adapterID: configuration.type, pathFormat: 'path', linesStartAt1: true, columnsStartAt1: true, supportsVariableType: true, // #8858 supportsVariablePaging: true, // #9537 supportsRunInTerminalRequest: true // #10574 }).then((result: DebugProtocol.InitializeResponse) => { if (session.disconnected) { return TPromise.wrapError(new Error(nls.localize('debugAdapterCrash', "Debug adapter process has terminated unexpectedly"))); } this.model.setExceptionBreakpoints(session.configuration.capabilities.exceptionBreakpointFilters); return configuration.request === 'attach' ? session.attach(configuration) : session.launch(configuration); }).then((result: DebugProtocol.Response) => { if (session.disconnected) { return TPromise.as(null); } if (configuration.internalConsoleOptions === 'openOnSessionStart' || (!this.viewModel.changedWorkbenchViewState && configuration.internalConsoleOptions !== 'neverOpen')) { this.panelService.openPanel(debug.REPL_ID, false).done(undefined, errors.onUnexpectedError); } if (!this.viewModel.changedWorkbenchViewState && !this.partService.isSideBarHidden()) { // We only want to change the workbench view state on the first debug session #5738 and if the side bar is not hidden this.viewModel.changedWorkbenchViewState = true; this.viewletService.openViewlet(debug.VIEWLET_ID); } // Do not change status bar to orange if we are just running without debug. if (!configuration.noDebug) { this.partService.addClass('debugging'); } this.extensionService.activateByEvent(`onDebug:${configuration.type}`).done(null, errors.onUnexpectedError); this.inDebugMode.set(true); this.transitionToRunningState(session); this.telemetryService.publicLog('debugSessionStart', { type: configuration.type, breakpointCount: this.model.getBreakpoints().length, exceptionBreakpoints: this.model.getExceptionBreakpoints(), watchExpressionsCount: this.model.getWatchExpressions().length, extensionName: `${adapter.extensionDescription.publisher}.${adapter.extensionDescription.name}`, isBuiltin: adapter.extensionDescription.isBuiltin }); }).then(undefined, (error: any) => { if (error instanceof Error && error.message === 'Canceled') { // Do not show 'canceled' error messages to the user #7906 return TPromise.as(null); } this.telemetryService.publicLog('debugMisconfiguration', { type: configuration ? configuration.type : undefined }); this.setStateAndEmit(session.getId(), debug.State.Inactive); if (!session.disconnected) { session.disconnect().done(null, errors.onUnexpectedError); } // Show the repl if some error got logged there #5870 if (this.model.getReplElements().length > 0) { this.panelService.openPanel(debug.REPL_ID, false).done(undefined, errors.onUnexpectedError); } const configureAction = this.instantiationService.createInstance(debugactions.ConfigureAction, debugactions.ConfigureAction.ID, debugactions.ConfigureAction.LABEL); const actions = (error.actions && error.actions.length) ? error.actions.concat([configureAction]) : [CloseAction, configureAction]; return TPromise.wrapError(errors.create(error.message, { actions })); }); }); } private runPreLaunchTask(taskName: string): TPromise<ITaskSummary> { if (!taskName) { return TPromise.as(null); } // run a task before starting a debug session return this.taskService.tasks().then(descriptions => { const filteredTasks = descriptions.filter(task => task.name === taskName); if (filteredTasks.length !== 1) { return TPromise.wrapError(errors.create(nls.localize('DebugTaskNotFound', "Could not find the preLaunchTask \'{0}\'.", taskName), { actions: [ this.instantiationService.createInstance(debugactions.ConfigureAction, debugactions.ConfigureAction.ID, debugactions.ConfigureAction.LABEL), this.taskService.configureAction(), CloseAction ] })); } // task is already running - nothing to do. if (this.lastTaskEvent && this.lastTaskEvent.taskName === taskName) { return TPromise.as(null); } if (this.lastTaskEvent) { // there is a different task running currently. return TPromise.wrapError(errors.create(nls.localize('differentTaskRunning', "There is a task {0} running. Can not run pre launch task {1}.", this.lastTaskEvent.taskName, taskName))); } // no task running, execute the preLaunchTask. const taskPromise = this.taskService.run(filteredTasks[0].id).then(result => { this.lastTaskEvent = null; return result; }, err => { this.lastTaskEvent = null; }); if (filteredTasks[0].isWatching) { return new TPromise((c, e) => this.taskService.addOneTimeDisposableListener(TaskServiceEvents.Inactive, () => c(null))); } return taskPromise; }); } private rawAttach(session: RawDebugSession, port: number): TPromise<any> { if (session) { return session.attach({ port }); } const sessionId = uuid.generateUuid(); this.setStateAndEmit(sessionId, debug.State.Initializing); return this.configurationManager.getConfiguration(this.viewModel.selectedConfigurationName).then((configuration: debug.IExtHostConfig) => this.doCreateProcess(sessionId, { type: configuration.type, request: 'attach', port, sourceMaps: configuration.sourceMaps, outDir: configuration.outDir, debugServer: configuration.debugServer }) ); } public restartProcess(process: debug.IProcess): TPromise<any> { return process ? process.session.disconnect(true).then(() => new TPromise<void>((c, e) => { setTimeout(() => { this.createProcess(process.name).then(() => c(null), err => e(err)); }, 300); }) ) : this.createProcess(this.viewModel.selectedConfigurationName); } private onSessionEnd(session: RawDebugSession): void { if (session) { const bpsExist = this.model.getBreakpoints().length > 0; this.telemetryService.publicLog('debugSessionStop', { type: session.configuration.type, success: session.emittedStopped || !bpsExist, sessionLengthInSeconds: session.getLengthInSeconds(), breakpointCount: this.model.getBreakpoints().length, watchExpressionsCount: this.model.getWatchExpressions().length }); } try { this.toDisposeOnSessionEnd[session.getId()] = lifecycle.dispose(this.toDisposeOnSessionEnd[session.getId()]); } catch (e) { // an internal module might be open so the dispose can throw -> ignore and continue with stop session. } this.partService.removeClass('debugging'); this.model.removeProcess(session.getId()); this.setFocusedStackFrameAndEvaluate(null).done(null, errors.onUnexpectedError); this.setStateAndEmit(session.getId(), debug.State.Inactive); // set breakpoints back to unverified since the session ended. // source reference changes across sessions, so we do not use it to persist the source. const data: { [id: string]: { line: number, verified: boolean } } = {}; this.model.getBreakpoints().forEach(bp => { delete bp.source.raw.sourceReference; data[bp.getId()] = { line: bp.lineNumber, verified: false }; }); this.model.updateBreakpoints(data); this.inDebugMode.reset(); if (!this.partService.isSideBarHidden() && this.configurationService.getConfiguration<debug.IDebugConfiguration>('debug').openExplorerOnEnd) { this.viewletService.openViewlet(EXPLORER_VIEWLET_ID).done(null, errors.onUnexpectedError); } } public getModel(): debug.IModel { return this.model; } public getViewModel(): debug.IViewModel { return this.viewModel; } public openOrRevealSource(source: Source, lineNumber: number, preserveFocus: boolean, sideBySide: boolean): TPromise<any> { const visibleEditors = this.editorService.getVisibleEditors(); for (let i = 0; i < visibleEditors.length; i++) { const fileInput = asFileEditorInput(visibleEditors[i].input); if ((fileInput && fileInput.getResource().toString() === source.uri.toString()) || (visibleEditors[i].input instanceof DebugStringEditorInput && (<DebugStringEditorInput>visibleEditors[i].input).getResource().toString() === source.uri.toString())) { const control = <editorbrowser.ICodeEditor>visibleEditors[i].getControl(); if (control) { control.revealLineInCenterIfOutsideViewport(lineNumber); control.setSelection({ startLineNumber: lineNumber, startColumn: 1, endLineNumber: lineNumber, endColumn: 1 }); this.editorGroupService.activateGroup(i); if (!preserveFocus) { this.editorGroupService.focusGroup(i); } } return TPromise.as(null); } } const process = this.viewModel.focusedProcess; if (source.inMemory) { // internal module if (source.reference !== 0 && process && source.available) { return process.session.source({ sourceReference: source.reference }).then(response => { const mime = response && response.body && response.body.mimeType ? response.body.mimeType : guessMimeTypes(source.name)[0]; const inputValue = response && response.body ? response.body.content : ''; return this.getDebugStringEditorInput(process, source, inputValue, mime); }, (err: DebugProtocol.ErrorResponse) => { // Display the error from debug adapter using a temporary editor #8836 return this.getDebugErrorEditorInput(process, source, err.message); }).then(editorInput => { return this.editorService.openEditor(editorInput, { preserveFocus, selection: { startLineNumber: lineNumber, startColumn: 1, endLineNumber: lineNumber, endColumn: 1 } }, sideBySide); }); } return this.sourceIsUnavailable(process, source, sideBySide); } return this.fileService.resolveFile(source.uri).then(() => this.editorService.openEditor({ resource: source.uri, options: { selection: { startLineNumber: lineNumber, startColumn: 1, endLineNumber: lineNumber, endColumn: 1 }, preserveFocus: preserveFocus } }, sideBySide), err => this.sourceIsUnavailable(process, source, sideBySide) ); } private sourceIsUnavailable(process: debug.IProcess, source: Source, sideBySide: boolean): TPromise<any> { this.model.sourceIsUnavailable(source); const editorInput = this.getDebugErrorEditorInput(process, source, nls.localize('debugSourceNotAvailable', "Source {0} is not available.", source.name)); return this.editorService.openEditor(editorInput, { preserveFocus: true }, sideBySide); } public getConfigurationManager(): debug.IConfigurationManager { return this.configurationManager; } private transitionToRunningState(session: RawDebugSession, threadId?: number): void { this.model.clearThreads(session.getId(), false, threadId); // TODO@Isidor remove this mess // Get a top stack frame of a stopped thread if there is any. const process = this.model.getProcesses().filter(p => p.getId() === session.getId()).pop(); const stoppedThread = process && process.getAllThreads().filter(t => t.stopped).pop(); const callStack = stoppedThread ? stoppedThread.getCachedCallStack() : null; const stackFrameToFocus = callStack && callStack.length > 0 ? callStack[0] : null; if (!stoppedThread && process) { this.setStateAndEmit(session.getId(), process.session.requestType === debug.SessionRequestType.LAUNCH_NO_DEBUG ? debug.State.RunningNoDebug : debug.State.Running); } this.setFocusedStackFrameAndEvaluate(stackFrameToFocus).done(null, errors.onUnexpectedError); } private getDebugStringEditorInput(process: debug.IProcess, source: Source, value: string, mtype: string): DebugStringEditorInput { const result = this.instantiationService.createInstance(DebugStringEditorInput, source.name, source.uri, source.origin, value, mtype, void 0); this.toDisposeOnSessionEnd[process.getId()].push(result); return result; } private getDebugErrorEditorInput(process: debug.IProcess, source: Source, value: string): DebugErrorEditorInput { const result = this.instantiationService.createInstance(DebugErrorEditorInput, source.name, value); this.toDisposeOnSessionEnd[process.getId()].push(result); return result; } private sendAllBreakpoints(session?: RawDebugSession): TPromise<any> { return TPromise.join(arrays.distinct(this.model.getBreakpoints(), bp => bp.source.uri.toString()).map(bp => this.sendBreakpoints(bp.source.uri, false, session))) .then(() => this.sendFunctionBreakpoints(session)) // send exception breakpoints at the end since some debug adapters rely on the order .then(() => this.sendExceptionBreakpoints(session)); } private sendBreakpoints(modelUri: uri, sourceModified = false, targetSession?: RawDebugSession): TPromise<void> { const sendBreakpointsToSession = (session: RawDebugSession): TPromise<void> => { if (!session.readyForBreakpoints) { return TPromise.as(null); } if (this.textFileService.isDirty(modelUri)) { // Only send breakpoints for a file once it is not dirty #8077 this.breakpointsToSendOnResourceSaved[modelUri.toString()] = true; return TPromise.as(null); } const breakpointsToSend = arrays.distinct( this.model.getBreakpoints().filter(bp => this.model.areBreakpointsActivated() && bp.enabled && bp.source.uri.toString() === modelUri.toString()), bp => `${bp.desiredLineNumber}` ); const rawSource = breakpointsToSend.length > 0 ? breakpointsToSend[0].source.raw : Source.toRawSource(modelUri, this.model); return session.setBreakpoints({ source: rawSource, lines: breakpointsToSend.map(bp => bp.desiredLineNumber), breakpoints: breakpointsToSend.map(bp => ({ line: bp.desiredLineNumber, condition: bp.condition, hitCondition: bp.hitCondition })), sourceModified }).then(response => { if (!response || !response.body) { return; } const data: { [id: string]: { line?: number, verified: boolean } } = {}; for (let i = 0; i < breakpointsToSend.length; i++) { data[breakpointsToSend[i].getId()] = response.body.breakpoints[i]; } this.model.updateBreakpoints(data); }); }; return this.sendToOneOrAllSessions(targetSession, sendBreakpointsToSession); } private sendFunctionBreakpoints(targetSession?: RawDebugSession): TPromise<void> { const sendFunctionBreakpointsToSession = (session: RawDebugSession): TPromise<void> => { if (!session.readyForBreakpoints || !session.configuration.capabilities.supportsFunctionBreakpoints) { return TPromise.as(null); } const breakpointsToSend = this.model.getFunctionBreakpoints().filter(fbp => fbp.enabled && this.model.areBreakpointsActivated()); return session.setFunctionBreakpoints({ breakpoints: breakpointsToSend }).then(response => { if (!response || !response.body) { return; } const data: { [id: string]: { name?: string, verified?: boolean } } = {}; for (let i = 0; i < breakpointsToSend.length; i++) { data[breakpointsToSend[i].getId()] = response.body.breakpoints[i]; } this.model.updateFunctionBreakpoints(data); }); }; return this.sendToOneOrAllSessions(targetSession, sendFunctionBreakpointsToSession); } private sendExceptionBreakpoints(targetSession?: RawDebugSession): TPromise<void> { const sendExceptionBreakpointsToSession = (session: RawDebugSession): TPromise<any> => { if (!session || !session.readyForBreakpoints || this.model.getExceptionBreakpoints().length === 0) { return TPromise.as(null); } const enabledExceptionBps = this.model.getExceptionBreakpoints().filter(exb => exb.enabled); return session.setExceptionBreakpoints({ filters: enabledExceptionBps.map(exb => exb.filter) }); }; return this.sendToOneOrAllSessions(targetSession, sendExceptionBreakpointsToSession); } private sendToOneOrAllSessions(session: RawDebugSession, send: (session: RawDebugSession) => TPromise<void>): TPromise<void> { if (session) { return send(session); } return TPromise.join(this.model.getProcesses().map(p => send(<RawDebugSession>p.session))).then(() => void 0); } private onFileChanges(fileChangesEvent: FileChangesEvent): void { this.model.removeBreakpoints(this.model.getBreakpoints().filter(bp => fileChangesEvent.contains(bp.source.uri, FileChangeType.DELETED))); fileChangesEvent.getUpdated().forEach(event => { if (this.breakpointsToSendOnResourceSaved[event.resource.toString()]) { this.breakpointsToSendOnResourceSaved[event.resource.toString()] = false; this.sendBreakpoints(event.resource, true).done(null, errors.onUnexpectedError); } }); } private store(): void { this.storageService.store(DEBUG_BREAKPOINTS_KEY, JSON.stringify(this.model.getBreakpoints()), StorageScope.WORKSPACE); this.storageService.store(DEBUG_BREAKPOINTS_ACTIVATED_KEY, this.model.areBreakpointsActivated() ? 'true' : 'false', StorageScope.WORKSPACE); this.storageService.store(DEBUG_FUNCTION_BREAKPOINTS_KEY, JSON.stringify(this.model.getFunctionBreakpoints()), StorageScope.WORKSPACE); this.storageService.store(DEBUG_EXCEPTION_BREAKPOINTS_KEY, JSON.stringify(this.model.getExceptionBreakpoints()), StorageScope.WORKSPACE); this.storageService.store(DEBUG_SELECTED_CONFIG_NAME_KEY, this.viewModel.selectedConfigurationName, StorageScope.WORKSPACE); this.storageService.store(DEBUG_WATCH_EXPRESSIONS_KEY, JSON.stringify(this.model.getWatchExpressions().map(we => ({ name: we.name, id: we.getId() }))), StorageScope.WORKSPACE); } public dispose(): void { Object.keys(this.toDisposeOnSessionEnd).forEach(key => lifecycle.dispose(this.toDisposeOnSessionEnd[key])); this.toDispose = lifecycle.dispose(this.toDispose); } }
src/vs/workbench/parts/debug/electron-browser/debugService.ts
1
https://github.com/microsoft/vscode/commit/a5ba48b76595d703ffbc26f108fd9f5acef154f9
[ 0.999049961566925, 0.281383752822876, 0.00016270630294457078, 0.00017020195082295686, 0.43792101740837097 ]
{ "id": 0, "code_window": [ "\t\t\t}\n", "\t\t});\n", "\t}\n", "}\n", "\n", "export class Breakpoint implements debug.IBreakpoint {\n", "\n", "\tpublic lineNumber: number;\n", "\tpublic verified: boolean;\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "// TODO@Isidor breakpoint should not have a pointer to source. Source should live inside a stack frame\n" ], "file_path": "src/vs/workbench/parts/debug/common/debugModel.ts", "type": "add", "edit_start_line_idx": 561 }
/*--------------------------------------------------------------------------------------------- * 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 gulp from 'gulp'; import * as tsb from 'gulp-tsb'; import * as es from 'event-stream'; const watch = require('./watch'); import * as nls from './nls'; import * as util from './util'; import { createReporter } from './reporter'; import * as path from 'path'; import * as bom from 'gulp-bom'; import * as sourcemaps from 'gulp-sourcemaps'; import * as _ from 'underscore'; import * as monacodts from '../monaco/api'; import * as fs from 'fs'; const reporter = createReporter(); const rootDir = path.join(__dirname, '../../src'); const options = require('../../src/tsconfig.json').compilerOptions; options.verbose = false; options.sourceMap = true; options.rootDir = rootDir; options.sourceRoot = util.toFileUri(rootDir); function createCompile(build:boolean, emitError?:boolean): (token?:util.ICancellationToken) => NodeJS.ReadWriteStream { const opts = _.clone(options); opts.inlineSources = !!build; opts.noFilesystemLookup = true; const ts = tsb.create(opts, null, null, err => reporter(err.toString())); return function (token?:util.ICancellationToken) { const utf8Filter = util.filter(data => /(\/|\\)test(\/|\\).*utf8/.test(data.path)); const tsFilter = util.filter(data => /\.ts$/.test(data.path)); const noDeclarationsFilter = util.filter(data => !(/\.d\.ts$/.test(data.path))); const input = es.through(); const output = input .pipe(utf8Filter) .pipe(bom()) .pipe(utf8Filter.restore) .pipe(tsFilter) .pipe(util.loadSourcemaps()) .pipe(ts(token)) .pipe(noDeclarationsFilter) .pipe(build ? nls() : es.through()) .pipe(noDeclarationsFilter.restore) .pipe(sourcemaps.write('.', { addComment: false, includeContent: !!build, sourceRoot: options.sourceRoot })) .pipe(tsFilter.restore) .pipe(reporter.end(emitError)); return es.duplex(input, output); }; } export function compileTask(out:string, build:boolean): () => NodeJS.ReadWriteStream { const compile = createCompile(build, true); return function () { const src = es.merge( gulp.src('src/**', { base: 'src' }), gulp.src('node_modules/typescript/lib/lib.d.ts') ); return src .pipe(compile()) .pipe(gulp.dest(out)) .pipe(monacodtsTask(out, false)); }; } export function watchTask(out:string, build:boolean): () => NodeJS.ReadWriteStream { const compile = createCompile(build); return function () { const src = es.merge( gulp.src('src/**', { base: 'src' }), gulp.src('node_modules/typescript/lib/lib.d.ts') ); const watchSrc = watch('src/**', { base: 'src' }); return watchSrc .pipe(util.incremental(compile, src, true)) .pipe(gulp.dest(out)) .pipe(monacodtsTask(out, true)); }; } function monacodtsTask(out:string, isWatch:boolean): NodeJS.ReadWriteStream { let timer:NodeJS.Timer = null; const runSoon = function(howSoon:number) { if (timer !== null) { clearTimeout(timer); timer = null; } timer = setTimeout(function() { timer = null; runNow(); }, howSoon); }; const runNow = function() { if (timer !== null) { clearTimeout(timer); timer = null; } // if (reporter.hasErrors()) { // monacodts.complainErrors(); // return; // } const result = monacodts.run(out); if (!result.isTheSame) { if (isWatch) { fs.writeFileSync(result.filePath, result.content); } else { resultStream.emit('error', 'monaco.d.ts is no longer up to date. Please run gulp watch and commit the new file.'); } } }; let resultStream: NodeJS.ReadWriteStream; if (isWatch) { const filesToWatchMap: {[file:string]:boolean;} = {}; monacodts.getFilesToWatch(out).forEach(function(filePath) { filesToWatchMap[path.normalize(filePath)] = true; }); watch('build/monaco/*').pipe(es.through(function() { runSoon(5000); })); resultStream = es.through(function(data) { const filePath = path.normalize(data.path); if (filesToWatchMap[filePath]) { runSoon(5000); } this.emit('data', data); }); } else { resultStream = es.through(null, function() { runNow(); this.emit('end'); }); } return resultStream; }
build/lib/compilation.ts
0
https://github.com/microsoft/vscode/commit/a5ba48b76595d703ffbc26f108fd9f5acef154f9
[ 0.0003658331697806716, 0.00018584290228318423, 0.0001677437248872593, 0.00017187331104651093, 0.000046840228606015444 ]
{ "id": 0, "code_window": [ "\t\t\t}\n", "\t\t});\n", "\t}\n", "}\n", "\n", "export class Breakpoint implements debug.IBreakpoint {\n", "\n", "\tpublic lineNumber: number;\n", "\tpublic verified: boolean;\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "// TODO@Isidor breakpoint should not have a pointer to source. Source should live inside a stack frame\n" ], "file_path": "src/vs/workbench/parts/debug/common/debugModel.ts", "type": "add", "edit_start_line_idx": 561 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "InPlaceReplaceAction.next.label": "Sostituisci con il valore successivo", "InPlaceReplaceAction.previous.label": "Sostituisci con il valore precedente" }
i18n/ita/src/vs/editor/contrib/inPlaceReplace/common/inPlaceReplace.i18n.json
0
https://github.com/microsoft/vscode/commit/a5ba48b76595d703ffbc26f108fd9f5acef154f9
[ 0.00017519210814498365, 0.00017519210814498365, 0.00017519210814498365, 0.00017519210814498365, 0 ]
{ "id": 0, "code_window": [ "\t\t\t}\n", "\t\t});\n", "\t}\n", "}\n", "\n", "export class Breakpoint implements debug.IBreakpoint {\n", "\n", "\tpublic lineNumber: number;\n", "\tpublic verified: boolean;\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "// TODO@Isidor breakpoint should not have a pointer to source. Source should live inside a stack frame\n" ], "file_path": "src/vs/workbench/parts/debug/common/debugModel.ts", "type": "add", "edit_start_line_idx": 561 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "enableValidation": "すべての検証を有効または無効にします", "rule.avoidFloat": "'float' は使用しないでください。float を使用すると、レイアウトの一部が変更されたときに CSS が破損しやすくなります。", "rule.avoidIdSelector": "セレクターには ID を含めないでください。これらの規則と HTML の結合が密接すぎます。", "rule.avoidImportant": "!important は使用しないでください。これは CSS 全体の特定性が制御不能になり、リファクタリングが必要なことを示しています。", "rule.colorFunction": "正しくないパラメーターの数", "rule.duplicateDeclarations": "重複するスタイル定義を使用しないでください", "rule.emptyRuleSets": "空の規則セットを使用しないでください", "rule.fontFaceProperties": "@font-face 規則で 'src' プロパティと 'font-family' プロパティを定義する必要があります", "rule.hexColor": "16 進数の色には、3 つまたは 6 つの 16 進数が含まれる必要があります", "rule.ieHack": "IE ハックは、IE7 以前をサポートする場合にのみ必要です", "rule.importDirective": "複数の Import ステートメントを同時に読み込むことはできません", "rule.propertyIgnoredDueToDisplay": "表示によりプロパティが無視されます。たとえば、'display: inline' の場合、width、height、margin-top、margin-bottom、および float のプロパティには効果がありません", "rule.standardvendorprefix.all": "ベンダー固有のプレフィックスを使用する場合は、標準のプロパティも含めます", "rule.universalSelector": "ユニバーサル セレクター (*) を使用すると処理速度が低下することが分かっています", "rule.unknownProperty": "不明なプロパティ。", "rule.unknownVendorSpecificProperty": "不明なベンダー固有のプロパティ。", "rule.vendorprefixes.all": "ベンダー固有のプレフィックスを使用する場合は、他のすべてのベンダー固有のプロパティも必ず含めてください", "rule.withHeightAndBorderPadding": "パディングまたは枠線を使用する場合は幅または高さを使用しないでください", "rule.zeroWidthUnit": "0 の単位は必要ありません" }
i18n/jpn/src/vs/languages/css/common/services/lintRules.i18n.json
0
https://github.com/microsoft/vscode/commit/a5ba48b76595d703ffbc26f108fd9f5acef154f9
[ 0.0006148867541924119, 0.0003162447828799486, 0.0001667387696215883, 0.00016710882482584566, 0.0002111718204105273 ]
{ "id": 1, "code_window": [ "\t\t\tthis.toDisposeOnSessionEnd[session.getId()] = lifecycle.dispose(this.toDisposeOnSessionEnd[session.getId()]);\n", "\t\t} catch (e) {\n", "\t\t\t// an internal module might be open so the dispose can throw -> ignore and continue with stop session.\n", "\t\t}\n", "\n", "\t\tthis.partService.removeClass('debugging');\n", "\n", "\t\tthis.model.removeProcess(session.getId());\n", "\t\tthis.setFocusedStackFrameAndEvaluate(null).done(null, errors.onUnexpectedError);\n", "\t\tthis.setStateAndEmit(session.getId(), debug.State.Inactive);\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/parts/debug/electron-browser/debugService.ts", "type": "replace", "edit_start_line_idx": 806 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import nls = require('vs/nls'); import lifecycle = require('vs/base/common/lifecycle'); import { guessMimeTypes } from 'vs/base/common/mime'; import Event, { Emitter } from 'vs/base/common/event'; import * as strings from 'vs/base/common/strings'; import uuid = require('vs/base/common/uuid'); import uri from 'vs/base/common/uri'; import { Action } from 'vs/base/common/actions'; import arrays = require('vs/base/common/arrays'); import types = require('vs/base/common/types'); import errors = require('vs/base/common/errors'); import severity from 'vs/base/common/severity'; import { TPromise } from 'vs/base/common/winjs.base'; import aria = require('vs/base/browser/ui/aria/aria'); import { Client as TelemetryClient } from 'vs/base/parts/ipc/node/ipc.cp'; import editorbrowser = require('vs/editor/browser/editorBrowser'); 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/platform/extensions/common/extensions'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IFileService, FileChangesEvent, FileChangeType, EventType } from 'vs/platform/files/common/files'; import { IEventService } from 'vs/platform/event/common/event'; import { IMessageService, CloseAction } from 'vs/platform/message/common/message'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { TelemetryService } from 'vs/platform/telemetry/common/telemetryService'; import { TelemetryAppenderClient } from 'vs/platform/telemetry/common/telemetryIpc'; import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage'; import { IEditorGroupService } from 'vs/workbench/services/group/common/groupService'; import { asFileEditorInput } from 'vs/workbench/common/editor'; import debug = require('vs/workbench/parts/debug/common/debug'); import { RawDebugSession } from 'vs/workbench/parts/debug/electron-browser/rawDebugSession'; import model = require('vs/workbench/parts/debug/common/debugModel'); import { DebugStringEditorInput, DebugErrorEditorInput } from 'vs/workbench/parts/debug/browser/debugEditorInputs'; import viewmodel = require('vs/workbench/parts/debug/common/debugViewModel'); import debugactions = require('vs/workbench/parts/debug/browser/debugActions'); import { ConfigurationManager } from 'vs/workbench/parts/debug/node/debugConfigurationManager'; import { Source } from 'vs/workbench/parts/debug/common/debugSource'; import { ITaskService, TaskEvent, TaskType, TaskServiceEvents, ITaskSummary } from 'vs/workbench/parts/tasks/common/taskService'; import { TaskError, TaskErrors } from 'vs/workbench/parts/tasks/common/taskSystem'; import { VIEWLET_ID as EXPLORER_VIEWLET_ID } from 'vs/workbench/parts/files/common/files'; import { IViewletService } from 'vs/workbench/services/viewlet/common/viewletService'; import { IPanelService } from 'vs/workbench/services/panel/common/panelService'; import { IPartService } from 'vs/workbench/services/part/common/partService'; import { ITextFileService } from 'vs/workbench/services/textfile/common/textfiles'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace'; import { IWorkbenchEditorService } from 'vs/workbench/services/editor/common/editorService'; import { IWindowService, IBroadcast } from 'vs/workbench/services/window/electron-browser/windowService'; import { ILogEntry, EXTENSION_LOG_BROADCAST_CHANNEL, EXTENSION_ATTACH_BROADCAST_CHANNEL, EXTENSION_TERMINATE_BROADCAST_CHANNEL } from 'vs/workbench/services/extensions/electron-browser/extensionHost'; import { ipcRenderer as ipc } from 'electron'; const DEBUG_BREAKPOINTS_KEY = 'debug.breakpoint'; const DEBUG_BREAKPOINTS_ACTIVATED_KEY = 'debug.breakpointactivated'; const DEBUG_FUNCTION_BREAKPOINTS_KEY = 'debug.functionbreakpoint'; const DEBUG_EXCEPTION_BREAKPOINTS_KEY = 'debug.exceptionbreakpoint'; const DEBUG_WATCH_EXPRESSIONS_KEY = 'debug.watchexpressions'; const DEBUG_SELECTED_CONFIG_NAME_KEY = 'debug.selectedconfigname'; export class DebugService implements debug.IDebugService { public _serviceBrand: any; private sessionStates: { [id: string]: debug.State }; private _onDidChangeState: Emitter<void>; private model: model.Model; private viewModel: viewmodel.ViewModel; private configurationManager: ConfigurationManager; private customTelemetryService: ITelemetryService; private lastTaskEvent: TaskEvent; private toDispose: lifecycle.IDisposable[]; private toDisposeOnSessionEnd: { [id: string]: lifecycle.IDisposable[] }; private inDebugMode: IContextKey<boolean>; private breakpointsToSendOnResourceSaved: { [uri: string]: boolean }; constructor( @IStorageService private storageService: IStorageService, @IWorkbenchEditorService private editorService: IWorkbenchEditorService, @ITextFileService private textFileService: ITextFileService, @IViewletService private viewletService: IViewletService, @IPanelService private panelService: IPanelService, @IFileService private fileService: IFileService, @IMessageService private messageService: IMessageService, @IPartService private partService: IPartService, @IWindowService private windowService: IWindowService, @ITelemetryService private telemetryService: ITelemetryService, @IWorkspaceContextService private contextService: IWorkspaceContextService, @IContextKeyService contextKeyService: IContextKeyService, @IEditorGroupService private editorGroupService: IEditorGroupService, @IEventService eventService: IEventService, @ILifecycleService lifecycleService: ILifecycleService, @IInstantiationService private instantiationService: IInstantiationService, @IExtensionService private extensionService: IExtensionService, @IMarkerService private markerService: IMarkerService, @ITaskService private taskService: ITaskService, @IConfigurationService private configurationService: IConfigurationService ) { this.toDispose = []; this.toDisposeOnSessionEnd = {}; this.breakpointsToSendOnResourceSaved = {}; this._onDidChangeState = new Emitter<void>(); this.sessionStates = {}; this.configurationManager = this.instantiationService.createInstance(ConfigurationManager); this.inDebugMode = debug.CONTEXT_IN_DEBUG_MODE.bindTo(contextKeyService); this.model = new model.Model(this.loadBreakpoints(), this.storageService.getBoolean(DEBUG_BREAKPOINTS_ACTIVATED_KEY, StorageScope.WORKSPACE, true), this.loadFunctionBreakpoints(), this.loadExceptionBreakpoints(), this.loadWatchExpressions()); this.toDispose.push(this.model); this.viewModel = new viewmodel.ViewModel(this.storageService.get(DEBUG_SELECTED_CONFIG_NAME_KEY, StorageScope.WORKSPACE, null)); this.registerListeners(eventService, lifecycleService); } private registerListeners(eventService: IEventService, lifecycleService: ILifecycleService): void { this.toDispose.push(eventService.addListener2(EventType.FILE_CHANGES, (e: FileChangesEvent) => this.onFileChanges(e))); if (this.taskService) { this.toDispose.push(this.taskService.addListener2(TaskServiceEvents.Active, (e: TaskEvent) => { this.lastTaskEvent = e; })); this.toDispose.push(this.taskService.addListener2(TaskServiceEvents.Inactive, (e: TaskEvent) => { if (e.type === TaskType.SingleRun) { this.lastTaskEvent = null; } })); this.toDispose.push(this.taskService.addListener2(TaskServiceEvents.Terminated, (e: TaskEvent) => { this.lastTaskEvent = null; })); } lifecycleService.onShutdown(this.store, this); lifecycleService.onShutdown(this.dispose, this); this.toDispose.push(this.windowService.onBroadcast(this.onBroadcast, this)); } private onBroadcast(broadcast: IBroadcast): void { // attach: PH is ready to be attached to // TODO@Isidor this is a hack to just get any 'extensionHost' session. // Optimally the broadcast would contain the id of the session // We are only intersted if we have an active debug session for extensionHost const session = <RawDebugSession>this.model.getProcesses().map(p => p.session).filter(s => s.configuration.type === 'extensionHost').pop(); if (broadcast.channel === EXTENSION_ATTACH_BROADCAST_CHANNEL) { this.rawAttach(session, broadcast.payload.port); return; } if (broadcast.channel === EXTENSION_TERMINATE_BROADCAST_CHANNEL) { this.onSessionEnd(session); return; } // from this point on we require an active session if (!session) { return; } // a plugin logged output, show it inside the REPL if (broadcast.channel === EXTENSION_LOG_BROADCAST_CHANNEL) { let extensionOutput: ILogEntry = broadcast.payload; let sev = extensionOutput.severity === 'warn' ? severity.Warning : extensionOutput.severity === 'error' ? severity.Error : severity.Info; let args: any[] = []; try { let parsed = JSON.parse(extensionOutput.arguments); args.push(...Object.getOwnPropertyNames(parsed).map(o => parsed[o])); } catch (error) { args.push(extensionOutput.arguments); } // add output for each argument logged let simpleVals: any[] = []; for (let i = 0; i < args.length; i++) { let a = args[i]; // undefined gets printed as 'undefined' if (typeof a === 'undefined') { simpleVals.push('undefined'); } // null gets printed as 'null' else if (a === null) { simpleVals.push('null'); } // objects & arrays are special because we want to inspect them in the REPL else if (types.isObject(a) || Array.isArray(a)) { // flush any existing simple values logged if (simpleVals.length) { this.logToRepl(simpleVals.join(' '), sev); simpleVals = []; } // show object this.logToRepl(a, sev); } // string: watch out for % replacement directive // string substitution and formatting @ https://developer.chrome.com/devtools/docs/console else if (typeof a === 'string') { let buf = ''; for (let j = 0, len = a.length; j < len; j++) { if (a[j] === '%' && (a[j + 1] === 's' || a[j + 1] === 'i' || a[j + 1] === 'd')) { i++; // read over substitution buf += !types.isUndefinedOrNull(args[i]) ? args[i] : ''; // replace j++; // read over directive } else { buf += a[j]; } } simpleVals.push(buf); } // number or boolean is joined together else { simpleVals.push(a); } } // flush simple values if (simpleVals.length) { this.logToRepl(simpleVals.join(' '), sev); } } } private registerSessionListeners(session: RawDebugSession): void { this.toDisposeOnSessionEnd[session.getId()].push(session); this.toDisposeOnSessionEnd[session.getId()].push(session.onDidInitialize(event => { aria.status(nls.localize('debuggingStarted', "Debugging started.")); const sendConfigurationDone = () => { if (session && session.configuration.capabilities.supportsConfigurationDoneRequest) { session.configurationDone().done(null, e => { // Disconnect the debug session on configuration done error #10596 if (session) { session.disconnect().done(null, errors.onUnexpectedError); } this.messageService.show(severity.Error, e.message); }); } }; this.sendAllBreakpoints(session).done(sendConfigurationDone, sendConfigurationDone); })); this.toDisposeOnSessionEnd[session.getId()].push(session.onDidStop(event => { this.setStateAndEmit(session.getId(), debug.State.Stopped); const threadId = event.body.threadId; session.threads().then(response => { if (!response || !response.body || !response.body.threads) { return; } const rawThread = response.body.threads.filter(t => t.id === threadId).pop(); this.model.rawUpdate({ sessionId: session.getId(), thread: rawThread, threadId, stoppedDetails: event.body, allThreadsStopped: event.body.allThreadsStopped }); const process = this.model.getProcesses().filter(p => p.getId() === session.getId()).pop(); const thread = process && process.getThread(threadId); if (thread) { thread.getCallStack().then(callStack => { if (callStack.length > 0) { // focus first stack frame from top that has source location const stackFrameToFocus = arrays.first(callStack, sf => sf.source && sf.source.available, callStack[0]); this.setFocusedStackFrameAndEvaluate(stackFrameToFocus).done(null, errors.onUnexpectedError); this.windowService.getWindow().focus(); aria.alert(nls.localize('debuggingPaused', "Debugging paused, reason {0}, {1} {2}", event.body.reason, stackFrameToFocus.source ? stackFrameToFocus.source.name : '', stackFrameToFocus.lineNumber)); return this.openOrRevealSource(stackFrameToFocus.source, stackFrameToFocus.lineNumber, false, false); } else { this.setFocusedStackFrameAndEvaluate(null).done(null, errors.onUnexpectedError); } }); } }, errors.onUnexpectedError); })); this.toDisposeOnSessionEnd[session.getId()].push(session.onDidThread(event => { if (event.body.reason === 'started') { session.threads().done(response => { if (response && response.body && response.body.threads) { response.body.threads.forEach(thread => this.model.rawUpdate({ sessionId: session.getId(), threadId: thread.id, thread })); } }, errors.onUnexpectedError); } else if (event.body.reason === 'exited') { this.model.clearThreads(session.getId(), true, event.body.threadId); } })); this.toDisposeOnSessionEnd[session.getId()].push(session.onDidTerminateDebugee(event => { aria.status(nls.localize('debuggingStopped', "Debugging stopped.")); if (session && session.getId() === event.body.sessionId) { if (event.body && typeof event.body.restart === 'boolean' && event.body.restart) { const process = this.model.getProcesses().filter(p => p.getId() === session.getId()).pop(); this.restartProcess(process).done(null, err => this.messageService.show(severity.Error, err.message)); } else { session.disconnect().done(null, errors.onUnexpectedError); } } })); this.toDisposeOnSessionEnd[session.getId()].push(session.onDidContinued(event => { this.transitionToRunningState(session, event.body.allThreadsContinued ? undefined : event.body.threadId); })); this.toDisposeOnSessionEnd[session.getId()].push(session.onDidOutput(event => { if (event.body && event.body.category === 'telemetry') { // only log telemetry events from debug adapter if the adapter provided the telemetry key // and the user opted in telemetry if (this.customTelemetryService && this.telemetryService.isOptedIn) { this.customTelemetryService.publicLog(event.body.output, event.body.data); } } else if (event.body && typeof event.body.output === 'string' && event.body.output.length > 0) { this.onOutput(event); } })); this.toDisposeOnSessionEnd[session.getId()].push(session.onDidBreakpoint(event => { const id = event.body && event.body.breakpoint ? event.body.breakpoint.id : undefined; const breakpoint = this.model.getBreakpoints().filter(bp => bp.idFromAdapter === id).pop(); if (breakpoint) { this.model.updateBreakpoints({ [breakpoint.getId()]: event.body.breakpoint }); } else { const functionBreakpoint = this.model.getFunctionBreakpoints().filter(bp => bp.idFromAdapter === id).pop(); if (functionBreakpoint) { this.model.updateFunctionBreakpoints({ [functionBreakpoint.getId()]: event.body.breakpoint }); } } })); this.toDisposeOnSessionEnd[session.getId()].push(session.onDidExitAdapter(event => { // 'Run without debugging' mode VSCode must terminate the extension host. More details: #3905 if (session && session.configuration.type === 'extensionHost' && this.sessionStates[session.getId()] === debug.State.RunningNoDebug) { ipc.send('vscode:closeExtensionHostWindow', this.contextService.getWorkspace().resource.fsPath); } if (session && session.getId() === event.body.sessionId) { this.onSessionEnd(session); } })); } private onOutput(event: DebugProtocol.OutputEvent): void { const outputSeverity = event.body.category === 'stderr' ? severity.Error : event.body.category === 'console' ? severity.Warning : severity.Info; this.appendReplOutput(event.body.output, outputSeverity); } private loadBreakpoints(): debug.IBreakpoint[] { let result: debug.IBreakpoint[]; try { result = JSON.parse(this.storageService.get(DEBUG_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((breakpoint: any) => { return new model.Breakpoint(new Source(breakpoint.source.raw ? breakpoint.source.raw : { path: uri.parse(breakpoint.source.uri).fsPath, name: breakpoint.source.name }), breakpoint.desiredLineNumber || breakpoint.lineNumber, breakpoint.enabled, breakpoint.condition, breakpoint.hitCondition); }); } catch (e) { } return result || []; } private loadFunctionBreakpoints(): debug.IFunctionBreakpoint[] { let result: debug.IFunctionBreakpoint[]; try { result = JSON.parse(this.storageService.get(DEBUG_FUNCTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((fb: any) => { return new model.FunctionBreakpoint(fb.name, fb.enabled, fb.hitCondition); }); } catch (e) { } return result || []; } private loadExceptionBreakpoints(): debug.IExceptionBreakpoint[] { let result: debug.IExceptionBreakpoint[]; try { result = JSON.parse(this.storageService.get(DEBUG_EXCEPTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((exBreakpoint: any) => { return new model.ExceptionBreakpoint(exBreakpoint.filter || exBreakpoint.name, exBreakpoint.label, exBreakpoint.enabled); }); } catch (e) { } return result || []; } private loadWatchExpressions(): model.Expression[] { let result: model.Expression[]; try { result = JSON.parse(this.storageService.get(DEBUG_WATCH_EXPRESSIONS_KEY, StorageScope.WORKSPACE, '[]')).map((watchStoredData: { name: string, id: string }) => { return new model.Expression(watchStoredData.name, false, watchStoredData.id); }); } catch (e) { } return result || []; } public get state(): debug.State { if (!this.contextService.getWorkspace()) { return debug.State.Disabled; } const focusedProcess = this.viewModel.focusedProcess; if (focusedProcess) { return this.sessionStates[focusedProcess.getId()]; } const processes = this.model.getProcesses(); if (processes.length > 0) { return this.sessionStates[processes[0].getId()]; } return debug.State.Inactive; } public get onDidChangeState(): Event<void> { return this._onDidChangeState.event; } private setStateAndEmit(sessionId: string, newState: debug.State): void { this.sessionStates[sessionId] = newState; this._onDidChangeState.fire(); } public get enabled(): boolean { return !!this.contextService.getWorkspace(); } public setFocusedStackFrameAndEvaluate(focusedStackFrame: debug.IStackFrame): TPromise<void> { const processes = this.model.getProcesses(); const process = focusedStackFrame ? focusedStackFrame.thread.process : processes.length ? processes[0] : null; if (process && !focusedStackFrame) { const thread = process.getAllThreads().pop(); const callStack = thread ? thread.getCachedCallStack() : null; focusedStackFrame = callStack && callStack.length ? callStack[0] : null; } this.viewModel.setFocusedStackFrame(focusedStackFrame, process); this._onDidChangeState.fire(); if (focusedStackFrame) { return this.model.evaluateWatchExpressions(focusedStackFrame); } else { this.model.clearWatchExpressionValues(); return TPromise.as(null); } } public enableOrDisableBreakpoints(enable: boolean, breakpoint?: debug.IEnablement): TPromise<void> { if (breakpoint) { this.model.setEnablement(breakpoint, enable); if (breakpoint instanceof model.Breakpoint) { return this.sendBreakpoints((<model.Breakpoint>breakpoint).source.uri); } else if (breakpoint instanceof model.FunctionBreakpoint) { return this.sendFunctionBreakpoints(); } return this.sendExceptionBreakpoints(); } this.model.enableOrDisableAllBreakpoints(enable); return this.sendAllBreakpoints(); } public addBreakpoints(rawBreakpoints: debug.IRawBreakpoint[]): TPromise<void> { this.model.addBreakpoints(rawBreakpoints); const uris = arrays.distinct(rawBreakpoints, raw => raw.uri.toString()).map(raw => raw.uri); rawBreakpoints.forEach(rbp => aria.status(nls.localize('breakpointAdded', "Added breakpoint, line {0}, file {1}", rbp.lineNumber, rbp.uri.fsPath))); return TPromise.join(uris.map(uri => this.sendBreakpoints(uri))).then(() => void 0); } public removeBreakpoints(id?: string): TPromise<any> { 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.source.uri.fsPath))); const urisToClear = arrays.distinct(toRemove, bp => bp.source.uri.toString()).map(bp => bp.source.uri); this.model.removeBreakpoints(toRemove); return TPromise.join(urisToClear.map(uri => this.sendBreakpoints(uri))); } public setBreakpointsActivated(activated: boolean): TPromise<void> { this.model.setBreakpointsActivated(activated); return this.sendAllBreakpoints(); } public addFunctionBreakpoint(): void { this.model.addFunctionBreakpoint(''); } public renameFunctionBreakpoint(id: string, newFunctionName: string): TPromise<void> { this.model.updateFunctionBreakpoints({ [id]: { name: newFunctionName } }); return this.sendFunctionBreakpoints(); } public removeFunctionBreakpoints(id?: string): TPromise<void> { this.model.removeFunctionBreakpoints(id); return this.sendFunctionBreakpoints(); } public addReplExpression(name: string): TPromise<void> { this.telemetryService.publicLog('debugService/addReplExpression'); return this.model.addReplExpression(this.viewModel.focusedStackFrame, name) // Evaluate all watch expressions again since repl evaluation might have changed some. .then(() => this.setFocusedStackFrameAndEvaluate(this.viewModel.focusedStackFrame)); } public logToRepl(value: string | { [key: string]: any }, severity?: severity): void { this.model.logToRepl(value, severity); } public appendReplOutput(value: string, severity?: severity): void { this.model.appendReplOutput(value, severity); } public removeReplExpressions(): void { this.model.removeReplExpressions(); } public addWatchExpression(name: string): TPromise<void> { return this.model.addWatchExpression(this.viewModel.focusedStackFrame, name); } public renameWatchExpression(id: string, newName: string): TPromise<void> { return this.model.renameWatchExpression(this.viewModel.focusedStackFrame, id, newName); } public removeWatchExpressions(id?: string): void { this.model.removeWatchExpressions(id); } public createProcess(configurationOrName: debug.IConfig | string): TPromise<any> { this.removeReplExpressions(); const sessionId = uuid.generateUuid(); this.setStateAndEmit(sessionId, debug.State.Initializing); return this.textFileService.saveAll() // make sure all dirty files are saved .then(() => this.configurationService.reloadConfiguration() // make sure configuration is up to date .then(() => this.extensionService.onReady() .then(() => this.configurationManager.getConfiguration(configurationOrName) .then(configuration => { if (!configuration) { return this.configurationManager.openConfigFile(false).then(openend => { if (openend) { this.messageService.show(severity.Info, nls.localize('NewLaunchConfig', "Please set up the launch configuration file for your application.")); } }); } if (configuration.silentlyAbort) { return; } if (strings.equalsIgnoreCase(configuration.type, 'composite') && configuration.configurationNames) { return TPromise.join(configuration.configurationNames.map(name => this.createProcess(name))); } if (!this.configurationManager.getAdapter(configuration.type)) { return configuration.type ? TPromise.wrapError(new Error(nls.localize('debugTypeNotSupported', "Configured debug type '{0}' is not supported.", configuration.type))) : TPromise.wrapError(errors.create(nls.localize('debugTypeMissing', "Missing property 'type' for the chosen launch configuration."), { actions: [this.instantiationService.createInstance(debugactions.ConfigureAction, debugactions.ConfigureAction.ID, debugactions.ConfigureAction.LABEL), CloseAction] })); } return this.runPreLaunchTask(configuration.preLaunchTask).then((taskSummary: ITaskSummary) => { const errorCount = configuration.preLaunchTask ? this.markerService.getStatistics().errors : 0; const successExitCode = taskSummary && taskSummary.exitCode === 0; const failureExitCode = taskSummary && taskSummary.exitCode !== undefined && taskSummary.exitCode !== 0; if (successExitCode || (errorCount === 0 && !failureExitCode)) { return this.doCreateProcess(sessionId, configuration); } this.messageService.show(severity.Error, { message: errorCount > 1 ? nls.localize('preLaunchTaskErrors', "Build errors have been detected during preLaunchTask '{0}'.", configuration.preLaunchTask) : errorCount === 1 ? nls.localize('preLaunchTaskError', "Build error has been detected during preLaunchTask '{0}'.", configuration.preLaunchTask) : nls.localize('preLaunchTaskExitCode', "The preLaunchTask '{0}' terminated with exit code {1}.", configuration.preLaunchTask, taskSummary.exitCode), actions: [new Action('debug.continue', nls.localize('debugAnyway', "Debug Anyway"), null, true, () => { this.messageService.hideAll(); return this.doCreateProcess(sessionId, configuration); }), CloseAction] }); }, (err: TaskError) => { if (err.code !== TaskErrors.NotConfigured) { throw err; } this.messageService.show(err.severity, { message: err.message, actions: [this.taskService.configureAction(), CloseAction] }); }); })))); } private doCreateProcess(sessionId: string, configuration: debug.IExtHostConfig): TPromise<any> { return this.telemetryService.getTelemetryInfo().then(info => { const telemetryInfo: { [key: string]: string } = Object.create(null); telemetryInfo['common.vscodemachineid'] = info.machineId; telemetryInfo['common.vscodesessionid'] = info.sessionId; return telemetryInfo; }).then(data => { const adapter = this.configurationManager.getAdapter(configuration.type); const { aiKey, type } = adapter; const publisher = adapter.extensionDescription.publisher; this.customTelemetryService = null; let client: TelemetryClient; if (aiKey) { client = new TelemetryClient( uri.parse(require.toUrl('bootstrap')).fsPath, { serverName: 'Debug Telemetry', timeout: 1000 * 60 * 5, args: [`${publisher}.${type}`, JSON.stringify(data), aiKey], env: { ELECTRON_RUN_AS_NODE: 1, PIPE_LOGGING: 'true', AMD_ENTRYPOINT: 'vs/workbench/parts/debug/node/telemetryApp' } } ); const channel = client.getChannel('telemetryAppender'); const appender = new TelemetryAppenderClient(channel); this.customTelemetryService = new TelemetryService({ appender }, this.configurationService); } const session = this.instantiationService.createInstance(RawDebugSession, sessionId, configuration.debugServer, adapter, this.customTelemetryService); this.model.addProcess(configuration.name, session); this.toDisposeOnSessionEnd[session.getId()] = []; if (client) { this.toDisposeOnSessionEnd[session.getId()].push(client); } this.registerSessionListeners(session); return session.initialize({ adapterID: configuration.type, pathFormat: 'path', linesStartAt1: true, columnsStartAt1: true, supportsVariableType: true, // #8858 supportsVariablePaging: true, // #9537 supportsRunInTerminalRequest: true // #10574 }).then((result: DebugProtocol.InitializeResponse) => { if (session.disconnected) { return TPromise.wrapError(new Error(nls.localize('debugAdapterCrash', "Debug adapter process has terminated unexpectedly"))); } this.model.setExceptionBreakpoints(session.configuration.capabilities.exceptionBreakpointFilters); return configuration.request === 'attach' ? session.attach(configuration) : session.launch(configuration); }).then((result: DebugProtocol.Response) => { if (session.disconnected) { return TPromise.as(null); } if (configuration.internalConsoleOptions === 'openOnSessionStart' || (!this.viewModel.changedWorkbenchViewState && configuration.internalConsoleOptions !== 'neverOpen')) { this.panelService.openPanel(debug.REPL_ID, false).done(undefined, errors.onUnexpectedError); } if (!this.viewModel.changedWorkbenchViewState && !this.partService.isSideBarHidden()) { // We only want to change the workbench view state on the first debug session #5738 and if the side bar is not hidden this.viewModel.changedWorkbenchViewState = true; this.viewletService.openViewlet(debug.VIEWLET_ID); } // Do not change status bar to orange if we are just running without debug. if (!configuration.noDebug) { this.partService.addClass('debugging'); } this.extensionService.activateByEvent(`onDebug:${configuration.type}`).done(null, errors.onUnexpectedError); this.inDebugMode.set(true); this.transitionToRunningState(session); this.telemetryService.publicLog('debugSessionStart', { type: configuration.type, breakpointCount: this.model.getBreakpoints().length, exceptionBreakpoints: this.model.getExceptionBreakpoints(), watchExpressionsCount: this.model.getWatchExpressions().length, extensionName: `${adapter.extensionDescription.publisher}.${adapter.extensionDescription.name}`, isBuiltin: adapter.extensionDescription.isBuiltin }); }).then(undefined, (error: any) => { if (error instanceof Error && error.message === 'Canceled') { // Do not show 'canceled' error messages to the user #7906 return TPromise.as(null); } this.telemetryService.publicLog('debugMisconfiguration', { type: configuration ? configuration.type : undefined }); this.setStateAndEmit(session.getId(), debug.State.Inactive); if (!session.disconnected) { session.disconnect().done(null, errors.onUnexpectedError); } // Show the repl if some error got logged there #5870 if (this.model.getReplElements().length > 0) { this.panelService.openPanel(debug.REPL_ID, false).done(undefined, errors.onUnexpectedError); } const configureAction = this.instantiationService.createInstance(debugactions.ConfigureAction, debugactions.ConfigureAction.ID, debugactions.ConfigureAction.LABEL); const actions = (error.actions && error.actions.length) ? error.actions.concat([configureAction]) : [CloseAction, configureAction]; return TPromise.wrapError(errors.create(error.message, { actions })); }); }); } private runPreLaunchTask(taskName: string): TPromise<ITaskSummary> { if (!taskName) { return TPromise.as(null); } // run a task before starting a debug session return this.taskService.tasks().then(descriptions => { const filteredTasks = descriptions.filter(task => task.name === taskName); if (filteredTasks.length !== 1) { return TPromise.wrapError(errors.create(nls.localize('DebugTaskNotFound', "Could not find the preLaunchTask \'{0}\'.", taskName), { actions: [ this.instantiationService.createInstance(debugactions.ConfigureAction, debugactions.ConfigureAction.ID, debugactions.ConfigureAction.LABEL), this.taskService.configureAction(), CloseAction ] })); } // task is already running - nothing to do. if (this.lastTaskEvent && this.lastTaskEvent.taskName === taskName) { return TPromise.as(null); } if (this.lastTaskEvent) { // there is a different task running currently. return TPromise.wrapError(errors.create(nls.localize('differentTaskRunning', "There is a task {0} running. Can not run pre launch task {1}.", this.lastTaskEvent.taskName, taskName))); } // no task running, execute the preLaunchTask. const taskPromise = this.taskService.run(filteredTasks[0].id).then(result => { this.lastTaskEvent = null; return result; }, err => { this.lastTaskEvent = null; }); if (filteredTasks[0].isWatching) { return new TPromise((c, e) => this.taskService.addOneTimeDisposableListener(TaskServiceEvents.Inactive, () => c(null))); } return taskPromise; }); } private rawAttach(session: RawDebugSession, port: number): TPromise<any> { if (session) { return session.attach({ port }); } const sessionId = uuid.generateUuid(); this.setStateAndEmit(sessionId, debug.State.Initializing); return this.configurationManager.getConfiguration(this.viewModel.selectedConfigurationName).then((configuration: debug.IExtHostConfig) => this.doCreateProcess(sessionId, { type: configuration.type, request: 'attach', port, sourceMaps: configuration.sourceMaps, outDir: configuration.outDir, debugServer: configuration.debugServer }) ); } public restartProcess(process: debug.IProcess): TPromise<any> { return process ? process.session.disconnect(true).then(() => new TPromise<void>((c, e) => { setTimeout(() => { this.createProcess(process.name).then(() => c(null), err => e(err)); }, 300); }) ) : this.createProcess(this.viewModel.selectedConfigurationName); } private onSessionEnd(session: RawDebugSession): void { if (session) { const bpsExist = this.model.getBreakpoints().length > 0; this.telemetryService.publicLog('debugSessionStop', { type: session.configuration.type, success: session.emittedStopped || !bpsExist, sessionLengthInSeconds: session.getLengthInSeconds(), breakpointCount: this.model.getBreakpoints().length, watchExpressionsCount: this.model.getWatchExpressions().length }); } try { this.toDisposeOnSessionEnd[session.getId()] = lifecycle.dispose(this.toDisposeOnSessionEnd[session.getId()]); } catch (e) { // an internal module might be open so the dispose can throw -> ignore and continue with stop session. } this.partService.removeClass('debugging'); this.model.removeProcess(session.getId()); this.setFocusedStackFrameAndEvaluate(null).done(null, errors.onUnexpectedError); this.setStateAndEmit(session.getId(), debug.State.Inactive); // set breakpoints back to unverified since the session ended. // source reference changes across sessions, so we do not use it to persist the source. const data: { [id: string]: { line: number, verified: boolean } } = {}; this.model.getBreakpoints().forEach(bp => { delete bp.source.raw.sourceReference; data[bp.getId()] = { line: bp.lineNumber, verified: false }; }); this.model.updateBreakpoints(data); this.inDebugMode.reset(); if (!this.partService.isSideBarHidden() && this.configurationService.getConfiguration<debug.IDebugConfiguration>('debug').openExplorerOnEnd) { this.viewletService.openViewlet(EXPLORER_VIEWLET_ID).done(null, errors.onUnexpectedError); } } public getModel(): debug.IModel { return this.model; } public getViewModel(): debug.IViewModel { return this.viewModel; } public openOrRevealSource(source: Source, lineNumber: number, preserveFocus: boolean, sideBySide: boolean): TPromise<any> { const visibleEditors = this.editorService.getVisibleEditors(); for (let i = 0; i < visibleEditors.length; i++) { const fileInput = asFileEditorInput(visibleEditors[i].input); if ((fileInput && fileInput.getResource().toString() === source.uri.toString()) || (visibleEditors[i].input instanceof DebugStringEditorInput && (<DebugStringEditorInput>visibleEditors[i].input).getResource().toString() === source.uri.toString())) { const control = <editorbrowser.ICodeEditor>visibleEditors[i].getControl(); if (control) { control.revealLineInCenterIfOutsideViewport(lineNumber); control.setSelection({ startLineNumber: lineNumber, startColumn: 1, endLineNumber: lineNumber, endColumn: 1 }); this.editorGroupService.activateGroup(i); if (!preserveFocus) { this.editorGroupService.focusGroup(i); } } return TPromise.as(null); } } const process = this.viewModel.focusedProcess; if (source.inMemory) { // internal module if (source.reference !== 0 && process && source.available) { return process.session.source({ sourceReference: source.reference }).then(response => { const mime = response && response.body && response.body.mimeType ? response.body.mimeType : guessMimeTypes(source.name)[0]; const inputValue = response && response.body ? response.body.content : ''; return this.getDebugStringEditorInput(process, source, inputValue, mime); }, (err: DebugProtocol.ErrorResponse) => { // Display the error from debug adapter using a temporary editor #8836 return this.getDebugErrorEditorInput(process, source, err.message); }).then(editorInput => { return this.editorService.openEditor(editorInput, { preserveFocus, selection: { startLineNumber: lineNumber, startColumn: 1, endLineNumber: lineNumber, endColumn: 1 } }, sideBySide); }); } return this.sourceIsUnavailable(process, source, sideBySide); } return this.fileService.resolveFile(source.uri).then(() => this.editorService.openEditor({ resource: source.uri, options: { selection: { startLineNumber: lineNumber, startColumn: 1, endLineNumber: lineNumber, endColumn: 1 }, preserveFocus: preserveFocus } }, sideBySide), err => this.sourceIsUnavailable(process, source, sideBySide) ); } private sourceIsUnavailable(process: debug.IProcess, source: Source, sideBySide: boolean): TPromise<any> { this.model.sourceIsUnavailable(source); const editorInput = this.getDebugErrorEditorInput(process, source, nls.localize('debugSourceNotAvailable', "Source {0} is not available.", source.name)); return this.editorService.openEditor(editorInput, { preserveFocus: true }, sideBySide); } public getConfigurationManager(): debug.IConfigurationManager { return this.configurationManager; } private transitionToRunningState(session: RawDebugSession, threadId?: number): void { this.model.clearThreads(session.getId(), false, threadId); // TODO@Isidor remove this mess // Get a top stack frame of a stopped thread if there is any. const process = this.model.getProcesses().filter(p => p.getId() === session.getId()).pop(); const stoppedThread = process && process.getAllThreads().filter(t => t.stopped).pop(); const callStack = stoppedThread ? stoppedThread.getCachedCallStack() : null; const stackFrameToFocus = callStack && callStack.length > 0 ? callStack[0] : null; if (!stoppedThread && process) { this.setStateAndEmit(session.getId(), process.session.requestType === debug.SessionRequestType.LAUNCH_NO_DEBUG ? debug.State.RunningNoDebug : debug.State.Running); } this.setFocusedStackFrameAndEvaluate(stackFrameToFocus).done(null, errors.onUnexpectedError); } private getDebugStringEditorInput(process: debug.IProcess, source: Source, value: string, mtype: string): DebugStringEditorInput { const result = this.instantiationService.createInstance(DebugStringEditorInput, source.name, source.uri, source.origin, value, mtype, void 0); this.toDisposeOnSessionEnd[process.getId()].push(result); return result; } private getDebugErrorEditorInput(process: debug.IProcess, source: Source, value: string): DebugErrorEditorInput { const result = this.instantiationService.createInstance(DebugErrorEditorInput, source.name, value); this.toDisposeOnSessionEnd[process.getId()].push(result); return result; } private sendAllBreakpoints(session?: RawDebugSession): TPromise<any> { return TPromise.join(arrays.distinct(this.model.getBreakpoints(), bp => bp.source.uri.toString()).map(bp => this.sendBreakpoints(bp.source.uri, false, session))) .then(() => this.sendFunctionBreakpoints(session)) // send exception breakpoints at the end since some debug adapters rely on the order .then(() => this.sendExceptionBreakpoints(session)); } private sendBreakpoints(modelUri: uri, sourceModified = false, targetSession?: RawDebugSession): TPromise<void> { const sendBreakpointsToSession = (session: RawDebugSession): TPromise<void> => { if (!session.readyForBreakpoints) { return TPromise.as(null); } if (this.textFileService.isDirty(modelUri)) { // Only send breakpoints for a file once it is not dirty #8077 this.breakpointsToSendOnResourceSaved[modelUri.toString()] = true; return TPromise.as(null); } const breakpointsToSend = arrays.distinct( this.model.getBreakpoints().filter(bp => this.model.areBreakpointsActivated() && bp.enabled && bp.source.uri.toString() === modelUri.toString()), bp => `${bp.desiredLineNumber}` ); const rawSource = breakpointsToSend.length > 0 ? breakpointsToSend[0].source.raw : Source.toRawSource(modelUri, this.model); return session.setBreakpoints({ source: rawSource, lines: breakpointsToSend.map(bp => bp.desiredLineNumber), breakpoints: breakpointsToSend.map(bp => ({ line: bp.desiredLineNumber, condition: bp.condition, hitCondition: bp.hitCondition })), sourceModified }).then(response => { if (!response || !response.body) { return; } const data: { [id: string]: { line?: number, verified: boolean } } = {}; for (let i = 0; i < breakpointsToSend.length; i++) { data[breakpointsToSend[i].getId()] = response.body.breakpoints[i]; } this.model.updateBreakpoints(data); }); }; return this.sendToOneOrAllSessions(targetSession, sendBreakpointsToSession); } private sendFunctionBreakpoints(targetSession?: RawDebugSession): TPromise<void> { const sendFunctionBreakpointsToSession = (session: RawDebugSession): TPromise<void> => { if (!session.readyForBreakpoints || !session.configuration.capabilities.supportsFunctionBreakpoints) { return TPromise.as(null); } const breakpointsToSend = this.model.getFunctionBreakpoints().filter(fbp => fbp.enabled && this.model.areBreakpointsActivated()); return session.setFunctionBreakpoints({ breakpoints: breakpointsToSend }).then(response => { if (!response || !response.body) { return; } const data: { [id: string]: { name?: string, verified?: boolean } } = {}; for (let i = 0; i < breakpointsToSend.length; i++) { data[breakpointsToSend[i].getId()] = response.body.breakpoints[i]; } this.model.updateFunctionBreakpoints(data); }); }; return this.sendToOneOrAllSessions(targetSession, sendFunctionBreakpointsToSession); } private sendExceptionBreakpoints(targetSession?: RawDebugSession): TPromise<void> { const sendExceptionBreakpointsToSession = (session: RawDebugSession): TPromise<any> => { if (!session || !session.readyForBreakpoints || this.model.getExceptionBreakpoints().length === 0) { return TPromise.as(null); } const enabledExceptionBps = this.model.getExceptionBreakpoints().filter(exb => exb.enabled); return session.setExceptionBreakpoints({ filters: enabledExceptionBps.map(exb => exb.filter) }); }; return this.sendToOneOrAllSessions(targetSession, sendExceptionBreakpointsToSession); } private sendToOneOrAllSessions(session: RawDebugSession, send: (session: RawDebugSession) => TPromise<void>): TPromise<void> { if (session) { return send(session); } return TPromise.join(this.model.getProcesses().map(p => send(<RawDebugSession>p.session))).then(() => void 0); } private onFileChanges(fileChangesEvent: FileChangesEvent): void { this.model.removeBreakpoints(this.model.getBreakpoints().filter(bp => fileChangesEvent.contains(bp.source.uri, FileChangeType.DELETED))); fileChangesEvent.getUpdated().forEach(event => { if (this.breakpointsToSendOnResourceSaved[event.resource.toString()]) { this.breakpointsToSendOnResourceSaved[event.resource.toString()] = false; this.sendBreakpoints(event.resource, true).done(null, errors.onUnexpectedError); } }); } private store(): void { this.storageService.store(DEBUG_BREAKPOINTS_KEY, JSON.stringify(this.model.getBreakpoints()), StorageScope.WORKSPACE); this.storageService.store(DEBUG_BREAKPOINTS_ACTIVATED_KEY, this.model.areBreakpointsActivated() ? 'true' : 'false', StorageScope.WORKSPACE); this.storageService.store(DEBUG_FUNCTION_BREAKPOINTS_KEY, JSON.stringify(this.model.getFunctionBreakpoints()), StorageScope.WORKSPACE); this.storageService.store(DEBUG_EXCEPTION_BREAKPOINTS_KEY, JSON.stringify(this.model.getExceptionBreakpoints()), StorageScope.WORKSPACE); this.storageService.store(DEBUG_SELECTED_CONFIG_NAME_KEY, this.viewModel.selectedConfigurationName, StorageScope.WORKSPACE); this.storageService.store(DEBUG_WATCH_EXPRESSIONS_KEY, JSON.stringify(this.model.getWatchExpressions().map(we => ({ name: we.name, id: we.getId() }))), StorageScope.WORKSPACE); } public dispose(): void { Object.keys(this.toDisposeOnSessionEnd).forEach(key => lifecycle.dispose(this.toDisposeOnSessionEnd[key])); this.toDispose = lifecycle.dispose(this.toDispose); } }
src/vs/workbench/parts/debug/electron-browser/debugService.ts
1
https://github.com/microsoft/vscode/commit/a5ba48b76595d703ffbc26f108fd9f5acef154f9
[ 0.9976503252983093, 0.01049377303570509, 0.0001588937157066539, 0.00017717928858473897, 0.09635888785123825 ]
{ "id": 1, "code_window": [ "\t\t\tthis.toDisposeOnSessionEnd[session.getId()] = lifecycle.dispose(this.toDisposeOnSessionEnd[session.getId()]);\n", "\t\t} catch (e) {\n", "\t\t\t// an internal module might be open so the dispose can throw -> ignore and continue with stop session.\n", "\t\t}\n", "\n", "\t\tthis.partService.removeClass('debugging');\n", "\n", "\t\tthis.model.removeProcess(session.getId());\n", "\t\tthis.setFocusedStackFrameAndEvaluate(null).done(null, errors.onUnexpectedError);\n", "\t\tthis.setStateAndEmit(session.getId(), debug.State.Inactive);\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/parts/debug/electron-browser/debugService.ts", "type": "replace", "edit_start_line_idx": 806 }
/*--------------------------------------------------------------------------------------------- * 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 { BinaryKeybindings, KeyCodeUtils } from 'vs/base/common/keyCodes'; import * as platform from 'vs/base/common/platform'; import { IKeybindingItem, IKeybindings } from 'vs/platform/keybinding/common/keybinding'; import { ContextKeyExpr } from 'vs/platform/contextkey/common/contextkey'; import { CommandsRegistry, ICommandHandler, ICommandHandlerDescription } from 'vs/platform/commands/common/commands'; import { Registry } from 'vs/platform/platform'; export interface IKeybindingRule extends IKeybindings { id: string; weight: number; when: ContextKeyExpr; } export interface ICommandAndKeybindingRule extends IKeybindingRule { handler: ICommandHandler; description?: ICommandHandlerDescription; } export interface IKeybindingsRegistry { registerKeybindingRule(rule: IKeybindingRule); registerCommandAndKeybindingRule(desc: ICommandAndKeybindingRule): void; getDefaultKeybindings(): IKeybindingItem[]; WEIGHT: { editorCore(importance?: number): number; editorContrib(importance?: number): number; workbenchContrib(importance?: number): number; builtinExtension(importance?: number): number; externalExtension(importance?: number): number; }; } class KeybindingsRegistryImpl implements IKeybindingsRegistry { private _keybindings: IKeybindingItem[]; public WEIGHT = { editorCore: (importance: number = 0): number => { return 0 + importance; }, editorContrib: (importance: number = 0): number => { return 100 + importance; }, workbenchContrib: (importance: number = 0): number => { return 200 + importance; }, builtinExtension: (importance: number = 0): number => { return 300 + importance; }, externalExtension: (importance: number = 0): number => { return 400 + importance; } }; constructor() { this._keybindings = []; } /** * Take current platform into account and reduce to primary & secondary. */ private static bindToCurrentPlatform(kb: IKeybindings): { primary?: number; secondary?: number[]; } { if (platform.isWindows) { if (kb && kb.win) { return kb.win; } } else if (platform.isMacintosh) { if (kb && kb.mac) { return kb.mac; } } else { if (kb && kb.linux) { return kb.linux; } } return kb; } public registerKeybindingRule(rule: IKeybindingRule): void { let actualKb = KeybindingsRegistryImpl.bindToCurrentPlatform(rule); // here if (actualKb && actualKb.primary) { this.registerDefaultKeybinding(actualKb.primary, rule.id, rule.weight, 0, rule.when); } // here if (actualKb && Array.isArray(actualKb.secondary)) { actualKb.secondary.forEach((k, i) => this.registerDefaultKeybinding(k, rule.id, rule.weight, -i - 1, rule.when)); } } public registerCommandAndKeybindingRule(desc: ICommandAndKeybindingRule): void { this.registerKeybindingRule(desc); CommandsRegistry.registerCommand(desc.id, desc); } private registerDefaultKeybinding(keybinding: number, commandId: string, weight1: number, weight2: number, when: ContextKeyExpr): void { if (platform.isWindows) { if (BinaryKeybindings.hasCtrlCmd(keybinding) && !BinaryKeybindings.hasShift(keybinding) && BinaryKeybindings.hasAlt(keybinding) && !BinaryKeybindings.hasWinCtrl(keybinding)) { if (/^[A-Z0-9\[\]\|\;\'\,\.\/\`]$/.test(KeyCodeUtils.toString(BinaryKeybindings.extractKeyCode(keybinding)))) { console.warn('Ctrl+Alt+ keybindings should not be used by default under Windows. Offender: ', keybinding, ' for ', commandId); } } } this._keybindings.push({ keybinding: keybinding, command: commandId, when: when, weight1: weight1, weight2: weight2 }); } public getDefaultKeybindings(): IKeybindingItem[] { return this._keybindings; } } export let KeybindingsRegistry: IKeybindingsRegistry = new KeybindingsRegistryImpl(); // Define extension point ids export let Extensions = { EditorModes: 'platform.keybindingsRegistry' }; Registry.add(Extensions.EditorModes, KeybindingsRegistry);
src/vs/platform/keybinding/common/keybindingsRegistry.ts
0
https://github.com/microsoft/vscode/commit/a5ba48b76595d703ffbc26f108fd9f5acef154f9
[ 0.000174411412444897, 0.0001717677660053596, 0.000167596954270266, 0.00017160744755528867, 0.0000018467798099663923 ]
{ "id": 1, "code_window": [ "\t\t\tthis.toDisposeOnSessionEnd[session.getId()] = lifecycle.dispose(this.toDisposeOnSessionEnd[session.getId()]);\n", "\t\t} catch (e) {\n", "\t\t\t// an internal module might be open so the dispose can throw -> ignore and continue with stop session.\n", "\t\t}\n", "\n", "\t\tthis.partService.removeClass('debugging');\n", "\n", "\t\tthis.model.removeProcess(session.getId());\n", "\t\tthis.setFocusedStackFrameAndEvaluate(null).done(null, errors.onUnexpectedError);\n", "\t\tthis.setStateAndEmit(session.getId(), debug.State.Inactive);\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/parts/debug/electron-browser/debugService.ts", "type": "replace", "edit_start_line_idx": 806 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "iframeEditor": "Средство просмотра IFrame" }
i18n/rus/src/vs/workbench/browser/parts/editor/iframeEditor.i18n.json
0
https://github.com/microsoft/vscode/commit/a5ba48b76595d703ffbc26f108fd9f5acef154f9
[ 0.0001733630197122693, 0.0001733630197122693, 0.0001733630197122693, 0.0001733630197122693, 0 ]
{ "id": 1, "code_window": [ "\t\t\tthis.toDisposeOnSessionEnd[session.getId()] = lifecycle.dispose(this.toDisposeOnSessionEnd[session.getId()]);\n", "\t\t} catch (e) {\n", "\t\t\t// an internal module might be open so the dispose can throw -> ignore and continue with stop session.\n", "\t\t}\n", "\n", "\t\tthis.partService.removeClass('debugging');\n", "\n", "\t\tthis.model.removeProcess(session.getId());\n", "\t\tthis.setFocusedStackFrameAndEvaluate(null).done(null, errors.onUnexpectedError);\n", "\t\tthis.setStateAndEmit(session.getId(), debug.State.Inactive);\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/parts/debug/electron-browser/debugService.ts", "type": "replace", "edit_start_line_idx": 806 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "limitHit": "{0} weitere Fehler und Warnungen werden nicht angezeigt." }
i18n/deu/src/vs/workbench/api/node/extHostDiagnostics.i18n.json
0
https://github.com/microsoft/vscode/commit/a5ba48b76595d703ffbc26f108fd9f5acef154f9
[ 0.00017350242706015706, 0.00017350242706015706, 0.00017350242706015706, 0.00017350242706015706, 0 ]
{ "id": 2, "code_window": [ "\t\tthis.setFocusedStackFrameAndEvaluate(null).done(null, errors.onUnexpectedError);\n", "\t\tthis.setStateAndEmit(session.getId(), debug.State.Inactive);\n", "\n", "\t\t// set breakpoints back to unverified since the session ended.\n", "\t\t// source reference changes across sessions, so we do not use it to persist the source.\n", "\t\tconst data: { [id: string]: { line: number, verified: boolean } } = {};\n", "\t\tthis.model.getBreakpoints().forEach(bp => {\n", "\t\t\tdelete bp.source.raw.sourceReference;\n", "\t\t\tdata[bp.getId()] = { line: bp.lineNumber, verified: false };\n", "\t\t});\n", "\t\tthis.model.updateBreakpoints(data);\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [ "\t\tif (this.model.getProcesses().length === 0) {\n", "\t\t\tthis.partService.removeClass('debugging');\n", "\t\t\t// set breakpoints back to unverified since the session ended.\n", "\t\t\t// source reference changes across sessions, so we do not use it to persist the source.\n", "\t\t\tconst data: { [id: string]: { line: number, verified: boolean } } = {};\n", "\t\t\tthis.model.getBreakpoints().forEach(bp => {\n", "\t\t\t\tdelete bp.source.raw.sourceReference;\n", "\t\t\t\tdata[bp.getId()] = { line: bp.lineNumber, verified: false };\n", "\t\t\t});\n", "\t\t\tthis.model.updateBreakpoints(data);\n" ], "file_path": "src/vs/workbench/parts/debug/electron-browser/debugService.ts", "type": "replace", "edit_start_line_idx": 812 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import nls = require('vs/nls'); import lifecycle = require('vs/base/common/lifecycle'); import { guessMimeTypes } from 'vs/base/common/mime'; import Event, { Emitter } from 'vs/base/common/event'; import * as strings from 'vs/base/common/strings'; import uuid = require('vs/base/common/uuid'); import uri from 'vs/base/common/uri'; import { Action } from 'vs/base/common/actions'; import arrays = require('vs/base/common/arrays'); import types = require('vs/base/common/types'); import errors = require('vs/base/common/errors'); import severity from 'vs/base/common/severity'; import { TPromise } from 'vs/base/common/winjs.base'; import aria = require('vs/base/browser/ui/aria/aria'); import { Client as TelemetryClient } from 'vs/base/parts/ipc/node/ipc.cp'; import editorbrowser = require('vs/editor/browser/editorBrowser'); 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/platform/extensions/common/extensions'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IFileService, FileChangesEvent, FileChangeType, EventType } from 'vs/platform/files/common/files'; import { IEventService } from 'vs/platform/event/common/event'; import { IMessageService, CloseAction } from 'vs/platform/message/common/message'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { TelemetryService } from 'vs/platform/telemetry/common/telemetryService'; import { TelemetryAppenderClient } from 'vs/platform/telemetry/common/telemetryIpc'; import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage'; import { IEditorGroupService } from 'vs/workbench/services/group/common/groupService'; import { asFileEditorInput } from 'vs/workbench/common/editor'; import debug = require('vs/workbench/parts/debug/common/debug'); import { RawDebugSession } from 'vs/workbench/parts/debug/electron-browser/rawDebugSession'; import model = require('vs/workbench/parts/debug/common/debugModel'); import { DebugStringEditorInput, DebugErrorEditorInput } from 'vs/workbench/parts/debug/browser/debugEditorInputs'; import viewmodel = require('vs/workbench/parts/debug/common/debugViewModel'); import debugactions = require('vs/workbench/parts/debug/browser/debugActions'); import { ConfigurationManager } from 'vs/workbench/parts/debug/node/debugConfigurationManager'; import { Source } from 'vs/workbench/parts/debug/common/debugSource'; import { ITaskService, TaskEvent, TaskType, TaskServiceEvents, ITaskSummary } from 'vs/workbench/parts/tasks/common/taskService'; import { TaskError, TaskErrors } from 'vs/workbench/parts/tasks/common/taskSystem'; import { VIEWLET_ID as EXPLORER_VIEWLET_ID } from 'vs/workbench/parts/files/common/files'; import { IViewletService } from 'vs/workbench/services/viewlet/common/viewletService'; import { IPanelService } from 'vs/workbench/services/panel/common/panelService'; import { IPartService } from 'vs/workbench/services/part/common/partService'; import { ITextFileService } from 'vs/workbench/services/textfile/common/textfiles'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace'; import { IWorkbenchEditorService } from 'vs/workbench/services/editor/common/editorService'; import { IWindowService, IBroadcast } from 'vs/workbench/services/window/electron-browser/windowService'; import { ILogEntry, EXTENSION_LOG_BROADCAST_CHANNEL, EXTENSION_ATTACH_BROADCAST_CHANNEL, EXTENSION_TERMINATE_BROADCAST_CHANNEL } from 'vs/workbench/services/extensions/electron-browser/extensionHost'; import { ipcRenderer as ipc } from 'electron'; const DEBUG_BREAKPOINTS_KEY = 'debug.breakpoint'; const DEBUG_BREAKPOINTS_ACTIVATED_KEY = 'debug.breakpointactivated'; const DEBUG_FUNCTION_BREAKPOINTS_KEY = 'debug.functionbreakpoint'; const DEBUG_EXCEPTION_BREAKPOINTS_KEY = 'debug.exceptionbreakpoint'; const DEBUG_WATCH_EXPRESSIONS_KEY = 'debug.watchexpressions'; const DEBUG_SELECTED_CONFIG_NAME_KEY = 'debug.selectedconfigname'; export class DebugService implements debug.IDebugService { public _serviceBrand: any; private sessionStates: { [id: string]: debug.State }; private _onDidChangeState: Emitter<void>; private model: model.Model; private viewModel: viewmodel.ViewModel; private configurationManager: ConfigurationManager; private customTelemetryService: ITelemetryService; private lastTaskEvent: TaskEvent; private toDispose: lifecycle.IDisposable[]; private toDisposeOnSessionEnd: { [id: string]: lifecycle.IDisposable[] }; private inDebugMode: IContextKey<boolean>; private breakpointsToSendOnResourceSaved: { [uri: string]: boolean }; constructor( @IStorageService private storageService: IStorageService, @IWorkbenchEditorService private editorService: IWorkbenchEditorService, @ITextFileService private textFileService: ITextFileService, @IViewletService private viewletService: IViewletService, @IPanelService private panelService: IPanelService, @IFileService private fileService: IFileService, @IMessageService private messageService: IMessageService, @IPartService private partService: IPartService, @IWindowService private windowService: IWindowService, @ITelemetryService private telemetryService: ITelemetryService, @IWorkspaceContextService private contextService: IWorkspaceContextService, @IContextKeyService contextKeyService: IContextKeyService, @IEditorGroupService private editorGroupService: IEditorGroupService, @IEventService eventService: IEventService, @ILifecycleService lifecycleService: ILifecycleService, @IInstantiationService private instantiationService: IInstantiationService, @IExtensionService private extensionService: IExtensionService, @IMarkerService private markerService: IMarkerService, @ITaskService private taskService: ITaskService, @IConfigurationService private configurationService: IConfigurationService ) { this.toDispose = []; this.toDisposeOnSessionEnd = {}; this.breakpointsToSendOnResourceSaved = {}; this._onDidChangeState = new Emitter<void>(); this.sessionStates = {}; this.configurationManager = this.instantiationService.createInstance(ConfigurationManager); this.inDebugMode = debug.CONTEXT_IN_DEBUG_MODE.bindTo(contextKeyService); this.model = new model.Model(this.loadBreakpoints(), this.storageService.getBoolean(DEBUG_BREAKPOINTS_ACTIVATED_KEY, StorageScope.WORKSPACE, true), this.loadFunctionBreakpoints(), this.loadExceptionBreakpoints(), this.loadWatchExpressions()); this.toDispose.push(this.model); this.viewModel = new viewmodel.ViewModel(this.storageService.get(DEBUG_SELECTED_CONFIG_NAME_KEY, StorageScope.WORKSPACE, null)); this.registerListeners(eventService, lifecycleService); } private registerListeners(eventService: IEventService, lifecycleService: ILifecycleService): void { this.toDispose.push(eventService.addListener2(EventType.FILE_CHANGES, (e: FileChangesEvent) => this.onFileChanges(e))); if (this.taskService) { this.toDispose.push(this.taskService.addListener2(TaskServiceEvents.Active, (e: TaskEvent) => { this.lastTaskEvent = e; })); this.toDispose.push(this.taskService.addListener2(TaskServiceEvents.Inactive, (e: TaskEvent) => { if (e.type === TaskType.SingleRun) { this.lastTaskEvent = null; } })); this.toDispose.push(this.taskService.addListener2(TaskServiceEvents.Terminated, (e: TaskEvent) => { this.lastTaskEvent = null; })); } lifecycleService.onShutdown(this.store, this); lifecycleService.onShutdown(this.dispose, this); this.toDispose.push(this.windowService.onBroadcast(this.onBroadcast, this)); } private onBroadcast(broadcast: IBroadcast): void { // attach: PH is ready to be attached to // TODO@Isidor this is a hack to just get any 'extensionHost' session. // Optimally the broadcast would contain the id of the session // We are only intersted if we have an active debug session for extensionHost const session = <RawDebugSession>this.model.getProcesses().map(p => p.session).filter(s => s.configuration.type === 'extensionHost').pop(); if (broadcast.channel === EXTENSION_ATTACH_BROADCAST_CHANNEL) { this.rawAttach(session, broadcast.payload.port); return; } if (broadcast.channel === EXTENSION_TERMINATE_BROADCAST_CHANNEL) { this.onSessionEnd(session); return; } // from this point on we require an active session if (!session) { return; } // a plugin logged output, show it inside the REPL if (broadcast.channel === EXTENSION_LOG_BROADCAST_CHANNEL) { let extensionOutput: ILogEntry = broadcast.payload; let sev = extensionOutput.severity === 'warn' ? severity.Warning : extensionOutput.severity === 'error' ? severity.Error : severity.Info; let args: any[] = []; try { let parsed = JSON.parse(extensionOutput.arguments); args.push(...Object.getOwnPropertyNames(parsed).map(o => parsed[o])); } catch (error) { args.push(extensionOutput.arguments); } // add output for each argument logged let simpleVals: any[] = []; for (let i = 0; i < args.length; i++) { let a = args[i]; // undefined gets printed as 'undefined' if (typeof a === 'undefined') { simpleVals.push('undefined'); } // null gets printed as 'null' else if (a === null) { simpleVals.push('null'); } // objects & arrays are special because we want to inspect them in the REPL else if (types.isObject(a) || Array.isArray(a)) { // flush any existing simple values logged if (simpleVals.length) { this.logToRepl(simpleVals.join(' '), sev); simpleVals = []; } // show object this.logToRepl(a, sev); } // string: watch out for % replacement directive // string substitution and formatting @ https://developer.chrome.com/devtools/docs/console else if (typeof a === 'string') { let buf = ''; for (let j = 0, len = a.length; j < len; j++) { if (a[j] === '%' && (a[j + 1] === 's' || a[j + 1] === 'i' || a[j + 1] === 'd')) { i++; // read over substitution buf += !types.isUndefinedOrNull(args[i]) ? args[i] : ''; // replace j++; // read over directive } else { buf += a[j]; } } simpleVals.push(buf); } // number or boolean is joined together else { simpleVals.push(a); } } // flush simple values if (simpleVals.length) { this.logToRepl(simpleVals.join(' '), sev); } } } private registerSessionListeners(session: RawDebugSession): void { this.toDisposeOnSessionEnd[session.getId()].push(session); this.toDisposeOnSessionEnd[session.getId()].push(session.onDidInitialize(event => { aria.status(nls.localize('debuggingStarted', "Debugging started.")); const sendConfigurationDone = () => { if (session && session.configuration.capabilities.supportsConfigurationDoneRequest) { session.configurationDone().done(null, e => { // Disconnect the debug session on configuration done error #10596 if (session) { session.disconnect().done(null, errors.onUnexpectedError); } this.messageService.show(severity.Error, e.message); }); } }; this.sendAllBreakpoints(session).done(sendConfigurationDone, sendConfigurationDone); })); this.toDisposeOnSessionEnd[session.getId()].push(session.onDidStop(event => { this.setStateAndEmit(session.getId(), debug.State.Stopped); const threadId = event.body.threadId; session.threads().then(response => { if (!response || !response.body || !response.body.threads) { return; } const rawThread = response.body.threads.filter(t => t.id === threadId).pop(); this.model.rawUpdate({ sessionId: session.getId(), thread: rawThread, threadId, stoppedDetails: event.body, allThreadsStopped: event.body.allThreadsStopped }); const process = this.model.getProcesses().filter(p => p.getId() === session.getId()).pop(); const thread = process && process.getThread(threadId); if (thread) { thread.getCallStack().then(callStack => { if (callStack.length > 0) { // focus first stack frame from top that has source location const stackFrameToFocus = arrays.first(callStack, sf => sf.source && sf.source.available, callStack[0]); this.setFocusedStackFrameAndEvaluate(stackFrameToFocus).done(null, errors.onUnexpectedError); this.windowService.getWindow().focus(); aria.alert(nls.localize('debuggingPaused', "Debugging paused, reason {0}, {1} {2}", event.body.reason, stackFrameToFocus.source ? stackFrameToFocus.source.name : '', stackFrameToFocus.lineNumber)); return this.openOrRevealSource(stackFrameToFocus.source, stackFrameToFocus.lineNumber, false, false); } else { this.setFocusedStackFrameAndEvaluate(null).done(null, errors.onUnexpectedError); } }); } }, errors.onUnexpectedError); })); this.toDisposeOnSessionEnd[session.getId()].push(session.onDidThread(event => { if (event.body.reason === 'started') { session.threads().done(response => { if (response && response.body && response.body.threads) { response.body.threads.forEach(thread => this.model.rawUpdate({ sessionId: session.getId(), threadId: thread.id, thread })); } }, errors.onUnexpectedError); } else if (event.body.reason === 'exited') { this.model.clearThreads(session.getId(), true, event.body.threadId); } })); this.toDisposeOnSessionEnd[session.getId()].push(session.onDidTerminateDebugee(event => { aria.status(nls.localize('debuggingStopped', "Debugging stopped.")); if (session && session.getId() === event.body.sessionId) { if (event.body && typeof event.body.restart === 'boolean' && event.body.restart) { const process = this.model.getProcesses().filter(p => p.getId() === session.getId()).pop(); this.restartProcess(process).done(null, err => this.messageService.show(severity.Error, err.message)); } else { session.disconnect().done(null, errors.onUnexpectedError); } } })); this.toDisposeOnSessionEnd[session.getId()].push(session.onDidContinued(event => { this.transitionToRunningState(session, event.body.allThreadsContinued ? undefined : event.body.threadId); })); this.toDisposeOnSessionEnd[session.getId()].push(session.onDidOutput(event => { if (event.body && event.body.category === 'telemetry') { // only log telemetry events from debug adapter if the adapter provided the telemetry key // and the user opted in telemetry if (this.customTelemetryService && this.telemetryService.isOptedIn) { this.customTelemetryService.publicLog(event.body.output, event.body.data); } } else if (event.body && typeof event.body.output === 'string' && event.body.output.length > 0) { this.onOutput(event); } })); this.toDisposeOnSessionEnd[session.getId()].push(session.onDidBreakpoint(event => { const id = event.body && event.body.breakpoint ? event.body.breakpoint.id : undefined; const breakpoint = this.model.getBreakpoints().filter(bp => bp.idFromAdapter === id).pop(); if (breakpoint) { this.model.updateBreakpoints({ [breakpoint.getId()]: event.body.breakpoint }); } else { const functionBreakpoint = this.model.getFunctionBreakpoints().filter(bp => bp.idFromAdapter === id).pop(); if (functionBreakpoint) { this.model.updateFunctionBreakpoints({ [functionBreakpoint.getId()]: event.body.breakpoint }); } } })); this.toDisposeOnSessionEnd[session.getId()].push(session.onDidExitAdapter(event => { // 'Run without debugging' mode VSCode must terminate the extension host. More details: #3905 if (session && session.configuration.type === 'extensionHost' && this.sessionStates[session.getId()] === debug.State.RunningNoDebug) { ipc.send('vscode:closeExtensionHostWindow', this.contextService.getWorkspace().resource.fsPath); } if (session && session.getId() === event.body.sessionId) { this.onSessionEnd(session); } })); } private onOutput(event: DebugProtocol.OutputEvent): void { const outputSeverity = event.body.category === 'stderr' ? severity.Error : event.body.category === 'console' ? severity.Warning : severity.Info; this.appendReplOutput(event.body.output, outputSeverity); } private loadBreakpoints(): debug.IBreakpoint[] { let result: debug.IBreakpoint[]; try { result = JSON.parse(this.storageService.get(DEBUG_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((breakpoint: any) => { return new model.Breakpoint(new Source(breakpoint.source.raw ? breakpoint.source.raw : { path: uri.parse(breakpoint.source.uri).fsPath, name: breakpoint.source.name }), breakpoint.desiredLineNumber || breakpoint.lineNumber, breakpoint.enabled, breakpoint.condition, breakpoint.hitCondition); }); } catch (e) { } return result || []; } private loadFunctionBreakpoints(): debug.IFunctionBreakpoint[] { let result: debug.IFunctionBreakpoint[]; try { result = JSON.parse(this.storageService.get(DEBUG_FUNCTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((fb: any) => { return new model.FunctionBreakpoint(fb.name, fb.enabled, fb.hitCondition); }); } catch (e) { } return result || []; } private loadExceptionBreakpoints(): debug.IExceptionBreakpoint[] { let result: debug.IExceptionBreakpoint[]; try { result = JSON.parse(this.storageService.get(DEBUG_EXCEPTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((exBreakpoint: any) => { return new model.ExceptionBreakpoint(exBreakpoint.filter || exBreakpoint.name, exBreakpoint.label, exBreakpoint.enabled); }); } catch (e) { } return result || []; } private loadWatchExpressions(): model.Expression[] { let result: model.Expression[]; try { result = JSON.parse(this.storageService.get(DEBUG_WATCH_EXPRESSIONS_KEY, StorageScope.WORKSPACE, '[]')).map((watchStoredData: { name: string, id: string }) => { return new model.Expression(watchStoredData.name, false, watchStoredData.id); }); } catch (e) { } return result || []; } public get state(): debug.State { if (!this.contextService.getWorkspace()) { return debug.State.Disabled; } const focusedProcess = this.viewModel.focusedProcess; if (focusedProcess) { return this.sessionStates[focusedProcess.getId()]; } const processes = this.model.getProcesses(); if (processes.length > 0) { return this.sessionStates[processes[0].getId()]; } return debug.State.Inactive; } public get onDidChangeState(): Event<void> { return this._onDidChangeState.event; } private setStateAndEmit(sessionId: string, newState: debug.State): void { this.sessionStates[sessionId] = newState; this._onDidChangeState.fire(); } public get enabled(): boolean { return !!this.contextService.getWorkspace(); } public setFocusedStackFrameAndEvaluate(focusedStackFrame: debug.IStackFrame): TPromise<void> { const processes = this.model.getProcesses(); const process = focusedStackFrame ? focusedStackFrame.thread.process : processes.length ? processes[0] : null; if (process && !focusedStackFrame) { const thread = process.getAllThreads().pop(); const callStack = thread ? thread.getCachedCallStack() : null; focusedStackFrame = callStack && callStack.length ? callStack[0] : null; } this.viewModel.setFocusedStackFrame(focusedStackFrame, process); this._onDidChangeState.fire(); if (focusedStackFrame) { return this.model.evaluateWatchExpressions(focusedStackFrame); } else { this.model.clearWatchExpressionValues(); return TPromise.as(null); } } public enableOrDisableBreakpoints(enable: boolean, breakpoint?: debug.IEnablement): TPromise<void> { if (breakpoint) { this.model.setEnablement(breakpoint, enable); if (breakpoint instanceof model.Breakpoint) { return this.sendBreakpoints((<model.Breakpoint>breakpoint).source.uri); } else if (breakpoint instanceof model.FunctionBreakpoint) { return this.sendFunctionBreakpoints(); } return this.sendExceptionBreakpoints(); } this.model.enableOrDisableAllBreakpoints(enable); return this.sendAllBreakpoints(); } public addBreakpoints(rawBreakpoints: debug.IRawBreakpoint[]): TPromise<void> { this.model.addBreakpoints(rawBreakpoints); const uris = arrays.distinct(rawBreakpoints, raw => raw.uri.toString()).map(raw => raw.uri); rawBreakpoints.forEach(rbp => aria.status(nls.localize('breakpointAdded', "Added breakpoint, line {0}, file {1}", rbp.lineNumber, rbp.uri.fsPath))); return TPromise.join(uris.map(uri => this.sendBreakpoints(uri))).then(() => void 0); } public removeBreakpoints(id?: string): TPromise<any> { 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.source.uri.fsPath))); const urisToClear = arrays.distinct(toRemove, bp => bp.source.uri.toString()).map(bp => bp.source.uri); this.model.removeBreakpoints(toRemove); return TPromise.join(urisToClear.map(uri => this.sendBreakpoints(uri))); } public setBreakpointsActivated(activated: boolean): TPromise<void> { this.model.setBreakpointsActivated(activated); return this.sendAllBreakpoints(); } public addFunctionBreakpoint(): void { this.model.addFunctionBreakpoint(''); } public renameFunctionBreakpoint(id: string, newFunctionName: string): TPromise<void> { this.model.updateFunctionBreakpoints({ [id]: { name: newFunctionName } }); return this.sendFunctionBreakpoints(); } public removeFunctionBreakpoints(id?: string): TPromise<void> { this.model.removeFunctionBreakpoints(id); return this.sendFunctionBreakpoints(); } public addReplExpression(name: string): TPromise<void> { this.telemetryService.publicLog('debugService/addReplExpression'); return this.model.addReplExpression(this.viewModel.focusedStackFrame, name) // Evaluate all watch expressions again since repl evaluation might have changed some. .then(() => this.setFocusedStackFrameAndEvaluate(this.viewModel.focusedStackFrame)); } public logToRepl(value: string | { [key: string]: any }, severity?: severity): void { this.model.logToRepl(value, severity); } public appendReplOutput(value: string, severity?: severity): void { this.model.appendReplOutput(value, severity); } public removeReplExpressions(): void { this.model.removeReplExpressions(); } public addWatchExpression(name: string): TPromise<void> { return this.model.addWatchExpression(this.viewModel.focusedStackFrame, name); } public renameWatchExpression(id: string, newName: string): TPromise<void> { return this.model.renameWatchExpression(this.viewModel.focusedStackFrame, id, newName); } public removeWatchExpressions(id?: string): void { this.model.removeWatchExpressions(id); } public createProcess(configurationOrName: debug.IConfig | string): TPromise<any> { this.removeReplExpressions(); const sessionId = uuid.generateUuid(); this.setStateAndEmit(sessionId, debug.State.Initializing); return this.textFileService.saveAll() // make sure all dirty files are saved .then(() => this.configurationService.reloadConfiguration() // make sure configuration is up to date .then(() => this.extensionService.onReady() .then(() => this.configurationManager.getConfiguration(configurationOrName) .then(configuration => { if (!configuration) { return this.configurationManager.openConfigFile(false).then(openend => { if (openend) { this.messageService.show(severity.Info, nls.localize('NewLaunchConfig', "Please set up the launch configuration file for your application.")); } }); } if (configuration.silentlyAbort) { return; } if (strings.equalsIgnoreCase(configuration.type, 'composite') && configuration.configurationNames) { return TPromise.join(configuration.configurationNames.map(name => this.createProcess(name))); } if (!this.configurationManager.getAdapter(configuration.type)) { return configuration.type ? TPromise.wrapError(new Error(nls.localize('debugTypeNotSupported', "Configured debug type '{0}' is not supported.", configuration.type))) : TPromise.wrapError(errors.create(nls.localize('debugTypeMissing', "Missing property 'type' for the chosen launch configuration."), { actions: [this.instantiationService.createInstance(debugactions.ConfigureAction, debugactions.ConfigureAction.ID, debugactions.ConfigureAction.LABEL), CloseAction] })); } return this.runPreLaunchTask(configuration.preLaunchTask).then((taskSummary: ITaskSummary) => { const errorCount = configuration.preLaunchTask ? this.markerService.getStatistics().errors : 0; const successExitCode = taskSummary && taskSummary.exitCode === 0; const failureExitCode = taskSummary && taskSummary.exitCode !== undefined && taskSummary.exitCode !== 0; if (successExitCode || (errorCount === 0 && !failureExitCode)) { return this.doCreateProcess(sessionId, configuration); } this.messageService.show(severity.Error, { message: errorCount > 1 ? nls.localize('preLaunchTaskErrors', "Build errors have been detected during preLaunchTask '{0}'.", configuration.preLaunchTask) : errorCount === 1 ? nls.localize('preLaunchTaskError', "Build error has been detected during preLaunchTask '{0}'.", configuration.preLaunchTask) : nls.localize('preLaunchTaskExitCode', "The preLaunchTask '{0}' terminated with exit code {1}.", configuration.preLaunchTask, taskSummary.exitCode), actions: [new Action('debug.continue', nls.localize('debugAnyway', "Debug Anyway"), null, true, () => { this.messageService.hideAll(); return this.doCreateProcess(sessionId, configuration); }), CloseAction] }); }, (err: TaskError) => { if (err.code !== TaskErrors.NotConfigured) { throw err; } this.messageService.show(err.severity, { message: err.message, actions: [this.taskService.configureAction(), CloseAction] }); }); })))); } private doCreateProcess(sessionId: string, configuration: debug.IExtHostConfig): TPromise<any> { return this.telemetryService.getTelemetryInfo().then(info => { const telemetryInfo: { [key: string]: string } = Object.create(null); telemetryInfo['common.vscodemachineid'] = info.machineId; telemetryInfo['common.vscodesessionid'] = info.sessionId; return telemetryInfo; }).then(data => { const adapter = this.configurationManager.getAdapter(configuration.type); const { aiKey, type } = adapter; const publisher = adapter.extensionDescription.publisher; this.customTelemetryService = null; let client: TelemetryClient; if (aiKey) { client = new TelemetryClient( uri.parse(require.toUrl('bootstrap')).fsPath, { serverName: 'Debug Telemetry', timeout: 1000 * 60 * 5, args: [`${publisher}.${type}`, JSON.stringify(data), aiKey], env: { ELECTRON_RUN_AS_NODE: 1, PIPE_LOGGING: 'true', AMD_ENTRYPOINT: 'vs/workbench/parts/debug/node/telemetryApp' } } ); const channel = client.getChannel('telemetryAppender'); const appender = new TelemetryAppenderClient(channel); this.customTelemetryService = new TelemetryService({ appender }, this.configurationService); } const session = this.instantiationService.createInstance(RawDebugSession, sessionId, configuration.debugServer, adapter, this.customTelemetryService); this.model.addProcess(configuration.name, session); this.toDisposeOnSessionEnd[session.getId()] = []; if (client) { this.toDisposeOnSessionEnd[session.getId()].push(client); } this.registerSessionListeners(session); return session.initialize({ adapterID: configuration.type, pathFormat: 'path', linesStartAt1: true, columnsStartAt1: true, supportsVariableType: true, // #8858 supportsVariablePaging: true, // #9537 supportsRunInTerminalRequest: true // #10574 }).then((result: DebugProtocol.InitializeResponse) => { if (session.disconnected) { return TPromise.wrapError(new Error(nls.localize('debugAdapterCrash', "Debug adapter process has terminated unexpectedly"))); } this.model.setExceptionBreakpoints(session.configuration.capabilities.exceptionBreakpointFilters); return configuration.request === 'attach' ? session.attach(configuration) : session.launch(configuration); }).then((result: DebugProtocol.Response) => { if (session.disconnected) { return TPromise.as(null); } if (configuration.internalConsoleOptions === 'openOnSessionStart' || (!this.viewModel.changedWorkbenchViewState && configuration.internalConsoleOptions !== 'neverOpen')) { this.panelService.openPanel(debug.REPL_ID, false).done(undefined, errors.onUnexpectedError); } if (!this.viewModel.changedWorkbenchViewState && !this.partService.isSideBarHidden()) { // We only want to change the workbench view state on the first debug session #5738 and if the side bar is not hidden this.viewModel.changedWorkbenchViewState = true; this.viewletService.openViewlet(debug.VIEWLET_ID); } // Do not change status bar to orange if we are just running without debug. if (!configuration.noDebug) { this.partService.addClass('debugging'); } this.extensionService.activateByEvent(`onDebug:${configuration.type}`).done(null, errors.onUnexpectedError); this.inDebugMode.set(true); this.transitionToRunningState(session); this.telemetryService.publicLog('debugSessionStart', { type: configuration.type, breakpointCount: this.model.getBreakpoints().length, exceptionBreakpoints: this.model.getExceptionBreakpoints(), watchExpressionsCount: this.model.getWatchExpressions().length, extensionName: `${adapter.extensionDescription.publisher}.${adapter.extensionDescription.name}`, isBuiltin: adapter.extensionDescription.isBuiltin }); }).then(undefined, (error: any) => { if (error instanceof Error && error.message === 'Canceled') { // Do not show 'canceled' error messages to the user #7906 return TPromise.as(null); } this.telemetryService.publicLog('debugMisconfiguration', { type: configuration ? configuration.type : undefined }); this.setStateAndEmit(session.getId(), debug.State.Inactive); if (!session.disconnected) { session.disconnect().done(null, errors.onUnexpectedError); } // Show the repl if some error got logged there #5870 if (this.model.getReplElements().length > 0) { this.panelService.openPanel(debug.REPL_ID, false).done(undefined, errors.onUnexpectedError); } const configureAction = this.instantiationService.createInstance(debugactions.ConfigureAction, debugactions.ConfigureAction.ID, debugactions.ConfigureAction.LABEL); const actions = (error.actions && error.actions.length) ? error.actions.concat([configureAction]) : [CloseAction, configureAction]; return TPromise.wrapError(errors.create(error.message, { actions })); }); }); } private runPreLaunchTask(taskName: string): TPromise<ITaskSummary> { if (!taskName) { return TPromise.as(null); } // run a task before starting a debug session return this.taskService.tasks().then(descriptions => { const filteredTasks = descriptions.filter(task => task.name === taskName); if (filteredTasks.length !== 1) { return TPromise.wrapError(errors.create(nls.localize('DebugTaskNotFound', "Could not find the preLaunchTask \'{0}\'.", taskName), { actions: [ this.instantiationService.createInstance(debugactions.ConfigureAction, debugactions.ConfigureAction.ID, debugactions.ConfigureAction.LABEL), this.taskService.configureAction(), CloseAction ] })); } // task is already running - nothing to do. if (this.lastTaskEvent && this.lastTaskEvent.taskName === taskName) { return TPromise.as(null); } if (this.lastTaskEvent) { // there is a different task running currently. return TPromise.wrapError(errors.create(nls.localize('differentTaskRunning', "There is a task {0} running. Can not run pre launch task {1}.", this.lastTaskEvent.taskName, taskName))); } // no task running, execute the preLaunchTask. const taskPromise = this.taskService.run(filteredTasks[0].id).then(result => { this.lastTaskEvent = null; return result; }, err => { this.lastTaskEvent = null; }); if (filteredTasks[0].isWatching) { return new TPromise((c, e) => this.taskService.addOneTimeDisposableListener(TaskServiceEvents.Inactive, () => c(null))); } return taskPromise; }); } private rawAttach(session: RawDebugSession, port: number): TPromise<any> { if (session) { return session.attach({ port }); } const sessionId = uuid.generateUuid(); this.setStateAndEmit(sessionId, debug.State.Initializing); return this.configurationManager.getConfiguration(this.viewModel.selectedConfigurationName).then((configuration: debug.IExtHostConfig) => this.doCreateProcess(sessionId, { type: configuration.type, request: 'attach', port, sourceMaps: configuration.sourceMaps, outDir: configuration.outDir, debugServer: configuration.debugServer }) ); } public restartProcess(process: debug.IProcess): TPromise<any> { return process ? process.session.disconnect(true).then(() => new TPromise<void>((c, e) => { setTimeout(() => { this.createProcess(process.name).then(() => c(null), err => e(err)); }, 300); }) ) : this.createProcess(this.viewModel.selectedConfigurationName); } private onSessionEnd(session: RawDebugSession): void { if (session) { const bpsExist = this.model.getBreakpoints().length > 0; this.telemetryService.publicLog('debugSessionStop', { type: session.configuration.type, success: session.emittedStopped || !bpsExist, sessionLengthInSeconds: session.getLengthInSeconds(), breakpointCount: this.model.getBreakpoints().length, watchExpressionsCount: this.model.getWatchExpressions().length }); } try { this.toDisposeOnSessionEnd[session.getId()] = lifecycle.dispose(this.toDisposeOnSessionEnd[session.getId()]); } catch (e) { // an internal module might be open so the dispose can throw -> ignore and continue with stop session. } this.partService.removeClass('debugging'); this.model.removeProcess(session.getId()); this.setFocusedStackFrameAndEvaluate(null).done(null, errors.onUnexpectedError); this.setStateAndEmit(session.getId(), debug.State.Inactive); // set breakpoints back to unverified since the session ended. // source reference changes across sessions, so we do not use it to persist the source. const data: { [id: string]: { line: number, verified: boolean } } = {}; this.model.getBreakpoints().forEach(bp => { delete bp.source.raw.sourceReference; data[bp.getId()] = { line: bp.lineNumber, verified: false }; }); this.model.updateBreakpoints(data); this.inDebugMode.reset(); if (!this.partService.isSideBarHidden() && this.configurationService.getConfiguration<debug.IDebugConfiguration>('debug').openExplorerOnEnd) { this.viewletService.openViewlet(EXPLORER_VIEWLET_ID).done(null, errors.onUnexpectedError); } } public getModel(): debug.IModel { return this.model; } public getViewModel(): debug.IViewModel { return this.viewModel; } public openOrRevealSource(source: Source, lineNumber: number, preserveFocus: boolean, sideBySide: boolean): TPromise<any> { const visibleEditors = this.editorService.getVisibleEditors(); for (let i = 0; i < visibleEditors.length; i++) { const fileInput = asFileEditorInput(visibleEditors[i].input); if ((fileInput && fileInput.getResource().toString() === source.uri.toString()) || (visibleEditors[i].input instanceof DebugStringEditorInput && (<DebugStringEditorInput>visibleEditors[i].input).getResource().toString() === source.uri.toString())) { const control = <editorbrowser.ICodeEditor>visibleEditors[i].getControl(); if (control) { control.revealLineInCenterIfOutsideViewport(lineNumber); control.setSelection({ startLineNumber: lineNumber, startColumn: 1, endLineNumber: lineNumber, endColumn: 1 }); this.editorGroupService.activateGroup(i); if (!preserveFocus) { this.editorGroupService.focusGroup(i); } } return TPromise.as(null); } } const process = this.viewModel.focusedProcess; if (source.inMemory) { // internal module if (source.reference !== 0 && process && source.available) { return process.session.source({ sourceReference: source.reference }).then(response => { const mime = response && response.body && response.body.mimeType ? response.body.mimeType : guessMimeTypes(source.name)[0]; const inputValue = response && response.body ? response.body.content : ''; return this.getDebugStringEditorInput(process, source, inputValue, mime); }, (err: DebugProtocol.ErrorResponse) => { // Display the error from debug adapter using a temporary editor #8836 return this.getDebugErrorEditorInput(process, source, err.message); }).then(editorInput => { return this.editorService.openEditor(editorInput, { preserveFocus, selection: { startLineNumber: lineNumber, startColumn: 1, endLineNumber: lineNumber, endColumn: 1 } }, sideBySide); }); } return this.sourceIsUnavailable(process, source, sideBySide); } return this.fileService.resolveFile(source.uri).then(() => this.editorService.openEditor({ resource: source.uri, options: { selection: { startLineNumber: lineNumber, startColumn: 1, endLineNumber: lineNumber, endColumn: 1 }, preserveFocus: preserveFocus } }, sideBySide), err => this.sourceIsUnavailable(process, source, sideBySide) ); } private sourceIsUnavailable(process: debug.IProcess, source: Source, sideBySide: boolean): TPromise<any> { this.model.sourceIsUnavailable(source); const editorInput = this.getDebugErrorEditorInput(process, source, nls.localize('debugSourceNotAvailable', "Source {0} is not available.", source.name)); return this.editorService.openEditor(editorInput, { preserveFocus: true }, sideBySide); } public getConfigurationManager(): debug.IConfigurationManager { return this.configurationManager; } private transitionToRunningState(session: RawDebugSession, threadId?: number): void { this.model.clearThreads(session.getId(), false, threadId); // TODO@Isidor remove this mess // Get a top stack frame of a stopped thread if there is any. const process = this.model.getProcesses().filter(p => p.getId() === session.getId()).pop(); const stoppedThread = process && process.getAllThreads().filter(t => t.stopped).pop(); const callStack = stoppedThread ? stoppedThread.getCachedCallStack() : null; const stackFrameToFocus = callStack && callStack.length > 0 ? callStack[0] : null; if (!stoppedThread && process) { this.setStateAndEmit(session.getId(), process.session.requestType === debug.SessionRequestType.LAUNCH_NO_DEBUG ? debug.State.RunningNoDebug : debug.State.Running); } this.setFocusedStackFrameAndEvaluate(stackFrameToFocus).done(null, errors.onUnexpectedError); } private getDebugStringEditorInput(process: debug.IProcess, source: Source, value: string, mtype: string): DebugStringEditorInput { const result = this.instantiationService.createInstance(DebugStringEditorInput, source.name, source.uri, source.origin, value, mtype, void 0); this.toDisposeOnSessionEnd[process.getId()].push(result); return result; } private getDebugErrorEditorInput(process: debug.IProcess, source: Source, value: string): DebugErrorEditorInput { const result = this.instantiationService.createInstance(DebugErrorEditorInput, source.name, value); this.toDisposeOnSessionEnd[process.getId()].push(result); return result; } private sendAllBreakpoints(session?: RawDebugSession): TPromise<any> { return TPromise.join(arrays.distinct(this.model.getBreakpoints(), bp => bp.source.uri.toString()).map(bp => this.sendBreakpoints(bp.source.uri, false, session))) .then(() => this.sendFunctionBreakpoints(session)) // send exception breakpoints at the end since some debug adapters rely on the order .then(() => this.sendExceptionBreakpoints(session)); } private sendBreakpoints(modelUri: uri, sourceModified = false, targetSession?: RawDebugSession): TPromise<void> { const sendBreakpointsToSession = (session: RawDebugSession): TPromise<void> => { if (!session.readyForBreakpoints) { return TPromise.as(null); } if (this.textFileService.isDirty(modelUri)) { // Only send breakpoints for a file once it is not dirty #8077 this.breakpointsToSendOnResourceSaved[modelUri.toString()] = true; return TPromise.as(null); } const breakpointsToSend = arrays.distinct( this.model.getBreakpoints().filter(bp => this.model.areBreakpointsActivated() && bp.enabled && bp.source.uri.toString() === modelUri.toString()), bp => `${bp.desiredLineNumber}` ); const rawSource = breakpointsToSend.length > 0 ? breakpointsToSend[0].source.raw : Source.toRawSource(modelUri, this.model); return session.setBreakpoints({ source: rawSource, lines: breakpointsToSend.map(bp => bp.desiredLineNumber), breakpoints: breakpointsToSend.map(bp => ({ line: bp.desiredLineNumber, condition: bp.condition, hitCondition: bp.hitCondition })), sourceModified }).then(response => { if (!response || !response.body) { return; } const data: { [id: string]: { line?: number, verified: boolean } } = {}; for (let i = 0; i < breakpointsToSend.length; i++) { data[breakpointsToSend[i].getId()] = response.body.breakpoints[i]; } this.model.updateBreakpoints(data); }); }; return this.sendToOneOrAllSessions(targetSession, sendBreakpointsToSession); } private sendFunctionBreakpoints(targetSession?: RawDebugSession): TPromise<void> { const sendFunctionBreakpointsToSession = (session: RawDebugSession): TPromise<void> => { if (!session.readyForBreakpoints || !session.configuration.capabilities.supportsFunctionBreakpoints) { return TPromise.as(null); } const breakpointsToSend = this.model.getFunctionBreakpoints().filter(fbp => fbp.enabled && this.model.areBreakpointsActivated()); return session.setFunctionBreakpoints({ breakpoints: breakpointsToSend }).then(response => { if (!response || !response.body) { return; } const data: { [id: string]: { name?: string, verified?: boolean } } = {}; for (let i = 0; i < breakpointsToSend.length; i++) { data[breakpointsToSend[i].getId()] = response.body.breakpoints[i]; } this.model.updateFunctionBreakpoints(data); }); }; return this.sendToOneOrAllSessions(targetSession, sendFunctionBreakpointsToSession); } private sendExceptionBreakpoints(targetSession?: RawDebugSession): TPromise<void> { const sendExceptionBreakpointsToSession = (session: RawDebugSession): TPromise<any> => { if (!session || !session.readyForBreakpoints || this.model.getExceptionBreakpoints().length === 0) { return TPromise.as(null); } const enabledExceptionBps = this.model.getExceptionBreakpoints().filter(exb => exb.enabled); return session.setExceptionBreakpoints({ filters: enabledExceptionBps.map(exb => exb.filter) }); }; return this.sendToOneOrAllSessions(targetSession, sendExceptionBreakpointsToSession); } private sendToOneOrAllSessions(session: RawDebugSession, send: (session: RawDebugSession) => TPromise<void>): TPromise<void> { if (session) { return send(session); } return TPromise.join(this.model.getProcesses().map(p => send(<RawDebugSession>p.session))).then(() => void 0); } private onFileChanges(fileChangesEvent: FileChangesEvent): void { this.model.removeBreakpoints(this.model.getBreakpoints().filter(bp => fileChangesEvent.contains(bp.source.uri, FileChangeType.DELETED))); fileChangesEvent.getUpdated().forEach(event => { if (this.breakpointsToSendOnResourceSaved[event.resource.toString()]) { this.breakpointsToSendOnResourceSaved[event.resource.toString()] = false; this.sendBreakpoints(event.resource, true).done(null, errors.onUnexpectedError); } }); } private store(): void { this.storageService.store(DEBUG_BREAKPOINTS_KEY, JSON.stringify(this.model.getBreakpoints()), StorageScope.WORKSPACE); this.storageService.store(DEBUG_BREAKPOINTS_ACTIVATED_KEY, this.model.areBreakpointsActivated() ? 'true' : 'false', StorageScope.WORKSPACE); this.storageService.store(DEBUG_FUNCTION_BREAKPOINTS_KEY, JSON.stringify(this.model.getFunctionBreakpoints()), StorageScope.WORKSPACE); this.storageService.store(DEBUG_EXCEPTION_BREAKPOINTS_KEY, JSON.stringify(this.model.getExceptionBreakpoints()), StorageScope.WORKSPACE); this.storageService.store(DEBUG_SELECTED_CONFIG_NAME_KEY, this.viewModel.selectedConfigurationName, StorageScope.WORKSPACE); this.storageService.store(DEBUG_WATCH_EXPRESSIONS_KEY, JSON.stringify(this.model.getWatchExpressions().map(we => ({ name: we.name, id: we.getId() }))), StorageScope.WORKSPACE); } public dispose(): void { Object.keys(this.toDisposeOnSessionEnd).forEach(key => lifecycle.dispose(this.toDisposeOnSessionEnd[key])); this.toDispose = lifecycle.dispose(this.toDispose); } }
src/vs/workbench/parts/debug/electron-browser/debugService.ts
1
https://github.com/microsoft/vscode/commit/a5ba48b76595d703ffbc26f108fd9f5acef154f9
[ 0.9980790615081787, 0.03991130739450455, 0.00016273811343126, 0.0001995268976315856, 0.17838379740715027 ]
{ "id": 2, "code_window": [ "\t\tthis.setFocusedStackFrameAndEvaluate(null).done(null, errors.onUnexpectedError);\n", "\t\tthis.setStateAndEmit(session.getId(), debug.State.Inactive);\n", "\n", "\t\t// set breakpoints back to unverified since the session ended.\n", "\t\t// source reference changes across sessions, so we do not use it to persist the source.\n", "\t\tconst data: { [id: string]: { line: number, verified: boolean } } = {};\n", "\t\tthis.model.getBreakpoints().forEach(bp => {\n", "\t\t\tdelete bp.source.raw.sourceReference;\n", "\t\t\tdata[bp.getId()] = { line: bp.lineNumber, verified: false };\n", "\t\t});\n", "\t\tthis.model.updateBreakpoints(data);\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [ "\t\tif (this.model.getProcesses().length === 0) {\n", "\t\t\tthis.partService.removeClass('debugging');\n", "\t\t\t// set breakpoints back to unverified since the session ended.\n", "\t\t\t// source reference changes across sessions, so we do not use it to persist the source.\n", "\t\t\tconst data: { [id: string]: { line: number, verified: boolean } } = {};\n", "\t\t\tthis.model.getBreakpoints().forEach(bp => {\n", "\t\t\t\tdelete bp.source.raw.sourceReference;\n", "\t\t\t\tdata[bp.getId()] = { line: bp.lineNumber, verified: false };\n", "\t\t\t});\n", "\t\t\tthis.model.updateBreakpoints(data);\n" ], "file_path": "src/vs/workbench/parts/debug/electron-browser/debugService.ts", "type": "replace", "edit_start_line_idx": 812 }
/*--------------------------------------------------------------------------------------------- * 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 { LanguageConfigurationRegistry, CommentRule } from 'vs/editor/common/modes/languageConfigurationRegistry'; import { MockMode } from 'vs/editor/test/common/mocks/mockMode'; export class CommentMode extends MockMode { constructor(commentsConfig: CommentRule) { super(); LanguageConfigurationRegistry.register(this.getId(), { comments: commentsConfig }); } }
src/vs/editor/test/common/testModes.ts
0
https://github.com/microsoft/vscode/commit/a5ba48b76595d703ffbc26f108fd9f5acef154f9
[ 0.00017801023204810917, 0.0001732931414153427, 0.0001685760507825762, 0.0001732931414153427, 0.000004717090632766485 ]
{ "id": 2, "code_window": [ "\t\tthis.setFocusedStackFrameAndEvaluate(null).done(null, errors.onUnexpectedError);\n", "\t\tthis.setStateAndEmit(session.getId(), debug.State.Inactive);\n", "\n", "\t\t// set breakpoints back to unverified since the session ended.\n", "\t\t// source reference changes across sessions, so we do not use it to persist the source.\n", "\t\tconst data: { [id: string]: { line: number, verified: boolean } } = {};\n", "\t\tthis.model.getBreakpoints().forEach(bp => {\n", "\t\t\tdelete bp.source.raw.sourceReference;\n", "\t\t\tdata[bp.getId()] = { line: bp.lineNumber, verified: false };\n", "\t\t});\n", "\t\tthis.model.updateBreakpoints(data);\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [ "\t\tif (this.model.getProcesses().length === 0) {\n", "\t\t\tthis.partService.removeClass('debugging');\n", "\t\t\t// set breakpoints back to unverified since the session ended.\n", "\t\t\t// source reference changes across sessions, so we do not use it to persist the source.\n", "\t\t\tconst data: { [id: string]: { line: number, verified: boolean } } = {};\n", "\t\t\tthis.model.getBreakpoints().forEach(bp => {\n", "\t\t\t\tdelete bp.source.raw.sourceReference;\n", "\t\t\t\tdata[bp.getId()] = { line: bp.lineNumber, verified: false };\n", "\t\t\t});\n", "\t\t\tthis.model.updateBreakpoints(data);\n" ], "file_path": "src/vs/workbench/parts/debug/electron-browser/debugService.ts", "type": "replace", "edit_start_line_idx": 812 }
/*--------------------------------------------------------------------------------------------- * 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 assert = require('assert'); import WinJS = require('vs/base/common/winjs.base'); import { TestInstantiationService } from 'vs/test/utils/instantiationTestUtils'; import { DeferredAction } from 'vs/platform/actions/common/actions'; import Actions = require('vs/base/common/actions'); import { AsyncDescriptor } from 'vs/platform/instantiation/common/descriptors'; import { IEventService } from 'vs/platform/event/common/event'; export class TestAction extends Actions.Action { private service; private first: string; private second: string; constructor(first: string, second: string, @IEventService eventService: IEventService) { super(first); this.service = eventService; this.first = first; this.second = second; } public run(): WinJS.Promise { return WinJS.TPromise.as((!!this.service && !!this.first && !!this.second) ? true : false); } } suite('Platform actions', () => { test('DeferredAction', (done) => { let instantiationService: TestInstantiationService = new TestInstantiationService(); instantiationService.stub(IEventService); let action = new DeferredAction( instantiationService, new AsyncDescriptor<Actions.Action>('vs/platform/actions/test/common/actions.test', 'TestAction', 'my.id', 'Second'), 'my.test.action', 'Hello World', 'css' ); assert.strictEqual(action.id, 'my.test.action'); action.run().then((result) => { assert.strictEqual(result, true); assert.strictEqual(action.id, 'my.id'); done(); }); }); });
src/vs/platform/actions/test/common/actions.test.ts
0
https://github.com/microsoft/vscode/commit/a5ba48b76595d703ffbc26f108fd9f5acef154f9
[ 0.00017695051792543381, 0.0001738317805575207, 0.000168425845913589, 0.00017471335013397038, 0.0000027639146082947263 ]
{ "id": 2, "code_window": [ "\t\tthis.setFocusedStackFrameAndEvaluate(null).done(null, errors.onUnexpectedError);\n", "\t\tthis.setStateAndEmit(session.getId(), debug.State.Inactive);\n", "\n", "\t\t// set breakpoints back to unverified since the session ended.\n", "\t\t// source reference changes across sessions, so we do not use it to persist the source.\n", "\t\tconst data: { [id: string]: { line: number, verified: boolean } } = {};\n", "\t\tthis.model.getBreakpoints().forEach(bp => {\n", "\t\t\tdelete bp.source.raw.sourceReference;\n", "\t\t\tdata[bp.getId()] = { line: bp.lineNumber, verified: false };\n", "\t\t});\n", "\t\tthis.model.updateBreakpoints(data);\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [ "\t\tif (this.model.getProcesses().length === 0) {\n", "\t\t\tthis.partService.removeClass('debugging');\n", "\t\t\t// set breakpoints back to unverified since the session ended.\n", "\t\t\t// source reference changes across sessions, so we do not use it to persist the source.\n", "\t\t\tconst data: { [id: string]: { line: number, verified: boolean } } = {};\n", "\t\t\tthis.model.getBreakpoints().forEach(bp => {\n", "\t\t\t\tdelete bp.source.raw.sourceReference;\n", "\t\t\t\tdata[bp.getId()] = { line: bp.lineNumber, verified: false };\n", "\t\t\t});\n", "\t\t\tthis.model.updateBreakpoints(data);\n" ], "file_path": "src/vs/workbench/parts/debug/electron-browser/debugService.ts", "type": "replace", "edit_start_line_idx": 812 }
/*--------------------------------------------------------------------------------------------- * 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 { TPromise } from 'vs/base/common/winjs.base'; export interface IWatcherRequest { basePath: string; ignored: string[]; verboseLogging: boolean; } export interface IWatcherService { watch(request: IWatcherRequest): TPromise<void>; }
src/vs/workbench/services/files/node/watcher/unix/watcher.ts
0
https://github.com/microsoft/vscode/commit/a5ba48b76595d703ffbc26f108fd9f5acef154f9
[ 0.00017539352120365947, 0.00017368613043799996, 0.00017197872512042522, 0.00017368613043799996, 0.0000017073980416171253 ]
{ "id": 3, "code_window": [ "\n", "\t\tthis.inDebugMode.reset();\n", "\n" ], "labels": [ "keep", "replace", "keep" ], "after_edit": [ "\t\t\tthis.inDebugMode.reset();\n" ], "file_path": "src/vs/workbench/parts/debug/electron-browser/debugService.ts", "type": "replace", "edit_start_line_idx": 821 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { TPromise } from 'vs/base/common/winjs.base'; import nls = require('vs/nls'); import lifecycle = require('vs/base/common/lifecycle'); import Event, { Emitter } from 'vs/base/common/event'; import uuid = require('vs/base/common/uuid'); import objects = require('vs/base/common/objects'); import severity from 'vs/base/common/severity'; import types = require('vs/base/common/types'); import arrays = require('vs/base/common/arrays'); import { ISuggestion } from 'vs/editor/common/modes'; import { Position } from 'vs/editor/common/core/position'; import debug = require('vs/workbench/parts/debug/common/debug'); import { Source } from 'vs/workbench/parts/debug/common/debugSource'; const MAX_REPL_LENGTH = 10000; const UNKNOWN_SOURCE_LABEL = nls.localize('unknownSource', "Unknown Source"); function massageValue(value: string): string { return value ? value.replace(/\n/g, '\\n').replace(/\r/g, '\\r').replace(/\t/g, '\\t') : value; } export function evaluateExpression(stackFrame: debug.IStackFrame, expression: Expression, context: string): TPromise<Expression> { if (!stackFrame || !stackFrame.thread.process) { expression.value = context === 'repl' ? nls.localize('startDebugFirst', "Please start a debug session to evaluate") : Expression.DEFAULT_VALUE; expression.available = false; expression.reference = 0; return TPromise.as(expression); } expression.stackFrame = stackFrame; return stackFrame.thread.process.session.evaluate({ expression: expression.name, frameId: stackFrame ? stackFrame.frameId : undefined, context }).then(response => { expression.available = !!(response && response.body); if (response && response.body) { expression.value = response.body.result; expression.reference = response.body.variablesReference; expression.namedVariables = response.body.namedVariables; expression.indexedVariables = response.body.indexedVariables; expression.type = response.body.type; } return expression; }, err => { expression.value = err.message; expression.available = false; expression.reference = 0; return expression; }); } export class OutputElement implements debug.ITreeElement { private static ID_COUNTER = 0; constructor(private id = OutputElement.ID_COUNTER++) { // noop } public getId(): string { return `outputelement:${this.id}`; } } export class ValueOutputElement extends OutputElement { constructor( public value: string, public severity: severity, public category?: string, public counter: number = 1 ) { super(); } } export class KeyValueOutputElement extends OutputElement { private static MAX_CHILDREN = 1000; // upper bound of children per value private children: debug.ITreeElement[]; private _valueName: string; constructor(public key: string, public valueObj: any, public annotation?: string) { super(); this._valueName = null; } public get value(): string { if (this._valueName === null) { if (this.valueObj === null) { this._valueName = 'null'; } else if (Array.isArray(this.valueObj)) { this._valueName = `Array[${this.valueObj.length}]`; } else if (types.isObject(this.valueObj)) { this._valueName = 'Object'; } else if (types.isString(this.valueObj)) { this._valueName = `"${massageValue(this.valueObj)}"`; } else { this._valueName = String(this.valueObj); } if (!this._valueName) { this._valueName = ''; } } return this._valueName; } public getChildren(): debug.ITreeElement[] { if (!this.children) { if (Array.isArray(this.valueObj)) { this.children = (<any[]>this.valueObj).slice(0, KeyValueOutputElement.MAX_CHILDREN).map((v, index) => new KeyValueOutputElement(String(index), v, null)); } else if (types.isObject(this.valueObj)) { this.children = Object.getOwnPropertyNames(this.valueObj).slice(0, KeyValueOutputElement.MAX_CHILDREN).map(key => new KeyValueOutputElement(key, this.valueObj[key], null)); } else { this.children = []; } } return this.children; } } export abstract class ExpressionContainer implements debug.IExpressionContainer { public static allValues: { [id: string]: string } = {}; // Use chunks to support variable paging #9537 private static BASE_CHUNK_SIZE = 100; public valueChanged: boolean; private children: TPromise<debug.IExpression[]>; private _value: string; constructor( public stackFrame: debug.IStackFrame, public reference: number, private id: string, private cacheChildren: boolean, public namedVariables: number, public indexedVariables: number, private startOfVariables = 0 ) { // noop } public getChildren(): TPromise<debug.IExpression[]> { if (!this.cacheChildren || !this.children) { // only variables with reference > 0 have children. if (this.reference <= 0) { this.children = TPromise.as([]); } else { if (!this.getChildrenInChunks) { return this.fetchVariables(undefined, undefined, undefined); } // Check if object has named variables, fetch them independent from indexed variables #9670 this.children = (!!this.namedVariables ? this.fetchVariables(undefined, undefined, 'named') : TPromise.as([])).then(childrenArray => { // Use a dynamic chunk size based on the number of elements #9774 let chunkSize = ExpressionContainer.BASE_CHUNK_SIZE; while (this.indexedVariables > chunkSize * ExpressionContainer.BASE_CHUNK_SIZE) { chunkSize *= ExpressionContainer.BASE_CHUNK_SIZE; } if (this.indexedVariables > chunkSize) { // There are a lot of children, create fake intermediate values that represent chunks #9537 const numberOfChunks = Math.ceil(this.indexedVariables / chunkSize); for (let i = 0; i < numberOfChunks; i++) { const start = this.startOfVariables + i * chunkSize; const count = Math.min(chunkSize, this.indexedVariables - i * chunkSize); childrenArray.push(new Variable(this.stackFrame, this, this.reference, `[${start}..${start + count - 1}]`, '', '', null, count, null, true, start)); } return childrenArray; } return this.fetchVariables(this.startOfVariables, this.indexedVariables, 'indexed') .then(variables => childrenArray.concat(variables)); }); } } return this.children; } public getId(): string { return this.id; } public get value(): string { return this._value; } private fetchVariables(start: number, count: number, filter: 'indexed' | 'named'): TPromise<Variable[]> { return this.stackFrame.thread.process.session.variables({ variablesReference: this.reference, start, count, filter }).then(response => { return response && response.body && response.body.variables ? arrays.distinct(response.body.variables.filter(v => !!v), v => v.name).map( v => new Variable(this.stackFrame, this, v.variablesReference, v.name, v.evaluateName, v.value, v.namedVariables, v.indexedVariables, v.type) ) : []; }, (e: Error) => [new Variable(this.stackFrame, this, 0, null, e.message, '', 0, 0, null, false)]); } // The adapter explicitly sents the children count of an expression only if there are lots of children which should be chunked. private get getChildrenInChunks(): boolean { return !!this.indexedVariables; } public set value(value: string) { this._value = massageValue(value); this.valueChanged = ExpressionContainer.allValues[this.getId()] && ExpressionContainer.allValues[this.getId()] !== Expression.DEFAULT_VALUE && ExpressionContainer.allValues[this.getId()] !== value; ExpressionContainer.allValues[this.getId()] = value; } } export class Expression extends ExpressionContainer implements debug.IExpression { static DEFAULT_VALUE = 'not available'; public available: boolean; public type: string; constructor(public name: string, cacheChildren: boolean, id = uuid.generateUuid()) { super(null, 0, id, cacheChildren, 0, 0); this.value = Expression.DEFAULT_VALUE; this.available = false; } } export class Variable extends ExpressionContainer implements debug.IExpression { // Used to show the error message coming from the adapter when setting the value #7807 public errorMessage: string; private static NOT_PROPERTY_SYNTAX = /^[a-zA-Z_][a-zA-Z0-9_]*$/; private static ARRAY_ELEMENT_SYNTAX = /\[.*\]$/; constructor( stackFrame: debug.IStackFrame, public parent: debug.IExpressionContainer, reference: number, public name: string, private _evaluateName: string, value: string, namedVariables: number, indexedVariables: number, public type: string = null, public available = true, startOfVariables = 0 ) { super(stackFrame, reference, `variable:${parent.getId()}:${name}:${reference}`, true, namedVariables, indexedVariables, startOfVariables); this.value = massageValue(value); } public get evaluateName(): string { if (this._evaluateName) { return this._evaluateName; } let names = [this.name]; let v = this.parent; while (v instanceof Variable || v instanceof Expression) { names.push((<Variable>v).name); v = (<Variable>v).parent; } names = names.reverse(); let result = null; names.forEach(name => { if (!result) { result = name; } else if (Variable.ARRAY_ELEMENT_SYNTAX.test(name) || (this.stackFrame.thread.process.session.configuration.type === 'node' && !Variable.NOT_PROPERTY_SYNTAX.test(name))) { // use safe way to access node properties a['property_name']. Also handles array elements. result = name && name.indexOf('[') === 0 ? `${result}${name}` : `${result}['${name}']`; } else { result = `${result}.${name}`; } }); return result; } public setVariable(value: string): TPromise<any> { return this.stackFrame.thread.process.session.setVariable({ name: this.name, value, variablesReference: this.parent.reference }).then(response => { if (response && response.body) { this.value = response.body.value; this.type = response.body.type || this.type; } // TODO@Isidor notify stackFrame that a change has happened so watch expressions get revelauted }, err => { this.errorMessage = err.message; }); } } export class Scope extends ExpressionContainer implements debug.IScope { constructor( stackFrame: debug.IStackFrame, public name: string, reference: number, public expensive: boolean, namedVariables: number, indexedVariables: number ) { super(stackFrame, reference, `scope:${stackFrame.getId()}:${name}:${reference}`, true, namedVariables, indexedVariables); } } export class StackFrame implements debug.IStackFrame { private scopes: TPromise<Scope[]>; constructor( public thread: debug.IThread, public frameId: number, public source: Source, public name: string, public lineNumber: number, public column: number ) { this.scopes = null; } public getId(): string { return `stackframe:${this.thread.getId()}:${this.frameId}`; } public getScopes(): TPromise<debug.IScope[]> { if (!this.scopes) { this.scopes = this.thread.process.session.scopes({ frameId: this.frameId }).then(response => { return response && response.body && response.body.scopes ? response.body.scopes.map(rs => new Scope(this, rs.name, rs.variablesReference, rs.expensive, rs.namedVariables, rs.indexedVariables)) : []; }, err => []); } return this.scopes; } public restart(): TPromise<any> { return this.thread.process.session.restartFrame({ frameId: this.frameId }); } public completions(text: string, position: Position, overwriteBefore: number): TPromise<ISuggestion[]> { if (!this.thread.process.session.configuration.capabilities.supportsCompletionsRequest) { return TPromise.as([]); } return this.thread.process.session.completions({ frameId: this.frameId, text, column: position.column, line: position.lineNumber }).then(response => { return response && response.body && response.body.targets ? response.body.targets.map(item => (<ISuggestion>{ label: item.label, insertText: item.text || item.label, type: item.type, overwriteBefore: item.length || overwriteBefore })) : []; }, err => []); } } export class Thread implements debug.IThread { private promisedCallStack: TPromise<debug.IStackFrame[]>; private cachedCallStack: debug.IStackFrame[]; public stoppedDetails: debug.IRawStoppedDetails; public stopped: boolean; constructor(public process: debug.IProcess, public name: string, public threadId: number) { this.promisedCallStack = undefined; this.stoppedDetails = undefined; this.cachedCallStack = undefined; this.stopped = false; } public getId(): string { return `thread:${this.process.getId()}:${this.name}:${this.threadId}`; } public clearCallStack(): void { this.promisedCallStack = undefined; this.cachedCallStack = undefined; } public getCachedCallStack(): debug.IStackFrame[] { return this.cachedCallStack; } public getCallStack(getAdditionalStackFrames = false): TPromise<debug.IStackFrame[]> { if (!this.stopped) { return TPromise.as([]); } if (!this.promisedCallStack) { this.promisedCallStack = this.getCallStackImpl(0).then(callStack => { this.cachedCallStack = callStack; return callStack; }); } else if (getAdditionalStackFrames) { this.promisedCallStack = this.promisedCallStack.then(callStackFirstPart => this.getCallStackImpl(callStackFirstPart.length).then(callStackSecondPart => { this.cachedCallStack = callStackFirstPart.concat(callStackSecondPart); return this.cachedCallStack; })); } return this.promisedCallStack; } private getCallStackImpl(startFrame: number): TPromise<debug.IStackFrame[]> { return this.process.session.stackTrace({ threadId: this.threadId, startFrame, levels: 20 }).then(response => { if (!response || !response.body) { return []; } this.stoppedDetails.totalFrames = response.body.totalFrames; return response.body.stackFrames.map((rsf, level) => { if (!rsf) { return new StackFrame(this, 0, new Source({ name: UNKNOWN_SOURCE_LABEL }, false), nls.localize('unknownStack', "Unknown stack location"), undefined, undefined); } return new StackFrame(this, rsf.id, rsf.source ? new Source(rsf.source) : new Source({ name: UNKNOWN_SOURCE_LABEL }, false), rsf.name, rsf.line, rsf.column); }); }, (err: Error) => { this.stoppedDetails.framesErrorMessage = err.message; return []; }); } public next(): TPromise<any> { return this.process.session.next({ threadId: this.threadId }); } public stepIn(): TPromise<any> { return this.process.session.stepIn({ threadId: this.threadId }); } public stepOut(): TPromise<any> { return this.process.session.stepOut({ threadId: this.threadId }); } public stepBack(): TPromise<any> { return this.process.session.stepBack({ threadId: this.threadId }); } public continue(): TPromise<any> { return this.process.session.continue({ threadId: this.threadId }); } public pause(): TPromise<any> { return this.process.session.pause({ threadId: this.threadId }); } } export class Process implements debug.IProcess { private threads: { [reference: number]: debug.IThread; }; constructor(public name: string, private _session: debug.ISession & debug.ITreeElement) { this.threads = {}; } public get session(): debug.ISession { return this._session; } public getThread(threadId: number): debug.IThread { return this.threads[threadId]; } public getAllThreads(): debug.IThread[] { return Object.keys(this.threads).map(key => this.threads[key]); } public getId(): string { return this._session.getId();; } public rawUpdate(data: debug.IRawModelUpdate): void { if (data.thread && !this.threads[data.threadId]) { // A new thread came in, initialize it. this.threads[data.threadId] = new Thread(this, data.thread.name, data.thread.id); } if (data.stoppedDetails) { // Set the availability of the threads' callstacks depending on // whether the thread is stopped or not if (data.allThreadsStopped) { Object.keys(this.threads).forEach(ref => { // Only update the details if all the threads are stopped // because we don't want to overwrite the details of other // threads that have stopped for a different reason this.threads[ref].stoppedDetails = objects.clone(data.stoppedDetails); this.threads[ref].stopped = true; this.threads[ref].clearCallStack(); }); } else { // One thread is stopped, only update that thread. this.threads[data.threadId].stoppedDetails = data.stoppedDetails; this.threads[data.threadId].clearCallStack(); this.threads[data.threadId].stopped = true; } } } public clearThreads(removeThreads: boolean, reference: number = undefined): void { if (reference) { if (this.threads[reference]) { this.threads[reference].clearCallStack(); this.threads[reference].stoppedDetails = undefined; this.threads[reference].stopped = false; if (removeThreads) { delete this.threads[reference]; } } } else { Object.keys(this.threads).forEach(ref => { this.threads[ref].clearCallStack(); this.threads[ref].stoppedDetails = undefined; this.threads[ref].stopped = false; }); if (removeThreads) { this.threads = {}; ExpressionContainer.allValues = {}; } } } public sourceIsUnavailable(source: Source): void { Object.keys(this.threads).forEach(key => { if (this.threads[key].getCachedCallStack()) { this.threads[key].getCachedCallStack().forEach(stackFrame => { if (stackFrame.source.uri.toString() === source.uri.toString()) { stackFrame.source.available = false; } }); } }); } } export class Breakpoint implements debug.IBreakpoint { public lineNumber: number; public verified: boolean; public idFromAdapter: number; public message: string; private id: string; constructor( public source: Source, public desiredLineNumber: number, public enabled: boolean, public condition: string, public hitCondition: string ) { if (enabled === undefined) { this.enabled = true; } this.lineNumber = this.desiredLineNumber; this.verified = false; this.id = uuid.generateUuid(); } public getId(): string { return this.id; } } export class FunctionBreakpoint implements debug.IFunctionBreakpoint { private id: string; public verified: boolean; public idFromAdapter: number; constructor(public name: string, public enabled: boolean, public hitCondition: string) { this.verified = false; this.id = uuid.generateUuid(); } public getId(): string { return this.id; } } export class ExceptionBreakpoint implements debug.IExceptionBreakpoint { private id: string; constructor(public filter: string, public label: string, public enabled: boolean) { this.id = uuid.generateUuid(); } public getId(): string { return this.id; } } export class Model implements debug.IModel { private processes: Process[]; private toDispose: lifecycle.IDisposable[]; private replElements: debug.ITreeElement[]; private _onDidChangeBreakpoints: Emitter<void>; private _onDidChangeCallStack: Emitter<void>; private _onDidChangeWatchExpressions: Emitter<debug.IExpression>; private _onDidChangeREPLElements: Emitter<void>; constructor( private breakpoints: debug.IBreakpoint[], private breakpointsActivated: boolean, private functionBreakpoints: debug.IFunctionBreakpoint[], private exceptionBreakpoints: debug.IExceptionBreakpoint[], private watchExpressions: Expression[] ) { this.processes = []; this.replElements = []; this.toDispose = []; this._onDidChangeBreakpoints = new Emitter<void>(); this._onDidChangeCallStack = new Emitter<void>(); this._onDidChangeWatchExpressions = new Emitter<debug.IExpression>(); this._onDidChangeREPLElements = new Emitter<void>(); } public getId(): string { return 'root'; } public getProcesses(): Process[] { return this.processes; } public addProcess(name: string, session: debug.ISession & debug.ITreeElement): void { this.processes.push(new Process(name, session)); } public removeProcess(id: string): void { this.processes = this.processes.filter(p => p.getId() !== id); this._onDidChangeCallStack.fire(); } public get onDidChangeBreakpoints(): Event<void> { return this._onDidChangeBreakpoints.event; } public get onDidChangeCallStack(): Event<void> { return this._onDidChangeCallStack.event; } public get onDidChangeWatchExpressions(): Event<debug.IExpression> { return this._onDidChangeWatchExpressions.event; } public get onDidChangeReplElements(): Event<void> { return this._onDidChangeREPLElements.event; } public rawUpdate(data: debug.IRawModelUpdate): void { let process = this.processes.filter(p => p.getId() === data.sessionId).pop(); if (process) { process.rawUpdate(data); this._onDidChangeCallStack.fire(); } } public clearThreads(id: string, removeThreads: boolean, reference: number = undefined): void { const process = this.processes.filter(p => p.getId() === id).pop(); if (process) { process.clearThreads(removeThreads, reference); this._onDidChangeCallStack.fire(); } } public getBreakpoints(): debug.IBreakpoint[] { return this.breakpoints; } public getFunctionBreakpoints(): debug.IFunctionBreakpoint[] { return this.functionBreakpoints; } public getExceptionBreakpoints(): debug.IExceptionBreakpoint[] { return this.exceptionBreakpoints; } public setExceptionBreakpoints(data: DebugProtocol.ExceptionBreakpointsFilter[]): void { if (data) { this.exceptionBreakpoints = data.map(d => { const ebp = this.exceptionBreakpoints.filter(ebp => ebp.filter === d.filter).pop(); return new ExceptionBreakpoint(d.filter, d.label, ebp ? ebp.enabled : d.default); }); } } public areBreakpointsActivated(): boolean { return this.breakpointsActivated; } public setBreakpointsActivated(activated: boolean): void { this.breakpointsActivated = activated; this._onDidChangeBreakpoints.fire(); } public addBreakpoints(rawData: debug.IRawBreakpoint[]): void { this.breakpoints = this.breakpoints.concat(rawData.map(rawBp => new Breakpoint(new Source(Source.toRawSource(rawBp.uri, this)), rawBp.lineNumber, rawBp.enabled, rawBp.condition, rawBp.hitCondition))); this.breakpointsActivated = true; this._onDidChangeBreakpoints.fire(); } public removeBreakpoints(toRemove: debug.IBreakpoint[]): void { this.breakpoints = this.breakpoints.filter(bp => !toRemove.some(toRemove => toRemove.getId() === bp.getId())); this._onDidChangeBreakpoints.fire(); } public updateBreakpoints(data: { [id: string]: DebugProtocol.Breakpoint }): void { this.breakpoints.forEach(bp => { const bpData = data[bp.getId()]; if (bpData) { bp.lineNumber = bpData.line ? bpData.line : bp.lineNumber; bp.verified = bpData.verified; bp.idFromAdapter = bpData.id; bp.message = bpData.message; } }); this._onDidChangeBreakpoints.fire(); } public setEnablement(element: debug.IEnablement, enable: boolean): void { element.enabled = enable; if (element instanceof Breakpoint && !element.enabled) { var breakpoint = <Breakpoint>element; breakpoint.lineNumber = breakpoint.desiredLineNumber; breakpoint.verified = false; } this._onDidChangeBreakpoints.fire(); } public enableOrDisableAllBreakpoints(enable: boolean): void { this.breakpoints.forEach(bp => { bp.enabled = enable; if (!enable) { bp.lineNumber = bp.desiredLineNumber; bp.verified = false; } }); this.exceptionBreakpoints.forEach(ebp => ebp.enabled = enable); this.functionBreakpoints.forEach(fbp => fbp.enabled = enable); this._onDidChangeBreakpoints.fire(); } public addFunctionBreakpoint(functionName: string): void { this.functionBreakpoints.push(new FunctionBreakpoint(functionName, true, null)); this._onDidChangeBreakpoints.fire(); } public updateFunctionBreakpoints(data: { [id: string]: { name?: string, verified?: boolean; id?: number; hitCondition?: string } }): void { this.functionBreakpoints.forEach(fbp => { const fbpData = data[fbp.getId()]; if (fbpData) { fbp.name = fbpData.name || fbp.name; fbp.verified = fbpData.verified; fbp.idFromAdapter = fbpData.id; fbp.hitCondition = fbpData.hitCondition; } }); this._onDidChangeBreakpoints.fire(); } public removeFunctionBreakpoints(id?: string): void { this.functionBreakpoints = id ? this.functionBreakpoints.filter(fbp => fbp.getId() !== id) : []; this._onDidChangeBreakpoints.fire(); } public getReplElements(): debug.ITreeElement[] { return this.replElements; } public addReplExpression(stackFrame: debug.IStackFrame, name: string): TPromise<void> { const expression = new Expression(name, true); this.addReplElements([expression]); return evaluateExpression(stackFrame, expression, 'repl') .then(() => this._onDidChangeREPLElements.fire()); } public logToRepl(value: string | { [key: string]: any }, severity?: severity): void { let elements: OutputElement[] = []; let previousOutput = this.replElements.length && (<ValueOutputElement>this.replElements[this.replElements.length - 1]); // string message if (typeof value === 'string') { if (value && value.trim() && previousOutput && previousOutput.value === value && previousOutput.severity === severity) { previousOutput.counter++; // we got the same output (but not an empty string when trimmed) so we just increment the counter } else { let lines = value.trim().split('\n'); lines.forEach((line, index) => { elements.push(new ValueOutputElement(line, severity)); }); } } // key-value output else { elements.push(new KeyValueOutputElement((<any>value).prototype, value, nls.localize('snapshotObj', "Only primitive values are shown for this object."))); } if (elements.length) { this.addReplElements(elements); } this._onDidChangeREPLElements.fire(); } public appendReplOutput(value: string, severity?: severity): void { const elements: OutputElement[] = []; let previousOutput = this.replElements.length && (<ValueOutputElement>this.replElements[this.replElements.length - 1]); let lines = value.split('\n'); let groupTogether = !!previousOutput && (previousOutput.category === 'output' && severity === previousOutput.severity); if (groupTogether) { // append to previous line if same group previousOutput.value += lines.shift(); } else if (previousOutput && previousOutput.value === '') { // remove potential empty lines between different output types this.replElements.pop(); } // fill in lines as output value elements lines.forEach((line, index) => { elements.push(new ValueOutputElement(line, severity, 'output')); }); this.addReplElements(elements); this._onDidChangeREPLElements.fire(); } private addReplElements(newElements: debug.ITreeElement[]): void { this.replElements.push(...newElements); if (this.replElements.length > MAX_REPL_LENGTH) { this.replElements.splice(0, this.replElements.length - MAX_REPL_LENGTH); } } public removeReplExpressions(): void { if (this.replElements.length > 0) { this.replElements = []; this._onDidChangeREPLElements.fire(); } } public getWatchExpressions(): Expression[] { return this.watchExpressions; } public addWatchExpression(stackFrame: debug.IStackFrame, name: string): TPromise<void> { const we = new Expression(name, false); this.watchExpressions.push(we); if (!name) { this._onDidChangeWatchExpressions.fire(we); return TPromise.as(null); } return this.evaluateWatchExpressions(stackFrame, we.getId()); } public renameWatchExpression(stackFrame: debug.IStackFrame, id: string, newName: string): TPromise<void> { const filtered = this.watchExpressions.filter(we => we.getId() === id); if (filtered.length === 1) { filtered[0].name = newName; return evaluateExpression(stackFrame, filtered[0], 'watch').then(() => { this._onDidChangeWatchExpressions.fire(filtered[0]); }); } return TPromise.as(null); } public evaluateWatchExpressions(stackFrame: debug.IStackFrame, id: string = null): TPromise<void> { if (id) { const filtered = this.watchExpressions.filter(we => we.getId() === id); if (filtered.length !== 1) { return TPromise.as(null); } return evaluateExpression(stackFrame, filtered[0], 'watch').then(() => { this._onDidChangeWatchExpressions.fire(filtered[0]); }); } return TPromise.join(this.watchExpressions.map(we => evaluateExpression(stackFrame, we, 'watch'))).then(() => { this._onDidChangeWatchExpressions.fire(); }); } public clearWatchExpressionValues(): void { this.watchExpressions.forEach(we => { we.value = Expression.DEFAULT_VALUE; we.available = false; we.reference = 0; }); this._onDidChangeWatchExpressions.fire(); } public removeWatchExpressions(id: string = null): void { this.watchExpressions = id ? this.watchExpressions.filter(we => we.getId() !== id) : []; this._onDidChangeWatchExpressions.fire(); } public sourceIsUnavailable(source: Source): void { this.processes.forEach(p => p.sourceIsUnavailable(source)); this._onDidChangeCallStack.fire(); } public dispose(): void { this.toDispose = lifecycle.dispose(this.toDispose); } }
src/vs/workbench/parts/debug/common/debugModel.ts
1
https://github.com/microsoft/vscode/commit/a5ba48b76595d703ffbc26f108fd9f5acef154f9
[ 0.35023126006126404, 0.003886183025315404, 0.00016522510850336403, 0.00016932241851463914, 0.03572293743491173 ]
{ "id": 3, "code_window": [ "\n", "\t\tthis.inDebugMode.reset();\n", "\n" ], "labels": [ "keep", "replace", "keep" ], "after_edit": [ "\t\t\tthis.inDebugMode.reset();\n" ], "file_path": "src/vs/workbench/parts/debug/electron-browser/debugService.ts", "type": "replace", "edit_start_line_idx": 821 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "json.npm.error.repoaccess": "对 NPM 存储库发出的请求失败: {0}", "json.npm.latestversion": "包的当前最新版本", "json.npm.majorversion": "与最新的主要版本(1.x.x)匹配", "json.npm.minorversion": "与最新的次要版本(1.2.x)匹配", "json.npm.package.hover": "{0}", "json.npm.version.hover": "最新版本: {0}", "json.package.default": "默认 package.json" }
i18n/chs/src/vs/languages/json/common/contributions/packageJSONContribution.i18n.json
0
https://github.com/microsoft/vscode/commit/a5ba48b76595d703ffbc26f108fd9f5acef154f9
[ 0.00016999278159346431, 0.00016924778174143285, 0.00016850278188940138, 0.00016924778174143285, 7.449998520314693e-7 ]
{ "id": 3, "code_window": [ "\n", "\t\tthis.inDebugMode.reset();\n", "\n" ], "labels": [ "keep", "replace", "keep" ], "after_edit": [ "\t\t\tthis.inDebugMode.reset();\n" ], "file_path": "src/vs/workbench/parts/debug/electron-browser/debugService.ts", "type": "replace", "edit_start_line_idx": 821 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "cmdCreate": "建立 jsconfig.json", "hintCreate": "建立 jsconfig.json,為整個工作區提供用更豐富的 IntelliSense 與程式碼巡覽功能。", "hintCreate.tooltip": "建立 jsconfig.json,在整個工作區啟用更豐富的 IntelliSense 及程式碼巡覽。", "hintExclude": "如需更好的效能,請排除包含大量檔案的資料夾,例如: {0}", "hintExclude.generic": "如需更好的效能,請排除包含大量檔案的資料夾。", "hintExclude.tooltip": "如需更佳的效能,請排除內含太多檔案的資料夾。", "ignore.cmdCreate": "忽略", "jsconfig.heading": "// 請參閱 https://go.microsoft.com/fwlink/?LinkId=759670\n\t// 以取得關於 jsconfig.json 格式的文件", "large.label": "設定排除項目", "open": "設定排除項目" }
i18n/cht/extensions/typescript/out/utils/projectStatus.i18n.json
0
https://github.com/microsoft/vscode/commit/a5ba48b76595d703ffbc26f108fd9f5acef154f9
[ 0.00016703776782378554, 0.0001656174863455817, 0.00016419720486737788, 0.0001656174863455817, 0.000001420281478203833 ]
{ "id": 3, "code_window": [ "\n", "\t\tthis.inDebugMode.reset();\n", "\n" ], "labels": [ "keep", "replace", "keep" ], "after_edit": [ "\t\t\tthis.inDebugMode.reset();\n" ], "file_path": "src/vs/workbench/parts/debug/electron-browser/debugService.ts", "type": "replace", "edit_start_line_idx": 821 }
/*--------------------------------------------------------------------------------------------- * 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 nls from 'vs/nls'; import { IHTMLContentElement } from 'vs/base/common/htmlContent'; import { IJSONSchema } from 'vs/base/common/jsonSchema'; import { Keybinding } from 'vs/base/common/keybinding'; import * as platform from 'vs/base/common/platform'; import { toDisposable } from 'vs/base/common/lifecycle'; import { IExtensionMessageCollector, ExtensionsRegistry } from 'vs/platform/extensions/common/extensionsRegistry'; import { Extensions, IJSONContributionRegistry } from 'vs/platform/jsonschemas/common/jsonContributionRegistry'; import { KeybindingService } from 'vs/platform/keybinding/browser/keybindingServiceImpl'; import { IStatusbarService } from 'vs/platform/statusbar/common/statusbar'; import { IOSupport } from 'vs/platform/keybinding/common/keybindingResolver'; import { ICommandService } from 'vs/platform/commands/common/commands'; import { IKeybindingItem, IUserFriendlyKeybinding } from 'vs/platform/keybinding/common/keybinding'; import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { IKeybindingRule, KeybindingsRegistry } from 'vs/platform/keybinding/common/keybindingsRegistry'; import { Registry } from 'vs/platform/platform'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { getNativeLabelProvider, getNativeAriaLabelProvider } from 'vs/workbench/services/keybinding/electron-browser/nativeKeymap'; import { IMessageService } from 'vs/platform/message/common/message'; import { ConfigWatcher } from 'vs/base/node/config'; import { IEnvironmentService } from 'vs/platform/environment/common/environment'; interface ContributedKeyBinding { command: string; key: string; when?: string; mac?: string; linux?: string; win?: string; } function isContributedKeyBindingsArray(thing: ContributedKeyBinding | ContributedKeyBinding[]): thing is ContributedKeyBinding[] { return Array.isArray(thing); } function isValidContributedKeyBinding(keyBinding: ContributedKeyBinding, rejects: string[]): boolean { if (!keyBinding) { rejects.push(nls.localize('nonempty', "expected non-empty value.")); return false; } if (typeof keyBinding.command !== 'string') { rejects.push(nls.localize('requirestring', "property `{0}` is mandatory and must be of type `string`", 'command')); return false; } if (typeof keyBinding.key !== 'string') { rejects.push(nls.localize('requirestring', "property `{0}` is mandatory and must be of type `string`", 'key')); return false; } if (keyBinding.when && typeof keyBinding.when !== 'string') { rejects.push(nls.localize('optstring', "property `{0}` can be omitted or must be of type `string`", 'when')); return false; } if (keyBinding.mac && typeof keyBinding.mac !== 'string') { rejects.push(nls.localize('optstring', "property `{0}` can be omitted or must be of type `string`", 'mac')); return false; } if (keyBinding.linux && typeof keyBinding.linux !== 'string') { rejects.push(nls.localize('optstring', "property `{0}` can be omitted or must be of type `string`", 'linux')); return false; } if (keyBinding.win && typeof keyBinding.win !== 'string') { rejects.push(nls.localize('optstring', "property `{0}` can be omitted or must be of type `string`", 'win')); return false; } return true; } let keybindingType: IJSONSchema = { type: 'object', default: { command: '', key: '' }, properties: { command: { description: nls.localize('vscode.extension.contributes.keybindings.command', 'Identifier of the command to run when keybinding is triggered.'), type: 'string' }, key: { description: nls.localize('vscode.extension.contributes.keybindings.key', 'Key or key sequence (separate keys with plus-sign and sequences with space, e.g Ctrl+O and Ctrl+L L for a chord'), type: 'string' }, mac: { description: nls.localize('vscode.extension.contributes.keybindings.mac', 'Mac specific key or key sequence.'), type: 'string' }, linux: { description: nls.localize('vscode.extension.contributes.keybindings.linux', 'Linux specific key or key sequence.'), type: 'string' }, win: { description: nls.localize('vscode.extension.contributes.keybindings.win', 'Windows specific key or key sequence.'), type: 'string' }, when: { description: nls.localize('vscode.extension.contributes.keybindings.when', 'Condition when the key is active.'), type: 'string' } } }; let keybindingsExtPoint = ExtensionsRegistry.registerExtensionPoint<ContributedKeyBinding | ContributedKeyBinding[]>('keybindings', { description: nls.localize('vscode.extension.contributes.keybindings', "Contributes keybindings."), oneOf: [ keybindingType, { type: 'array', items: keybindingType } ] }); export class WorkbenchKeybindingService extends KeybindingService { private userKeybindings: ConfigWatcher<IUserFriendlyKeybinding[]>; constructor( domNode: HTMLElement, @IContextKeyService contextKeyService: IContextKeyService, @ICommandService commandService: ICommandService, @ITelemetryService private telemetryService: ITelemetryService, @IMessageService messageService: IMessageService, @IEnvironmentService environmentService: IEnvironmentService, @IStatusbarService statusBarService: IStatusbarService ) { super(contextKeyService, commandService, messageService, statusBarService); this.userKeybindings = new ConfigWatcher(environmentService.appKeybindingsPath, { defaultConfig: [] }); this.toDispose.push(toDisposable(() => this.userKeybindings.dispose())); keybindingsExtPoint.setHandler((extensions) => { let commandAdded = false; for (let extension of extensions) { commandAdded = this._handleKeybindingsExtensionPointUser(extension.description.isBuiltin, extension.value, extension.collector) || commandAdded; } if (commandAdded) { this.updateResolver(); } }); this.toDispose.push(this.userKeybindings.onDidUpdateConfiguration(() => this.updateResolver())); this._beginListening(domNode); } private _safeGetConfig(): IUserFriendlyKeybinding[] { let rawConfig = this.userKeybindings.getConfig(); if (Array.isArray(rawConfig)) { return rawConfig; } return []; } public customKeybindingsCount(): number { let userKeybindings = this._safeGetConfig(); return userKeybindings.length; } protected _getExtraKeybindings(isFirstTime: boolean): IKeybindingItem[] { let extraUserKeybindings: IUserFriendlyKeybinding[] = this._safeGetConfig(); if (!isFirstTime) { let cnt = extraUserKeybindings.length; this.telemetryService.publicLog('customKeybindingsChanged', { keyCount: cnt }); } return extraUserKeybindings.map((k, i) => IOSupport.readKeybindingItem(k, i)); } public getLabelFor(keybinding: Keybinding): string { return keybinding.toCustomLabel(getNativeLabelProvider()); } public getHTMLLabelFor(keybinding: Keybinding): IHTMLContentElement[] { return keybinding.toCustomHTMLLabel(getNativeLabelProvider()); } public getAriaLabelFor(keybinding: Keybinding): string { return keybinding.toCustomLabel(getNativeAriaLabelProvider()); } public getElectronAcceleratorFor(keybinding: Keybinding): string { if (platform.isWindows) { // electron menus always do the correct rendering on Windows return super.getElectronAcceleratorFor(keybinding); } let usLabel = keybinding._toUSLabel(); let label = this.getLabelFor(keybinding); if (usLabel !== label) { // electron menus are incorrect in rendering (linux) and in rendering and interpreting (mac) // for non US standard keyboard layouts return null; } return super.getElectronAcceleratorFor(keybinding); } private _handleKeybindingsExtensionPointUser(isBuiltin: boolean, keybindings: ContributedKeyBinding | ContributedKeyBinding[], collector: IExtensionMessageCollector): boolean { if (isContributedKeyBindingsArray(keybindings)) { let commandAdded = false; for (let i = 0, len = keybindings.length; i < len; i++) { commandAdded = this._handleKeybinding(isBuiltin, i + 1, keybindings[i], collector) || commandAdded; } return commandAdded; } else { return this._handleKeybinding(isBuiltin, 1, keybindings, collector); } } private _handleKeybinding(isBuiltin: boolean, idx: number, keybindings: ContributedKeyBinding, collector: IExtensionMessageCollector): boolean { let rejects: string[] = []; let commandAdded = false; if (isValidContributedKeyBinding(keybindings, rejects)) { let rule = this._asCommandRule(isBuiltin, idx++, keybindings); if (rule) { KeybindingsRegistry.registerKeybindingRule(rule); commandAdded = true; } } if (rejects.length > 0) { collector.error(nls.localize( 'invalid.keybindings', "Invalid `contributes.{0}`: {1}", keybindingsExtPoint.name, rejects.join('\n') )); } return commandAdded; } private _asCommandRule(isBuiltin: boolean, idx: number, binding: ContributedKeyBinding): IKeybindingRule { let {command, when, key, mac, linux, win} = binding; let weight: number; if (isBuiltin) { weight = KeybindingsRegistry.WEIGHT.builtinExtension(idx); } else { weight = KeybindingsRegistry.WEIGHT.externalExtension(idx); } let desc = { id: command, when: IOSupport.readKeybindingWhen(when), weight: weight, primary: IOSupport.readKeybinding(key), mac: mac && { primary: IOSupport.readKeybinding(mac) }, linux: linux && { primary: IOSupport.readKeybinding(linux) }, win: win && { primary: IOSupport.readKeybinding(win) } }; if (!desc.primary && !desc.mac && !desc.linux && !desc.win) { return; } return desc; } } let schemaId = 'vscode://schemas/keybindings'; let schema: IJSONSchema = { 'id': schemaId, 'type': 'array', 'title': nls.localize('keybindings.json.title', "Keybindings configuration"), 'items': { 'required': ['key'], 'type': 'object', 'defaultSnippets': [{ 'body': { 'key': '{{_}}', 'command': '{{_}}', 'when': '{{_}}' } }], 'properties': { 'key': { 'type': 'string', 'description': nls.localize('keybindings.json.key', 'Key or key sequence (separated by space)'), }, 'command': { 'description': nls.localize('keybindings.json.command', 'Name of the command to execute'), }, 'when': { 'type': 'string', 'description': nls.localize('keybindings.json.when', 'Condition when the key is active.') } } } }; let schemaRegistry = <IJSONContributionRegistry>Registry.as(Extensions.JSONContribution); schemaRegistry.registerSchema(schemaId, schema);
src/vs/workbench/services/keybinding/electron-browser/keybindingService.ts
0
https://github.com/microsoft/vscode/commit/a5ba48b76595d703ffbc26f108fd9f5acef154f9
[ 0.0007851814152672887, 0.00019742970471270382, 0.00016585554112680256, 0.00016871027764864266, 0.00011114621884189546 ]
{ "id": 4, "code_window": [ "\n", "\t\tif (!this.partService.isSideBarHidden() && this.configurationService.getConfiguration<debug.IDebugConfiguration>('debug').openExplorerOnEnd) {\n", "\t\t\tthis.viewletService.openViewlet(EXPLORER_VIEWLET_ID).done(null, errors.onUnexpectedError);\n", "\t\t}\n", "\t}\n", "\n", "\tpublic getModel(): debug.IModel {\n" ], "labels": [ "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tif (!this.partService.isSideBarHidden() && this.configurationService.getConfiguration<debug.IDebugConfiguration>('debug').openExplorerOnEnd) {\n", "\t\t\t\tthis.viewletService.openViewlet(EXPLORER_VIEWLET_ID).done(null, errors.onUnexpectedError);\n", "\t\t\t}\n" ], "file_path": "src/vs/workbench/parts/debug/electron-browser/debugService.ts", "type": "replace", "edit_start_line_idx": 823 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import nls = require('vs/nls'); import lifecycle = require('vs/base/common/lifecycle'); import { guessMimeTypes } from 'vs/base/common/mime'; import Event, { Emitter } from 'vs/base/common/event'; import * as strings from 'vs/base/common/strings'; import uuid = require('vs/base/common/uuid'); import uri from 'vs/base/common/uri'; import { Action } from 'vs/base/common/actions'; import arrays = require('vs/base/common/arrays'); import types = require('vs/base/common/types'); import errors = require('vs/base/common/errors'); import severity from 'vs/base/common/severity'; import { TPromise } from 'vs/base/common/winjs.base'; import aria = require('vs/base/browser/ui/aria/aria'); import { Client as TelemetryClient } from 'vs/base/parts/ipc/node/ipc.cp'; import editorbrowser = require('vs/editor/browser/editorBrowser'); 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/platform/extensions/common/extensions'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IFileService, FileChangesEvent, FileChangeType, EventType } from 'vs/platform/files/common/files'; import { IEventService } from 'vs/platform/event/common/event'; import { IMessageService, CloseAction } from 'vs/platform/message/common/message'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { TelemetryService } from 'vs/platform/telemetry/common/telemetryService'; import { TelemetryAppenderClient } from 'vs/platform/telemetry/common/telemetryIpc'; import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage'; import { IEditorGroupService } from 'vs/workbench/services/group/common/groupService'; import { asFileEditorInput } from 'vs/workbench/common/editor'; import debug = require('vs/workbench/parts/debug/common/debug'); import { RawDebugSession } from 'vs/workbench/parts/debug/electron-browser/rawDebugSession'; import model = require('vs/workbench/parts/debug/common/debugModel'); import { DebugStringEditorInput, DebugErrorEditorInput } from 'vs/workbench/parts/debug/browser/debugEditorInputs'; import viewmodel = require('vs/workbench/parts/debug/common/debugViewModel'); import debugactions = require('vs/workbench/parts/debug/browser/debugActions'); import { ConfigurationManager } from 'vs/workbench/parts/debug/node/debugConfigurationManager'; import { Source } from 'vs/workbench/parts/debug/common/debugSource'; import { ITaskService, TaskEvent, TaskType, TaskServiceEvents, ITaskSummary } from 'vs/workbench/parts/tasks/common/taskService'; import { TaskError, TaskErrors } from 'vs/workbench/parts/tasks/common/taskSystem'; import { VIEWLET_ID as EXPLORER_VIEWLET_ID } from 'vs/workbench/parts/files/common/files'; import { IViewletService } from 'vs/workbench/services/viewlet/common/viewletService'; import { IPanelService } from 'vs/workbench/services/panel/common/panelService'; import { IPartService } from 'vs/workbench/services/part/common/partService'; import { ITextFileService } from 'vs/workbench/services/textfile/common/textfiles'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace'; import { IWorkbenchEditorService } from 'vs/workbench/services/editor/common/editorService'; import { IWindowService, IBroadcast } from 'vs/workbench/services/window/electron-browser/windowService'; import { ILogEntry, EXTENSION_LOG_BROADCAST_CHANNEL, EXTENSION_ATTACH_BROADCAST_CHANNEL, EXTENSION_TERMINATE_BROADCAST_CHANNEL } from 'vs/workbench/services/extensions/electron-browser/extensionHost'; import { ipcRenderer as ipc } from 'electron'; const DEBUG_BREAKPOINTS_KEY = 'debug.breakpoint'; const DEBUG_BREAKPOINTS_ACTIVATED_KEY = 'debug.breakpointactivated'; const DEBUG_FUNCTION_BREAKPOINTS_KEY = 'debug.functionbreakpoint'; const DEBUG_EXCEPTION_BREAKPOINTS_KEY = 'debug.exceptionbreakpoint'; const DEBUG_WATCH_EXPRESSIONS_KEY = 'debug.watchexpressions'; const DEBUG_SELECTED_CONFIG_NAME_KEY = 'debug.selectedconfigname'; export class DebugService implements debug.IDebugService { public _serviceBrand: any; private sessionStates: { [id: string]: debug.State }; private _onDidChangeState: Emitter<void>; private model: model.Model; private viewModel: viewmodel.ViewModel; private configurationManager: ConfigurationManager; private customTelemetryService: ITelemetryService; private lastTaskEvent: TaskEvent; private toDispose: lifecycle.IDisposable[]; private toDisposeOnSessionEnd: { [id: string]: lifecycle.IDisposable[] }; private inDebugMode: IContextKey<boolean>; private breakpointsToSendOnResourceSaved: { [uri: string]: boolean }; constructor( @IStorageService private storageService: IStorageService, @IWorkbenchEditorService private editorService: IWorkbenchEditorService, @ITextFileService private textFileService: ITextFileService, @IViewletService private viewletService: IViewletService, @IPanelService private panelService: IPanelService, @IFileService private fileService: IFileService, @IMessageService private messageService: IMessageService, @IPartService private partService: IPartService, @IWindowService private windowService: IWindowService, @ITelemetryService private telemetryService: ITelemetryService, @IWorkspaceContextService private contextService: IWorkspaceContextService, @IContextKeyService contextKeyService: IContextKeyService, @IEditorGroupService private editorGroupService: IEditorGroupService, @IEventService eventService: IEventService, @ILifecycleService lifecycleService: ILifecycleService, @IInstantiationService private instantiationService: IInstantiationService, @IExtensionService private extensionService: IExtensionService, @IMarkerService private markerService: IMarkerService, @ITaskService private taskService: ITaskService, @IConfigurationService private configurationService: IConfigurationService ) { this.toDispose = []; this.toDisposeOnSessionEnd = {}; this.breakpointsToSendOnResourceSaved = {}; this._onDidChangeState = new Emitter<void>(); this.sessionStates = {}; this.configurationManager = this.instantiationService.createInstance(ConfigurationManager); this.inDebugMode = debug.CONTEXT_IN_DEBUG_MODE.bindTo(contextKeyService); this.model = new model.Model(this.loadBreakpoints(), this.storageService.getBoolean(DEBUG_BREAKPOINTS_ACTIVATED_KEY, StorageScope.WORKSPACE, true), this.loadFunctionBreakpoints(), this.loadExceptionBreakpoints(), this.loadWatchExpressions()); this.toDispose.push(this.model); this.viewModel = new viewmodel.ViewModel(this.storageService.get(DEBUG_SELECTED_CONFIG_NAME_KEY, StorageScope.WORKSPACE, null)); this.registerListeners(eventService, lifecycleService); } private registerListeners(eventService: IEventService, lifecycleService: ILifecycleService): void { this.toDispose.push(eventService.addListener2(EventType.FILE_CHANGES, (e: FileChangesEvent) => this.onFileChanges(e))); if (this.taskService) { this.toDispose.push(this.taskService.addListener2(TaskServiceEvents.Active, (e: TaskEvent) => { this.lastTaskEvent = e; })); this.toDispose.push(this.taskService.addListener2(TaskServiceEvents.Inactive, (e: TaskEvent) => { if (e.type === TaskType.SingleRun) { this.lastTaskEvent = null; } })); this.toDispose.push(this.taskService.addListener2(TaskServiceEvents.Terminated, (e: TaskEvent) => { this.lastTaskEvent = null; })); } lifecycleService.onShutdown(this.store, this); lifecycleService.onShutdown(this.dispose, this); this.toDispose.push(this.windowService.onBroadcast(this.onBroadcast, this)); } private onBroadcast(broadcast: IBroadcast): void { // attach: PH is ready to be attached to // TODO@Isidor this is a hack to just get any 'extensionHost' session. // Optimally the broadcast would contain the id of the session // We are only intersted if we have an active debug session for extensionHost const session = <RawDebugSession>this.model.getProcesses().map(p => p.session).filter(s => s.configuration.type === 'extensionHost').pop(); if (broadcast.channel === EXTENSION_ATTACH_BROADCAST_CHANNEL) { this.rawAttach(session, broadcast.payload.port); return; } if (broadcast.channel === EXTENSION_TERMINATE_BROADCAST_CHANNEL) { this.onSessionEnd(session); return; } // from this point on we require an active session if (!session) { return; } // a plugin logged output, show it inside the REPL if (broadcast.channel === EXTENSION_LOG_BROADCAST_CHANNEL) { let extensionOutput: ILogEntry = broadcast.payload; let sev = extensionOutput.severity === 'warn' ? severity.Warning : extensionOutput.severity === 'error' ? severity.Error : severity.Info; let args: any[] = []; try { let parsed = JSON.parse(extensionOutput.arguments); args.push(...Object.getOwnPropertyNames(parsed).map(o => parsed[o])); } catch (error) { args.push(extensionOutput.arguments); } // add output for each argument logged let simpleVals: any[] = []; for (let i = 0; i < args.length; i++) { let a = args[i]; // undefined gets printed as 'undefined' if (typeof a === 'undefined') { simpleVals.push('undefined'); } // null gets printed as 'null' else if (a === null) { simpleVals.push('null'); } // objects & arrays are special because we want to inspect them in the REPL else if (types.isObject(a) || Array.isArray(a)) { // flush any existing simple values logged if (simpleVals.length) { this.logToRepl(simpleVals.join(' '), sev); simpleVals = []; } // show object this.logToRepl(a, sev); } // string: watch out for % replacement directive // string substitution and formatting @ https://developer.chrome.com/devtools/docs/console else if (typeof a === 'string') { let buf = ''; for (let j = 0, len = a.length; j < len; j++) { if (a[j] === '%' && (a[j + 1] === 's' || a[j + 1] === 'i' || a[j + 1] === 'd')) { i++; // read over substitution buf += !types.isUndefinedOrNull(args[i]) ? args[i] : ''; // replace j++; // read over directive } else { buf += a[j]; } } simpleVals.push(buf); } // number or boolean is joined together else { simpleVals.push(a); } } // flush simple values if (simpleVals.length) { this.logToRepl(simpleVals.join(' '), sev); } } } private registerSessionListeners(session: RawDebugSession): void { this.toDisposeOnSessionEnd[session.getId()].push(session); this.toDisposeOnSessionEnd[session.getId()].push(session.onDidInitialize(event => { aria.status(nls.localize('debuggingStarted', "Debugging started.")); const sendConfigurationDone = () => { if (session && session.configuration.capabilities.supportsConfigurationDoneRequest) { session.configurationDone().done(null, e => { // Disconnect the debug session on configuration done error #10596 if (session) { session.disconnect().done(null, errors.onUnexpectedError); } this.messageService.show(severity.Error, e.message); }); } }; this.sendAllBreakpoints(session).done(sendConfigurationDone, sendConfigurationDone); })); this.toDisposeOnSessionEnd[session.getId()].push(session.onDidStop(event => { this.setStateAndEmit(session.getId(), debug.State.Stopped); const threadId = event.body.threadId; session.threads().then(response => { if (!response || !response.body || !response.body.threads) { return; } const rawThread = response.body.threads.filter(t => t.id === threadId).pop(); this.model.rawUpdate({ sessionId: session.getId(), thread: rawThread, threadId, stoppedDetails: event.body, allThreadsStopped: event.body.allThreadsStopped }); const process = this.model.getProcesses().filter(p => p.getId() === session.getId()).pop(); const thread = process && process.getThread(threadId); if (thread) { thread.getCallStack().then(callStack => { if (callStack.length > 0) { // focus first stack frame from top that has source location const stackFrameToFocus = arrays.first(callStack, sf => sf.source && sf.source.available, callStack[0]); this.setFocusedStackFrameAndEvaluate(stackFrameToFocus).done(null, errors.onUnexpectedError); this.windowService.getWindow().focus(); aria.alert(nls.localize('debuggingPaused', "Debugging paused, reason {0}, {1} {2}", event.body.reason, stackFrameToFocus.source ? stackFrameToFocus.source.name : '', stackFrameToFocus.lineNumber)); return this.openOrRevealSource(stackFrameToFocus.source, stackFrameToFocus.lineNumber, false, false); } else { this.setFocusedStackFrameAndEvaluate(null).done(null, errors.onUnexpectedError); } }); } }, errors.onUnexpectedError); })); this.toDisposeOnSessionEnd[session.getId()].push(session.onDidThread(event => { if (event.body.reason === 'started') { session.threads().done(response => { if (response && response.body && response.body.threads) { response.body.threads.forEach(thread => this.model.rawUpdate({ sessionId: session.getId(), threadId: thread.id, thread })); } }, errors.onUnexpectedError); } else if (event.body.reason === 'exited') { this.model.clearThreads(session.getId(), true, event.body.threadId); } })); this.toDisposeOnSessionEnd[session.getId()].push(session.onDidTerminateDebugee(event => { aria.status(nls.localize('debuggingStopped', "Debugging stopped.")); if (session && session.getId() === event.body.sessionId) { if (event.body && typeof event.body.restart === 'boolean' && event.body.restart) { const process = this.model.getProcesses().filter(p => p.getId() === session.getId()).pop(); this.restartProcess(process).done(null, err => this.messageService.show(severity.Error, err.message)); } else { session.disconnect().done(null, errors.onUnexpectedError); } } })); this.toDisposeOnSessionEnd[session.getId()].push(session.onDidContinued(event => { this.transitionToRunningState(session, event.body.allThreadsContinued ? undefined : event.body.threadId); })); this.toDisposeOnSessionEnd[session.getId()].push(session.onDidOutput(event => { if (event.body && event.body.category === 'telemetry') { // only log telemetry events from debug adapter if the adapter provided the telemetry key // and the user opted in telemetry if (this.customTelemetryService && this.telemetryService.isOptedIn) { this.customTelemetryService.publicLog(event.body.output, event.body.data); } } else if (event.body && typeof event.body.output === 'string' && event.body.output.length > 0) { this.onOutput(event); } })); this.toDisposeOnSessionEnd[session.getId()].push(session.onDidBreakpoint(event => { const id = event.body && event.body.breakpoint ? event.body.breakpoint.id : undefined; const breakpoint = this.model.getBreakpoints().filter(bp => bp.idFromAdapter === id).pop(); if (breakpoint) { this.model.updateBreakpoints({ [breakpoint.getId()]: event.body.breakpoint }); } else { const functionBreakpoint = this.model.getFunctionBreakpoints().filter(bp => bp.idFromAdapter === id).pop(); if (functionBreakpoint) { this.model.updateFunctionBreakpoints({ [functionBreakpoint.getId()]: event.body.breakpoint }); } } })); this.toDisposeOnSessionEnd[session.getId()].push(session.onDidExitAdapter(event => { // 'Run without debugging' mode VSCode must terminate the extension host. More details: #3905 if (session && session.configuration.type === 'extensionHost' && this.sessionStates[session.getId()] === debug.State.RunningNoDebug) { ipc.send('vscode:closeExtensionHostWindow', this.contextService.getWorkspace().resource.fsPath); } if (session && session.getId() === event.body.sessionId) { this.onSessionEnd(session); } })); } private onOutput(event: DebugProtocol.OutputEvent): void { const outputSeverity = event.body.category === 'stderr' ? severity.Error : event.body.category === 'console' ? severity.Warning : severity.Info; this.appendReplOutput(event.body.output, outputSeverity); } private loadBreakpoints(): debug.IBreakpoint[] { let result: debug.IBreakpoint[]; try { result = JSON.parse(this.storageService.get(DEBUG_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((breakpoint: any) => { return new model.Breakpoint(new Source(breakpoint.source.raw ? breakpoint.source.raw : { path: uri.parse(breakpoint.source.uri).fsPath, name: breakpoint.source.name }), breakpoint.desiredLineNumber || breakpoint.lineNumber, breakpoint.enabled, breakpoint.condition, breakpoint.hitCondition); }); } catch (e) { } return result || []; } private loadFunctionBreakpoints(): debug.IFunctionBreakpoint[] { let result: debug.IFunctionBreakpoint[]; try { result = JSON.parse(this.storageService.get(DEBUG_FUNCTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((fb: any) => { return new model.FunctionBreakpoint(fb.name, fb.enabled, fb.hitCondition); }); } catch (e) { } return result || []; } private loadExceptionBreakpoints(): debug.IExceptionBreakpoint[] { let result: debug.IExceptionBreakpoint[]; try { result = JSON.parse(this.storageService.get(DEBUG_EXCEPTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((exBreakpoint: any) => { return new model.ExceptionBreakpoint(exBreakpoint.filter || exBreakpoint.name, exBreakpoint.label, exBreakpoint.enabled); }); } catch (e) { } return result || []; } private loadWatchExpressions(): model.Expression[] { let result: model.Expression[]; try { result = JSON.parse(this.storageService.get(DEBUG_WATCH_EXPRESSIONS_KEY, StorageScope.WORKSPACE, '[]')).map((watchStoredData: { name: string, id: string }) => { return new model.Expression(watchStoredData.name, false, watchStoredData.id); }); } catch (e) { } return result || []; } public get state(): debug.State { if (!this.contextService.getWorkspace()) { return debug.State.Disabled; } const focusedProcess = this.viewModel.focusedProcess; if (focusedProcess) { return this.sessionStates[focusedProcess.getId()]; } const processes = this.model.getProcesses(); if (processes.length > 0) { return this.sessionStates[processes[0].getId()]; } return debug.State.Inactive; } public get onDidChangeState(): Event<void> { return this._onDidChangeState.event; } private setStateAndEmit(sessionId: string, newState: debug.State): void { this.sessionStates[sessionId] = newState; this._onDidChangeState.fire(); } public get enabled(): boolean { return !!this.contextService.getWorkspace(); } public setFocusedStackFrameAndEvaluate(focusedStackFrame: debug.IStackFrame): TPromise<void> { const processes = this.model.getProcesses(); const process = focusedStackFrame ? focusedStackFrame.thread.process : processes.length ? processes[0] : null; if (process && !focusedStackFrame) { const thread = process.getAllThreads().pop(); const callStack = thread ? thread.getCachedCallStack() : null; focusedStackFrame = callStack && callStack.length ? callStack[0] : null; } this.viewModel.setFocusedStackFrame(focusedStackFrame, process); this._onDidChangeState.fire(); if (focusedStackFrame) { return this.model.evaluateWatchExpressions(focusedStackFrame); } else { this.model.clearWatchExpressionValues(); return TPromise.as(null); } } public enableOrDisableBreakpoints(enable: boolean, breakpoint?: debug.IEnablement): TPromise<void> { if (breakpoint) { this.model.setEnablement(breakpoint, enable); if (breakpoint instanceof model.Breakpoint) { return this.sendBreakpoints((<model.Breakpoint>breakpoint).source.uri); } else if (breakpoint instanceof model.FunctionBreakpoint) { return this.sendFunctionBreakpoints(); } return this.sendExceptionBreakpoints(); } this.model.enableOrDisableAllBreakpoints(enable); return this.sendAllBreakpoints(); } public addBreakpoints(rawBreakpoints: debug.IRawBreakpoint[]): TPromise<void> { this.model.addBreakpoints(rawBreakpoints); const uris = arrays.distinct(rawBreakpoints, raw => raw.uri.toString()).map(raw => raw.uri); rawBreakpoints.forEach(rbp => aria.status(nls.localize('breakpointAdded', "Added breakpoint, line {0}, file {1}", rbp.lineNumber, rbp.uri.fsPath))); return TPromise.join(uris.map(uri => this.sendBreakpoints(uri))).then(() => void 0); } public removeBreakpoints(id?: string): TPromise<any> { 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.source.uri.fsPath))); const urisToClear = arrays.distinct(toRemove, bp => bp.source.uri.toString()).map(bp => bp.source.uri); this.model.removeBreakpoints(toRemove); return TPromise.join(urisToClear.map(uri => this.sendBreakpoints(uri))); } public setBreakpointsActivated(activated: boolean): TPromise<void> { this.model.setBreakpointsActivated(activated); return this.sendAllBreakpoints(); } public addFunctionBreakpoint(): void { this.model.addFunctionBreakpoint(''); } public renameFunctionBreakpoint(id: string, newFunctionName: string): TPromise<void> { this.model.updateFunctionBreakpoints({ [id]: { name: newFunctionName } }); return this.sendFunctionBreakpoints(); } public removeFunctionBreakpoints(id?: string): TPromise<void> { this.model.removeFunctionBreakpoints(id); return this.sendFunctionBreakpoints(); } public addReplExpression(name: string): TPromise<void> { this.telemetryService.publicLog('debugService/addReplExpression'); return this.model.addReplExpression(this.viewModel.focusedStackFrame, name) // Evaluate all watch expressions again since repl evaluation might have changed some. .then(() => this.setFocusedStackFrameAndEvaluate(this.viewModel.focusedStackFrame)); } public logToRepl(value: string | { [key: string]: any }, severity?: severity): void { this.model.logToRepl(value, severity); } public appendReplOutput(value: string, severity?: severity): void { this.model.appendReplOutput(value, severity); } public removeReplExpressions(): void { this.model.removeReplExpressions(); } public addWatchExpression(name: string): TPromise<void> { return this.model.addWatchExpression(this.viewModel.focusedStackFrame, name); } public renameWatchExpression(id: string, newName: string): TPromise<void> { return this.model.renameWatchExpression(this.viewModel.focusedStackFrame, id, newName); } public removeWatchExpressions(id?: string): void { this.model.removeWatchExpressions(id); } public createProcess(configurationOrName: debug.IConfig | string): TPromise<any> { this.removeReplExpressions(); const sessionId = uuid.generateUuid(); this.setStateAndEmit(sessionId, debug.State.Initializing); return this.textFileService.saveAll() // make sure all dirty files are saved .then(() => this.configurationService.reloadConfiguration() // make sure configuration is up to date .then(() => this.extensionService.onReady() .then(() => this.configurationManager.getConfiguration(configurationOrName) .then(configuration => { if (!configuration) { return this.configurationManager.openConfigFile(false).then(openend => { if (openend) { this.messageService.show(severity.Info, nls.localize('NewLaunchConfig', "Please set up the launch configuration file for your application.")); } }); } if (configuration.silentlyAbort) { return; } if (strings.equalsIgnoreCase(configuration.type, 'composite') && configuration.configurationNames) { return TPromise.join(configuration.configurationNames.map(name => this.createProcess(name))); } if (!this.configurationManager.getAdapter(configuration.type)) { return configuration.type ? TPromise.wrapError(new Error(nls.localize('debugTypeNotSupported', "Configured debug type '{0}' is not supported.", configuration.type))) : TPromise.wrapError(errors.create(nls.localize('debugTypeMissing', "Missing property 'type' for the chosen launch configuration."), { actions: [this.instantiationService.createInstance(debugactions.ConfigureAction, debugactions.ConfigureAction.ID, debugactions.ConfigureAction.LABEL), CloseAction] })); } return this.runPreLaunchTask(configuration.preLaunchTask).then((taskSummary: ITaskSummary) => { const errorCount = configuration.preLaunchTask ? this.markerService.getStatistics().errors : 0; const successExitCode = taskSummary && taskSummary.exitCode === 0; const failureExitCode = taskSummary && taskSummary.exitCode !== undefined && taskSummary.exitCode !== 0; if (successExitCode || (errorCount === 0 && !failureExitCode)) { return this.doCreateProcess(sessionId, configuration); } this.messageService.show(severity.Error, { message: errorCount > 1 ? nls.localize('preLaunchTaskErrors', "Build errors have been detected during preLaunchTask '{0}'.", configuration.preLaunchTask) : errorCount === 1 ? nls.localize('preLaunchTaskError', "Build error has been detected during preLaunchTask '{0}'.", configuration.preLaunchTask) : nls.localize('preLaunchTaskExitCode', "The preLaunchTask '{0}' terminated with exit code {1}.", configuration.preLaunchTask, taskSummary.exitCode), actions: [new Action('debug.continue', nls.localize('debugAnyway', "Debug Anyway"), null, true, () => { this.messageService.hideAll(); return this.doCreateProcess(sessionId, configuration); }), CloseAction] }); }, (err: TaskError) => { if (err.code !== TaskErrors.NotConfigured) { throw err; } this.messageService.show(err.severity, { message: err.message, actions: [this.taskService.configureAction(), CloseAction] }); }); })))); } private doCreateProcess(sessionId: string, configuration: debug.IExtHostConfig): TPromise<any> { return this.telemetryService.getTelemetryInfo().then(info => { const telemetryInfo: { [key: string]: string } = Object.create(null); telemetryInfo['common.vscodemachineid'] = info.machineId; telemetryInfo['common.vscodesessionid'] = info.sessionId; return telemetryInfo; }).then(data => { const adapter = this.configurationManager.getAdapter(configuration.type); const { aiKey, type } = adapter; const publisher = adapter.extensionDescription.publisher; this.customTelemetryService = null; let client: TelemetryClient; if (aiKey) { client = new TelemetryClient( uri.parse(require.toUrl('bootstrap')).fsPath, { serverName: 'Debug Telemetry', timeout: 1000 * 60 * 5, args: [`${publisher}.${type}`, JSON.stringify(data), aiKey], env: { ELECTRON_RUN_AS_NODE: 1, PIPE_LOGGING: 'true', AMD_ENTRYPOINT: 'vs/workbench/parts/debug/node/telemetryApp' } } ); const channel = client.getChannel('telemetryAppender'); const appender = new TelemetryAppenderClient(channel); this.customTelemetryService = new TelemetryService({ appender }, this.configurationService); } const session = this.instantiationService.createInstance(RawDebugSession, sessionId, configuration.debugServer, adapter, this.customTelemetryService); this.model.addProcess(configuration.name, session); this.toDisposeOnSessionEnd[session.getId()] = []; if (client) { this.toDisposeOnSessionEnd[session.getId()].push(client); } this.registerSessionListeners(session); return session.initialize({ adapterID: configuration.type, pathFormat: 'path', linesStartAt1: true, columnsStartAt1: true, supportsVariableType: true, // #8858 supportsVariablePaging: true, // #9537 supportsRunInTerminalRequest: true // #10574 }).then((result: DebugProtocol.InitializeResponse) => { if (session.disconnected) { return TPromise.wrapError(new Error(nls.localize('debugAdapterCrash', "Debug adapter process has terminated unexpectedly"))); } this.model.setExceptionBreakpoints(session.configuration.capabilities.exceptionBreakpointFilters); return configuration.request === 'attach' ? session.attach(configuration) : session.launch(configuration); }).then((result: DebugProtocol.Response) => { if (session.disconnected) { return TPromise.as(null); } if (configuration.internalConsoleOptions === 'openOnSessionStart' || (!this.viewModel.changedWorkbenchViewState && configuration.internalConsoleOptions !== 'neverOpen')) { this.panelService.openPanel(debug.REPL_ID, false).done(undefined, errors.onUnexpectedError); } if (!this.viewModel.changedWorkbenchViewState && !this.partService.isSideBarHidden()) { // We only want to change the workbench view state on the first debug session #5738 and if the side bar is not hidden this.viewModel.changedWorkbenchViewState = true; this.viewletService.openViewlet(debug.VIEWLET_ID); } // Do not change status bar to orange if we are just running without debug. if (!configuration.noDebug) { this.partService.addClass('debugging'); } this.extensionService.activateByEvent(`onDebug:${configuration.type}`).done(null, errors.onUnexpectedError); this.inDebugMode.set(true); this.transitionToRunningState(session); this.telemetryService.publicLog('debugSessionStart', { type: configuration.type, breakpointCount: this.model.getBreakpoints().length, exceptionBreakpoints: this.model.getExceptionBreakpoints(), watchExpressionsCount: this.model.getWatchExpressions().length, extensionName: `${adapter.extensionDescription.publisher}.${adapter.extensionDescription.name}`, isBuiltin: adapter.extensionDescription.isBuiltin }); }).then(undefined, (error: any) => { if (error instanceof Error && error.message === 'Canceled') { // Do not show 'canceled' error messages to the user #7906 return TPromise.as(null); } this.telemetryService.publicLog('debugMisconfiguration', { type: configuration ? configuration.type : undefined }); this.setStateAndEmit(session.getId(), debug.State.Inactive); if (!session.disconnected) { session.disconnect().done(null, errors.onUnexpectedError); } // Show the repl if some error got logged there #5870 if (this.model.getReplElements().length > 0) { this.panelService.openPanel(debug.REPL_ID, false).done(undefined, errors.onUnexpectedError); } const configureAction = this.instantiationService.createInstance(debugactions.ConfigureAction, debugactions.ConfigureAction.ID, debugactions.ConfigureAction.LABEL); const actions = (error.actions && error.actions.length) ? error.actions.concat([configureAction]) : [CloseAction, configureAction]; return TPromise.wrapError(errors.create(error.message, { actions })); }); }); } private runPreLaunchTask(taskName: string): TPromise<ITaskSummary> { if (!taskName) { return TPromise.as(null); } // run a task before starting a debug session return this.taskService.tasks().then(descriptions => { const filteredTasks = descriptions.filter(task => task.name === taskName); if (filteredTasks.length !== 1) { return TPromise.wrapError(errors.create(nls.localize('DebugTaskNotFound', "Could not find the preLaunchTask \'{0}\'.", taskName), { actions: [ this.instantiationService.createInstance(debugactions.ConfigureAction, debugactions.ConfigureAction.ID, debugactions.ConfigureAction.LABEL), this.taskService.configureAction(), CloseAction ] })); } // task is already running - nothing to do. if (this.lastTaskEvent && this.lastTaskEvent.taskName === taskName) { return TPromise.as(null); } if (this.lastTaskEvent) { // there is a different task running currently. return TPromise.wrapError(errors.create(nls.localize('differentTaskRunning', "There is a task {0} running. Can not run pre launch task {1}.", this.lastTaskEvent.taskName, taskName))); } // no task running, execute the preLaunchTask. const taskPromise = this.taskService.run(filteredTasks[0].id).then(result => { this.lastTaskEvent = null; return result; }, err => { this.lastTaskEvent = null; }); if (filteredTasks[0].isWatching) { return new TPromise((c, e) => this.taskService.addOneTimeDisposableListener(TaskServiceEvents.Inactive, () => c(null))); } return taskPromise; }); } private rawAttach(session: RawDebugSession, port: number): TPromise<any> { if (session) { return session.attach({ port }); } const sessionId = uuid.generateUuid(); this.setStateAndEmit(sessionId, debug.State.Initializing); return this.configurationManager.getConfiguration(this.viewModel.selectedConfigurationName).then((configuration: debug.IExtHostConfig) => this.doCreateProcess(sessionId, { type: configuration.type, request: 'attach', port, sourceMaps: configuration.sourceMaps, outDir: configuration.outDir, debugServer: configuration.debugServer }) ); } public restartProcess(process: debug.IProcess): TPromise<any> { return process ? process.session.disconnect(true).then(() => new TPromise<void>((c, e) => { setTimeout(() => { this.createProcess(process.name).then(() => c(null), err => e(err)); }, 300); }) ) : this.createProcess(this.viewModel.selectedConfigurationName); } private onSessionEnd(session: RawDebugSession): void { if (session) { const bpsExist = this.model.getBreakpoints().length > 0; this.telemetryService.publicLog('debugSessionStop', { type: session.configuration.type, success: session.emittedStopped || !bpsExist, sessionLengthInSeconds: session.getLengthInSeconds(), breakpointCount: this.model.getBreakpoints().length, watchExpressionsCount: this.model.getWatchExpressions().length }); } try { this.toDisposeOnSessionEnd[session.getId()] = lifecycle.dispose(this.toDisposeOnSessionEnd[session.getId()]); } catch (e) { // an internal module might be open so the dispose can throw -> ignore and continue with stop session. } this.partService.removeClass('debugging'); this.model.removeProcess(session.getId()); this.setFocusedStackFrameAndEvaluate(null).done(null, errors.onUnexpectedError); this.setStateAndEmit(session.getId(), debug.State.Inactive); // set breakpoints back to unverified since the session ended. // source reference changes across sessions, so we do not use it to persist the source. const data: { [id: string]: { line: number, verified: boolean } } = {}; this.model.getBreakpoints().forEach(bp => { delete bp.source.raw.sourceReference; data[bp.getId()] = { line: bp.lineNumber, verified: false }; }); this.model.updateBreakpoints(data); this.inDebugMode.reset(); if (!this.partService.isSideBarHidden() && this.configurationService.getConfiguration<debug.IDebugConfiguration>('debug').openExplorerOnEnd) { this.viewletService.openViewlet(EXPLORER_VIEWLET_ID).done(null, errors.onUnexpectedError); } } public getModel(): debug.IModel { return this.model; } public getViewModel(): debug.IViewModel { return this.viewModel; } public openOrRevealSource(source: Source, lineNumber: number, preserveFocus: boolean, sideBySide: boolean): TPromise<any> { const visibleEditors = this.editorService.getVisibleEditors(); for (let i = 0; i < visibleEditors.length; i++) { const fileInput = asFileEditorInput(visibleEditors[i].input); if ((fileInput && fileInput.getResource().toString() === source.uri.toString()) || (visibleEditors[i].input instanceof DebugStringEditorInput && (<DebugStringEditorInput>visibleEditors[i].input).getResource().toString() === source.uri.toString())) { const control = <editorbrowser.ICodeEditor>visibleEditors[i].getControl(); if (control) { control.revealLineInCenterIfOutsideViewport(lineNumber); control.setSelection({ startLineNumber: lineNumber, startColumn: 1, endLineNumber: lineNumber, endColumn: 1 }); this.editorGroupService.activateGroup(i); if (!preserveFocus) { this.editorGroupService.focusGroup(i); } } return TPromise.as(null); } } const process = this.viewModel.focusedProcess; if (source.inMemory) { // internal module if (source.reference !== 0 && process && source.available) { return process.session.source({ sourceReference: source.reference }).then(response => { const mime = response && response.body && response.body.mimeType ? response.body.mimeType : guessMimeTypes(source.name)[0]; const inputValue = response && response.body ? response.body.content : ''; return this.getDebugStringEditorInput(process, source, inputValue, mime); }, (err: DebugProtocol.ErrorResponse) => { // Display the error from debug adapter using a temporary editor #8836 return this.getDebugErrorEditorInput(process, source, err.message); }).then(editorInput => { return this.editorService.openEditor(editorInput, { preserveFocus, selection: { startLineNumber: lineNumber, startColumn: 1, endLineNumber: lineNumber, endColumn: 1 } }, sideBySide); }); } return this.sourceIsUnavailable(process, source, sideBySide); } return this.fileService.resolveFile(source.uri).then(() => this.editorService.openEditor({ resource: source.uri, options: { selection: { startLineNumber: lineNumber, startColumn: 1, endLineNumber: lineNumber, endColumn: 1 }, preserveFocus: preserveFocus } }, sideBySide), err => this.sourceIsUnavailable(process, source, sideBySide) ); } private sourceIsUnavailable(process: debug.IProcess, source: Source, sideBySide: boolean): TPromise<any> { this.model.sourceIsUnavailable(source); const editorInput = this.getDebugErrorEditorInput(process, source, nls.localize('debugSourceNotAvailable', "Source {0} is not available.", source.name)); return this.editorService.openEditor(editorInput, { preserveFocus: true }, sideBySide); } public getConfigurationManager(): debug.IConfigurationManager { return this.configurationManager; } private transitionToRunningState(session: RawDebugSession, threadId?: number): void { this.model.clearThreads(session.getId(), false, threadId); // TODO@Isidor remove this mess // Get a top stack frame of a stopped thread if there is any. const process = this.model.getProcesses().filter(p => p.getId() === session.getId()).pop(); const stoppedThread = process && process.getAllThreads().filter(t => t.stopped).pop(); const callStack = stoppedThread ? stoppedThread.getCachedCallStack() : null; const stackFrameToFocus = callStack && callStack.length > 0 ? callStack[0] : null; if (!stoppedThread && process) { this.setStateAndEmit(session.getId(), process.session.requestType === debug.SessionRequestType.LAUNCH_NO_DEBUG ? debug.State.RunningNoDebug : debug.State.Running); } this.setFocusedStackFrameAndEvaluate(stackFrameToFocus).done(null, errors.onUnexpectedError); } private getDebugStringEditorInput(process: debug.IProcess, source: Source, value: string, mtype: string): DebugStringEditorInput { const result = this.instantiationService.createInstance(DebugStringEditorInput, source.name, source.uri, source.origin, value, mtype, void 0); this.toDisposeOnSessionEnd[process.getId()].push(result); return result; } private getDebugErrorEditorInput(process: debug.IProcess, source: Source, value: string): DebugErrorEditorInput { const result = this.instantiationService.createInstance(DebugErrorEditorInput, source.name, value); this.toDisposeOnSessionEnd[process.getId()].push(result); return result; } private sendAllBreakpoints(session?: RawDebugSession): TPromise<any> { return TPromise.join(arrays.distinct(this.model.getBreakpoints(), bp => bp.source.uri.toString()).map(bp => this.sendBreakpoints(bp.source.uri, false, session))) .then(() => this.sendFunctionBreakpoints(session)) // send exception breakpoints at the end since some debug adapters rely on the order .then(() => this.sendExceptionBreakpoints(session)); } private sendBreakpoints(modelUri: uri, sourceModified = false, targetSession?: RawDebugSession): TPromise<void> { const sendBreakpointsToSession = (session: RawDebugSession): TPromise<void> => { if (!session.readyForBreakpoints) { return TPromise.as(null); } if (this.textFileService.isDirty(modelUri)) { // Only send breakpoints for a file once it is not dirty #8077 this.breakpointsToSendOnResourceSaved[modelUri.toString()] = true; return TPromise.as(null); } const breakpointsToSend = arrays.distinct( this.model.getBreakpoints().filter(bp => this.model.areBreakpointsActivated() && bp.enabled && bp.source.uri.toString() === modelUri.toString()), bp => `${bp.desiredLineNumber}` ); const rawSource = breakpointsToSend.length > 0 ? breakpointsToSend[0].source.raw : Source.toRawSource(modelUri, this.model); return session.setBreakpoints({ source: rawSource, lines: breakpointsToSend.map(bp => bp.desiredLineNumber), breakpoints: breakpointsToSend.map(bp => ({ line: bp.desiredLineNumber, condition: bp.condition, hitCondition: bp.hitCondition })), sourceModified }).then(response => { if (!response || !response.body) { return; } const data: { [id: string]: { line?: number, verified: boolean } } = {}; for (let i = 0; i < breakpointsToSend.length; i++) { data[breakpointsToSend[i].getId()] = response.body.breakpoints[i]; } this.model.updateBreakpoints(data); }); }; return this.sendToOneOrAllSessions(targetSession, sendBreakpointsToSession); } private sendFunctionBreakpoints(targetSession?: RawDebugSession): TPromise<void> { const sendFunctionBreakpointsToSession = (session: RawDebugSession): TPromise<void> => { if (!session.readyForBreakpoints || !session.configuration.capabilities.supportsFunctionBreakpoints) { return TPromise.as(null); } const breakpointsToSend = this.model.getFunctionBreakpoints().filter(fbp => fbp.enabled && this.model.areBreakpointsActivated()); return session.setFunctionBreakpoints({ breakpoints: breakpointsToSend }).then(response => { if (!response || !response.body) { return; } const data: { [id: string]: { name?: string, verified?: boolean } } = {}; for (let i = 0; i < breakpointsToSend.length; i++) { data[breakpointsToSend[i].getId()] = response.body.breakpoints[i]; } this.model.updateFunctionBreakpoints(data); }); }; return this.sendToOneOrAllSessions(targetSession, sendFunctionBreakpointsToSession); } private sendExceptionBreakpoints(targetSession?: RawDebugSession): TPromise<void> { const sendExceptionBreakpointsToSession = (session: RawDebugSession): TPromise<any> => { if (!session || !session.readyForBreakpoints || this.model.getExceptionBreakpoints().length === 0) { return TPromise.as(null); } const enabledExceptionBps = this.model.getExceptionBreakpoints().filter(exb => exb.enabled); return session.setExceptionBreakpoints({ filters: enabledExceptionBps.map(exb => exb.filter) }); }; return this.sendToOneOrAllSessions(targetSession, sendExceptionBreakpointsToSession); } private sendToOneOrAllSessions(session: RawDebugSession, send: (session: RawDebugSession) => TPromise<void>): TPromise<void> { if (session) { return send(session); } return TPromise.join(this.model.getProcesses().map(p => send(<RawDebugSession>p.session))).then(() => void 0); } private onFileChanges(fileChangesEvent: FileChangesEvent): void { this.model.removeBreakpoints(this.model.getBreakpoints().filter(bp => fileChangesEvent.contains(bp.source.uri, FileChangeType.DELETED))); fileChangesEvent.getUpdated().forEach(event => { if (this.breakpointsToSendOnResourceSaved[event.resource.toString()]) { this.breakpointsToSendOnResourceSaved[event.resource.toString()] = false; this.sendBreakpoints(event.resource, true).done(null, errors.onUnexpectedError); } }); } private store(): void { this.storageService.store(DEBUG_BREAKPOINTS_KEY, JSON.stringify(this.model.getBreakpoints()), StorageScope.WORKSPACE); this.storageService.store(DEBUG_BREAKPOINTS_ACTIVATED_KEY, this.model.areBreakpointsActivated() ? 'true' : 'false', StorageScope.WORKSPACE); this.storageService.store(DEBUG_FUNCTION_BREAKPOINTS_KEY, JSON.stringify(this.model.getFunctionBreakpoints()), StorageScope.WORKSPACE); this.storageService.store(DEBUG_EXCEPTION_BREAKPOINTS_KEY, JSON.stringify(this.model.getExceptionBreakpoints()), StorageScope.WORKSPACE); this.storageService.store(DEBUG_SELECTED_CONFIG_NAME_KEY, this.viewModel.selectedConfigurationName, StorageScope.WORKSPACE); this.storageService.store(DEBUG_WATCH_EXPRESSIONS_KEY, JSON.stringify(this.model.getWatchExpressions().map(we => ({ name: we.name, id: we.getId() }))), StorageScope.WORKSPACE); } public dispose(): void { Object.keys(this.toDisposeOnSessionEnd).forEach(key => lifecycle.dispose(this.toDisposeOnSessionEnd[key])); this.toDispose = lifecycle.dispose(this.toDispose); } }
src/vs/workbench/parts/debug/electron-browser/debugService.ts
1
https://github.com/microsoft/vscode/commit/a5ba48b76595d703ffbc26f108fd9f5acef154f9
[ 0.9970510005950928, 0.03544224053621292, 0.0001629395119380206, 0.00017373147420585155, 0.1742742359638214 ]
{ "id": 4, "code_window": [ "\n", "\t\tif (!this.partService.isSideBarHidden() && this.configurationService.getConfiguration<debug.IDebugConfiguration>('debug').openExplorerOnEnd) {\n", "\t\t\tthis.viewletService.openViewlet(EXPLORER_VIEWLET_ID).done(null, errors.onUnexpectedError);\n", "\t\t}\n", "\t}\n", "\n", "\tpublic getModel(): debug.IModel {\n" ], "labels": [ "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tif (!this.partService.isSideBarHidden() && this.configurationService.getConfiguration<debug.IDebugConfiguration>('debug').openExplorerOnEnd) {\n", "\t\t\t\tthis.viewletService.openViewlet(EXPLORER_VIEWLET_ID).done(null, errors.onUnexpectedError);\n", "\t\t\t}\n" ], "file_path": "src/vs/workbench/parts/debug/electron-browser/debugService.ts", "type": "replace", "edit_start_line_idx": 823 }
/*--------------------------------------------------------------------------------------------- * 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 { onUnexpectedError } from 'vs/base/common/errors'; import { TPromise } from 'vs/base/common/winjs.base'; import { IReadOnlyModel } from 'vs/editor/common/editorCommon'; import { CommonEditorRegistry } from 'vs/editor/common/editorCommonExtensions'; import { Location, ReferenceProviderRegistry } from 'vs/editor/common/modes'; import { asWinJsPromise } from 'vs/base/common/async'; import { Position } from 'vs/editor/common/core/position'; export function provideReferences(model: IReadOnlyModel, position: Position): TPromise<Location[]> { // collect references from all providers const promises = ReferenceProviderRegistry.ordered(model).map(provider => { return asWinJsPromise((token) => { return provider.provideReferences(model, position, { includeDeclaration: true }, token); }).then(result => { if (Array.isArray(result)) { return <Location[]>result; } }, err => { onUnexpectedError(err); }); }); return TPromise.join(promises).then(references => { let result: Location[] = []; for (let ref of references) { if (ref) { result.push(...ref); } } return result; }); } CommonEditorRegistry.registerDefaultLanguageCommand('_executeReferenceProvider', provideReferences);
src/vs/editor/contrib/referenceSearch/common/referenceSearch.ts
0
https://github.com/microsoft/vscode/commit/a5ba48b76595d703ffbc26f108fd9f5acef154f9
[ 0.00017716341244522482, 0.00017203131574206054, 0.0001642823772272095, 0.0001755559933371842, 0.000005370302005758276 ]
{ "id": 4, "code_window": [ "\n", "\t\tif (!this.partService.isSideBarHidden() && this.configurationService.getConfiguration<debug.IDebugConfiguration>('debug').openExplorerOnEnd) {\n", "\t\t\tthis.viewletService.openViewlet(EXPLORER_VIEWLET_ID).done(null, errors.onUnexpectedError);\n", "\t\t}\n", "\t}\n", "\n", "\tpublic getModel(): debug.IModel {\n" ], "labels": [ "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tif (!this.partService.isSideBarHidden() && this.configurationService.getConfiguration<debug.IDebugConfiguration>('debug').openExplorerOnEnd) {\n", "\t\t\t\tthis.viewletService.openViewlet(EXPLORER_VIEWLET_ID).done(null, errors.onUnexpectedError);\n", "\t\t\t}\n" ], "file_path": "src/vs/workbench/parts/debug/electron-browser/debugService.ts", "type": "replace", "edit_start_line_idx": 823 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "actions.goToDecl.label": "移至定義", "actions.goToDeclToSide.label": "在一側開啟定義", "actions.previewDecl.label": "預覽定義", "meta.title": " - {0} 個定義", "multipleResults": "按一下以顯示找到的 {0} 個定義。" }
i18n/cht/src/vs/editor/contrib/goToDeclaration/browser/goToDeclaration.i18n.json
0
https://github.com/microsoft/vscode/commit/a5ba48b76595d703ffbc26f108fd9f5acef154f9
[ 0.00017349384143017232, 0.0001726724294712767, 0.00017185101751238108, 0.0001726724294712767, 8.214119588956237e-7 ]
{ "id": 4, "code_window": [ "\n", "\t\tif (!this.partService.isSideBarHidden() && this.configurationService.getConfiguration<debug.IDebugConfiguration>('debug').openExplorerOnEnd) {\n", "\t\t\tthis.viewletService.openViewlet(EXPLORER_VIEWLET_ID).done(null, errors.onUnexpectedError);\n", "\t\t}\n", "\t}\n", "\n", "\tpublic getModel(): debug.IModel {\n" ], "labels": [ "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tif (!this.partService.isSideBarHidden() && this.configurationService.getConfiguration<debug.IDebugConfiguration>('debug').openExplorerOnEnd) {\n", "\t\t\t\tthis.viewletService.openViewlet(EXPLORER_VIEWLET_ID).done(null, errors.onUnexpectedError);\n", "\t\t\t}\n" ], "file_path": "src/vs/workbench/parts/debug/electron-browser/debugService.ts", "type": "replace", "edit_start_line_idx": 823 }
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32"><path d="M19.23 4.095c-4.842 0-8.769 3.928-8.769 8.771 0 1.781.539 3.43 1.449 4.815 0 0-5.482 5.455-7.102 7.102-1.621 1.646 1.001 4.071 2.602 2.409 1.602-1.659 7.006-7.005 7.006-7.005 1.384.911 3.035 1.45 4.814 1.45 4.845 0 8.772-3.93 8.772-8.771.001-4.844-3.927-8.771-8.772-8.771zm0 15.035c-3.459 0-6.265-2.804-6.265-6.264 0-3.46 2.805-6.265 6.265-6.265 3.462 0 6.266 2.804 6.266 6.265 0 3.46-2.804 6.264-6.266 6.264z" fill="#fff"/></svg>
src/vs/workbench/parts/search/browser/media/search-dark.svg
0
https://github.com/microsoft/vscode/commit/a5ba48b76595d703ffbc26f108fd9f5acef154f9
[ 0.0001699976419331506, 0.0001699976419331506, 0.0001699976419331506, 0.0001699976419331506, 0 ]
{ "id": 0, "code_window": [ "------------ | -------------\n", "*$__time(dateColumn)* | Will be replaced by an expression to rename the column to `time`. For example, *dateColumn as time*\n", "*$__timeSec(dateColumn)* | Will be replaced by an expression to rename the column to `time` and converting the value to unix timestamp. For example, *extract(epoch from dateColumn) as time*\n", "*$__timeFilter(dateColumn)* | Will be replaced by a time range filter using the specified column name. For example, *dateColumn > to_timestamp(1494410783) AND dateColumn < to_timestamp(1494497183)*\n", "*$__timeFrom()* | Will be replaced by the start of the currently active time selection. For example, *to_timestamp(1494410783)*\n", "*$__timeTo()* | Will be replaced by the end of the currently active time selection. For example, *to_timestamp(1494497183)*\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ "*$__timeFilter(dateColumn)* | Will be replaced by a time range filter using the specified column name. For example, *extract(epoch from dateColumn) BETWEEN 1494410783 AND 1494497183*\n" ], "file_path": "docs/sources/features/datasources/postgres.md", "type": "replace", "edit_start_line_idx": 47 }
<query-editor-row query-ctrl="ctrl" can-collapse="false"> <div class="gf-form-inline"> <div class="gf-form gf-form--grow"> <code-editor content="ctrl.target.rawSql" datasource="ctrl.datasource" on-change="ctrl.panelCtrl.refresh()" data-mode="sql"> </code-editor> </div> </div> <div class="gf-form-inline"> <div class="gf-form"> <label class="gf-form-label query-keyword">Format as</label> <div class="gf-form-select-wrapper"> <select class="gf-form-input gf-size-auto" ng-model="ctrl.target.format" ng-options="f.value as f.text for f in ctrl.formats" ng-change="ctrl.refresh()"></select> </div> </div> <div class="gf-form"> <label class="gf-form-label query-keyword" ng-click="ctrl.showHelp = !ctrl.showHelp"> Show Help <i class="fa fa-caret-down" ng-show="ctrl.showHelp"></i> <i class="fa fa-caret-right" ng-hide="ctrl.showHelp"></i> </label> </div> <div class="gf-form" ng-show="ctrl.lastQueryMeta"> <label class="gf-form-label query-keyword" ng-click="ctrl.showLastQuerySQL = !ctrl.showLastQuerySQL"> Generated SQL <i class="fa fa-caret-down" ng-show="ctrl.showLastQuerySQL"></i> <i class="fa fa-caret-right" ng-hide="ctrl.showLastQuerySQL"></i> </label> </div> <div class="gf-form gf-form--grow"> <div class="gf-form-label gf-form-label--grow"></div> </div> </div> <div class="gf-form" ng-show="ctrl.showLastQuerySQL"> <pre class="gf-form-pre">{{ctrl.lastQueryMeta.sql}}</pre> </div> <div class="gf-form" ng-show="ctrl.showHelp"> <pre class="gf-form-pre alert alert-info">Time series: - return column named <i>time</i> (UTC in seconds or timestamp) - return column(s) with numeric datatype as values - (Optional: return column named <i>metric</i> to represent the series name. If no column named metric is found the column name of the value column is used as series name) Table: - return any set of columns Macros: - $__time(column) -&gt; column as "time" - $__timeEpoch -&gt; extract(epoch from column) as "time" - $__timeFilter(column) -&gt; column &ge; to_timestamp(1492750877) AND column &le; to_timestamp(1492750877) - $__unixEpochFilter(column) -&gt; column &gt; 1492750877 AND column &lt; 1492750877 - $__timeGroup(column,'5m') -&gt; (extract(epoch from "dateColumn")/extract(epoch from '5m'::interval))::int Example of group by and order by with $__timeGroup: SELECT $__timeGroup(date_time_col, '1h') AS time, sum(value) as value FROM yourtable GROUP BY time ORDER BY time Or build your own conditionals using these macros which just return the values: - $__timeFrom() -&gt; to_timestamp(1492750877) - $__timeTo() -&gt; to_timestamp(1492750877) - $__unixEpochFrom() -&gt; 1492750877 - $__unixEpochTo() -&gt; 1492750877 </pre> </div> </div> <div class="gf-form" ng-show="ctrl.lastQueryError"> <pre class="gf-form-pre alert alert-error">{{ctrl.lastQueryError}}</pre> </div> </query-editor-row>
public/app/plugins/datasource/postgres/partials/query.editor.html
1
https://github.com/grafana/grafana/commit/108f582ec4a42dfd96760df527c68171b75ef79d
[ 0.1577841341495514, 0.023226609453558922, 0.00016556370246689767, 0.0001710941141936928, 0.05138406530022621 ]
{ "id": 0, "code_window": [ "------------ | -------------\n", "*$__time(dateColumn)* | Will be replaced by an expression to rename the column to `time`. For example, *dateColumn as time*\n", "*$__timeSec(dateColumn)* | Will be replaced by an expression to rename the column to `time` and converting the value to unix timestamp. For example, *extract(epoch from dateColumn) as time*\n", "*$__timeFilter(dateColumn)* | Will be replaced by a time range filter using the specified column name. For example, *dateColumn > to_timestamp(1494410783) AND dateColumn < to_timestamp(1494497183)*\n", "*$__timeFrom()* | Will be replaced by the start of the currently active time selection. For example, *to_timestamp(1494410783)*\n", "*$__timeTo()* | Will be replaced by the end of the currently active time selection. For example, *to_timestamp(1494497183)*\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ "*$__timeFilter(dateColumn)* | Will be replaced by a time range filter using the specified column name. For example, *extract(epoch from dateColumn) BETWEEN 1494410783 AND 1494497183*\n" ], "file_path": "docs/sources/features/datasources/postgres.md", "type": "replace", "edit_start_line_idx": 47 }
foo.*.*.*.*
vendor/github.com/jmespath/go-jmespath/fuzz/corpus/expr-584
0
https://github.com/grafana/grafana/commit/108f582ec4a42dfd96760df527c68171b75ef79d
[ 0.00016556955233681947, 0.00016556955233681947, 0.00016556955233681947, 0.00016556955233681947, 0 ]
{ "id": 0, "code_window": [ "------------ | -------------\n", "*$__time(dateColumn)* | Will be replaced by an expression to rename the column to `time`. For example, *dateColumn as time*\n", "*$__timeSec(dateColumn)* | Will be replaced by an expression to rename the column to `time` and converting the value to unix timestamp. For example, *extract(epoch from dateColumn) as time*\n", "*$__timeFilter(dateColumn)* | Will be replaced by a time range filter using the specified column name. For example, *dateColumn > to_timestamp(1494410783) AND dateColumn < to_timestamp(1494497183)*\n", "*$__timeFrom()* | Will be replaced by the start of the currently active time selection. For example, *to_timestamp(1494410783)*\n", "*$__timeTo()* | Will be replaced by the end of the currently active time selection. For example, *to_timestamp(1494497183)*\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ "*$__timeFilter(dateColumn)* | Will be replaced by a time range filter using the specified column name. For example, *extract(epoch from dateColumn) BETWEEN 1494410783 AND 1494497183*\n" ], "file_path": "docs/sources/features/datasources/postgres.md", "type": "replace", "edit_start_line_idx": 47 }
// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build ignore /* Input to cgo -godefs. See also mkerrors.sh and mkall.sh */ // +godefs map struct_in_addr [4]byte /* in_addr */ // +godefs map struct_in6_addr [16]byte /* in6_addr */ package unix /* #define KERNEL // These defines ensure that builds done on newer versions of Solaris are // backwards-compatible with older versions of Solaris and // OpenSolaris-based derivatives. #define __USE_SUNOS_SOCKETS__ // msghdr #define __USE_LEGACY_PROTOTYPES__ // iovec #include <dirent.h> #include <fcntl.h> #include <limits.h> #include <signal.h> #include <termios.h> #include <termio.h> #include <stdio.h> #include <unistd.h> #include <sys/mman.h> #include <sys/mount.h> #include <sys/param.h> #include <sys/resource.h> #include <sys/select.h> #include <sys/signal.h> #include <sys/socket.h> #include <sys/stat.h> #include <sys/time.h> #include <sys/times.h> #include <sys/types.h> #include <sys/utsname.h> #include <sys/un.h> #include <sys/wait.h> #include <net/bpf.h> #include <net/if.h> #include <net/if_dl.h> #include <net/route.h> #include <netinet/in.h> #include <netinet/icmp6.h> #include <netinet/tcp.h> #include <ustat.h> #include <utime.h> enum { sizeofPtr = sizeof(void*), }; union sockaddr_all { struct sockaddr s1; // this one gets used for fields struct sockaddr_in s2; // these pad it out struct sockaddr_in6 s3; struct sockaddr_un s4; struct sockaddr_dl s5; }; struct sockaddr_any { struct sockaddr addr; char pad[sizeof(union sockaddr_all) - sizeof(struct sockaddr)]; }; */ import "C" // Machine characteristics; for internal use. const ( sizeofPtr = C.sizeofPtr sizeofShort = C.sizeof_short sizeofInt = C.sizeof_int sizeofLong = C.sizeof_long sizeofLongLong = C.sizeof_longlong PathMax = C.PATH_MAX ) // Basic types type ( _C_short C.short _C_int C.int _C_long C.long _C_long_long C.longlong ) // Time type Timespec C.struct_timespec type Timeval C.struct_timeval type Timeval32 C.struct_timeval32 type Tms C.struct_tms type Utimbuf C.struct_utimbuf // Processes type Rusage C.struct_rusage type Rlimit C.struct_rlimit type _Gid_t C.gid_t // Files const ( // Directory mode bits S_IFMT = C.S_IFMT S_IFIFO = C.S_IFIFO S_IFCHR = C.S_IFCHR S_IFDIR = C.S_IFDIR S_IFBLK = C.S_IFBLK S_IFREG = C.S_IFREG S_IFLNK = C.S_IFLNK S_IFSOCK = C.S_IFSOCK S_ISUID = C.S_ISUID S_ISGID = C.S_ISGID S_ISVTX = C.S_ISVTX S_IRUSR = C.S_IRUSR S_IWUSR = C.S_IWUSR S_IXUSR = C.S_IXUSR ) type Stat_t C.struct_stat type Flock_t C.struct_flock type Dirent C.struct_dirent // Sockets type RawSockaddrInet4 C.struct_sockaddr_in type RawSockaddrInet6 C.struct_sockaddr_in6 type RawSockaddrUnix C.struct_sockaddr_un type RawSockaddrDatalink C.struct_sockaddr_dl type RawSockaddr C.struct_sockaddr type RawSockaddrAny C.struct_sockaddr_any type _Socklen C.socklen_t type Linger C.struct_linger type Iovec C.struct_iovec type IPMreq C.struct_ip_mreq type IPv6Mreq C.struct_ipv6_mreq type Msghdr C.struct_msghdr type Cmsghdr C.struct_cmsghdr type Inet6Pktinfo C.struct_in6_pktinfo type IPv6MTUInfo C.struct_ip6_mtuinfo type ICMPv6Filter C.struct_icmp6_filter const ( SizeofSockaddrInet4 = C.sizeof_struct_sockaddr_in SizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 SizeofSockaddrAny = C.sizeof_struct_sockaddr_any SizeofSockaddrUnix = C.sizeof_struct_sockaddr_un SizeofSockaddrDatalink = C.sizeof_struct_sockaddr_dl SizeofLinger = C.sizeof_struct_linger SizeofIPMreq = C.sizeof_struct_ip_mreq SizeofIPv6Mreq = C.sizeof_struct_ipv6_mreq SizeofMsghdr = C.sizeof_struct_msghdr SizeofCmsghdr = C.sizeof_struct_cmsghdr SizeofInet6Pktinfo = C.sizeof_struct_in6_pktinfo SizeofIPv6MTUInfo = C.sizeof_struct_ip6_mtuinfo SizeofICMPv6Filter = C.sizeof_struct_icmp6_filter ) // Select type FdSet C.fd_set // Misc type Utsname C.struct_utsname type Ustat_t C.struct_ustat const ( AT_FDCWD = C.AT_FDCWD AT_SYMLINK_NOFOLLOW = C.AT_SYMLINK_NOFOLLOW AT_SYMLINK_FOLLOW = C.AT_SYMLINK_FOLLOW AT_REMOVEDIR = C.AT_REMOVEDIR AT_EACCESS = C.AT_EACCESS ) // Routing and interface messages const ( SizeofIfMsghdr = C.sizeof_struct_if_msghdr SizeofIfData = C.sizeof_struct_if_data SizeofIfaMsghdr = C.sizeof_struct_ifa_msghdr SizeofRtMsghdr = C.sizeof_struct_rt_msghdr SizeofRtMetrics = C.sizeof_struct_rt_metrics ) type IfMsghdr C.struct_if_msghdr type IfData C.struct_if_data type IfaMsghdr C.struct_ifa_msghdr type RtMsghdr C.struct_rt_msghdr type RtMetrics C.struct_rt_metrics // Berkeley packet filter const ( SizeofBpfVersion = C.sizeof_struct_bpf_version SizeofBpfStat = C.sizeof_struct_bpf_stat SizeofBpfProgram = C.sizeof_struct_bpf_program SizeofBpfInsn = C.sizeof_struct_bpf_insn SizeofBpfHdr = C.sizeof_struct_bpf_hdr ) type BpfVersion C.struct_bpf_version type BpfStat C.struct_bpf_stat type BpfProgram C.struct_bpf_program type BpfInsn C.struct_bpf_insn type BpfTimeval C.struct_bpf_timeval type BpfHdr C.struct_bpf_hdr // sysconf information const _SC_PAGESIZE = C._SC_PAGESIZE // Terminal handling type Termios C.struct_termios type Termio C.struct_termio type Winsize C.struct_winsize
vendor/golang.org/x/sys/unix/types_solaris.go
0
https://github.com/grafana/grafana/commit/108f582ec4a42dfd96760df527c68171b75ef79d
[ 0.0002576109254732728, 0.00017556593229528517, 0.00016214950301218778, 0.0001678073895163834, 0.0000257435385719873 ]
{ "id": 0, "code_window": [ "------------ | -------------\n", "*$__time(dateColumn)* | Will be replaced by an expression to rename the column to `time`. For example, *dateColumn as time*\n", "*$__timeSec(dateColumn)* | Will be replaced by an expression to rename the column to `time` and converting the value to unix timestamp. For example, *extract(epoch from dateColumn) as time*\n", "*$__timeFilter(dateColumn)* | Will be replaced by a time range filter using the specified column name. For example, *dateColumn > to_timestamp(1494410783) AND dateColumn < to_timestamp(1494497183)*\n", "*$__timeFrom()* | Will be replaced by the start of the currently active time selection. For example, *to_timestamp(1494410783)*\n", "*$__timeTo()* | Will be replaced by the end of the currently active time selection. For example, *to_timestamp(1494497183)*\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ "*$__timeFilter(dateColumn)* | Will be replaced by a time range filter using the specified column name. For example, *extract(epoch from dateColumn) BETWEEN 1494410783 AND 1494497183*\n" ], "file_path": "docs/sources/features/datasources/postgres.md", "type": "replace", "edit_start_line_idx": 47 }
<div class="gf-form-group"> <div class="gf-form-inline"> <div class="gf-form"> <span class="gf-form-label">Mode</span> <span class="gf-form-select-wrapper"> <select class="gf-form-input" ng-model="ctrl.panel.mode" ng-options="f for f in ['html','markdown']"></select> </span> </div> </div> </div> <h3 class="page-heading">Content</h3> <span ng-show="ctrl.panel.mode == 'markdown'"> (This area uses <a target="_blank" href="http://en.wikipedia.org/wiki/Markdown">Markdown</a>. HTML is not supported) </span> <div class="gf-form-inline"> <div class="gf-form gf-form--grow"> <code-editor content="ctrl.panel.content" rows="20" on-change="ctrl.render()" data-mode="markdown" code-editor-focus="true"> </code-editor> </div> </div>
public/app/plugins/panel/text/editor.html
0
https://github.com/grafana/grafana/commit/108f582ec4a42dfd96760df527c68171b75ef79d
[ 0.00017270242096856236, 0.0001694414095254615, 0.0001650700141908601, 0.0001705517788650468, 0.000003213316858818871 ]
{ "id": 1, "code_window": [ "*$__timeFrom()* | Will be replaced by the start of the currently active time selection. For example, *to_timestamp(1494410783)*\n", "*$__timeTo()* | Will be replaced by the end of the currently active time selection. For example, *to_timestamp(1494497183)*\n", "*$__timeGroup(dateColumn,'5m')* | Will be replaced by an expression usable in GROUP BY clause. For example, *(extract(epoch from \"dateColumn\")/extract(epoch from '5m'::interval))::int*extract(epoch from '5m'::interval)*\n", "*$__unixEpochFilter(dateColumn)* | Will be replaced by a time range filter using the specified column name with times represented as unix timestamp. For example, *dateColumn > 1494410783 AND dateColumn < 1494497183*\n", "*$__unixEpochFrom()* | Will be replaced by the start of the currently active time selection as unix timestamp. For example, *1494410783*\n", "*$__unixEpochTo()* | Will be replaced by the end of the currently active time selection as unix timestamp. For example, *1494497183*\n", "\n", "We plan to add many more macros. If you have suggestions for what macros you would like to see, please [open an issue](https://github.com/grafana/grafana) in our GitHub repo.\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "*$__timeGroup(dateColumn,'5m')* | Will be replaced by an expression usable in GROUP BY clause. For example, *(extract(epoch from \"dateColumn\")/300)::bigint*300*\n" ], "file_path": "docs/sources/features/datasources/postgres.md", "type": "replace", "edit_start_line_idx": 50 }
+++ title = "Using PostgreSQL in Grafana" description = "Guide for using PostgreSQL in Grafana" keywords = ["grafana", "postgresql", "guide"] type = "docs" [menu.docs] name = "PostgreSQL" parent = "datasources" weight = 7 +++ # Using PostgreSQL in Grafana Grafana ships with a built-in PostgreSQL data source plugin that allows you to query and visualize data from a PostgreSQL compatible database. ## Adding the data source 1. Open the side menu by clicking the Grafana icon in the top header. 2. In the side menu under the `Dashboards` link you should find a link named `Data Sources`. 3. Click the `+ Add data source` button in the top header. 4. Select *PostgreSQL* from the *Type* dropdown. ### Database User Permissions (Important!) The database user you specify when you add the data source should only be granted SELECT permissions on the specified database & tables you want to query. Grafana does not validate that the query is safe. The query could include any SQL statement. For example, statements like `DELETE FROM user;` and `DROP TABLE user;` would be executed. To protect against this we **Highly** recommmend you create a specific postgresql user with restricted permissions. Example: ```sql CREATE USER grafanareader WITH PASSWORD 'password'; GRANT USAGE ON SCHEMA schema TO grafanareader; GRANT SELECT ON schema.table TO grafanareader; ``` Make sure the user does not get any unwanted privileges from the public role. ## Macros To simplify syntax and to allow for dynamic parts, like date range filters, the query can contain macros. Macro example | Description ------------ | ------------- *$__time(dateColumn)* | Will be replaced by an expression to rename the column to `time`. For example, *dateColumn as time* *$__timeSec(dateColumn)* | Will be replaced by an expression to rename the column to `time` and converting the value to unix timestamp. For example, *extract(epoch from dateColumn) as time* *$__timeFilter(dateColumn)* | Will be replaced by a time range filter using the specified column name. For example, *dateColumn > to_timestamp(1494410783) AND dateColumn < to_timestamp(1494497183)* *$__timeFrom()* | Will be replaced by the start of the currently active time selection. For example, *to_timestamp(1494410783)* *$__timeTo()* | Will be replaced by the end of the currently active time selection. For example, *to_timestamp(1494497183)* *$__timeGroup(dateColumn,'5m')* | Will be replaced by an expression usable in GROUP BY clause. For example, *(extract(epoch from "dateColumn")/extract(epoch from '5m'::interval))::int*extract(epoch from '5m'::interval)* *$__unixEpochFilter(dateColumn)* | Will be replaced by a time range filter using the specified column name with times represented as unix timestamp. For example, *dateColumn > 1494410783 AND dateColumn < 1494497183* *$__unixEpochFrom()* | Will be replaced by the start of the currently active time selection as unix timestamp. For example, *1494410783* *$__unixEpochTo()* | Will be replaced by the end of the currently active time selection as unix timestamp. For example, *1494497183* We plan to add many more macros. If you have suggestions for what macros you would like to see, please [open an issue](https://github.com/grafana/grafana) in our GitHub repo. The query editor has a link named `Generated SQL` that shows up after a query as been executed, while in panel edit mode. Click on it and it will expand and show the raw interpolated SQL string that was executed. ## Table queries If the `Format as` query option is set to `Table` then you can basically do any type of SQL query. The table panel will automatically show the results of whatever columns & rows your query returns. Query editor with example query: ![](/img/docs/v46/postgres_table_query.png) The query: ```sql SELECT title as "Title", "user".login as "Created By", dashboard.created as "Created On" FROM dashboard INNER JOIN "user" on "user".id = dashboard.created_by WHERE $__timeFilter(dashboard.created) ``` You can control the name of the Table panel columns by using regular `as ` SQL column selection syntax. The resulting table panel: ![](/img/docs/v46/postgres_table.png) ### Time series queries If you set `Format as` to `Time series`, for use in Graph panel for example, then the query must return a column named `time` that returns either a sql datetime or any numeric datatype representing unix epoch in seconds. Any column except `time` and `metric` is treated as a value column. You may return a column named `metric` that is used as metric name for the value column. Example with `metric` column ```sql SELECT $__timeGroup(time_date_time,'5m') as time, min(value_double), 'min' as metric FROM test_data WHERE $__timeFilter(time_date_time) GROUP BY time ORDER BY time ``` Example with multiple columns: ```sql SELECT $__timeGroup(time_date_time,'5m') as time, min(value_double) as min_value, max(value_double) as max_value FROM test_data WHERE $__timeFilter(time_date_time) GROUP BY time ORDER BY time ``` ## Templating Instead of hard-coding things like server, application and sensor name in you metric queries you can use variables in their place. Variables are shown as dropdown select boxes at the top of the dashboard. These dropdowns makes it easy to change the data being displayed in your dashboard. Checkout the [Templating]({{< relref "reference/templating.md" >}}) documentation for an introduction to the templating feature and the different types of template variables. ### Query Variable If you add a template variable of the type `Query`, you can write a PostgreSQL query that can return things like measurement names, key names or key values that are shown as a dropdown select box. For example, you can have a variable that contains all values for the `hostname` column in a table if you specify a query like this in the templating variable *Query* setting. ```sql SELECT hostname FROM host ``` A query can return multiple columns and Grafana will automatically create a list from them. For example, the query below will return a list with values from `hostname` and `hostname2`. ```sql SELECT host.hostname, other_host.hostname2 FROM host JOIN other_host ON host.city = other_host.city ``` Another option is a query that can create a key/value variable. The query should return two columns that are named `__text` and `__value`. The `__text` column value should be unique (if it is not unique then the first value is used). The options in the dropdown will have a text and value that allows you to have a friendly name as text and an id as the value. An example query with `hostname` as the text and `id` as the value: ```sql SELECT hostname AS __text, id AS __value FROM host ``` You can also create nested variables. For example if you had another variable named `region`. Then you could have the hosts variable only show hosts from the current selected region with a query like this (if `region` is a multi-value variable then use the `IN` comparison operator rather than `=` to match against multiple values): ```sql SELECT hostname FROM host WHERE region IN($region) ``` ### Using Variables in Queries From Grafana 4.3.0 to 4.6.0, template variables are always quoted automatically so if it is a string value do not wrap them in quotes in where clauses. From Grafana 4.7.0, template variable values are only quoted when the template variable is a `multi-value`. If the variable is a multi-value variable then use the `IN` comparison operator rather than `=` to match against multiple values. There are two syntaxes: `$<varname>` Example with a template variable named `hostname`: ```sql SELECT atimestamp as time, aint as value FROM table WHERE $__timeFilter(atimestamp) and hostname in($hostname) ORDER BY atimestamp ASC ``` `[[varname]]` Example with a template variable named `hostname`: ```sql SELECT atimestamp as time, aint as value FROM table WHERE $__timeFilter(atimestamp) and hostname in([[hostname]]) ORDER BY atimestamp ASC ``` ## Annotations [Annotations]({{< relref "reference/annotations.md" >}}) allow you to overlay rich event information on top of graphs. You add annotation queries via the Dashboard menu / Annotations view. An example query: ```sql SELECT extract(epoch from time_date_time) AS time, metric1 as text, concat_ws(', ', metric1::text, metric2::text) as tags FROM public.test_data WHERE $__timeFilter(time_date_time) ``` Name | Description ------------ | ------------- time | The name of the date/time field. text | Event description field. tags | Optional field name to use for event tags as a comma separated string. ## Alerting Time series queries should work in alerting conditions. Table formatted queries is not yet supported in alert rule conditions.
docs/sources/features/datasources/postgres.md
1
https://github.com/grafana/grafana/commit/108f582ec4a42dfd96760df527c68171b75ef79d
[ 0.46055808663368225, 0.04337511956691742, 0.000162752068717964, 0.00020208591013215482, 0.11258139461278915 ]
{ "id": 1, "code_window": [ "*$__timeFrom()* | Will be replaced by the start of the currently active time selection. For example, *to_timestamp(1494410783)*\n", "*$__timeTo()* | Will be replaced by the end of the currently active time selection. For example, *to_timestamp(1494497183)*\n", "*$__timeGroup(dateColumn,'5m')* | Will be replaced by an expression usable in GROUP BY clause. For example, *(extract(epoch from \"dateColumn\")/extract(epoch from '5m'::interval))::int*extract(epoch from '5m'::interval)*\n", "*$__unixEpochFilter(dateColumn)* | Will be replaced by a time range filter using the specified column name with times represented as unix timestamp. For example, *dateColumn > 1494410783 AND dateColumn < 1494497183*\n", "*$__unixEpochFrom()* | Will be replaced by the start of the currently active time selection as unix timestamp. For example, *1494410783*\n", "*$__unixEpochTo()* | Will be replaced by the end of the currently active time selection as unix timestamp. For example, *1494497183*\n", "\n", "We plan to add many more macros. If you have suggestions for what macros you would like to see, please [open an issue](https://github.com/grafana/grafana) in our GitHub repo.\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "*$__timeGroup(dateColumn,'5m')* | Will be replaced by an expression usable in GROUP BY clause. For example, *(extract(epoch from \"dateColumn\")/300)::bigint*300*\n" ], "file_path": "docs/sources/features/datasources/postgres.md", "type": "replace", "edit_start_line_idx": 50 }
# Mixed Datasource - Native Plugin This is a **built in** datasource that allows you to mix different datasource on the same graph! You can enable this by selecting the built in -- Mixed -- data source. When selected this will allow you to specify data source on a per query basis. This will, for example, allow you to plot metrics from different Graphite servers on the same Graph or plot data from Elasticsearch alongside data from Prometheus. Mixing different data sources on the same graph works for any data source, even custom ones.
public/app/plugins/datasource/mixed/README.md
0
https://github.com/grafana/grafana/commit/108f582ec4a42dfd96760df527c68171b75ef79d
[ 0.0001632562925806269, 0.0001632562925806269, 0.0001632562925806269, 0.0001632562925806269, 0 ]
{ "id": 1, "code_window": [ "*$__timeFrom()* | Will be replaced by the start of the currently active time selection. For example, *to_timestamp(1494410783)*\n", "*$__timeTo()* | Will be replaced by the end of the currently active time selection. For example, *to_timestamp(1494497183)*\n", "*$__timeGroup(dateColumn,'5m')* | Will be replaced by an expression usable in GROUP BY clause. For example, *(extract(epoch from \"dateColumn\")/extract(epoch from '5m'::interval))::int*extract(epoch from '5m'::interval)*\n", "*$__unixEpochFilter(dateColumn)* | Will be replaced by a time range filter using the specified column name with times represented as unix timestamp. For example, *dateColumn > 1494410783 AND dateColumn < 1494497183*\n", "*$__unixEpochFrom()* | Will be replaced by the start of the currently active time selection as unix timestamp. For example, *1494410783*\n", "*$__unixEpochTo()* | Will be replaced by the end of the currently active time selection as unix timestamp. For example, *1494497183*\n", "\n", "We plan to add many more macros. If you have suggestions for what macros you would like to see, please [open an issue](https://github.com/grafana/grafana) in our GitHub repo.\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "*$__timeGroup(dateColumn,'5m')* | Will be replaced by an expression usable in GROUP BY clause. For example, *(extract(epoch from \"dateColumn\")/300)::bigint*300*\n" ], "file_path": "docs/sources/features/datasources/postgres.md", "type": "replace", "edit_start_line_idx": 50 }
# Prometheus Datasource - Native Plugin Grafana ships with **built in** support for Prometheus, the open-source service monitoring system and time series database. Read more about it here: [http://docs.grafana.org/datasources/prometheus/](http://docs.grafana.org/datasources/prometheus/)
public/app/plugins/datasource/prometheus/README.md
0
https://github.com/grafana/grafana/commit/108f582ec4a42dfd96760df527c68171b75ef79d
[ 0.00018557364819571376, 0.00018557364819571376, 0.00018557364819571376, 0.00018557364819571376, 0 ]
{ "id": 1, "code_window": [ "*$__timeFrom()* | Will be replaced by the start of the currently active time selection. For example, *to_timestamp(1494410783)*\n", "*$__timeTo()* | Will be replaced by the end of the currently active time selection. For example, *to_timestamp(1494497183)*\n", "*$__timeGroup(dateColumn,'5m')* | Will be replaced by an expression usable in GROUP BY clause. For example, *(extract(epoch from \"dateColumn\")/extract(epoch from '5m'::interval))::int*extract(epoch from '5m'::interval)*\n", "*$__unixEpochFilter(dateColumn)* | Will be replaced by a time range filter using the specified column name with times represented as unix timestamp. For example, *dateColumn > 1494410783 AND dateColumn < 1494497183*\n", "*$__unixEpochFrom()* | Will be replaced by the start of the currently active time selection as unix timestamp. For example, *1494410783*\n", "*$__unixEpochTo()* | Will be replaced by the end of the currently active time selection as unix timestamp. For example, *1494497183*\n", "\n", "We plan to add many more macros. If you have suggestions for what macros you would like to see, please [open an issue](https://github.com/grafana/grafana) in our GitHub repo.\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "*$__timeGroup(dateColumn,'5m')* | Will be replaced by an expression usable in GROUP BY clause. For example, *(extract(epoch from \"dateColumn\")/300)::bigint*300*\n" ], "file_path": "docs/sources/features/datasources/postgres.md", "type": "replace", "edit_start_line_idx": 50 }
// Copyright 2013 - 2016 The XORM Authors. All rights reserved. // Use of this source code is governed by a BSD // license that can be found in the LICENSE file. /* Package xorm is a simple and powerful ORM for Go. Installation Make sure you have installed Go 1.1+ and then: go get github.com/go-xorm/xorm Create Engine Firstly, we should new an engine for a database engine, err := xorm.NewEngine(driverName, dataSourceName) Method NewEngine's parameters is the same as sql.Open. It depends drivers' implementation. Generally, one engine for an application is enough. You can set it as package variable. Raw Methods XORM also support raw SQL execution: 1. query a SQL string, the returned results is []map[string][]byte results, err := engine.Query("select * from user") 2. execute a SQL string, the returned results affected, err := engine.Exec("update user set .... where ...") ORM Methods There are 8 major ORM methods and many helpful methods to use to operate database. 1. Insert one or multiple records to database affected, err := engine.Insert(&struct) // INSERT INTO struct () values () affected, err := engine.Insert(&struct1, &struct2) // INSERT INTO struct1 () values () // INSERT INTO struct2 () values () affected, err := engine.Insert(&sliceOfStruct) // INSERT INTO struct () values (),(),() affected, err := engine.Insert(&struct1, &sliceOfStruct2) // INSERT INTO struct1 () values () // INSERT INTO struct2 () values (),(),() 2. Query one record from database has, err := engine.Get(&user) // SELECT * FROM user LIMIT 1 3. Query multiple records from database var sliceOfStructs []Struct err := engine.Find(&sliceOfStructs) // SELECT * FROM user var mapOfStructs = make(map[int64]Struct) err := engine.Find(&mapOfStructs) // SELECT * FROM user var int64s []int64 err := engine.Table("user").Cols("id").Find(&int64s) // SELECT id FROM user 4. Query multiple records and record by record handle, there two methods, one is Iterate, another is Rows err := engine.Iterate(...) // SELECT * FROM user rows, err := engine.Rows(...) // SELECT * FROM user defer rows.Close() bean := new(Struct) for rows.Next() { err = rows.Scan(bean) } 5. Update one or more records affected, err := engine.Id(...).Update(&user) // UPDATE user SET ... 6. Delete one or more records, Delete MUST has condition affected, err := engine.Where(...).Delete(&user) // DELETE FROM user Where ... 7. Count records counts, err := engine.Count(&user) // SELECT count(*) AS total FROM user 8. Sum records sumFloat64, err := engine.Sum(&user, "id") // SELECT sum(id) from user sumFloat64s, err := engine.Sums(&user, "id1", "id2") // SELECT sum(id1), sum(id2) from user sumInt64s, err := engine.SumsInt(&user, "id1", "id2") // SELECT sum(id1), sum(id2) from user Conditions The above 8 methods could use with condition methods chainable. Attention: the above 8 methods should be the last chainable method. 1. ID, In engine.ID(1).Get(&user) // for single primary key // SELECT * FROM user WHERE id = 1 engine.ID(core.PK{1, 2}).Get(&user) // for composite primary keys // SELECT * FROM user WHERE id1 = 1 AND id2 = 2 engine.In("id", 1, 2, 3).Find(&users) // SELECT * FROM user WHERE id IN (1, 2, 3) engine.In("id", []int{1, 2, 3}).Find(&users) // SELECT * FROM user WHERE id IN (1, 2, 3) 2. Where, And, Or engine.Where().And().Or().Find() // SELECT * FROM user WHERE (.. AND ..) OR ... 3. OrderBy, Asc, Desc engine.Asc().Desc().Find() // SELECT * FROM user ORDER BY .. ASC, .. DESC engine.OrderBy().Find() // SELECT * FROM user ORDER BY .. 4. Limit, Top engine.Limit().Find() // SELECT * FROM user LIMIT .. OFFSET .. engine.Top(5).Find() // SELECT TOP 5 * FROM user // for mssql // SELECT * FROM user LIMIT .. OFFSET 0 //for other databases 5. SQL, let you custom SQL var users []User engine.SQL("select * from user").Find(&users) 6. Cols, Omit, Distinct var users []*User engine.Cols("col1, col2").Find(&users) // SELECT col1, col2 FROM user engine.Cols("col1", "col2").Where().Update(user) // UPDATE user set col1 = ?, col2 = ? Where ... engine.Omit("col1").Find(&users) // SELECT col2, col3 FROM user engine.Omit("col1").Insert(&user) // INSERT INTO table (non-col1) VALUES () engine.Distinct("col1").Find(&users) // SELECT DISTINCT col1 FROM user 7. Join, GroupBy, Having engine.GroupBy("name").Having("name='xlw'").Find(&users) //SELECT * FROM user GROUP BY name HAVING name='xlw' engine.Join("LEFT", "userdetail", "user.id=userdetail.id").Find(&users) //SELECT * FROM user LEFT JOIN userdetail ON user.id=userdetail.id More usage, please visit http://xorm.io/docs */ package xorm
vendor/github.com/go-xorm/xorm/doc.go
0
https://github.com/grafana/grafana/commit/108f582ec4a42dfd96760df527c68171b75ef79d
[ 0.000189416270586662, 0.00016666202282067388, 0.00016354343097191304, 0.00016508101543877274, 0.000005655420409311773 ]
{ "id": 2, "code_window": [ "\t\t\treturn \"\", fmt.Errorf(\"missing time column argument for macro %v\", name)\n", "\t\t}\n", "\t\treturn fmt.Sprintf(\"extract(epoch from %s) as \\\"time\\\"\", args[0]), nil\n", "\tcase \"__timeFilter\":\n", "\t\tif len(args) == 0 {\n", "\t\t\treturn \"\", fmt.Errorf(\"missing time column argument for macro %v\", name)\n", "\t\t}\n", "\t\treturn fmt.Sprintf(\"extract(epoch from %s) BETWEEN %d AND %d\", args[0], uint64(m.TimeRange.GetFromAsMsEpoch()/1000), uint64(m.TimeRange.GetToAsMsEpoch()/1000)), nil\n", "\tcase \"__timeFrom\":\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t// dont use to_timestamp in this macro for redshift compatibility #9566\n" ], "file_path": "pkg/tsdb/postgres/macros.go", "type": "add", "edit_start_line_idx": 74 }
<query-editor-row query-ctrl="ctrl" can-collapse="false"> <div class="gf-form-inline"> <div class="gf-form gf-form--grow"> <code-editor content="ctrl.target.rawSql" datasource="ctrl.datasource" on-change="ctrl.panelCtrl.refresh()" data-mode="sql"> </code-editor> </div> </div> <div class="gf-form-inline"> <div class="gf-form"> <label class="gf-form-label query-keyword">Format as</label> <div class="gf-form-select-wrapper"> <select class="gf-form-input gf-size-auto" ng-model="ctrl.target.format" ng-options="f.value as f.text for f in ctrl.formats" ng-change="ctrl.refresh()"></select> </div> </div> <div class="gf-form"> <label class="gf-form-label query-keyword" ng-click="ctrl.showHelp = !ctrl.showHelp"> Show Help <i class="fa fa-caret-down" ng-show="ctrl.showHelp"></i> <i class="fa fa-caret-right" ng-hide="ctrl.showHelp"></i> </label> </div> <div class="gf-form" ng-show="ctrl.lastQueryMeta"> <label class="gf-form-label query-keyword" ng-click="ctrl.showLastQuerySQL = !ctrl.showLastQuerySQL"> Generated SQL <i class="fa fa-caret-down" ng-show="ctrl.showLastQuerySQL"></i> <i class="fa fa-caret-right" ng-hide="ctrl.showLastQuerySQL"></i> </label> </div> <div class="gf-form gf-form--grow"> <div class="gf-form-label gf-form-label--grow"></div> </div> </div> <div class="gf-form" ng-show="ctrl.showLastQuerySQL"> <pre class="gf-form-pre">{{ctrl.lastQueryMeta.sql}}</pre> </div> <div class="gf-form" ng-show="ctrl.showHelp"> <pre class="gf-form-pre alert alert-info">Time series: - return column named <i>time</i> (UTC in seconds or timestamp) - return column(s) with numeric datatype as values - (Optional: return column named <i>metric</i> to represent the series name. If no column named metric is found the column name of the value column is used as series name) Table: - return any set of columns Macros: - $__time(column) -&gt; column as "time" - $__timeEpoch -&gt; extract(epoch from column) as "time" - $__timeFilter(column) -&gt; column &ge; to_timestamp(1492750877) AND column &le; to_timestamp(1492750877) - $__unixEpochFilter(column) -&gt; column &gt; 1492750877 AND column &lt; 1492750877 - $__timeGroup(column,'5m') -&gt; (extract(epoch from "dateColumn")/extract(epoch from '5m'::interval))::int Example of group by and order by with $__timeGroup: SELECT $__timeGroup(date_time_col, '1h') AS time, sum(value) as value FROM yourtable GROUP BY time ORDER BY time Or build your own conditionals using these macros which just return the values: - $__timeFrom() -&gt; to_timestamp(1492750877) - $__timeTo() -&gt; to_timestamp(1492750877) - $__unixEpochFrom() -&gt; 1492750877 - $__unixEpochTo() -&gt; 1492750877 </pre> </div> </div> <div class="gf-form" ng-show="ctrl.lastQueryError"> <pre class="gf-form-pre alert alert-error">{{ctrl.lastQueryError}}</pre> </div> </query-editor-row>
public/app/plugins/datasource/postgres/partials/query.editor.html
1
https://github.com/grafana/grafana/commit/108f582ec4a42dfd96760df527c68171b75ef79d
[ 0.001254367409273982, 0.0004130721790716052, 0.0001697291008895263, 0.00017229802324436605, 0.0003696797357406467 ]
{ "id": 2, "code_window": [ "\t\t\treturn \"\", fmt.Errorf(\"missing time column argument for macro %v\", name)\n", "\t\t}\n", "\t\treturn fmt.Sprintf(\"extract(epoch from %s) as \\\"time\\\"\", args[0]), nil\n", "\tcase \"__timeFilter\":\n", "\t\tif len(args) == 0 {\n", "\t\t\treturn \"\", fmt.Errorf(\"missing time column argument for macro %v\", name)\n", "\t\t}\n", "\t\treturn fmt.Sprintf(\"extract(epoch from %s) BETWEEN %d AND %d\", args[0], uint64(m.TimeRange.GetFromAsMsEpoch()/1000), uint64(m.TimeRange.GetToAsMsEpoch()/1000)), nil\n", "\tcase \"__timeFrom\":\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t// dont use to_timestamp in this macro for redshift compatibility #9566\n" ], "file_path": "pkg/tsdb/postgres/macros.go", "type": "add", "edit_start_line_idx": 74 }
/* Flot plugin for stacking data sets rather than overlyaing them. Copyright (c) 2007-2014 IOLA and Ole Laursen. Licensed under the MIT license. The plugin assumes the data is sorted on x (or y if stacking horizontally). For line charts, it is assumed that if a line has an undefined gap (from a null point), then the line above it should have the same gap - insert zeros instead of "null" if you want another behaviour. This also holds for the start and end of the chart. Note that stacking a mix of positive and negative values in most instances doesn't make sense (so it looks weird). Two or more series are stacked when their "stack" attribute is set to the same key (which can be any number or string or just "true"). To specify the default stack, you can set the stack option like this: series: { stack: null/false, true, or a key (number/string) } You can also specify it for a single series, like this: $.plot( $("#placeholder"), [{ data: [ ... ], stack: true }]) The stacking order is determined by the order of the data series in the array (later series end up on top of the previous). Internally, the plugin modifies the datapoints in each series, adding an offset to the y value. For line series, extra data points are inserted through interpolation. If there's a second y value, it's also adjusted (e.g for bar charts or filled areas). */ (function ($) { var options = { series: { stack: null } // or number/string }; function init(plot) { function findMatchingSeries(s, allseries) { var res = null; for (var i = 0; i < allseries.length; ++i) { if (s == allseries[i]) break; if (allseries[i].stack == s.stack) res = allseries[i]; } return res; } function stackData(plot, s, datapoints) { if (s.stack == null || s.stack === false) return; var other = findMatchingSeries(s, plot.getData()); if (!other) return; var ps = datapoints.pointsize, points = datapoints.points, otherps = other.datapoints.pointsize, otherpoints = other.datapoints.points, newpoints = [], px, py, intery, qx, qy, bottom, withlines = s.lines.show, horizontal = s.bars.horizontal, withbottom = ps > 2 && (horizontal ? datapoints.format[2].x : datapoints.format[2].y), withsteps = withlines && s.lines.steps, keyOffset = horizontal ? 1 : 0, accumulateOffset = horizontal ? 0 : 1, i = 0, j = 0, l, m; while (true) { if (i >= points.length && j >= otherpoints.length) break; l = newpoints.length; if (i < points.length && points[i] == null) { // copy gaps for (m = 0; m < ps; ++m) newpoints.push(points[i + m]); i += ps; } else if (i >= points.length) { // take the remaining points from the previous series for (m = 0; m < ps; ++m) newpoints.push(otherpoints[j + m]); if (withbottom) newpoints[l + 2] = otherpoints[j + accumulateOffset]; j += otherps; } else if (j >= otherpoints.length) { // take the remaining points from the current series for (m = 0; m < ps; ++m) newpoints.push(points[i + m]); i += ps; } else if (j < otherpoints.length && otherpoints[j] == null) { // ignore point j += otherps; } else { // cases where we actually got two points px = points[i + keyOffset]; py = points[i + accumulateOffset]; qx = otherpoints[j + keyOffset]; qy = otherpoints[j + accumulateOffset]; bottom = 0; if (px == qx) { for (m = 0; m < ps; ++m) newpoints.push(points[i + m]); newpoints[l + accumulateOffset] += qy; bottom = qy; i += ps; j += otherps; } else if (px > qx) { // take the point from the previous series so that next series will correctly stack if (i == 0) { for (m = 0; m < ps; ++m) newpoints.push(otherpoints[j + m]); bottom = qy; } // we got past point below, might need to // insert interpolated extra point if (i > 0 && points[i - ps] != null) { intery = py + (points[i - ps + accumulateOffset] - py) * (qx - px) / (points[i - ps + keyOffset] - px); newpoints.push(qx); newpoints.push(intery + qy); for (m = 2; m < ps; ++m) newpoints.push(points[i + m]); bottom = qy; } j += otherps; } else { // px < qx for (m = 0; m < ps; ++m) newpoints.push(points[i + m]); // we might be able to interpolate a point below, // this can give us a better y if (j > 0 && otherpoints[j - otherps] != null) bottom = qy + (otherpoints[j - otherps + accumulateOffset] - qy) * (px - qx) / (otherpoints[j - otherps + keyOffset] - qx); newpoints[l + accumulateOffset] += bottom; i += ps; } fromgap = false; if (l != newpoints.length && withbottom) newpoints[l + 2] = bottom; } // maintain the line steps invariant if (withsteps && l != newpoints.length && l > 0 && newpoints[l] != null && newpoints[l] != newpoints[l - ps] && newpoints[l + 1] != newpoints[l - ps + 1]) { for (m = 0; m < ps; ++m) newpoints[l + ps + m] = newpoints[l + m]; newpoints[l + 1] = newpoints[l - ps + 1]; } } datapoints.points = newpoints; } plot.hooks.processDatapoints.push(stackData); } $.plot.plugins.push({ init: init, options: options, name: 'stack', version: '1.2' }); })(jQuery);
public/vendor/flot/jquery.flot.stack.js
0
https://github.com/grafana/grafana/commit/108f582ec4a42dfd96760df527c68171b75ef79d
[ 0.002125933999195695, 0.00027631883858703077, 0.0001678355474723503, 0.00017240954912267625, 0.00042548245983198285 ]
{ "id": 2, "code_window": [ "\t\t\treturn \"\", fmt.Errorf(\"missing time column argument for macro %v\", name)\n", "\t\t}\n", "\t\treturn fmt.Sprintf(\"extract(epoch from %s) as \\\"time\\\"\", args[0]), nil\n", "\tcase \"__timeFilter\":\n", "\t\tif len(args) == 0 {\n", "\t\t\treturn \"\", fmt.Errorf(\"missing time column argument for macro %v\", name)\n", "\t\t}\n", "\t\treturn fmt.Sprintf(\"extract(epoch from %s) BETWEEN %d AND %d\", args[0], uint64(m.TimeRange.GetFromAsMsEpoch()/1000), uint64(m.TimeRange.GetToAsMsEpoch()/1000)), nil\n", "\tcase \"__timeFrom\":\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t// dont use to_timestamp in this macro for redshift compatibility #9566\n" ], "file_path": "pkg/tsdb/postgres/macros.go", "type": "add", "edit_start_line_idx": 74 }
.heatmap-canvas-wrapper { // position: relative; cursor: crosshair; } .heatmap-panel { position: relative; .axis .tick { text { fill: $text-color; color: $text-color; font-size: $font-size-sm; } line { opacity: 0.4; stroke: $text-color-weak; } } // This hack prevents mouseenter/mouseleave events get fired too often svg { pointer-events: none; rect { pointer-events: visiblePainted; } } } .heatmap-tooltip { white-space: nowrap; font-size: $font-size-sm; background-color: $graph-tooltip-bg; color: $text-color; } .heatmap-histogram rect { fill: $text-color-weak; } .heatmap-crosshair { line { stroke: darken($red,15%); stroke-width: 1; } } .heatmap-selection { stroke-width: 1; fill: rgba(102, 102, 102, 0.4); stroke: rgba(102, 102, 102, 0.8); } .heatmap-legend-wrapper { @include clearfix(); margin: 0 $spacer; padding-top: 10px; svg { width: 100%; max-width: 300px; height: 33px; float: left; white-space: nowrap; padding-left: 10px; } .heatmap-legend-values { display: inline-block; } .axis .tick { text { fill: $text-color; color: $text-color; font-size: $font-size-sm; } line { opacity: 0.4; stroke: $text-color-weak; } .domain { opacity: 0.4; stroke: $text-color-weak; } } }
public/sass/components/_panel_heatmap.scss
0
https://github.com/grafana/grafana/commit/108f582ec4a42dfd96760df527c68171b75ef79d
[ 0.00017806947289500386, 0.00017484152340330184, 0.00017170475621242076, 0.00017541696433909237, 0.000001865022795755067 ]
{ "id": 2, "code_window": [ "\t\t\treturn \"\", fmt.Errorf(\"missing time column argument for macro %v\", name)\n", "\t\t}\n", "\t\treturn fmt.Sprintf(\"extract(epoch from %s) as \\\"time\\\"\", args[0]), nil\n", "\tcase \"__timeFilter\":\n", "\t\tif len(args) == 0 {\n", "\t\t\treturn \"\", fmt.Errorf(\"missing time column argument for macro %v\", name)\n", "\t\t}\n", "\t\treturn fmt.Sprintf(\"extract(epoch from %s) BETWEEN %d AND %d\", args[0], uint64(m.TimeRange.GetFromAsMsEpoch()/1000), uint64(m.TimeRange.GetToAsMsEpoch()/1000)), nil\n", "\tcase \"__timeFrom\":\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t// dont use to_timestamp in this macro for redshift compatibility #9566\n" ], "file_path": "pkg/tsdb/postgres/macros.go", "type": "add", "edit_start_line_idx": 74 }
// mksysnum_linux.pl /usr/include/asm/unistd.h // MACHINE GENERATED BY THE ABOVE COMMAND; DO NOT EDIT // +build ppc64,linux package unix const ( SYS_RESTART_SYSCALL = 0 SYS_EXIT = 1 SYS_FORK = 2 SYS_READ = 3 SYS_WRITE = 4 SYS_OPEN = 5 SYS_CLOSE = 6 SYS_WAITPID = 7 SYS_CREAT = 8 SYS_LINK = 9 SYS_UNLINK = 10 SYS_EXECVE = 11 SYS_CHDIR = 12 SYS_TIME = 13 SYS_MKNOD = 14 SYS_CHMOD = 15 SYS_LCHOWN = 16 SYS_BREAK = 17 SYS_OLDSTAT = 18 SYS_LSEEK = 19 SYS_GETPID = 20 SYS_MOUNT = 21 SYS_UMOUNT = 22 SYS_SETUID = 23 SYS_GETUID = 24 SYS_STIME = 25 SYS_PTRACE = 26 SYS_ALARM = 27 SYS_OLDFSTAT = 28 SYS_PAUSE = 29 SYS_UTIME = 30 SYS_STTY = 31 SYS_GTTY = 32 SYS_ACCESS = 33 SYS_NICE = 34 SYS_FTIME = 35 SYS_SYNC = 36 SYS_KILL = 37 SYS_RENAME = 38 SYS_MKDIR = 39 SYS_RMDIR = 40 SYS_DUP = 41 SYS_PIPE = 42 SYS_TIMES = 43 SYS_PROF = 44 SYS_BRK = 45 SYS_SETGID = 46 SYS_GETGID = 47 SYS_SIGNAL = 48 SYS_GETEUID = 49 SYS_GETEGID = 50 SYS_ACCT = 51 SYS_UMOUNT2 = 52 SYS_LOCK = 53 SYS_IOCTL = 54 SYS_FCNTL = 55 SYS_MPX = 56 SYS_SETPGID = 57 SYS_ULIMIT = 58 SYS_OLDOLDUNAME = 59 SYS_UMASK = 60 SYS_CHROOT = 61 SYS_USTAT = 62 SYS_DUP2 = 63 SYS_GETPPID = 64 SYS_GETPGRP = 65 SYS_SETSID = 66 SYS_SIGACTION = 67 SYS_SGETMASK = 68 SYS_SSETMASK = 69 SYS_SETREUID = 70 SYS_SETREGID = 71 SYS_SIGSUSPEND = 72 SYS_SIGPENDING = 73 SYS_SETHOSTNAME = 74 SYS_SETRLIMIT = 75 SYS_GETRLIMIT = 76 SYS_GETRUSAGE = 77 SYS_GETTIMEOFDAY = 78 SYS_SETTIMEOFDAY = 79 SYS_GETGROUPS = 80 SYS_SETGROUPS = 81 SYS_SELECT = 82 SYS_SYMLINK = 83 SYS_OLDLSTAT = 84 SYS_READLINK = 85 SYS_USELIB = 86 SYS_SWAPON = 87 SYS_REBOOT = 88 SYS_READDIR = 89 SYS_MMAP = 90 SYS_MUNMAP = 91 SYS_TRUNCATE = 92 SYS_FTRUNCATE = 93 SYS_FCHMOD = 94 SYS_FCHOWN = 95 SYS_GETPRIORITY = 96 SYS_SETPRIORITY = 97 SYS_PROFIL = 98 SYS_STATFS = 99 SYS_FSTATFS = 100 SYS_IOPERM = 101 SYS_SOCKETCALL = 102 SYS_SYSLOG = 103 SYS_SETITIMER = 104 SYS_GETITIMER = 105 SYS_STAT = 106 SYS_LSTAT = 107 SYS_FSTAT = 108 SYS_OLDUNAME = 109 SYS_IOPL = 110 SYS_VHANGUP = 111 SYS_IDLE = 112 SYS_VM86 = 113 SYS_WAIT4 = 114 SYS_SWAPOFF = 115 SYS_SYSINFO = 116 SYS_IPC = 117 SYS_FSYNC = 118 SYS_SIGRETURN = 119 SYS_CLONE = 120 SYS_SETDOMAINNAME = 121 SYS_UNAME = 122 SYS_MODIFY_LDT = 123 SYS_ADJTIMEX = 124 SYS_MPROTECT = 125 SYS_SIGPROCMASK = 126 SYS_CREATE_MODULE = 127 SYS_INIT_MODULE = 128 SYS_DELETE_MODULE = 129 SYS_GET_KERNEL_SYMS = 130 SYS_QUOTACTL = 131 SYS_GETPGID = 132 SYS_FCHDIR = 133 SYS_BDFLUSH = 134 SYS_SYSFS = 135 SYS_PERSONALITY = 136 SYS_AFS_SYSCALL = 137 SYS_SETFSUID = 138 SYS_SETFSGID = 139 SYS__LLSEEK = 140 SYS_GETDENTS = 141 SYS__NEWSELECT = 142 SYS_FLOCK = 143 SYS_MSYNC = 144 SYS_READV = 145 SYS_WRITEV = 146 SYS_GETSID = 147 SYS_FDATASYNC = 148 SYS__SYSCTL = 149 SYS_MLOCK = 150 SYS_MUNLOCK = 151 SYS_MLOCKALL = 152 SYS_MUNLOCKALL = 153 SYS_SCHED_SETPARAM = 154 SYS_SCHED_GETPARAM = 155 SYS_SCHED_SETSCHEDULER = 156 SYS_SCHED_GETSCHEDULER = 157 SYS_SCHED_YIELD = 158 SYS_SCHED_GET_PRIORITY_MAX = 159 SYS_SCHED_GET_PRIORITY_MIN = 160 SYS_SCHED_RR_GET_INTERVAL = 161 SYS_NANOSLEEP = 162 SYS_MREMAP = 163 SYS_SETRESUID = 164 SYS_GETRESUID = 165 SYS_QUERY_MODULE = 166 SYS_POLL = 167 SYS_NFSSERVCTL = 168 SYS_SETRESGID = 169 SYS_GETRESGID = 170 SYS_PRCTL = 171 SYS_RT_SIGRETURN = 172 SYS_RT_SIGACTION = 173 SYS_RT_SIGPROCMASK = 174 SYS_RT_SIGPENDING = 175 SYS_RT_SIGTIMEDWAIT = 176 SYS_RT_SIGQUEUEINFO = 177 SYS_RT_SIGSUSPEND = 178 SYS_PREAD64 = 179 SYS_PWRITE64 = 180 SYS_CHOWN = 181 SYS_GETCWD = 182 SYS_CAPGET = 183 SYS_CAPSET = 184 SYS_SIGALTSTACK = 185 SYS_SENDFILE = 186 SYS_GETPMSG = 187 SYS_PUTPMSG = 188 SYS_VFORK = 189 SYS_UGETRLIMIT = 190 SYS_READAHEAD = 191 SYS_PCICONFIG_READ = 198 SYS_PCICONFIG_WRITE = 199 SYS_PCICONFIG_IOBASE = 200 SYS_MULTIPLEXER = 201 SYS_GETDENTS64 = 202 SYS_PIVOT_ROOT = 203 SYS_MADVISE = 205 SYS_MINCORE = 206 SYS_GETTID = 207 SYS_TKILL = 208 SYS_SETXATTR = 209 SYS_LSETXATTR = 210 SYS_FSETXATTR = 211 SYS_GETXATTR = 212 SYS_LGETXATTR = 213 SYS_FGETXATTR = 214 SYS_LISTXATTR = 215 SYS_LLISTXATTR = 216 SYS_FLISTXATTR = 217 SYS_REMOVEXATTR = 218 SYS_LREMOVEXATTR = 219 SYS_FREMOVEXATTR = 220 SYS_FUTEX = 221 SYS_SCHED_SETAFFINITY = 222 SYS_SCHED_GETAFFINITY = 223 SYS_TUXCALL = 225 SYS_IO_SETUP = 227 SYS_IO_DESTROY = 228 SYS_IO_GETEVENTS = 229 SYS_IO_SUBMIT = 230 SYS_IO_CANCEL = 231 SYS_SET_TID_ADDRESS = 232 SYS_FADVISE64 = 233 SYS_EXIT_GROUP = 234 SYS_LOOKUP_DCOOKIE = 235 SYS_EPOLL_CREATE = 236 SYS_EPOLL_CTL = 237 SYS_EPOLL_WAIT = 238 SYS_REMAP_FILE_PAGES = 239 SYS_TIMER_CREATE = 240 SYS_TIMER_SETTIME = 241 SYS_TIMER_GETTIME = 242 SYS_TIMER_GETOVERRUN = 243 SYS_TIMER_DELETE = 244 SYS_CLOCK_SETTIME = 245 SYS_CLOCK_GETTIME = 246 SYS_CLOCK_GETRES = 247 SYS_CLOCK_NANOSLEEP = 248 SYS_SWAPCONTEXT = 249 SYS_TGKILL = 250 SYS_UTIMES = 251 SYS_STATFS64 = 252 SYS_FSTATFS64 = 253 SYS_RTAS = 255 SYS_SYS_DEBUG_SETCONTEXT = 256 SYS_MIGRATE_PAGES = 258 SYS_MBIND = 259 SYS_GET_MEMPOLICY = 260 SYS_SET_MEMPOLICY = 261 SYS_MQ_OPEN = 262 SYS_MQ_UNLINK = 263 SYS_MQ_TIMEDSEND = 264 SYS_MQ_TIMEDRECEIVE = 265 SYS_MQ_NOTIFY = 266 SYS_MQ_GETSETATTR = 267 SYS_KEXEC_LOAD = 268 SYS_ADD_KEY = 269 SYS_REQUEST_KEY = 270 SYS_KEYCTL = 271 SYS_WAITID = 272 SYS_IOPRIO_SET = 273 SYS_IOPRIO_GET = 274 SYS_INOTIFY_INIT = 275 SYS_INOTIFY_ADD_WATCH = 276 SYS_INOTIFY_RM_WATCH = 277 SYS_SPU_RUN = 278 SYS_SPU_CREATE = 279 SYS_PSELECT6 = 280 SYS_PPOLL = 281 SYS_UNSHARE = 282 SYS_SPLICE = 283 SYS_TEE = 284 SYS_VMSPLICE = 285 SYS_OPENAT = 286 SYS_MKDIRAT = 287 SYS_MKNODAT = 288 SYS_FCHOWNAT = 289 SYS_FUTIMESAT = 290 SYS_NEWFSTATAT = 291 SYS_UNLINKAT = 292 SYS_RENAMEAT = 293 SYS_LINKAT = 294 SYS_SYMLINKAT = 295 SYS_READLINKAT = 296 SYS_FCHMODAT = 297 SYS_FACCESSAT = 298 SYS_GET_ROBUST_LIST = 299 SYS_SET_ROBUST_LIST = 300 SYS_MOVE_PAGES = 301 SYS_GETCPU = 302 SYS_EPOLL_PWAIT = 303 SYS_UTIMENSAT = 304 SYS_SIGNALFD = 305 SYS_TIMERFD_CREATE = 306 SYS_EVENTFD = 307 SYS_SYNC_FILE_RANGE2 = 308 SYS_FALLOCATE = 309 SYS_SUBPAGE_PROT = 310 SYS_TIMERFD_SETTIME = 311 SYS_TIMERFD_GETTIME = 312 SYS_SIGNALFD4 = 313 SYS_EVENTFD2 = 314 SYS_EPOLL_CREATE1 = 315 SYS_DUP3 = 316 SYS_PIPE2 = 317 SYS_INOTIFY_INIT1 = 318 SYS_PERF_EVENT_OPEN = 319 SYS_PREADV = 320 SYS_PWRITEV = 321 SYS_RT_TGSIGQUEUEINFO = 322 SYS_FANOTIFY_INIT = 323 SYS_FANOTIFY_MARK = 324 SYS_PRLIMIT64 = 325 SYS_SOCKET = 326 SYS_BIND = 327 SYS_CONNECT = 328 SYS_LISTEN = 329 SYS_ACCEPT = 330 SYS_GETSOCKNAME = 331 SYS_GETPEERNAME = 332 SYS_SOCKETPAIR = 333 SYS_SEND = 334 SYS_SENDTO = 335 SYS_RECV = 336 SYS_RECVFROM = 337 SYS_SHUTDOWN = 338 SYS_SETSOCKOPT = 339 SYS_GETSOCKOPT = 340 SYS_SENDMSG = 341 SYS_RECVMSG = 342 SYS_RECVMMSG = 343 SYS_ACCEPT4 = 344 SYS_NAME_TO_HANDLE_AT = 345 SYS_OPEN_BY_HANDLE_AT = 346 SYS_CLOCK_ADJTIME = 347 SYS_SYNCFS = 348 SYS_SENDMMSG = 349 SYS_SETNS = 350 SYS_PROCESS_VM_READV = 351 SYS_PROCESS_VM_WRITEV = 352 SYS_FINIT_MODULE = 353 SYS_KCMP = 354 SYS_SCHED_SETATTR = 355 SYS_SCHED_GETATTR = 356 SYS_RENAMEAT2 = 357 SYS_SECCOMP = 358 SYS_GETRANDOM = 359 SYS_MEMFD_CREATE = 360 SYS_BPF = 361 )
vendor/golang.org/x/sys/unix/zsysnum_linux_ppc64.go
0
https://github.com/grafana/grafana/commit/108f582ec4a42dfd96760df527c68171b75ef79d
[ 0.00023964665888343006, 0.00017188342462759465, 0.00016260163101833314, 0.00016486032109241933, 0.00001811939182516653 ]
{ "id": 3, "code_window": [ "\n", "Macros:\n", "- $__time(column) -&gt; column as \"time\"\n", "- $__timeEpoch -&gt; extract(epoch from column) as \"time\"\n", "- $__timeFilter(column) -&gt; column &ge; to_timestamp(1492750877) AND column &le; to_timestamp(1492750877)\n", "- $__unixEpochFilter(column) -&gt; column &gt; 1492750877 AND column &lt; 1492750877\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "- $__timeFilter(column) -&gt; extract(epoch from column) BETWEEN 1492750877 AND 1492750877\n" ], "file_path": "public/app/plugins/datasource/postgres/partials/query.editor.html", "type": "replace", "edit_start_line_idx": 50 }
package postgres import ( "fmt" "regexp" "strings" "time" "github.com/grafana/grafana/pkg/tsdb" ) //const rsString = `(?:"([^"]*)")`; const rsIdentifier = `([_a-zA-Z0-9]+)` const sExpr = `\$` + rsIdentifier + `\(([^\)]*)\)` type PostgresMacroEngine struct { TimeRange *tsdb.TimeRange } func NewPostgresMacroEngine() tsdb.SqlMacroEngine { return &PostgresMacroEngine{} } func (m *PostgresMacroEngine) Interpolate(timeRange *tsdb.TimeRange, sql string) (string, error) { m.TimeRange = timeRange rExp, _ := regexp.Compile(sExpr) var macroError error sql = replaceAllStringSubmatchFunc(rExp, sql, func(groups []string) string { res, err := m.evaluateMacro(groups[1], strings.Split(groups[2], ",")) if err != nil && macroError == nil { macroError = err return "macro_error()" } return res }) if macroError != nil { return "", macroError } return sql, nil } func replaceAllStringSubmatchFunc(re *regexp.Regexp, str string, repl func([]string) string) string { result := "" lastIndex := 0 for _, v := range re.FindAllSubmatchIndex([]byte(str), -1) { groups := []string{} for i := 0; i < len(v); i += 2 { groups = append(groups, str[v[i]:v[i+1]]) } result += str[lastIndex:v[0]] + repl(groups) lastIndex = v[1] } return result + str[lastIndex:] } func (m *PostgresMacroEngine) evaluateMacro(name string, args []string) (string, error) { switch name { case "__time": if len(args) == 0 { return "", fmt.Errorf("missing time column argument for macro %v", name) } return fmt.Sprintf("%s AS \"time\"", args[0]), nil case "__timeEpoch": if len(args) == 0 { return "", fmt.Errorf("missing time column argument for macro %v", name) } return fmt.Sprintf("extract(epoch from %s) as \"time\"", args[0]), nil case "__timeFilter": if len(args) == 0 { return "", fmt.Errorf("missing time column argument for macro %v", name) } return fmt.Sprintf("extract(epoch from %s) BETWEEN %d AND %d", args[0], uint64(m.TimeRange.GetFromAsMsEpoch()/1000), uint64(m.TimeRange.GetToAsMsEpoch()/1000)), nil case "__timeFrom": return fmt.Sprintf("to_timestamp(%d)", uint64(m.TimeRange.GetFromAsMsEpoch()/1000)), nil case "__timeTo": return fmt.Sprintf("to_timestamp(%d)", uint64(m.TimeRange.GetToAsMsEpoch()/1000)), nil case "__timeGroup": if len(args) != 2 { return "", fmt.Errorf("macro %v needs time column and interval", name) } interval, err := time.ParseDuration(strings.Trim(args[1], `' `)) if err != nil { return "", fmt.Errorf("error parsing interval %v", args[1]) } return fmt.Sprintf("(extract(epoch from \"%s\")/%v)::bigint*%v", args[0], interval.Seconds(), interval.Seconds()), nil case "__unixEpochFilter": if len(args) == 0 { return "", fmt.Errorf("missing time column argument for macro %v", name) } return fmt.Sprintf("%s >= %d AND %s <= %d", args[0], uint64(m.TimeRange.GetFromAsMsEpoch()/1000), args[0], uint64(m.TimeRange.GetToAsMsEpoch()/1000)), nil case "__unixEpochFrom": return fmt.Sprintf("%d", uint64(m.TimeRange.GetFromAsMsEpoch()/1000)), nil case "__unixEpochTo": return fmt.Sprintf("%d", uint64(m.TimeRange.GetToAsMsEpoch()/1000)), nil default: return "", fmt.Errorf("Unknown macro %v", name) } }
pkg/tsdb/postgres/macros.go
1
https://github.com/grafana/grafana/commit/108f582ec4a42dfd96760df527c68171b75ef79d
[ 0.8344684839248657, 0.09748575836420059, 0.00016663101268932223, 0.0037427968345582485, 0.23642031848430634 ]
{ "id": 3, "code_window": [ "\n", "Macros:\n", "- $__time(column) -&gt; column as \"time\"\n", "- $__timeEpoch -&gt; extract(epoch from column) as \"time\"\n", "- $__timeFilter(column) -&gt; column &ge; to_timestamp(1492750877) AND column &le; to_timestamp(1492750877)\n", "- $__unixEpochFilter(column) -&gt; column &gt; 1492750877 AND column &lt; 1492750877\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "- $__timeFilter(column) -&gt; extract(epoch from column) BETWEEN 1492750877 AND 1492750877\n" ], "file_path": "public/app/plugins/datasource/postgres/partials/query.editor.html", "type": "replace", "edit_start_line_idx": 50 }
package middleware import ( "testing" "time" "github.com/grafana/grafana/pkg/login" m "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/setting" . "github.com/smartystreets/goconvey/convey" ) func TestAuthProxyWithLdapEnabled(t *testing.T) { Convey("When calling sync grafana user with ldap user", t, func() { setting.LdapEnabled = true setting.AuthProxyLdapSyncTtl = 60 servers := []*login.LdapServerConf{{Host: "127.0.0.1"}} login.LdapCfg = login.LdapConfig{Servers: servers} mockLdapAuther := mockLdapAuthenticator{} login.NewLdapAuthenticator = func(server *login.LdapServerConf) login.ILdapAuther { return &mockLdapAuther } signedInUser := m.SignedInUser{} query := m.GetSignedInUserQuery{Result: &signedInUser} Convey("When session variable lastLdapSync not set, call syncSignedInUser and set lastLdapSync", func() { // arrange session := mockSession{} ctx := Context{Session: &session} So(session.Get(SESS_KEY_LASTLDAPSYNC), ShouldBeNil) // act syncGrafanaUserWithLdapUser(&ctx, &query) // assert So(mockLdapAuther.syncSignedInUserCalled, ShouldBeTrue) So(session.Get(SESS_KEY_LASTLDAPSYNC), ShouldBeGreaterThan, 0) }) Convey("When session variable not expired, don't sync and don't change session var", func() { // arrange session := mockSession{} ctx := Context{Session: &session} now := time.Now().Unix() session.Set(SESS_KEY_LASTLDAPSYNC, now) // act syncGrafanaUserWithLdapUser(&ctx, &query) // assert So(session.Get(SESS_KEY_LASTLDAPSYNC), ShouldEqual, now) So(mockLdapAuther.syncSignedInUserCalled, ShouldBeFalse) }) Convey("When lastldapsync is expired, session variable should be updated", func() { // arrange session := mockSession{} ctx := Context{Session: &session} expiredTime := time.Now().Add(time.Duration(-120) * time.Minute).Unix() session.Set(SESS_KEY_LASTLDAPSYNC, expiredTime) // act syncGrafanaUserWithLdapUser(&ctx, &query) // assert So(session.Get(SESS_KEY_LASTLDAPSYNC), ShouldBeGreaterThan, expiredTime) So(mockLdapAuther.syncSignedInUserCalled, ShouldBeTrue) }) }) } type mockSession struct { value interface{} } func (s *mockSession) Start(c *Context) error { return nil } func (s *mockSession) Set(k interface{}, v interface{}) error { s.value = v return nil } func (s *mockSession) Get(k interface{}) interface{} { return s.value } func (s *mockSession) Delete(k interface{}) interface{} { return nil } func (s *mockSession) ID() string { return "" } func (s *mockSession) Release() error { return nil } func (s *mockSession) Destory(c *Context) error { return nil } func (s *mockSession) RegenerateId(c *Context) error { return nil } type mockLdapAuthenticator struct { syncSignedInUserCalled bool } func (a *mockLdapAuthenticator) Login(query *login.LoginUserQuery) error { return nil } func (a *mockLdapAuthenticator) SyncSignedInUser(signedInUser *m.SignedInUser) error { a.syncSignedInUserCalled = true return nil } func (a *mockLdapAuthenticator) GetGrafanaUserFor(ldapUser *login.LdapUserInfo) (*m.User, error) { return nil, nil } func (a *mockLdapAuthenticator) SyncOrgRoles(user *m.User, ldapUser *login.LdapUserInfo) error { return nil }
pkg/middleware/auth_proxy_test.go
0
https://github.com/grafana/grafana/commit/108f582ec4a42dfd96760df527c68171b75ef79d
[ 0.00022954566520638764, 0.00017669623775873333, 0.00016512810543645173, 0.00016827270155772567, 0.000017988539184443653 ]
{ "id": 3, "code_window": [ "\n", "Macros:\n", "- $__time(column) -&gt; column as \"time\"\n", "- $__timeEpoch -&gt; extract(epoch from column) as \"time\"\n", "- $__timeFilter(column) -&gt; column &ge; to_timestamp(1492750877) AND column &le; to_timestamp(1492750877)\n", "- $__unixEpochFilter(column) -&gt; column &gt; 1492750877 AND column &lt; 1492750877\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "- $__timeFilter(column) -&gt; extract(epoch from column) BETWEEN 1492750877 AND 1492750877\n" ], "file_path": "public/app/plugins/datasource/postgres/partials/query.editor.html", "type": "replace", "edit_start_line_idx": 50 }
// Copyright (c) 2014, Hugh Kennedy // Based on code from https://github.com/hughsk/flat/blob/master/index.js // export default function flatten(target, opts): any { opts = opts || {}; var delimiter = opts.delimiter || '.'; var maxDepth = opts.maxDepth || 3; var currentDepth = 1; var output = {}; function step(object, prev) { Object.keys(object).forEach(function(key) { var value = object[key]; var isarray = opts.safe && Array.isArray(value); var type = Object.prototype.toString.call(value); var isobject = type === "[object Object]"; var newKey = prev ? prev + delimiter + key : key; if (!opts.maxDepth) { maxDepth = currentDepth + 1; } if (!isarray && isobject && Object.keys(value).length && currentDepth < maxDepth) { ++currentDepth; return step(value, newKey); } output[newKey] = value; }); } step(target, null); return output; }
public/app/core/utils/flatten.ts
0
https://github.com/grafana/grafana/commit/108f582ec4a42dfd96760df527c68171b75ef79d
[ 0.00018341501709073782, 0.00017093167116399854, 0.00016480122576467693, 0.00016775522090028971, 0.000007345779067691183 ]
{ "id": 3, "code_window": [ "\n", "Macros:\n", "- $__time(column) -&gt; column as \"time\"\n", "- $__timeEpoch -&gt; extract(epoch from column) as \"time\"\n", "- $__timeFilter(column) -&gt; column &ge; to_timestamp(1492750877) AND column &le; to_timestamp(1492750877)\n", "- $__unixEpochFilter(column) -&gt; column &gt; 1492750877 AND column &lt; 1492750877\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "- $__timeFilter(column) -&gt; extract(epoch from column) BETWEEN 1492750877 AND 1492750877\n" ], "file_path": "public/app/plugins/datasource/postgres/partials/query.editor.html", "type": "replace", "edit_start_line_idx": 50 }
define([ 'angular', '../core_module', 'app/core/config', ], function (angular, coreModule, config) { 'use strict'; config = config.default; coreModule.default.controller('InvitedCtrl', function($scope, $routeParams, contextSrv, backendSrv) { contextSrv.sidemenu = false; $scope.formModel = {}; $scope.init = function() { backendSrv.get('/api/user/invite/' + $routeParams.code).then(function(invite) { $scope.formModel.name = invite.name; $scope.formModel.email = invite.email; $scope.formModel.username = invite.email; $scope.formModel.inviteCode = $routeParams.code; $scope.greeting = invite.name || invite.email || invite.username; $scope.invitedBy = invite.invitedBy; }); }; $scope.submit = function() { if (!$scope.inviteForm.$valid) { return; } backendSrv.post('/api/user/invite/complete', $scope.formModel).then(function() { window.location.href = config.appSubUrl + '/'; }); }; $scope.init(); }); });
public/app/core/controllers/invited_ctrl.js
0
https://github.com/grafana/grafana/commit/108f582ec4a42dfd96760df527c68171b75ef79d
[ 0.0049746097065508366, 0.001130602671764791, 0.00016811088426038623, 0.0001704170135781169, 0.0019220039248466492 ]
{ "id": 4, "code_window": [ "- $__unixEpochFilter(column) -&gt; column &gt; 1492750877 AND column &lt; 1492750877\n", "- $__timeGroup(column,'5m') -&gt; (extract(epoch from \"dateColumn\")/extract(epoch from '5m'::interval))::int\n", "\n", "Example of group by and order by with $__timeGroup:\n", "SELECT\n", " $__timeGroup(date_time_col, '1h') AS time,\n", " sum(value) as value\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "- $__timeGroup(column,'5m') -&gt; (extract(epoch from \"dateColumn\")/300)::bigint*300\n" ], "file_path": "public/app/plugins/datasource/postgres/partials/query.editor.html", "type": "replace", "edit_start_line_idx": 52 }
+++ title = "Using PostgreSQL in Grafana" description = "Guide for using PostgreSQL in Grafana" keywords = ["grafana", "postgresql", "guide"] type = "docs" [menu.docs] name = "PostgreSQL" parent = "datasources" weight = 7 +++ # Using PostgreSQL in Grafana Grafana ships with a built-in PostgreSQL data source plugin that allows you to query and visualize data from a PostgreSQL compatible database. ## Adding the data source 1. Open the side menu by clicking the Grafana icon in the top header. 2. In the side menu under the `Dashboards` link you should find a link named `Data Sources`. 3. Click the `+ Add data source` button in the top header. 4. Select *PostgreSQL* from the *Type* dropdown. ### Database User Permissions (Important!) The database user you specify when you add the data source should only be granted SELECT permissions on the specified database & tables you want to query. Grafana does not validate that the query is safe. The query could include any SQL statement. For example, statements like `DELETE FROM user;` and `DROP TABLE user;` would be executed. To protect against this we **Highly** recommmend you create a specific postgresql user with restricted permissions. Example: ```sql CREATE USER grafanareader WITH PASSWORD 'password'; GRANT USAGE ON SCHEMA schema TO grafanareader; GRANT SELECT ON schema.table TO grafanareader; ``` Make sure the user does not get any unwanted privileges from the public role. ## Macros To simplify syntax and to allow for dynamic parts, like date range filters, the query can contain macros. Macro example | Description ------------ | ------------- *$__time(dateColumn)* | Will be replaced by an expression to rename the column to `time`. For example, *dateColumn as time* *$__timeSec(dateColumn)* | Will be replaced by an expression to rename the column to `time` and converting the value to unix timestamp. For example, *extract(epoch from dateColumn) as time* *$__timeFilter(dateColumn)* | Will be replaced by a time range filter using the specified column name. For example, *dateColumn > to_timestamp(1494410783) AND dateColumn < to_timestamp(1494497183)* *$__timeFrom()* | Will be replaced by the start of the currently active time selection. For example, *to_timestamp(1494410783)* *$__timeTo()* | Will be replaced by the end of the currently active time selection. For example, *to_timestamp(1494497183)* *$__timeGroup(dateColumn,'5m')* | Will be replaced by an expression usable in GROUP BY clause. For example, *(extract(epoch from "dateColumn")/extract(epoch from '5m'::interval))::int*extract(epoch from '5m'::interval)* *$__unixEpochFilter(dateColumn)* | Will be replaced by a time range filter using the specified column name with times represented as unix timestamp. For example, *dateColumn > 1494410783 AND dateColumn < 1494497183* *$__unixEpochFrom()* | Will be replaced by the start of the currently active time selection as unix timestamp. For example, *1494410783* *$__unixEpochTo()* | Will be replaced by the end of the currently active time selection as unix timestamp. For example, *1494497183* We plan to add many more macros. If you have suggestions for what macros you would like to see, please [open an issue](https://github.com/grafana/grafana) in our GitHub repo. The query editor has a link named `Generated SQL` that shows up after a query as been executed, while in panel edit mode. Click on it and it will expand and show the raw interpolated SQL string that was executed. ## Table queries If the `Format as` query option is set to `Table` then you can basically do any type of SQL query. The table panel will automatically show the results of whatever columns & rows your query returns. Query editor with example query: ![](/img/docs/v46/postgres_table_query.png) The query: ```sql SELECT title as "Title", "user".login as "Created By", dashboard.created as "Created On" FROM dashboard INNER JOIN "user" on "user".id = dashboard.created_by WHERE $__timeFilter(dashboard.created) ``` You can control the name of the Table panel columns by using regular `as ` SQL column selection syntax. The resulting table panel: ![](/img/docs/v46/postgres_table.png) ### Time series queries If you set `Format as` to `Time series`, for use in Graph panel for example, then the query must return a column named `time` that returns either a sql datetime or any numeric datatype representing unix epoch in seconds. Any column except `time` and `metric` is treated as a value column. You may return a column named `metric` that is used as metric name for the value column. Example with `metric` column ```sql SELECT $__timeGroup(time_date_time,'5m') as time, min(value_double), 'min' as metric FROM test_data WHERE $__timeFilter(time_date_time) GROUP BY time ORDER BY time ``` Example with multiple columns: ```sql SELECT $__timeGroup(time_date_time,'5m') as time, min(value_double) as min_value, max(value_double) as max_value FROM test_data WHERE $__timeFilter(time_date_time) GROUP BY time ORDER BY time ``` ## Templating Instead of hard-coding things like server, application and sensor name in you metric queries you can use variables in their place. Variables are shown as dropdown select boxes at the top of the dashboard. These dropdowns makes it easy to change the data being displayed in your dashboard. Checkout the [Templating]({{< relref "reference/templating.md" >}}) documentation for an introduction to the templating feature and the different types of template variables. ### Query Variable If you add a template variable of the type `Query`, you can write a PostgreSQL query that can return things like measurement names, key names or key values that are shown as a dropdown select box. For example, you can have a variable that contains all values for the `hostname` column in a table if you specify a query like this in the templating variable *Query* setting. ```sql SELECT hostname FROM host ``` A query can return multiple columns and Grafana will automatically create a list from them. For example, the query below will return a list with values from `hostname` and `hostname2`. ```sql SELECT host.hostname, other_host.hostname2 FROM host JOIN other_host ON host.city = other_host.city ``` Another option is a query that can create a key/value variable. The query should return two columns that are named `__text` and `__value`. The `__text` column value should be unique (if it is not unique then the first value is used). The options in the dropdown will have a text and value that allows you to have a friendly name as text and an id as the value. An example query with `hostname` as the text and `id` as the value: ```sql SELECT hostname AS __text, id AS __value FROM host ``` You can also create nested variables. For example if you had another variable named `region`. Then you could have the hosts variable only show hosts from the current selected region with a query like this (if `region` is a multi-value variable then use the `IN` comparison operator rather than `=` to match against multiple values): ```sql SELECT hostname FROM host WHERE region IN($region) ``` ### Using Variables in Queries From Grafana 4.3.0 to 4.6.0, template variables are always quoted automatically so if it is a string value do not wrap them in quotes in where clauses. From Grafana 4.7.0, template variable values are only quoted when the template variable is a `multi-value`. If the variable is a multi-value variable then use the `IN` comparison operator rather than `=` to match against multiple values. There are two syntaxes: `$<varname>` Example with a template variable named `hostname`: ```sql SELECT atimestamp as time, aint as value FROM table WHERE $__timeFilter(atimestamp) and hostname in($hostname) ORDER BY atimestamp ASC ``` `[[varname]]` Example with a template variable named `hostname`: ```sql SELECT atimestamp as time, aint as value FROM table WHERE $__timeFilter(atimestamp) and hostname in([[hostname]]) ORDER BY atimestamp ASC ``` ## Annotations [Annotations]({{< relref "reference/annotations.md" >}}) allow you to overlay rich event information on top of graphs. You add annotation queries via the Dashboard menu / Annotations view. An example query: ```sql SELECT extract(epoch from time_date_time) AS time, metric1 as text, concat_ws(', ', metric1::text, metric2::text) as tags FROM public.test_data WHERE $__timeFilter(time_date_time) ``` Name | Description ------------ | ------------- time | The name of the date/time field. text | Event description field. tags | Optional field name to use for event tags as a comma separated string. ## Alerting Time series queries should work in alerting conditions. Table formatted queries is not yet supported in alert rule conditions.
docs/sources/features/datasources/postgres.md
1
https://github.com/grafana/grafana/commit/108f582ec4a42dfd96760df527c68171b75ef79d
[ 0.9748527407646179, 0.17213615775108337, 0.00016281494754366577, 0.0002762888325378299, 0.35576775670051575 ]
{ "id": 4, "code_window": [ "- $__unixEpochFilter(column) -&gt; column &gt; 1492750877 AND column &lt; 1492750877\n", "- $__timeGroup(column,'5m') -&gt; (extract(epoch from \"dateColumn\")/extract(epoch from '5m'::interval))::int\n", "\n", "Example of group by and order by with $__timeGroup:\n", "SELECT\n", " $__timeGroup(date_time_col, '1h') AS time,\n", " sum(value) as value\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "- $__timeGroup(column,'5m') -&gt; (extract(epoch from \"dateColumn\")/300)::bigint*300\n" ], "file_path": "public/app/plugins/datasource/postgres/partials/query.editor.html", "type": "replace", "edit_start_line_idx": 52 }
{ "stable": "4.5.2", "testing": "4.5.2" }
latest.json
0
https://github.com/grafana/grafana/commit/108f582ec4a42dfd96760df527c68171b75ef79d
[ 0.00017215852858498693, 0.00017215852858498693, 0.00017215852858498693, 0.00017215852858498693, 0 ]
{ "id": 4, "code_window": [ "- $__unixEpochFilter(column) -&gt; column &gt; 1492750877 AND column &lt; 1492750877\n", "- $__timeGroup(column,'5m') -&gt; (extract(epoch from \"dateColumn\")/extract(epoch from '5m'::interval))::int\n", "\n", "Example of group by and order by with $__timeGroup:\n", "SELECT\n", " $__timeGroup(date_time_col, '1h') AS time,\n", " sum(value) as value\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "- $__timeGroup(column,'5m') -&gt; (extract(epoch from \"dateColumn\")/300)::bigint*300\n" ], "file_path": "public/app/plugins/datasource/postgres/partials/query.editor.html", "type": "replace", "edit_start_line_idx": 52 }
declare var OpenTsDatasource: any; export default OpenTsDatasource;
public/app/plugins/datasource/opentsdb/datasource.d.ts
0
https://github.com/grafana/grafana/commit/108f582ec4a42dfd96760df527c68171b75ef79d
[ 0.00016935679013840854, 0.00016935679013840854, 0.00016935679013840854, 0.00016935679013840854, 0 ]
{ "id": 4, "code_window": [ "- $__unixEpochFilter(column) -&gt; column &gt; 1492750877 AND column &lt; 1492750877\n", "- $__timeGroup(column,'5m') -&gt; (extract(epoch from \"dateColumn\")/extract(epoch from '5m'::interval))::int\n", "\n", "Example of group by and order by with $__timeGroup:\n", "SELECT\n", " $__timeGroup(date_time_col, '1h') AS time,\n", " sum(value) as value\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "- $__timeGroup(column,'5m') -&gt; (extract(epoch from \"dateColumn\")/300)::bigint*300\n" ], "file_path": "public/app/plugins/datasource/postgres/partials/query.editor.html", "type": "replace", "edit_start_line_idx": 52 }
.json-formatter-row { font-family: monospace; &, a, a:hover { color: $json-explorer-default-color; text-decoration: none; } .json-formatter-row { margin-left: 1rem; } .json-formatter-children { &.json-formatter-empty { opacity: 0.5; margin-left: 1rem; &::after { display: none; } &.json-formatter-object::after { content: "No properties"; } &.json-formatter-array::after { content: "[]"; } } } .json-formatter-string { color: $json-explorer-string-color; white-space: normal; word-wrap: break-word; } .json-formatter-number { color: $json-explorer-number-color; } .json-formatter-boolean { color: $json-explorer-boolean-color; } .json-formatter-null { color: $json-explorer-null-color; } .json-formatter-undefined { color: $json-explorer-undefined-color; } .json-formatter-function { color: $json-explorer-function-color; } .json-formatter-date { background-color: fade($json-explorer-default-color, 5%); } .json-formatter-url { text-decoration: underline; color: $json-explorer-url-color; cursor: pointer; } .json-formatter-bracket { color: $json-explorer-bracket-color; } .json-formatter-key { color: $json-explorer-key-color; cursor: pointer; padding-right: 0.2rem; margin-right: 4px; } .json-formatter-constructor-name { cursor: pointer; } .json-formatter-array-comma { margin-right: 4px; } .json-formatter-toggler { line-height: 1.2rem; font-size: 0.7rem; vertical-align: middle; opacity: $json-explorer-toggler-opacity; cursor: pointer; padding-right: 0.2rem; &::after { display: inline-block; transition: transform $json-explorer-rotate-time ease-in; content: "►"; } } // Inline preview on hover (optional) > a > .json-formatter-preview-text { opacity: 0; transition: opacity .15s ease-in; font-style: italic; } &:hover > a > .json-formatter-preview-text { opacity: 0.6; } // Open state &.json-formatter-open { > .json-formatter-toggler-link .json-formatter-toggler::after{ transform: rotate(90deg); } > .json-formatter-children::after { display: inline-block; } > a > .json-formatter-preview-text { display: none; } &.json-formatter-empty::after { display: block; } } }
public/sass/components/_json_explorer.scss
0
https://github.com/grafana/grafana/commit/108f582ec4a42dfd96760df527c68171b75ef79d
[ 0.00017756540910340846, 0.000175782639416866, 0.00017295208817813545, 0.00017565503367222846, 0.0000013129387070875964 ]
{ "id": 0, "code_window": [ " if (key === 'color') {\n", " classKey += isEmpty(classKey) ? props[key] : capitalize(props[key]);\n", " } else {\n", " classKey += `${isEmpty(classKey) ? key : capitalize(key)}${capitalize(props[key])}`;\n", " }\n", " });\n", "\n", " return classKey;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " classKey += `${isEmpty(classKey) ? key : capitalize(key)}${capitalize(\n", " props[key].toString(),\n", " )}`;\n" ], "file_path": "packages/material-ui-styles/src/propsToClassKey/propsToClassKey.js", "type": "replace", "edit_start_line_idx": 31 }
import { expect } from 'chai'; import propsToClassKey from './propsToClassKey'; describe('propsToClassKey', () => { it('should return the variant value as string', () => { expect(propsToClassKey({ variant: 'custom' })).to.equal('custom'); }); it('should combine the variant with other props', () => { expect(propsToClassKey({ variant: 'custom', size: 'large' })).to.equal('customSizeLarge'); }); it('should append the props after the variant in alphabetical order', () => { expect(propsToClassKey({ variant: 'custom', size: 'large', mode: 'static' })).to.equal( 'customModeStaticSizeLarge', ); }); it('should not prefix the color prop', () => { expect(propsToClassKey({ variant: 'custom', color: 'primary' })).to.equal('customPrimary'); }); it('should work without variant in props', () => { expect(propsToClassKey({ color: 'primary', size: 'large', mode: 'static' })).to.equal( 'primaryModeStaticSizeLarge', ); }); it('should not capitalize the first prop ', () => { expect(propsToClassKey({ size: 'large', zIndex: 'toolbar' })).to.equal( 'sizeLargeZIndexToolbar', ); }); });
packages/material-ui-styles/src/propsToClassKey/propsToClassKey.test.js
1
https://github.com/mui/material-ui/commit/16c648dfd8d9b47772a44f3a77c6648a55557d80
[ 0.00020521438273135573, 0.00017678247240837663, 0.00016353158571291715, 0.00016919197514653206, 0.000016832815163070336 ]
{ "id": 0, "code_window": [ " if (key === 'color') {\n", " classKey += isEmpty(classKey) ? props[key] : capitalize(props[key]);\n", " } else {\n", " classKey += `${isEmpty(classKey) ? key : capitalize(key)}${capitalize(props[key])}`;\n", " }\n", " });\n", "\n", " return classKey;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " classKey += `${isEmpty(classKey) ? key : capitalize(key)}${capitalize(\n", " props[key].toString(),\n", " )}`;\n" ], "file_path": "packages/material-ui-styles/src/propsToClassKey/propsToClassKey.js", "type": "replace", "edit_start_line_idx": 31 }
--- title: Tree View React component components: TreeView, TreeItem githubLabel: 'component: TreeView' waiAria: 'https://www.w3.org/TR/wai-aria-practices/#TreeView' packageName: '@material-ui/lab' --- # Tree View (Vue arborescente) <p class="description">A tree view widget presents a hierarchical list.</p> Tree views can be used to represent a file system navigator displaying folders and files, an item representing a folder can be expanded to reveal the contents of the folder, which may be files, folders, or both. {{"component": "modules/components/ComponentLinkHeader.js"}} ## Basic tree view {{"demo": "pages/components/tree-view/FileSystemNavigator.js"}} ## Multi-sélection L'arborescence prend également en charge la sélection multiple. {{"demo": "pages/components/tree-view/MultiSelectTreeView.js"}} ## Controlled tree view The tree view also offers a controlled API. {{"demo": "pages/components/tree-view/ControlledTreeView.js"}} ## Rich object While the `TreeView`/`TreeItem` component API maximizes flexibility, an extra step is needed to handle a rich object. Let's consider a data variable with the following shape, recursion can be used to handle it. ```js const data = { id: 'root', name: 'Parent', children: [ { id: '1', name: 'Child - 1', }, // … ], }; ``` {{"demo": "pages/components/tree-view/RecursiveTreeView.js", "defaultCodeOpen": false}} ## ContentComponent prop You can use the `ContentComponent` prop and the `useTreeItem` hook to further customize the behavior of the TreeItem. Such as limiting expansion to clicking the icon: {{"demo": "pages/components/tree-view/IconExpansionTreeView.js", "defaultCodeOpen": false}} Or increasing the width of the state indicator: {{"demo": "pages/components/tree-view/BarTreeView.js", "defaultCodeOpen": false}} ## Customized tree view ### Custom icons, border and animation {{"demo": "pages/components/tree-view/CustomizedTreeView.js"}} ### Gmail clone {{"demo": "pages/components/tree-view/GmailTreeView.js"}} ## Items désactivés {{"demo": "pages/components/tree-view/DisabledTreeItems.js"}} Le comportement des items désactivés dépend de la propriété `disabledItemsFocusable`. Si elle vaut `false`: - Arrow keys will not focus disabled items and, the next non-disabled item will be focused. - Typing the first character of a disabled item's label will not focus the item. - Mouse or keyboard interaction will not expand/collapse disabled items. - Mouse or keyboard interaction will not select disabled items. - Shift + arrow keys will skip disabled items and, the next non-disabled item will be selected. - Programmatic focus will not focus disabled items. Si elle vaut `true`: - Arrow keys will focus disabled items. - Taper le premier caractère du label d'un élément désactivé pour mettre le focus sur l'élément. - Mouse or keyboard interaction will not expand/collapse disabled items. - Mouse or keyboard interaction will not select disabled items. - Shift + arrow keys will not skip disabled items but, the disabled item will not be selected. - Programmatic focus will focus disabled items. ## Accessibilité (WAI-ARIA: https://www.w3.org/TR/wai-aria-practices/#TreeView) The component follows the WAI-ARIA authoring practices. To have an accessible tree view you must use `aria-labelledby` or `aria-label` to reference or provide a label on the TreeView, otherwise screen readers will announce it as "tree", making it hard to understand the context of a specific tree item.
docs/src/pages/components/tree-view/tree-view-fr.md
0
https://github.com/mui/material-ui/commit/16c648dfd8d9b47772a44f3a77c6648a55557d80
[ 0.00017648075299803168, 0.00017057843797374517, 0.00016451282135676593, 0.00017085274157579988, 0.000003703997663251357 ]
{ "id": 0, "code_window": [ " if (key === 'color') {\n", " classKey += isEmpty(classKey) ? props[key] : capitalize(props[key]);\n", " } else {\n", " classKey += `${isEmpty(classKey) ? key : capitalize(key)}${capitalize(props[key])}`;\n", " }\n", " });\n", "\n", " return classKey;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " classKey += `${isEmpty(classKey) ? key : capitalize(key)}${capitalize(\n", " props[key].toString(),\n", " )}`;\n" ], "file_path": "packages/material-ui-styles/src/propsToClassKey/propsToClassKey.js", "type": "replace", "edit_start_line_idx": 31 }
import * as React from 'react'; import { expect } from 'chai'; import { getClasses, createMount, createClientRender, describeConformance } from 'test/utils'; import TableHead from './TableHead'; import Tablelvl2Context from '../Table/Tablelvl2Context'; describe('<TableHead />', () => { const mount = createMount(); let classes; const render = createClientRender(); function renderInTable(node) { return render(<table>{node}</table>); } before(() => { classes = getClasses(<TableHead>foo</TableHead>); }); describeConformance(<TableHead />, () => ({ classes, inheritComponent: 'thead', mount: (node) => { const wrapper = mount(<table>{node}</table>); return wrapper.find('table').childAt(0); }, refInstanceof: window.HTMLTableSectionElement, testComponentPropWith: 'tbody', })); it('should render children', () => { const children = <tr data-testid="test" />; const { getByTestId } = renderInTable(<TableHead>{children}</TableHead>); getByTestId('test'); }); it('should define table.head in the child context', () => { let context; // TODO: test integration with TableCell renderInTable( <TableHead> <Tablelvl2Context.Consumer> {(value) => { context = value; }} </Tablelvl2Context.Consumer> </TableHead>, ); expect(context.variant).to.equal('head'); }); describe('prop: component', () => { it('can render a different component', () => { const { container } = render(<TableHead component="div" />); expect(container.firstChild).to.have.property('nodeName', 'DIV'); }); it('sets role="rowgroup"', () => { const { container } = render(<TableHead component="div" />); expect(container.firstChild).to.have.attribute('role', 'rowgroup'); }); }); });
packages/material-ui/src/TableHead/TableHead.test.js
0
https://github.com/mui/material-ui/commit/16c648dfd8d9b47772a44f3a77c6648a55557d80
[ 0.00017708775703795254, 0.00017448922153562307, 0.00016937196778599173, 0.0001756874262355268, 0.000002657699269548175 ]
{ "id": 0, "code_window": [ " if (key === 'color') {\n", " classKey += isEmpty(classKey) ? props[key] : capitalize(props[key]);\n", " } else {\n", " classKey += `${isEmpty(classKey) ? key : capitalize(key)}${capitalize(props[key])}`;\n", " }\n", " });\n", "\n", " return classKey;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " classKey += `${isEmpty(classKey) ? key : capitalize(key)}${capitalize(\n", " props[key].toString(),\n", " )}`;\n" ], "file_path": "packages/material-ui-styles/src/propsToClassKey/propsToClassKey.js", "type": "replace", "edit_start_line_idx": 31 }
export default function memoize(fn) { const cache = {}; return (arg) => { if (cache[arg] === undefined) { cache[arg] = fn(arg); } return cache[arg]; }; }
packages/material-ui-system/src/memoize.js
0
https://github.com/mui/material-ui/commit/16c648dfd8d9b47772a44f3a77c6648a55557d80
[ 0.0013617435470223427, 0.000769790553022176, 0.00017783752991817892, 0.000769790553022176, 0.0005919530522078276 ]
{ "id": 1, "code_window": [ " expect(propsToClassKey({ color: 'primary', size: 'large', mode: 'static' })).to.equal(\n", " 'primaryModeStaticSizeLarge',\n", " );\n", " });\n", "\n", " it('should not capitalize the first prop ', () => {\n", " expect(propsToClassKey({ size: 'large', zIndex: 'toolbar' })).to.equal(\n", " 'sizeLargeZIndexToolbar',\n", " );\n", " });\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " it('should not capitalize the first prop', () => {\n" ], "file_path": "packages/material-ui-styles/src/propsToClassKey/propsToClassKey.test.js", "type": "replace", "edit_start_line_idx": 28 }
import { expect } from 'chai'; import propsToClassKey from './propsToClassKey'; describe('propsToClassKey', () => { it('should return the variant value as string', () => { expect(propsToClassKey({ variant: 'custom' })).to.equal('custom'); }); it('should combine the variant with other props', () => { expect(propsToClassKey({ variant: 'custom', size: 'large' })).to.equal('customSizeLarge'); }); it('should append the props after the variant in alphabetical order', () => { expect(propsToClassKey({ variant: 'custom', size: 'large', mode: 'static' })).to.equal( 'customModeStaticSizeLarge', ); }); it('should not prefix the color prop', () => { expect(propsToClassKey({ variant: 'custom', color: 'primary' })).to.equal('customPrimary'); }); it('should work without variant in props', () => { expect(propsToClassKey({ color: 'primary', size: 'large', mode: 'static' })).to.equal( 'primaryModeStaticSizeLarge', ); }); it('should not capitalize the first prop ', () => { expect(propsToClassKey({ size: 'large', zIndex: 'toolbar' })).to.equal( 'sizeLargeZIndexToolbar', ); }); });
packages/material-ui-styles/src/propsToClassKey/propsToClassKey.test.js
1
https://github.com/mui/material-ui/commit/16c648dfd8d9b47772a44f3a77c6648a55557d80
[ 0.9502312541007996, 0.24225933849811554, 0.0004569601151160896, 0.00917457602918148, 0.40876463055610657 ]
{ "id": 1, "code_window": [ " expect(propsToClassKey({ color: 'primary', size: 'large', mode: 'static' })).to.equal(\n", " 'primaryModeStaticSizeLarge',\n", " );\n", " });\n", "\n", " it('should not capitalize the first prop ', () => {\n", " expect(propsToClassKey({ size: 'large', zIndex: 'toolbar' })).to.equal(\n", " 'sizeLargeZIndexToolbar',\n", " );\n", " });\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " it('should not capitalize the first prop', () => {\n" ], "file_path": "packages/material-ui-styles/src/propsToClassKey/propsToClassKey.test.js", "type": "replace", "edit_start_line_idx": 28 }
import * as React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M22 22H2v-2h20v2zM10 2H7v16h3V2zm7 6h-3v10h3V8z" /> , 'AlignVerticalBottom');
packages/material-ui-icons/src/AlignVerticalBottom.js
0
https://github.com/mui/material-ui/commit/16c648dfd8d9b47772a44f3a77c6648a55557d80
[ 0.00017628681962378323, 0.00017628681962378323, 0.00017628681962378323, 0.00017628681962378323, 0 ]
{ "id": 1, "code_window": [ " expect(propsToClassKey({ color: 'primary', size: 'large', mode: 'static' })).to.equal(\n", " 'primaryModeStaticSizeLarge',\n", " );\n", " });\n", "\n", " it('should not capitalize the first prop ', () => {\n", " expect(propsToClassKey({ size: 'large', zIndex: 'toolbar' })).to.equal(\n", " 'sizeLargeZIndexToolbar',\n", " );\n", " });\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " it('should not capitalize the first prop', () => {\n" ], "file_path": "packages/material-ui-styles/src/propsToClassKey/propsToClassKey.test.js", "type": "replace", "edit_start_line_idx": 28 }
import * as React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M18 16l4-4-4-4v3h-5.06C12.6 7.9 10.68 5.28 8 3.95 7.96 2.31 6.64 1 5 1 3.34 1 2 2.34 2 4s1.34 3 3 3c.95 0 1.78-.45 2.33-1.14C9.23 6.9 10.6 8.77 10.92 11h-3.1C7.4 9.84 6.3 9 5 9c-1.66 0-3 1.34-3 3s1.34 3 3 3c1.3 0 2.4-.84 2.82-2h3.1c-.32 2.23-1.69 4.1-3.58 5.14C6.78 17.45 5.95 17 5 17c-1.66 0-3 1.34-3 3s1.34 3 3 3c1.64 0 2.96-1.31 2.99-2.95 2.68-1.33 4.6-3.95 4.94-7.05H18v3z" /> , 'MediationOutlined');
packages/material-ui-icons/src/MediationOutlined.js
0
https://github.com/mui/material-ui/commit/16c648dfd8d9b47772a44f3a77c6648a55557d80
[ 0.0001720622240100056, 0.0001720622240100056, 0.0001720622240100056, 0.0001720622240100056, 0 ]
{ "id": 1, "code_window": [ " expect(propsToClassKey({ color: 'primary', size: 'large', mode: 'static' })).to.equal(\n", " 'primaryModeStaticSizeLarge',\n", " );\n", " });\n", "\n", " it('should not capitalize the first prop ', () => {\n", " expect(propsToClassKey({ size: 'large', zIndex: 'toolbar' })).to.equal(\n", " 'sizeLargeZIndexToolbar',\n", " );\n", " });\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " it('should not capitalize the first prop', () => {\n" ], "file_path": "packages/material-ui-styles/src/propsToClassKey/propsToClassKey.test.js", "type": "replace", "edit_start_line_idx": 28 }
{ "componentDescription": "", "propDescriptions": { "action": "The action to display in the card header.", "avatar": "The Avatar for the Card Header.", "classes": "Override or extend the styles applied to the component. See <a href=\"#css\">CSS API</a> below for more details.", "component": "The component used for the root node. Either a string to use a HTML element or a component.", "disableTypography": "If <code>true</code>, <code>subheader</code> and <code>title</code> won&#39;t be wrapped by a Typography component. This can be useful to render an alternative Typography variant by wrapping the <code>title</code> text, and optional <code>subheader</code> text with the Typography component.", "subheader": "The content of the component.", "subheaderTypographyProps": "These props will be forwarded to the subheader (as long as disableTypography is not <code>true</code>).", "title": "The content of the Card Title.", "titleTypographyProps": "These props will be forwarded to the title (as long as disableTypography is not <code>true</code>)." }, "classDescriptions": { "root": { "description": "Styles applied to the root element." }, "avatar": { "description": "Styles applied to the avatar element." }, "action": { "description": "Styles applied to the action element." }, "content": { "description": "Styles applied to the content wrapper element." }, "title": { "description": "Styles applied to the title Typography element." }, "subheader": { "description": "Styles applied to the subheader Typography element." } } }
docs/translations/api-docs/card-header/card-header-pt.json
0
https://github.com/mui/material-ui/commit/16c648dfd8d9b47772a44f3a77c6648a55557d80
[ 0.0001749180373735726, 0.00017080087854992598, 0.00016598337970208377, 0.00017150120402220637, 0.0000036810210986004677 ]
{ "id": 2, "code_window": [ " 'sizeLargeZIndexToolbar',\n", " );\n", " });\n", "});" ], "labels": [ "keep", "keep", "add", "keep" ], "after_edit": [ "\n", " it('should work with non string properties', () => {\n", " expect(propsToClassKey({ disabled: true, valid: false })).to.equal('disabledTrueValidFalse');\n", " });\n" ], "file_path": "packages/material-ui-styles/src/propsToClassKey/propsToClassKey.test.js", "type": "add", "edit_start_line_idx": 33 }
import { expect } from 'chai'; import propsToClassKey from './propsToClassKey'; describe('propsToClassKey', () => { it('should return the variant value as string', () => { expect(propsToClassKey({ variant: 'custom' })).to.equal('custom'); }); it('should combine the variant with other props', () => { expect(propsToClassKey({ variant: 'custom', size: 'large' })).to.equal('customSizeLarge'); }); it('should append the props after the variant in alphabetical order', () => { expect(propsToClassKey({ variant: 'custom', size: 'large', mode: 'static' })).to.equal( 'customModeStaticSizeLarge', ); }); it('should not prefix the color prop', () => { expect(propsToClassKey({ variant: 'custom', color: 'primary' })).to.equal('customPrimary'); }); it('should work without variant in props', () => { expect(propsToClassKey({ color: 'primary', size: 'large', mode: 'static' })).to.equal( 'primaryModeStaticSizeLarge', ); }); it('should not capitalize the first prop ', () => { expect(propsToClassKey({ size: 'large', zIndex: 'toolbar' })).to.equal( 'sizeLargeZIndexToolbar', ); }); });
packages/material-ui-styles/src/propsToClassKey/propsToClassKey.test.js
1
https://github.com/mui/material-ui/commit/16c648dfd8d9b47772a44f3a77c6648a55557d80
[ 0.8094737529754639, 0.20250821113586426, 0.00016480877820868045, 0.00019714146037586033, 0.3504317104816437 ]
{ "id": 2, "code_window": [ " 'sizeLargeZIndexToolbar',\n", " );\n", " });\n", "});" ], "labels": [ "keep", "keep", "add", "keep" ], "after_edit": [ "\n", " it('should work with non string properties', () => {\n", " expect(propsToClassKey({ disabled: true, valid: false })).to.equal('disabledTrueValidFalse');\n", " });\n" ], "file_path": "packages/material-ui-styles/src/propsToClassKey/propsToClassKey.test.js", "type": "add", "edit_start_line_idx": 33 }
import * as React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M9 13c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0-6c1.1 0 2 .9 2 2s-.9 2-2 2-2-.9-2-2 .9-2 2-2zm0 8c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4zm-6 4c.22-.72 3.31-2 6-2 2.7 0 5.8 1.29 6 2H3zM15.08 7.05c.84 1.18.84 2.71 0 3.89l1.68 1.69c2.02-2.02 2.02-5.07 0-7.27l-1.68 1.69zM20.07 2l-1.63 1.63c2.77 3.02 2.77 7.56 0 10.74L20.07 16c3.9-3.89 3.91-9.95 0-14z" /> , 'RecordVoiceOverOutlined');
packages/material-ui-icons/src/RecordVoiceOverOutlined.js
0
https://github.com/mui/material-ui/commit/16c648dfd8d9b47772a44f3a77c6648a55557d80
[ 0.0001696847757557407, 0.0001696847757557407, 0.0001696847757557407, 0.0001696847757557407, 0 ]
{ "id": 2, "code_window": [ " 'sizeLargeZIndexToolbar',\n", " );\n", " });\n", "});" ], "labels": [ "keep", "keep", "add", "keep" ], "after_edit": [ "\n", " it('should work with non string properties', () => {\n", " expect(propsToClassKey({ disabled: true, valid: false })).to.equal('disabledTrueValidFalse');\n", " });\n" ], "file_path": "packages/material-ui-styles/src/propsToClassKey/propsToClassKey.test.js", "type": "add", "edit_start_line_idx": 33 }
import * as React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M17.66 8L12 2.35 6.34 8C4.78 9.56 4 11.64 4 13.64s.78 4.11 2.34 5.67 3.61 2.35 5.66 2.35 4.1-.79 5.66-2.35S20 15.64 20 13.64 19.22 9.56 17.66 8zM6 14c.01-2 .62-3.27 1.76-4.4L12 5.27l4.24 4.38C17.38 10.77 17.99 12 18 14H6z" /> , 'OpacityOutlined');
packages/material-ui-icons/src/OpacityOutlined.js
0
https://github.com/mui/material-ui/commit/16c648dfd8d9b47772a44f3a77c6648a55557d80
[ 0.00017182104056701064, 0.00017182104056701064, 0.00017182104056701064, 0.00017182104056701064, 0 ]
{ "id": 2, "code_window": [ " 'sizeLargeZIndexToolbar',\n", " );\n", " });\n", "});" ], "labels": [ "keep", "keep", "add", "keep" ], "after_edit": [ "\n", " it('should work with non string properties', () => {\n", " expect(propsToClassKey({ disabled: true, valid: false })).to.equal('disabledTrueValidFalse');\n", " });\n" ], "file_path": "packages/material-ui-styles/src/propsToClassKey/propsToClassKey.test.js", "type": "add", "edit_start_line_idx": 33 }
import PropTypes from 'prop-types'; import { makeDateRangePicker } from '../DateRangePicker/makeDateRangePicker'; import StaticWrapper from '../internal/pickers/wrappers/StaticWrapper'; /** * @ignore - do not document. */ /* @typescript-to-proptypes-generate */ const StaticDateRangePicker = makeDateRangePicker('MuiPickersDateRangePicker', StaticWrapper); (StaticDateRangePicker as any).propTypes = { // ----------------------------- Warning -------------------------------- // | These PropTypes are generated from the TypeScript type definitions | // | To update them edit TypeScript types and run "yarn proptypes" | // ---------------------------------------------------------------------- /** * Regular expression to detect "accepted" symbols. * @default /\dap/gi */ acceptRegex: PropTypes.instanceOf(RegExp), /** * Enables keyboard listener for moving between days in calendar. * @default currentWrapper !== 'static' */ allowKeyboardControl: PropTypes.bool, /** * If `true`, `onChange` is fired on click even if the same date is selected. * @default false */ allowSameDateSelection: PropTypes.bool, /** * The number of calendars that render on **desktop**. * @default 2 */ calendars: PropTypes.oneOf([1, 2, 3]), /** * className applied to the root component. */ className: PropTypes.string, /** * Allows to pass configured date-io adapter directly. More info [here](https://next.material-ui-pickers.dev/guides/date-adapter-passing) * ```jsx * dateAdapter={new AdapterDateFns({ locale: ruLocale })} * ``` */ dateAdapter: PropTypes.object, /** * Default calendar month displayed when `value={null}`. * @default `new Date()` */ defaultCalendarMonth: PropTypes.any, /** * if `true` after selecting `start` date calendar will not automatically switch to the month of `end` date * @default false */ disableAutoMonthSwitching: PropTypes.bool, /** * If `true` the popup or dialog will immediately close after submitting full date. * @default `true` for Desktop, `false` for Mobile (based on the chosen wrapper and `desktopModeMediaQuery` prop). */ disableCloseOnSelect: PropTypes.bool, /** * If `true`, the picker and text field are disabled. */ disabled: PropTypes.bool, /** * Disable future dates. * @default false */ disableFuture: PropTypes.bool, /** * If `true`, todays date is rendering without highlighting with circle. * @default false */ disableHighlightToday: PropTypes.bool, /** * Disable mask on the keyboard, this should be used rarely. Consider passing proper mask for your format. * @default false */ disableMaskedInput: PropTypes.bool, /** * Do not render open picker button (renders only text field with validation). * @default false */ disableOpenPicker: PropTypes.bool, /** * Disable past dates. * @default false */ disablePast: PropTypes.bool, /** * Force static wrapper inner components to be rendered in mobile or desktop mode * @default "static" */ displayStaticWrapperAs: PropTypes.oneOf(['desktop', 'mobile']), /** * Text for end input label and toolbar placeholder. * @default "end" */ endText: PropTypes.node, /** * Get aria-label text for control that opens picker dialog. Aria-label text must include selected date. @DateIOType * @default (value, utils) => `Choose date, selected date is ${utils.format(utils.date(value), 'fullDate')}` */ getOpenDialogAriaText: PropTypes.func, /** * Get aria-label text for switching between views button. */ getViewSwitchingButtonText: PropTypes.func, /** * @ignore */ ignoreInvalidInputs: PropTypes.bool, /** * Props to pass to keyboard input adornment. */ InputAdornmentProps: PropTypes.object, /** * Format string. */ inputFormat: PropTypes.string, /** * @ignore */ InputProps: PropTypes.object, /** * @ignore */ key: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), /** * @ignore */ label: PropTypes.node, /** * Props to pass to left arrow button. */ leftArrowButtonProps: PropTypes.object, /** * Left arrow icon aria-label text. */ leftArrowButtonText: PropTypes.string, /** * Left arrow icon. */ leftArrowIcon: PropTypes.node, /** * If `true` renders `LoadingComponent` in calendar instead of calendar view. * Can be used to preload information and show it in calendar. * @default false */ loading: PropTypes.bool, /** * Custom mask. Can be used to override generate from format. (e.g. __/__/____ __:__ or __/__/____ __:__ _M) */ mask: PropTypes.string, /** * Max selectable date. @DateIOType * @default Date(2099-31-12) */ maxDate: PropTypes.any, /** * Min selectable date. @DateIOType * @default Date(1900-01-01) */ minDate: PropTypes.any, /** * Callback fired when date is accepted @DateIOType. */ onAccept: PropTypes.func, /** * Callback fired when the value (the selected date) changes. @DateIOType. */ onChange: PropTypes.func.isRequired, /** * Callback fired when the popup requests to be closed. * Use in controlled mode (see open). */ onClose: PropTypes.func, /** * Callback that fired when input value or new `value` prop validation returns **new** validation error (or value is valid after error). * In case of validation error detected `reason` prop return non-null value and `TextField` must be displayed in `error` state. * This can be used to render appropriate form error. * * [Read the guide](https://next.material-ui-pickers.dev/guides/forms) about form integration and error displaying. * @DateIOType */ onError: PropTypes.func, /** * Callback firing on month change. @DateIOType */ onMonthChange: PropTypes.func, /** * Callback fired when the popup requests to be opened. * Use in controlled mode (see open). */ onOpen: PropTypes.func, /** * Callback fired on view change. */ onViewChange: PropTypes.func, /** * Control the popup or dialog open state. */ open: PropTypes.bool, /** * Props to pass to keyboard adornment button. */ OpenPickerButtonProps: PropTypes.object, /** * Icon displaying for open picker button. */ openPickerIcon: PropTypes.node, /** * Force rendering in particular orientation. */ orientation: PropTypes.oneOf(['landscape', 'portrait']), /** * Make picker read only. */ readOnly: PropTypes.bool, /** * Disable heavy animations. * @default /(android)/i.test(window.navigator.userAgent). */ reduceAnimations: PropTypes.bool, /** * Custom renderer for `<DateRangePicker />` days. @DateIOType * @example (date, DateRangeDayProps) => <DateRangePickerDay {...DateRangeDayProps} /> */ renderDay: PropTypes.func, /** * The `renderInput` prop allows you to customize the rendered input. * The `startProps` and `endProps` arguments of this render prop contains props of [TextField](https://material-ui.com/api/text-field/#textfield-api), * that you need to forward to the range start/end inputs respectively. * Pay specific attention to the `ref` and `inputProps` keys. * @example * ```jsx * <DateRangePicker * renderInput={(startProps, endProps) => ( * <React.Fragment> * <TextField {...startProps} /> * <DateRangeDelimiter> to <DateRangeDelimiter> * <TextField {...endProps} /> * </React.Fragment>; * )} * /> * ```` */ renderInput: PropTypes.func.isRequired, /** * Component displaying when passed `loading` true. * @default () => "..." */ renderLoading: PropTypes.func, /** * Custom formatter to be passed into Rifm component. */ rifmFormatter: PropTypes.func, /** * Props to pass to right arrow button. */ rightArrowButtonProps: PropTypes.object, /** * Right arrow icon aria-label text. */ rightArrowButtonText: PropTypes.string, /** * Right arrow icon. */ rightArrowIcon: PropTypes.node, /** * Disable specific date. @DateIOType */ shouldDisableDate: PropTypes.func, /** * Disable specific years dynamically. * Works like `shouldDisableDate` but for year selection view. @DateIOType. */ shouldDisableYear: PropTypes.func, /** * If `true`, days that have `outsideCurrentMonth={true}` are displayed. * @default false */ showDaysOutsideCurrentMonth: PropTypes.bool, /** * If `true`, show the toolbar even in desktop mode. */ showToolbar: PropTypes.bool, /** * Text for start input label and toolbar placeholder. * @default "Start" */ startText: PropTypes.node, /** * Component that will replace default toolbar renderer. */ ToolbarComponent: PropTypes.elementType, /** * Date format, that is displaying in toolbar. */ toolbarFormat: PropTypes.string, /** * Mobile picker date value placeholder, displaying if `value` === `null`. * @default "–" */ toolbarPlaceholder: PropTypes.node, /** * Mobile picker title, displaying in the toolbar. * @default "SELECT DATE" */ toolbarTitle: PropTypes.node, /** * The value of the picker. */ value: PropTypes.arrayOf( PropTypes.oneOfType([ PropTypes.any, PropTypes.instanceOf(Date), PropTypes.number, PropTypes.string, ]), ).isRequired, }; export type StaticDateRangePickerProps = React.ComponentProps<typeof StaticDateRangePicker>; export default StaticDateRangePicker;
packages/material-ui-lab/src/StaticDateRangePicker/StaticDateRangePicker.tsx
0
https://github.com/mui/material-ui/commit/16c648dfd8d9b47772a44f3a77c6648a55557d80
[ 0.0008365676621906459, 0.00021515702246688306, 0.00016547547420486808, 0.00017101816774811596, 0.00013826128270011395 ]
{ "id": 0, "code_window": [ " const instance = {\n", " matches: mediaQuery.match(query, {\n", " width,\n", " }),\n", " addEventListener: (type, listener) => {\n", " listeners.push(listener);\n", " },\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ " // Mocking matchMedia in Safari < 14 where MediaQueryList doesn't inherit from EventTarget\n", " addListener: (listener) => {\n" ], "file_path": "packages/mui-material/src/useMediaQuery/useMediaQuery.test.js", "type": "replace", "edit_start_line_idx": 24 }
import * as React from 'react'; import { getThemeProps, useThemeWithoutDefault as useTheme } from '@mui/system'; import useEnhancedEffect from '../utils/useEnhancedEffect'; /** * @deprecated Not used internally. Use `MediaQueryListEvent` from lib.dom.d.ts instead. */ export interface MuiMediaQueryListEvent { matches: boolean; } /** * @deprecated Not used internally. Use `MediaQueryList` from lib.dom.d.ts instead. */ export interface MuiMediaQueryList { matches: boolean; addListener: (listener: MuiMediaQueryListListener) => void; removeListener: (listener: MuiMediaQueryListListener) => void; } /** * @deprecated Not used internally. Use `(event: MediaQueryListEvent) => void` instead. */ export type MuiMediaQueryListListener = (event: MuiMediaQueryListEvent) => void; export interface Options { defaultMatches?: boolean; matchMedia?: typeof window.matchMedia; /** * This option is kept for backwards compatibility and has no longer any effect. * It's previous behavior is now handled automatically. */ // TODO: Deprecate for v6 noSsr?: boolean; ssrMatchMedia?: (query: string) => { matches: boolean }; } function useMediaQueryOld( query: string, defaultMatches: boolean, matchMedia: typeof window.matchMedia | null, ssrMatchMedia: ((query: string) => { matches: boolean }) | null, noSsr: boolean | undefined, ): boolean { const supportMatchMedia = typeof window !== 'undefined' && typeof window.matchMedia !== 'undefined'; const [match, setMatch] = React.useState(() => { if (noSsr && supportMatchMedia) { return matchMedia!(query).matches; } if (ssrMatchMedia) { return ssrMatchMedia(query).matches; } // Once the component is mounted, we rely on the // event listeners to return the correct matches value. return defaultMatches; }); useEnhancedEffect(() => { let active = true; if (!supportMatchMedia) { return undefined; } const queryList = matchMedia!(query); const updateMatch = () => { // Workaround Safari wrong implementation of matchMedia // TODO can we remove it? // https://github.com/mui-org/material-ui/pull/17315#issuecomment-528286677 if (active) { setMatch(queryList.matches); } }; updateMatch(); queryList.addEventListener('change', updateMatch); return () => { active = false; queryList.removeEventListener('change', updateMatch); }; }, [query, matchMedia, supportMatchMedia]); return match; } function useMediaQueryNew( query: string, defaultMatches: boolean, matchMedia: typeof window.matchMedia | null, ssrMatchMedia: ((query: string) => { matches: boolean }) | null, ): boolean { const getDefaultSnapshot = React.useCallback(() => defaultMatches, [defaultMatches]); const getServerSnapshot = React.useMemo(() => { if (ssrMatchMedia !== null) { const { matches } = ssrMatchMedia(query); return () => matches; } return getDefaultSnapshot; }, [getDefaultSnapshot, query, ssrMatchMedia]); const [getSnapshot, subscribe] = React.useMemo(() => { if (matchMedia === null) { return [getDefaultSnapshot, () => () => {}]; } const mediaQueryList = matchMedia(query); return [ () => mediaQueryList.matches, (notify: () => void) => { mediaQueryList.addEventListener('change', notify); return () => { mediaQueryList.removeEventListener('change', notify); }; }, ]; }, [getDefaultSnapshot, matchMedia, query]); const match = (React as any).useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot); return match; } export default function useMediaQuery<Theme = unknown>( queryInput: string | ((theme: Theme) => string), options: Options = {}, ): boolean { const theme = useTheme<Theme>(); // Wait for jsdom to support the match media feature. // All the browsers MUI support have this built-in. // This defensive check is here for simplicity. // Most of the time, the match media logic isn't central to people tests. const supportMatchMedia = typeof window !== 'undefined' && typeof window.matchMedia !== 'undefined'; const { defaultMatches = false, matchMedia = supportMatchMedia ? window.matchMedia : null, ssrMatchMedia = null, noSsr, } = getThemeProps({ name: 'MuiUseMediaQuery', props: options, theme }); if (process.env.NODE_ENV !== 'production') { if (typeof queryInput === 'function' && theme === null) { console.error( [ 'MUI: The `query` argument provided is invalid.', 'You are providing a function without a theme in the context.', 'One of the parent elements needs to use a ThemeProvider.', ].join('\n'), ); } } let query = typeof queryInput === 'function' ? queryInput(theme) : queryInput; query = query.replace(/^@media( ?)/m, ''); // TODO: Drop `useMediaQueryOld` and use `use-sync-external-store` shim in `useMediaQueryNew` once the package is stable const useMediaQueryImplementation = (React as any).useSyncExternalStore !== undefined ? useMediaQueryNew : useMediaQueryOld; const match = useMediaQueryImplementation( query, defaultMatches, matchMedia, ssrMatchMedia, noSsr, ); if (process.env.NODE_ENV !== 'production') { // eslint-disable-next-line react-hooks/rules-of-hooks React.useDebugValue({ query, match }); } return match; }
packages/mui-material/src/useMediaQuery/useMediaQuery.ts
1
https://github.com/mui/material-ui/commit/fb9808c62e610ddd082a151827c46db022f6f0fe
[ 0.9142636060714722, 0.051441531628370285, 0.00016520763165317476, 0.00028690072940662503, 0.20926673710346222 ]
{ "id": 0, "code_window": [ " const instance = {\n", " matches: mediaQuery.match(query, {\n", " width,\n", " }),\n", " addEventListener: (type, listener) => {\n", " listeners.push(listener);\n", " },\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ " // Mocking matchMedia in Safari < 14 where MediaQueryList doesn't inherit from EventTarget\n", " addListener: (listener) => {\n" ], "file_path": "packages/mui-material/src/useMediaQuery/useMediaQuery.test.js", "type": "replace", "edit_start_line_idx": 24 }
import createSvgIcon from './utils/createSvgIcon'; import { jsx as _jsx } from "react/jsx-runtime"; export default createSvgIcon( /*#__PURE__*/_jsx("path", { d: "M9 2c-1.05 0-2.05.16-3 .46 4.06 1.27 7 5.06 7 9.54s-2.94 8.27-7 9.54c.95.3 1.95.46 3 .46 5.52 0 10-4.48 10-10S14.52 2 9 2z" }), 'Brightness3Sharp');
packages/mui-icons-material/lib/esm/Brightness3Sharp.js
0
https://github.com/mui/material-ui/commit/fb9808c62e610ddd082a151827c46db022f6f0fe
[ 0.0001738120918162167, 0.0001738120918162167, 0.0001738120918162167, 0.0001738120918162167, 0 ]
{ "id": 0, "code_window": [ " const instance = {\n", " matches: mediaQuery.match(query, {\n", " width,\n", " }),\n", " addEventListener: (type, listener) => {\n", " listeners.push(listener);\n", " },\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ " // Mocking matchMedia in Safari < 14 where MediaQueryList doesn't inherit from EventTarget\n", " addListener: (listener) => {\n" ], "file_path": "packages/mui-material/src/useMediaQuery/useMediaQuery.test.js", "type": "replace", "edit_start_line_idx": 24 }
<svg xmlns="http://www.w3.org/2000/svg" enable-background="new 0 0 24 24" height="24" viewBox="0 0 24 24" width="24"><g><rect fill="none" height="24" width="24"/></g><g><g><path d="M4,4v2h5v2H5v2h4v2H4v2h7V4H4z M13,4h7v10h-7V4z M18,6h-3v6h3V6z M5,22H3v-5h2V22z M9,22H7v-5h2V22z M13,22h-2v-5h2V22z M21,22h-6v-5h6V22z"/></g></g></svg>
packages/mui-icons-material/material-icons/30fps_select_sharp_24px.svg
0
https://github.com/mui/material-ui/commit/fb9808c62e610ddd082a151827c46db022f6f0fe
[ 0.00017376634059473872, 0.00017376634059473872, 0.00017376634059473872, 0.00017376634059473872, 0 ]
{ "id": 0, "code_window": [ " const instance = {\n", " matches: mediaQuery.match(query, {\n", " width,\n", " }),\n", " addEventListener: (type, listener) => {\n", " listeners.push(listener);\n", " },\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ " // Mocking matchMedia in Safari < 14 where MediaQueryList doesn't inherit from EventTarget\n", " addListener: (listener) => {\n" ], "file_path": "packages/mui-material/src/useMediaQuery/useMediaQuery.test.js", "type": "replace", "edit_start_line_idx": 24 }
<svg xmlns="http://www.w3.org/2000/svg" enable-background="new 0 0 24 24" height="24" viewBox="0 0 24 24" width="24"><g><rect fill="none" height="24" width="24"/></g><g><g><path d="M9,12c0,1.66,1.34,3,3,3s3-1.34,3-3s-1.34-3-3-3S9,10.34,9,12z"/><path d="M8,10V8H5.09C6.47,5.61,9.05,4,12,4c3.72,0,6.85,2.56,7.74,6h2.06c-0.93-4.56-4.96-8-9.8-8C8.73,2,5.82,3.58,4,6.01V4H2v6 H8z"/><path d="M16,14v2h2.91c-1.38,2.39-3.96,4-6.91,4c-3.72,0-6.85-2.56-7.74-6H2.2c0.93,4.56,4.96,8,9.8,8c3.27,0,6.18-1.58,8-4.01V20 h2v-6H16z"/></g></g></svg>
packages/mui-icons-material/material-icons/flip_camera_android_sharp_24px.svg
0
https://github.com/mui/material-ui/commit/fb9808c62e610ddd082a151827c46db022f6f0fe
[ 0.00017263639892917126, 0.00017263639892917126, 0.00017263639892917126, 0.00017263639892917126, 0 ]
{ "id": 1, "code_window": [ " listeners.push(listener);\n", " },\n", " removeEventListener: (type, listener) => {\n", " const index = listeners.indexOf(listener);\n", " if (index > -1) {\n", " listeners.splice(index, 1);\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " removeListener: (listener) => {\n" ], "file_path": "packages/mui-material/src/useMediaQuery/useMediaQuery.test.js", "type": "replace", "edit_start_line_idx": 27 }
import * as React from 'react'; import PropTypes from 'prop-types'; import { ThemeProvider } from '@mui/material/styles'; import useMediaQuery from '@mui/material/useMediaQuery'; import { act, createRenderer, screen, RenderCounter, strictModeDoubleLoggingSupressed, } from 'test/utils'; import mediaQuery from 'css-mediaquery'; import { expect } from 'chai'; import { stub } from 'sinon'; const usesUseSyncExternalStore = React.useSyncExternalStore !== undefined; function createMatchMedia(width, ref) { const listeners = []; return (query) => { const instance = { matches: mediaQuery.match(query, { width, }), addEventListener: (type, listener) => { listeners.push(listener); }, removeEventListener: (type, listener) => { const index = listeners.indexOf(listener); if (index > -1) { listeners.splice(index, 1); } }, }; ref.push({ instance, listeners, }); return instance; }; } describe('useMediaQuery', () => { const { render, renderToString } = createRenderer(); describe('without window.matchMedia', () => { let originalMatchmedia; beforeEach(() => { originalMatchmedia = window.matchMedia; delete window.matchMedia; }); afterEach(() => { window.matchMedia = originalMatchmedia; }); it('should work without window.matchMedia available', () => { expect(typeof window.matchMedia).to.equal('undefined'); const Test = () => { const matches = useMediaQuery('(min-width:100px)'); return <span data-testid="matches">{`${matches}`}</span>; }; render(<Test />); expect(screen.getByTestId('matches').textContent).to.equal('false'); }); }); describe('with window.matchMedia', () => { let matchMediaInstances; beforeEach(() => { matchMediaInstances = []; const fakeMatchMedia = createMatchMedia(1200, matchMediaInstances); // can't stub non-existent properties with sinon // jsdom does not implement window.matchMedia if (window.matchMedia === undefined) { window.matchMedia = fakeMatchMedia; window.matchMedia.restore = () => { delete window.matchMedia; }; } else { stub(window, 'matchMedia').callsFake(fakeMatchMedia); } }); afterEach(() => { window.matchMedia.restore(); }); describe('option: defaultMatches', () => { it('should be false by default', () => { const getRenderCountRef = React.createRef(); const Test = () => { const matches = useMediaQuery('(min-width:2000px)'); return ( <RenderCounter ref={getRenderCountRef}> <span data-testid="matches">{`${matches}`}</span> </RenderCounter> ); }; render(<Test />); expect(screen.getByTestId('matches').textContent).to.equal('false'); expect(getRenderCountRef.current()).to.equal(1); }); it('should take the option into account', () => { const getRenderCountRef = React.createRef(); const Test = () => { const matches = useMediaQuery('(min-width:2000px)', { defaultMatches: true, }); return ( <RenderCounter ref={getRenderCountRef}> <span data-testid="matches">{`${matches}`}</span> </RenderCounter> ); }; render(<Test />); expect(screen.getByTestId('matches').textContent).to.equal('false'); expect(getRenderCountRef.current()).to.equal(usesUseSyncExternalStore ? 1 : 2); }); }); describe('option: noSsr', () => { it('should render once if the default value match the expectation', () => { const getRenderCountRef = React.createRef(); const Test = () => { const matches = useMediaQuery('(min-width:2000px)', { defaultMatches: false, }); return ( <RenderCounter ref={getRenderCountRef}> <span data-testid="matches">{`${matches}`}</span> </RenderCounter> ); }; render(<Test />); expect(screen.getByTestId('matches').textContent).to.equal('false'); expect(getRenderCountRef.current()).to.equal(1); }); it('should render twice if the default value does not match the expectation', () => { const getRenderCountRef = React.createRef(); const Test = () => { const matches = useMediaQuery('(min-width:2000px)', { defaultMatches: true, }); return ( <RenderCounter ref={getRenderCountRef}> <span data-testid="matches">{`${matches}`}</span> </RenderCounter> ); }; render(<Test />); expect(screen.getByTestId('matches').textContent).to.equal('false'); expect(getRenderCountRef.current()).to.equal(usesUseSyncExternalStore ? 1 : 2); }); it('should render once if the default value does not match the expectation but `noSsr` is enabled', () => { const getRenderCountRef = React.createRef(); const Test = () => { const matches = useMediaQuery('(min-width:2000px)', { defaultMatches: true, noSsr: true, }); return ( <RenderCounter ref={getRenderCountRef}> <span data-testid="matches">{`${matches}`}</span> </RenderCounter> ); }; render(<Test />); expect(screen.getByTestId('matches').textContent).to.equal('false'); expect(getRenderCountRef.current()).to.equal(1); }); }); it('should try to reconcile each time', () => { const getRenderCountRef = React.createRef(); const Test = () => { const matches = useMediaQuery('(min-width:2000px)', { defaultMatches: true, }); return ( <RenderCounter ref={getRenderCountRef}> <span data-testid="matches">{`${matches}`}</span> </RenderCounter> ); }; const { unmount } = render(<Test />); expect(screen.getByTestId('matches').textContent).to.equal('false'); expect(getRenderCountRef.current()).to.equal(usesUseSyncExternalStore ? 1 : 2); unmount(); render(<Test />); expect(screen.getByTestId('matches').textContent).to.equal('false'); expect(getRenderCountRef.current()).to.equal(usesUseSyncExternalStore ? 1 : 2); }); it('should be able to change the query dynamically', () => { const getRenderCountRef = React.createRef(); const Test = (props) => { const matches = useMediaQuery(props.query, { defaultMatches: true, }); return ( <RenderCounter ref={getRenderCountRef}> <span data-testid="matches">{`${matches}`}</span> </RenderCounter> ); }; Test.propTypes = { query: PropTypes.string.isRequired, }; const { setProps } = render(<Test query="(min-width:2000px)" />); expect(screen.getByTestId('matches').textContent).to.equal('false'); expect(getRenderCountRef.current()).to.equal(usesUseSyncExternalStore ? 1 : 2); setProps({ query: '(min-width:100px)' }); expect(screen.getByTestId('matches').textContent).to.equal('true'); expect(getRenderCountRef.current()).to.equal(usesUseSyncExternalStore ? 2 : 4); }); it('should observe the media query', () => { const getRenderCountRef = React.createRef(); const Test = (props) => { const matches = useMediaQuery(props.query); return ( <RenderCounter ref={getRenderCountRef}> <span data-testid="matches">{`${matches}`}</span> </RenderCounter> ); }; Test.propTypes = { query: PropTypes.string.isRequired, }; render(<Test query="(min-width:2000px)" />); expect(getRenderCountRef.current()).to.equal(1); expect(screen.getByTestId('matches').textContent).to.equal('false'); act(() => { matchMediaInstances[matchMediaInstances.length - 1].instance.matches = true; matchMediaInstances[matchMediaInstances.length - 1].listeners[0](); }); expect(screen.getByTestId('matches').textContent).to.equal('true'); expect(getRenderCountRef.current()).to.equal(2); }); }); describe('server-side', () => { it('should use the ssr match media ponyfill', () => { function MyComponent() { const matches = useMediaQuery('(min-width:2000px)'); return <span>{`${matches}`}</span>; } const Test = () => { const ssrMatchMedia = (query) => ({ matches: mediaQuery.match(query, { width: 3000, }), }); return ( <ThemeProvider theme={{ components: { MuiUseMediaQuery: { defaultProps: { ssrMatchMedia } } } }} > <MyComponent /> </ThemeProvider> ); }; const { container } = renderToString(<Test />); expect(container.firstChild).to.have.text('true'); }); }); describe('warnings', () => { it('warns on invalid `query` argument', () => { function MyComponent() { useMediaQuery(() => '(min-width:2000px)'); return null; } expect(() => { render(<MyComponent />); }).toErrorDev([ 'MUI: The `query` argument provided is invalid', !strictModeDoubleLoggingSupressed && 'MUI: The `query` argument provided is invalid', ]); }); }); });
packages/mui-material/src/useMediaQuery/useMediaQuery.test.js
1
https://github.com/mui/material-ui/commit/fb9808c62e610ddd082a151827c46db022f6f0fe
[ 0.9981634020805359, 0.0640961229801178, 0.00016885179502423853, 0.00017156434478238225, 0.24314704537391663 ]
{ "id": 1, "code_window": [ " listeners.push(listener);\n", " },\n", " removeEventListener: (type, listener) => {\n", " const index = listeners.indexOf(listener);\n", " if (index > -1) {\n", " listeners.splice(index, 1);\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " removeListener: (listener) => {\n" ], "file_path": "packages/mui-material/src/useMediaQuery/useMediaQuery.test.js", "type": "replace", "edit_start_line_idx": 27 }
<svg width="18" height="18" viewBox="0 0 18 18" fill="none" xmlns="http://www.w3.org/2000/svg"> <circle cx="9" cy="9" r="9" fill="none"/> <path d="M5 9H13" stroke="#BFC7CF" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/> </svg>
docs/public/static/branding/pricing/no-light.svg
0
https://github.com/mui/material-ui/commit/fb9808c62e610ddd082a151827c46db022f6f0fe
[ 0.0001702172594377771, 0.0001702172594377771, 0.0001702172594377771, 0.0001702172594377771, 0 ]
{ "id": 1, "code_window": [ " listeners.push(listener);\n", " },\n", " removeEventListener: (type, listener) => {\n", " const index = listeners.indexOf(listener);\n", " if (index > -1) {\n", " listeners.splice(index, 1);\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " removeListener: (listener) => {\n" ], "file_path": "packages/mui-material/src/useMediaQuery/useMediaQuery.test.js", "type": "replace", "edit_start_line_idx": 27 }
import * as React from 'react'; import Avatar from '@mui/material/Avatar'; import Button from '@mui/material/Button'; import CssBaseline from '@mui/material/CssBaseline'; import TextField from '@mui/material/TextField'; import FormControlLabel from '@mui/material/FormControlLabel'; import Checkbox from '@mui/material/Checkbox'; import Link from '@mui/material/Link'; import Paper from '@mui/material/Paper'; import Box from '@mui/material/Box'; import Grid from '@mui/material/Grid'; import LockOutlinedIcon from '@mui/icons-material/LockOutlined'; import Typography from '@mui/material/Typography'; import { createTheme, ThemeProvider } from '@mui/material/styles'; function Copyright(props: any) { return ( <Typography variant="body2" color="text.secondary" align="center" {...props}> {'Copyright © '} <Link color="inherit" href="https://mui.com/"> Your Website </Link>{' '} {new Date().getFullYear()} {'.'} </Typography> ); } const theme = createTheme(); export default function SignInSide() { const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => { event.preventDefault(); const data = new FormData(event.currentTarget); // eslint-disable-next-line no-console console.log({ email: data.get('email'), password: data.get('password'), }); }; return ( <ThemeProvider theme={theme}> <Grid container component="main" sx={{ height: '100vh' }}> <CssBaseline /> <Grid item xs={false} sm={4} md={7} sx={{ backgroundImage: 'url(https://source.unsplash.com/random)', backgroundRepeat: 'no-repeat', backgroundColor: (t) => t.palette.mode === 'light' ? t.palette.grey[50] : t.palette.grey[900], backgroundSize: 'cover', backgroundPosition: 'center', }} /> <Grid item xs={12} sm={8} md={5} component={Paper} elevation={6} square> <Box sx={{ my: 8, mx: 4, display: 'flex', flexDirection: 'column', alignItems: 'center', }} > <Avatar sx={{ m: 1, bgcolor: 'secondary.main' }}> <LockOutlinedIcon /> </Avatar> <Typography component="h1" variant="h5"> Sign in </Typography> <Box component="form" noValidate onSubmit={handleSubmit} sx={{ mt: 1 }}> <TextField margin="normal" required fullWidth id="email" label="Email Address" name="email" autoComplete="email" autoFocus /> <TextField margin="normal" required fullWidth name="password" label="Password" type="password" id="password" autoComplete="current-password" /> <FormControlLabel control={<Checkbox value="remember" color="primary" />} label="Remember me" /> <Button type="submit" fullWidth variant="contained" sx={{ mt: 3, mb: 2 }} > Sign In </Button> <Grid container> <Grid item xs> <Link href="#" variant="body2"> Forgot password? </Link> </Grid> <Grid item> <Link href="#" variant="body2"> {"Don't have an account? Sign Up"} </Link> </Grid> </Grid> <Copyright sx={{ mt: 5 }} /> </Box> </Box> </Grid> </Grid> </ThemeProvider> ); }
docs/src/pages/getting-started/templates/sign-in-side/SignInSide.tsx
0
https://github.com/mui/material-ui/commit/fb9808c62e610ddd082a151827c46db022f6f0fe
[ 0.00017615492106415331, 0.00017318219761364162, 0.00016983886598609388, 0.0001739493600325659, 0.0000018414744999972754 ]
{ "id": 1, "code_window": [ " listeners.push(listener);\n", " },\n", " removeEventListener: (type, listener) => {\n", " const index = listeners.indexOf(listener);\n", " if (index > -1) {\n", " listeners.splice(index, 1);\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " removeListener: (listener) => {\n" ], "file_path": "packages/mui-material/src/useMediaQuery/useMediaQuery.test.js", "type": "replace", "edit_start_line_idx": 27 }
import * as React from 'react'; import Box from '@mui/material/Box'; import InputLabel from '@mui/material/InputLabel'; function InputLabels() { return ( <Box sx={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-start', padding: '20px', // so transform doesn't let things get cut off }} > <InputLabel shrink>First Name Shrunk</InputLabel> <InputLabel>First Name</InputLabel> <InputLabel focused>Required</InputLabel> <InputLabel focused required> Focused Required </InputLabel> <InputLabel required>Required</InputLabel> <InputLabel error>Error</InputLabel> <InputLabel required error> Required Error </InputLabel> </Box> ); } export default InputLabels;
test/regressions/fixtures/Input/InputLabels.js
0
https://github.com/mui/material-ui/commit/fb9808c62e610ddd082a151827c46db022f6f0fe
[ 0.0001754278055159375, 0.00017344410298392177, 0.00017092833877541125, 0.00017371014109812677, 0.0000017638996041569044 ]
{ "id": 2, "code_window": [ " setMatch(queryList.matches);\n", " }\n", " };\n", " updateMatch();\n", " queryList.addEventListener('change', updateMatch);\n", " return () => {\n", " active = false;\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ " // TODO: Use `addEventListener` once support for Safari < 14 is dropped\n", " queryList.addListener(updateMatch);\n" ], "file_path": "packages/mui-material/src/useMediaQuery/useMediaQuery.ts", "type": "replace", "edit_start_line_idx": 77 }
import * as React from 'react'; import PropTypes from 'prop-types'; import { ThemeProvider } from '@mui/material/styles'; import useMediaQuery from '@mui/material/useMediaQuery'; import { act, createRenderer, screen, RenderCounter, strictModeDoubleLoggingSupressed, } from 'test/utils'; import mediaQuery from 'css-mediaquery'; import { expect } from 'chai'; import { stub } from 'sinon'; const usesUseSyncExternalStore = React.useSyncExternalStore !== undefined; function createMatchMedia(width, ref) { const listeners = []; return (query) => { const instance = { matches: mediaQuery.match(query, { width, }), addEventListener: (type, listener) => { listeners.push(listener); }, removeEventListener: (type, listener) => { const index = listeners.indexOf(listener); if (index > -1) { listeners.splice(index, 1); } }, }; ref.push({ instance, listeners, }); return instance; }; } describe('useMediaQuery', () => { const { render, renderToString } = createRenderer(); describe('without window.matchMedia', () => { let originalMatchmedia; beforeEach(() => { originalMatchmedia = window.matchMedia; delete window.matchMedia; }); afterEach(() => { window.matchMedia = originalMatchmedia; }); it('should work without window.matchMedia available', () => { expect(typeof window.matchMedia).to.equal('undefined'); const Test = () => { const matches = useMediaQuery('(min-width:100px)'); return <span data-testid="matches">{`${matches}`}</span>; }; render(<Test />); expect(screen.getByTestId('matches').textContent).to.equal('false'); }); }); describe('with window.matchMedia', () => { let matchMediaInstances; beforeEach(() => { matchMediaInstances = []; const fakeMatchMedia = createMatchMedia(1200, matchMediaInstances); // can't stub non-existent properties with sinon // jsdom does not implement window.matchMedia if (window.matchMedia === undefined) { window.matchMedia = fakeMatchMedia; window.matchMedia.restore = () => { delete window.matchMedia; }; } else { stub(window, 'matchMedia').callsFake(fakeMatchMedia); } }); afterEach(() => { window.matchMedia.restore(); }); describe('option: defaultMatches', () => { it('should be false by default', () => { const getRenderCountRef = React.createRef(); const Test = () => { const matches = useMediaQuery('(min-width:2000px)'); return ( <RenderCounter ref={getRenderCountRef}> <span data-testid="matches">{`${matches}`}</span> </RenderCounter> ); }; render(<Test />); expect(screen.getByTestId('matches').textContent).to.equal('false'); expect(getRenderCountRef.current()).to.equal(1); }); it('should take the option into account', () => { const getRenderCountRef = React.createRef(); const Test = () => { const matches = useMediaQuery('(min-width:2000px)', { defaultMatches: true, }); return ( <RenderCounter ref={getRenderCountRef}> <span data-testid="matches">{`${matches}`}</span> </RenderCounter> ); }; render(<Test />); expect(screen.getByTestId('matches').textContent).to.equal('false'); expect(getRenderCountRef.current()).to.equal(usesUseSyncExternalStore ? 1 : 2); }); }); describe('option: noSsr', () => { it('should render once if the default value match the expectation', () => { const getRenderCountRef = React.createRef(); const Test = () => { const matches = useMediaQuery('(min-width:2000px)', { defaultMatches: false, }); return ( <RenderCounter ref={getRenderCountRef}> <span data-testid="matches">{`${matches}`}</span> </RenderCounter> ); }; render(<Test />); expect(screen.getByTestId('matches').textContent).to.equal('false'); expect(getRenderCountRef.current()).to.equal(1); }); it('should render twice if the default value does not match the expectation', () => { const getRenderCountRef = React.createRef(); const Test = () => { const matches = useMediaQuery('(min-width:2000px)', { defaultMatches: true, }); return ( <RenderCounter ref={getRenderCountRef}> <span data-testid="matches">{`${matches}`}</span> </RenderCounter> ); }; render(<Test />); expect(screen.getByTestId('matches').textContent).to.equal('false'); expect(getRenderCountRef.current()).to.equal(usesUseSyncExternalStore ? 1 : 2); }); it('should render once if the default value does not match the expectation but `noSsr` is enabled', () => { const getRenderCountRef = React.createRef(); const Test = () => { const matches = useMediaQuery('(min-width:2000px)', { defaultMatches: true, noSsr: true, }); return ( <RenderCounter ref={getRenderCountRef}> <span data-testid="matches">{`${matches}`}</span> </RenderCounter> ); }; render(<Test />); expect(screen.getByTestId('matches').textContent).to.equal('false'); expect(getRenderCountRef.current()).to.equal(1); }); }); it('should try to reconcile each time', () => { const getRenderCountRef = React.createRef(); const Test = () => { const matches = useMediaQuery('(min-width:2000px)', { defaultMatches: true, }); return ( <RenderCounter ref={getRenderCountRef}> <span data-testid="matches">{`${matches}`}</span> </RenderCounter> ); }; const { unmount } = render(<Test />); expect(screen.getByTestId('matches').textContent).to.equal('false'); expect(getRenderCountRef.current()).to.equal(usesUseSyncExternalStore ? 1 : 2); unmount(); render(<Test />); expect(screen.getByTestId('matches').textContent).to.equal('false'); expect(getRenderCountRef.current()).to.equal(usesUseSyncExternalStore ? 1 : 2); }); it('should be able to change the query dynamically', () => { const getRenderCountRef = React.createRef(); const Test = (props) => { const matches = useMediaQuery(props.query, { defaultMatches: true, }); return ( <RenderCounter ref={getRenderCountRef}> <span data-testid="matches">{`${matches}`}</span> </RenderCounter> ); }; Test.propTypes = { query: PropTypes.string.isRequired, }; const { setProps } = render(<Test query="(min-width:2000px)" />); expect(screen.getByTestId('matches').textContent).to.equal('false'); expect(getRenderCountRef.current()).to.equal(usesUseSyncExternalStore ? 1 : 2); setProps({ query: '(min-width:100px)' }); expect(screen.getByTestId('matches').textContent).to.equal('true'); expect(getRenderCountRef.current()).to.equal(usesUseSyncExternalStore ? 2 : 4); }); it('should observe the media query', () => { const getRenderCountRef = React.createRef(); const Test = (props) => { const matches = useMediaQuery(props.query); return ( <RenderCounter ref={getRenderCountRef}> <span data-testid="matches">{`${matches}`}</span> </RenderCounter> ); }; Test.propTypes = { query: PropTypes.string.isRequired, }; render(<Test query="(min-width:2000px)" />); expect(getRenderCountRef.current()).to.equal(1); expect(screen.getByTestId('matches').textContent).to.equal('false'); act(() => { matchMediaInstances[matchMediaInstances.length - 1].instance.matches = true; matchMediaInstances[matchMediaInstances.length - 1].listeners[0](); }); expect(screen.getByTestId('matches').textContent).to.equal('true'); expect(getRenderCountRef.current()).to.equal(2); }); }); describe('server-side', () => { it('should use the ssr match media ponyfill', () => { function MyComponent() { const matches = useMediaQuery('(min-width:2000px)'); return <span>{`${matches}`}</span>; } const Test = () => { const ssrMatchMedia = (query) => ({ matches: mediaQuery.match(query, { width: 3000, }), }); return ( <ThemeProvider theme={{ components: { MuiUseMediaQuery: { defaultProps: { ssrMatchMedia } } } }} > <MyComponent /> </ThemeProvider> ); }; const { container } = renderToString(<Test />); expect(container.firstChild).to.have.text('true'); }); }); describe('warnings', () => { it('warns on invalid `query` argument', () => { function MyComponent() { useMediaQuery(() => '(min-width:2000px)'); return null; } expect(() => { render(<MyComponent />); }).toErrorDev([ 'MUI: The `query` argument provided is invalid', !strictModeDoubleLoggingSupressed && 'MUI: The `query` argument provided is invalid', ]); }); }); });
packages/mui-material/src/useMediaQuery/useMediaQuery.test.js
1
https://github.com/mui/material-ui/commit/fb9808c62e610ddd082a151827c46db022f6f0fe
[ 0.0023803410585969687, 0.0003983771603088826, 0.00016340173897333443, 0.0001743399043334648, 0.0005721301422454417 ]
{ "id": 2, "code_window": [ " setMatch(queryList.matches);\n", " }\n", " };\n", " updateMatch();\n", " queryList.addEventListener('change', updateMatch);\n", " return () => {\n", " active = false;\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ " // TODO: Use `addEventListener` once support for Safari < 14 is dropped\n", " queryList.addListener(updateMatch);\n" ], "file_path": "packages/mui-material/src/useMediaQuery/useMediaQuery.ts", "type": "replace", "edit_start_line_idx": 77 }
<svg xmlns="http://www.w3.org/2000/svg" enable-background="new 0 0 24 24" height="24" viewBox="0 0 24 24" width="24"><g><rect fill="none" height="24" width="24"/></g><g><g><path d="M10,16.5c0-3.58,2.92-6.5,6.5-6.5c0.89,0,1.73,0.18,2.5,0.5V5h-2v3H7V5H5v14h5.5 C10.18,18.23,10,17.39,10,16.5z" opacity=".3"/><path d="M10.5,19H5V5h2v3h10V5h2v5.5c0.75,0.31,1.42,0.76,2,1.32V5c0-1.1-0.9-2-2-2h-4.18C14.4,1.84,13.3,1,12,1S9.6,1.84,9.18,3 H5C3.9,3,3,3.9,3,5v14c0,1.1,0.9,2,2,2h6.82C11.27,20.42,10.81,19.75,10.5,19z M12,3c0.55,0,1,0.45,1,1s-0.45,1-1,1s-1-0.45-1-1 S11.45,3,12,3z"/><path d="M20.3,18.9c0.4-0.7,0.7-1.5,0.7-2.4c0-2.5-2-4.5-4.5-4.5S12,14,12,16.5s2,4.5,4.5,4.5c0.9,0,1.7-0.3,2.4-0.7l2.7,2.7 l1.4-1.4L20.3,18.9z M16.5,19c-1.4,0-2.5-1.1-2.5-2.5c0-1.4,1.1-2.5,2.5-2.5s2.5,1.1,2.5,2.5C19,17.9,17.9,19,16.5,19z"/></g></g></svg>
packages/mui-icons-material/material-icons/content_paste_search_two_tone_24px.svg
0
https://github.com/mui/material-ui/commit/fb9808c62e610ddd082a151827c46db022f6f0fe
[ 0.00022078436450101435, 0.00022078436450101435, 0.00022078436450101435, 0.00022078436450101435, 0 ]
{ "id": 2, "code_window": [ " setMatch(queryList.matches);\n", " }\n", " };\n", " updateMatch();\n", " queryList.addEventListener('change', updateMatch);\n", " return () => {\n", " active = false;\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ " // TODO: Use `addEventListener` once support for Safari < 14 is dropped\n", " queryList.addListener(updateMatch);\n" ], "file_path": "packages/mui-material/src/useMediaQuery/useMediaQuery.ts", "type": "replace", "edit_start_line_idx": 77 }
import PropTypes from 'prop-types'; function Modal(inProps) { const props = getThemeProps({ props: inProps }); const { onKeyDown, ...other } = props; function handleKeyDown(event) { if (onKeyDown) { onKeyDown(event); } } return <div onKeyDown={handleKeyDown} {...other} />; } Modal.propTypes = { onKeyDown: PropTypes.func, }; export default Modal;
packages/typescript-to-proptypes/test/getThemeProps/output.js
0
https://github.com/mui/material-ui/commit/fb9808c62e610ddd082a151827c46db022f6f0fe
[ 0.00017645314801484346, 0.00017541807028464973, 0.00017438297800254077, 0.00017541807028464973, 0.0000010350850061513484 ]
{ "id": 2, "code_window": [ " setMatch(queryList.matches);\n", " }\n", " };\n", " updateMatch();\n", " queryList.addEventListener('change', updateMatch);\n", " return () => {\n", " active = false;\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ " // TODO: Use `addEventListener` once support for Safari < 14 is dropped\n", " queryList.addListener(updateMatch);\n" ], "file_path": "packages/mui-material/src/useMediaQuery/useMediaQuery.ts", "type": "replace", "edit_start_line_idx": 77 }
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon")); var _jsxRuntime = require("react/jsx-runtime"); var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "m22.42 11.34-1.86-2.12.26-2.81c.05-.5-.29-.96-.77-1.07l-2.76-.63-1.44-2.43c-.26-.43-.79-.61-1.25-.41L12 3 9.41 1.89c-.46-.2-1-.02-1.25.41L6.71 4.72l-2.75.62c-.49.11-.83.56-.78 1.07l.26 2.8-1.86 2.13c-.33.38-.33.94 0 1.32l1.86 2.12-.26 2.82c-.05.5.29.96.77 1.07l2.76.63 1.44 2.42c.26.43.79.61 1.26.41L12 21l2.59 1.11c.46.2 1 .02 1.25-.41l1.44-2.43 2.76-.63c.49-.11.82-.57.77-1.07l-.26-2.81 1.86-2.12c.34-.36.34-.92.01-1.3zM13 17h-2v-2h2v2zm-1-4c-.55 0-1-.45-1-1V8c0-.55.45-1 1-1s1 .45 1 1v4c0 .55-.45 1-1 1z" }), 'NewReleasesRounded'); exports.default = _default;
packages/mui-icons-material/lib/NewReleasesRounded.js
0
https://github.com/mui/material-ui/commit/fb9808c62e610ddd082a151827c46db022f6f0fe
[ 0.0001891017600428313, 0.0001816654985304922, 0.00017422923701815307, 0.0001816654985304922, 0.000007436261512339115 ]
{ "id": 3, "code_window": [ " return () => {\n", " active = false;\n", " queryList.removeEventListener('change', updateMatch);\n", " };\n", " }, [query, matchMedia, supportMatchMedia]);\n", "\n", " return match;\n", "}\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " queryList.removeListener(updateMatch);\n" ], "file_path": "packages/mui-material/src/useMediaQuery/useMediaQuery.ts", "type": "replace", "edit_start_line_idx": 80 }
import * as React from 'react'; import { getThemeProps, useThemeWithoutDefault as useTheme } from '@mui/system'; import useEnhancedEffect from '../utils/useEnhancedEffect'; /** * @deprecated Not used internally. Use `MediaQueryListEvent` from lib.dom.d.ts instead. */ export interface MuiMediaQueryListEvent { matches: boolean; } /** * @deprecated Not used internally. Use `MediaQueryList` from lib.dom.d.ts instead. */ export interface MuiMediaQueryList { matches: boolean; addListener: (listener: MuiMediaQueryListListener) => void; removeListener: (listener: MuiMediaQueryListListener) => void; } /** * @deprecated Not used internally. Use `(event: MediaQueryListEvent) => void` instead. */ export type MuiMediaQueryListListener = (event: MuiMediaQueryListEvent) => void; export interface Options { defaultMatches?: boolean; matchMedia?: typeof window.matchMedia; /** * This option is kept for backwards compatibility and has no longer any effect. * It's previous behavior is now handled automatically. */ // TODO: Deprecate for v6 noSsr?: boolean; ssrMatchMedia?: (query: string) => { matches: boolean }; } function useMediaQueryOld( query: string, defaultMatches: boolean, matchMedia: typeof window.matchMedia | null, ssrMatchMedia: ((query: string) => { matches: boolean }) | null, noSsr: boolean | undefined, ): boolean { const supportMatchMedia = typeof window !== 'undefined' && typeof window.matchMedia !== 'undefined'; const [match, setMatch] = React.useState(() => { if (noSsr && supportMatchMedia) { return matchMedia!(query).matches; } if (ssrMatchMedia) { return ssrMatchMedia(query).matches; } // Once the component is mounted, we rely on the // event listeners to return the correct matches value. return defaultMatches; }); useEnhancedEffect(() => { let active = true; if (!supportMatchMedia) { return undefined; } const queryList = matchMedia!(query); const updateMatch = () => { // Workaround Safari wrong implementation of matchMedia // TODO can we remove it? // https://github.com/mui-org/material-ui/pull/17315#issuecomment-528286677 if (active) { setMatch(queryList.matches); } }; updateMatch(); queryList.addEventListener('change', updateMatch); return () => { active = false; queryList.removeEventListener('change', updateMatch); }; }, [query, matchMedia, supportMatchMedia]); return match; } function useMediaQueryNew( query: string, defaultMatches: boolean, matchMedia: typeof window.matchMedia | null, ssrMatchMedia: ((query: string) => { matches: boolean }) | null, ): boolean { const getDefaultSnapshot = React.useCallback(() => defaultMatches, [defaultMatches]); const getServerSnapshot = React.useMemo(() => { if (ssrMatchMedia !== null) { const { matches } = ssrMatchMedia(query); return () => matches; } return getDefaultSnapshot; }, [getDefaultSnapshot, query, ssrMatchMedia]); const [getSnapshot, subscribe] = React.useMemo(() => { if (matchMedia === null) { return [getDefaultSnapshot, () => () => {}]; } const mediaQueryList = matchMedia(query); return [ () => mediaQueryList.matches, (notify: () => void) => { mediaQueryList.addEventListener('change', notify); return () => { mediaQueryList.removeEventListener('change', notify); }; }, ]; }, [getDefaultSnapshot, matchMedia, query]); const match = (React as any).useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot); return match; } export default function useMediaQuery<Theme = unknown>( queryInput: string | ((theme: Theme) => string), options: Options = {}, ): boolean { const theme = useTheme<Theme>(); // Wait for jsdom to support the match media feature. // All the browsers MUI support have this built-in. // This defensive check is here for simplicity. // Most of the time, the match media logic isn't central to people tests. const supportMatchMedia = typeof window !== 'undefined' && typeof window.matchMedia !== 'undefined'; const { defaultMatches = false, matchMedia = supportMatchMedia ? window.matchMedia : null, ssrMatchMedia = null, noSsr, } = getThemeProps({ name: 'MuiUseMediaQuery', props: options, theme }); if (process.env.NODE_ENV !== 'production') { if (typeof queryInput === 'function' && theme === null) { console.error( [ 'MUI: The `query` argument provided is invalid.', 'You are providing a function without a theme in the context.', 'One of the parent elements needs to use a ThemeProvider.', ].join('\n'), ); } } let query = typeof queryInput === 'function' ? queryInput(theme) : queryInput; query = query.replace(/^@media( ?)/m, ''); // TODO: Drop `useMediaQueryOld` and use `use-sync-external-store` shim in `useMediaQueryNew` once the package is stable const useMediaQueryImplementation = (React as any).useSyncExternalStore !== undefined ? useMediaQueryNew : useMediaQueryOld; const match = useMediaQueryImplementation( query, defaultMatches, matchMedia, ssrMatchMedia, noSsr, ); if (process.env.NODE_ENV !== 'production') { // eslint-disable-next-line react-hooks/rules-of-hooks React.useDebugValue({ query, match }); } return match; }
packages/mui-material/src/useMediaQuery/useMediaQuery.ts
1
https://github.com/mui/material-ui/commit/fb9808c62e610ddd082a151827c46db022f6f0fe
[ 0.9970003962516785, 0.06328979134559631, 0.00016843868070282042, 0.0025654565542936325, 0.22754864394664764 ]
{ "id": 3, "code_window": [ " return () => {\n", " active = false;\n", " queryList.removeEventListener('change', updateMatch);\n", " };\n", " }, [query, matchMedia, supportMatchMedia]);\n", "\n", " return match;\n", "}\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " queryList.removeListener(updateMatch);\n" ], "file_path": "packages/mui-material/src/useMediaQuery/useMediaQuery.ts", "type": "replace", "edit_start_line_idx": 80 }
<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 0 24 24" width="24"><path d="M0 0h24v24H0V0z" fill="none"/><path d="M3.42 2.36L2.01 3.78 4.1 5.87C2.79 7.57 2 9.69 2 12c0 3.7 2.01 6.92 4.99 8.65l1-1.73C5.61 17.53 4 14.96 4 12c0-1.76.57-3.38 1.53-4.69l1.43 1.44C6.36 9.68 6 10.8 6 12c0 2.22 1.21 4.15 3 5.19l1-1.74c-1.19-.7-2-1.97-2-3.45 0-.65.17-1.25.44-1.79l1.58 1.58L10 12c0 1.1.9 2 2 2l.21-.02 7.52 7.52 1.41-1.41L3.42 2.36zm14.29 11.46c.18-.57.29-1.19.29-1.82 0-3.31-2.69-6-6-6-.63 0-1.25.11-1.82.29l1.72 1.72c.03 0 .06-.01.1-.01 2.21 0 4 1.79 4 4 0 .04-.01.07-.01.11l1.72 1.71zM12 4c4.42 0 8 3.58 8 8 0 1.2-.29 2.32-.77 3.35l1.49 1.49C21.53 15.4 22 13.76 22 12c0-5.52-4.48-10-10-10-1.76 0-3.4.48-4.84 1.28l1.48 1.48C9.66 4.28 10.8 4 12 4z"/></svg>
packages/mui-icons-material/material-icons/portable_wifi_off_two_tone_24px.svg
0
https://github.com/mui/material-ui/commit/fb9808c62e610ddd082a151827c46db022f6f0fe
[ 0.0008299292530864477, 0.0008299292530864477, 0.0008299292530864477, 0.0008299292530864477, 0 ]
{ "id": 3, "code_window": [ " return () => {\n", " active = false;\n", " queryList.removeEventListener('change', updateMatch);\n", " };\n", " }, [query, matchMedia, supportMatchMedia]);\n", "\n", " return match;\n", "}\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " queryList.removeListener(updateMatch);\n" ], "file_path": "packages/mui-material/src/useMediaQuery/useMediaQuery.ts", "type": "replace", "edit_start_line_idx": 80 }
import createSvgIcon from './utils/createSvgIcon'; import { jsx as _jsx } from "react/jsx-runtime"; export default createSvgIcon( /*#__PURE__*/_jsx("path", { d: "m22 5.72-4.6-3.86-1.29 1.53 4.6 3.86L22 5.72zM7.88 3.39 6.6 1.86 2 5.71l1.29 1.53 4.59-3.85zM12.5 8H11v6l4.75 2.85.75-1.23-4-2.37V8zM12 4c-4.97 0-9 4.03-9 9s4.02 9 9 9c4.97 0 9-4.03 9-9s-4.03-9-9-9zm0 16c-3.87 0-7-3.13-7-7s3.13-7 7-7 7 3.13 7 7-3.13 7-7 7z" }), 'Alarm');
packages/mui-icons-material/lib/esm/Alarm.js
0
https://github.com/mui/material-ui/commit/fb9808c62e610ddd082a151827c46db022f6f0fe
[ 0.0001765426859492436, 0.0001765426859492436, 0.0001765426859492436, 0.0001765426859492436, 0 ]
{ "id": 3, "code_window": [ " return () => {\n", " active = false;\n", " queryList.removeEventListener('change', updateMatch);\n", " };\n", " }, [query, matchMedia, supportMatchMedia]);\n", "\n", " return match;\n", "}\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " queryList.removeListener(updateMatch);\n" ], "file_path": "packages/mui-material/src/useMediaQuery/useMediaQuery.ts", "type": "replace", "edit_start_line_idx": 80 }
<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 0 24 24" width="24"><path d="M0 0h24v24H0V0z" fill="none"/><path d="M16 9H8v14h8V9zm-4 6c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2zM7.05 6.05l1.41 1.41C9.37 6.56 10.62 6 12 6s2.63.56 3.54 1.46l1.41-1.41C15.68 4.78 13.93 4 12 4s-3.68.78-4.95 2.05zM12 0C8.96 0 6.21 1.23 4.22 3.22l1.41 1.41C7.26 3.01 9.51 2 12 2s4.74 1.01 6.36 2.64l1.41-1.41C17.79 1.23 15.04 0 12 0z"/></svg>
packages/mui-icons-material/material-icons/settings_remote_sharp_24px.svg
0
https://github.com/mui/material-ui/commit/fb9808c62e610ddd082a151827c46db022f6f0fe
[ 0.0001734384277369827, 0.0001734384277369827, 0.0001734384277369827, 0.0001734384277369827, 0 ]
{ "id": 4, "code_window": [ " const mediaQueryList = matchMedia(query);\n", "\n", " return [\n", " () => mediaQueryList.matches,\n", " (notify: () => void) => {\n", " mediaQueryList.addEventListener('change', notify);\n", " return () => {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ " // TODO: Use `addEventListener` once support for Safari < 14 is dropped\n", " mediaQueryList.addListener(notify);\n" ], "file_path": "packages/mui-material/src/useMediaQuery/useMediaQuery.ts", "type": "replace", "edit_start_line_idx": 111 }
import * as React from 'react'; import { getThemeProps, useThemeWithoutDefault as useTheme } from '@mui/system'; import useEnhancedEffect from '../utils/useEnhancedEffect'; /** * @deprecated Not used internally. Use `MediaQueryListEvent` from lib.dom.d.ts instead. */ export interface MuiMediaQueryListEvent { matches: boolean; } /** * @deprecated Not used internally. Use `MediaQueryList` from lib.dom.d.ts instead. */ export interface MuiMediaQueryList { matches: boolean; addListener: (listener: MuiMediaQueryListListener) => void; removeListener: (listener: MuiMediaQueryListListener) => void; } /** * @deprecated Not used internally. Use `(event: MediaQueryListEvent) => void` instead. */ export type MuiMediaQueryListListener = (event: MuiMediaQueryListEvent) => void; export interface Options { defaultMatches?: boolean; matchMedia?: typeof window.matchMedia; /** * This option is kept for backwards compatibility and has no longer any effect. * It's previous behavior is now handled automatically. */ // TODO: Deprecate for v6 noSsr?: boolean; ssrMatchMedia?: (query: string) => { matches: boolean }; } function useMediaQueryOld( query: string, defaultMatches: boolean, matchMedia: typeof window.matchMedia | null, ssrMatchMedia: ((query: string) => { matches: boolean }) | null, noSsr: boolean | undefined, ): boolean { const supportMatchMedia = typeof window !== 'undefined' && typeof window.matchMedia !== 'undefined'; const [match, setMatch] = React.useState(() => { if (noSsr && supportMatchMedia) { return matchMedia!(query).matches; } if (ssrMatchMedia) { return ssrMatchMedia(query).matches; } // Once the component is mounted, we rely on the // event listeners to return the correct matches value. return defaultMatches; }); useEnhancedEffect(() => { let active = true; if (!supportMatchMedia) { return undefined; } const queryList = matchMedia!(query); const updateMatch = () => { // Workaround Safari wrong implementation of matchMedia // TODO can we remove it? // https://github.com/mui-org/material-ui/pull/17315#issuecomment-528286677 if (active) { setMatch(queryList.matches); } }; updateMatch(); queryList.addEventListener('change', updateMatch); return () => { active = false; queryList.removeEventListener('change', updateMatch); }; }, [query, matchMedia, supportMatchMedia]); return match; } function useMediaQueryNew( query: string, defaultMatches: boolean, matchMedia: typeof window.matchMedia | null, ssrMatchMedia: ((query: string) => { matches: boolean }) | null, ): boolean { const getDefaultSnapshot = React.useCallback(() => defaultMatches, [defaultMatches]); const getServerSnapshot = React.useMemo(() => { if (ssrMatchMedia !== null) { const { matches } = ssrMatchMedia(query); return () => matches; } return getDefaultSnapshot; }, [getDefaultSnapshot, query, ssrMatchMedia]); const [getSnapshot, subscribe] = React.useMemo(() => { if (matchMedia === null) { return [getDefaultSnapshot, () => () => {}]; } const mediaQueryList = matchMedia(query); return [ () => mediaQueryList.matches, (notify: () => void) => { mediaQueryList.addEventListener('change', notify); return () => { mediaQueryList.removeEventListener('change', notify); }; }, ]; }, [getDefaultSnapshot, matchMedia, query]); const match = (React as any).useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot); return match; } export default function useMediaQuery<Theme = unknown>( queryInput: string | ((theme: Theme) => string), options: Options = {}, ): boolean { const theme = useTheme<Theme>(); // Wait for jsdom to support the match media feature. // All the browsers MUI support have this built-in. // This defensive check is here for simplicity. // Most of the time, the match media logic isn't central to people tests. const supportMatchMedia = typeof window !== 'undefined' && typeof window.matchMedia !== 'undefined'; const { defaultMatches = false, matchMedia = supportMatchMedia ? window.matchMedia : null, ssrMatchMedia = null, noSsr, } = getThemeProps({ name: 'MuiUseMediaQuery', props: options, theme }); if (process.env.NODE_ENV !== 'production') { if (typeof queryInput === 'function' && theme === null) { console.error( [ 'MUI: The `query` argument provided is invalid.', 'You are providing a function without a theme in the context.', 'One of the parent elements needs to use a ThemeProvider.', ].join('\n'), ); } } let query = typeof queryInput === 'function' ? queryInput(theme) : queryInput; query = query.replace(/^@media( ?)/m, ''); // TODO: Drop `useMediaQueryOld` and use `use-sync-external-store` shim in `useMediaQueryNew` once the package is stable const useMediaQueryImplementation = (React as any).useSyncExternalStore !== undefined ? useMediaQueryNew : useMediaQueryOld; const match = useMediaQueryImplementation( query, defaultMatches, matchMedia, ssrMatchMedia, noSsr, ); if (process.env.NODE_ENV !== 'production') { // eslint-disable-next-line react-hooks/rules-of-hooks React.useDebugValue({ query, match }); } return match; }
packages/mui-material/src/useMediaQuery/useMediaQuery.ts
1
https://github.com/mui/material-ui/commit/fb9808c62e610ddd082a151827c46db022f6f0fe
[ 0.9981157779693604, 0.11730994284152985, 0.00016935888561420143, 0.0021014297381043434, 0.3090365529060364 ]
{ "id": 4, "code_window": [ " const mediaQueryList = matchMedia(query);\n", "\n", " return [\n", " () => mediaQueryList.matches,\n", " (notify: () => void) => {\n", " mediaQueryList.addEventListener('change', notify);\n", " return () => {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ " // TODO: Use `addEventListener` once support for Safari < 14 is dropped\n", " mediaQueryList.addListener(notify);\n" ], "file_path": "packages/mui-material/src/useMediaQuery/useMediaQuery.ts", "type": "replace", "edit_start_line_idx": 111 }
import * as React from 'react'; import { describeConformance } from 'test/utils'; import DateRangePickerDay, { dateRangePickerDayClasses as classes, } from '@mui/lab/DateRangePickerDay'; import { adapterToUse, wrapPickerMount, createPickerRenderer, } from '../internal/pickers/test-utils'; describe('<DateRangePickerDay />', () => { const { render } = createPickerRenderer(); describeConformance( <DateRangePickerDay day={adapterToUse.date()} outsideCurrentMonth={false} selected onDaySelect={() => {}} isHighlighting isPreviewing isStartOfPreviewing isEndOfPreviewing isStartOfHighlighting isEndOfHighlighting />, () => ({ classes, inheritComponent: 'button', muiName: 'MuiDateRangePickerDay', render, wrapMount: wrapPickerMount, refInstanceof: window.HTMLButtonElement, // cannot test reactTestRenderer because of required context skip: [ 'componentProp', 'rootClass', // forwards classes to DateRangePickerDayDay, but applies root class on DateRangePickerDayRoot 'componentsProp', 'reactTestRenderer', 'propsSpread', 'refForwarding', // TODO: Fix DateRangePickerDays is not spreading props on root 'themeDefaultProps', 'themeVariants', ], }), ); });
packages/mui-lab/src/DateRangePickerDay/DateRangePickerDay.test.tsx
0
https://github.com/mui/material-ui/commit/fb9808c62e610ddd082a151827c46db022f6f0fe
[ 0.0001756330020725727, 0.0001723546301946044, 0.0001668768236413598, 0.0001746325579006225, 0.0000035202797334932256 ]
{ "id": 4, "code_window": [ " const mediaQueryList = matchMedia(query);\n", "\n", " return [\n", " () => mediaQueryList.matches,\n", " (notify: () => void) => {\n", " mediaQueryList.addEventListener('change', notify);\n", " return () => {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ " // TODO: Use `addEventListener` once support for Safari < 14 is dropped\n", " mediaQueryList.addListener(notify);\n" ], "file_path": "packages/mui-material/src/useMediaQuery/useMediaQuery.ts", "type": "replace", "edit_start_line_idx": 111 }
import * as React from 'react'; import ApiPage from 'docs/src/modules/components/ApiPage'; import mapApiPageTranslations from 'docs/src/modules/utils/mapApiPageTranslations'; import jsonPageContent from './time-picker.json'; export default function Page(props) { const { descriptions, pageContent } = props; return <ApiPage descriptions={descriptions} pageContent={pageContent} />; } Page.getInitialProps = () => { const req = require.context( 'docs/translations/api-docs/time-picker', false, /time-picker.*.json$/, ); const descriptions = mapApiPageTranslations(req); return { descriptions, pageContent: jsonPageContent, }; };
docs/pages/api-docs/time-picker.js
0
https://github.com/mui/material-ui/commit/fb9808c62e610ddd082a151827c46db022f6f0fe
[ 0.0001758372673066333, 0.00017336181190330535, 0.00016956331091932952, 0.00017468487203586847, 0.0000027268404210190056 ]
{ "id": 4, "code_window": [ " const mediaQueryList = matchMedia(query);\n", "\n", " return [\n", " () => mediaQueryList.matches,\n", " (notify: () => void) => {\n", " mediaQueryList.addEventListener('change', notify);\n", " return () => {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ " // TODO: Use `addEventListener` once support for Safari < 14 is dropped\n", " mediaQueryList.addListener(notify);\n" ], "file_path": "packages/mui-material/src/useMediaQuery/useMediaQuery.ts", "type": "replace", "edit_start_line_idx": 111 }
import createSvgIcon from './utils/createSvgIcon'; import { jsx as _jsx } from "react/jsx-runtime"; export default createSvgIcon( /*#__PURE__*/_jsx("path", { d: "M3 19h18v2H3zM3 7h12v2H3zm0-4h18v2H3zm0 12h12v2H3zm0-4h18v2H3z" }), 'FormatAlignLeftTwoTone');
packages/mui-icons-material/lib/esm/FormatAlignLeftTwoTone.js
0
https://github.com/mui/material-ui/commit/fb9808c62e610ddd082a151827c46db022f6f0fe
[ 0.00017543014837428927, 0.00017543014837428927, 0.00017543014837428927, 0.00017543014837428927, 0 ]
{ "id": 5, "code_window": [ " return () => {\n", " mediaQueryList.removeEventListener('change', notify);\n", " };\n", " },\n", " ];\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " mediaQueryList.removeListener(notify);\n" ], "file_path": "packages/mui-material/src/useMediaQuery/useMediaQuery.ts", "type": "replace", "edit_start_line_idx": 113 }
import * as React from 'react'; import PropTypes from 'prop-types'; import { ThemeProvider } from '@mui/material/styles'; import useMediaQuery from '@mui/material/useMediaQuery'; import { act, createRenderer, screen, RenderCounter, strictModeDoubleLoggingSupressed, } from 'test/utils'; import mediaQuery from 'css-mediaquery'; import { expect } from 'chai'; import { stub } from 'sinon'; const usesUseSyncExternalStore = React.useSyncExternalStore !== undefined; function createMatchMedia(width, ref) { const listeners = []; return (query) => { const instance = { matches: mediaQuery.match(query, { width, }), addEventListener: (type, listener) => { listeners.push(listener); }, removeEventListener: (type, listener) => { const index = listeners.indexOf(listener); if (index > -1) { listeners.splice(index, 1); } }, }; ref.push({ instance, listeners, }); return instance; }; } describe('useMediaQuery', () => { const { render, renderToString } = createRenderer(); describe('without window.matchMedia', () => { let originalMatchmedia; beforeEach(() => { originalMatchmedia = window.matchMedia; delete window.matchMedia; }); afterEach(() => { window.matchMedia = originalMatchmedia; }); it('should work without window.matchMedia available', () => { expect(typeof window.matchMedia).to.equal('undefined'); const Test = () => { const matches = useMediaQuery('(min-width:100px)'); return <span data-testid="matches">{`${matches}`}</span>; }; render(<Test />); expect(screen.getByTestId('matches').textContent).to.equal('false'); }); }); describe('with window.matchMedia', () => { let matchMediaInstances; beforeEach(() => { matchMediaInstances = []; const fakeMatchMedia = createMatchMedia(1200, matchMediaInstances); // can't stub non-existent properties with sinon // jsdom does not implement window.matchMedia if (window.matchMedia === undefined) { window.matchMedia = fakeMatchMedia; window.matchMedia.restore = () => { delete window.matchMedia; }; } else { stub(window, 'matchMedia').callsFake(fakeMatchMedia); } }); afterEach(() => { window.matchMedia.restore(); }); describe('option: defaultMatches', () => { it('should be false by default', () => { const getRenderCountRef = React.createRef(); const Test = () => { const matches = useMediaQuery('(min-width:2000px)'); return ( <RenderCounter ref={getRenderCountRef}> <span data-testid="matches">{`${matches}`}</span> </RenderCounter> ); }; render(<Test />); expect(screen.getByTestId('matches').textContent).to.equal('false'); expect(getRenderCountRef.current()).to.equal(1); }); it('should take the option into account', () => { const getRenderCountRef = React.createRef(); const Test = () => { const matches = useMediaQuery('(min-width:2000px)', { defaultMatches: true, }); return ( <RenderCounter ref={getRenderCountRef}> <span data-testid="matches">{`${matches}`}</span> </RenderCounter> ); }; render(<Test />); expect(screen.getByTestId('matches').textContent).to.equal('false'); expect(getRenderCountRef.current()).to.equal(usesUseSyncExternalStore ? 1 : 2); }); }); describe('option: noSsr', () => { it('should render once if the default value match the expectation', () => { const getRenderCountRef = React.createRef(); const Test = () => { const matches = useMediaQuery('(min-width:2000px)', { defaultMatches: false, }); return ( <RenderCounter ref={getRenderCountRef}> <span data-testid="matches">{`${matches}`}</span> </RenderCounter> ); }; render(<Test />); expect(screen.getByTestId('matches').textContent).to.equal('false'); expect(getRenderCountRef.current()).to.equal(1); }); it('should render twice if the default value does not match the expectation', () => { const getRenderCountRef = React.createRef(); const Test = () => { const matches = useMediaQuery('(min-width:2000px)', { defaultMatches: true, }); return ( <RenderCounter ref={getRenderCountRef}> <span data-testid="matches">{`${matches}`}</span> </RenderCounter> ); }; render(<Test />); expect(screen.getByTestId('matches').textContent).to.equal('false'); expect(getRenderCountRef.current()).to.equal(usesUseSyncExternalStore ? 1 : 2); }); it('should render once if the default value does not match the expectation but `noSsr` is enabled', () => { const getRenderCountRef = React.createRef(); const Test = () => { const matches = useMediaQuery('(min-width:2000px)', { defaultMatches: true, noSsr: true, }); return ( <RenderCounter ref={getRenderCountRef}> <span data-testid="matches">{`${matches}`}</span> </RenderCounter> ); }; render(<Test />); expect(screen.getByTestId('matches').textContent).to.equal('false'); expect(getRenderCountRef.current()).to.equal(1); }); }); it('should try to reconcile each time', () => { const getRenderCountRef = React.createRef(); const Test = () => { const matches = useMediaQuery('(min-width:2000px)', { defaultMatches: true, }); return ( <RenderCounter ref={getRenderCountRef}> <span data-testid="matches">{`${matches}`}</span> </RenderCounter> ); }; const { unmount } = render(<Test />); expect(screen.getByTestId('matches').textContent).to.equal('false'); expect(getRenderCountRef.current()).to.equal(usesUseSyncExternalStore ? 1 : 2); unmount(); render(<Test />); expect(screen.getByTestId('matches').textContent).to.equal('false'); expect(getRenderCountRef.current()).to.equal(usesUseSyncExternalStore ? 1 : 2); }); it('should be able to change the query dynamically', () => { const getRenderCountRef = React.createRef(); const Test = (props) => { const matches = useMediaQuery(props.query, { defaultMatches: true, }); return ( <RenderCounter ref={getRenderCountRef}> <span data-testid="matches">{`${matches}`}</span> </RenderCounter> ); }; Test.propTypes = { query: PropTypes.string.isRequired, }; const { setProps } = render(<Test query="(min-width:2000px)" />); expect(screen.getByTestId('matches').textContent).to.equal('false'); expect(getRenderCountRef.current()).to.equal(usesUseSyncExternalStore ? 1 : 2); setProps({ query: '(min-width:100px)' }); expect(screen.getByTestId('matches').textContent).to.equal('true'); expect(getRenderCountRef.current()).to.equal(usesUseSyncExternalStore ? 2 : 4); }); it('should observe the media query', () => { const getRenderCountRef = React.createRef(); const Test = (props) => { const matches = useMediaQuery(props.query); return ( <RenderCounter ref={getRenderCountRef}> <span data-testid="matches">{`${matches}`}</span> </RenderCounter> ); }; Test.propTypes = { query: PropTypes.string.isRequired, }; render(<Test query="(min-width:2000px)" />); expect(getRenderCountRef.current()).to.equal(1); expect(screen.getByTestId('matches').textContent).to.equal('false'); act(() => { matchMediaInstances[matchMediaInstances.length - 1].instance.matches = true; matchMediaInstances[matchMediaInstances.length - 1].listeners[0](); }); expect(screen.getByTestId('matches').textContent).to.equal('true'); expect(getRenderCountRef.current()).to.equal(2); }); }); describe('server-side', () => { it('should use the ssr match media ponyfill', () => { function MyComponent() { const matches = useMediaQuery('(min-width:2000px)'); return <span>{`${matches}`}</span>; } const Test = () => { const ssrMatchMedia = (query) => ({ matches: mediaQuery.match(query, { width: 3000, }), }); return ( <ThemeProvider theme={{ components: { MuiUseMediaQuery: { defaultProps: { ssrMatchMedia } } } }} > <MyComponent /> </ThemeProvider> ); }; const { container } = renderToString(<Test />); expect(container.firstChild).to.have.text('true'); }); }); describe('warnings', () => { it('warns on invalid `query` argument', () => { function MyComponent() { useMediaQuery(() => '(min-width:2000px)'); return null; } expect(() => { render(<MyComponent />); }).toErrorDev([ 'MUI: The `query` argument provided is invalid', !strictModeDoubleLoggingSupressed && 'MUI: The `query` argument provided is invalid', ]); }); }); });
packages/mui-material/src/useMediaQuery/useMediaQuery.test.js
1
https://github.com/mui/material-ui/commit/fb9808c62e610ddd082a151827c46db022f6f0fe
[ 0.0006217076443135738, 0.00018809811444953084, 0.00016343228344339877, 0.00016699876869097352, 0.00008578280539950356 ]
{ "id": 5, "code_window": [ " return () => {\n", " mediaQueryList.removeEventListener('change', notify);\n", " };\n", " },\n", " ];\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " mediaQueryList.removeListener(notify);\n" ], "file_path": "packages/mui-material/src/useMediaQuery/useMediaQuery.ts", "type": "replace", "edit_start_line_idx": 113 }
import createSvgIcon from './utils/createSvgIcon'; import { jsx as _jsx } from "react/jsx-runtime"; export default createSvgIcon( /*#__PURE__*/_jsx("path", { d: "m19.17 12-4.58-4.59L16 6l6 6-3.59 3.59L17 14.17 19.17 12zM1.39 4.22l4.19 4.19L2 12l6 6 1.41-1.41L4.83 12 7 9.83l12.78 12.78 1.41-1.41L2.81 2.81 1.39 4.22z" }), 'CodeOffSharp');
packages/mui-icons-material/lib/esm/CodeOffSharp.js
0
https://github.com/mui/material-ui/commit/fb9808c62e610ddd082a151827c46db022f6f0fe
[ 0.00016861014591995627, 0.00016861014591995627, 0.00016861014591995627, 0.00016861014591995627, 0 ]
{ "id": 5, "code_window": [ " return () => {\n", " mediaQueryList.removeEventListener('change', notify);\n", " };\n", " },\n", " ];\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " mediaQueryList.removeListener(notify);\n" ], "file_path": "packages/mui-material/src/useMediaQuery/useMediaQuery.ts", "type": "replace", "edit_start_line_idx": 113 }
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon")); var _jsxRuntime = require("react/jsx-runtime"); var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M19.5 9.5c-1.03 0-1.9.62-2.29 1.5h-2.92c-.39-.88-1.26-1.5-2.29-1.5s-1.9.62-2.29 1.5H6.79c-.39-.88-1.26-1.5-2.29-1.5C3.12 9.5 2 10.62 2 12s1.12 2.5 2.5 2.5c1.03 0 1.9-.62 2.29-1.5h2.92c.39.88 1.26 1.5 2.29 1.5s1.9-.62 2.29-1.5h2.92c.39.88 1.26 1.5 2.29 1.5 1.38 0 2.5-1.12 2.5-2.5s-1.12-2.5-2.5-2.5z" }), 'LinearScaleTwoTone'); exports.default = _default;
packages/mui-icons-material/lib/LinearScaleTwoTone.js
0
https://github.com/mui/material-ui/commit/fb9808c62e610ddd082a151827c46db022f6f0fe
[ 0.00016631670587230474, 0.0001656305103097111, 0.00016494430019520223, 0.0001656305103097111, 6.862028385512531e-7 ]
{ "id": 5, "code_window": [ " return () => {\n", " mediaQueryList.removeEventListener('change', notify);\n", " };\n", " },\n", " ];\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " mediaQueryList.removeListener(notify);\n" ], "file_path": "packages/mui-material/src/useMediaQuery/useMediaQuery.ts", "type": "replace", "edit_start_line_idx": 113 }
<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 0 24 24" width="24"><path d="M0 0h24v24H0V0z" fill="none"/><path d="M7 3h2v2H7zm0 8h2v2H7zm0 8h2v2H7zm-4 0h2v2H3zM3 3h2v2H3zm0 8h2v2H3zm16-8h2v2h-2zM3 7h2v2H3zm8-4h2v18h-2zM3 15h2v2H3zm12-4h2v2h-2zm4 4h2v2h-2zm0-4h2v2h-2zm0-4h2v2h-2zm0 12h2v2h-2zm-4 0h2v2h-2zm0-16h2v2h-2z"/></svg>
packages/mui-icons-material/material-icons/border_vertical_two_tone_24px.svg
0
https://github.com/mui/material-ui/commit/fb9808c62e610ddd082a151827c46db022f6f0fe
[ 0.0001662000286160037, 0.0001662000286160037, 0.0001662000286160037, 0.0001662000286160037, 0 ]
{ "id": 0, "code_window": [ "import { Orientation } from './Stepper';\n", "import { ButtonBaseProps, ButtonBaseClassKey } from '../ButtonBase';\n", "\n", "export type Icon = React.ReactElement<any> | string | number;\n", "\n", "export interface StepButtonProps extends StandardProps<\n", " ButtonBaseProps,\n", " StepButtonClasskey\n", "> {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "export type StepButtonIcon = React.ReactElement<any> | string | number;\n" ], "file_path": "src/Stepper/StepButton.d.ts", "type": "replace", "edit_start_line_idx": 5 }
import * as React from 'react'; import { StandardProps } from '..'; import { Orientation } from './Stepper'; import { ButtonBaseProps, ButtonBaseClassKey } from '../ButtonBase'; export type Icon = React.ReactElement<any> | string | number; export interface StepButtonProps extends StandardProps< ButtonBaseProps, StepButtonClasskey > { active?: boolean; alternativeLabel?: boolean; children: React.ReactElement<any>; completed?: boolean; disabled?: boolean; icon?: Icon; last?: boolean; optional?: boolean; orientation: Orientation; } export type StepButtonClasskey = | ButtonBaseClassKey | 'root' | 'alternativeLabel' ; declare const StepButton: React.ComponentType<StepButtonProps>; export default StepButton;
src/Stepper/StepButton.d.ts
1
https://github.com/mui/material-ui/commit/d03af40b8fa10d8848106b2df21b215c8c232e54
[ 0.9982290863990784, 0.3204483985900879, 0.0034751431085169315, 0.1400446891784668, 0.40521058440208435 ]
{ "id": 0, "code_window": [ "import { Orientation } from './Stepper';\n", "import { ButtonBaseProps, ButtonBaseClassKey } from '../ButtonBase';\n", "\n", "export type Icon = React.ReactElement<any> | string | number;\n", "\n", "export interface StepButtonProps extends StandardProps<\n", " ButtonBaseProps,\n", " StepButtonClasskey\n", "> {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "export type StepButtonIcon = React.ReactElement<any> | string | number;\n" ], "file_path": "src/Stepper/StepButton.d.ts", "type": "replace", "edit_start_line_idx": 5 }
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; const SvgIconCustom = global.__MUI_SvgIcon__ || SvgIcon; let CallEnd = props => <SvgIconCustom {...props}> <path d="M12 9c-1.6 0-3.15.25-4.6.72v3.1c0 .39-.23.74-.56.9-.98.49-1.87 1.12-2.66 1.85-.18.18-.43.28-.7.28-.28 0-.53-.11-.71-.29L.29 13.08c-.18-.17-.29-.42-.29-.7 0-.28.11-.53.29-.71C3.34 8.78 7.46 7 12 7s8.66 1.78 11.71 4.67c.18.18.29.43.29.71 0 .28-.11.53-.29.71l-2.48 2.48c-.18.18-.43.29-.71.29-.27 0-.52-.11-.7-.28-.79-.74-1.69-1.36-2.67-1.85-.33-.16-.56-.5-.56-.9v-3.1C15.15 9.25 13.6 9 12 9z" /> </SvgIconCustom>; CallEnd = pure(CallEnd); CallEnd.muiName = 'SvgIcon'; export default CallEnd;
packages/material-ui-icons/src/CallEnd.js
0
https://github.com/mui/material-ui/commit/d03af40b8fa10d8848106b2df21b215c8c232e54
[ 0.0001779040030669421, 0.00017234261031262577, 0.00016678121755830944, 0.00017234261031262577, 0.00000556139275431633 ]
{ "id": 0, "code_window": [ "import { Orientation } from './Stepper';\n", "import { ButtonBaseProps, ButtonBaseClassKey } from '../ButtonBase';\n", "\n", "export type Icon = React.ReactElement<any> | string | number;\n", "\n", "export interface StepButtonProps extends StandardProps<\n", " ButtonBaseProps,\n", " StepButtonClasskey\n", "> {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "export type StepButtonIcon = React.ReactElement<any> | string | number;\n" ], "file_path": "src/Stepper/StepButton.d.ts", "type": "replace", "edit_start_line_idx": 5 }
// flow-typed signature: 6a5610678d4b01e13bbfbbc62bdaf583 // flow-typed version: 3817bc6980/flow-bin_v0.x.x/flow_>=v0.25.x declare module "flow-bin" { declare module.exports: string; }
flow-typed/npm/flow-bin_v0.x.x.js
0
https://github.com/mui/material-ui/commit/d03af40b8fa10d8848106b2df21b215c8c232e54
[ 0.000173966953298077, 0.000173966953298077, 0.000173966953298077, 0.000173966953298077, 0 ]
{ "id": 0, "code_window": [ "import { Orientation } from './Stepper';\n", "import { ButtonBaseProps, ButtonBaseClassKey } from '../ButtonBase';\n", "\n", "export type Icon = React.ReactElement<any> | string | number;\n", "\n", "export interface StepButtonProps extends StandardProps<\n", " ButtonBaseProps,\n", " StepButtonClasskey\n", "> {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "export type StepButtonIcon = React.ReactElement<any> | string | number;\n" ], "file_path": "src/Stepper/StepButton.d.ts", "type": "replace", "edit_start_line_idx": 5 }
// @flow weak import React from 'react'; import PropTypes from 'prop-types'; import { withStyles } from 'material-ui/styles'; import { CircularProgress } from 'material-ui/Progress'; const styles = theme => ({ progress: { margin: `0 ${theme.spacing.unit * 2}px`, }, }); function CircularDeterminate(props) { const { classes } = props; return ( <div> <CircularProgress className={classes.progress} mode="determinate" value={75} /> <CircularProgress className={classes.progress} size={50} mode="determinate" value={25} min={0} max={50} /> <CircularProgress className={classes.progress} color="accent" mode="determinate" value={75} /> <CircularProgress className={classes.progress} color="accent" size={50} mode="determinate" value={25} min={0} max={50} /> </div> ); } CircularDeterminate.propTypes = { classes: PropTypes.object.isRequired, }; export default withStyles(styles)(CircularDeterminate);
docs/src/pages/demos/progress/CircularDeterminate.js
0
https://github.com/mui/material-ui/commit/d03af40b8fa10d8848106b2df21b215c8c232e54
[ 0.00018033449305221438, 0.00017686928913462907, 0.00017326866509392858, 0.0001775002310751006, 0.000002938889110737364 ]
{ "id": 1, "code_window": [ " alternativeLabel?: boolean;\n", " children: React.ReactElement<any>;\n", " completed?: boolean;\n", " disabled?: boolean;\n", " icon?: Icon;\n", " last?: boolean;\n", " optional?: boolean;\n", " orientation: Orientation;\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " icon?: StepButtonIcon;\n" ], "file_path": "src/Stepper/StepButton.d.ts", "type": "replace", "edit_start_line_idx": 16 }
import * as React from 'react'; import { StandardProps } from '..'; import { Orientation } from './Stepper'; export type Icon = React.ReactElement<any> | string | number; export interface StepConnectorProps extends StandardProps< React.HTMLAttributes<HTMLDivElement>, StepConnectorClasskey > { alternativeLabel?: boolean, orientation?: Orientation, } export type StepConnectorClasskey = | 'root' | 'alternativeLabel' ; declare const StepConnector: React.ComponentType<StepConnectorProps>; export default StepConnector;
src/Stepper/StepConnector.d.ts
1
https://github.com/mui/material-ui/commit/d03af40b8fa10d8848106b2df21b215c8c232e54
[ 0.010208366438746452, 0.0036815942730754614, 0.0001774254342308268, 0.0006589903496205807, 0.0046193101443350315 ]
{ "id": 1, "code_window": [ " alternativeLabel?: boolean;\n", " children: React.ReactElement<any>;\n", " completed?: boolean;\n", " disabled?: boolean;\n", " icon?: Icon;\n", " last?: boolean;\n", " optional?: boolean;\n", " orientation: Orientation;\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " icon?: StepButtonIcon;\n" ], "file_path": "src/Stepper/StepButton.d.ts", "type": "replace", "edit_start_line_idx": 16 }
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; const SvgIconCustom = global.__MUI_SvgIcon__ || SvgIcon; let Watch = props => <SvgIconCustom {...props}> <path d="M20 12c0-2.54-1.19-4.81-3.04-6.27L16 0H8l-.95 5.73C5.19 7.19 4 9.45 4 12s1.19 4.81 3.05 6.27L8 24h8l.96-5.73C18.81 16.81 20 14.54 20 12zM6 12c0-3.31 2.69-6 6-6s6 2.69 6 6-2.69 6-6 6-6-2.69-6-6z" /> </SvgIconCustom>; Watch = pure(Watch); Watch.muiName = 'SvgIcon'; export default Watch;
packages/material-ui-icons/src/Watch.js
0
https://github.com/mui/material-ui/commit/d03af40b8fa10d8848106b2df21b215c8c232e54
[ 0.00017882100655697286, 0.00017293202108703554, 0.0001670430356170982, 0.00017293202108703554, 0.0000058889854699373245 ]
{ "id": 1, "code_window": [ " alternativeLabel?: boolean;\n", " children: React.ReactElement<any>;\n", " completed?: boolean;\n", " disabled?: boolean;\n", " icon?: Icon;\n", " last?: boolean;\n", " optional?: boolean;\n", " orientation: Orientation;\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " icon?: StepButtonIcon;\n" ], "file_path": "src/Stepper/StepButton.d.ts", "type": "replace", "edit_start_line_idx": 16 }
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; const SvgIconCustom = global.__MUI_SvgIcon__ || SvgIcon; let ExposureNeg1 = props => <SvgIconCustom {...props}> <path d="M4 11v2h8v-2H4zm15 7h-2V7.38L14 8.4V6.7L18.7 5h.3v13z" /> </SvgIconCustom>; ExposureNeg1 = pure(ExposureNeg1); ExposureNeg1.muiName = 'SvgIcon'; export default ExposureNeg1;
packages/material-ui-icons/src/ExposureNeg1.js
0
https://github.com/mui/material-ui/commit/d03af40b8fa10d8848106b2df21b215c8c232e54
[ 0.0001754410332068801, 0.00017148617189377546, 0.0001675312960287556, 0.00017148617189377546, 0.000003954868589062244 ]
{ "id": 1, "code_window": [ " alternativeLabel?: boolean;\n", " children: React.ReactElement<any>;\n", " completed?: boolean;\n", " disabled?: boolean;\n", " icon?: Icon;\n", " last?: boolean;\n", " optional?: boolean;\n", " orientation: Orientation;\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " icon?: StepButtonIcon;\n" ], "file_path": "src/Stepper/StepButton.d.ts", "type": "replace", "edit_start_line_idx": 16 }
/* eslint-disable flowtype/require-valid-file-annotation */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; import Button from 'material-ui/Button'; import Dialog, { DialogTitle, DialogContent, DialogContentText, DialogActions, } from 'material-ui/Dialog'; import Typography from 'material-ui/Typography'; import { withStyles } from 'material-ui/styles'; import withRoot from '../components/withRoot'; const styles = { root: { textAlign: 'center', paddingTop: 200, }, }; class Index extends Component { state = { open: false, }; handleRequestClose = () => { this.setState({ open: false, }); }; handleClick = () => { this.setState({ open: true, }); }; render() { return ( <div className={this.props.classes.root}> <Dialog open={this.state.open} onRequestClose={this.handleRequestClose}> <DialogTitle>Super Secret Password</DialogTitle> <DialogContent> <DialogContentText>1-2-3-4-5</DialogContentText> </DialogContent> <DialogActions> <Button color="primary" onClick={this.handleRequestClose}> OK </Button> </DialogActions> </Dialog> <Typography type="display1" gutterBottom> Material-UI </Typography> <Typography type="subheading" gutterBottom> example project </Typography> <Button raised color="accent" onClick={this.handleClick}> Super Secret Password </Button> </div> ); } } Index.propTypes = { classes: PropTypes.object.isRequired, }; export default withRoot(withStyles(styles)(Index));
examples/nextjs/pages/index.js
0
https://github.com/mui/material-ui/commit/d03af40b8fa10d8848106b2df21b215c8c232e54
[ 0.00017942393606062979, 0.00017548896721564233, 0.00016858040180522949, 0.00017638075223658234, 0.000003445102720434079 ]
{ "id": 2, "code_window": [ "import * as React from 'react';\n", "import { StandardProps } from '..';\n", "import { Orientation } from './Stepper';\n", "\n", "export type Icon = React.ReactElement<any> | string | number;\n", "\n", "export interface StepConnectorProps extends StandardProps<\n", " React.HTMLAttributes<HTMLDivElement>,\n", " StepConnectorClasskey\n", "> {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "export type StepConnectorIcon = React.ReactElement<any> | string | number;\n" ], "file_path": "src/Stepper/StepConnector.d.ts", "type": "replace", "edit_start_line_idx": 4 }
import * as React from 'react'; import { StandardProps } from '..'; import { Orientation } from './Stepper'; import { ButtonBaseProps, ButtonBaseClassKey } from '../ButtonBase'; export type Icon = React.ReactElement<any> | string | number; export interface StepButtonProps extends StandardProps< ButtonBaseProps, StepButtonClasskey > { active?: boolean; alternativeLabel?: boolean; children: React.ReactElement<any>; completed?: boolean; disabled?: boolean; icon?: Icon; last?: boolean; optional?: boolean; orientation: Orientation; } export type StepButtonClasskey = | ButtonBaseClassKey | 'root' | 'alternativeLabel' ; declare const StepButton: React.ComponentType<StepButtonProps>; export default StepButton;
src/Stepper/StepButton.d.ts
1
https://github.com/mui/material-ui/commit/d03af40b8fa10d8848106b2df21b215c8c232e54
[ 0.9703720211982727, 0.2499096393585205, 0.00023043554392643273, 0.014518076553940773, 0.4160478711128235 ]
{ "id": 2, "code_window": [ "import * as React from 'react';\n", "import { StandardProps } from '..';\n", "import { Orientation } from './Stepper';\n", "\n", "export type Icon = React.ReactElement<any> | string | number;\n", "\n", "export interface StepConnectorProps extends StandardProps<\n", " React.HTMLAttributes<HTMLDivElement>,\n", " StepConnectorClasskey\n", "> {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "export type StepConnectorIcon = React.ReactElement<any> | string | number;\n" ], "file_path": "src/Stepper/StepConnector.d.ts", "type": "replace", "edit_start_line_idx": 4 }
// @flow import { assert } from 'chai'; import { stub } from 'sinon'; import transitions, { easing, duration, formatMs, isString, isNumber } from './transitions'; describe('transitions', () => { let consoleErrorStub; beforeEach(() => { consoleErrorStub = stub(console, 'error'); }); afterEach(() => { consoleErrorStub.restore(); }); describe('formatMs() function', () => { it('should round decimal digits and return formatted value', () => { const formattedValue = formatMs(12.125); assert.strictEqual(formattedValue, '12ms'); }); }); describe('isString() function', () => { it('should return false when passed undefined', () => { const value = isString(); assert.strictEqual(value, false); }); it('should return false when not passed a string', () => { let value = isString(1); assert.strictEqual(value, false); value = isString({}); assert.strictEqual(value, false); value = isString([]); assert.strictEqual(value, false); }); it('should return true when passed a string', () => { let value = isString(''); assert.strictEqual(value, true); value = isString('test'); assert.strictEqual(value, true); }); }); describe('isNumber() function', () => { it('should return false when passed undefined', () => { const value = isNumber(); assert.strictEqual(value, false); }); it('should return false when not passed a number', () => { let value = isNumber(''); assert.strictEqual(value, false); value = isNumber('test'); assert.strictEqual(value, false); value = isNumber({}); assert.strictEqual(value, false); value = isNumber([]); assert.strictEqual(value, false); }); it('should return true when passed a number', () => { let value = isNumber(1); assert.strictEqual(value, true); value = isNumber(1.5); assert.strictEqual(value, true); }); }); describe('create() function', () => { it('should create default transition without arguments', () => { const transition = transitions.create(); assert.strictEqual(transition, `all ${duration.standard}ms ${easing.easeInOut} 0ms`); assert.strictEqual(consoleErrorStub.callCount, 0, 'Wrong number of calls of warning()'); }); it('should take string props as a first argument', () => { const transition = transitions.create('color'); assert.strictEqual(transition, `color ${duration.standard}ms ${easing.easeInOut} 0ms`); assert.strictEqual(consoleErrorStub.callCount, 0, 'Wrong number of calls of warning()'); }); it('should also take array of props as first argument', () => { const options = { delay: 20 }; const multiple = transitions.create(['color', 'size'], options); const single1 = transitions.create('color', options); const single2 = transitions.create('size', options); const expected = `${single1},${single2}`; assert.strictEqual(multiple, expected); assert.strictEqual(consoleErrorStub.callCount, 0, 'Wrong number of calls of warning()'); }); it('should warn when first argument is of bad type', () => { // $FlowExpectedError transitions.create(5554); // $FlowExpectedError transitions.create({}); assert.strictEqual(consoleErrorStub.callCount, 2, 'Wrong number of calls of warning()'); }); it('should optionally accept number "duration" option in second argument', () => { const transition = transitions.create('font', { duration: 500 }); assert.strictEqual(transition, `font 500ms ${easing.easeInOut} 0ms`); assert.strictEqual(consoleErrorStub.callCount, 0, 'Wrong number of calls of warning()'); }); it('should round decimal digits of "duration" prop to whole numbers', () => { const transition = transitions.create('font', { duration: 12.125 }); assert.strictEqual(transition, `font 12ms ${easing.easeInOut} 0ms`); assert.strictEqual(consoleErrorStub.callCount, 0, 'Wrong number of calls of warning()'); }); it('should warn when bad "duration" option type', () => { // $FlowExpectedError transitions.create('font', { duration: '' }); // $FlowExpectedError transitions.create('font', { duration: {} }); assert.strictEqual(consoleErrorStub.callCount, 2, 'Wrong number of calls of warning()'); }); it('should optionally accept string "easing" option in second argument', () => { const transition = transitions.create('transform', { easing: easing.sharp }); assert.strictEqual(transition, `transform ${duration.standard}ms ${easing.sharp} 0ms`); assert.strictEqual(consoleErrorStub.callCount, 0, 'Wrong number of calls of warning()'); }); it('should warn when bad "easing" option type', () => { // $FlowExpectedError transitions.create('transform', { easing: 123 }); // $FlowExpectedError transitions.create('transform', { easing: {} }); assert.strictEqual(consoleErrorStub.callCount, 2, 'Wrong number of calls of warning()'); }); it('should optionally accept number "delay" option in second argument', () => { const transition = transitions.create('size', { delay: 150 }); assert.strictEqual(transition, `size ${duration.standard}ms ${easing.easeInOut} 150ms`); assert.strictEqual(consoleErrorStub.callCount, 0, 'Wrong number of calls of warning()'); }); it('should round decimal digits of "delay" prop to whole numbers', () => { const transition = transitions.create('size', { delay: 1.547 }); assert.strictEqual(transition, `size ${duration.standard}ms ${easing.easeInOut} 2ms`); assert.strictEqual(consoleErrorStub.callCount, 0, 'Wrong number of calls of warning()'); }); it('should warn when bad "delay" option type', () => { // $FlowExpectedError transitions.create('size', { delay: '' }); // $FlowExpectedError transitions.create('size', { delay: {} }); assert.strictEqual(consoleErrorStub.callCount, 2, 'Wrong number of calls of warning()'); }); it('should warn when passed unrecognized option', () => { transitions.create('size', { fffds: 'value' }); assert.strictEqual(consoleErrorStub.callCount, 1, 'Wrong number of calls of warning()'); }); it('should return zero when not passed arguments', () => { const zeroHeightDuration = transitions.getAutoHeightDuration(); assert.strictEqual(zeroHeightDuration, 0); }); it('should return zero when passed undefined', () => { const zeroHeightDuration = transitions.getAutoHeightDuration(undefined); assert.strictEqual(zeroHeightDuration, 0); }); it('should return zero when passed null', () => { const zeroHeightDuration = transitions.getAutoHeightDuration(null); assert.strictEqual(zeroHeightDuration, 0); }); it('should return NaN when passed a negative number', () => { const zeroHeightDurationNegativeOne = transitions.getAutoHeightDuration(-1); assert.strictEqual(Number.isNaN(zeroHeightDurationNegativeOne), true); const zeroHeightDurationSmallNegative = transitions.getAutoHeightDuration(-0.000001); assert.strictEqual(Number.isNaN(zeroHeightDurationSmallNegative), true); const zeroHeightDurationBigNegative = transitions.getAutoHeightDuration(-100000); assert.strictEqual(Number.isNaN(zeroHeightDurationBigNegative), true); }); it('should return values for pre-calculated positive examples', () => { let zeroHeightDuration = transitions.getAutoHeightDuration(14); assert.strictEqual(zeroHeightDuration, 159); zeroHeightDuration = transitions.getAutoHeightDuration(100); assert.strictEqual(zeroHeightDuration, 239); zeroHeightDuration = transitions.getAutoHeightDuration(0.0001); assert.strictEqual(zeroHeightDuration, 46); zeroHeightDuration = transitions.getAutoHeightDuration(100000); assert.strictEqual(zeroHeightDuration, 6685); }); }); });
src/styles/transitions.spec.js
0
https://github.com/mui/material-ui/commit/d03af40b8fa10d8848106b2df21b215c8c232e54
[ 0.00018086296040564775, 0.00017818331252783537, 0.00017413572641089559, 0.0001779907033778727, 0.0000016855220792422188 ]
{ "id": 2, "code_window": [ "import * as React from 'react';\n", "import { StandardProps } from '..';\n", "import { Orientation } from './Stepper';\n", "\n", "export type Icon = React.ReactElement<any> | string | number;\n", "\n", "export interface StepConnectorProps extends StandardProps<\n", " React.HTMLAttributes<HTMLDivElement>,\n", " StepConnectorClasskey\n", "> {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "export type StepConnectorIcon = React.ReactElement<any> | string | number;\n" ], "file_path": "src/Stepper/StepConnector.d.ts", "type": "replace", "edit_start_line_idx": 4 }
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; const SvgIconCustom = global.__MUI_SvgIcon__ || SvgIcon; let VolumeUp = props => <SvgIconCustom {...props}> <path d="M3 9v6h4l5 5V4L7 9H3zm13.5 3c0-1.77-1.02-3.29-2.5-4.03v8.05c1.48-.73 2.5-2.25 2.5-4.02zM14 3.23v2.06c2.89.86 5 3.54 5 6.71s-2.11 5.85-5 6.71v2.06c4.01-.91 7-4.49 7-8.77s-2.99-7.86-7-8.77z" /> </SvgIconCustom>; VolumeUp = pure(VolumeUp); VolumeUp.muiName = 'SvgIcon'; export default VolumeUp;
packages/material-ui-icons/src/VolumeUp.js
0
https://github.com/mui/material-ui/commit/d03af40b8fa10d8848106b2df21b215c8c232e54
[ 0.00017932814080268145, 0.0001754467375576496, 0.00017156531976070255, 0.0001754467375576496, 0.000003881410520989448 ]
{ "id": 2, "code_window": [ "import * as React from 'react';\n", "import { StandardProps } from '..';\n", "import { Orientation } from './Stepper';\n", "\n", "export type Icon = React.ReactElement<any> | string | number;\n", "\n", "export interface StepConnectorProps extends StandardProps<\n", " React.HTMLAttributes<HTMLDivElement>,\n", " StepConnectorClasskey\n", "> {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "export type StepConnectorIcon = React.ReactElement<any> | string | number;\n" ], "file_path": "src/Stepper/StepConnector.d.ts", "type": "replace", "edit_start_line_idx": 4 }
// @flow import React from 'react'; import withRoot from 'docs/src/modules/components/withRoot'; import MarkdownDocs from 'docs/src/modules/components/MarkdownDocs'; import markdown from './step-label.md'; function Page() { return <MarkdownDocs markdown={markdown} />; } export default withRoot(Page);
pages/api/step-label.js
0
https://github.com/mui/material-ui/commit/d03af40b8fa10d8848106b2df21b215c8c232e54
[ 0.00016977831546682864, 0.0001687378971837461, 0.00016769749345257878, 0.0001687378971837461, 0.0000010404110071249306 ]
{ "id": 3, "code_window": [ "import * as React from 'react';\n", "import { StandardProps } from '..';\n", "import { Orientation } from './Stepper';\n", "import { Icon } from './StepButton';\n", "\n", "export interface StepLabelProps extends StandardProps<\n", " React.HTMLAttributes<HTMLDivElement>,\n", " StepLabelClasskey\n", "> {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { StepButtonIcon } from './StepButton';\n" ], "file_path": "src/Stepper/StepLabel.d.ts", "type": "replace", "edit_start_line_idx": 3 }
import * as React from 'react'; import { StandardProps } from '..'; import { Orientation } from './Stepper'; import { ButtonBaseProps, ButtonBaseClassKey } from '../ButtonBase'; export type Icon = React.ReactElement<any> | string | number; export interface StepButtonProps extends StandardProps< ButtonBaseProps, StepButtonClasskey > { active?: boolean; alternativeLabel?: boolean; children: React.ReactElement<any>; completed?: boolean; disabled?: boolean; icon?: Icon; last?: boolean; optional?: boolean; orientation: Orientation; } export type StepButtonClasskey = | ButtonBaseClassKey | 'root' | 'alternativeLabel' ; declare const StepButton: React.ComponentType<StepButtonProps>; export default StepButton;
src/Stepper/StepButton.d.ts
1
https://github.com/mui/material-ui/commit/d03af40b8fa10d8848106b2df21b215c8c232e54
[ 0.01649170182645321, 0.00852891430258751, 0.001295969937928021, 0.008163990452885628, 0.005651859100908041 ]
{ "id": 3, "code_window": [ "import * as React from 'react';\n", "import { StandardProps } from '..';\n", "import { Orientation } from './Stepper';\n", "import { Icon } from './StepButton';\n", "\n", "export interface StepLabelProps extends StandardProps<\n", " React.HTMLAttributes<HTMLDivElement>,\n", " StepLabelClasskey\n", "> {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { StepButtonIcon } from './StepButton';\n" ], "file_path": "src/Stepper/StepLabel.d.ts", "type": "replace", "edit_start_line_idx": 3 }
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; const SvgIconCustom = global.__MUI_SvgIcon__ || SvgIcon; let Mood = props => <SvgIconCustom {...props}> <path d="M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zM12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8zm3.5-9c.83 0 1.5-.67 1.5-1.5S16.33 8 15.5 8 14 8.67 14 9.5s.67 1.5 1.5 1.5zm-7 0c.83 0 1.5-.67 1.5-1.5S9.33 8 8.5 8 7 8.67 7 9.5 7.67 11 8.5 11zm3.5 6.5c2.33 0 4.31-1.46 5.11-3.5H6.89c.8 2.04 2.78 3.5 5.11 3.5z" /> </SvgIconCustom>; Mood = pure(Mood); Mood.muiName = 'SvgIcon'; export default Mood;
packages/material-ui-icons/src/Mood.js
0
https://github.com/mui/material-ui/commit/d03af40b8fa10d8848106b2df21b215c8c232e54
[ 0.00017717354057822376, 0.00017339283658657223, 0.0001696121325949207, 0.00017339283658657223, 0.000003780703991651535 ]
{ "id": 3, "code_window": [ "import * as React from 'react';\n", "import { StandardProps } from '..';\n", "import { Orientation } from './Stepper';\n", "import { Icon } from './StepButton';\n", "\n", "export interface StepLabelProps extends StandardProps<\n", " React.HTMLAttributes<HTMLDivElement>,\n", " StepLabelClasskey\n", "> {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { StepButtonIcon } from './StepButton';\n" ], "file_path": "src/Stepper/StepLabel.d.ts", "type": "replace", "edit_start_line_idx": 3 }
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; const SvgIconCustom = global.__MUI_SvgIcon__ || SvgIcon; let BeachAccess = props => <SvgIconCustom {...props}> <path d="M13.127 14.56l1.43-1.43 6.44 6.443L19.57 21zm4.293-5.73l2.86-2.86c-3.95-3.95-10.35-3.96-14.3-.02 3.93-1.3 8.31-.25 11.44 2.88zM5.95 5.98c-3.94 3.95-3.93 10.35.02 14.3l2.86-2.86C5.7 14.29 4.65 9.91 5.95 5.98zm.02-.02l-.01.01c-.38 3.01 1.17 6.88 4.3 10.02l5.73-5.73c-3.13-3.13-7.01-4.68-10.02-4.3z" /> </SvgIconCustom>; BeachAccess = pure(BeachAccess); BeachAccess.muiName = 'SvgIcon'; export default BeachAccess;
packages/material-ui-icons/src/BeachAccess.js
0
https://github.com/mui/material-ui/commit/d03af40b8fa10d8848106b2df21b215c8c232e54
[ 0.0001745360204949975, 0.000171124585904181, 0.00016771316586527973, 0.000171124585904181, 0.0000034114273148588836 ]
{ "id": 3, "code_window": [ "import * as React from 'react';\n", "import { StandardProps } from '..';\n", "import { Orientation } from './Stepper';\n", "import { Icon } from './StepButton';\n", "\n", "export interface StepLabelProps extends StandardProps<\n", " React.HTMLAttributes<HTMLDivElement>,\n", " StepLabelClasskey\n", "> {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { StepButtonIcon } from './StepButton';\n" ], "file_path": "src/Stepper/StepLabel.d.ts", "type": "replace", "edit_start_line_idx": 3 }
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; const SvgIconCustom = global.__MUI_SvgIcon__ || SvgIcon; let Filter3 = props => <SvgIconCustom {...props}> <path d="M21 1H7c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V3c0-1.1-.9-2-2-2zm0 16H7V3h14v14zM3 5H1v16c0 1.1.9 2 2 2h16v-2H3V5zm14 8v-1.5c0-.83-.67-1.5-1.5-1.5.83 0 1.5-.67 1.5-1.5V7c0-1.11-.9-2-2-2h-4v2h4v2h-2v2h2v2h-4v2h4c1.1 0 2-.89 2-2z" /> </SvgIconCustom>; Filter3 = pure(Filter3); Filter3.muiName = 'SvgIcon'; export default Filter3;
packages/material-ui-icons/src/Filter3.js
0
https://github.com/mui/material-ui/commit/d03af40b8fa10d8848106b2df21b215c8c232e54
[ 0.000174635075381957, 0.00017163748270832002, 0.00016863987548276782, 0.00017163748270832002, 0.000002997599949594587 ]
{ "id": 4, "code_window": [ " children: React.ReactNode;\n", " completed?: boolean;\n", " disabled?: boolean;\n", " icon?: Icon;\n", " last?: boolean;\n", " optional?: boolean;\n", " orientation?: Orientation;\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " icon?: StepButtonIcon;\n" ], "file_path": "src/Stepper/StepLabel.d.ts", "type": "replace", "edit_start_line_idx": 14 }
import * as React from 'react'; import { StandardProps } from '..'; import { Orientation } from './Stepper'; import { Icon } from './StepButton'; export interface StepLabelProps extends StandardProps< React.HTMLAttributes<HTMLDivElement>, StepLabelClasskey > { active?: boolean; alternativeLabel?: boolean; children: React.ReactNode; completed?: boolean; disabled?: boolean; icon?: Icon; last?: boolean; optional?: boolean; orientation?: Orientation; } export type StepLabelClasskey = | 'root' | 'horizontal' | 'vertical' | 'active' | 'completed' | 'disabled' | 'iconContainer' | 'iconContainerNoAlternative' | 'alternativeLabelRoot' | 'alternativeLabel' ; declare const StepLabel: React.ComponentType<StepLabelProps>; export default StepLabel;
src/Stepper/StepLabel.d.ts
1
https://github.com/mui/material-ui/commit/d03af40b8fa10d8848106b2df21b215c8c232e54
[ 0.9977141618728638, 0.2502899765968323, 0.00017318922618869692, 0.0016362563474103808, 0.43152719736099243 ]
{ "id": 4, "code_window": [ " children: React.ReactNode;\n", " completed?: boolean;\n", " disabled?: boolean;\n", " icon?: Icon;\n", " last?: boolean;\n", " optional?: boolean;\n", " orientation?: Orientation;\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " icon?: StepButtonIcon;\n" ], "file_path": "src/Stepper/StepLabel.d.ts", "type": "replace", "edit_start_line_idx": 14 }
// flow-typed signature: 0c846661866cb5deeb0198bc0e17e612 // flow-typed version: <<STUB>>/doctrine_v^2.0.0/flow_v0.59.0 /** * This is an autogenerated libdef stub for: * * 'doctrine' * * Fill this stub out by replacing all the `any` types. * * Once filled out, we encourage you to share your work with the * community by sending a pull request to: * https://github.com/flowtype/flow-typed */ declare module 'doctrine' { declare module.exports: any; } /** * We include stubs for each file inside this npm package in case you need to * require those files directly. Feel free to delete any files that aren't * needed. */ declare module 'doctrine/lib/doctrine' { declare module.exports: any; } declare module 'doctrine/lib/typed' { declare module.exports: any; } declare module 'doctrine/lib/utility' { declare module.exports: any; } // Filename aliases declare module 'doctrine/lib/doctrine.js' { declare module.exports: $Exports<'doctrine/lib/doctrine'>; } declare module 'doctrine/lib/typed.js' { declare module.exports: $Exports<'doctrine/lib/typed'>; } declare module 'doctrine/lib/utility.js' { declare module.exports: $Exports<'doctrine/lib/utility'>; }
flow-typed/npm/doctrine_vx.x.x.js
0
https://github.com/mui/material-ui/commit/d03af40b8fa10d8848106b2df21b215c8c232e54
[ 0.00017600550199858844, 0.0001730531657813117, 0.00016429788956884295, 0.00017527783347759396, 0.000004416835508891381 ]
{ "id": 4, "code_window": [ " children: React.ReactNode;\n", " completed?: boolean;\n", " disabled?: boolean;\n", " icon?: Icon;\n", " last?: boolean;\n", " optional?: boolean;\n", " orientation?: Orientation;\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " icon?: StepButtonIcon;\n" ], "file_path": "src/Stepper/StepLabel.d.ts", "type": "replace", "edit_start_line_idx": 14 }
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; const SvgIconCustom = global.__MUI_SvgIcon__ || SvgIcon; let Headset = props => <SvgIconCustom {...props}> <path d="M12 1c-4.97 0-9 4.03-9 9v7c0 1.66 1.34 3 3 3h3v-8H5v-2c0-3.87 3.13-7 7-7s7 3.13 7 7v2h-4v8h3c1.66 0 3-1.34 3-3v-7c0-4.97-4.03-9-9-9z" /> </SvgIconCustom>; Headset = pure(Headset); Headset.muiName = 'SvgIcon'; export default Headset;
packages/material-ui-icons/src/Headset.js
0
https://github.com/mui/material-ui/commit/d03af40b8fa10d8848106b2df21b215c8c232e54
[ 0.00017958070384338498, 0.00017479444795753807, 0.00017000819207169116, 0.00017479444795753807, 0.000004786255885846913 ]
{ "id": 4, "code_window": [ " children: React.ReactNode;\n", " completed?: boolean;\n", " disabled?: boolean;\n", " icon?: Icon;\n", " last?: boolean;\n", " optional?: boolean;\n", " orientation?: Orientation;\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " icon?: StepButtonIcon;\n" ], "file_path": "src/Stepper/StepLabel.d.ts", "type": "replace", "edit_start_line_idx": 14 }
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; const SvgIconCustom = global.__MUI_SvgIcon__ || SvgIcon; let Error = props => <SvgIconCustom {...props}> <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-2h2v2zm0-4h-2V7h2v6z" /> </SvgIconCustom>; Error = pure(Error); Error.muiName = 'SvgIcon'; export default Error;
packages/material-ui-icons/src/Error.js
0
https://github.com/mui/material-ui/commit/d03af40b8fa10d8848106b2df21b215c8c232e54
[ 0.00018051202641800046, 0.00017365036183036864, 0.00016678869724273682, 0.00017365036183036864, 0.000006861664587631822 ]
{ "id": 0, "code_window": [ " @keydown.enter.exact=\"onNavigate(NavigateDir.NEXT, $event)\"\n", " @keydown.shift.enter.exact=\"onNavigate(NavigateDir.PREV, $event)\"\n", " >\n", " <template v-if=\"intersected\">\n", " <LazyVirtualCellLinks v-if=\"isLink(column)\" :readonly=\"isUnderLookup\" />\n", " <LazyVirtualCellHasMany v-else-if=\"isHm(column)\" />\n", " <LazyVirtualCellManyToMany v-else-if=\"isMm(column)\" />\n", " <LazyVirtualCellBelongsTo v-else-if=\"isBt(column)\" />\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " <LazyVirtualCellLinks v-if=\"isLink(column)\" />\n" ], "file_path": "packages/nc-gui/components/smartsheet/VirtualCell.vue", "type": "replace", "edit_start_line_idx": 103 }
<script setup lang="ts"> import { computed } from '@vue/reactivity' import type { ColumnType } from 'nocodb-sdk' import { ref } from 'vue' import type { Ref } from 'vue' import { ActiveCellInj, CellValueInj, ColumnInj, IsUnderLookupInj, inject, useSelectedCellKeyupListener } from '#imports' const props = defineProps<{ readonly: boolean }>() const value = inject(CellValueInj, ref(0)) const column = inject(ColumnInj)! const row = inject(RowInj)! const reloadRowTrigger = inject(ReloadRowDataHookInj, createEventHook()) const isForm = inject(IsFormInj) const _readOnly = inject(ReadonlyInj, ref(false)) const readOnly = computed(() => props.readonly || _readOnly.value) const isLocked = inject(IsLockedInj, ref(false)) const isUnderLookup = inject(IsUnderLookupInj, ref(false)) const colTitle = computed(() => column.value?.title || '') const listItemsDlg = ref(false) const childListDlg = ref(false) const { isUIAllowed } = useRoles() const { t } = useI18n() const { state, isNew } = useSmartsheetRowStoreOrThrow() const { relatedTableMeta, loadRelatedTableMeta, relatedTableDisplayValueProp } = useProvideLTARStore( column as Ref<Required<ColumnType>>, row, isNew, reloadRowTrigger.trigger, ) const relatedTableDisplayColumn = computed( () => relatedTableMeta.value?.columns?.find((c: any) => c.title === relatedTableDisplayValueProp.value) as ColumnType | undefined, ) loadRelatedTableMeta() const textVal = computed(() => { if (isForm?.value) { return state.value?.[colTitle.value]?.length ? `${+state.value?.[colTitle.value]?.length} ${t('msg.recordsLinked')}` : t('msg.noRecordsLinked') } const parsedValue = +value?.value || 0 if (!parsedValue) { return t('msg.noRecordsLinked') } else if (parsedValue === 1) { return `1 ${column.value?.meta?.singular || t('general.link')}` } else { return `${parsedValue} ${column.value?.meta?.plural || t('general.links')}` } }) const toatlRecordsLinked = computed(() => { if (isForm?.value) { return state.value?.[colTitle.value]?.length } return +value?.value || 0 }) const onAttachRecord = () => { childListDlg.value = false listItemsDlg.value = true } const openChildList = () => { if (readOnly.value) return if (!isLocked.value) { childListDlg.value = true } } useSelectedCellKeyupListener(inject(ActiveCellInj, ref(false)), (e: KeyboardEvent) => { switch (e.key) { case 'Enter': if (isLocked.value || listItemsDlg.value) return childListDlg.value = true e.stopPropagation() break } }) const localCellValue = computed<any[]>(() => { if (isNew.value) { return state?.value?.[column?.value.title as string] ?? [] } return [] }) const openListDlg = () => { if (readOnly.value) return listItemsDlg.value = true } </script> <template> <div class="flex w-full group items-center nc-links-wrapper" @dblclick.stop="openChildList"> <div class="block flex-shrink truncate"> <component :is="isLocked || isUnderLookup ? 'span' : 'a'" v-e="['c:cell:links:modal:open']" :title="textVal" class="text-center nc-datatype-link underline-transparent" :class="{ '!text-gray-300': !textVal }" @click.stop.prevent="openChildList" > {{ textVal }} </component> </div> <div class="flex-grow" /> <div v-if="!isLocked && !isUnderLookup" class="!xs:hidden flex justify-end hidden group-hover:flex items-center"> <MdiPlus v-if="(!readOnly && isUIAllowed('dataEdit')) || isForm" class="select-none !text-md text-gray-700 nc-action-icon nc-plus" @click.stop="openListDlg" /> </div> <LazyVirtualCellComponentsListItems v-if="listItemsDlg || childListDlg" v-model="listItemsDlg" :column="relatedTableDisplayColumn" /> <LazyVirtualCellComponentsListChildItems v-if="listItemsDlg || childListDlg" v-model="childListDlg" :items="toatlRecordsLinked" :column="relatedTableDisplayColumn" :cell-value="localCellValue" @attach-record="onAttachRecord" /> </div> </template>
packages/nc-gui/components/virtual-cell/Links.vue
1
https://github.com/nocodb/nocodb/commit/cfe6c234eee6067a01e9ccf6501d60f8a26513fd
[ 0.0018192745046690106, 0.00031256332295015454, 0.00016377422434743494, 0.00016879585746210068, 0.0004042962391395122 ]
{ "id": 0, "code_window": [ " @keydown.enter.exact=\"onNavigate(NavigateDir.NEXT, $event)\"\n", " @keydown.shift.enter.exact=\"onNavigate(NavigateDir.PREV, $event)\"\n", " >\n", " <template v-if=\"intersected\">\n", " <LazyVirtualCellLinks v-if=\"isLink(column)\" :readonly=\"isUnderLookup\" />\n", " <LazyVirtualCellHasMany v-else-if=\"isHm(column)\" />\n", " <LazyVirtualCellManyToMany v-else-if=\"isMm(column)\" />\n", " <LazyVirtualCellBelongsTo v-else-if=\"isBt(column)\" />\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " <LazyVirtualCellLinks v-if=\"isLink(column)\" />\n" ], "file_path": "packages/nc-gui/components/smartsheet/VirtualCell.vue", "type": "replace", "edit_start_line_idx": 103 }
import { RelationTypes, UITypes } from 'nocodb-sdk' import type { ColumnType, LinkToAnotherRecordType, TableType } from 'nocodb-sdk' import type { Row } from 'lib' import { isColumnRequiredAndNull } from './columnUtils' export const extractPkFromRow = (row: Record<string, any>, columns: ColumnType[]) => { if (!row || !columns) return null return columns .filter((c) => c.pk) .map((c) => row?.[c.title as string]) .join('___') } export const rowPkData = (row: Record<string, any>, columns: ColumnType[]) => { const pkData: Record<string, string> = {} const pks = columns?.filter((c) => c.pk) if (row && pks && pks.length) { for (const pk of pks) { if (pk.title) pkData[pk.title] = row[pk.title] } } return pkData } export const findIndexByPk = (pk: Record<string, string>, data: Row[]) => { for (const [i, row] of Object.entries(data)) { if (Object.keys(pk).every((k) => pk[k] === row.row[k])) { return parseInt(i) } } return -1 } // a function to populate insert object and verify if all required fields are present export async function populateInsertObject({ getMeta, row, meta, ltarState, throwError, undo = false, }: { meta: TableType ltarState: Record<string, any> getMeta: (tableIdOrTitle: string, force?: boolean) => Promise<TableType | null> row: Record<string, any> throwError?: boolean undo?: boolean }) { const missingRequiredColumns = new Set() const insertObj = await meta.columns?.reduce(async (_o: Promise<any>, col) => { const o = await _o // if column is BT relation then check if foreign key is not_null(required) if ( ltarState && col.uidt === UITypes.LinkToAnotherRecord && (<LinkToAnotherRecordType>col.colOptions).type === RelationTypes.BELONGS_TO ) { if (ltarState[col.title!]) { const colOpt = <LinkToAnotherRecordType>col.colOptions const childCol = meta.columns!.find((c) => colOpt.fk_child_column_id === c.id) const relatedTableMeta = (await getMeta(colOpt.fk_related_model_id!)) as TableType if (relatedTableMeta && childCol) { o[childCol.title!] = ltarState[col.title!][relatedTableMeta!.columns!.find((c) => c.id === colOpt.fk_parent_column_id)!.title!] missingRequiredColumns.delete(childCol.title) } } } // check all the required columns are not null if (isColumnRequiredAndNull(col, row)) { missingRequiredColumns.add(col.title) } if ((!col.ai || undo) && row?.[col.title as string] !== null) { o[col.title as string] = row?.[col.title as string] } return o }, Promise.resolve({})) if (throwError && missingRequiredColumns.size) { throw new Error(`Missing required columns: ${[...missingRequiredColumns].join(', ')}`) } return { missingRequiredColumns, insertObj } }
packages/nc-gui/utils/dataUtils.ts
0
https://github.com/nocodb/nocodb/commit/cfe6c234eee6067a01e9ccf6501d60f8a26513fd
[ 0.000176325993379578, 0.00017114677757490426, 0.0001660197740420699, 0.00017091627523768693, 0.0000033530786822666414 ]