hunk
dict
file
stringlengths
0
11.8M
file_path
stringlengths
2
234
label
int64
0
1
commit_url
stringlengths
74
103
dependency_score
sequencelengths
5
5
{ "id": 2, "code_window": [ "import parse from \"../../helpers/parse\";\n", "\n", "var context = {\n", " Transformer,\n", " Plugin,\n", " types,\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " messages,\n" ], "file_path": "src/babel/transformation/file/plugin-manager.js", "type": "add", "edit_start_line_idx": 7 }
{ "throws": "Line 2: \"MULTIPLIER\" is read-only" }
test/core/fixtures/transformation/errors/constants/options.json
0
https://github.com/babel/babel/commit/050bcec617117e21e240858edf310ff25bfa8d95
[ 0.00017459427181165665, 0.00017459427181165665, 0.00017459427181165665, 0.00017459427181165665, 0 ]
{ "id": 2, "code_window": [ "import parse from \"../../helpers/parse\";\n", "\n", "var context = {\n", " Transformer,\n", " Plugin,\n", " types,\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " messages,\n" ], "file_path": "src/babel/transformation/file/plugin-manager.js", "type": "add", "edit_start_line_idx": 7 }
debugger;
test/core/fixtures/generation/types/DebuggerStatement/expected.js
0
https://github.com/babel/babel/commit/050bcec617117e21e240858edf310ff25bfa8d95
[ 0.00017155910609290004, 0.00017155910609290004, 0.00017155910609290004, 0.00017155910609290004, 0 ]
{ "id": 3, "code_window": [ " types,\n", " parse,\n", " traverse\n", "};\n", "\n", "import * as messages from \"../../messages\";\n", "import * as util from \"../../util\";\n", "\n", "export default class PluginManager {\n", " static memoisedPlugins = [];\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/babel/transformation/file/plugin-manager.js", "type": "replace", "edit_start_line_idx": 14 }
import Transformer from "../transformer"; import Plugin from "../plugin"; import * as types from "../../types"; import traverse from "../../types"; import parse from "../../helpers/parse"; var context = { Transformer, Plugin, types, parse, traverse }; import * as messages from "../../messages"; import * as util from "../../util"; export default class PluginManager { static memoisedPlugins = []; static memoisePluginContainer(fn) { for (var i = 0; i < PluginManager.memoisedPlugins.length; i++) { var plugin = PluginManager.memoisedPlugins[i]; if (plugin.container === fn) return plugin.transformer; } var transformer = fn(context); PluginManager.memoisedPlugins.push({ container: fn, transformer: transformer }); return transformer; } static positions = ["before", "after"]; constructor({ file, transformers, before, after } = { transformers: {}, before: [], after: [] }) { this.transformers = transformers; this.file = file; this.before = before; this.after = after; } subnormaliseString(name, position) { // this is a plugin in the form of "foobar" or "foobar:after" // where the optional colon is the delimiter for plugin position in the transformer stack var match = name.match(/^(.*?):(after|before)$/); if (match) [, name, position] = match; var loc = util.resolveRelative(`babel-plugin-${name}`) || util.resolveRelative(name); if (loc) { var plugin = require(loc); return { position: position, plugin: plugin.default || plugin }; } else { throw new ReferenceError(messages.get("pluginUnknown", name)); } } validate(name, plugin) { // validate transformer key var key = plugin.key; if (this.transformers[key]) { throw new ReferenceError(messages.get("pluginKeyCollision", key)); } // validate Transformer instance if (!plugin.buildPass || plugin.constructor.name !== "Plugin") { throw new TypeError(messages.get("pluginNotTransformer", name)); } // register as a plugin plugin.metadata.plugin = true; } add(name) { var position; var plugin; if (name) { if (typeof name === "object" && name.transformer) { ({ transformer: plugin, position } = name); } else if (typeof name !== "string") { // not a string so we'll just assume that it's a direct Transformer instance, if not then // the checks later on will complain plugin = name; } if (typeof name === "string") { ({ plugin, position } = this.subnormaliseString(name, position)); } } else { throw new TypeError(messages.get("pluginIllegalKind", typeof name, name)); } // default position position = position || "before"; // validate position if (PluginManager.positions.indexOf(position) < 0) { throw new TypeError(messages.get("pluginIllegalPosition", position, name)); } // allow plugin containers to be specified so they don't have to manually require if (typeof plugin === "function") { plugin = PluginManager.memoisePluginContainer(plugin); } // this.validate(name, plugin); // build! var pass = this.transformers[plugin.key] = plugin.buildPass(this.file); if (pass.canTransform()) { var stack = position === "before" ? this.before : this.after; stack.push(pass); } } }
src/babel/transformation/file/plugin-manager.js
1
https://github.com/babel/babel/commit/050bcec617117e21e240858edf310ff25bfa8d95
[ 0.9990803003311157, 0.23090335726737976, 0.0001698945852695033, 0.00018796259246300906, 0.4204379618167877 ]
{ "id": 3, "code_window": [ " types,\n", " parse,\n", " traverse\n", "};\n", "\n", "import * as messages from \"../../messages\";\n", "import * as util from \"../../util\";\n", "\n", "export default class PluginManager {\n", " static memoisedPlugins = [];\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/babel/transformation/file/plugin-manager.js", "type": "replace", "edit_start_line_idx": 14 }
(function (left, right) { if (right != null && right[Symbol.hasInstance]) { return right[Symbol.hasInstance](left); } else { return left instanceof right; } });
src/babel/transformation/templates/helper-instanceof.js
0
https://github.com/babel/babel/commit/050bcec617117e21e240858edf310ff25bfa8d95
[ 0.00017492937331553549, 0.00017492937331553549, 0.00017492937331553549, 0.00017492937331553549, 0 ]
{ "id": 3, "code_window": [ " types,\n", " parse,\n", " traverse\n", "};\n", "\n", "import * as messages from \"../../messages\";\n", "import * as util from \"../../util\";\n", "\n", "export default class PluginManager {\n", " static memoisedPlugins = [];\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/babel/transformation/file/plugin-manager.js", "type": "replace", "edit_start_line_idx": 14 }
class Foo { @bar get foo() { } @foo set foo(bar) { } }
test/core/fixtures/transformation/es7.decorators/class-getter-and-setter/actual.js
0
https://github.com/babel/babel/commit/050bcec617117e21e240858edf310ff25bfa8d95
[ 0.00017459561058785766, 0.00017286348156630993, 0.00017113136709667742, 0.00017286348156630993, 0.0000017321217455901206 ]
{ "id": 3, "code_window": [ " types,\n", " parse,\n", " traverse\n", "};\n", "\n", "import * as messages from \"../../messages\";\n", "import * as util from \"../../util\";\n", "\n", "export default class PluginManager {\n", " static memoisedPlugins = [];\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/babel/transformation/file/plugin-manager.js", "type": "replace", "edit_start_line_idx": 14 }
import TraversalContext from "./context"; import * as visitors from "./visitors"; import * as messages from "../messages"; import includes from "lodash/collection/includes"; import * as t from "../types"; export default function traverse(parent, opts, scope, state, parentPath) { if (!parent) return; if (!opts.noScope && !scope) { if (parent.type !== "Program" && parent.type !== "File") { throw new Error(messages.get("traverseNeedsParent", parent.type)); } } if (!opts) opts = {}; visitors.explode(opts); // array of nodes if (Array.isArray(parent)) { for (var i = 0; i < parent.length; i++) { traverse.node(parent[i], opts, scope, state, parentPath); } } else { traverse.node(parent, opts, scope, state, parentPath); } } traverse.visitors = visitors; traverse.verify = visitors.verify; traverse.explode = visitors.explode; traverse.node = function (node, opts, scope, state, parentPath, skipKeys?) { var keys = t.VISITOR_KEYS[node.type]; if (!keys) return; var context = new TraversalContext(scope, opts, state, parentPath); for (var key of (keys: Array)) { if (skipKeys && skipKeys[key]) continue; if (context.visit(node, key)) return; } }; const CLEAR_KEYS = [ "trailingComments", "leadingComments", "extendedRange", "_scopeInfo", "_paths", "tokens", "range", "start", "end", "loc", "raw" ]; traverse.clearNode = function (node) { for (var i = 0; i < CLEAR_KEYS.length; i++) { let key = CLEAR_KEYS[i]; if (node[key] != null) node[key] = null; } }; var clearVisitor = { noScope: true, exit: traverse.clearNode }; traverse.removeProperties = function (tree) { traverse(tree, clearVisitor); traverse.clearNode(tree); return tree; }; function hasBlacklistedType(node, parent, scope, state) { if (node.type === state.type) { state.has = true; this.skip(); } } traverse.hasType = function (tree, scope, type, blacklistTypes) { // the node we're searching in is blacklisted if (includes(blacklistTypes, tree.type)) return false; // the type we're looking for is the same as the passed node if (tree.type === type) return true; var state = { has: false, type: type }; traverse(tree, { blacklist: blacklistTypes, enter: hasBlacklistedType }, scope, state); return state.has; };
src/babel/traversal/index.js
0
https://github.com/babel/babel/commit/050bcec617117e21e240858edf310ff25bfa8d95
[ 0.0029094284400343895, 0.0005661704344674945, 0.00016120389045681804, 0.0001851597335189581, 0.0008341055363416672 ]
{ "id": 0, "code_window": [ "import { AnchorAlignment } from 'vs/base/browser/ui/contextview/contextview';\n", "import { DropdownMenuActionViewItem } from 'vs/base/browser/ui/dropdown/dropdownActionViewItem';\n", "import { HistoryInputBox } from 'vs/base/browser/ui/inputbox/inputBox';\n", "import { Action, IAction, IActionRunner } from 'vs/base/common/actions';\n", "import { Delayer } from 'vs/base/common/async';\n", "import { Emitter, Event } from 'vs/base/common/event';\n", "import { KeyCode } from 'vs/base/common/keyCodes';\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "import { Action, IAction, IActionRunner, Separator } from 'vs/base/common/actions';\n" ], "file_path": "src/vs/workbench/contrib/testing/browser/testingExplorerFilter.ts", "type": "replace", "edit_start_line_idx": 11 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as dom from 'vs/base/browser/dom'; import { ActionBar } from 'vs/base/browser/ui/actionbar/actionbar'; import * as aria from 'vs/base/browser/ui/aria/aria'; import { IIdentityProvider, IKeyboardNavigationLabelProvider, IListVirtualDelegate } from 'vs/base/browser/ui/list/list'; import { DefaultKeyboardNavigationDelegate, IListAccessibilityProvider } from 'vs/base/browser/ui/list/listWidget'; import { ICompressedTreeNode } from 'vs/base/browser/ui/tree/compressedObjectTreeModel'; import { ObjectTree } from 'vs/base/browser/ui/tree/objectTree'; import { ITreeEvent, ITreeFilter, ITreeNode, ITreeRenderer, ITreeSorter, TreeFilterResult, TreeVisibility } from 'vs/base/browser/ui/tree/tree'; import { Action, IAction, IActionViewItem } from 'vs/base/common/actions'; import { DeferredPromise } from 'vs/base/common/async'; import { Color, RGBA } from 'vs/base/common/color'; import { throttle } from 'vs/base/common/decorators'; import { Event } from 'vs/base/common/event'; import { FuzzyScore } from 'vs/base/common/filters'; import { splitGlobAware } from 'vs/base/common/glob'; import { Iterable } from 'vs/base/common/iterator'; import { Disposable, DisposableStore, MutableDisposable, toDisposable } from 'vs/base/common/lifecycle'; import { URI } from 'vs/base/common/uri'; import 'vs/css!./media/testing'; import { ICodeEditor, isCodeEditor } from 'vs/editor/browser/editorBrowser'; import { ICodeEditorService } from 'vs/editor/browser/services/codeEditorService'; import { localize } from 'vs/nls'; import { MenuEntryActionViewItem } from 'vs/platform/actions/browser/menuEntryActionViewItem'; import { MenuItemAction } from 'vs/platform/actions/common/actions'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { IContextMenuService } from 'vs/platform/contextview/browser/contextView'; import { FileKind } from 'vs/platform/files/common/files'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { WorkbenchObjectTree } from 'vs/platform/list/browser/listService'; import { IOpenerService } from 'vs/platform/opener/common/opener'; import { IProgress, IProgressService, IProgressStep } from 'vs/platform/progress/common/progress'; import { IStorageService, StorageScope, StorageTarget } from 'vs/platform/storage/common/storage'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { foreground } from 'vs/platform/theme/common/colorRegistry'; import { IThemeService, registerThemingParticipant, ThemeIcon } from 'vs/platform/theme/common/themeService'; import { TestRunState } from 'vs/workbench/api/common/extHostTypes'; import { IResourceLabel, IResourceLabelOptions, IResourceLabelProps, ResourceLabels } from 'vs/workbench/browser/labels'; import { ViewPane } from 'vs/workbench/browser/parts/views/viewPane'; import { IViewletViewOptions } from 'vs/workbench/browser/parts/views/viewsViewlet'; import { IViewDescriptorService, ViewContainerLocation } from 'vs/workbench/common/views'; import { ITestTreeElement, ITestTreeProjection } from 'vs/workbench/contrib/testing/browser/explorerProjections'; import { HierarchicalByLocationProjection } from 'vs/workbench/contrib/testing/browser/explorerProjections/hierarchalByLocation'; import { HierarchicalByNameProjection } from 'vs/workbench/contrib/testing/browser/explorerProjections/hierarchalByName'; import { testingStatesToIcons } from 'vs/workbench/contrib/testing/browser/icons'; import { ITestExplorerFilterState, TestExplorerFilterState, TestingExplorerFilter } from 'vs/workbench/contrib/testing/browser/testingExplorerFilter'; import { ITestingPeekOpener, TestingOutputPeekController } from 'vs/workbench/contrib/testing/browser/testingOutputPeek'; import { TestExplorerViewMode, TestExplorerViewSorting, Testing, testStateNames } from 'vs/workbench/contrib/testing/common/constants'; import { TestingContextKeys } from 'vs/workbench/contrib/testing/common/testingContextKeys'; import { cmpPriority, isFailedState } from 'vs/workbench/contrib/testing/common/testingStates'; import { ITestResultService, sumCounts, TestStateCount } from 'vs/workbench/contrib/testing/common/testResultService'; import { ITestService } from 'vs/workbench/contrib/testing/common/testService'; import { IWorkspaceTestCollectionService, TestSubscriptionListener } from 'vs/workbench/contrib/testing/common/workspaceTestCollectionService'; import { IActivityService, NumberBadge, ProgressBadge } from 'vs/workbench/services/activity/common/activity'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { DebugAction, RunAction } from './testExplorerActions'; export class TestingExplorerView extends ViewPane { public viewModel!: TestingExplorerViewModel; private filterActionBar = this._register(new MutableDisposable()); private readonly currentSubscription = new MutableDisposable<TestSubscriptionListener>(); private container!: HTMLElement; private finishDiscovery?: () => void; private readonly location = TestingContextKeys.explorerLocation.bindTo(this.contextKeyService);; constructor( options: IViewletViewOptions, @IWorkspaceTestCollectionService private readonly testCollection: IWorkspaceTestCollectionService, @ITestService private readonly testService: ITestService, @IProgressService private readonly progress: IProgressService, @IContextMenuService contextMenuService: IContextMenuService, @IKeybindingService keybindingService: IKeybindingService, @IConfigurationService configurationService: IConfigurationService, @IInstantiationService instantiationService: IInstantiationService, @IViewDescriptorService viewDescriptorService: IViewDescriptorService, @IContextKeyService contextKeyService: IContextKeyService, @IOpenerService openerService: IOpenerService, @IThemeService themeService: IThemeService, @ITelemetryService telemetryService: ITelemetryService, ) { super(options, keybindingService, contextMenuService, configurationService, contextKeyService, viewDescriptorService, instantiationService, openerService, themeService, telemetryService); this._register(testService.onDidChangeProviders(() => this._onDidChangeViewWelcomeState.fire())); this.location.set(viewDescriptorService.getViewLocationById(Testing.ExplorerViewId) ?? ViewContainerLocation.Sidebar); } /** * @override */ public shouldShowWelcome() { return this.testService.providers === 0; } /** * @override */ protected renderBody(container: HTMLElement): void { super.renderBody(container); this.container = dom.append(container, dom.$('.test-explorer')); if (this.location.get() === ViewContainerLocation.Sidebar) { this.filterActionBar.value = this.createFilterActionBar(); } const messagesContainer = dom.append(this.container, dom.$('.test-explorer-messages')); this._register(this.instantiationService.createInstance(TestRunProgress, messagesContainer, this.getProgressLocation())); const listContainer = dom.append(this.container, dom.$('.test-explorer-tree')); this.viewModel = this.instantiationService.createInstance(TestingExplorerViewModel, listContainer, this.onDidChangeBodyVisibility, this.currentSubscription.value); this._register(this.viewModel); this._register(this.onDidChangeBodyVisibility(visible => { if (!visible && this.currentSubscription) { this.currentSubscription.value = undefined; this.viewModel.replaceSubscription(undefined); } else if (visible && !this.currentSubscription.value) { this.currentSubscription.value = this.createSubscription(); this.viewModel.replaceSubscription(this.currentSubscription.value); } })); } /** * @override */ public getActionViewItem(action: IAction): IActionViewItem | undefined { if (action.id === Testing.FilterActionId) { return this.instantiationService.createInstance(TestingExplorerFilter, action); } return super.getActionViewItem(action); } /** * @override */ public saveState() { super.saveState(); } private createFilterActionBar() { const bar = new ActionBar(this.container, { actionViewItemProvider: action => this.getActionViewItem(action) }); bar.push(new Action(Testing.FilterActionId)); bar.getContainer().classList.add('testing-filter-action-bar'); return bar; } private updateDiscoveryProgress(busy: number) { if (!busy && this.finishDiscovery) { this.finishDiscovery(); this.finishDiscovery = undefined; } else if (busy && !this.finishDiscovery) { const promise = new Promise<void>(resolve => { this.finishDiscovery = resolve; }); this.progress.withProgress({ location: this.getProgressLocation() }, () => promise); } } /** * @override */ protected layoutBody(height: number, width: number): void { super.layoutBody(height, width); this.container.style.height = `${height}px`; this.viewModel.layout(height, width); } private createSubscription() { const handle = this.testCollection.subscribeToWorkspaceTests(); handle.subscription.onBusyProvidersChange(() => this.updateDiscoveryProgress(handle.subscription.busyProviders)); return handle; } } export class TestingExplorerViewModel extends Disposable { public tree: ObjectTree<ITestTreeElement, FuzzyScore>; private filter: TestsFilter; public projection!: ITestTreeProjection; private readonly _viewMode = TestingContextKeys.viewMode.bindTo(this.contextKeyService); private readonly _viewSorting = TestingContextKeys.viewSorting.bindTo(this.contextKeyService); /** * Fires when the selected tests change. */ public readonly onDidChangeSelection: Event<ITreeEvent<ITestTreeElement | null>>; public get viewMode() { return this._viewMode.get() ?? TestExplorerViewMode.Tree; } public set viewMode(newMode: TestExplorerViewMode) { if (newMode === this._viewMode.get()) { return; } this._viewMode.set(newMode); this.updatePreferredProjection(); this.storageService.store('testing.viewMode', newMode, StorageScope.WORKSPACE, StorageTarget.USER); } public get viewSorting() { return this._viewSorting.get() ?? TestExplorerViewSorting.ByLocation; } public set viewSorting(newSorting: TestExplorerViewSorting) { if (newSorting === this._viewSorting.get()) { return; } this._viewSorting.set(newSorting); this.tree.resort(null); this.storageService.store('testing.viewSorting', newSorting, StorageScope.WORKSPACE, StorageTarget.USER); } constructor( listContainer: HTMLElement, onDidChangeVisibility: Event<boolean>, private listener: TestSubscriptionListener | undefined, @ITestExplorerFilterState filterState: TestExplorerFilterState, @IInstantiationService private readonly instantiationService: IInstantiationService, @IEditorService private readonly editorService: IEditorService, @IStorageService private readonly storageService: IStorageService, @IContextKeyService private readonly contextKeyService: IContextKeyService, @ITestResultService private readonly testResults: ITestResultService, @ITestingPeekOpener private readonly peekOpener: ITestingPeekOpener, ) { super(); this._viewMode.set(this.storageService.get('testing.viewMode', StorageScope.WORKSPACE, TestExplorerViewMode.Tree) as TestExplorerViewMode); this._viewSorting.set(this.storageService.get('testing.viewSorting', StorageScope.WORKSPACE, TestExplorerViewSorting.ByLocation) as TestExplorerViewSorting); const labels = this._register(instantiationService.createInstance(ResourceLabels, { onDidChangeVisibility: onDidChangeVisibility })); this.filter = this.instantiationService.createInstance(TestsFilter); this.tree = instantiationService.createInstance( WorkbenchObjectTree, 'Test Explorer List', listContainer, new ListDelegate(), [ instantiationService.createInstance(TestsRenderer, labels) ], { simpleKeyboardNavigation: true, identityProvider: instantiationService.createInstance(IdentityProvider), hideTwistiesOfChildlessElements: true, sorter: instantiationService.createInstance(TreeSorter, this), keyboardNavigationLabelProvider: instantiationService.createInstance(TreeKeyboardNavigationLabelProvider), accessibilityProvider: instantiationService.createInstance(ListAccessibilityProvider), filter: this.filter, }) as WorkbenchObjectTree<ITestTreeElement, FuzzyScore>; this._register(Event.any(filterState.currentDocumentOnly.onDidChange, filterState.text.onDidChange)(this.tree.refilter, this.tree)); this._register(editorService.onDidActiveEditorChange(() => { if (filterState.currentDocumentOnly.value && editorService.activeEditor?.resource) { if (this.projection.hasTestInDocument(editorService.activeEditor.resource)) { this.filter.filterToUri(editorService.activeEditor.resource); this.tree.refilter(); } } })); this._register(this.tree); this._register(dom.addStandardDisposableListener(this.tree.getHTMLElement(), 'keydown', evt => { if (DefaultKeyboardNavigationDelegate.mightProducePrintableCharacter(evt)) { filterState.text.value = evt.browserEvent.key; filterState.focusInput(); } })); this.updatePreferredProjection(); this.onDidChangeSelection = this.tree.onDidChangeSelection; this._register(this.tree.onDidChangeSelection(evt => { const selected = evt.elements[0]; if (selected && evt.browserEvent) { this.openEditorForItem(selected); } })); const tracker = this._register(this.instantiationService.createInstance(CodeEditorTracker, this)); this._register(onDidChangeVisibility(visible => { if (visible) { tracker.activate(); } else { tracker.deactivate(); } })); this._register(testResults.onResultsChanged(() => { this.tree.resort(null); })); } /** * Re-layout the tree. */ public layout(height: number, width: number): void { this.tree.layout(height, width); } /** * Replaces the test listener and recalculates the tree. */ public replaceSubscription(listener: TestSubscriptionListener | undefined) { this.listener = listener; this.updatePreferredProjection(); } /** * Reveals and moves focus to the item. */ public async revealItem(item: ITestTreeElement, reveal = true): Promise<void> { if (!this.tree.hasElement(item)) { return; } const chain: ITestTreeElement[] = []; for (let parent = item.parentItem; parent; parent = parent.parentItem) { chain.push(parent); } for (const parent of chain.reverse()) { try { this.tree.expand(parent); } catch { // ignore if not present } } if (reveal === true && this.tree.getRelativeTop(item) === null) { // Don't scroll to the item if it's already visible, or if set not to. this.tree.reveal(item, 0.5); } this.tree.setFocus([item]); this.tree.setSelection([item]); } /** * Collapse all items in the tree. */ public async collapseAll() { this.tree.collapseAll(); } /** * Opens an editor for the item. If there is a failure associated with the * test item, it will be shown. */ public async openEditorForItem(item: ITestTreeElement, preserveFocus = true) { if (await this.tryPeekError(item)) { return; } const location = item?.location; if (!location) { return; } const pane = await this.editorService.openEditor({ resource: location.uri, options: { selection: { startColumn: location.range.startColumn, startLineNumber: location.range.startLineNumber }, preserveFocus, }, }); // if the user selected a failed test and now they didn't, hide the peek const control = pane?.getControl(); if (isCodeEditor(control)) { TestingOutputPeekController.get(control).removePeek(); } } /** * Tries to peek the first test error, if the item is in a failed state. */ private async tryPeekError(item: ITestTreeElement) { const lookup = item.test && this.testResults.getStateByExtId(item.test.item.extId); return lookup && isFailedState(lookup[1].state.state) ? this.peekOpener.tryPeekFirstError(lookup[0], lookup[1], { preserveFocus: true }) : false; } private updatePreferredProjection() { this.projection?.dispose(); if (!this.listener) { this.tree.setChildren(null, []); return; } if (this._viewMode.get() === TestExplorerViewMode.List) { this.projection = this.instantiationService.createInstance(HierarchicalByNameProjection, this.listener); } else { this.projection = this.instantiationService.createInstance(HierarchicalByLocationProjection, this.listener); } this.projection.onUpdate(this.deferUpdate, this); this.projection.applyTo(this.tree); } @throttle(200) private deferUpdate() { this.projection.applyTo(this.tree); } /** * Gets the selected tests from the tree. */ public getSelectedTests() { return this.tree.getSelection(); } } class CodeEditorTracker { private store = new DisposableStore(); private lastRevealed?: ITestTreeElement; constructor( private readonly model: TestingExplorerViewModel, @ICodeEditorService private readonly codeEditorService: ICodeEditorService, ) { } public activate() { const editorStores = new Set<DisposableStore>(); this.store.add(toDisposable(() => { for (const store of editorStores) { store.dispose(); } })); const register = (editor: ICodeEditor) => { const store = new DisposableStore(); editorStores.add(store); store.add(editor.onDidChangeCursorPosition(evt => { const uri = editor.getModel()?.uri; if (!uri) { return; } const test = this.model.projection.getTestAtPosition(uri, evt.position); if (test && test !== this.lastRevealed) { this.model.revealItem(test); this.lastRevealed = test; } })); editor.onDidDispose(() => { store.dispose(); editorStores.delete(store); }); }; this.store.add(this.codeEditorService.onCodeEditorAdd(register)); this.codeEditorService.listCodeEditors().forEach(register); } public deactivate() { this.store.dispose(); this.store = new DisposableStore(); } public dispose() { this.store.dispose(); } } const enum FilterResult { Exclude, Inherit, Include, } class TestsFilter implements ITreeFilter<ITestTreeElement> { private lastText?: string; private filters: [include: boolean, value: string][] | undefined; private _filterToUri: string | undefined; constructor(@ITestExplorerFilterState private readonly state: ITestExplorerFilterState) { } /** * Parses and updates the tree filter. Supports lists of patterns that can be !negated. */ private setFilter(text: string) { this.lastText = text; text = text.trim(); if (!text) { this.filters = undefined; return; } this.filters = []; for (const filter of splitGlobAware(text, ',').map(s => s.trim()).filter(s => !!s.length)) { if (filter.startsWith('!')) { this.filters.push([false, filter.slice(1).toLowerCase()]); } else { this.filters.push([true, filter.toLowerCase()]); } } } public filterToUri(uri: URI) { this._filterToUri = uri.toString(); } /** * @inheritdoc */ public filter(element: ITestTreeElement): TreeFilterResult<void> { if (this.state.text.value !== this.lastText) { this.setFilter(this.state.text.value); } switch (Math.min(this.testFilterText(element), this.testLocation(element))) { case FilterResult.Exclude: return TreeVisibility.Hidden; case FilterResult.Include: return TreeVisibility.Visible; default: return TreeVisibility.Recurse; } } private testLocation(element: ITestTreeElement): FilterResult { if (!this._filterToUri || !this.state.currentDocumentOnly.value) { return FilterResult.Include; } for (let e: ITestTreeElement | null = element; e; e = e!.parentItem) { if (!e.location) { continue; } return e.location.uri.toString() === this._filterToUri ? FilterResult.Include : FilterResult.Exclude; } return FilterResult.Inherit; } private testFilterText(element: ITestTreeElement) { if (!this.filters) { return FilterResult.Include; } for (let e: ITestTreeElement | null = element; e; e = e.parentItem) { // start as included if the first glob is a negation let included = this.filters[0][0] === false ? FilterResult.Exclude : FilterResult.Inherit; const data = e.label.toLowerCase(); for (const [include, filter] of this.filters) { if (data.includes(filter)) { included = include ? FilterResult.Include : FilterResult.Exclude; } } if (included !== FilterResult.Inherit) { return included; } } return FilterResult.Inherit; } } class TreeSorter implements ITreeSorter<ITestTreeElement> { constructor(private readonly viewModel: TestingExplorerViewModel) { } public compare(a: ITestTreeElement, b: ITestTreeElement): number { let delta = cmpPriority(a.state, b.state); if (delta !== 0) { return delta; } if (this.viewModel.viewSorting === TestExplorerViewSorting.ByLocation && a.location && b.location && a.location.uri.toString() === b.location.uri.toString()) { delta = a.location.range.startLineNumber - b.location.range.startLineNumber; if (delta !== 0) { return delta; } } return a.label.localeCompare(b.label); } } class ListAccessibilityProvider implements IListAccessibilityProvider<ITestTreeElement> { getWidgetAriaLabel(): string { return localize('testExplorer', "Test Explorer"); } getAriaLabel(element: ITestTreeElement): string { let label = localize({ key: 'testing.treeElementLabel', comment: ['label then the unit tests state, for example "Addition Tests (Running)"'], }, '{0} ({1})', element.label, testStateNames[element.state]); if (element.retired) { label = localize({ key: 'testing.treeElementLabelOutdated', comment: ['{0} is the original label in testing.treeElementLabel'], }, '{0}, outdated result', label, testStateNames[element.state]); } return label; } } class TreeKeyboardNavigationLabelProvider implements IKeyboardNavigationLabelProvider<ITestTreeElement> { getKeyboardNavigationLabel(element: ITestTreeElement) { return element.label; } } class ListDelegate implements IListVirtualDelegate<ITestTreeElement> { getHeight(_element: ITestTreeElement) { return 22; } getTemplateId(_element: ITestTreeElement) { return TestsRenderer.ID; } } class IdentityProvider implements IIdentityProvider<ITestTreeElement> { public getId(element: ITestTreeElement) { return element.treeId; } } interface TestTemplateData { label: IResourceLabel; icon: HTMLElement; actionBar: ActionBar; } class TestsRenderer implements ITreeRenderer<ITestTreeElement, FuzzyScore, TestTemplateData> { public static readonly ID = 'testExplorer'; constructor( private labels: ResourceLabels, @IInstantiationService private readonly instantiationService: IInstantiationService ) { } renderCompressedElements(node: ITreeNode<ICompressedTreeNode<ITestTreeElement>, FuzzyScore>, index: number, templateData: TestTemplateData): void { const element = node.element.elements[node.element.elements.length - 1]; this.renderElementDirect(element, templateData); } get templateId(): string { return TestsRenderer.ID; } public renderTemplate(container: HTMLElement): TestTemplateData { const wrapper = dom.append(container, dom.$('.test-item')); const icon = dom.append(wrapper, dom.$('.computed-state')); const name = dom.append(wrapper, dom.$('.name')); const label = this.labels.create(name, { supportHighlights: true }); const actionBar = new ActionBar(wrapper, { actionViewItemProvider: action => action instanceof MenuItemAction ? this.instantiationService.createInstance(MenuEntryActionViewItem, action) : undefined }); return { label, actionBar, icon }; } public renderElement(node: ITreeNode<ITestTreeElement, FuzzyScore>, index: number, data: TestTemplateData): void { this.renderElementDirect(node.element, data); } private renderElementDirect(element: ITestTreeElement, data: TestTemplateData) { const label: IResourceLabelProps = { name: element.label }; const options: IResourceLabelOptions = {}; data.actionBar.clear(); const icon = testingStatesToIcons.get(element.state); data.icon.className = 'computed-state ' + (icon ? ThemeIcon.asClassName(icon) : ''); if (element.retired) { data.icon.className += ' retired'; } const test = element.test; if (test) { if (test.item.location) { label.resource = test.item.location.uri; } let title = element.label; for (let p = element.parentItem; p; p = p.parentItem) { title = `${p.label}, ${title}`; } options.title = title; options.fileKind = FileKind.FILE; label.description = element.description; } else { options.fileKind = FileKind.ROOT_FOLDER; } const running = element.state === TestRunState.Running; if (!Iterable.isEmpty(element.runnable)) { data.actionBar.push( this.instantiationService.createInstance(RunAction, element.runnable, running), { icon: true, label: false }, ); } if (!Iterable.isEmpty(element.debuggable)) { data.actionBar.push( this.instantiationService.createInstance(DebugAction, element.debuggable, running), { icon: true, label: false }, ); } data.label.setResource(label, options); } disposeTemplate(templateData: TestTemplateData): void { templateData.label.dispose(); templateData.actionBar.dispose(); } } type CountSummary = ReturnType<typeof collectCounts>; const collectCounts = (count: TestStateCount) => { const failed = count[TestRunState.Errored] + count[TestRunState.Failed]; const passed = count[TestRunState.Passed]; const skipped = count[TestRunState.Skipped]; return { passed, failed, runSoFar: passed + failed, totalWillBeRun: passed + failed + count[TestRunState.Queued] + count[TestRunState.Running], skipped, }; }; const getProgressText = ({ passed, runSoFar, skipped, failed }: CountSummary) => { let percent = passed / runSoFar * 100; if (failed > 0) { // fix: prevent from rounding to 100 if there's any failed test percent = Math.min(percent, 99.9); } if (skipped === 0) { return localize('testProgress', '{0}/{1} tests passed ({2}%)', passed, runSoFar, percent.toPrecision(3)); } else { return localize('testProgressWithSkip', '{0}/{1} tests passed ({2}%, {3} skipped)', passed, runSoFar, percent.toPrecision(3), skipped); } }; class TestRunProgress { private current?: { update: IProgress<IProgressStep>; deferred: DeferredPromise<void> }; private badge = new MutableDisposable(); private readonly resultLister = this.resultService.onResultsChanged(result => { if (!('started' in result)) { return; } this.updateProgress(); this.updateBadge(); result.started.onChange(this.throttledProgressUpdate, this); result.started.onComplete(() => { this.throttledProgressUpdate(); this.updateBadge(); }); }); constructor( private readonly messagesContainer: HTMLElement, private readonly location: string, @IProgressService private readonly progress: IProgressService, @ITestResultService private readonly resultService: ITestResultService, @IActivityService private readonly activityService: IActivityService, ) { } public dispose() { this.resultLister.dispose(); this.current?.deferred.complete(); this.badge.dispose(); } @throttle(200) private throttledProgressUpdate() { this.updateProgress(); } private updateProgress() { const running = this.resultService.results.filter(r => !r.isComplete); if (!running.length) { this.setIdleText(this.resultService.results[0]?.counts); this.current?.deferred.complete(); this.current = undefined; } else if (!this.current) { this.progress.withProgress({ location: this.location, total: 100 }, update => { this.current = { update, deferred: new DeferredPromise() }; this.updateProgress(); return this.current.deferred.p; }); } else { const counts = sumCounts(running.map(r => r.counts)); this.setRunningText(counts); const { runSoFar, totalWillBeRun } = collectCounts(counts); this.current.update.report({ increment: runSoFar, total: totalWillBeRun }); } } private setRunningText(counts: TestStateCount) { this.messagesContainer.dataset.state = 'running'; const collected = collectCounts(counts); if (collected.runSoFar === 0) { this.messagesContainer.innerText = localize('testResultStarting', 'Test run is starting...'); } else { this.messagesContainer.innerText = getProgressText(collected); } } private setIdleText(lastCount?: TestStateCount) { if (!lastCount) { this.messagesContainer.innerText = ''; } else { const collected = collectCounts(lastCount); this.messagesContainer.dataset.state = collected.failed ? 'failed' : 'running'; const doneMessage = getProgressText(collected); this.messagesContainer.innerText = doneMessage; aria.alert(doneMessage); } } private updateBadge() { this.badge.value = undefined; const result = this.resultService.results[0]; // currently running, or last run if (!result) { return; } if (!result.isComplete) { const badge = new ProgressBadge(() => localize('testBadgeRunning', 'Test run in progress')); this.badge.value = this.activityService.showViewActivity(Testing.ExplorerViewId, { badge, clazz: 'progress-badge' }); return; } const failures = result.counts[TestRunState.Failed] + result.counts[TestRunState.Errored]; if (failures === 0) { return; } const badge = new NumberBadge(failures, () => localize('testBadgeFailures', '{0} tests failed', failures)); this.badge.value = this.activityService.showViewActivity(Testing.ExplorerViewId, { badge }); } } registerThemingParticipant((theme, collector) => { if (theme.type === 'dark') { const foregroundColor = theme.getColor(foreground); if (foregroundColor) { const fgWithOpacity = new Color(new RGBA(foregroundColor.rgba.r, foregroundColor.rgba.g, foregroundColor.rgba.b, 0.65)); collector.addRule(`.test-explorer .test-explorer-messages { color: ${fgWithOpacity}; }`); } } });
src/vs/workbench/contrib/testing/browser/testingExplorerView.ts
1
https://github.com/microsoft/vscode/commit/07e3bcf7eacfb5a3f9c6e426fc977d176e40a726
[ 0.003355642082169652, 0.0002226004289695993, 0.0001637825189391151, 0.0001728861388983205, 0.00034212582977488637 ]
{ "id": 0, "code_window": [ "import { AnchorAlignment } from 'vs/base/browser/ui/contextview/contextview';\n", "import { DropdownMenuActionViewItem } from 'vs/base/browser/ui/dropdown/dropdownActionViewItem';\n", "import { HistoryInputBox } from 'vs/base/browser/ui/inputbox/inputBox';\n", "import { Action, IAction, IActionRunner } from 'vs/base/common/actions';\n", "import { Delayer } from 'vs/base/common/async';\n", "import { Emitter, Event } from 'vs/base/common/event';\n", "import { KeyCode } from 'vs/base/common/keyCodes';\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "import { Action, IAction, IActionRunner, Separator } from 'vs/base/common/actions';\n" ], "file_path": "src/vs/workbench/contrib/testing/browser/testingExplorerFilter.ts", "type": "replace", "edit_start_line_idx": 11 }
{ "name": "github", "displayName": "%displayName%", "description": "%description%", "publisher": "vscode", "license": "MIT", "version": "0.0.1", "engines": { "vscode": "^1.41.0" }, "enableProposedApi": true, "categories": [ "Other" ], "activationEvents": [ "*" ], "extensionDependencies": [ "vscode.git" ], "main": "./out/extension.js", "contributes": { "commands": [ { "command": "github.publish", "title": "Publish to GitHub" } ], "configuration": [ { "title": "GitHub", "properties": { "github.gitAuthentication": { "type": "boolean", "scope": "resource", "default": true, "description": "%config.gitAuthentication%" } } } ], "viewsWelcome": [ { "view": "scm", "contents": "%welcome.publishFolder%", "when": "config.git.enabled && git.state == initialized && workbenchState == folder" }, { "view": "scm", "contents": "%welcome.publishWorkspaceFolder%", "when": "config.git.enabled && git.state == initialized && workbenchState == workspace && workspaceFolderCount != 0" } ] }, "scripts": { "vscode:prepublish": "npm run compile", "compile": "gulp compile-extension:github", "watch": "gulp watch-extension:github" }, "dependencies": { "@octokit/rest": "^18.0.1", "tunnel": "^0.0.6", "vscode-nls": "^4.1.2" }, "devDependencies": { "@types/node": "^12.19.9" }, "repository": { "type": "git", "url": "https://github.com/microsoft/vscode.git" } }
extensions/github/package.json
0
https://github.com/microsoft/vscode/commit/07e3bcf7eacfb5a3f9c6e426fc977d176e40a726
[ 0.0001760081941029057, 0.00017313295393250883, 0.0001715787366265431, 0.000172715270309709, 0.0000013380458767642267 ]
{ "id": 0, "code_window": [ "import { AnchorAlignment } from 'vs/base/browser/ui/contextview/contextview';\n", "import { DropdownMenuActionViewItem } from 'vs/base/browser/ui/dropdown/dropdownActionViewItem';\n", "import { HistoryInputBox } from 'vs/base/browser/ui/inputbox/inputBox';\n", "import { Action, IAction, IActionRunner } from 'vs/base/common/actions';\n", "import { Delayer } from 'vs/base/common/async';\n", "import { Emitter, Event } from 'vs/base/common/event';\n", "import { KeyCode } from 'vs/base/common/keyCodes';\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "import { Action, IAction, IActionRunner, Separator } from 'vs/base/common/actions';\n" ], "file_path": "src/vs/workbench/contrib/testing/browser/testingExplorerFilter.ts", "type": "replace", "edit_start_line_idx": 11 }
# Gulp - Automate and enhance your workflow **Notice:** This extension is bundled with Visual Studio Code. It can be disabled but not uninstalled. ## Features This extension supports running [Gulp](https://gulpjs.com/) tasks defined in a `gulpfile.{js,ts}` file as [VS Code tasks](https://code.visualstudio.com/docs/editor/tasks). Gulp tasks with the name 'build', 'compile', or 'watch' are treated as build tasks. To run Gulp tasks, use the **Tasks** menu. ## Settings - `gulp.autoDetect` - Enable detecting tasks from `gulpfile.{js,ts}` files, the default is `on`.
extensions/gulp/README.md
0
https://github.com/microsoft/vscode/commit/07e3bcf7eacfb5a3f9c6e426fc977d176e40a726
[ 0.0001738271676003933, 0.00016882747877389193, 0.00016382780449930578, 0.00016882747877389193, 0.000004999681550543755 ]
{ "id": 0, "code_window": [ "import { AnchorAlignment } from 'vs/base/browser/ui/contextview/contextview';\n", "import { DropdownMenuActionViewItem } from 'vs/base/browser/ui/dropdown/dropdownActionViewItem';\n", "import { HistoryInputBox } from 'vs/base/browser/ui/inputbox/inputBox';\n", "import { Action, IAction, IActionRunner } from 'vs/base/common/actions';\n", "import { Delayer } from 'vs/base/common/async';\n", "import { Emitter, Event } from 'vs/base/common/event';\n", "import { KeyCode } from 'vs/base/common/keyCodes';\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "import { Action, IAction, IActionRunner, Separator } from 'vs/base/common/actions';\n" ], "file_path": "src/vs/workbench/contrib/testing/browser/testingExplorerFilter.ts", "type": "replace", "edit_start_line_idx": 11 }
# Emmet integration in Visual Studio Code **Notice:** This extension is bundled with Visual Studio Code. It can be disabled but not uninstalled. ## Features See [Emmet in Visual Studio Code](https://code.visualstudio.com/docs/editor/emmet) to learn about the features of this extension. Please read the [CONTRIBUTING.md](https://github.com/microsoft/vscode/blob/master/extensions/emmet/CONTRIBUTING.md) file to learn how to contribute to this extension.
extensions/emmet/README.md
0
https://github.com/microsoft/vscode/commit/07e3bcf7eacfb5a3f9c6e426fc977d176e40a726
[ 0.00016662782581988722, 0.00016662782581988722, 0.00016662782581988722, 0.00016662782581988722, 0 ]
{ "id": 1, "code_window": [ "import { attachInputBoxStyler } from 'vs/platform/theme/common/styler';\n", "import { IThemeService, ThemeIcon } from 'vs/platform/theme/common/themeService';\n", "import { ViewContainerLocation } from 'vs/workbench/common/views';\n", "import { testingFilterIcon } from 'vs/workbench/contrib/testing/browser/icons';\n", "import { Testing } from 'vs/workbench/contrib/testing/common/constants';\n", "import { ObservableValue } from 'vs/workbench/contrib/testing/common/observableValue';\n", "import { StoredValue } from 'vs/workbench/contrib/testing/common/storedValue';\n", "import { TestingContextKeys } from 'vs/workbench/contrib/testing/common/testingContextKeys';\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "import { TestExplorerStateFilter, Testing } from 'vs/workbench/contrib/testing/common/constants';\n" ], "file_path": "src/vs/workbench/contrib/testing/browser/testingExplorerFilter.ts", "type": "replace", "edit_start_line_idx": 26 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { localize } from 'vs/nls'; import { TestRunState } from 'vs/workbench/api/common/extHostTypes'; export const enum Testing { // marked as "extension" so that any existing test extensions are assigned to it. ViewletId = 'workbench.view.extension.test', ExplorerViewId = 'workbench.view.testing', OutputPeekContributionId = 'editor.contrib.testingOutputPeek', DecorationsContributionId = 'editor.contrib.testingDecorations', FilterActionId = 'workbench.actions.treeView.testExplorer.filter', } export const enum TestExplorerViewMode { List = 'list', Tree = 'true' } export const enum TestExplorerViewSorting { ByLocation = 'location', ByName = 'name', } export const testStateNames: { [K in TestRunState]: string } = { [TestRunState.Errored]: localize('testState.errored', 'Errored'), [TestRunState.Failed]: localize('testState.failed', 'Failed'), [TestRunState.Passed]: localize('testState.passed', 'Passed'), [TestRunState.Queued]: localize('testState.queued', 'Queued'), [TestRunState.Running]: localize('testState.running', 'Running'), [TestRunState.Skipped]: localize('testState.skipped', 'Skipped'), [TestRunState.Unset]: localize('testState.unset', 'Unset'), };
src/vs/workbench/contrib/testing/common/constants.ts
1
https://github.com/microsoft/vscode/commit/07e3bcf7eacfb5a3f9c6e426fc977d176e40a726
[ 0.0002339505881536752, 0.00018605028162710369, 0.00016789270739536732, 0.00017117889365181327, 0.000027765161576098762 ]
{ "id": 1, "code_window": [ "import { attachInputBoxStyler } from 'vs/platform/theme/common/styler';\n", "import { IThemeService, ThemeIcon } from 'vs/platform/theme/common/themeService';\n", "import { ViewContainerLocation } from 'vs/workbench/common/views';\n", "import { testingFilterIcon } from 'vs/workbench/contrib/testing/browser/icons';\n", "import { Testing } from 'vs/workbench/contrib/testing/common/constants';\n", "import { ObservableValue } from 'vs/workbench/contrib/testing/common/observableValue';\n", "import { StoredValue } from 'vs/workbench/contrib/testing/common/storedValue';\n", "import { TestingContextKeys } from 'vs/workbench/contrib/testing/common/testingContextKeys';\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "import { TestExplorerStateFilter, Testing } from 'vs/workbench/contrib/testing/common/constants';\n" ], "file_path": "src/vs/workbench/contrib/testing/browser/testingExplorerFilter.ts", "type": "replace", "edit_start_line_idx": 26 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { EditorInput, Verbosity, GroupIdentifier, IEditorInput, ISaveOptions, IRevertOptions, IEditorInputWithPreferredResource } from 'vs/workbench/common/editor'; import { URI } from 'vs/base/common/uri'; import { ITextFileService, ITextFileSaveOptions } from 'vs/workbench/services/textfile/common/textfiles'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService'; import { IFileService, FileSystemProviderCapabilities } from 'vs/platform/files/common/files'; import { ILabelService } from 'vs/platform/label/common/label'; import { IFilesConfigurationService, AutoSaveMode } from 'vs/workbench/services/filesConfiguration/common/filesConfigurationService'; import { Schemas } from 'vs/base/common/network'; import { dirname, isEqual } from 'vs/base/common/resources'; /** * The base class for all editor inputs that open in text editors. */ export abstract class AbstractTextResourceEditorInput extends EditorInput implements IEditorInputWithPreferredResource { private _preferredResource: URI; get preferredResource(): URI { return this._preferredResource; } constructor( public readonly resource: URI, preferredResource: URI | undefined, @IEditorService protected readonly editorService: IEditorService, @IEditorGroupsService protected readonly editorGroupService: IEditorGroupsService, @ITextFileService protected readonly textFileService: ITextFileService, @ILabelService protected readonly labelService: ILabelService, @IFileService protected readonly fileService: IFileService, @IFilesConfigurationService protected readonly filesConfigurationService: IFilesConfigurationService ) { super(); this._preferredResource = preferredResource || resource; this.registerListeners(); } protected registerListeners(): void { // Clear label memoizer on certain events that have impact this._register(this.labelService.onDidChangeFormatters(e => this.onLabelEvent(e.scheme))); this._register(this.fileService.onDidChangeFileSystemProviderRegistrations(e => this.onLabelEvent(e.scheme))); this._register(this.fileService.onDidChangeFileSystemProviderCapabilities(e => this.onLabelEvent(e.scheme))); } private onLabelEvent(scheme: string): void { if (scheme === this._preferredResource.scheme) { this.updateLabel(); } } private updateLabel(): void { // Clear any cached labels from before this._name = undefined; this._shortDescription = undefined; this._mediumDescription = undefined; this._longDescription = undefined; this._shortTitle = undefined; this._mediumTitle = undefined; this._longTitle = undefined; // Trigger recompute of label this._onDidChangeLabel.fire(); } setPreferredResource(preferredResource: URI): void { if (!isEqual(preferredResource, this._preferredResource)) { this._preferredResource = preferredResource; this.updateLabel(); } } private _name: string | undefined = undefined; getName(): string { if (typeof this._name !== 'string') { this._name = this.labelService.getUriBasenameLabel(this._preferredResource); } return this._name; } getDescription(verbosity: Verbosity = Verbosity.MEDIUM): string | undefined { switch (verbosity) { case Verbosity.SHORT: return this.shortDescription; case Verbosity.LONG: return this.longDescription; case Verbosity.MEDIUM: default: return this.mediumDescription; } } private _shortDescription: string | undefined = undefined; private get shortDescription(): string { if (typeof this._shortDescription !== 'string') { this._shortDescription = this.labelService.getUriBasenameLabel(dirname(this._preferredResource)); } return this._shortDescription; } private _mediumDescription: string | undefined = undefined; private get mediumDescription(): string { if (typeof this._mediumDescription !== 'string') { this._mediumDescription = this.labelService.getUriLabel(dirname(this._preferredResource), { relative: true }); } return this._mediumDescription; } private _longDescription: string | undefined = undefined; private get longDescription(): string { if (typeof this._longDescription !== 'string') { this._longDescription = this.labelService.getUriLabel(dirname(this._preferredResource)); } return this._longDescription; } private _shortTitle: string | undefined = undefined; private get shortTitle(): string { if (typeof this._shortTitle !== 'string') { this._shortTitle = this.getName(); } return this._shortTitle; } private _mediumTitle: string | undefined = undefined; private get mediumTitle(): string { if (typeof this._mediumTitle !== 'string') { this._mediumTitle = this.labelService.getUriLabel(this._preferredResource, { relative: true }); } return this._mediumTitle; } private _longTitle: string | undefined = undefined; private get longTitle(): string { if (typeof this._longTitle !== 'string') { this._longTitle = this.labelService.getUriLabel(this._preferredResource); } return this._longTitle; } getTitle(verbosity: Verbosity): string { switch (verbosity) { case Verbosity.SHORT: return this.shortTitle; case Verbosity.LONG: return this.longTitle; default: case Verbosity.MEDIUM: return this.mediumTitle; } } isUntitled(): boolean { // anyFile: is never untitled as it can be saved // untitled: is untitled by definition // anyOther: is untitled because it cannot be saved, as such we expect a "Save As" dialog return !this.fileService.canHandleResource(this.resource); } isReadonly(): boolean { if (this.isUntitled()) { return false; // untitled is never readonly } return this.fileService.hasCapability(this.resource, FileSystemProviderCapabilities.Readonly); } isSaving(): boolean { if (this.isUntitled()) { return false; // untitled is never saving automatically } if (this.filesConfigurationService.getAutoSaveMode() === AutoSaveMode.AFTER_SHORT_DELAY) { return true; // a short auto save is configured, treat this as being saved } return false; } save(group: GroupIdentifier, options?: ITextFileSaveOptions): Promise<IEditorInput | undefined> { // If this is neither an `untitled` resource, nor a resource // we can handle with the file service, we can only "Save As..." if (this.resource.scheme !== Schemas.untitled && !this.fileService.canHandleResource(this.resource)) { return this.saveAs(group, options); } // Normal save return this.doSave(options, false); } saveAs(group: GroupIdentifier, options?: ITextFileSaveOptions): Promise<IEditorInput | undefined> { return this.doSave(options, true); } private async doSave(options: ISaveOptions | undefined, saveAs: boolean): Promise<IEditorInput | undefined> { // Save / Save As let target: URI | undefined; if (saveAs) { target = await this.textFileService.saveAs(this.resource, undefined, { ...options, suggestedTarget: this.preferredResource }); } else { target = await this.textFileService.save(this.resource, options); } if (!target) { return undefined; // save cancelled } // If this save operation results in a new editor, either // because it was saved to disk (e.g. from untitled) or // through an explicit "Save As", make sure to replace it. if ( target.scheme !== this.resource.scheme || (saveAs && !isEqual(target, this.preferredResource)) ) { return this.editorService.createEditorInput({ resource: target }); } return this; } async revert(group: GroupIdentifier, options?: IRevertOptions): Promise<void> { await this.textFileService.revert(this.resource, options); } }
src/vs/workbench/common/editor/textResourceEditorInput.ts
0
https://github.com/microsoft/vscode/commit/07e3bcf7eacfb5a3f9c6e426fc977d176e40a726
[ 0.0001759612059686333, 0.00017232254322152585, 0.0001660565030761063, 0.00017265192582271993, 0.00000239433529714006 ]
{ "id": 1, "code_window": [ "import { attachInputBoxStyler } from 'vs/platform/theme/common/styler';\n", "import { IThemeService, ThemeIcon } from 'vs/platform/theme/common/themeService';\n", "import { ViewContainerLocation } from 'vs/workbench/common/views';\n", "import { testingFilterIcon } from 'vs/workbench/contrib/testing/browser/icons';\n", "import { Testing } from 'vs/workbench/contrib/testing/common/constants';\n", "import { ObservableValue } from 'vs/workbench/contrib/testing/common/observableValue';\n", "import { StoredValue } from 'vs/workbench/contrib/testing/common/storedValue';\n", "import { TestingContextKeys } from 'vs/workbench/contrib/testing/common/testingContextKeys';\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "import { TestExplorerStateFilter, Testing } from 'vs/workbench/contrib/testing/common/constants';\n" ], "file_path": "src/vs/workbench/contrib/testing/browser/testingExplorerFilter.ts", "type": "replace", "edit_start_line_idx": 26 }
<?xml version="1.0" encoding="UTF-8"?> <mime-info xmlns="http://www.freedesktop.org/standards/shared-mime-info"> <mime-type type="application/x-@@NAME@@-workspace"> <comment>@@NAME_LONG@@ Workspace</comment> <glob pattern="*.code-workspace"/> </mime-type> </mime-info>
resources/linux/code-workspace.xml
0
https://github.com/microsoft/vscode/commit/07e3bcf7eacfb5a3f9c6e426fc977d176e40a726
[ 0.00017119584663305432, 0.00017119584663305432, 0.00017119584663305432, 0.00017119584663305432, 0 ]
{ "id": 1, "code_window": [ "import { attachInputBoxStyler } from 'vs/platform/theme/common/styler';\n", "import { IThemeService, ThemeIcon } from 'vs/platform/theme/common/themeService';\n", "import { ViewContainerLocation } from 'vs/workbench/common/views';\n", "import { testingFilterIcon } from 'vs/workbench/contrib/testing/browser/icons';\n", "import { Testing } from 'vs/workbench/contrib/testing/common/constants';\n", "import { ObservableValue } from 'vs/workbench/contrib/testing/common/observableValue';\n", "import { StoredValue } from 'vs/workbench/contrib/testing/common/storedValue';\n", "import { TestingContextKeys } from 'vs/workbench/contrib/testing/common/testingContextKeys';\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "import { TestExplorerStateFilter, Testing } from 'vs/workbench/contrib/testing/common/constants';\n" ], "file_path": "src/vs/workbench/contrib/testing/browser/testingExplorerFilter.ts", "type": "replace", "edit_start_line_idx": 26 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ /*---------------------------------------------------------- The base color for this template is #5c87b2. If you'd like to use a different color start by replacing all instances of #5c87b2 with your new color. ----------------------------------------------------------*/ body { background-color: #5c87b2; font-size: .75em; font-family: Segoe UI, Verdana, Helvetica, Sans-Serif; margin: 8px; padding: 0; color: #696969; } h1, h2, h3, h4, h5, h6 { color: #000; font-size: 40px; margin: 0px; } textarea { font-family: Consolas } #results { margin-top: 2em; margin-left: 2em; color: black; font-size: medium; }
src/vs/platform/files/test/electron-browser/fixtures/resolver/site.css
0
https://github.com/microsoft/vscode/commit/07e3bcf7eacfb5a3f9c6e426fc977d176e40a726
[ 0.0001733387471176684, 0.00017166475299745798, 0.00016860371397342533, 0.00017231587844435126, 0.0000016944858316492173 ]
{ "id": 2, "code_window": [ "\t_serviceBrand: undefined;\n", "\treadonly text: ObservableValue<string>;\n", "\t/** Reveal request, the extId of the test to reveal */\n", "\treadonly reveal: ObservableValue<string | undefined>;\n", "\treadonly currentDocumentOnly: ObservableValue<boolean>;\n", "\n", "\treadonly onDidRequestInputFocus: Event<void>;\n", "\tfocusInput(): void;\n", "}\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\treadonly stateFilter: ObservableValue<TestExplorerStateFilter>;\n" ], "file_path": "src/vs/workbench/contrib/testing/browser/testingExplorerFilter.ts", "type": "add", "edit_start_line_idx": 36 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as dom from 'vs/base/browser/dom'; import { ActionBar } from 'vs/base/browser/ui/actionbar/actionbar'; import { BaseActionViewItem } from 'vs/base/browser/ui/actionbar/actionViewItems'; import { AnchorAlignment } from 'vs/base/browser/ui/contextview/contextview'; import { DropdownMenuActionViewItem } from 'vs/base/browser/ui/dropdown/dropdownActionViewItem'; import { HistoryInputBox } from 'vs/base/browser/ui/inputbox/inputBox'; import { Action, IAction, IActionRunner } from 'vs/base/common/actions'; import { Delayer } from 'vs/base/common/async'; import { Emitter, Event } from 'vs/base/common/event'; import { KeyCode } from 'vs/base/common/keyCodes'; import { localize } from 'vs/nls'; import { Action2, MenuId, registerAction2 } from 'vs/platform/actions/common/actions'; import { ContextScopedHistoryInputBox } from 'vs/platform/browser/contextScopedHistoryWidget'; import { ContextKeyEqualsExpr, ContextKeyExpr } from 'vs/platform/contextkey/common/contextkey'; import { IContextMenuService, IContextViewService } from 'vs/platform/contextview/browser/contextView'; import { createDecorator, IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IStorageService, StorageScope, StorageTarget } from 'vs/platform/storage/common/storage'; import { attachInputBoxStyler } from 'vs/platform/theme/common/styler'; import { IThemeService, ThemeIcon } from 'vs/platform/theme/common/themeService'; import { ViewContainerLocation } from 'vs/workbench/common/views'; import { testingFilterIcon } from 'vs/workbench/contrib/testing/browser/icons'; import { Testing } from 'vs/workbench/contrib/testing/common/constants'; import { ObservableValue } from 'vs/workbench/contrib/testing/common/observableValue'; import { StoredValue } from 'vs/workbench/contrib/testing/common/storedValue'; import { TestingContextKeys } from 'vs/workbench/contrib/testing/common/testingContextKeys'; export interface ITestExplorerFilterState { _serviceBrand: undefined; readonly text: ObservableValue<string>; /** Reveal request, the extId of the test to reveal */ readonly reveal: ObservableValue<string | undefined>; readonly currentDocumentOnly: ObservableValue<boolean>; readonly onDidRequestInputFocus: Event<void>; focusInput(): void; } export const ITestExplorerFilterState = createDecorator<ITestExplorerFilterState>('testingFilterState'); export class TestExplorerFilterState implements ITestExplorerFilterState { declare _serviceBrand: undefined; private readonly focusEmitter = new Emitter<void>(); public readonly text = new ObservableValue(''); public readonly currentDocumentOnly = ObservableValue.stored(new StoredValue<boolean>({ key: 'testsByCurrentDocumentOnly', scope: StorageScope.WORKSPACE, target: StorageTarget.USER }, this.storage), false); public readonly reveal = new ObservableValue<string | undefined>(undefined); public readonly onDidRequestInputFocus = this.focusEmitter.event; constructor(@IStorageService private readonly storage: IStorageService) { } public focusInput() { this.focusEmitter.fire(); } } export class TestingExplorerFilter extends BaseActionViewItem { private input!: HistoryInputBox; private readonly history: StoredValue<string[]> = this.instantiationService.createInstance(StoredValue, { key: 'testing.filterHistory', scope: StorageScope.WORKSPACE, target: StorageTarget.USER }); private readonly filtersAction = new Action('markersFiltersAction', localize('testing.filters.menu', "More Filters..."), 'testing-filter-button ' + ThemeIcon.asClassName(testingFilterIcon)); constructor( action: IAction, @ITestExplorerFilterState private readonly state: ITestExplorerFilterState, @IContextViewService private readonly contextViewService: IContextViewService, @IThemeService private readonly themeService: IThemeService, @IInstantiationService private readonly instantiationService: IInstantiationService, ) { super(null, action); this.updateFilterActiveState(); this._register(state.currentDocumentOnly.onDidChange(this.updateFilterActiveState, this)); } /** * @override */ public render(container: HTMLElement) { container.classList.add('testing-filter-action-item'); const updateDelayer = this._register(new Delayer<void>(400)); const wrapper = dom.$('.testing-filter-wrapper'); container.appendChild(wrapper); const input = this.input = this._register(this.instantiationService.createInstance(ContextScopedHistoryInputBox, wrapper, this.contextViewService, { placeholder: localize('testExplorerFilter', "Filter (e.g. text, !exclude)"), history: this.history.get([]), })); input.value = this.state.text.value; this._register(attachInputBoxStyler(input, this.themeService)); this._register(this.state.text.onDidChange(newValue => { input.value = newValue; })); this._register(this.state.onDidRequestInputFocus(() => { input.focus(); })); this._register(input.onDidChange(() => updateDelayer.trigger(() => { input.addToHistory(); this.state.text.value = input.value; }))); this._register(dom.addStandardDisposableListener(input.inputElement, dom.EventType.KEY_DOWN, e => { if (e.equals(KeyCode.Escape)) { input.value = ''; e.stopPropagation(); e.preventDefault(); } })); const actionbar = this._register(new ActionBar(container, { actionViewItemProvider: action => { if (action.id === this.filtersAction.id) { return this.instantiationService.createInstance(FiltersDropdownMenuActionViewItem, action, this.state, this.actionRunner); } return undefined; } })); actionbar.push(this.filtersAction, { icon: true, label: false }); } /** * Focuses the filter input. */ public focus(): void { this.input.focus(); } /** * Persists changes to the input history. */ public saveState() { const history = this.input.getHistory(); if (history.length) { this.history.store(history); } else { this.history.delete(); } } /** * @override */ public dispose() { this.saveState(); super.dispose(); } /** * Updates the 'checked' state of the filter submenu. */ private updateFilterActiveState() { this.filtersAction.checked = this.state.currentDocumentOnly.value; } } class FiltersDropdownMenuActionViewItem extends DropdownMenuActionViewItem { constructor( action: IAction, private readonly filters: ITestExplorerFilterState, actionRunner: IActionRunner, @IContextMenuService contextMenuService: IContextMenuService ) { super(action, { getActions: () => this.getActions() }, contextMenuService, { actionRunner, classNames: action.class, anchorAlignmentProvider: () => AnchorAlignment.RIGHT, menuAsChild: true } ); } render(container: HTMLElement): void { super.render(container); this.updateChecked(); } private getActions(): IAction[] { return [ { checked: this.filters.currentDocumentOnly.value, class: undefined, enabled: true, id: 'currentDocument', label: localize('testing.filters.currentFile', "Show in Active File Only"), run: async () => this.filters.currentDocumentOnly.value = !this.filters.currentDocumentOnly.value, tooltip: '', dispose: () => null }, ]; } updateChecked(): void { this.element!.classList.toggle('checked', this._action.checked); } } registerAction2(class extends Action2 { constructor() { super({ id: Testing.FilterActionId, title: localize('filter', "Filter"), menu: { id: MenuId.ViewTitle, when: ContextKeyExpr.and(ContextKeyEqualsExpr.create('view', Testing.ExplorerViewId), TestingContextKeys.explorerLocation.isEqualTo(ViewContainerLocation.Panel)), group: 'navigation', order: 1, }, }); } async run(): Promise<void> { } });
src/vs/workbench/contrib/testing/browser/testingExplorerFilter.ts
1
https://github.com/microsoft/vscode/commit/07e3bcf7eacfb5a3f9c6e426fc977d176e40a726
[ 0.9984531402587891, 0.2874978482723236, 0.00016217518714256585, 0.00017650212976150215, 0.4477404057979584 ]
{ "id": 2, "code_window": [ "\t_serviceBrand: undefined;\n", "\treadonly text: ObservableValue<string>;\n", "\t/** Reveal request, the extId of the test to reveal */\n", "\treadonly reveal: ObservableValue<string | undefined>;\n", "\treadonly currentDocumentOnly: ObservableValue<boolean>;\n", "\n", "\treadonly onDidRequestInputFocus: Event<void>;\n", "\tfocusInput(): void;\n", "}\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\treadonly stateFilter: ObservableValue<TestExplorerStateFilter>;\n" ], "file_path": "src/vs/workbench/contrib/testing/browser/testingExplorerFilter.ts", "type": "add", "edit_start_line_idx": 36 }
steps: - task: NodeTool@0 inputs: versionSpec: "12.18.3" - task: geeklearningio.gl-vsts-tasks-yarn.yarn-installer-task.YarnInstaller@2 inputs: versionSpec: "1.x" - task: UsePythonVersion@0 inputs: versionSpec: "2.x" addToPath: true - task: AzureKeyVault@1 displayName: "Azure Key Vault: Get Secrets" inputs: azureSubscription: "vscode-builds-subscription" KeyVaultName: vscode - task: DownloadPipelineArtifact@2 inputs: artifact: Compilation path: $(Build.ArtifactStagingDirectory) displayName: Download compilation output - powershell: | . build/azure-pipelines/win32/exec.ps1 $ErrorActionPreference = "Stop" exec { tar --force-local -xzf $(Build.ArtifactStagingDirectory)/compilation.tar.gz } displayName: Extract compilation output - powershell: | . build/azure-pipelines/win32/exec.ps1 $ErrorActionPreference = "Stop" "machine github.com`nlogin vscode`npassword $(github-distro-mixin-password)" | Out-File "$env:USERPROFILE\_netrc" -Encoding ASCII exec { git config user.email "[email protected]" } exec { git config user.name "VSCode" } displayName: Prepare tooling - powershell: | . build/azure-pipelines/win32/exec.ps1 $ErrorActionPreference = "Stop" exec { git pull --no-rebase https://github.com/$(VSCODE_MIXIN_REPO).git $(node -p "require('./package.json').distro") } displayName: Merge distro - powershell: | "$(VSCODE_ARCH)" | Out-File -Encoding ascii -NoNewLine .build\arch "$env:ENABLE_TERRAPIN" | Out-File -Encoding ascii -NoNewLine .build\terrapin node build/azure-pipelines/common/computeNodeModulesCacheKey.js > .build/yarnlockhash displayName: Prepare yarn cache flags - task: Cache@2 inputs: key: 'nodeModules | $(Agent.OS) | .build/arch, .build/terrapin, .build/yarnlockhash' path: .build/node_modules_cache cacheHitVar: NODE_MODULES_RESTORED displayName: Restore node_modules cache - powershell: | . build/azure-pipelines/win32/exec.ps1 $ErrorActionPreference = "Stop" exec { 7z.exe x .build/node_modules_cache/cache.7z -aos } condition: and(succeeded(), eq(variables.NODE_MODULES_RESTORED, 'true')) displayName: Extract node_modules cache - script: | npx https://aka.ms/enablesecurefeed standAlone timeoutInMinutes: 5 condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true'), eq(variables['ENABLE_TERRAPIN'], 'true')) displayName: Switch to Terrapin packages - powershell: | . build/azure-pipelines/win32/exec.ps1 . build/azure-pipelines/win32/retry.ps1 $ErrorActionPreference = "Stop" $env:npm_config_arch="$(VSCODE_ARCH)" $env:CHILD_CONCURRENCY="1" retry { exec { yarn --frozen-lockfile } } env: ELECTRON_SKIP_BINARY_DOWNLOAD: 1 PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: 1 displayName: Install dependencies condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) - powershell: | . build/azure-pipelines/win32/exec.ps1 $ErrorActionPreference = "Stop" exec { node build/azure-pipelines/common/listNodeModules.js .build/node_modules_list.txt } exec { mkdir -Force .build/node_modules_cache } exec { 7z.exe a .build/node_modules_cache/cache.7z -mx3 `@.build/node_modules_list.txt } condition: and(succeeded(), ne(variables.NODE_MODULES_RESTORED, 'true')) displayName: Create node_modules archive - powershell: | . build/azure-pipelines/win32/exec.ps1 $ErrorActionPreference = "Stop" exec { node build/azure-pipelines/mixin } displayName: Mix in quality - powershell: | . build/azure-pipelines/win32/exec.ps1 $ErrorActionPreference = "Stop" $env:VSCODE_MIXIN_PASSWORD="$(github-distro-mixin-password)" exec { yarn gulp "vscode-win32-$(VSCODE_ARCH)-min-ci" } echo "##vso[task.setvariable variable=CodeSigningFolderPath]$(agent.builddirectory)/VSCode-win32-$(VSCODE_ARCH)" displayName: Build - powershell: | . build/azure-pipelines/win32/exec.ps1 $ErrorActionPreference = "Stop" $env:VSCODE_MIXIN_PASSWORD="$(github-distro-mixin-password)" exec { yarn gulp "vscode-win32-$(VSCODE_ARCH)-code-helper" } exec { yarn gulp "vscode-win32-$(VSCODE_ARCH)-inno-updater" } displayName: Prepare Package condition: and(succeeded(), ne(variables['VSCODE_PUBLISH'], 'false')) - powershell: | . build/azure-pipelines/win32/exec.ps1 $ErrorActionPreference = "Stop" $env:VSCODE_MIXIN_PASSWORD="$(github-distro-mixin-password)" exec { yarn gulp "vscode-reh-win32-$(VSCODE_ARCH)-min-ci" } exec { yarn gulp "vscode-reh-web-win32-$(VSCODE_ARCH)-min-ci" } echo "##vso[task.setvariable variable=CodeSigningFolderPath]$(CodeSigningFolderPath),$(agent.builddirectory)/vscode-reh-win32-$(VSCODE_ARCH)" displayName: Build Server condition: and(succeeded(), ne(variables['VSCODE_ARCH'], 'arm64')) - powershell: | . build/azure-pipelines/win32/exec.ps1 $ErrorActionPreference = "Stop" $env:VSCODE_MIXIN_PASSWORD="$(github-distro-mixin-password)" exec { yarn npm-run-all -lp "electron $(VSCODE_ARCH)" "playwright-install" } displayName: Download Electron and Playwright condition: and(succeeded(), eq(variables['VSCODE_STEP_ON_IT'], 'false'), ne(variables['VSCODE_ARCH'], 'arm64')) - powershell: | . build/azure-pipelines/win32/exec.ps1 $ErrorActionPreference = "Stop" exec { yarn electron $(VSCODE_ARCH) } exec { .\scripts\test.bat --build --tfs "Unit Tests" } displayName: Run unit tests (Electron) timeoutInMinutes: 7 condition: and(succeeded(), eq(variables['VSCODE_STEP_ON_IT'], 'false'), ne(variables['VSCODE_ARCH'], 'arm64')) - powershell: | . build/azure-pipelines/win32/exec.ps1 $ErrorActionPreference = "Stop" exec { yarn test-browser --build --browser chromium --browser firefox --tfs "Browser Unit Tests" } displayName: Run unit tests (Browser) timeoutInMinutes: 7 condition: and(succeeded(), eq(variables['VSCODE_STEP_ON_IT'], 'false'), ne(variables['VSCODE_ARCH'], 'arm64')) - powershell: | . build/azure-pipelines/win32/exec.ps1 $ErrorActionPreference = "Stop" exec { yarn --cwd test/integration/browser compile } displayName: Compile integration tests condition: and(succeeded(), eq(variables['VSCODE_STEP_ON_IT'], 'false'), ne(variables['VSCODE_ARCH'], 'arm64')) - powershell: | # Figure out the full absolute path of the product we just built # including the remote server and configure the integration tests # to run with these builds instead of running out of sources. . build/azure-pipelines/win32/exec.ps1 $ErrorActionPreference = "Stop" $AppRoot = "$(agent.builddirectory)\VSCode-win32-$(VSCODE_ARCH)" $AppProductJson = Get-Content -Raw -Path "$AppRoot\resources\app\product.json" | ConvertFrom-Json $AppNameShort = $AppProductJson.nameShort exec { $env:INTEGRATION_TEST_ELECTRON_PATH = "$AppRoot\$AppNameShort.exe"; $env:VSCODE_REMOTE_SERVER_PATH = "$(agent.builddirectory)\vscode-reh-win32-$(VSCODE_ARCH)"; .\scripts\test-integration.bat --build --tfs "Integration Tests" } displayName: Run integration tests (Electron) timeoutInMinutes: 10 condition: and(succeeded(), eq(variables['VSCODE_STEP_ON_IT'], 'false'), ne(variables['VSCODE_ARCH'], 'arm64')) - powershell: | . build/azure-pipelines/win32/exec.ps1 $ErrorActionPreference = "Stop" exec { $env:VSCODE_REMOTE_SERVER_PATH = "$(agent.builddirectory)\vscode-reh-web-win32-$(VSCODE_ARCH)"; .\resources\server\test\test-web-integration.bat --browser firefox } displayName: Run integration tests (Browser) timeoutInMinutes: 7 condition: and(succeeded(), eq(variables['VSCODE_STEP_ON_IT'], 'false'), ne(variables['VSCODE_ARCH'], 'arm64')) - powershell: | . build/azure-pipelines/win32/exec.ps1 $ErrorActionPreference = "Stop" $AppRoot = "$(agent.builddirectory)\VSCode-win32-$(VSCODE_ARCH)" $AppProductJson = Get-Content -Raw -Path "$AppRoot\resources\app\product.json" | ConvertFrom-Json $AppNameShort = $AppProductJson.nameShort exec { $env:INTEGRATION_TEST_ELECTRON_PATH = "$AppRoot\$AppNameShort.exe"; $env:VSCODE_REMOTE_SERVER_PATH = "$(agent.builddirectory)\vscode-reh-win32-$(VSCODE_ARCH)"; .\resources\server\test\test-remote-integration.bat } displayName: Run remote integration tests (Electron) timeoutInMinutes: 7 condition: and(succeeded(), eq(variables['VSCODE_STEP_ON_IT'], 'false'), ne(variables['VSCODE_ARCH'], 'arm64')) - task: PublishPipelineArtifact@0 inputs: artifactName: crash-dump-windows-$(VSCODE_ARCH) targetPath: .build\crashes displayName: "Publish Crash Reports" continueOnError: true condition: failed() - task: PublishTestResults@2 displayName: Publish Tests Results inputs: testResultsFiles: "*-results.xml" searchFolder: "$(Build.ArtifactStagingDirectory)/test-results" condition: and(succeededOrFailed(), eq(variables['VSCODE_STEP_ON_IT'], 'false'), ne(variables['VSCODE_ARCH'], 'arm64')) - task: SFP.build-tasks.custom-build-task-1.EsrpCodeSigning@1 inputs: ConnectedServiceName: "ESRP CodeSign" FolderPath: "$(CodeSigningFolderPath)" Pattern: "*.dll,*.exe,*.node" signConfigType: inlineSignParams inlineOperation: | [ { "keyCode": "CP-230012", "operationSetCode": "SigntoolSign", "parameters": [ { "parameterName": "OpusName", "parameterValue": "VS Code" }, { "parameterName": "OpusInfo", "parameterValue": "https://code.visualstudio.com/" }, { "parameterName": "Append", "parameterValue": "/as" }, { "parameterName": "FileDigest", "parameterValue": "/fd \"SHA256\"" }, { "parameterName": "PageHash", "parameterValue": "/NPH" }, { "parameterName": "TimeStamp", "parameterValue": "/tr \"http://rfc3161.gtm.corp.microsoft.com/TSS/HttpTspServer\" /td sha256" } ], "toolName": "sign", "toolVersion": "1.0" }, { "keyCode": "CP-230012", "operationSetCode": "SigntoolVerify", "parameters": [ { "parameterName": "VerifyAll", "parameterValue": "/all" } ], "toolName": "sign", "toolVersion": "1.0" } ] SessionTimeout: 120 condition: and(succeeded(), ne(variables['VSCODE_PUBLISH'], 'false')) - task: NuGetCommand@2 displayName: Install ESRPClient.exe inputs: restoreSolution: 'build\azure-pipelines\win32\ESRPClient\packages.config' feedsToUse: config nugetConfigPath: 'build\azure-pipelines\win32\ESRPClient\NuGet.config' externalFeedCredentials: "ESRP Nuget" restoreDirectory: packages condition: and(succeeded(), ne(variables['VSCODE_PUBLISH'], 'false')) - task: ESRPImportCertTask@1 displayName: Import ESRP Request Signing Certificate inputs: ESRP: "ESRP CodeSign" condition: and(succeeded(), ne(variables['VSCODE_PUBLISH'], 'false')) - task: PowerShell@2 inputs: targetType: filePath filePath: .\build\azure-pipelines\win32\import-esrp-auth-cert.ps1 arguments: "$(ESRP-SSL-AADAuth)" displayName: Import ESRP Auth Certificate condition: and(succeeded(), ne(variables['VSCODE_PUBLISH'], 'false')) - powershell: | . build/azure-pipelines/win32/exec.ps1 $ErrorActionPreference = "Stop" $env:AZURE_STORAGE_ACCESS_KEY_2 = "$(vscode-storage-key)" $env:AZURE_DOCUMENTDB_MASTERKEY = "$(builds-docdb-key-readwrite)" $env:VSCODE_MIXIN_PASSWORD="$(github-distro-mixin-password)" .\build\azure-pipelines\win32\publish.ps1 displayName: Publish condition: and(succeeded(), ne(variables['VSCODE_PUBLISH'], 'false')) - publish: $(System.DefaultWorkingDirectory)\.build\win32-$(VSCODE_ARCH)\archive\VSCode-win32-$(VSCODE_ARCH).zip artifact: vscode-win32-$(VSCODE_ARCH) displayName: Publish archive condition: and(succeeded(), ne(variables['VSCODE_PUBLISH'], 'false')) - publish: $(System.DefaultWorkingDirectory)\.build\win32-$(VSCODE_ARCH)\system-setup\VSCodeSetup.exe artifact: vscode-win32-$(VSCODE_ARCH)-setup displayName: Publish system setup condition: and(succeeded(), ne(variables['VSCODE_PUBLISH'], 'false')) - publish: $(System.DefaultWorkingDirectory)\.build\win32-$(VSCODE_ARCH)\user-setup\VSCodeSetup.exe artifact: vscode-win32-$(VSCODE_ARCH)-user-setup displayName: Publish user setup condition: and(succeeded(), ne(variables['VSCODE_PUBLISH'], 'false')) - publish: $(System.DefaultWorkingDirectory)\.build\vscode-server-win32-$(VSCODE_ARCH).zip artifact: vscode-server-win32-$(VSCODE_ARCH) displayName: Publish server archive condition: and(succeeded(), ne(variables['VSCODE_PUBLISH'], 'false'), ne(variables['VSCODE_ARCH'], 'arm64')) - publish: $(System.DefaultWorkingDirectory)\.build\vscode-server-win32-$(VSCODE_ARCH)-web.zip artifact: vscode-server-win32-$(VSCODE_ARCH)-web displayName: Publish web server archive condition: and(succeeded(), ne(variables['VSCODE_PUBLISH'], 'false'), ne(variables['VSCODE_ARCH'], 'arm64')) - task: ms.vss-governance-buildtask.governance-build-task-component-detection.ComponentGovernanceComponentDetection@0 displayName: "Component Detection" continueOnError: true
build/azure-pipelines/win32/product-build-win32.yml
0
https://github.com/microsoft/vscode/commit/07e3bcf7eacfb5a3f9c6e426fc977d176e40a726
[ 0.00018124432244803756, 0.00017770596605259925, 0.00017211241356562823, 0.00017777546599972993, 0.0000020586480786732864 ]
{ "id": 2, "code_window": [ "\t_serviceBrand: undefined;\n", "\treadonly text: ObservableValue<string>;\n", "\t/** Reveal request, the extId of the test to reveal */\n", "\treadonly reveal: ObservableValue<string | undefined>;\n", "\treadonly currentDocumentOnly: ObservableValue<boolean>;\n", "\n", "\treadonly onDidRequestInputFocus: Event<void>;\n", "\tfocusInput(): void;\n", "}\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\treadonly stateFilter: ObservableValue<TestExplorerStateFilter>;\n" ], "file_path": "src/vs/workbench/contrib/testing/browser/testingExplorerFilter.ts", "type": "add", "edit_start_line_idx": 36 }
/*--------------------------------------------------------------------------------------------- * 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 { createDecorator, IInstantiationService, optional, ServicesAccessor } from 'vs/platform/instantiation/common/instantiation'; import { InstantiationService } from 'vs/platform/instantiation/common/instantiationService'; import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection'; import { SyncDescriptor } from 'vs/platform/instantiation/common/descriptors'; let IService1 = createDecorator<IService1>('service1'); interface IService1 { readonly _serviceBrand: undefined; c: number; } class Service1 implements IService1 { declare readonly _serviceBrand: undefined; c = 1; } let IService2 = createDecorator<IService2>('service2'); interface IService2 { readonly _serviceBrand: undefined; d: boolean; } class Service2 implements IService2 { declare readonly _serviceBrand: undefined; d = true; } let IService3 = createDecorator<IService3>('service3'); interface IService3 { readonly _serviceBrand: undefined; s: string; } class Service3 implements IService3 { declare readonly _serviceBrand: undefined; s = 'farboo'; } let IDependentService = createDecorator<IDependentService>('dependentService'); interface IDependentService { readonly _serviceBrand: undefined; name: string; } class DependentService implements IDependentService { declare readonly _serviceBrand: undefined; constructor(@IService1 service: IService1) { assert.equal(service.c, 1); } name = 'farboo'; } class Service1Consumer { constructor(@IService1 service1: IService1) { assert.ok(service1); assert.equal(service1.c, 1); } } class Target2Dep { constructor(@IService1 service1: IService1, @IService2 service2: Service2) { assert.ok(service1 instanceof Service1); assert.ok(service2 instanceof Service2); } } class TargetWithStaticParam { constructor(v: boolean, @IService1 service1: IService1) { assert.ok(v); assert.ok(service1); assert.equal(service1.c, 1); } } class TargetNotOptional { constructor(@IService1 service1: IService1, @IService2 service2: IService2) { } } class TargetOptional { constructor(@IService1 service1: IService1, @optional(IService2) service2: IService2) { assert.ok(service1); assert.equal(service1.c, 1); assert.ok(service2 === undefined); } } class DependentServiceTarget { constructor(@IDependentService d: IDependentService) { assert.ok(d); assert.equal(d.name, 'farboo'); } } class DependentServiceTarget2 { constructor(@IDependentService d: IDependentService, @IService1 s: IService1) { assert.ok(d); assert.equal(d.name, 'farboo'); assert.ok(s); assert.equal(s.c, 1); } } class ServiceLoop1 implements IService1 { declare readonly _serviceBrand: undefined; c = 1; constructor(@IService2 s: IService2) { } } class ServiceLoop2 implements IService2 { declare readonly _serviceBrand: undefined; d = true; constructor(@IService1 s: IService1) { } } suite('Instantiation Service', () => { test('service collection, cannot overwrite', function () { let collection = new ServiceCollection(); let result = collection.set(IService1, null!); assert.equal(result, undefined); result = collection.set(IService1, new Service1()); assert.equal(result, null); }); test('service collection, add/has', function () { let collection = new ServiceCollection(); collection.set(IService1, null!); assert.ok(collection.has(IService1)); collection.set(IService2, null!); assert.ok(collection.has(IService1)); assert.ok(collection.has(IService2)); }); test('@Param - simple clase', function () { let collection = new ServiceCollection(); let service = new InstantiationService(collection); collection.set(IService1, new Service1()); collection.set(IService2, new Service2()); collection.set(IService3, new Service3()); service.createInstance(Service1Consumer); }); test('@Param - fixed args', function () { let collection = new ServiceCollection(); let service = new InstantiationService(collection); collection.set(IService1, new Service1()); collection.set(IService2, new Service2()); collection.set(IService3, new Service3()); service.createInstance(TargetWithStaticParam, true); }); test('service collection is live', function () { let collection = new ServiceCollection(); collection.set(IService1, new Service1()); let service = new InstantiationService(collection); service.createInstance(Service1Consumer); // no IService2 assert.throws(() => service.createInstance(Target2Dep)); service.invokeFunction(function (a) { assert.ok(a.get(IService1)); assert.ok(!a.get(IService2, optional)); }); collection.set(IService2, new Service2()); service.createInstance(Target2Dep); service.invokeFunction(function (a) { assert.ok(a.get(IService1)); assert.ok(a.get(IService2)); }); }); test('@Param - optional', function () { let collection = new ServiceCollection([IService1, new Service1()]); let service = new InstantiationService(collection, true); service.createInstance(TargetOptional); assert.throws(() => service.createInstance(TargetNotOptional)); service = new InstantiationService(collection, false); service.createInstance(TargetOptional); service.createInstance(TargetNotOptional); }); // we made this a warning // test('@Param - too many args', function () { // let service = instantiationService.create(Object.create(null)); // service.addSingleton(IService1, new Service1()); // service.addSingleton(IService2, new Service2()); // service.addSingleton(IService3, new Service3()); // assert.throws(() => service.createInstance(ParameterTarget2, true, 2)); // }); // test('@Param - too few args', function () { // let service = instantiationService.create(Object.create(null)); // service.addSingleton(IService1, new Service1()); // service.addSingleton(IService2, new Service2()); // service.addSingleton(IService3, new Service3()); // assert.throws(() => service.createInstance(ParameterTarget2)); // }); test('SyncDesc - no dependencies', function () { let collection = new ServiceCollection(); let service = new InstantiationService(collection); collection.set(IService1, new SyncDescriptor<IService1>(Service1)); service.invokeFunction(accessor => { let service1 = accessor.get(IService1); assert.ok(service1); assert.equal(service1.c, 1); let service2 = accessor.get(IService1); assert.ok(service1 === service2); }); }); test('SyncDesc - service with service dependency', function () { let collection = new ServiceCollection(); let service = new InstantiationService(collection); collection.set(IService1, new SyncDescriptor<IService1>(Service1)); collection.set(IDependentService, new SyncDescriptor<IDependentService>(DependentService)); service.invokeFunction(accessor => { let d = accessor.get(IDependentService); assert.ok(d); assert.equal(d.name, 'farboo'); }); }); test('SyncDesc - target depends on service future', function () { let collection = new ServiceCollection(); let service = new InstantiationService(collection); collection.set(IService1, new SyncDescriptor<IService1>(Service1)); collection.set(IDependentService, new SyncDescriptor<IDependentService>(DependentService)); let d = service.createInstance(DependentServiceTarget); assert.ok(d instanceof DependentServiceTarget); let d2 = service.createInstance(DependentServiceTarget2); assert.ok(d2 instanceof DependentServiceTarget2); }); test('SyncDesc - explode on loop', function () { let collection = new ServiceCollection(); let service = new InstantiationService(collection); collection.set(IService1, new SyncDescriptor<IService1>(ServiceLoop1)); collection.set(IService2, new SyncDescriptor<IService2>(ServiceLoop2)); assert.throws(() => { service.invokeFunction(accessor => { accessor.get(IService1); }); }); assert.throws(() => { service.invokeFunction(accessor => { accessor.get(IService2); }); }); try { service.invokeFunction(accessor => { accessor.get(IService1); }); } catch (err) { assert.ok(err.name); assert.ok(err.message); } }); test('Invoke - get services', function () { let collection = new ServiceCollection(); let service = new InstantiationService(collection); collection.set(IService1, new Service1()); collection.set(IService2, new Service2()); function test(accessor: ServicesAccessor) { assert.ok(accessor.get(IService1) instanceof Service1); assert.equal(accessor.get(IService1).c, 1); return true; } assert.equal(service.invokeFunction(test), true); }); test('Invoke - get service, optional', function () { let collection = new ServiceCollection([IService1, new Service1()]); let service = new InstantiationService(collection); function test(accessor: ServicesAccessor) { assert.ok(accessor.get(IService1) instanceof Service1); assert.throws(() => accessor.get(IService2)); assert.equal(accessor.get(IService2, optional), undefined); return true; } assert.equal(service.invokeFunction(test), true); }); test('Invoke - keeping accessor NOT allowed', function () { let collection = new ServiceCollection(); let service = new InstantiationService(collection); collection.set(IService1, new Service1()); collection.set(IService2, new Service2()); let cached: ServicesAccessor; function test(accessor: ServicesAccessor) { assert.ok(accessor.get(IService1) instanceof Service1); assert.equal(accessor.get(IService1).c, 1); cached = accessor; return true; } assert.equal(service.invokeFunction(test), true); assert.throws(() => cached.get(IService2)); }); test('Invoke - throw error', function () { let collection = new ServiceCollection(); let service = new InstantiationService(collection); collection.set(IService1, new Service1()); collection.set(IService2, new Service2()); function test(accessor: ServicesAccessor) { throw new Error(); } assert.throws(() => service.invokeFunction(test)); }); test('Create child', function () { let serviceInstanceCount = 0; const CtorCounter = class implements Service1 { declare readonly _serviceBrand: undefined; c = 1; constructor() { serviceInstanceCount += 1; } }; // creating the service instance BEFORE the child service let service = new InstantiationService(new ServiceCollection([IService1, new SyncDescriptor(CtorCounter)])); service.createInstance(Service1Consumer); // second instance must be earlier ONE let child = service.createChild(new ServiceCollection([IService2, new Service2()])); child.createInstance(Service1Consumer); assert.equal(serviceInstanceCount, 1); // creating the service instance AFTER the child service serviceInstanceCount = 0; service = new InstantiationService(new ServiceCollection([IService1, new SyncDescriptor(CtorCounter)])); child = service.createChild(new ServiceCollection([IService2, new Service2()])); // second instance must be earlier ONE service.createInstance(Service1Consumer); child.createInstance(Service1Consumer); assert.equal(serviceInstanceCount, 1); }); test('Remote window / integration tests is broken #105562', function () { const Service1 = createDecorator<any>('service1'); class Service1Impl { constructor(@IInstantiationService insta: IInstantiationService) { const c = insta.invokeFunction(accessor => accessor.get(Service2)); // THIS is the recursive call assert.ok(c); } } const Service2 = createDecorator<any>('service2'); class Service2Impl { constructor() { } } // This service depends on Service1 and Service2 BUT creating Service1 creates Service2 (via recursive invocation) // and then Servce2 should not be created a second time const Service21 = createDecorator<any>('service21'); class Service21Impl { constructor(@Service2 readonly service2: Service2Impl, @Service1 readonly service1: Service1Impl) { } } const insta = new InstantiationService(new ServiceCollection( [Service1, new SyncDescriptor(Service1Impl)], [Service2, new SyncDescriptor(Service2Impl)], [Service21, new SyncDescriptor(Service21Impl)], )); const obj = insta.invokeFunction(accessor => accessor.get(Service21)); assert.ok(obj); }); });
src/vs/platform/instantiation/test/common/instantiationService.test.ts
0
https://github.com/microsoft/vscode/commit/07e3bcf7eacfb5a3f9c6e426fc977d176e40a726
[ 0.0006421816069632769, 0.00019606860587373376, 0.00016550546570215374, 0.00017660936282481998, 0.00007777214341331273 ]
{ "id": 2, "code_window": [ "\t_serviceBrand: undefined;\n", "\treadonly text: ObservableValue<string>;\n", "\t/** Reveal request, the extId of the test to reveal */\n", "\treadonly reveal: ObservableValue<string | undefined>;\n", "\treadonly currentDocumentOnly: ObservableValue<boolean>;\n", "\n", "\treadonly onDidRequestInputFocus: Event<void>;\n", "\tfocusInput(): void;\n", "}\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\treadonly stateFilter: ObservableValue<TestExplorerStateFilter>;\n" ], "file_path": "src/vs/workbench/contrib/testing/browser/testingExplorerFilter.ts", "type": "add", "edit_start_line_idx": 36 }
{ "name": "search-result", "displayName": "%displayName%", "description": "%description%", "version": "1.0.0", "enableProposedApi": true, "publisher": "vscode", "license": "MIT", "engines": { "vscode": "^1.39.0" }, "categories": [ "Programming Languages" ], "main": "./out/extension.js", "browser": "./dist/extension.js", "activationEvents": [ "onLanguage:search-result" ], "scripts": { "generate-grammar": "node ./syntaxes/generateTMLanguage.js", "vscode:prepublish": "node ../../node_modules/gulp/bin/gulp.js --gulpfile ../../build/gulpfile.extensions.js compile-extension:search-result ./tsconfig.json" }, "contributes": { "configurationDefaults": { "[search-result]": { "editor.lineNumbers": "off" } }, "languages": [ { "id": "search-result", "extensions": [ ".code-search" ], "aliases": [ "Search Result" ] } ], "grammars": [ { "language": "search-result", "scopeName": "text.searchResult", "path": "./syntaxes/searchResult.tmLanguage.json" } ] }, "repository": { "type": "git", "url": "https://github.com/microsoft/vscode.git" } }
extensions/search-result/package.json
0
https://github.com/microsoft/vscode/commit/07e3bcf7eacfb5a3f9c6e426fc977d176e40a726
[ 0.00018002834985964, 0.0001782213366823271, 0.00017545875743962824, 0.00017857921193353832, 0.0000015592293038935168 ]
{ "id": 3, "code_window": [ "\tdeclare _serviceBrand: undefined;\n", "\tprivate readonly focusEmitter = new Emitter<void>();\n", "\tpublic readonly text = new ObservableValue('');\n", "\tpublic readonly currentDocumentOnly = ObservableValue.stored(new StoredValue<boolean>({\n", "\t\tkey: 'testsByCurrentDocumentOnly',\n", "\t\tscope: StorageScope.WORKSPACE,\n", "\t\ttarget: StorageTarget.USER\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tpublic readonly stateFilter = ObservableValue.stored(new StoredValue<TestExplorerStateFilter>({\n", "\t\tkey: 'testStateFilter',\n", "\t\tscope: StorageScope.WORKSPACE,\n", "\t\ttarget: StorageTarget.USER\n", "\t}, this.storage), TestExplorerStateFilter.All);\n" ], "file_path": "src/vs/workbench/contrib/testing/browser/testingExplorerFilter.ts", "type": "add", "edit_start_line_idx": 48 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { localize } from 'vs/nls'; import { TestRunState } from 'vs/workbench/api/common/extHostTypes'; export const enum Testing { // marked as "extension" so that any existing test extensions are assigned to it. ViewletId = 'workbench.view.extension.test', ExplorerViewId = 'workbench.view.testing', OutputPeekContributionId = 'editor.contrib.testingOutputPeek', DecorationsContributionId = 'editor.contrib.testingDecorations', FilterActionId = 'workbench.actions.treeView.testExplorer.filter', } export const enum TestExplorerViewMode { List = 'list', Tree = 'true' } export const enum TestExplorerViewSorting { ByLocation = 'location', ByName = 'name', } export const testStateNames: { [K in TestRunState]: string } = { [TestRunState.Errored]: localize('testState.errored', 'Errored'), [TestRunState.Failed]: localize('testState.failed', 'Failed'), [TestRunState.Passed]: localize('testState.passed', 'Passed'), [TestRunState.Queued]: localize('testState.queued', 'Queued'), [TestRunState.Running]: localize('testState.running', 'Running'), [TestRunState.Skipped]: localize('testState.skipped', 'Skipped'), [TestRunState.Unset]: localize('testState.unset', 'Unset'), };
src/vs/workbench/contrib/testing/common/constants.ts
1
https://github.com/microsoft/vscode/commit/07e3bcf7eacfb5a3f9c6e426fc977d176e40a726
[ 0.00017801277863327414, 0.0001765317574609071, 0.00017491971084382385, 0.00017659725563134998, 0.0000011111794719909085 ]
{ "id": 3, "code_window": [ "\tdeclare _serviceBrand: undefined;\n", "\tprivate readonly focusEmitter = new Emitter<void>();\n", "\tpublic readonly text = new ObservableValue('');\n", "\tpublic readonly currentDocumentOnly = ObservableValue.stored(new StoredValue<boolean>({\n", "\t\tkey: 'testsByCurrentDocumentOnly',\n", "\t\tscope: StorageScope.WORKSPACE,\n", "\t\ttarget: StorageTarget.USER\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tpublic readonly stateFilter = ObservableValue.stored(new StoredValue<TestExplorerStateFilter>({\n", "\t\tkey: 'testStateFilter',\n", "\t\tscope: StorageScope.WORKSPACE,\n", "\t\ttarget: StorageTarget.USER\n", "\t}, this.storage), TestExplorerStateFilter.All);\n" ], "file_path": "src/vs/workbench/contrib/testing/browser/testingExplorerFilter.ts", "type": "add", "edit_start_line_idx": 48 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { IQuickPick, IQuickPickItem, IQuickNavigateConfiguration } from 'vs/platform/quickinput/common/quickInput'; import { CancellationToken } from 'vs/base/common/cancellation'; import { Registry } from 'vs/platform/registry/common/platform'; import { coalesce } from 'vs/base/common/arrays'; import { IDisposable, toDisposable } from 'vs/base/common/lifecycle'; import { ItemActivation } from 'vs/base/parts/quickinput/common/quickInput'; export interface IQuickAccessOptions { /** * Allows to enable quick navigate support in quick input. */ quickNavigateConfiguration?: IQuickNavigateConfiguration; /** * Allows to configure a different item activation strategy. * By default the first item in the list will get activated. */ itemActivation?: ItemActivation; /** * Whether to take the input value as is and not restore it * from any existing value if quick access is visible. */ preserveValue?: boolean; } export interface IQuickAccessController { /** * Open the quick access picker with the optional value prefilled. */ show(value?: string, options?: IQuickAccessOptions): void; } export enum DefaultQuickAccessFilterValue { /** * Keep the value as it is given to quick access. */ PRESERVE = 0, /** * Use the value that was used last time something was accepted from the picker. */ LAST = 1 } export interface IQuickAccessProvider { /** * Allows to set a default filter value when the provider opens. This can be: * - `undefined` to not specify any default value * - `DefaultFilterValues.PRESERVE` to use the value that was last typed * - `string` for the actual value to use * * Note: the default filter will only be used if quick access was opened with * the exact prefix of the provider. Otherwise the filter value is preserved. */ readonly defaultFilterValue?: string | DefaultQuickAccessFilterValue; /** * Called whenever a prefix was typed into quick pick that matches the provider. * * @param picker the picker to use for showing provider results. The picker is * automatically shown after the method returns, no need to call `show()`. * @param token providers have to check the cancellation token everytime after * a long running operation or from event handlers because it could be that the * picker has been closed or changed meanwhile. The token can be used to find out * that the picker was closed without picking an entry (e.g. was canceled by the user). * @return a disposable that will automatically be disposed when the picker * closes or is replaced by another picker. */ provide(picker: IQuickPick<IQuickPickItem>, token: CancellationToken): IDisposable; } export interface IQuickAccessProviderHelp { /** * The prefix to show for the help entry. If not provided, * the prefix used for registration will be taken. */ prefix?: string; /** * A description text to help understand the intent of the provider. */ description: string; /** * Separation between provider for editors and global ones. */ needsEditor: boolean; } export interface IQuickAccessProviderDescriptor { /** * The actual provider that will be instantiated as needed. */ readonly ctor: { new(...services: any /* TS BrandedService but no clue how to type this properly */[]): IQuickAccessProvider }; /** * The prefix for quick access picker to use the provider for. */ readonly prefix: string; /** * A placeholder to use for the input field when the provider is active. * This will also be read out by screen readers and thus helps for * accessibility. */ readonly placeholder?: string; /** * Documentation for the provider in the quick access help. */ readonly helpEntries: IQuickAccessProviderHelp[]; /** * A context key that will be set automatically when the * picker for the provider is showing. */ readonly contextKey?: string; } export const Extensions = { Quickaccess: 'workbench.contributions.quickaccess' }; export interface IQuickAccessRegistry { /** * Registers a quick access provider to the platform. */ registerQuickAccessProvider(provider: IQuickAccessProviderDescriptor): IDisposable; /** * Get all registered quick access providers. */ getQuickAccessProviders(): IQuickAccessProviderDescriptor[]; /** * Get a specific quick access provider for a given prefix. */ getQuickAccessProvider(prefix: string): IQuickAccessProviderDescriptor | undefined; } export class QuickAccessRegistry implements IQuickAccessRegistry { private providers: IQuickAccessProviderDescriptor[] = []; private defaultProvider: IQuickAccessProviderDescriptor | undefined = undefined; registerQuickAccessProvider(provider: IQuickAccessProviderDescriptor): IDisposable { // Extract the default provider when no prefix is present if (provider.prefix.length === 0) { this.defaultProvider = provider; } else { this.providers.push(provider); } // sort the providers by decreasing prefix length, such that longer // prefixes take priority: 'ext' vs 'ext install' - the latter should win this.providers.sort((providerA, providerB) => providerB.prefix.length - providerA.prefix.length); return toDisposable(() => { this.providers.splice(this.providers.indexOf(provider), 1); if (this.defaultProvider === provider) { this.defaultProvider = undefined; } }); } getQuickAccessProviders(): IQuickAccessProviderDescriptor[] { return coalesce([this.defaultProvider, ...this.providers]); } getQuickAccessProvider(prefix: string): IQuickAccessProviderDescriptor | undefined { const result = prefix ? (this.providers.find(provider => prefix.startsWith(provider.prefix)) || undefined) : undefined; return result || this.defaultProvider; } clear(): Function { const providers = [...this.providers]; const defaultProvider = this.defaultProvider; this.providers = []; this.defaultProvider = undefined; return () => { this.providers = providers; this.defaultProvider = defaultProvider; }; } } Registry.add(Extensions.Quickaccess, new QuickAccessRegistry());
src/vs/platform/quickinput/common/quickAccess.ts
0
https://github.com/microsoft/vscode/commit/07e3bcf7eacfb5a3f9c6e426fc977d176e40a726
[ 0.00017575145466253161, 0.00017029367154464126, 0.00016380359011236578, 0.0001701304572634399, 0.000003587040509955841 ]
{ "id": 3, "code_window": [ "\tdeclare _serviceBrand: undefined;\n", "\tprivate readonly focusEmitter = new Emitter<void>();\n", "\tpublic readonly text = new ObservableValue('');\n", "\tpublic readonly currentDocumentOnly = ObservableValue.stored(new StoredValue<boolean>({\n", "\t\tkey: 'testsByCurrentDocumentOnly',\n", "\t\tscope: StorageScope.WORKSPACE,\n", "\t\ttarget: StorageTarget.USER\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tpublic readonly stateFilter = ObservableValue.stored(new StoredValue<TestExplorerStateFilter>({\n", "\t\tkey: 'testStateFilter',\n", "\t\tscope: StorageScope.WORKSPACE,\n", "\t\ttarget: StorageTarget.USER\n", "\t}, this.storage), TestExplorerStateFilter.All);\n" ], "file_path": "src/vs/workbench/contrib/testing/browser/testingExplorerFilter.ts", "type": "add", "edit_start_line_idx": 48 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Event, Emitter } from 'vs/base/common/event'; import { Range, IRange } from 'vs/editor/common/core/range'; import { FoldingModel, CollapseMemento } from 'vs/editor/contrib/folding/foldingModel'; import { IDisposable } from 'vs/base/common/lifecycle'; import { Selection } from 'vs/editor/common/core/selection'; import { findFirstInSorted } from 'vs/base/common/arrays'; export class HiddenRangeModel { private readonly _foldingModel: FoldingModel; private _hiddenRanges: IRange[]; private _foldingModelListener: IDisposable | null; private readonly _updateEventEmitter = new Emitter<IRange[]>(); public get onDidChange(): Event<IRange[]> { return this._updateEventEmitter.event; } public get hiddenRanges() { return this._hiddenRanges; } public constructor(model: FoldingModel) { this._foldingModel = model; this._foldingModelListener = model.onDidChange(_ => this.updateHiddenRanges()); this._hiddenRanges = []; if (model.regions.length) { this.updateHiddenRanges(); } } private updateHiddenRanges(): void { let updateHiddenAreas = false; let newHiddenAreas: IRange[] = []; let i = 0; // index into hidden let k = 0; let lastCollapsedStart = Number.MAX_VALUE; let lastCollapsedEnd = -1; let ranges = this._foldingModel.regions; for (; i < ranges.length; i++) { if (!ranges.isCollapsed(i)) { continue; } let startLineNumber = ranges.getStartLineNumber(i) + 1; // the first line is not hidden let endLineNumber = ranges.getEndLineNumber(i); if (lastCollapsedStart <= startLineNumber && endLineNumber <= lastCollapsedEnd) { // ignore ranges contained in collapsed regions continue; } if (!updateHiddenAreas && k < this._hiddenRanges.length && this._hiddenRanges[k].startLineNumber === startLineNumber && this._hiddenRanges[k].endLineNumber === endLineNumber) { // reuse the old ranges newHiddenAreas.push(this._hiddenRanges[k]); k++; } else { updateHiddenAreas = true; newHiddenAreas.push(new Range(startLineNumber, 1, endLineNumber, 1)); } lastCollapsedStart = startLineNumber; lastCollapsedEnd = endLineNumber; } if (updateHiddenAreas || k < this._hiddenRanges.length) { this.applyHiddenRanges(newHiddenAreas); } } public applyMemento(state: CollapseMemento): boolean { if (!Array.isArray(state) || state.length === 0) { return false; } let hiddenRanges: IRange[] = []; for (let r of state) { if (!r.startLineNumber || !r.endLineNumber) { return false; } hiddenRanges.push(new Range(r.startLineNumber + 1, 1, r.endLineNumber, 1)); } this.applyHiddenRanges(hiddenRanges); return true; } /** * Collapse state memento, for persistence only, only used if folding model is not yet initialized */ public getMemento(): CollapseMemento { return this._hiddenRanges.map(r => ({ startLineNumber: r.startLineNumber - 1, endLineNumber: r.endLineNumber })); } private applyHiddenRanges(newHiddenAreas: IRange[]) { this._hiddenRanges = newHiddenAreas; this._updateEventEmitter.fire(newHiddenAreas); } public hasRanges() { return this._hiddenRanges.length > 0; } public isHidden(line: number): boolean { return findRange(this._hiddenRanges, line) !== null; } public adjustSelections(selections: Selection[]): boolean { let hasChanges = false; let editorModel = this._foldingModel.textModel; let lastRange: IRange | null = null; let adjustLine = (line: number) => { if (!lastRange || !isInside(line, lastRange)) { lastRange = findRange(this._hiddenRanges, line); } if (lastRange) { return lastRange.startLineNumber - 1; } return null; }; for (let i = 0, len = selections.length; i < len; i++) { let selection = selections[i]; let adjustedStartLine = adjustLine(selection.startLineNumber); if (adjustedStartLine) { selection = selection.setStartPosition(adjustedStartLine, editorModel.getLineMaxColumn(adjustedStartLine)); hasChanges = true; } let adjustedEndLine = adjustLine(selection.endLineNumber); if (adjustedEndLine) { selection = selection.setEndPosition(adjustedEndLine, editorModel.getLineMaxColumn(adjustedEndLine)); hasChanges = true; } selections[i] = selection; } return hasChanges; } public dispose() { if (this.hiddenRanges.length > 0) { this._hiddenRanges = []; this._updateEventEmitter.fire(this._hiddenRanges); } if (this._foldingModelListener) { this._foldingModelListener.dispose(); this._foldingModelListener = null; } } } function isInside(line: number, range: IRange) { return line >= range.startLineNumber && line <= range.endLineNumber; } function findRange(ranges: IRange[], line: number): IRange | null { let i = findFirstInSorted(ranges, r => line < r.startLineNumber) - 1; if (i >= 0 && ranges[i].endLineNumber >= line) { return ranges[i]; } return null; }
src/vs/editor/contrib/folding/hiddenRangeModel.ts
0
https://github.com/microsoft/vscode/commit/07e3bcf7eacfb5a3f9c6e426fc977d176e40a726
[ 0.00018787066801451147, 0.00017473805928602815, 0.00016698682156857103, 0.00017458302318118513, 0.000004554252427624306 ]
{ "id": 3, "code_window": [ "\tdeclare _serviceBrand: undefined;\n", "\tprivate readonly focusEmitter = new Emitter<void>();\n", "\tpublic readonly text = new ObservableValue('');\n", "\tpublic readonly currentDocumentOnly = ObservableValue.stored(new StoredValue<boolean>({\n", "\t\tkey: 'testsByCurrentDocumentOnly',\n", "\t\tscope: StorageScope.WORKSPACE,\n", "\t\ttarget: StorageTarget.USER\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tpublic readonly stateFilter = ObservableValue.stored(new StoredValue<TestExplorerStateFilter>({\n", "\t\tkey: 'testStateFilter',\n", "\t\tscope: StorageScope.WORKSPACE,\n", "\t\ttarget: StorageTarget.USER\n", "\t}, this.storage), TestExplorerStateFilter.All);\n" ], "file_path": "src/vs/workbench/contrib/testing/browser/testingExplorerFilter.ts", "type": "add", "edit_start_line_idx": 48 }
{ "registrations": [ { "component": { "type": "git", "git": { "name": "Colorsublime-Themes", "repositoryUrl": "https://github.com/Colorsublime/Colorsublime-Themes", "commitHash": "c10fdd8b144486b7a4f3cb4e2251c66df222a825" } }, "version": "0.1.0" } ], "version": 1 }
extensions/theme-red/cgmanifest.json
0
https://github.com/microsoft/vscode/commit/07e3bcf7eacfb5a3f9c6e426fc977d176e40a726
[ 0.0001782930630724877, 0.00017619496793486178, 0.00017409688734915107, 0.00017619496793486178, 0.0000020980878616683185 ]
{ "id": 4, "code_window": [ "\t) {\n", "\t\tsuper(null, action);\n", "\t\tthis.updateFilterActiveState();\n", "\t\tthis._register(state.currentDocumentOnly.onDidChange(this.updateFilterActiveState, this));\n", "\t}\n", "\n", "\t/**\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis._register(state.stateFilter.onDidChange(this.updateFilterActiveState, this));\n" ], "file_path": "src/vs/workbench/contrib/testing/browser/testingExplorerFilter.ts", "type": "add", "edit_start_line_idx": 85 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as dom from 'vs/base/browser/dom'; import { ActionBar } from 'vs/base/browser/ui/actionbar/actionbar'; import { BaseActionViewItem } from 'vs/base/browser/ui/actionbar/actionViewItems'; import { AnchorAlignment } from 'vs/base/browser/ui/contextview/contextview'; import { DropdownMenuActionViewItem } from 'vs/base/browser/ui/dropdown/dropdownActionViewItem'; import { HistoryInputBox } from 'vs/base/browser/ui/inputbox/inputBox'; import { Action, IAction, IActionRunner } from 'vs/base/common/actions'; import { Delayer } from 'vs/base/common/async'; import { Emitter, Event } from 'vs/base/common/event'; import { KeyCode } from 'vs/base/common/keyCodes'; import { localize } from 'vs/nls'; import { Action2, MenuId, registerAction2 } from 'vs/platform/actions/common/actions'; import { ContextScopedHistoryInputBox } from 'vs/platform/browser/contextScopedHistoryWidget'; import { ContextKeyEqualsExpr, ContextKeyExpr } from 'vs/platform/contextkey/common/contextkey'; import { IContextMenuService, IContextViewService } from 'vs/platform/contextview/browser/contextView'; import { createDecorator, IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IStorageService, StorageScope, StorageTarget } from 'vs/platform/storage/common/storage'; import { attachInputBoxStyler } from 'vs/platform/theme/common/styler'; import { IThemeService, ThemeIcon } from 'vs/platform/theme/common/themeService'; import { ViewContainerLocation } from 'vs/workbench/common/views'; import { testingFilterIcon } from 'vs/workbench/contrib/testing/browser/icons'; import { Testing } from 'vs/workbench/contrib/testing/common/constants'; import { ObservableValue } from 'vs/workbench/contrib/testing/common/observableValue'; import { StoredValue } from 'vs/workbench/contrib/testing/common/storedValue'; import { TestingContextKeys } from 'vs/workbench/contrib/testing/common/testingContextKeys'; export interface ITestExplorerFilterState { _serviceBrand: undefined; readonly text: ObservableValue<string>; /** Reveal request, the extId of the test to reveal */ readonly reveal: ObservableValue<string | undefined>; readonly currentDocumentOnly: ObservableValue<boolean>; readonly onDidRequestInputFocus: Event<void>; focusInput(): void; } export const ITestExplorerFilterState = createDecorator<ITestExplorerFilterState>('testingFilterState'); export class TestExplorerFilterState implements ITestExplorerFilterState { declare _serviceBrand: undefined; private readonly focusEmitter = new Emitter<void>(); public readonly text = new ObservableValue(''); public readonly currentDocumentOnly = ObservableValue.stored(new StoredValue<boolean>({ key: 'testsByCurrentDocumentOnly', scope: StorageScope.WORKSPACE, target: StorageTarget.USER }, this.storage), false); public readonly reveal = new ObservableValue<string | undefined>(undefined); public readonly onDidRequestInputFocus = this.focusEmitter.event; constructor(@IStorageService private readonly storage: IStorageService) { } public focusInput() { this.focusEmitter.fire(); } } export class TestingExplorerFilter extends BaseActionViewItem { private input!: HistoryInputBox; private readonly history: StoredValue<string[]> = this.instantiationService.createInstance(StoredValue, { key: 'testing.filterHistory', scope: StorageScope.WORKSPACE, target: StorageTarget.USER }); private readonly filtersAction = new Action('markersFiltersAction', localize('testing.filters.menu', "More Filters..."), 'testing-filter-button ' + ThemeIcon.asClassName(testingFilterIcon)); constructor( action: IAction, @ITestExplorerFilterState private readonly state: ITestExplorerFilterState, @IContextViewService private readonly contextViewService: IContextViewService, @IThemeService private readonly themeService: IThemeService, @IInstantiationService private readonly instantiationService: IInstantiationService, ) { super(null, action); this.updateFilterActiveState(); this._register(state.currentDocumentOnly.onDidChange(this.updateFilterActiveState, this)); } /** * @override */ public render(container: HTMLElement) { container.classList.add('testing-filter-action-item'); const updateDelayer = this._register(new Delayer<void>(400)); const wrapper = dom.$('.testing-filter-wrapper'); container.appendChild(wrapper); const input = this.input = this._register(this.instantiationService.createInstance(ContextScopedHistoryInputBox, wrapper, this.contextViewService, { placeholder: localize('testExplorerFilter', "Filter (e.g. text, !exclude)"), history: this.history.get([]), })); input.value = this.state.text.value; this._register(attachInputBoxStyler(input, this.themeService)); this._register(this.state.text.onDidChange(newValue => { input.value = newValue; })); this._register(this.state.onDidRequestInputFocus(() => { input.focus(); })); this._register(input.onDidChange(() => updateDelayer.trigger(() => { input.addToHistory(); this.state.text.value = input.value; }))); this._register(dom.addStandardDisposableListener(input.inputElement, dom.EventType.KEY_DOWN, e => { if (e.equals(KeyCode.Escape)) { input.value = ''; e.stopPropagation(); e.preventDefault(); } })); const actionbar = this._register(new ActionBar(container, { actionViewItemProvider: action => { if (action.id === this.filtersAction.id) { return this.instantiationService.createInstance(FiltersDropdownMenuActionViewItem, action, this.state, this.actionRunner); } return undefined; } })); actionbar.push(this.filtersAction, { icon: true, label: false }); } /** * Focuses the filter input. */ public focus(): void { this.input.focus(); } /** * Persists changes to the input history. */ public saveState() { const history = this.input.getHistory(); if (history.length) { this.history.store(history); } else { this.history.delete(); } } /** * @override */ public dispose() { this.saveState(); super.dispose(); } /** * Updates the 'checked' state of the filter submenu. */ private updateFilterActiveState() { this.filtersAction.checked = this.state.currentDocumentOnly.value; } } class FiltersDropdownMenuActionViewItem extends DropdownMenuActionViewItem { constructor( action: IAction, private readonly filters: ITestExplorerFilterState, actionRunner: IActionRunner, @IContextMenuService contextMenuService: IContextMenuService ) { super(action, { getActions: () => this.getActions() }, contextMenuService, { actionRunner, classNames: action.class, anchorAlignmentProvider: () => AnchorAlignment.RIGHT, menuAsChild: true } ); } render(container: HTMLElement): void { super.render(container); this.updateChecked(); } private getActions(): IAction[] { return [ { checked: this.filters.currentDocumentOnly.value, class: undefined, enabled: true, id: 'currentDocument', label: localize('testing.filters.currentFile', "Show in Active File Only"), run: async () => this.filters.currentDocumentOnly.value = !this.filters.currentDocumentOnly.value, tooltip: '', dispose: () => null }, ]; } updateChecked(): void { this.element!.classList.toggle('checked', this._action.checked); } } registerAction2(class extends Action2 { constructor() { super({ id: Testing.FilterActionId, title: localize('filter', "Filter"), menu: { id: MenuId.ViewTitle, when: ContextKeyExpr.and(ContextKeyEqualsExpr.create('view', Testing.ExplorerViewId), TestingContextKeys.explorerLocation.isEqualTo(ViewContainerLocation.Panel)), group: 'navigation', order: 1, }, }); } async run(): Promise<void> { } });
src/vs/workbench/contrib/testing/browser/testingExplorerFilter.ts
1
https://github.com/microsoft/vscode/commit/07e3bcf7eacfb5a3f9c6e426fc977d176e40a726
[ 0.7358824610710144, 0.03109189122915268, 0.0001568503794260323, 0.0001691650104476139, 0.14696073532104492 ]
{ "id": 4, "code_window": [ "\t) {\n", "\t\tsuper(null, action);\n", "\t\tthis.updateFilterActiveState();\n", "\t\tthis._register(state.currentDocumentOnly.onDidChange(this.updateFilterActiveState, this));\n", "\t}\n", "\n", "\t/**\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis._register(state.stateFilter.onDidChange(this.updateFilterActiveState, this));\n" ], "file_path": "src/vs/workbench/contrib/testing/browser/testingExplorerFilter.ts", "type": "add", "edit_start_line_idx": 85 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Registry } from 'vs/platform/registry/common/platform'; import { IViewlet } from 'vs/workbench/common/viewlet'; import { CompositeDescriptor, CompositeRegistry } from 'vs/workbench/browser/composite'; import { IConstructorSignature0, IInstantiationService, BrandedService } from 'vs/platform/instantiation/common/instantiation'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IWorkbenchLayoutService } from 'vs/workbench/services/layout/browser/layoutService'; import { IThemeService } from 'vs/platform/theme/common/themeService'; import { URI } from 'vs/base/common/uri'; import { IStorageService } from 'vs/platform/storage/common/storage'; import { IContextMenuService } from 'vs/platform/contextview/browser/contextView'; import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions'; import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { PaneComposite } from 'vs/workbench/browser/panecomposite'; export abstract class Viewlet extends PaneComposite implements IViewlet { constructor(id: string, @ITelemetryService telemetryService: ITelemetryService, @IStorageService protected storageService: IStorageService, @IInstantiationService protected instantiationService: IInstantiationService, @IThemeService themeService: IThemeService, @IContextMenuService protected contextMenuService: IContextMenuService, @IExtensionService protected extensionService: IExtensionService, @IWorkspaceContextService protected contextService: IWorkspaceContextService, @IWorkbenchLayoutService protected layoutService: IWorkbenchLayoutService, @IConfigurationService protected configurationService: IConfigurationService ) { super(id, telemetryService, storageService, instantiationService, themeService, contextMenuService, extensionService, contextService); } } /** * A viewlet descriptor is a leightweight descriptor of a viewlet in the workbench. */ export class ViewletDescriptor extends CompositeDescriptor<Viewlet> { static create<Services extends BrandedService[]>( ctor: { new(...services: Services): Viewlet }, id: string, name: string, cssClass?: string, order?: number, requestedIndex?: number, iconUrl?: URI ): ViewletDescriptor { return new ViewletDescriptor(ctor as IConstructorSignature0<Viewlet>, id, name, cssClass, order, requestedIndex, iconUrl); } private constructor( ctor: IConstructorSignature0<Viewlet>, id: string, name: string, cssClass?: string, order?: number, requestedIndex?: number, readonly iconUrl?: URI ) { super(ctor, id, name, cssClass, order, requestedIndex); } } export const Extensions = { Viewlets: 'workbench.contributions.viewlets' }; export class ViewletRegistry extends CompositeRegistry<Viewlet> { /** * Registers a viewlet to the platform. */ registerViewlet(descriptor: ViewletDescriptor): void { super.registerComposite(descriptor); } /** * Deregisters a viewlet to the platform. */ deregisterViewlet(id: string): void { super.deregisterComposite(id); } /** * Returns the viewlet descriptor for the given id or null if none. */ getViewlet(id: string): ViewletDescriptor { return this.getComposite(id) as ViewletDescriptor; } /** * Returns an array of registered viewlets known to the platform. */ getViewlets(): ViewletDescriptor[] { return this.getComposites() as ViewletDescriptor[]; } } Registry.add(Extensions.Viewlets, new ViewletRegistry());
src/vs/workbench/browser/viewlet.ts
0
https://github.com/microsoft/vscode/commit/07e3bcf7eacfb5a3f9c6e426fc977d176e40a726
[ 0.00017455847410019487, 0.000171816922375001, 0.00016412972763646394, 0.00017305139044765383, 0.0000034096399303962244 ]
{ "id": 4, "code_window": [ "\t) {\n", "\t\tsuper(null, action);\n", "\t\tthis.updateFilterActiveState();\n", "\t\tthis._register(state.currentDocumentOnly.onDidChange(this.updateFilterActiveState, this));\n", "\t}\n", "\n", "\t/**\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis._register(state.stateFilter.onDidChange(this.updateFilterActiveState, this));\n" ], "file_path": "src/vs/workbench/contrib/testing/browser/testingExplorerFilter.ts", "type": "add", "edit_start_line_idx": 85 }
/*--------------------------------------------------------------------------------------------- * 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 { LineDecoder } from 'vs/base/node/decoder'; suite('Decoder', () => { test('decoding', () => { const lineDecoder = new LineDecoder(); let res = lineDecoder.write(Buffer.from('hello')); assert.strictEqual(res.length, 0); res = lineDecoder.write(Buffer.from('\nworld')); assert.strictEqual(res[0], 'hello'); assert.strictEqual(res.length, 1); assert.strictEqual(lineDecoder.end(), 'world'); }); });
src/vs/base/test/node/decoder.test.ts
0
https://github.com/microsoft/vscode/commit/07e3bcf7eacfb5a3f9c6e426fc977d176e40a726
[ 0.0001777768338797614, 0.00017635147378314286, 0.0001755256816977635, 0.00017575193487573415, 0.000001012098550745577 ]
{ "id": 4, "code_window": [ "\t) {\n", "\t\tsuper(null, action);\n", "\t\tthis.updateFilterActiveState();\n", "\t\tthis._register(state.currentDocumentOnly.onDidChange(this.updateFilterActiveState, this));\n", "\t}\n", "\n", "\t/**\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis._register(state.stateFilter.onDidChange(this.updateFilterActiveState, this));\n" ], "file_path": "src/vs/workbench/contrib/testing/browser/testingExplorerFilter.ts", "type": "add", "edit_start_line_idx": 85 }
# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. # yarn lockfile v1
extensions/clojure/yarn.lock
0
https://github.com/microsoft/vscode/commit/07e3bcf7eacfb5a3f9c6e426fc977d176e40a726
[ 0.000172860745806247, 0.000172860745806247, 0.000172860745806247, 0.000172860745806247, 0 ]
{ "id": 5, "code_window": [ "\n", "\t/**\n", "\t * Updates the 'checked' state of the filter submenu.\n", "\t */\n", "\tprivate updateFilterActiveState() {\n", "\t\tthis.filtersAction.checked = this.state.currentDocumentOnly.value;\n", "\t}\n", "}\n", "\n", "\n", "class FiltersDropdownMenuActionViewItem extends DropdownMenuActionViewItem {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis.filtersAction.checked = this.state.currentDocumentOnly.value\n", "\t\t\t|| this.state.stateFilter.value !== TestExplorerStateFilter.All;\n" ], "file_path": "src/vs/workbench/contrib/testing/browser/testingExplorerFilter.ts", "type": "replace", "edit_start_line_idx": 168 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as dom from 'vs/base/browser/dom'; import { ActionBar } from 'vs/base/browser/ui/actionbar/actionbar'; import * as aria from 'vs/base/browser/ui/aria/aria'; import { IIdentityProvider, IKeyboardNavigationLabelProvider, IListVirtualDelegate } from 'vs/base/browser/ui/list/list'; import { DefaultKeyboardNavigationDelegate, IListAccessibilityProvider } from 'vs/base/browser/ui/list/listWidget'; import { ICompressedTreeNode } from 'vs/base/browser/ui/tree/compressedObjectTreeModel'; import { ObjectTree } from 'vs/base/browser/ui/tree/objectTree'; import { ITreeEvent, ITreeFilter, ITreeNode, ITreeRenderer, ITreeSorter, TreeFilterResult, TreeVisibility } from 'vs/base/browser/ui/tree/tree'; import { Action, IAction, IActionViewItem } from 'vs/base/common/actions'; import { DeferredPromise } from 'vs/base/common/async'; import { Color, RGBA } from 'vs/base/common/color'; import { throttle } from 'vs/base/common/decorators'; import { Event } from 'vs/base/common/event'; import { FuzzyScore } from 'vs/base/common/filters'; import { splitGlobAware } from 'vs/base/common/glob'; import { Iterable } from 'vs/base/common/iterator'; import { Disposable, DisposableStore, MutableDisposable, toDisposable } from 'vs/base/common/lifecycle'; import { URI } from 'vs/base/common/uri'; import 'vs/css!./media/testing'; import { ICodeEditor, isCodeEditor } from 'vs/editor/browser/editorBrowser'; import { ICodeEditorService } from 'vs/editor/browser/services/codeEditorService'; import { localize } from 'vs/nls'; import { MenuEntryActionViewItem } from 'vs/platform/actions/browser/menuEntryActionViewItem'; import { MenuItemAction } from 'vs/platform/actions/common/actions'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { IContextMenuService } from 'vs/platform/contextview/browser/contextView'; import { FileKind } from 'vs/platform/files/common/files'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { WorkbenchObjectTree } from 'vs/platform/list/browser/listService'; import { IOpenerService } from 'vs/platform/opener/common/opener'; import { IProgress, IProgressService, IProgressStep } from 'vs/platform/progress/common/progress'; import { IStorageService, StorageScope, StorageTarget } from 'vs/platform/storage/common/storage'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { foreground } from 'vs/platform/theme/common/colorRegistry'; import { IThemeService, registerThemingParticipant, ThemeIcon } from 'vs/platform/theme/common/themeService'; import { TestRunState } from 'vs/workbench/api/common/extHostTypes'; import { IResourceLabel, IResourceLabelOptions, IResourceLabelProps, ResourceLabels } from 'vs/workbench/browser/labels'; import { ViewPane } from 'vs/workbench/browser/parts/views/viewPane'; import { IViewletViewOptions } from 'vs/workbench/browser/parts/views/viewsViewlet'; import { IViewDescriptorService, ViewContainerLocation } from 'vs/workbench/common/views'; import { ITestTreeElement, ITestTreeProjection } from 'vs/workbench/contrib/testing/browser/explorerProjections'; import { HierarchicalByLocationProjection } from 'vs/workbench/contrib/testing/browser/explorerProjections/hierarchalByLocation'; import { HierarchicalByNameProjection } from 'vs/workbench/contrib/testing/browser/explorerProjections/hierarchalByName'; import { testingStatesToIcons } from 'vs/workbench/contrib/testing/browser/icons'; import { ITestExplorerFilterState, TestExplorerFilterState, TestingExplorerFilter } from 'vs/workbench/contrib/testing/browser/testingExplorerFilter'; import { ITestingPeekOpener, TestingOutputPeekController } from 'vs/workbench/contrib/testing/browser/testingOutputPeek'; import { TestExplorerViewMode, TestExplorerViewSorting, Testing, testStateNames } from 'vs/workbench/contrib/testing/common/constants'; import { TestingContextKeys } from 'vs/workbench/contrib/testing/common/testingContextKeys'; import { cmpPriority, isFailedState } from 'vs/workbench/contrib/testing/common/testingStates'; import { ITestResultService, sumCounts, TestStateCount } from 'vs/workbench/contrib/testing/common/testResultService'; import { ITestService } from 'vs/workbench/contrib/testing/common/testService'; import { IWorkspaceTestCollectionService, TestSubscriptionListener } from 'vs/workbench/contrib/testing/common/workspaceTestCollectionService'; import { IActivityService, NumberBadge, ProgressBadge } from 'vs/workbench/services/activity/common/activity'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { DebugAction, RunAction } from './testExplorerActions'; export class TestingExplorerView extends ViewPane { public viewModel!: TestingExplorerViewModel; private filterActionBar = this._register(new MutableDisposable()); private readonly currentSubscription = new MutableDisposable<TestSubscriptionListener>(); private container!: HTMLElement; private finishDiscovery?: () => void; private readonly location = TestingContextKeys.explorerLocation.bindTo(this.contextKeyService);; constructor( options: IViewletViewOptions, @IWorkspaceTestCollectionService private readonly testCollection: IWorkspaceTestCollectionService, @ITestService private readonly testService: ITestService, @IProgressService private readonly progress: IProgressService, @IContextMenuService contextMenuService: IContextMenuService, @IKeybindingService keybindingService: IKeybindingService, @IConfigurationService configurationService: IConfigurationService, @IInstantiationService instantiationService: IInstantiationService, @IViewDescriptorService viewDescriptorService: IViewDescriptorService, @IContextKeyService contextKeyService: IContextKeyService, @IOpenerService openerService: IOpenerService, @IThemeService themeService: IThemeService, @ITelemetryService telemetryService: ITelemetryService, ) { super(options, keybindingService, contextMenuService, configurationService, contextKeyService, viewDescriptorService, instantiationService, openerService, themeService, telemetryService); this._register(testService.onDidChangeProviders(() => this._onDidChangeViewWelcomeState.fire())); this.location.set(viewDescriptorService.getViewLocationById(Testing.ExplorerViewId) ?? ViewContainerLocation.Sidebar); } /** * @override */ public shouldShowWelcome() { return this.testService.providers === 0; } /** * @override */ protected renderBody(container: HTMLElement): void { super.renderBody(container); this.container = dom.append(container, dom.$('.test-explorer')); if (this.location.get() === ViewContainerLocation.Sidebar) { this.filterActionBar.value = this.createFilterActionBar(); } const messagesContainer = dom.append(this.container, dom.$('.test-explorer-messages')); this._register(this.instantiationService.createInstance(TestRunProgress, messagesContainer, this.getProgressLocation())); const listContainer = dom.append(this.container, dom.$('.test-explorer-tree')); this.viewModel = this.instantiationService.createInstance(TestingExplorerViewModel, listContainer, this.onDidChangeBodyVisibility, this.currentSubscription.value); this._register(this.viewModel); this._register(this.onDidChangeBodyVisibility(visible => { if (!visible && this.currentSubscription) { this.currentSubscription.value = undefined; this.viewModel.replaceSubscription(undefined); } else if (visible && !this.currentSubscription.value) { this.currentSubscription.value = this.createSubscription(); this.viewModel.replaceSubscription(this.currentSubscription.value); } })); } /** * @override */ public getActionViewItem(action: IAction): IActionViewItem | undefined { if (action.id === Testing.FilterActionId) { return this.instantiationService.createInstance(TestingExplorerFilter, action); } return super.getActionViewItem(action); } /** * @override */ public saveState() { super.saveState(); } private createFilterActionBar() { const bar = new ActionBar(this.container, { actionViewItemProvider: action => this.getActionViewItem(action) }); bar.push(new Action(Testing.FilterActionId)); bar.getContainer().classList.add('testing-filter-action-bar'); return bar; } private updateDiscoveryProgress(busy: number) { if (!busy && this.finishDiscovery) { this.finishDiscovery(); this.finishDiscovery = undefined; } else if (busy && !this.finishDiscovery) { const promise = new Promise<void>(resolve => { this.finishDiscovery = resolve; }); this.progress.withProgress({ location: this.getProgressLocation() }, () => promise); } } /** * @override */ protected layoutBody(height: number, width: number): void { super.layoutBody(height, width); this.container.style.height = `${height}px`; this.viewModel.layout(height, width); } private createSubscription() { const handle = this.testCollection.subscribeToWorkspaceTests(); handle.subscription.onBusyProvidersChange(() => this.updateDiscoveryProgress(handle.subscription.busyProviders)); return handle; } } export class TestingExplorerViewModel extends Disposable { public tree: ObjectTree<ITestTreeElement, FuzzyScore>; private filter: TestsFilter; public projection!: ITestTreeProjection; private readonly _viewMode = TestingContextKeys.viewMode.bindTo(this.contextKeyService); private readonly _viewSorting = TestingContextKeys.viewSorting.bindTo(this.contextKeyService); /** * Fires when the selected tests change. */ public readonly onDidChangeSelection: Event<ITreeEvent<ITestTreeElement | null>>; public get viewMode() { return this._viewMode.get() ?? TestExplorerViewMode.Tree; } public set viewMode(newMode: TestExplorerViewMode) { if (newMode === this._viewMode.get()) { return; } this._viewMode.set(newMode); this.updatePreferredProjection(); this.storageService.store('testing.viewMode', newMode, StorageScope.WORKSPACE, StorageTarget.USER); } public get viewSorting() { return this._viewSorting.get() ?? TestExplorerViewSorting.ByLocation; } public set viewSorting(newSorting: TestExplorerViewSorting) { if (newSorting === this._viewSorting.get()) { return; } this._viewSorting.set(newSorting); this.tree.resort(null); this.storageService.store('testing.viewSorting', newSorting, StorageScope.WORKSPACE, StorageTarget.USER); } constructor( listContainer: HTMLElement, onDidChangeVisibility: Event<boolean>, private listener: TestSubscriptionListener | undefined, @ITestExplorerFilterState filterState: TestExplorerFilterState, @IInstantiationService private readonly instantiationService: IInstantiationService, @IEditorService private readonly editorService: IEditorService, @IStorageService private readonly storageService: IStorageService, @IContextKeyService private readonly contextKeyService: IContextKeyService, @ITestResultService private readonly testResults: ITestResultService, @ITestingPeekOpener private readonly peekOpener: ITestingPeekOpener, ) { super(); this._viewMode.set(this.storageService.get('testing.viewMode', StorageScope.WORKSPACE, TestExplorerViewMode.Tree) as TestExplorerViewMode); this._viewSorting.set(this.storageService.get('testing.viewSorting', StorageScope.WORKSPACE, TestExplorerViewSorting.ByLocation) as TestExplorerViewSorting); const labels = this._register(instantiationService.createInstance(ResourceLabels, { onDidChangeVisibility: onDidChangeVisibility })); this.filter = this.instantiationService.createInstance(TestsFilter); this.tree = instantiationService.createInstance( WorkbenchObjectTree, 'Test Explorer List', listContainer, new ListDelegate(), [ instantiationService.createInstance(TestsRenderer, labels) ], { simpleKeyboardNavigation: true, identityProvider: instantiationService.createInstance(IdentityProvider), hideTwistiesOfChildlessElements: true, sorter: instantiationService.createInstance(TreeSorter, this), keyboardNavigationLabelProvider: instantiationService.createInstance(TreeKeyboardNavigationLabelProvider), accessibilityProvider: instantiationService.createInstance(ListAccessibilityProvider), filter: this.filter, }) as WorkbenchObjectTree<ITestTreeElement, FuzzyScore>; this._register(Event.any(filterState.currentDocumentOnly.onDidChange, filterState.text.onDidChange)(this.tree.refilter, this.tree)); this._register(editorService.onDidActiveEditorChange(() => { if (filterState.currentDocumentOnly.value && editorService.activeEditor?.resource) { if (this.projection.hasTestInDocument(editorService.activeEditor.resource)) { this.filter.filterToUri(editorService.activeEditor.resource); this.tree.refilter(); } } })); this._register(this.tree); this._register(dom.addStandardDisposableListener(this.tree.getHTMLElement(), 'keydown', evt => { if (DefaultKeyboardNavigationDelegate.mightProducePrintableCharacter(evt)) { filterState.text.value = evt.browserEvent.key; filterState.focusInput(); } })); this.updatePreferredProjection(); this.onDidChangeSelection = this.tree.onDidChangeSelection; this._register(this.tree.onDidChangeSelection(evt => { const selected = evt.elements[0]; if (selected && evt.browserEvent) { this.openEditorForItem(selected); } })); const tracker = this._register(this.instantiationService.createInstance(CodeEditorTracker, this)); this._register(onDidChangeVisibility(visible => { if (visible) { tracker.activate(); } else { tracker.deactivate(); } })); this._register(testResults.onResultsChanged(() => { this.tree.resort(null); })); } /** * Re-layout the tree. */ public layout(height: number, width: number): void { this.tree.layout(height, width); } /** * Replaces the test listener and recalculates the tree. */ public replaceSubscription(listener: TestSubscriptionListener | undefined) { this.listener = listener; this.updatePreferredProjection(); } /** * Reveals and moves focus to the item. */ public async revealItem(item: ITestTreeElement, reveal = true): Promise<void> { if (!this.tree.hasElement(item)) { return; } const chain: ITestTreeElement[] = []; for (let parent = item.parentItem; parent; parent = parent.parentItem) { chain.push(parent); } for (const parent of chain.reverse()) { try { this.tree.expand(parent); } catch { // ignore if not present } } if (reveal === true && this.tree.getRelativeTop(item) === null) { // Don't scroll to the item if it's already visible, or if set not to. this.tree.reveal(item, 0.5); } this.tree.setFocus([item]); this.tree.setSelection([item]); } /** * Collapse all items in the tree. */ public async collapseAll() { this.tree.collapseAll(); } /** * Opens an editor for the item. If there is a failure associated with the * test item, it will be shown. */ public async openEditorForItem(item: ITestTreeElement, preserveFocus = true) { if (await this.tryPeekError(item)) { return; } const location = item?.location; if (!location) { return; } const pane = await this.editorService.openEditor({ resource: location.uri, options: { selection: { startColumn: location.range.startColumn, startLineNumber: location.range.startLineNumber }, preserveFocus, }, }); // if the user selected a failed test and now they didn't, hide the peek const control = pane?.getControl(); if (isCodeEditor(control)) { TestingOutputPeekController.get(control).removePeek(); } } /** * Tries to peek the first test error, if the item is in a failed state. */ private async tryPeekError(item: ITestTreeElement) { const lookup = item.test && this.testResults.getStateByExtId(item.test.item.extId); return lookup && isFailedState(lookup[1].state.state) ? this.peekOpener.tryPeekFirstError(lookup[0], lookup[1], { preserveFocus: true }) : false; } private updatePreferredProjection() { this.projection?.dispose(); if (!this.listener) { this.tree.setChildren(null, []); return; } if (this._viewMode.get() === TestExplorerViewMode.List) { this.projection = this.instantiationService.createInstance(HierarchicalByNameProjection, this.listener); } else { this.projection = this.instantiationService.createInstance(HierarchicalByLocationProjection, this.listener); } this.projection.onUpdate(this.deferUpdate, this); this.projection.applyTo(this.tree); } @throttle(200) private deferUpdate() { this.projection.applyTo(this.tree); } /** * Gets the selected tests from the tree. */ public getSelectedTests() { return this.tree.getSelection(); } } class CodeEditorTracker { private store = new DisposableStore(); private lastRevealed?: ITestTreeElement; constructor( private readonly model: TestingExplorerViewModel, @ICodeEditorService private readonly codeEditorService: ICodeEditorService, ) { } public activate() { const editorStores = new Set<DisposableStore>(); this.store.add(toDisposable(() => { for (const store of editorStores) { store.dispose(); } })); const register = (editor: ICodeEditor) => { const store = new DisposableStore(); editorStores.add(store); store.add(editor.onDidChangeCursorPosition(evt => { const uri = editor.getModel()?.uri; if (!uri) { return; } const test = this.model.projection.getTestAtPosition(uri, evt.position); if (test && test !== this.lastRevealed) { this.model.revealItem(test); this.lastRevealed = test; } })); editor.onDidDispose(() => { store.dispose(); editorStores.delete(store); }); }; this.store.add(this.codeEditorService.onCodeEditorAdd(register)); this.codeEditorService.listCodeEditors().forEach(register); } public deactivate() { this.store.dispose(); this.store = new DisposableStore(); } public dispose() { this.store.dispose(); } } const enum FilterResult { Exclude, Inherit, Include, } class TestsFilter implements ITreeFilter<ITestTreeElement> { private lastText?: string; private filters: [include: boolean, value: string][] | undefined; private _filterToUri: string | undefined; constructor(@ITestExplorerFilterState private readonly state: ITestExplorerFilterState) { } /** * Parses and updates the tree filter. Supports lists of patterns that can be !negated. */ private setFilter(text: string) { this.lastText = text; text = text.trim(); if (!text) { this.filters = undefined; return; } this.filters = []; for (const filter of splitGlobAware(text, ',').map(s => s.trim()).filter(s => !!s.length)) { if (filter.startsWith('!')) { this.filters.push([false, filter.slice(1).toLowerCase()]); } else { this.filters.push([true, filter.toLowerCase()]); } } } public filterToUri(uri: URI) { this._filterToUri = uri.toString(); } /** * @inheritdoc */ public filter(element: ITestTreeElement): TreeFilterResult<void> { if (this.state.text.value !== this.lastText) { this.setFilter(this.state.text.value); } switch (Math.min(this.testFilterText(element), this.testLocation(element))) { case FilterResult.Exclude: return TreeVisibility.Hidden; case FilterResult.Include: return TreeVisibility.Visible; default: return TreeVisibility.Recurse; } } private testLocation(element: ITestTreeElement): FilterResult { if (!this._filterToUri || !this.state.currentDocumentOnly.value) { return FilterResult.Include; } for (let e: ITestTreeElement | null = element; e; e = e!.parentItem) { if (!e.location) { continue; } return e.location.uri.toString() === this._filterToUri ? FilterResult.Include : FilterResult.Exclude; } return FilterResult.Inherit; } private testFilterText(element: ITestTreeElement) { if (!this.filters) { return FilterResult.Include; } for (let e: ITestTreeElement | null = element; e; e = e.parentItem) { // start as included if the first glob is a negation let included = this.filters[0][0] === false ? FilterResult.Exclude : FilterResult.Inherit; const data = e.label.toLowerCase(); for (const [include, filter] of this.filters) { if (data.includes(filter)) { included = include ? FilterResult.Include : FilterResult.Exclude; } } if (included !== FilterResult.Inherit) { return included; } } return FilterResult.Inherit; } } class TreeSorter implements ITreeSorter<ITestTreeElement> { constructor(private readonly viewModel: TestingExplorerViewModel) { } public compare(a: ITestTreeElement, b: ITestTreeElement): number { let delta = cmpPriority(a.state, b.state); if (delta !== 0) { return delta; } if (this.viewModel.viewSorting === TestExplorerViewSorting.ByLocation && a.location && b.location && a.location.uri.toString() === b.location.uri.toString()) { delta = a.location.range.startLineNumber - b.location.range.startLineNumber; if (delta !== 0) { return delta; } } return a.label.localeCompare(b.label); } } class ListAccessibilityProvider implements IListAccessibilityProvider<ITestTreeElement> { getWidgetAriaLabel(): string { return localize('testExplorer', "Test Explorer"); } getAriaLabel(element: ITestTreeElement): string { let label = localize({ key: 'testing.treeElementLabel', comment: ['label then the unit tests state, for example "Addition Tests (Running)"'], }, '{0} ({1})', element.label, testStateNames[element.state]); if (element.retired) { label = localize({ key: 'testing.treeElementLabelOutdated', comment: ['{0} is the original label in testing.treeElementLabel'], }, '{0}, outdated result', label, testStateNames[element.state]); } return label; } } class TreeKeyboardNavigationLabelProvider implements IKeyboardNavigationLabelProvider<ITestTreeElement> { getKeyboardNavigationLabel(element: ITestTreeElement) { return element.label; } } class ListDelegate implements IListVirtualDelegate<ITestTreeElement> { getHeight(_element: ITestTreeElement) { return 22; } getTemplateId(_element: ITestTreeElement) { return TestsRenderer.ID; } } class IdentityProvider implements IIdentityProvider<ITestTreeElement> { public getId(element: ITestTreeElement) { return element.treeId; } } interface TestTemplateData { label: IResourceLabel; icon: HTMLElement; actionBar: ActionBar; } class TestsRenderer implements ITreeRenderer<ITestTreeElement, FuzzyScore, TestTemplateData> { public static readonly ID = 'testExplorer'; constructor( private labels: ResourceLabels, @IInstantiationService private readonly instantiationService: IInstantiationService ) { } renderCompressedElements(node: ITreeNode<ICompressedTreeNode<ITestTreeElement>, FuzzyScore>, index: number, templateData: TestTemplateData): void { const element = node.element.elements[node.element.elements.length - 1]; this.renderElementDirect(element, templateData); } get templateId(): string { return TestsRenderer.ID; } public renderTemplate(container: HTMLElement): TestTemplateData { const wrapper = dom.append(container, dom.$('.test-item')); const icon = dom.append(wrapper, dom.$('.computed-state')); const name = dom.append(wrapper, dom.$('.name')); const label = this.labels.create(name, { supportHighlights: true }); const actionBar = new ActionBar(wrapper, { actionViewItemProvider: action => action instanceof MenuItemAction ? this.instantiationService.createInstance(MenuEntryActionViewItem, action) : undefined }); return { label, actionBar, icon }; } public renderElement(node: ITreeNode<ITestTreeElement, FuzzyScore>, index: number, data: TestTemplateData): void { this.renderElementDirect(node.element, data); } private renderElementDirect(element: ITestTreeElement, data: TestTemplateData) { const label: IResourceLabelProps = { name: element.label }; const options: IResourceLabelOptions = {}; data.actionBar.clear(); const icon = testingStatesToIcons.get(element.state); data.icon.className = 'computed-state ' + (icon ? ThemeIcon.asClassName(icon) : ''); if (element.retired) { data.icon.className += ' retired'; } const test = element.test; if (test) { if (test.item.location) { label.resource = test.item.location.uri; } let title = element.label; for (let p = element.parentItem; p; p = p.parentItem) { title = `${p.label}, ${title}`; } options.title = title; options.fileKind = FileKind.FILE; label.description = element.description; } else { options.fileKind = FileKind.ROOT_FOLDER; } const running = element.state === TestRunState.Running; if (!Iterable.isEmpty(element.runnable)) { data.actionBar.push( this.instantiationService.createInstance(RunAction, element.runnable, running), { icon: true, label: false }, ); } if (!Iterable.isEmpty(element.debuggable)) { data.actionBar.push( this.instantiationService.createInstance(DebugAction, element.debuggable, running), { icon: true, label: false }, ); } data.label.setResource(label, options); } disposeTemplate(templateData: TestTemplateData): void { templateData.label.dispose(); templateData.actionBar.dispose(); } } type CountSummary = ReturnType<typeof collectCounts>; const collectCounts = (count: TestStateCount) => { const failed = count[TestRunState.Errored] + count[TestRunState.Failed]; const passed = count[TestRunState.Passed]; const skipped = count[TestRunState.Skipped]; return { passed, failed, runSoFar: passed + failed, totalWillBeRun: passed + failed + count[TestRunState.Queued] + count[TestRunState.Running], skipped, }; }; const getProgressText = ({ passed, runSoFar, skipped, failed }: CountSummary) => { let percent = passed / runSoFar * 100; if (failed > 0) { // fix: prevent from rounding to 100 if there's any failed test percent = Math.min(percent, 99.9); } if (skipped === 0) { return localize('testProgress', '{0}/{1} tests passed ({2}%)', passed, runSoFar, percent.toPrecision(3)); } else { return localize('testProgressWithSkip', '{0}/{1} tests passed ({2}%, {3} skipped)', passed, runSoFar, percent.toPrecision(3), skipped); } }; class TestRunProgress { private current?: { update: IProgress<IProgressStep>; deferred: DeferredPromise<void> }; private badge = new MutableDisposable(); private readonly resultLister = this.resultService.onResultsChanged(result => { if (!('started' in result)) { return; } this.updateProgress(); this.updateBadge(); result.started.onChange(this.throttledProgressUpdate, this); result.started.onComplete(() => { this.throttledProgressUpdate(); this.updateBadge(); }); }); constructor( private readonly messagesContainer: HTMLElement, private readonly location: string, @IProgressService private readonly progress: IProgressService, @ITestResultService private readonly resultService: ITestResultService, @IActivityService private readonly activityService: IActivityService, ) { } public dispose() { this.resultLister.dispose(); this.current?.deferred.complete(); this.badge.dispose(); } @throttle(200) private throttledProgressUpdate() { this.updateProgress(); } private updateProgress() { const running = this.resultService.results.filter(r => !r.isComplete); if (!running.length) { this.setIdleText(this.resultService.results[0]?.counts); this.current?.deferred.complete(); this.current = undefined; } else if (!this.current) { this.progress.withProgress({ location: this.location, total: 100 }, update => { this.current = { update, deferred: new DeferredPromise() }; this.updateProgress(); return this.current.deferred.p; }); } else { const counts = sumCounts(running.map(r => r.counts)); this.setRunningText(counts); const { runSoFar, totalWillBeRun } = collectCounts(counts); this.current.update.report({ increment: runSoFar, total: totalWillBeRun }); } } private setRunningText(counts: TestStateCount) { this.messagesContainer.dataset.state = 'running'; const collected = collectCounts(counts); if (collected.runSoFar === 0) { this.messagesContainer.innerText = localize('testResultStarting', 'Test run is starting...'); } else { this.messagesContainer.innerText = getProgressText(collected); } } private setIdleText(lastCount?: TestStateCount) { if (!lastCount) { this.messagesContainer.innerText = ''; } else { const collected = collectCounts(lastCount); this.messagesContainer.dataset.state = collected.failed ? 'failed' : 'running'; const doneMessage = getProgressText(collected); this.messagesContainer.innerText = doneMessage; aria.alert(doneMessage); } } private updateBadge() { this.badge.value = undefined; const result = this.resultService.results[0]; // currently running, or last run if (!result) { return; } if (!result.isComplete) { const badge = new ProgressBadge(() => localize('testBadgeRunning', 'Test run in progress')); this.badge.value = this.activityService.showViewActivity(Testing.ExplorerViewId, { badge, clazz: 'progress-badge' }); return; } const failures = result.counts[TestRunState.Failed] + result.counts[TestRunState.Errored]; if (failures === 0) { return; } const badge = new NumberBadge(failures, () => localize('testBadgeFailures', '{0} tests failed', failures)); this.badge.value = this.activityService.showViewActivity(Testing.ExplorerViewId, { badge }); } } registerThemingParticipant((theme, collector) => { if (theme.type === 'dark') { const foregroundColor = theme.getColor(foreground); if (foregroundColor) { const fgWithOpacity = new Color(new RGBA(foregroundColor.rgba.r, foregroundColor.rgba.g, foregroundColor.rgba.b, 0.65)); collector.addRule(`.test-explorer .test-explorer-messages { color: ${fgWithOpacity}; }`); } } });
src/vs/workbench/contrib/testing/browser/testingExplorerView.ts
1
https://github.com/microsoft/vscode/commit/07e3bcf7eacfb5a3f9c6e426fc977d176e40a726
[ 0.9411173462867737, 0.01094687171280384, 0.00016385482740588486, 0.00017089542234316468, 0.09916780889034271 ]
{ "id": 5, "code_window": [ "\n", "\t/**\n", "\t * Updates the 'checked' state of the filter submenu.\n", "\t */\n", "\tprivate updateFilterActiveState() {\n", "\t\tthis.filtersAction.checked = this.state.currentDocumentOnly.value;\n", "\t}\n", "}\n", "\n", "\n", "class FiltersDropdownMenuActionViewItem extends DropdownMenuActionViewItem {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis.filtersAction.checked = this.state.currentDocumentOnly.value\n", "\t\t\t|| this.state.stateFilter.value !== TestExplorerStateFilter.All;\n" ], "file_path": "src/vs/workbench/contrib/testing/browser/testingExplorerFilter.ts", "type": "replace", "edit_start_line_idx": 168 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.getProductionDependencies = void 0; const path = require("path"); const cp = require("child_process"); const _ = require("underscore"); const parseSemver = require('parse-semver'); function asYarnDependency(prefix, tree) { let parseResult; try { parseResult = parseSemver(tree.name); } catch (err) { err.message += `: ${tree.name}`; console.warn(`Could not parse semver: ${tree.name}`); return null; } // not an actual dependency in disk if (parseResult.version !== parseResult.range) { return null; } const name = parseResult.name; const version = parseResult.version; const dependencyPath = path.join(prefix, name); const children = []; for (const child of (tree.children || [])) { const dep = asYarnDependency(path.join(prefix, name, 'node_modules'), child); if (dep) { children.push(dep); } } return { name, version, path: dependencyPath, children }; } function getYarnProductionDependencies(cwd) { const raw = cp.execSync('yarn list --json', { cwd, encoding: 'utf8', env: Object.assign(Object.assign({}, process.env), { NODE_ENV: 'production' }), stdio: [null, null, 'inherit'] }); const match = /^{"type":"tree".*$/m.exec(raw); if (!match || match.length !== 1) { throw new Error('Could not parse result of `yarn list --json`'); } const trees = JSON.parse(match[0]).data.trees; return trees .map(tree => asYarnDependency(path.join(cwd, 'node_modules'), tree)) .filter((dep) => !!dep); } function getProductionDependencies(cwd) { const result = []; const deps = getYarnProductionDependencies(cwd); const flatten = (dep) => { result.push({ name: dep.name, version: dep.version, path: dep.path }); dep.children.forEach(flatten); }; deps.forEach(flatten); return _.uniq(result); } exports.getProductionDependencies = getProductionDependencies; if (require.main === module) { const root = path.dirname(path.dirname(__dirname)); console.log(JSON.stringify(getProductionDependencies(root), null, ' ')); }
build/lib/dependencies.js
0
https://github.com/microsoft/vscode/commit/07e3bcf7eacfb5a3f9c6e426fc977d176e40a726
[ 0.00018511292000766844, 0.000176155474036932, 0.0001729814539430663, 0.00017504866991657764, 0.000003935499080398586 ]
{ "id": 5, "code_window": [ "\n", "\t/**\n", "\t * Updates the 'checked' state of the filter submenu.\n", "\t */\n", "\tprivate updateFilterActiveState() {\n", "\t\tthis.filtersAction.checked = this.state.currentDocumentOnly.value;\n", "\t}\n", "}\n", "\n", "\n", "class FiltersDropdownMenuActionViewItem extends DropdownMenuActionViewItem {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis.filtersAction.checked = this.state.currentDocumentOnly.value\n", "\t\t\t|| this.state.stateFilter.value !== TestExplorerStateFilter.All;\n" ], "file_path": "src/vs/workbench/contrib/testing/browser/testingExplorerFilter.ts", "type": "replace", "edit_start_line_idx": 168 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.config = void 0; const fs = require("fs"); const path = require("path"); const vfs = require("vinyl-fs"); const filter = require("gulp-filter"); const _ = require("underscore"); const util = require("./util"); const root = path.dirname(path.dirname(__dirname)); const product = JSON.parse(fs.readFileSync(path.join(root, 'product.json'), 'utf8')); const commit = util.getVersion(root); const darwinCreditsTemplate = product.darwinCredits && _.template(fs.readFileSync(path.join(root, product.darwinCredits), 'utf8')); function darwinBundleDocumentType(extensions, icon) { return { name: product.nameLong + ' document', role: 'Editor', ostypes: ['TEXT', 'utxt', 'TUTX', '****'], extensions: extensions, iconFile: icon }; } exports.config = { version: util.getElectronVersion(), productAppName: product.nameLong, companyName: 'Microsoft Corporation', copyright: 'Copyright (C) 2019 Microsoft. All rights reserved', darwinIcon: 'resources/darwin/code.icns', darwinBundleIdentifier: product.darwinBundleIdentifier, darwinApplicationCategoryType: 'public.app-category.developer-tools', darwinHelpBookFolder: 'VS Code HelpBook', darwinHelpBookName: 'VS Code HelpBook', darwinBundleDocumentTypes: [ darwinBundleDocumentType(['bat', 'cmd'], 'resources/darwin/bat.icns'), darwinBundleDocumentType(['bowerrc'], 'resources/darwin/bower.icns'), darwinBundleDocumentType(['c', 'h'], 'resources/darwin/c.icns'), darwinBundleDocumentType(['config', 'editorconfig', 'gitattributes', 'gitconfig', 'gitignore', 'ini'], 'resources/darwin/config.icns'), darwinBundleDocumentType(['cc', 'cpp', 'cxx', 'c++', 'hh', 'hpp', 'hxx', 'h++'], 'resources/darwin/cpp.icns'), darwinBundleDocumentType(['cs', 'csx'], 'resources/darwin/csharp.icns'), darwinBundleDocumentType(['css'], 'resources/darwin/css.icns'), darwinBundleDocumentType(['go'], 'resources/darwin/go.icns'), darwinBundleDocumentType(['asp', 'aspx', 'cshtml', 'htm', 'html', 'jshtm', 'jsp', 'phtml', 'shtml'], 'resources/darwin/html.icns'), darwinBundleDocumentType(['jade'], 'resources/darwin/jade.icns'), darwinBundleDocumentType(['jav', 'java'], 'resources/darwin/java.icns'), darwinBundleDocumentType(['js', 'jscsrc', 'jshintrc', 'mjs', 'cjs'], 'resources/darwin/javascript.icns'), darwinBundleDocumentType(['json'], 'resources/darwin/json.icns'), darwinBundleDocumentType(['less'], 'resources/darwin/less.icns'), darwinBundleDocumentType(['markdown', 'md', 'mdoc', 'mdown', 'mdtext', 'mdtxt', 'mdwn', 'mkd', 'mkdn'], 'resources/darwin/markdown.icns'), darwinBundleDocumentType(['php'], 'resources/darwin/php.icns'), darwinBundleDocumentType(['ps1', 'psd1', 'psm1'], 'resources/darwin/powershell.icns'), darwinBundleDocumentType(['py'], 'resources/darwin/python.icns'), darwinBundleDocumentType(['gemspec', 'rb'], 'resources/darwin/ruby.icns'), darwinBundleDocumentType(['scss'], 'resources/darwin/sass.icns'), darwinBundleDocumentType(['bash', 'bash_login', 'bash_logout', 'bash_profile', 'bashrc', 'profile', 'rhistory', 'rprofile', 'sh', 'zlogin', 'zlogout', 'zprofile', 'zsh', 'zshenv', 'zshrc'], 'resources/darwin/shell.icns'), darwinBundleDocumentType(['sql'], 'resources/darwin/sql.icns'), darwinBundleDocumentType(['ts'], 'resources/darwin/typescript.icns'), darwinBundleDocumentType(['tsx', 'jsx'], 'resources/darwin/react.icns'), darwinBundleDocumentType(['vue'], 'resources/darwin/vue.icns'), darwinBundleDocumentType(['ascx', 'csproj', 'dtd', 'wxi', 'wxl', 'wxs', 'xml', 'xaml'], 'resources/darwin/xml.icns'), darwinBundleDocumentType(['eyaml', 'eyml', 'yaml', 'yml'], 'resources/darwin/yaml.icns'), darwinBundleDocumentType(['clj', 'cljs', 'cljx', 'clojure', 'code-workspace', 'coffee', 'containerfile', 'ctp', 'dockerfile', 'dot', 'edn', 'fs', 'fsi', 'fsscript', 'fsx', 'handlebars', 'hbs', 'lua', 'm', 'makefile', 'ml', 'mli', 'pl', 'pl6', 'pm', 'pm6', 'pod', 'pp', 'properties', 'psgi', 'pug', 'r', 'rs', 'rt', 'svg', 'svgz', 't', 'txt', 'vb', 'xcodeproj', 'xcworkspace'], 'resources/darwin/default.icns') ], darwinBundleURLTypes: [{ role: 'Viewer', name: product.nameLong, urlSchemes: [product.urlProtocol] }], darwinForceDarkModeSupport: true, darwinCredits: darwinCreditsTemplate ? Buffer.from(darwinCreditsTemplate({ commit: commit, date: new Date().toISOString() })) : undefined, linuxExecutableName: product.applicationName, winIcon: 'resources/win32/code.ico', token: process.env['VSCODE_MIXIN_PASSWORD'] || process.env['GITHUB_TOKEN'] || undefined, repo: product.electronRepository || undefined }; function getElectron(arch) { return () => { const electron = require('gulp-atom-electron'); const json = require('gulp-json-editor'); const electronOpts = _.extend({}, exports.config, { platform: process.platform, arch: arch === 'armhf' ? 'arm' : arch, ffmpegChromium: true, keepDefaultApp: true }); return vfs.src('package.json') .pipe(json({ name: product.nameShort })) .pipe(electron(electronOpts)) .pipe(filter(['**', '!**/app/package.json'])) .pipe(vfs.dest('.build/electron')); }; } async function main(arch = process.arch) { const version = util.getElectronVersion(); const electronPath = path.join(root, '.build', 'electron'); const versionFile = path.join(electronPath, 'version'); const isUpToDate = fs.existsSync(versionFile) && fs.readFileSync(versionFile, 'utf8') === `${version}`; if (!isUpToDate) { await util.rimraf(electronPath)(); await util.streamToPromise(getElectron(arch)()); } } if (require.main === module) { main(process.argv[2]).catch(err => { console.error(err); process.exit(1); }); }
build/lib/electron.js
0
https://github.com/microsoft/vscode/commit/07e3bcf7eacfb5a3f9c6e426fc977d176e40a726
[ 0.00017686819774098694, 0.00017289623792748898, 0.00016729695198591799, 0.00017425237456336617, 0.0000032303612442774465 ]
{ "id": 5, "code_window": [ "\n", "\t/**\n", "\t * Updates the 'checked' state of the filter submenu.\n", "\t */\n", "\tprivate updateFilterActiveState() {\n", "\t\tthis.filtersAction.checked = this.state.currentDocumentOnly.value;\n", "\t}\n", "}\n", "\n", "\n", "class FiltersDropdownMenuActionViewItem extends DropdownMenuActionViewItem {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis.filtersAction.checked = this.state.currentDocumentOnly.value\n", "\t\t\t|| this.state.stateFilter.value !== TestExplorerStateFilter.All;\n" ], "file_path": "src/vs/workbench/contrib/testing/browser/testingExplorerFilter.ts", "type": "replace", "edit_start_line_idx": 168 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ /*---------------------------------------------------------- The base color for this template is #5c87b2. If you'd like to use a different color start by replacing all instances of #5c87b2 with your new color. öäüßßß ----------------------------------------------------------*/ body { background-color: #5c87b2; font-size: .75em; font-family: Segoe UI, Verdana, Helvetica, Sans-Serif; margin: 8px; padding: 0; color: #696969; } h1, h2, h3, h4, h5, h6 { color: #000; font-size: 40px; margin: 0px; } textarea { font-family: Consolas } #results { margin-top: 2em; margin-left: 2em; color: black; font-size: medium; }
src/vs/workbench/services/textfile/test/node/encoding/fixtures/some_utf8.css
0
https://github.com/microsoft/vscode/commit/07e3bcf7eacfb5a3f9c6e426fc977d176e40a726
[ 0.0001741168089210987, 0.00017182754527311772, 0.0001696176186669618, 0.0001708926574792713, 0.0000018855056396205327 ]
{ "id": 6, "code_window": [ "\t}\n", "\n", "\tprivate getActions(): IAction[] {\n", "\t\treturn [\n", "\t\t\t{\n", "\t\t\t\tchecked: this.filters.currentDocumentOnly.value,\n", "\t\t\t\tclass: undefined,\n", "\t\t\t\tenabled: true,\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t...[\n", "\t\t\t\t{ v: TestExplorerStateFilter.OnlyFailed, label: localize('testing.filters.showOnlyFailed', \"Show Only Failed Tests\") },\n", "\t\t\t\t{ v: TestExplorerStateFilter.OnlyExecuted, label: localize('testing.filters.showOnlyExecuted', \"Show Only Executed Tests\") },\n", "\t\t\t\t{ v: TestExplorerStateFilter.All, label: localize('testing.filters.showAll', \"Show All Tests\") },\n", "\t\t\t].map(({ v, label }) => ({\n", "\t\t\t\tchecked: this.filters.stateFilter.value === v,\n", "\t\t\t\tclass: undefined,\n", "\t\t\t\tenabled: true,\n", "\t\t\t\tid: v,\n", "\t\t\t\tlabel,\n", "\t\t\t\trun: async () => this.filters.stateFilter.value = v,\n", "\t\t\t\ttooltip: '',\n", "\t\t\t\tdispose: () => null\n", "\t\t\t})),\n", "\t\t\tnew Separator(),\n" ], "file_path": "src/vs/workbench/contrib/testing/browser/testingExplorerFilter.ts", "type": "add", "edit_start_line_idx": 200 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as dom from 'vs/base/browser/dom'; import { ActionBar } from 'vs/base/browser/ui/actionbar/actionbar'; import * as aria from 'vs/base/browser/ui/aria/aria'; import { IIdentityProvider, IKeyboardNavigationLabelProvider, IListVirtualDelegate } from 'vs/base/browser/ui/list/list'; import { DefaultKeyboardNavigationDelegate, IListAccessibilityProvider } from 'vs/base/browser/ui/list/listWidget'; import { ICompressedTreeNode } from 'vs/base/browser/ui/tree/compressedObjectTreeModel'; import { ObjectTree } from 'vs/base/browser/ui/tree/objectTree'; import { ITreeEvent, ITreeFilter, ITreeNode, ITreeRenderer, ITreeSorter, TreeFilterResult, TreeVisibility } from 'vs/base/browser/ui/tree/tree'; import { Action, IAction, IActionViewItem } from 'vs/base/common/actions'; import { DeferredPromise } from 'vs/base/common/async'; import { Color, RGBA } from 'vs/base/common/color'; import { throttle } from 'vs/base/common/decorators'; import { Event } from 'vs/base/common/event'; import { FuzzyScore } from 'vs/base/common/filters'; import { splitGlobAware } from 'vs/base/common/glob'; import { Iterable } from 'vs/base/common/iterator'; import { Disposable, DisposableStore, MutableDisposable, toDisposable } from 'vs/base/common/lifecycle'; import { URI } from 'vs/base/common/uri'; import 'vs/css!./media/testing'; import { ICodeEditor, isCodeEditor } from 'vs/editor/browser/editorBrowser'; import { ICodeEditorService } from 'vs/editor/browser/services/codeEditorService'; import { localize } from 'vs/nls'; import { MenuEntryActionViewItem } from 'vs/platform/actions/browser/menuEntryActionViewItem'; import { MenuItemAction } from 'vs/platform/actions/common/actions'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { IContextMenuService } from 'vs/platform/contextview/browser/contextView'; import { FileKind } from 'vs/platform/files/common/files'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { WorkbenchObjectTree } from 'vs/platform/list/browser/listService'; import { IOpenerService } from 'vs/platform/opener/common/opener'; import { IProgress, IProgressService, IProgressStep } from 'vs/platform/progress/common/progress'; import { IStorageService, StorageScope, StorageTarget } from 'vs/platform/storage/common/storage'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { foreground } from 'vs/platform/theme/common/colorRegistry'; import { IThemeService, registerThemingParticipant, ThemeIcon } from 'vs/platform/theme/common/themeService'; import { TestRunState } from 'vs/workbench/api/common/extHostTypes'; import { IResourceLabel, IResourceLabelOptions, IResourceLabelProps, ResourceLabels } from 'vs/workbench/browser/labels'; import { ViewPane } from 'vs/workbench/browser/parts/views/viewPane'; import { IViewletViewOptions } from 'vs/workbench/browser/parts/views/viewsViewlet'; import { IViewDescriptorService, ViewContainerLocation } from 'vs/workbench/common/views'; import { ITestTreeElement, ITestTreeProjection } from 'vs/workbench/contrib/testing/browser/explorerProjections'; import { HierarchicalByLocationProjection } from 'vs/workbench/contrib/testing/browser/explorerProjections/hierarchalByLocation'; import { HierarchicalByNameProjection } from 'vs/workbench/contrib/testing/browser/explorerProjections/hierarchalByName'; import { testingStatesToIcons } from 'vs/workbench/contrib/testing/browser/icons'; import { ITestExplorerFilterState, TestExplorerFilterState, TestingExplorerFilter } from 'vs/workbench/contrib/testing/browser/testingExplorerFilter'; import { ITestingPeekOpener, TestingOutputPeekController } from 'vs/workbench/contrib/testing/browser/testingOutputPeek'; import { TestExplorerViewMode, TestExplorerViewSorting, Testing, testStateNames } from 'vs/workbench/contrib/testing/common/constants'; import { TestingContextKeys } from 'vs/workbench/contrib/testing/common/testingContextKeys'; import { cmpPriority, isFailedState } from 'vs/workbench/contrib/testing/common/testingStates'; import { ITestResultService, sumCounts, TestStateCount } from 'vs/workbench/contrib/testing/common/testResultService'; import { ITestService } from 'vs/workbench/contrib/testing/common/testService'; import { IWorkspaceTestCollectionService, TestSubscriptionListener } from 'vs/workbench/contrib/testing/common/workspaceTestCollectionService'; import { IActivityService, NumberBadge, ProgressBadge } from 'vs/workbench/services/activity/common/activity'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { DebugAction, RunAction } from './testExplorerActions'; export class TestingExplorerView extends ViewPane { public viewModel!: TestingExplorerViewModel; private filterActionBar = this._register(new MutableDisposable()); private readonly currentSubscription = new MutableDisposable<TestSubscriptionListener>(); private container!: HTMLElement; private finishDiscovery?: () => void; private readonly location = TestingContextKeys.explorerLocation.bindTo(this.contextKeyService);; constructor( options: IViewletViewOptions, @IWorkspaceTestCollectionService private readonly testCollection: IWorkspaceTestCollectionService, @ITestService private readonly testService: ITestService, @IProgressService private readonly progress: IProgressService, @IContextMenuService contextMenuService: IContextMenuService, @IKeybindingService keybindingService: IKeybindingService, @IConfigurationService configurationService: IConfigurationService, @IInstantiationService instantiationService: IInstantiationService, @IViewDescriptorService viewDescriptorService: IViewDescriptorService, @IContextKeyService contextKeyService: IContextKeyService, @IOpenerService openerService: IOpenerService, @IThemeService themeService: IThemeService, @ITelemetryService telemetryService: ITelemetryService, ) { super(options, keybindingService, contextMenuService, configurationService, contextKeyService, viewDescriptorService, instantiationService, openerService, themeService, telemetryService); this._register(testService.onDidChangeProviders(() => this._onDidChangeViewWelcomeState.fire())); this.location.set(viewDescriptorService.getViewLocationById(Testing.ExplorerViewId) ?? ViewContainerLocation.Sidebar); } /** * @override */ public shouldShowWelcome() { return this.testService.providers === 0; } /** * @override */ protected renderBody(container: HTMLElement): void { super.renderBody(container); this.container = dom.append(container, dom.$('.test-explorer')); if (this.location.get() === ViewContainerLocation.Sidebar) { this.filterActionBar.value = this.createFilterActionBar(); } const messagesContainer = dom.append(this.container, dom.$('.test-explorer-messages')); this._register(this.instantiationService.createInstance(TestRunProgress, messagesContainer, this.getProgressLocation())); const listContainer = dom.append(this.container, dom.$('.test-explorer-tree')); this.viewModel = this.instantiationService.createInstance(TestingExplorerViewModel, listContainer, this.onDidChangeBodyVisibility, this.currentSubscription.value); this._register(this.viewModel); this._register(this.onDidChangeBodyVisibility(visible => { if (!visible && this.currentSubscription) { this.currentSubscription.value = undefined; this.viewModel.replaceSubscription(undefined); } else if (visible && !this.currentSubscription.value) { this.currentSubscription.value = this.createSubscription(); this.viewModel.replaceSubscription(this.currentSubscription.value); } })); } /** * @override */ public getActionViewItem(action: IAction): IActionViewItem | undefined { if (action.id === Testing.FilterActionId) { return this.instantiationService.createInstance(TestingExplorerFilter, action); } return super.getActionViewItem(action); } /** * @override */ public saveState() { super.saveState(); } private createFilterActionBar() { const bar = new ActionBar(this.container, { actionViewItemProvider: action => this.getActionViewItem(action) }); bar.push(new Action(Testing.FilterActionId)); bar.getContainer().classList.add('testing-filter-action-bar'); return bar; } private updateDiscoveryProgress(busy: number) { if (!busy && this.finishDiscovery) { this.finishDiscovery(); this.finishDiscovery = undefined; } else if (busy && !this.finishDiscovery) { const promise = new Promise<void>(resolve => { this.finishDiscovery = resolve; }); this.progress.withProgress({ location: this.getProgressLocation() }, () => promise); } } /** * @override */ protected layoutBody(height: number, width: number): void { super.layoutBody(height, width); this.container.style.height = `${height}px`; this.viewModel.layout(height, width); } private createSubscription() { const handle = this.testCollection.subscribeToWorkspaceTests(); handle.subscription.onBusyProvidersChange(() => this.updateDiscoveryProgress(handle.subscription.busyProviders)); return handle; } } export class TestingExplorerViewModel extends Disposable { public tree: ObjectTree<ITestTreeElement, FuzzyScore>; private filter: TestsFilter; public projection!: ITestTreeProjection; private readonly _viewMode = TestingContextKeys.viewMode.bindTo(this.contextKeyService); private readonly _viewSorting = TestingContextKeys.viewSorting.bindTo(this.contextKeyService); /** * Fires when the selected tests change. */ public readonly onDidChangeSelection: Event<ITreeEvent<ITestTreeElement | null>>; public get viewMode() { return this._viewMode.get() ?? TestExplorerViewMode.Tree; } public set viewMode(newMode: TestExplorerViewMode) { if (newMode === this._viewMode.get()) { return; } this._viewMode.set(newMode); this.updatePreferredProjection(); this.storageService.store('testing.viewMode', newMode, StorageScope.WORKSPACE, StorageTarget.USER); } public get viewSorting() { return this._viewSorting.get() ?? TestExplorerViewSorting.ByLocation; } public set viewSorting(newSorting: TestExplorerViewSorting) { if (newSorting === this._viewSorting.get()) { return; } this._viewSorting.set(newSorting); this.tree.resort(null); this.storageService.store('testing.viewSorting', newSorting, StorageScope.WORKSPACE, StorageTarget.USER); } constructor( listContainer: HTMLElement, onDidChangeVisibility: Event<boolean>, private listener: TestSubscriptionListener | undefined, @ITestExplorerFilterState filterState: TestExplorerFilterState, @IInstantiationService private readonly instantiationService: IInstantiationService, @IEditorService private readonly editorService: IEditorService, @IStorageService private readonly storageService: IStorageService, @IContextKeyService private readonly contextKeyService: IContextKeyService, @ITestResultService private readonly testResults: ITestResultService, @ITestingPeekOpener private readonly peekOpener: ITestingPeekOpener, ) { super(); this._viewMode.set(this.storageService.get('testing.viewMode', StorageScope.WORKSPACE, TestExplorerViewMode.Tree) as TestExplorerViewMode); this._viewSorting.set(this.storageService.get('testing.viewSorting', StorageScope.WORKSPACE, TestExplorerViewSorting.ByLocation) as TestExplorerViewSorting); const labels = this._register(instantiationService.createInstance(ResourceLabels, { onDidChangeVisibility: onDidChangeVisibility })); this.filter = this.instantiationService.createInstance(TestsFilter); this.tree = instantiationService.createInstance( WorkbenchObjectTree, 'Test Explorer List', listContainer, new ListDelegate(), [ instantiationService.createInstance(TestsRenderer, labels) ], { simpleKeyboardNavigation: true, identityProvider: instantiationService.createInstance(IdentityProvider), hideTwistiesOfChildlessElements: true, sorter: instantiationService.createInstance(TreeSorter, this), keyboardNavigationLabelProvider: instantiationService.createInstance(TreeKeyboardNavigationLabelProvider), accessibilityProvider: instantiationService.createInstance(ListAccessibilityProvider), filter: this.filter, }) as WorkbenchObjectTree<ITestTreeElement, FuzzyScore>; this._register(Event.any(filterState.currentDocumentOnly.onDidChange, filterState.text.onDidChange)(this.tree.refilter, this.tree)); this._register(editorService.onDidActiveEditorChange(() => { if (filterState.currentDocumentOnly.value && editorService.activeEditor?.resource) { if (this.projection.hasTestInDocument(editorService.activeEditor.resource)) { this.filter.filterToUri(editorService.activeEditor.resource); this.tree.refilter(); } } })); this._register(this.tree); this._register(dom.addStandardDisposableListener(this.tree.getHTMLElement(), 'keydown', evt => { if (DefaultKeyboardNavigationDelegate.mightProducePrintableCharacter(evt)) { filterState.text.value = evt.browserEvent.key; filterState.focusInput(); } })); this.updatePreferredProjection(); this.onDidChangeSelection = this.tree.onDidChangeSelection; this._register(this.tree.onDidChangeSelection(evt => { const selected = evt.elements[0]; if (selected && evt.browserEvent) { this.openEditorForItem(selected); } })); const tracker = this._register(this.instantiationService.createInstance(CodeEditorTracker, this)); this._register(onDidChangeVisibility(visible => { if (visible) { tracker.activate(); } else { tracker.deactivate(); } })); this._register(testResults.onResultsChanged(() => { this.tree.resort(null); })); } /** * Re-layout the tree. */ public layout(height: number, width: number): void { this.tree.layout(height, width); } /** * Replaces the test listener and recalculates the tree. */ public replaceSubscription(listener: TestSubscriptionListener | undefined) { this.listener = listener; this.updatePreferredProjection(); } /** * Reveals and moves focus to the item. */ public async revealItem(item: ITestTreeElement, reveal = true): Promise<void> { if (!this.tree.hasElement(item)) { return; } const chain: ITestTreeElement[] = []; for (let parent = item.parentItem; parent; parent = parent.parentItem) { chain.push(parent); } for (const parent of chain.reverse()) { try { this.tree.expand(parent); } catch { // ignore if not present } } if (reveal === true && this.tree.getRelativeTop(item) === null) { // Don't scroll to the item if it's already visible, or if set not to. this.tree.reveal(item, 0.5); } this.tree.setFocus([item]); this.tree.setSelection([item]); } /** * Collapse all items in the tree. */ public async collapseAll() { this.tree.collapseAll(); } /** * Opens an editor for the item. If there is a failure associated with the * test item, it will be shown. */ public async openEditorForItem(item: ITestTreeElement, preserveFocus = true) { if (await this.tryPeekError(item)) { return; } const location = item?.location; if (!location) { return; } const pane = await this.editorService.openEditor({ resource: location.uri, options: { selection: { startColumn: location.range.startColumn, startLineNumber: location.range.startLineNumber }, preserveFocus, }, }); // if the user selected a failed test and now they didn't, hide the peek const control = pane?.getControl(); if (isCodeEditor(control)) { TestingOutputPeekController.get(control).removePeek(); } } /** * Tries to peek the first test error, if the item is in a failed state. */ private async tryPeekError(item: ITestTreeElement) { const lookup = item.test && this.testResults.getStateByExtId(item.test.item.extId); return lookup && isFailedState(lookup[1].state.state) ? this.peekOpener.tryPeekFirstError(lookup[0], lookup[1], { preserveFocus: true }) : false; } private updatePreferredProjection() { this.projection?.dispose(); if (!this.listener) { this.tree.setChildren(null, []); return; } if (this._viewMode.get() === TestExplorerViewMode.List) { this.projection = this.instantiationService.createInstance(HierarchicalByNameProjection, this.listener); } else { this.projection = this.instantiationService.createInstance(HierarchicalByLocationProjection, this.listener); } this.projection.onUpdate(this.deferUpdate, this); this.projection.applyTo(this.tree); } @throttle(200) private deferUpdate() { this.projection.applyTo(this.tree); } /** * Gets the selected tests from the tree. */ public getSelectedTests() { return this.tree.getSelection(); } } class CodeEditorTracker { private store = new DisposableStore(); private lastRevealed?: ITestTreeElement; constructor( private readonly model: TestingExplorerViewModel, @ICodeEditorService private readonly codeEditorService: ICodeEditorService, ) { } public activate() { const editorStores = new Set<DisposableStore>(); this.store.add(toDisposable(() => { for (const store of editorStores) { store.dispose(); } })); const register = (editor: ICodeEditor) => { const store = new DisposableStore(); editorStores.add(store); store.add(editor.onDidChangeCursorPosition(evt => { const uri = editor.getModel()?.uri; if (!uri) { return; } const test = this.model.projection.getTestAtPosition(uri, evt.position); if (test && test !== this.lastRevealed) { this.model.revealItem(test); this.lastRevealed = test; } })); editor.onDidDispose(() => { store.dispose(); editorStores.delete(store); }); }; this.store.add(this.codeEditorService.onCodeEditorAdd(register)); this.codeEditorService.listCodeEditors().forEach(register); } public deactivate() { this.store.dispose(); this.store = new DisposableStore(); } public dispose() { this.store.dispose(); } } const enum FilterResult { Exclude, Inherit, Include, } class TestsFilter implements ITreeFilter<ITestTreeElement> { private lastText?: string; private filters: [include: boolean, value: string][] | undefined; private _filterToUri: string | undefined; constructor(@ITestExplorerFilterState private readonly state: ITestExplorerFilterState) { } /** * Parses and updates the tree filter. Supports lists of patterns that can be !negated. */ private setFilter(text: string) { this.lastText = text; text = text.trim(); if (!text) { this.filters = undefined; return; } this.filters = []; for (const filter of splitGlobAware(text, ',').map(s => s.trim()).filter(s => !!s.length)) { if (filter.startsWith('!')) { this.filters.push([false, filter.slice(1).toLowerCase()]); } else { this.filters.push([true, filter.toLowerCase()]); } } } public filterToUri(uri: URI) { this._filterToUri = uri.toString(); } /** * @inheritdoc */ public filter(element: ITestTreeElement): TreeFilterResult<void> { if (this.state.text.value !== this.lastText) { this.setFilter(this.state.text.value); } switch (Math.min(this.testFilterText(element), this.testLocation(element))) { case FilterResult.Exclude: return TreeVisibility.Hidden; case FilterResult.Include: return TreeVisibility.Visible; default: return TreeVisibility.Recurse; } } private testLocation(element: ITestTreeElement): FilterResult { if (!this._filterToUri || !this.state.currentDocumentOnly.value) { return FilterResult.Include; } for (let e: ITestTreeElement | null = element; e; e = e!.parentItem) { if (!e.location) { continue; } return e.location.uri.toString() === this._filterToUri ? FilterResult.Include : FilterResult.Exclude; } return FilterResult.Inherit; } private testFilterText(element: ITestTreeElement) { if (!this.filters) { return FilterResult.Include; } for (let e: ITestTreeElement | null = element; e; e = e.parentItem) { // start as included if the first glob is a negation let included = this.filters[0][0] === false ? FilterResult.Exclude : FilterResult.Inherit; const data = e.label.toLowerCase(); for (const [include, filter] of this.filters) { if (data.includes(filter)) { included = include ? FilterResult.Include : FilterResult.Exclude; } } if (included !== FilterResult.Inherit) { return included; } } return FilterResult.Inherit; } } class TreeSorter implements ITreeSorter<ITestTreeElement> { constructor(private readonly viewModel: TestingExplorerViewModel) { } public compare(a: ITestTreeElement, b: ITestTreeElement): number { let delta = cmpPriority(a.state, b.state); if (delta !== 0) { return delta; } if (this.viewModel.viewSorting === TestExplorerViewSorting.ByLocation && a.location && b.location && a.location.uri.toString() === b.location.uri.toString()) { delta = a.location.range.startLineNumber - b.location.range.startLineNumber; if (delta !== 0) { return delta; } } return a.label.localeCompare(b.label); } } class ListAccessibilityProvider implements IListAccessibilityProvider<ITestTreeElement> { getWidgetAriaLabel(): string { return localize('testExplorer', "Test Explorer"); } getAriaLabel(element: ITestTreeElement): string { let label = localize({ key: 'testing.treeElementLabel', comment: ['label then the unit tests state, for example "Addition Tests (Running)"'], }, '{0} ({1})', element.label, testStateNames[element.state]); if (element.retired) { label = localize({ key: 'testing.treeElementLabelOutdated', comment: ['{0} is the original label in testing.treeElementLabel'], }, '{0}, outdated result', label, testStateNames[element.state]); } return label; } } class TreeKeyboardNavigationLabelProvider implements IKeyboardNavigationLabelProvider<ITestTreeElement> { getKeyboardNavigationLabel(element: ITestTreeElement) { return element.label; } } class ListDelegate implements IListVirtualDelegate<ITestTreeElement> { getHeight(_element: ITestTreeElement) { return 22; } getTemplateId(_element: ITestTreeElement) { return TestsRenderer.ID; } } class IdentityProvider implements IIdentityProvider<ITestTreeElement> { public getId(element: ITestTreeElement) { return element.treeId; } } interface TestTemplateData { label: IResourceLabel; icon: HTMLElement; actionBar: ActionBar; } class TestsRenderer implements ITreeRenderer<ITestTreeElement, FuzzyScore, TestTemplateData> { public static readonly ID = 'testExplorer'; constructor( private labels: ResourceLabels, @IInstantiationService private readonly instantiationService: IInstantiationService ) { } renderCompressedElements(node: ITreeNode<ICompressedTreeNode<ITestTreeElement>, FuzzyScore>, index: number, templateData: TestTemplateData): void { const element = node.element.elements[node.element.elements.length - 1]; this.renderElementDirect(element, templateData); } get templateId(): string { return TestsRenderer.ID; } public renderTemplate(container: HTMLElement): TestTemplateData { const wrapper = dom.append(container, dom.$('.test-item')); const icon = dom.append(wrapper, dom.$('.computed-state')); const name = dom.append(wrapper, dom.$('.name')); const label = this.labels.create(name, { supportHighlights: true }); const actionBar = new ActionBar(wrapper, { actionViewItemProvider: action => action instanceof MenuItemAction ? this.instantiationService.createInstance(MenuEntryActionViewItem, action) : undefined }); return { label, actionBar, icon }; } public renderElement(node: ITreeNode<ITestTreeElement, FuzzyScore>, index: number, data: TestTemplateData): void { this.renderElementDirect(node.element, data); } private renderElementDirect(element: ITestTreeElement, data: TestTemplateData) { const label: IResourceLabelProps = { name: element.label }; const options: IResourceLabelOptions = {}; data.actionBar.clear(); const icon = testingStatesToIcons.get(element.state); data.icon.className = 'computed-state ' + (icon ? ThemeIcon.asClassName(icon) : ''); if (element.retired) { data.icon.className += ' retired'; } const test = element.test; if (test) { if (test.item.location) { label.resource = test.item.location.uri; } let title = element.label; for (let p = element.parentItem; p; p = p.parentItem) { title = `${p.label}, ${title}`; } options.title = title; options.fileKind = FileKind.FILE; label.description = element.description; } else { options.fileKind = FileKind.ROOT_FOLDER; } const running = element.state === TestRunState.Running; if (!Iterable.isEmpty(element.runnable)) { data.actionBar.push( this.instantiationService.createInstance(RunAction, element.runnable, running), { icon: true, label: false }, ); } if (!Iterable.isEmpty(element.debuggable)) { data.actionBar.push( this.instantiationService.createInstance(DebugAction, element.debuggable, running), { icon: true, label: false }, ); } data.label.setResource(label, options); } disposeTemplate(templateData: TestTemplateData): void { templateData.label.dispose(); templateData.actionBar.dispose(); } } type CountSummary = ReturnType<typeof collectCounts>; const collectCounts = (count: TestStateCount) => { const failed = count[TestRunState.Errored] + count[TestRunState.Failed]; const passed = count[TestRunState.Passed]; const skipped = count[TestRunState.Skipped]; return { passed, failed, runSoFar: passed + failed, totalWillBeRun: passed + failed + count[TestRunState.Queued] + count[TestRunState.Running], skipped, }; }; const getProgressText = ({ passed, runSoFar, skipped, failed }: CountSummary) => { let percent = passed / runSoFar * 100; if (failed > 0) { // fix: prevent from rounding to 100 if there's any failed test percent = Math.min(percent, 99.9); } if (skipped === 0) { return localize('testProgress', '{0}/{1} tests passed ({2}%)', passed, runSoFar, percent.toPrecision(3)); } else { return localize('testProgressWithSkip', '{0}/{1} tests passed ({2}%, {3} skipped)', passed, runSoFar, percent.toPrecision(3), skipped); } }; class TestRunProgress { private current?: { update: IProgress<IProgressStep>; deferred: DeferredPromise<void> }; private badge = new MutableDisposable(); private readonly resultLister = this.resultService.onResultsChanged(result => { if (!('started' in result)) { return; } this.updateProgress(); this.updateBadge(); result.started.onChange(this.throttledProgressUpdate, this); result.started.onComplete(() => { this.throttledProgressUpdate(); this.updateBadge(); }); }); constructor( private readonly messagesContainer: HTMLElement, private readonly location: string, @IProgressService private readonly progress: IProgressService, @ITestResultService private readonly resultService: ITestResultService, @IActivityService private readonly activityService: IActivityService, ) { } public dispose() { this.resultLister.dispose(); this.current?.deferred.complete(); this.badge.dispose(); } @throttle(200) private throttledProgressUpdate() { this.updateProgress(); } private updateProgress() { const running = this.resultService.results.filter(r => !r.isComplete); if (!running.length) { this.setIdleText(this.resultService.results[0]?.counts); this.current?.deferred.complete(); this.current = undefined; } else if (!this.current) { this.progress.withProgress({ location: this.location, total: 100 }, update => { this.current = { update, deferred: new DeferredPromise() }; this.updateProgress(); return this.current.deferred.p; }); } else { const counts = sumCounts(running.map(r => r.counts)); this.setRunningText(counts); const { runSoFar, totalWillBeRun } = collectCounts(counts); this.current.update.report({ increment: runSoFar, total: totalWillBeRun }); } } private setRunningText(counts: TestStateCount) { this.messagesContainer.dataset.state = 'running'; const collected = collectCounts(counts); if (collected.runSoFar === 0) { this.messagesContainer.innerText = localize('testResultStarting', 'Test run is starting...'); } else { this.messagesContainer.innerText = getProgressText(collected); } } private setIdleText(lastCount?: TestStateCount) { if (!lastCount) { this.messagesContainer.innerText = ''; } else { const collected = collectCounts(lastCount); this.messagesContainer.dataset.state = collected.failed ? 'failed' : 'running'; const doneMessage = getProgressText(collected); this.messagesContainer.innerText = doneMessage; aria.alert(doneMessage); } } private updateBadge() { this.badge.value = undefined; const result = this.resultService.results[0]; // currently running, or last run if (!result) { return; } if (!result.isComplete) { const badge = new ProgressBadge(() => localize('testBadgeRunning', 'Test run in progress')); this.badge.value = this.activityService.showViewActivity(Testing.ExplorerViewId, { badge, clazz: 'progress-badge' }); return; } const failures = result.counts[TestRunState.Failed] + result.counts[TestRunState.Errored]; if (failures === 0) { return; } const badge = new NumberBadge(failures, () => localize('testBadgeFailures', '{0} tests failed', failures)); this.badge.value = this.activityService.showViewActivity(Testing.ExplorerViewId, { badge }); } } registerThemingParticipant((theme, collector) => { if (theme.type === 'dark') { const foregroundColor = theme.getColor(foreground); if (foregroundColor) { const fgWithOpacity = new Color(new RGBA(foregroundColor.rgba.r, foregroundColor.rgba.g, foregroundColor.rgba.b, 0.65)); collector.addRule(`.test-explorer .test-explorer-messages { color: ${fgWithOpacity}; }`); } } });
src/vs/workbench/contrib/testing/browser/testingExplorerView.ts
1
https://github.com/microsoft/vscode/commit/07e3bcf7eacfb5a3f9c6e426fc977d176e40a726
[ 0.004799053072929382, 0.00028415111592039466, 0.00016007684462238103, 0.00017196955741383135, 0.0005762882647104561 ]
{ "id": 6, "code_window": [ "\t}\n", "\n", "\tprivate getActions(): IAction[] {\n", "\t\treturn [\n", "\t\t\t{\n", "\t\t\t\tchecked: this.filters.currentDocumentOnly.value,\n", "\t\t\t\tclass: undefined,\n", "\t\t\t\tenabled: true,\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t...[\n", "\t\t\t\t{ v: TestExplorerStateFilter.OnlyFailed, label: localize('testing.filters.showOnlyFailed', \"Show Only Failed Tests\") },\n", "\t\t\t\t{ v: TestExplorerStateFilter.OnlyExecuted, label: localize('testing.filters.showOnlyExecuted', \"Show Only Executed Tests\") },\n", "\t\t\t\t{ v: TestExplorerStateFilter.All, label: localize('testing.filters.showAll', \"Show All Tests\") },\n", "\t\t\t].map(({ v, label }) => ({\n", "\t\t\t\tchecked: this.filters.stateFilter.value === v,\n", "\t\t\t\tclass: undefined,\n", "\t\t\t\tenabled: true,\n", "\t\t\t\tid: v,\n", "\t\t\t\tlabel,\n", "\t\t\t\trun: async () => this.filters.stateFilter.value = v,\n", "\t\t\t\ttooltip: '',\n", "\t\t\t\tdispose: () => null\n", "\t\t\t})),\n", "\t\t\tnew Separator(),\n" ], "file_path": "src/vs/workbench/contrib/testing/browser/testingExplorerFilter.ts", "type": "add", "edit_start_line_idx": 200 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { URI } from 'vs/base/common/uri'; import { createDecorator } from 'vs/platform/instantiation/common/instantiation'; import { Event } from 'vs/base/common/event'; import { IDisposable } from 'vs/base/common/lifecycle'; import { Command } from 'vs/editor/common/modes'; import { ISequence } from 'vs/base/common/sequence'; import { IAction } from 'vs/base/common/actions'; import { IMenu } from 'vs/platform/actions/common/actions'; export const VIEWLET_ID = 'workbench.view.scm'; export const VIEW_PANE_ID = 'workbench.scm'; export const REPOSITORIES_VIEW_PANE_ID = 'workbench.scm.repositories'; export interface IBaselineResourceProvider { getBaselineResource(resource: URI): Promise<URI>; } export const ISCMService = createDecorator<ISCMService>('scm'); export interface ISCMResourceDecorations { icon?: URI; iconDark?: URI; tooltip?: string; strikeThrough?: boolean; faded?: boolean; } export interface ISCMResource { readonly resourceGroup: ISCMResourceGroup; readonly sourceUri: URI; readonly decorations: ISCMResourceDecorations; readonly contextValue: string | undefined; readonly command: Command | undefined; open(preserveFocus: boolean): Promise<void>; } export interface ISCMResourceGroup extends ISequence<ISCMResource> { readonly provider: ISCMProvider; readonly label: string; readonly id: string; readonly hideWhenEmpty: boolean; readonly onDidChange: Event<void>; } export interface ISCMProvider extends IDisposable { readonly label: string; readonly id: string; readonly contextValue: string; readonly groups: ISequence<ISCMResourceGroup>; // TODO@Joao: remove readonly onDidChangeResources: Event<void>; readonly rootUri?: URI; readonly count?: number; readonly commitTemplate: string; readonly onDidChangeCommitTemplate: Event<string>; readonly onDidChangeStatusBarCommands?: Event<Command[]>; readonly acceptInputCommand?: Command; readonly statusBarCommands?: Command[]; readonly onDidChange: Event<void>; getOriginalResource(uri: URI): Promise<URI | null>; } export const enum InputValidationType { Error = 0, Warning = 1, Information = 2 } export interface IInputValidation { message: string; type: InputValidationType; } export interface IInputValidator { (value: string, cursorPosition: number): Promise<IInputValidation | undefined>; } export enum SCMInputChangeReason { HistoryPrevious, HistoryNext } export interface ISCMInputChangeEvent { readonly value: string; readonly reason?: SCMInputChangeReason; } export interface ISCMInput { readonly repository: ISCMRepository; readonly value: string; setValue(value: string, fromKeyboard: boolean): void; readonly onDidChange: Event<ISCMInputChangeEvent>; placeholder: string; readonly onDidChangePlaceholder: Event<string>; validateInput: IInputValidator; readonly onDidChangeValidateInput: Event<void>; visible: boolean; readonly onDidChangeVisibility: Event<boolean>; showNextHistoryValue(): void; showPreviousHistoryValue(): void; } export interface ISCMRepository extends IDisposable { readonly provider: ISCMProvider; readonly input: ISCMInput; } export interface ISCMService { readonly _serviceBrand: undefined; readonly onDidAddRepository: Event<ISCMRepository>; readonly onDidRemoveRepository: Event<ISCMRepository>; readonly repositories: ISCMRepository[]; registerSCMProvider(provider: ISCMProvider): ISCMRepository; } export interface ISCMTitleMenu { readonly actions: IAction[]; readonly secondaryActions: IAction[]; readonly onDidChangeTitle: Event<void>; readonly menu: IMenu; } export interface ISCMRepositoryMenus { readonly titleMenu: ISCMTitleMenu; readonly repositoryMenu: IMenu; getResourceGroupMenu(group: ISCMResourceGroup): IMenu; getResourceMenu(resource: ISCMResource): IMenu; getResourceFolderMenu(group: ISCMResourceGroup): IMenu; } export interface ISCMMenus { getRepositoryMenus(provider: ISCMProvider): ISCMRepositoryMenus; } export const ISCMViewService = createDecorator<ISCMViewService>('scmView'); export interface ISCMViewVisibleRepositoryChangeEvent { readonly added: Iterable<ISCMRepository>; readonly removed: Iterable<ISCMRepository>; } export interface ISCMViewService { readonly _serviceBrand: undefined; readonly menus: ISCMMenus; visibleRepositories: ISCMRepository[]; readonly onDidChangeVisibleRepositories: Event<ISCMViewVisibleRepositoryChangeEvent>; isVisible(repository: ISCMRepository): boolean; toggleVisibility(repository: ISCMRepository, visible?: boolean): void; readonly focusedRepository: ISCMRepository | undefined; readonly onDidFocusRepository: Event<ISCMRepository | undefined>; focus(repository: ISCMRepository): void; }
src/vs/workbench/contrib/scm/common/scm.ts
0
https://github.com/microsoft/vscode/commit/07e3bcf7eacfb5a3f9c6e426fc977d176e40a726
[ 0.04359486326575279, 0.0026287250220775604, 0.00016574267647229135, 0.00017267995281144977, 0.00993704330176115 ]
{ "id": 6, "code_window": [ "\t}\n", "\n", "\tprivate getActions(): IAction[] {\n", "\t\treturn [\n", "\t\t\t{\n", "\t\t\t\tchecked: this.filters.currentDocumentOnly.value,\n", "\t\t\t\tclass: undefined,\n", "\t\t\t\tenabled: true,\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t...[\n", "\t\t\t\t{ v: TestExplorerStateFilter.OnlyFailed, label: localize('testing.filters.showOnlyFailed', \"Show Only Failed Tests\") },\n", "\t\t\t\t{ v: TestExplorerStateFilter.OnlyExecuted, label: localize('testing.filters.showOnlyExecuted', \"Show Only Executed Tests\") },\n", "\t\t\t\t{ v: TestExplorerStateFilter.All, label: localize('testing.filters.showAll', \"Show All Tests\") },\n", "\t\t\t].map(({ v, label }) => ({\n", "\t\t\t\tchecked: this.filters.stateFilter.value === v,\n", "\t\t\t\tclass: undefined,\n", "\t\t\t\tenabled: true,\n", "\t\t\t\tid: v,\n", "\t\t\t\tlabel,\n", "\t\t\t\trun: async () => this.filters.stateFilter.value = v,\n", "\t\t\t\ttooltip: '',\n", "\t\t\t\tdispose: () => null\n", "\t\t\t})),\n", "\t\t\tnew Separator(),\n" ], "file_path": "src/vs/workbench/contrib/testing/browser/testingExplorerFilter.ts", "type": "add", "edit_start_line_idx": 200 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { createDecorator } from 'vs/platform/instantiation/common/instantiation'; import { ClassifiedEvent, StrictPropertyCheck, GDPRClassification } from 'vs/platform/telemetry/common/gdprTypings'; export const ITelemetryService = createDecorator<ITelemetryService>('telemetryService'); export interface ITelemetryInfo { sessionId: string; machineId: string; instanceId: string; msftInternal?: boolean; } export interface ITelemetryData { from?: string; target?: string; [key: string]: any; } export interface ITelemetryService { /** * Whether error telemetry will get sent. If false, `publicLogError` will no-op. */ readonly sendErrorTelemetry: boolean; readonly _serviceBrand: undefined; /** * Sends a telemetry event that has been privacy approved. * Do not call this unless you have been given approval. */ publicLog(eventName: string, data?: ITelemetryData, anonymizeFilePaths?: boolean): Promise<void>; publicLog2<E extends ClassifiedEvent<T> = never, T extends GDPRClassification<T> = never>(eventName: string, data?: StrictPropertyCheck<T, E>, anonymizeFilePaths?: boolean): Promise<void>; publicLogError(errorEventName: string, data?: ITelemetryData): Promise<void>; publicLogError2<E extends ClassifiedEvent<T> = never, T extends GDPRClassification<T> = never>(eventName: string, data?: StrictPropertyCheck<T, E>): Promise<void>; setEnabled(value: boolean): void; getTelemetryInfo(): Promise<ITelemetryInfo>; setExperimentProperty(name: string, value: string): void; isOptedIn: boolean; } // Keys export const instanceStorageKey = 'telemetry.instanceId'; export const currentSessionDateStorageKey = 'telemetry.currentSessionDate'; export const firstSessionDateStorageKey = 'telemetry.firstSessionDate'; export const lastSessionDateStorageKey = 'telemetry.lastSessionDate'; export const machineIdKey = 'telemetry.machineId';
src/vs/platform/telemetry/common/telemetry.ts
0
https://github.com/microsoft/vscode/commit/07e3bcf7eacfb5a3f9c6e426fc977d176e40a726
[ 0.0002770910214167088, 0.00019074413285125047, 0.00016559718642383814, 0.00017288228264078498, 0.000039185615605674684 ]
{ "id": 6, "code_window": [ "\t}\n", "\n", "\tprivate getActions(): IAction[] {\n", "\t\treturn [\n", "\t\t\t{\n", "\t\t\t\tchecked: this.filters.currentDocumentOnly.value,\n", "\t\t\t\tclass: undefined,\n", "\t\t\t\tenabled: true,\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t...[\n", "\t\t\t\t{ v: TestExplorerStateFilter.OnlyFailed, label: localize('testing.filters.showOnlyFailed', \"Show Only Failed Tests\") },\n", "\t\t\t\t{ v: TestExplorerStateFilter.OnlyExecuted, label: localize('testing.filters.showOnlyExecuted', \"Show Only Executed Tests\") },\n", "\t\t\t\t{ v: TestExplorerStateFilter.All, label: localize('testing.filters.showAll', \"Show All Tests\") },\n", "\t\t\t].map(({ v, label }) => ({\n", "\t\t\t\tchecked: this.filters.stateFilter.value === v,\n", "\t\t\t\tclass: undefined,\n", "\t\t\t\tenabled: true,\n", "\t\t\t\tid: v,\n", "\t\t\t\tlabel,\n", "\t\t\t\trun: async () => this.filters.stateFilter.value = v,\n", "\t\t\t\ttooltip: '',\n", "\t\t\t\tdispose: () => null\n", "\t\t\t})),\n", "\t\t\tnew Separator(),\n" ], "file_path": "src/vs/workbench/contrib/testing/browser/testingExplorerFilter.ts", "type": "add", "edit_start_line_idx": 200 }
struct Foo { Foo(); int a; int b; int c; }; Foo::Foo() : a(1), // b(2), c(3) {}
extensions/vscode-colorize-tests/test/colorize-fixtures/test-80644.cpp
0
https://github.com/microsoft/vscode/commit/07e3bcf7eacfb5a3f9c6e426fc977d176e40a726
[ 0.00017755135195329785, 0.00017477832443546504, 0.00017200529691763222, 0.00017477832443546504, 0.0000027730275178328156 ]
{ "id": 7, "code_window": [ "import { testingStatesToIcons } from 'vs/workbench/contrib/testing/browser/icons';\n", "import { ITestExplorerFilterState, TestExplorerFilterState, TestingExplorerFilter } from 'vs/workbench/contrib/testing/browser/testingExplorerFilter';\n", "import { ITestingPeekOpener, TestingOutputPeekController } from 'vs/workbench/contrib/testing/browser/testingOutputPeek';\n", "import { TestExplorerViewMode, TestExplorerViewSorting, Testing, testStateNames } from 'vs/workbench/contrib/testing/common/constants';\n", "import { TestingContextKeys } from 'vs/workbench/contrib/testing/common/testingContextKeys';\n", "import { cmpPriority, isFailedState } from 'vs/workbench/contrib/testing/common/testingStates';\n", "import { ITestResultService, sumCounts, TestStateCount } from 'vs/workbench/contrib/testing/common/testResultService';\n", "import { ITestService } from 'vs/workbench/contrib/testing/common/testService';\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { TestExplorerStateFilter, TestExplorerViewMode, TestExplorerViewSorting, Testing, testStateNames } from 'vs/workbench/contrib/testing/common/constants';\n" ], "file_path": "src/vs/workbench/contrib/testing/browser/testingExplorerView.ts", "type": "replace", "edit_start_line_idx": 53 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as dom from 'vs/base/browser/dom'; import { ActionBar } from 'vs/base/browser/ui/actionbar/actionbar'; import * as aria from 'vs/base/browser/ui/aria/aria'; import { IIdentityProvider, IKeyboardNavigationLabelProvider, IListVirtualDelegate } from 'vs/base/browser/ui/list/list'; import { DefaultKeyboardNavigationDelegate, IListAccessibilityProvider } from 'vs/base/browser/ui/list/listWidget'; import { ICompressedTreeNode } from 'vs/base/browser/ui/tree/compressedObjectTreeModel'; import { ObjectTree } from 'vs/base/browser/ui/tree/objectTree'; import { ITreeEvent, ITreeFilter, ITreeNode, ITreeRenderer, ITreeSorter, TreeFilterResult, TreeVisibility } from 'vs/base/browser/ui/tree/tree'; import { Action, IAction, IActionViewItem } from 'vs/base/common/actions'; import { DeferredPromise } from 'vs/base/common/async'; import { Color, RGBA } from 'vs/base/common/color'; import { throttle } from 'vs/base/common/decorators'; import { Event } from 'vs/base/common/event'; import { FuzzyScore } from 'vs/base/common/filters'; import { splitGlobAware } from 'vs/base/common/glob'; import { Iterable } from 'vs/base/common/iterator'; import { Disposable, DisposableStore, MutableDisposable, toDisposable } from 'vs/base/common/lifecycle'; import { URI } from 'vs/base/common/uri'; import 'vs/css!./media/testing'; import { ICodeEditor, isCodeEditor } from 'vs/editor/browser/editorBrowser'; import { ICodeEditorService } from 'vs/editor/browser/services/codeEditorService'; import { localize } from 'vs/nls'; import { MenuEntryActionViewItem } from 'vs/platform/actions/browser/menuEntryActionViewItem'; import { MenuItemAction } from 'vs/platform/actions/common/actions'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { IContextMenuService } from 'vs/platform/contextview/browser/contextView'; import { FileKind } from 'vs/platform/files/common/files'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { WorkbenchObjectTree } from 'vs/platform/list/browser/listService'; import { IOpenerService } from 'vs/platform/opener/common/opener'; import { IProgress, IProgressService, IProgressStep } from 'vs/platform/progress/common/progress'; import { IStorageService, StorageScope, StorageTarget } from 'vs/platform/storage/common/storage'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { foreground } from 'vs/platform/theme/common/colorRegistry'; import { IThemeService, registerThemingParticipant, ThemeIcon } from 'vs/platform/theme/common/themeService'; import { TestRunState } from 'vs/workbench/api/common/extHostTypes'; import { IResourceLabel, IResourceLabelOptions, IResourceLabelProps, ResourceLabels } from 'vs/workbench/browser/labels'; import { ViewPane } from 'vs/workbench/browser/parts/views/viewPane'; import { IViewletViewOptions } from 'vs/workbench/browser/parts/views/viewsViewlet'; import { IViewDescriptorService, ViewContainerLocation } from 'vs/workbench/common/views'; import { ITestTreeElement, ITestTreeProjection } from 'vs/workbench/contrib/testing/browser/explorerProjections'; import { HierarchicalByLocationProjection } from 'vs/workbench/contrib/testing/browser/explorerProjections/hierarchalByLocation'; import { HierarchicalByNameProjection } from 'vs/workbench/contrib/testing/browser/explorerProjections/hierarchalByName'; import { testingStatesToIcons } from 'vs/workbench/contrib/testing/browser/icons'; import { ITestExplorerFilterState, TestExplorerFilterState, TestingExplorerFilter } from 'vs/workbench/contrib/testing/browser/testingExplorerFilter'; import { ITestingPeekOpener, TestingOutputPeekController } from 'vs/workbench/contrib/testing/browser/testingOutputPeek'; import { TestExplorerViewMode, TestExplorerViewSorting, Testing, testStateNames } from 'vs/workbench/contrib/testing/common/constants'; import { TestingContextKeys } from 'vs/workbench/contrib/testing/common/testingContextKeys'; import { cmpPriority, isFailedState } from 'vs/workbench/contrib/testing/common/testingStates'; import { ITestResultService, sumCounts, TestStateCount } from 'vs/workbench/contrib/testing/common/testResultService'; import { ITestService } from 'vs/workbench/contrib/testing/common/testService'; import { IWorkspaceTestCollectionService, TestSubscriptionListener } from 'vs/workbench/contrib/testing/common/workspaceTestCollectionService'; import { IActivityService, NumberBadge, ProgressBadge } from 'vs/workbench/services/activity/common/activity'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { DebugAction, RunAction } from './testExplorerActions'; export class TestingExplorerView extends ViewPane { public viewModel!: TestingExplorerViewModel; private filterActionBar = this._register(new MutableDisposable()); private readonly currentSubscription = new MutableDisposable<TestSubscriptionListener>(); private container!: HTMLElement; private finishDiscovery?: () => void; private readonly location = TestingContextKeys.explorerLocation.bindTo(this.contextKeyService);; constructor( options: IViewletViewOptions, @IWorkspaceTestCollectionService private readonly testCollection: IWorkspaceTestCollectionService, @ITestService private readonly testService: ITestService, @IProgressService private readonly progress: IProgressService, @IContextMenuService contextMenuService: IContextMenuService, @IKeybindingService keybindingService: IKeybindingService, @IConfigurationService configurationService: IConfigurationService, @IInstantiationService instantiationService: IInstantiationService, @IViewDescriptorService viewDescriptorService: IViewDescriptorService, @IContextKeyService contextKeyService: IContextKeyService, @IOpenerService openerService: IOpenerService, @IThemeService themeService: IThemeService, @ITelemetryService telemetryService: ITelemetryService, ) { super(options, keybindingService, contextMenuService, configurationService, contextKeyService, viewDescriptorService, instantiationService, openerService, themeService, telemetryService); this._register(testService.onDidChangeProviders(() => this._onDidChangeViewWelcomeState.fire())); this.location.set(viewDescriptorService.getViewLocationById(Testing.ExplorerViewId) ?? ViewContainerLocation.Sidebar); } /** * @override */ public shouldShowWelcome() { return this.testService.providers === 0; } /** * @override */ protected renderBody(container: HTMLElement): void { super.renderBody(container); this.container = dom.append(container, dom.$('.test-explorer')); if (this.location.get() === ViewContainerLocation.Sidebar) { this.filterActionBar.value = this.createFilterActionBar(); } const messagesContainer = dom.append(this.container, dom.$('.test-explorer-messages')); this._register(this.instantiationService.createInstance(TestRunProgress, messagesContainer, this.getProgressLocation())); const listContainer = dom.append(this.container, dom.$('.test-explorer-tree')); this.viewModel = this.instantiationService.createInstance(TestingExplorerViewModel, listContainer, this.onDidChangeBodyVisibility, this.currentSubscription.value); this._register(this.viewModel); this._register(this.onDidChangeBodyVisibility(visible => { if (!visible && this.currentSubscription) { this.currentSubscription.value = undefined; this.viewModel.replaceSubscription(undefined); } else if (visible && !this.currentSubscription.value) { this.currentSubscription.value = this.createSubscription(); this.viewModel.replaceSubscription(this.currentSubscription.value); } })); } /** * @override */ public getActionViewItem(action: IAction): IActionViewItem | undefined { if (action.id === Testing.FilterActionId) { return this.instantiationService.createInstance(TestingExplorerFilter, action); } return super.getActionViewItem(action); } /** * @override */ public saveState() { super.saveState(); } private createFilterActionBar() { const bar = new ActionBar(this.container, { actionViewItemProvider: action => this.getActionViewItem(action) }); bar.push(new Action(Testing.FilterActionId)); bar.getContainer().classList.add('testing-filter-action-bar'); return bar; } private updateDiscoveryProgress(busy: number) { if (!busy && this.finishDiscovery) { this.finishDiscovery(); this.finishDiscovery = undefined; } else if (busy && !this.finishDiscovery) { const promise = new Promise<void>(resolve => { this.finishDiscovery = resolve; }); this.progress.withProgress({ location: this.getProgressLocation() }, () => promise); } } /** * @override */ protected layoutBody(height: number, width: number): void { super.layoutBody(height, width); this.container.style.height = `${height}px`; this.viewModel.layout(height, width); } private createSubscription() { const handle = this.testCollection.subscribeToWorkspaceTests(); handle.subscription.onBusyProvidersChange(() => this.updateDiscoveryProgress(handle.subscription.busyProviders)); return handle; } } export class TestingExplorerViewModel extends Disposable { public tree: ObjectTree<ITestTreeElement, FuzzyScore>; private filter: TestsFilter; public projection!: ITestTreeProjection; private readonly _viewMode = TestingContextKeys.viewMode.bindTo(this.contextKeyService); private readonly _viewSorting = TestingContextKeys.viewSorting.bindTo(this.contextKeyService); /** * Fires when the selected tests change. */ public readonly onDidChangeSelection: Event<ITreeEvent<ITestTreeElement | null>>; public get viewMode() { return this._viewMode.get() ?? TestExplorerViewMode.Tree; } public set viewMode(newMode: TestExplorerViewMode) { if (newMode === this._viewMode.get()) { return; } this._viewMode.set(newMode); this.updatePreferredProjection(); this.storageService.store('testing.viewMode', newMode, StorageScope.WORKSPACE, StorageTarget.USER); } public get viewSorting() { return this._viewSorting.get() ?? TestExplorerViewSorting.ByLocation; } public set viewSorting(newSorting: TestExplorerViewSorting) { if (newSorting === this._viewSorting.get()) { return; } this._viewSorting.set(newSorting); this.tree.resort(null); this.storageService.store('testing.viewSorting', newSorting, StorageScope.WORKSPACE, StorageTarget.USER); } constructor( listContainer: HTMLElement, onDidChangeVisibility: Event<boolean>, private listener: TestSubscriptionListener | undefined, @ITestExplorerFilterState filterState: TestExplorerFilterState, @IInstantiationService private readonly instantiationService: IInstantiationService, @IEditorService private readonly editorService: IEditorService, @IStorageService private readonly storageService: IStorageService, @IContextKeyService private readonly contextKeyService: IContextKeyService, @ITestResultService private readonly testResults: ITestResultService, @ITestingPeekOpener private readonly peekOpener: ITestingPeekOpener, ) { super(); this._viewMode.set(this.storageService.get('testing.viewMode', StorageScope.WORKSPACE, TestExplorerViewMode.Tree) as TestExplorerViewMode); this._viewSorting.set(this.storageService.get('testing.viewSorting', StorageScope.WORKSPACE, TestExplorerViewSorting.ByLocation) as TestExplorerViewSorting); const labels = this._register(instantiationService.createInstance(ResourceLabels, { onDidChangeVisibility: onDidChangeVisibility })); this.filter = this.instantiationService.createInstance(TestsFilter); this.tree = instantiationService.createInstance( WorkbenchObjectTree, 'Test Explorer List', listContainer, new ListDelegate(), [ instantiationService.createInstance(TestsRenderer, labels) ], { simpleKeyboardNavigation: true, identityProvider: instantiationService.createInstance(IdentityProvider), hideTwistiesOfChildlessElements: true, sorter: instantiationService.createInstance(TreeSorter, this), keyboardNavigationLabelProvider: instantiationService.createInstance(TreeKeyboardNavigationLabelProvider), accessibilityProvider: instantiationService.createInstance(ListAccessibilityProvider), filter: this.filter, }) as WorkbenchObjectTree<ITestTreeElement, FuzzyScore>; this._register(Event.any(filterState.currentDocumentOnly.onDidChange, filterState.text.onDidChange)(this.tree.refilter, this.tree)); this._register(editorService.onDidActiveEditorChange(() => { if (filterState.currentDocumentOnly.value && editorService.activeEditor?.resource) { if (this.projection.hasTestInDocument(editorService.activeEditor.resource)) { this.filter.filterToUri(editorService.activeEditor.resource); this.tree.refilter(); } } })); this._register(this.tree); this._register(dom.addStandardDisposableListener(this.tree.getHTMLElement(), 'keydown', evt => { if (DefaultKeyboardNavigationDelegate.mightProducePrintableCharacter(evt)) { filterState.text.value = evt.browserEvent.key; filterState.focusInput(); } })); this.updatePreferredProjection(); this.onDidChangeSelection = this.tree.onDidChangeSelection; this._register(this.tree.onDidChangeSelection(evt => { const selected = evt.elements[0]; if (selected && evt.browserEvent) { this.openEditorForItem(selected); } })); const tracker = this._register(this.instantiationService.createInstance(CodeEditorTracker, this)); this._register(onDidChangeVisibility(visible => { if (visible) { tracker.activate(); } else { tracker.deactivate(); } })); this._register(testResults.onResultsChanged(() => { this.tree.resort(null); })); } /** * Re-layout the tree. */ public layout(height: number, width: number): void { this.tree.layout(height, width); } /** * Replaces the test listener and recalculates the tree. */ public replaceSubscription(listener: TestSubscriptionListener | undefined) { this.listener = listener; this.updatePreferredProjection(); } /** * Reveals and moves focus to the item. */ public async revealItem(item: ITestTreeElement, reveal = true): Promise<void> { if (!this.tree.hasElement(item)) { return; } const chain: ITestTreeElement[] = []; for (let parent = item.parentItem; parent; parent = parent.parentItem) { chain.push(parent); } for (const parent of chain.reverse()) { try { this.tree.expand(parent); } catch { // ignore if not present } } if (reveal === true && this.tree.getRelativeTop(item) === null) { // Don't scroll to the item if it's already visible, or if set not to. this.tree.reveal(item, 0.5); } this.tree.setFocus([item]); this.tree.setSelection([item]); } /** * Collapse all items in the tree. */ public async collapseAll() { this.tree.collapseAll(); } /** * Opens an editor for the item. If there is a failure associated with the * test item, it will be shown. */ public async openEditorForItem(item: ITestTreeElement, preserveFocus = true) { if (await this.tryPeekError(item)) { return; } const location = item?.location; if (!location) { return; } const pane = await this.editorService.openEditor({ resource: location.uri, options: { selection: { startColumn: location.range.startColumn, startLineNumber: location.range.startLineNumber }, preserveFocus, }, }); // if the user selected a failed test and now they didn't, hide the peek const control = pane?.getControl(); if (isCodeEditor(control)) { TestingOutputPeekController.get(control).removePeek(); } } /** * Tries to peek the first test error, if the item is in a failed state. */ private async tryPeekError(item: ITestTreeElement) { const lookup = item.test && this.testResults.getStateByExtId(item.test.item.extId); return lookup && isFailedState(lookup[1].state.state) ? this.peekOpener.tryPeekFirstError(lookup[0], lookup[1], { preserveFocus: true }) : false; } private updatePreferredProjection() { this.projection?.dispose(); if (!this.listener) { this.tree.setChildren(null, []); return; } if (this._viewMode.get() === TestExplorerViewMode.List) { this.projection = this.instantiationService.createInstance(HierarchicalByNameProjection, this.listener); } else { this.projection = this.instantiationService.createInstance(HierarchicalByLocationProjection, this.listener); } this.projection.onUpdate(this.deferUpdate, this); this.projection.applyTo(this.tree); } @throttle(200) private deferUpdate() { this.projection.applyTo(this.tree); } /** * Gets the selected tests from the tree. */ public getSelectedTests() { return this.tree.getSelection(); } } class CodeEditorTracker { private store = new DisposableStore(); private lastRevealed?: ITestTreeElement; constructor( private readonly model: TestingExplorerViewModel, @ICodeEditorService private readonly codeEditorService: ICodeEditorService, ) { } public activate() { const editorStores = new Set<DisposableStore>(); this.store.add(toDisposable(() => { for (const store of editorStores) { store.dispose(); } })); const register = (editor: ICodeEditor) => { const store = new DisposableStore(); editorStores.add(store); store.add(editor.onDidChangeCursorPosition(evt => { const uri = editor.getModel()?.uri; if (!uri) { return; } const test = this.model.projection.getTestAtPosition(uri, evt.position); if (test && test !== this.lastRevealed) { this.model.revealItem(test); this.lastRevealed = test; } })); editor.onDidDispose(() => { store.dispose(); editorStores.delete(store); }); }; this.store.add(this.codeEditorService.onCodeEditorAdd(register)); this.codeEditorService.listCodeEditors().forEach(register); } public deactivate() { this.store.dispose(); this.store = new DisposableStore(); } public dispose() { this.store.dispose(); } } const enum FilterResult { Exclude, Inherit, Include, } class TestsFilter implements ITreeFilter<ITestTreeElement> { private lastText?: string; private filters: [include: boolean, value: string][] | undefined; private _filterToUri: string | undefined; constructor(@ITestExplorerFilterState private readonly state: ITestExplorerFilterState) { } /** * Parses and updates the tree filter. Supports lists of patterns that can be !negated. */ private setFilter(text: string) { this.lastText = text; text = text.trim(); if (!text) { this.filters = undefined; return; } this.filters = []; for (const filter of splitGlobAware(text, ',').map(s => s.trim()).filter(s => !!s.length)) { if (filter.startsWith('!')) { this.filters.push([false, filter.slice(1).toLowerCase()]); } else { this.filters.push([true, filter.toLowerCase()]); } } } public filterToUri(uri: URI) { this._filterToUri = uri.toString(); } /** * @inheritdoc */ public filter(element: ITestTreeElement): TreeFilterResult<void> { if (this.state.text.value !== this.lastText) { this.setFilter(this.state.text.value); } switch (Math.min(this.testFilterText(element), this.testLocation(element))) { case FilterResult.Exclude: return TreeVisibility.Hidden; case FilterResult.Include: return TreeVisibility.Visible; default: return TreeVisibility.Recurse; } } private testLocation(element: ITestTreeElement): FilterResult { if (!this._filterToUri || !this.state.currentDocumentOnly.value) { return FilterResult.Include; } for (let e: ITestTreeElement | null = element; e; e = e!.parentItem) { if (!e.location) { continue; } return e.location.uri.toString() === this._filterToUri ? FilterResult.Include : FilterResult.Exclude; } return FilterResult.Inherit; } private testFilterText(element: ITestTreeElement) { if (!this.filters) { return FilterResult.Include; } for (let e: ITestTreeElement | null = element; e; e = e.parentItem) { // start as included if the first glob is a negation let included = this.filters[0][0] === false ? FilterResult.Exclude : FilterResult.Inherit; const data = e.label.toLowerCase(); for (const [include, filter] of this.filters) { if (data.includes(filter)) { included = include ? FilterResult.Include : FilterResult.Exclude; } } if (included !== FilterResult.Inherit) { return included; } } return FilterResult.Inherit; } } class TreeSorter implements ITreeSorter<ITestTreeElement> { constructor(private readonly viewModel: TestingExplorerViewModel) { } public compare(a: ITestTreeElement, b: ITestTreeElement): number { let delta = cmpPriority(a.state, b.state); if (delta !== 0) { return delta; } if (this.viewModel.viewSorting === TestExplorerViewSorting.ByLocation && a.location && b.location && a.location.uri.toString() === b.location.uri.toString()) { delta = a.location.range.startLineNumber - b.location.range.startLineNumber; if (delta !== 0) { return delta; } } return a.label.localeCompare(b.label); } } class ListAccessibilityProvider implements IListAccessibilityProvider<ITestTreeElement> { getWidgetAriaLabel(): string { return localize('testExplorer', "Test Explorer"); } getAriaLabel(element: ITestTreeElement): string { let label = localize({ key: 'testing.treeElementLabel', comment: ['label then the unit tests state, for example "Addition Tests (Running)"'], }, '{0} ({1})', element.label, testStateNames[element.state]); if (element.retired) { label = localize({ key: 'testing.treeElementLabelOutdated', comment: ['{0} is the original label in testing.treeElementLabel'], }, '{0}, outdated result', label, testStateNames[element.state]); } return label; } } class TreeKeyboardNavigationLabelProvider implements IKeyboardNavigationLabelProvider<ITestTreeElement> { getKeyboardNavigationLabel(element: ITestTreeElement) { return element.label; } } class ListDelegate implements IListVirtualDelegate<ITestTreeElement> { getHeight(_element: ITestTreeElement) { return 22; } getTemplateId(_element: ITestTreeElement) { return TestsRenderer.ID; } } class IdentityProvider implements IIdentityProvider<ITestTreeElement> { public getId(element: ITestTreeElement) { return element.treeId; } } interface TestTemplateData { label: IResourceLabel; icon: HTMLElement; actionBar: ActionBar; } class TestsRenderer implements ITreeRenderer<ITestTreeElement, FuzzyScore, TestTemplateData> { public static readonly ID = 'testExplorer'; constructor( private labels: ResourceLabels, @IInstantiationService private readonly instantiationService: IInstantiationService ) { } renderCompressedElements(node: ITreeNode<ICompressedTreeNode<ITestTreeElement>, FuzzyScore>, index: number, templateData: TestTemplateData): void { const element = node.element.elements[node.element.elements.length - 1]; this.renderElementDirect(element, templateData); } get templateId(): string { return TestsRenderer.ID; } public renderTemplate(container: HTMLElement): TestTemplateData { const wrapper = dom.append(container, dom.$('.test-item')); const icon = dom.append(wrapper, dom.$('.computed-state')); const name = dom.append(wrapper, dom.$('.name')); const label = this.labels.create(name, { supportHighlights: true }); const actionBar = new ActionBar(wrapper, { actionViewItemProvider: action => action instanceof MenuItemAction ? this.instantiationService.createInstance(MenuEntryActionViewItem, action) : undefined }); return { label, actionBar, icon }; } public renderElement(node: ITreeNode<ITestTreeElement, FuzzyScore>, index: number, data: TestTemplateData): void { this.renderElementDirect(node.element, data); } private renderElementDirect(element: ITestTreeElement, data: TestTemplateData) { const label: IResourceLabelProps = { name: element.label }; const options: IResourceLabelOptions = {}; data.actionBar.clear(); const icon = testingStatesToIcons.get(element.state); data.icon.className = 'computed-state ' + (icon ? ThemeIcon.asClassName(icon) : ''); if (element.retired) { data.icon.className += ' retired'; } const test = element.test; if (test) { if (test.item.location) { label.resource = test.item.location.uri; } let title = element.label; for (let p = element.parentItem; p; p = p.parentItem) { title = `${p.label}, ${title}`; } options.title = title; options.fileKind = FileKind.FILE; label.description = element.description; } else { options.fileKind = FileKind.ROOT_FOLDER; } const running = element.state === TestRunState.Running; if (!Iterable.isEmpty(element.runnable)) { data.actionBar.push( this.instantiationService.createInstance(RunAction, element.runnable, running), { icon: true, label: false }, ); } if (!Iterable.isEmpty(element.debuggable)) { data.actionBar.push( this.instantiationService.createInstance(DebugAction, element.debuggable, running), { icon: true, label: false }, ); } data.label.setResource(label, options); } disposeTemplate(templateData: TestTemplateData): void { templateData.label.dispose(); templateData.actionBar.dispose(); } } type CountSummary = ReturnType<typeof collectCounts>; const collectCounts = (count: TestStateCount) => { const failed = count[TestRunState.Errored] + count[TestRunState.Failed]; const passed = count[TestRunState.Passed]; const skipped = count[TestRunState.Skipped]; return { passed, failed, runSoFar: passed + failed, totalWillBeRun: passed + failed + count[TestRunState.Queued] + count[TestRunState.Running], skipped, }; }; const getProgressText = ({ passed, runSoFar, skipped, failed }: CountSummary) => { let percent = passed / runSoFar * 100; if (failed > 0) { // fix: prevent from rounding to 100 if there's any failed test percent = Math.min(percent, 99.9); } if (skipped === 0) { return localize('testProgress', '{0}/{1} tests passed ({2}%)', passed, runSoFar, percent.toPrecision(3)); } else { return localize('testProgressWithSkip', '{0}/{1} tests passed ({2}%, {3} skipped)', passed, runSoFar, percent.toPrecision(3), skipped); } }; class TestRunProgress { private current?: { update: IProgress<IProgressStep>; deferred: DeferredPromise<void> }; private badge = new MutableDisposable(); private readonly resultLister = this.resultService.onResultsChanged(result => { if (!('started' in result)) { return; } this.updateProgress(); this.updateBadge(); result.started.onChange(this.throttledProgressUpdate, this); result.started.onComplete(() => { this.throttledProgressUpdate(); this.updateBadge(); }); }); constructor( private readonly messagesContainer: HTMLElement, private readonly location: string, @IProgressService private readonly progress: IProgressService, @ITestResultService private readonly resultService: ITestResultService, @IActivityService private readonly activityService: IActivityService, ) { } public dispose() { this.resultLister.dispose(); this.current?.deferred.complete(); this.badge.dispose(); } @throttle(200) private throttledProgressUpdate() { this.updateProgress(); } private updateProgress() { const running = this.resultService.results.filter(r => !r.isComplete); if (!running.length) { this.setIdleText(this.resultService.results[0]?.counts); this.current?.deferred.complete(); this.current = undefined; } else if (!this.current) { this.progress.withProgress({ location: this.location, total: 100 }, update => { this.current = { update, deferred: new DeferredPromise() }; this.updateProgress(); return this.current.deferred.p; }); } else { const counts = sumCounts(running.map(r => r.counts)); this.setRunningText(counts); const { runSoFar, totalWillBeRun } = collectCounts(counts); this.current.update.report({ increment: runSoFar, total: totalWillBeRun }); } } private setRunningText(counts: TestStateCount) { this.messagesContainer.dataset.state = 'running'; const collected = collectCounts(counts); if (collected.runSoFar === 0) { this.messagesContainer.innerText = localize('testResultStarting', 'Test run is starting...'); } else { this.messagesContainer.innerText = getProgressText(collected); } } private setIdleText(lastCount?: TestStateCount) { if (!lastCount) { this.messagesContainer.innerText = ''; } else { const collected = collectCounts(lastCount); this.messagesContainer.dataset.state = collected.failed ? 'failed' : 'running'; const doneMessage = getProgressText(collected); this.messagesContainer.innerText = doneMessage; aria.alert(doneMessage); } } private updateBadge() { this.badge.value = undefined; const result = this.resultService.results[0]; // currently running, or last run if (!result) { return; } if (!result.isComplete) { const badge = new ProgressBadge(() => localize('testBadgeRunning', 'Test run in progress')); this.badge.value = this.activityService.showViewActivity(Testing.ExplorerViewId, { badge, clazz: 'progress-badge' }); return; } const failures = result.counts[TestRunState.Failed] + result.counts[TestRunState.Errored]; if (failures === 0) { return; } const badge = new NumberBadge(failures, () => localize('testBadgeFailures', '{0} tests failed', failures)); this.badge.value = this.activityService.showViewActivity(Testing.ExplorerViewId, { badge }); } } registerThemingParticipant((theme, collector) => { if (theme.type === 'dark') { const foregroundColor = theme.getColor(foreground); if (foregroundColor) { const fgWithOpacity = new Color(new RGBA(foregroundColor.rgba.r, foregroundColor.rgba.g, foregroundColor.rgba.b, 0.65)); collector.addRule(`.test-explorer .test-explorer-messages { color: ${fgWithOpacity}; }`); } } });
src/vs/workbench/contrib/testing/browser/testingExplorerView.ts
1
https://github.com/microsoft/vscode/commit/07e3bcf7eacfb5a3f9c6e426fc977d176e40a726
[ 0.9963639378547668, 0.011567984707653522, 0.00016381546447519213, 0.00017234758706763387, 0.10498420894145966 ]
{ "id": 7, "code_window": [ "import { testingStatesToIcons } from 'vs/workbench/contrib/testing/browser/icons';\n", "import { ITestExplorerFilterState, TestExplorerFilterState, TestingExplorerFilter } from 'vs/workbench/contrib/testing/browser/testingExplorerFilter';\n", "import { ITestingPeekOpener, TestingOutputPeekController } from 'vs/workbench/contrib/testing/browser/testingOutputPeek';\n", "import { TestExplorerViewMode, TestExplorerViewSorting, Testing, testStateNames } from 'vs/workbench/contrib/testing/common/constants';\n", "import { TestingContextKeys } from 'vs/workbench/contrib/testing/common/testingContextKeys';\n", "import { cmpPriority, isFailedState } from 'vs/workbench/contrib/testing/common/testingStates';\n", "import { ITestResultService, sumCounts, TestStateCount } from 'vs/workbench/contrib/testing/common/testResultService';\n", "import { ITestService } from 'vs/workbench/contrib/testing/common/testService';\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { TestExplorerStateFilter, TestExplorerViewMode, TestExplorerViewSorting, Testing, testStateNames } from 'vs/workbench/contrib/testing/common/constants';\n" ], "file_path": "src/vs/workbench/contrib/testing/browser/testingExplorerView.ts", "type": "replace", "edit_start_line_idx": 53 }
/*--------------------------------------------------------------------------------------------- * 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 { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { FinalNewLineParticipant, TrimFinalNewLinesParticipant, TrimWhitespaceParticipant } from 'vs/workbench/contrib/codeEditor/browser/saveParticipants'; import { TestConfigurationService } from 'vs/platform/configuration/test/common/testConfigurationService'; import { workbenchInstantiationService, TestServiceAccessor } from 'vs/workbench/test/browser/workbenchTestServices'; import { toResource } from 'vs/base/test/common/utils'; import { Range } from 'vs/editor/common/core/range'; import { Selection } from 'vs/editor/common/core/selection'; import { TextFileEditorModel } from 'vs/workbench/services/textfile/common/textFileEditorModel'; import { IResolvedTextFileEditorModel, snapshotToString } from 'vs/workbench/services/textfile/common/textfiles'; import { SaveReason } from 'vs/workbench/common/editor'; import { TextFileEditorModelManager } from 'vs/workbench/services/textfile/common/textFileEditorModelManager'; suite('Save Participants', function () { let instantiationService: IInstantiationService; let accessor: TestServiceAccessor; setup(() => { instantiationService = workbenchInstantiationService(); accessor = instantiationService.createInstance(TestServiceAccessor); }); teardown(() => { (<TextFileEditorModelManager>accessor.textFileService.files).dispose(); }); test('insert final new line', async function () { const model = instantiationService.createInstance(TextFileEditorModel, toResource.call(this, '/path/final_new_line.txt'), 'utf8', undefined) as IResolvedTextFileEditorModel; await model.load(); const configService = new TestConfigurationService(); configService.setUserConfiguration('files', { 'insertFinalNewline': true }); const participant = new FinalNewLineParticipant(configService, undefined!); // No new line for empty lines let lineContent = ''; model.textEditorModel.setValue(lineContent); await participant.participate(model, { reason: SaveReason.EXPLICIT }); assert.strictEqual(snapshotToString(model.createSnapshot()!), lineContent); // No new line if last line already empty lineContent = `Hello New Line${model.textEditorModel.getEOL()}`; model.textEditorModel.setValue(lineContent); await participant.participate(model, { reason: SaveReason.EXPLICIT }); assert.strictEqual(snapshotToString(model.createSnapshot()!), lineContent); // New empty line added (single line) lineContent = 'Hello New Line'; model.textEditorModel.setValue(lineContent); await participant.participate(model, { reason: SaveReason.EXPLICIT }); assert.strictEqual(snapshotToString(model.createSnapshot()!), `${lineContent}${model.textEditorModel.getEOL()}`); // New empty line added (multi line) lineContent = `Hello New Line${model.textEditorModel.getEOL()}Hello New Line${model.textEditorModel.getEOL()}Hello New Line`; model.textEditorModel.setValue(lineContent); await participant.participate(model, { reason: SaveReason.EXPLICIT }); assert.strictEqual(snapshotToString(model.createSnapshot()!), `${lineContent}${model.textEditorModel.getEOL()}`); }); test('trim final new lines', async function () { const model = instantiationService.createInstance(TextFileEditorModel, toResource.call(this, '/path/trim_final_new_line.txt'), 'utf8', undefined) as IResolvedTextFileEditorModel; await model.load(); const configService = new TestConfigurationService(); configService.setUserConfiguration('files', { 'trimFinalNewlines': true }); const participant = new TrimFinalNewLinesParticipant(configService, undefined!); const textContent = 'Trim New Line'; const eol = `${model.textEditorModel.getEOL()}`; // No new line removal if last line is not new line let lineContent = `${textContent}`; model.textEditorModel.setValue(lineContent); await participant.participate(model, { reason: SaveReason.EXPLICIT }); assert.strictEqual(snapshotToString(model.createSnapshot()!), lineContent); // No new line removal if last line is single new line lineContent = `${textContent}${eol}`; model.textEditorModel.setValue(lineContent); await participant.participate(model, { reason: SaveReason.EXPLICIT }); assert.strictEqual(snapshotToString(model.createSnapshot()!), lineContent); // Remove new line (single line with two new lines) lineContent = `${textContent}${eol}${eol}`; model.textEditorModel.setValue(lineContent); await participant.participate(model, { reason: SaveReason.EXPLICIT }); assert.strictEqual(snapshotToString(model.createSnapshot()!), `${textContent}${eol}`); // Remove new lines (multiple lines with multiple new lines) lineContent = `${textContent}${eol}${textContent}${eol}${eol}${eol}`; model.textEditorModel.setValue(lineContent); await participant.participate(model, { reason: SaveReason.EXPLICIT }); assert.strictEqual(snapshotToString(model.createSnapshot()!), `${textContent}${eol}${textContent}${eol}`); }); test('trim final new lines bug#39750', async function () { const model = instantiationService.createInstance(TextFileEditorModel, toResource.call(this, '/path/trim_final_new_line.txt'), 'utf8', undefined) as IResolvedTextFileEditorModel; await model.load(); const configService = new TestConfigurationService(); configService.setUserConfiguration('files', { 'trimFinalNewlines': true }); const participant = new TrimFinalNewLinesParticipant(configService, undefined!); const textContent = 'Trim New Line'; // single line let lineContent = `${textContent}`; model.textEditorModel.setValue(lineContent); // apply edits and push to undo stack. let textEdits = [{ range: new Range(1, 14, 1, 14), text: '.', forceMoveMarkers: false }]; model.textEditorModel.pushEditOperations([new Selection(1, 14, 1, 14)], textEdits, () => { return [new Selection(1, 15, 1, 15)]; }); // undo await model.textEditorModel.undo(); assert.strictEqual(snapshotToString(model.createSnapshot()!), `${textContent}`); // trim final new lines should not mess the undo stack await participant.participate(model, { reason: SaveReason.EXPLICIT }); await model.textEditorModel.redo(); assert.strictEqual(snapshotToString(model.createSnapshot()!), `${textContent}.`); }); test('trim final new lines bug#46075', async function () { const model = instantiationService.createInstance(TextFileEditorModel, toResource.call(this, '/path/trim_final_new_line.txt'), 'utf8', undefined) as IResolvedTextFileEditorModel; await model.load(); const configService = new TestConfigurationService(); configService.setUserConfiguration('files', { 'trimFinalNewlines': true }); const participant = new TrimFinalNewLinesParticipant(configService, undefined!); const textContent = 'Test'; const eol = `${model.textEditorModel.getEOL()}`; let content = `${textContent}${eol}${eol}`; model.textEditorModel.setValue(content); // save many times for (let i = 0; i < 10; i++) { await participant.participate(model, { reason: SaveReason.EXPLICIT }); } // confirm trimming assert.strictEqual(snapshotToString(model.createSnapshot()!), `${textContent}${eol}`); // undo should go back to previous content immediately await model.textEditorModel.undo(); assert.strictEqual(snapshotToString(model.createSnapshot()!), `${textContent}${eol}${eol}`); await model.textEditorModel.redo(); assert.strictEqual(snapshotToString(model.createSnapshot()!), `${textContent}${eol}`); }); test('trim whitespace', async function () { const model = instantiationService.createInstance(TextFileEditorModel, toResource.call(this, '/path/trim_final_new_line.txt'), 'utf8', undefined) as IResolvedTextFileEditorModel; await model.load(); const configService = new TestConfigurationService(); configService.setUserConfiguration('files', { 'trimTrailingWhitespace': true }); const participant = new TrimWhitespaceParticipant(configService, undefined!); const textContent = 'Test'; let content = `${textContent} `; model.textEditorModel.setValue(content); // save many times for (let i = 0; i < 10; i++) { await participant.participate(model, { reason: SaveReason.EXPLICIT }); } // confirm trimming assert.strictEqual(snapshotToString(model.createSnapshot()!), `${textContent}`); }); });
src/vs/workbench/contrib/codeEditor/test/browser/saveParticipant.test.ts
0
https://github.com/microsoft/vscode/commit/07e3bcf7eacfb5a3f9c6e426fc977d176e40a726
[ 0.00017766329983714968, 0.000174444547155872, 0.00016970369324553758, 0.00017467702855356038, 0.0000021000012111471733 ]
{ "id": 7, "code_window": [ "import { testingStatesToIcons } from 'vs/workbench/contrib/testing/browser/icons';\n", "import { ITestExplorerFilterState, TestExplorerFilterState, TestingExplorerFilter } from 'vs/workbench/contrib/testing/browser/testingExplorerFilter';\n", "import { ITestingPeekOpener, TestingOutputPeekController } from 'vs/workbench/contrib/testing/browser/testingOutputPeek';\n", "import { TestExplorerViewMode, TestExplorerViewSorting, Testing, testStateNames } from 'vs/workbench/contrib/testing/common/constants';\n", "import { TestingContextKeys } from 'vs/workbench/contrib/testing/common/testingContextKeys';\n", "import { cmpPriority, isFailedState } from 'vs/workbench/contrib/testing/common/testingStates';\n", "import { ITestResultService, sumCounts, TestStateCount } from 'vs/workbench/contrib/testing/common/testResultService';\n", "import { ITestService } from 'vs/workbench/contrib/testing/common/testService';\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { TestExplorerStateFilter, TestExplorerViewMode, TestExplorerViewSorting, Testing, testStateNames } from 'vs/workbench/contrib/testing/common/constants';\n" ], "file_path": "src/vs/workbench/contrib/testing/browser/testingExplorerView.ts", "type": "replace", "edit_start_line_idx": 53 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { defaultGenerator } from 'vs/base/common/idGenerator'; import { IFileQuery } from 'vs/workbench/services/search/common/search'; import { equals } from 'vs/base/common/objects'; enum LoadingPhase { Created = 1, Loading = 2, Loaded = 3, Errored = 4, Disposed = 5 } export class FileQueryCacheState { private readonly _cacheKey = defaultGenerator.nextId(); get cacheKey(): string { if (this.loadingPhase === LoadingPhase.Loaded || !this.previousCacheState) { return this._cacheKey; } return this.previousCacheState.cacheKey; } get isLoaded(): boolean { const isLoaded = this.loadingPhase === LoadingPhase.Loaded; return isLoaded || !this.previousCacheState ? isLoaded : this.previousCacheState.isLoaded; } get isUpdating(): boolean { const isUpdating = this.loadingPhase === LoadingPhase.Loading; return isUpdating || !this.previousCacheState ? isUpdating : this.previousCacheState.isUpdating; } private readonly query = this.cacheQuery(this._cacheKey); private loadingPhase = LoadingPhase.Created; private loadPromise: Promise<void> | undefined; constructor( private cacheQuery: (cacheKey: string) => IFileQuery, private loadFn: (query: IFileQuery) => Promise<any>, private disposeFn: (cacheKey: string) => Promise<void>, private previousCacheState: FileQueryCacheState | undefined ) { if (this.previousCacheState) { const current = Object.assign({}, this.query, { cacheKey: null }); const previous = Object.assign({}, this.previousCacheState.query, { cacheKey: null }); if (!equals(current, previous)) { this.previousCacheState.dispose(); this.previousCacheState = undefined; } } } load(): FileQueryCacheState { if (this.isUpdating) { return this; } this.loadingPhase = LoadingPhase.Loading; this.loadPromise = (async () => { try { await this.loadFn(this.query); this.loadingPhase = LoadingPhase.Loaded; if (this.previousCacheState) { this.previousCacheState.dispose(); this.previousCacheState = undefined; } } catch (error) { this.loadingPhase = LoadingPhase.Errored; throw error; } })(); return this; } dispose(): void { if (this.loadPromise) { (async () => { try { await this.loadPromise; } catch (error) { // ignore } this.loadingPhase = LoadingPhase.Disposed; this.disposeFn(this._cacheKey); })(); } else { this.loadingPhase = LoadingPhase.Disposed; } if (this.previousCacheState) { this.previousCacheState.dispose(); this.previousCacheState = undefined; } } }
src/vs/workbench/contrib/search/common/cacheState.ts
0
https://github.com/microsoft/vscode/commit/07e3bcf7eacfb5a3f9c6e426fc977d176e40a726
[ 0.00017466371355112642, 0.00017084747378248721, 0.00016522685473319143, 0.00017178754205815494, 0.0000027710718768503284 ]
{ "id": 7, "code_window": [ "import { testingStatesToIcons } from 'vs/workbench/contrib/testing/browser/icons';\n", "import { ITestExplorerFilterState, TestExplorerFilterState, TestingExplorerFilter } from 'vs/workbench/contrib/testing/browser/testingExplorerFilter';\n", "import { ITestingPeekOpener, TestingOutputPeekController } from 'vs/workbench/contrib/testing/browser/testingOutputPeek';\n", "import { TestExplorerViewMode, TestExplorerViewSorting, Testing, testStateNames } from 'vs/workbench/contrib/testing/common/constants';\n", "import { TestingContextKeys } from 'vs/workbench/contrib/testing/common/testingContextKeys';\n", "import { cmpPriority, isFailedState } from 'vs/workbench/contrib/testing/common/testingStates';\n", "import { ITestResultService, sumCounts, TestStateCount } from 'vs/workbench/contrib/testing/common/testResultService';\n", "import { ITestService } from 'vs/workbench/contrib/testing/common/testService';\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { TestExplorerStateFilter, TestExplorerViewMode, TestExplorerViewSorting, Testing, testStateNames } from 'vs/workbench/contrib/testing/common/constants';\n" ], "file_path": "src/vs/workbench/contrib/testing/browser/testingExplorerView.ts", "type": "replace", "edit_start_line_idx": 53 }
/*--------------------------------------------------------------------------------------------- * 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 { Event, Emitter, EventBufferer, EventMultiplexer, PauseableEmitter } from 'vs/base/common/event'; import { IDisposable, DisposableStore } from 'vs/base/common/lifecycle'; import { errorHandler, setUnexpectedErrorHandler } from 'vs/base/common/errors'; import { AsyncEmitter, IWaitUntil, timeout } from 'vs/base/common/async'; import { CancellationToken } from 'vs/base/common/cancellation'; namespace Samples { export class EventCounter { count = 0; reset() { this.count = 0; } onEvent() { this.count += 1; } } export class Document3 { private readonly _onDidChange = new Emitter<string>(); onDidChange: Event<string> = this._onDidChange.event; setText(value: string) { //... this._onDidChange.fire(value); } } } suite('Event', function () { const counter = new Samples.EventCounter(); setup(() => counter.reset()); test('Emitter plain', function () { let doc = new Samples.Document3(); document.createElement('div').onclick = function () { }; let subscription = doc.onDidChange(counter.onEvent, counter); doc.setText('far'); doc.setText('boo'); // unhook listener subscription.dispose(); doc.setText('boo'); assert.strictEqual(counter.count, 2); }); test('Emitter, bucket', function () { let bucket: IDisposable[] = []; let doc = new Samples.Document3(); let subscription = doc.onDidChange(counter.onEvent, counter, bucket); doc.setText('far'); doc.setText('boo'); // unhook listener while (bucket.length) { bucket.pop()!.dispose(); } doc.setText('boo'); // noop subscription.dispose(); doc.setText('boo'); assert.strictEqual(counter.count, 2); }); test('Emitter, store', function () { let bucket = new DisposableStore(); let doc = new Samples.Document3(); let subscription = doc.onDidChange(counter.onEvent, counter, bucket); doc.setText('far'); doc.setText('boo'); // unhook listener bucket.clear(); doc.setText('boo'); // noop subscription.dispose(); doc.setText('boo'); assert.strictEqual(counter.count, 2); }); test('onFirstAdd|onLastRemove', () => { let firstCount = 0; let lastCount = 0; let a = new Emitter({ onFirstListenerAdd() { firstCount += 1; }, onLastListenerRemove() { lastCount += 1; } }); assert.strictEqual(firstCount, 0); assert.strictEqual(lastCount, 0); let subscription = a.event(function () { }); assert.strictEqual(firstCount, 1); assert.strictEqual(lastCount, 0); subscription.dispose(); assert.strictEqual(firstCount, 1); assert.strictEqual(lastCount, 1); subscription = a.event(function () { }); assert.strictEqual(firstCount, 2); assert.strictEqual(lastCount, 1); }); test('throwingListener', () => { const origErrorHandler = errorHandler.getUnexpectedErrorHandler(); setUnexpectedErrorHandler(() => null); try { let a = new Emitter<undefined>(); let hit = false; a.event(function () { // eslint-disable-next-line no-throw-literal throw 9; }); a.event(function () { hit = true; }); a.fire(undefined); assert.strictEqual(hit, true); } finally { setUnexpectedErrorHandler(origErrorHandler); } }); test('reusing event function and context', function () { let counter = 0; function listener() { counter += 1; } const context = {}; let emitter = new Emitter<undefined>(); let reg1 = emitter.event(listener, context); let reg2 = emitter.event(listener, context); emitter.fire(undefined); assert.strictEqual(counter, 2); reg1.dispose(); emitter.fire(undefined); assert.strictEqual(counter, 3); reg2.dispose(); emitter.fire(undefined); assert.strictEqual(counter, 3); }); test('Debounce Event', function (done: () => void) { let doc = new Samples.Document3(); let onDocDidChange = Event.debounce(doc.onDidChange, (prev: string[] | undefined, cur) => { if (!prev) { prev = [cur]; } else if (prev.indexOf(cur) < 0) { prev.push(cur); } return prev; }, 10); let count = 0; onDocDidChange(keys => { count++; assert.ok(keys, 'was not expecting keys.'); if (count === 1) { doc.setText('4'); assert.deepStrictEqual(keys, ['1', '2', '3']); } else if (count === 2) { assert.deepStrictEqual(keys, ['4']); done(); } }); doc.setText('1'); doc.setText('2'); doc.setText('3'); }); test('Debounce Event - leading', async function () { const emitter = new Emitter<void>(); let debounced = Event.debounce(emitter.event, (l, e) => e, 0, /*leading=*/true); let calls = 0; debounced(() => { calls++; }); // If the source event is fired once, the debounced (on the leading edge) event should be fired only once emitter.fire(); await timeout(1); assert.strictEqual(calls, 1); }); test('Debounce Event - leading', async function () { const emitter = new Emitter<void>(); let debounced = Event.debounce(emitter.event, (l, e) => e, 0, /*leading=*/true); let calls = 0; debounced(() => { calls++; }); // If the source event is fired multiple times, the debounced (on the leading edge) event should be fired twice emitter.fire(); emitter.fire(); emitter.fire(); await timeout(1); assert.strictEqual(calls, 2); }); test('Debounce Event - leading reset', async function () { const emitter = new Emitter<number>(); let debounced = Event.debounce(emitter.event, (l, e) => l ? l + 1 : 1, 0, /*leading=*/true); let calls: number[] = []; debounced((e) => calls.push(e)); emitter.fire(1); emitter.fire(1); await timeout(1); assert.deepStrictEqual(calls, [1, 1]); }); test('Emitter - In Order Delivery', function () { const a = new Emitter<string>(); const listener2Events: string[] = []; a.event(function listener1(event) { if (event === 'e1') { a.fire('e2'); // assert that all events are delivered at this point assert.deepStrictEqual(listener2Events, ['e1', 'e2']); } }); a.event(function listener2(event) { listener2Events.push(event); }); a.fire('e1'); // assert that all events are delivered in order assert.deepStrictEqual(listener2Events, ['e1', 'e2']); }); }); suite('AsyncEmitter', function () { test('event has waitUntil-function', async function () { interface E extends IWaitUntil { foo: boolean; bar: number; } let emitter = new AsyncEmitter<E>(); emitter.event(e => { assert.strictEqual(e.foo, true); assert.strictEqual(e.bar, 1); assert.strictEqual(typeof e.waitUntil, 'function'); }); emitter.fireAsync({ foo: true, bar: 1, }, CancellationToken.None); emitter.dispose(); }); test('sequential delivery', async function () { interface E extends IWaitUntil { foo: boolean; } let globalState = 0; let emitter = new AsyncEmitter<E>(); emitter.event(e => { e.waitUntil(timeout(10).then(_ => { assert.strictEqual(globalState, 0); globalState += 1; })); }); emitter.event(e => { e.waitUntil(timeout(1).then(_ => { assert.strictEqual(globalState, 1); globalState += 1; })); }); await emitter.fireAsync({ foo: true }, CancellationToken.None); assert.strictEqual(globalState, 2); }); test('sequential, in-order delivery', async function () { interface E extends IWaitUntil { foo: number; } let events: number[] = []; let done = false; let emitter = new AsyncEmitter<E>(); // e1 emitter.event(e => { e.waitUntil(timeout(10).then(async _ => { if (e.foo === 1) { await emitter.fireAsync({ foo: 2 }, CancellationToken.None); assert.deepStrictEqual(events, [1, 2]); done = true; } })); }); // e2 emitter.event(e => { events.push(e.foo); e.waitUntil(timeout(7)); }); await emitter.fireAsync({ foo: 1 }, CancellationToken.None); assert.ok(done); }); test('catch errors', async function () { const origErrorHandler = errorHandler.getUnexpectedErrorHandler(); setUnexpectedErrorHandler(() => null); interface E extends IWaitUntil { foo: boolean; } let globalState = 0; let emitter = new AsyncEmitter<E>(); emitter.event(e => { globalState += 1; e.waitUntil(new Promise((_r, reject) => reject(new Error()))); }); emitter.event(e => { globalState += 1; e.waitUntil(timeout(10)); e.waitUntil(timeout(20).then(() => globalState++)); // multiple `waitUntil` are supported and awaited on }); await emitter.fireAsync({ foo: true }, CancellationToken.None).then(() => { assert.strictEqual(globalState, 3); }).catch(e => { console.log(e); assert.ok(false); }); setUnexpectedErrorHandler(origErrorHandler); }); }); suite('PausableEmitter', function () { test('basic', function () { const data: number[] = []; const emitter = new PauseableEmitter<number>(); emitter.event(e => data.push(e)); emitter.fire(1); emitter.fire(2); assert.deepStrictEqual(data, [1, 2]); }); test('pause/resume - no merge', function () { const data: number[] = []; const emitter = new PauseableEmitter<number>(); emitter.event(e => data.push(e)); emitter.fire(1); emitter.fire(2); assert.deepStrictEqual(data, [1, 2]); emitter.pause(); emitter.fire(3); emitter.fire(4); assert.deepStrictEqual(data, [1, 2]); emitter.resume(); assert.deepStrictEqual(data, [1, 2, 3, 4]); emitter.fire(5); assert.deepStrictEqual(data, [1, 2, 3, 4, 5]); }); test('pause/resume - merge', function () { const data: number[] = []; const emitter = new PauseableEmitter<number>({ merge: (a) => a.reduce((p, c) => p + c, 0) }); emitter.event(e => data.push(e)); emitter.fire(1); emitter.fire(2); assert.deepStrictEqual(data, [1, 2]); emitter.pause(); emitter.fire(3); emitter.fire(4); assert.deepStrictEqual(data, [1, 2]); emitter.resume(); assert.deepStrictEqual(data, [1, 2, 7]); emitter.fire(5); assert.deepStrictEqual(data, [1, 2, 7, 5]); }); test('double pause/resume', function () { const data: number[] = []; const emitter = new PauseableEmitter<number>(); emitter.event(e => data.push(e)); emitter.fire(1); emitter.fire(2); assert.deepStrictEqual(data, [1, 2]); emitter.pause(); emitter.pause(); emitter.fire(3); emitter.fire(4); assert.deepStrictEqual(data, [1, 2]); emitter.resume(); assert.deepStrictEqual(data, [1, 2]); emitter.resume(); assert.deepStrictEqual(data, [1, 2, 3, 4]); emitter.resume(); assert.deepStrictEqual(data, [1, 2, 3, 4]); }); test('resume, no pause', function () { const data: number[] = []; const emitter = new PauseableEmitter<number>(); emitter.event(e => data.push(e)); emitter.fire(1); emitter.fire(2); assert.deepStrictEqual(data, [1, 2]); emitter.resume(); emitter.fire(3); assert.deepStrictEqual(data, [1, 2, 3]); }); test('nested pause', function () { const data: number[] = []; const emitter = new PauseableEmitter<number>(); let once = true; emitter.event(e => { data.push(e); if (once) { emitter.pause(); once = false; } }); emitter.event(e => { data.push(e); }); emitter.pause(); emitter.fire(1); emitter.fire(2); assert.deepStrictEqual(data, []); emitter.resume(); assert.deepStrictEqual(data, [1, 1]); // paused after first event emitter.resume(); assert.deepStrictEqual(data, [1, 1, 2, 2]); // remaing event delivered emitter.fire(3); assert.deepStrictEqual(data, [1, 1, 2, 2, 3, 3]); }); }); suite('Event utils', () => { suite('EventBufferer', () => { test('should not buffer when not wrapped', () => { const bufferer = new EventBufferer(); const counter = new Samples.EventCounter(); const emitter = new Emitter<void>(); const event = bufferer.wrapEvent(emitter.event); const listener = event(counter.onEvent, counter); assert.strictEqual(counter.count, 0); emitter.fire(); assert.strictEqual(counter.count, 1); emitter.fire(); assert.strictEqual(counter.count, 2); emitter.fire(); assert.strictEqual(counter.count, 3); listener.dispose(); }); test('should buffer when wrapped', () => { const bufferer = new EventBufferer(); const counter = new Samples.EventCounter(); const emitter = new Emitter<void>(); const event = bufferer.wrapEvent(emitter.event); const listener = event(counter.onEvent, counter); assert.strictEqual(counter.count, 0); emitter.fire(); assert.strictEqual(counter.count, 1); bufferer.bufferEvents(() => { emitter.fire(); assert.strictEqual(counter.count, 1); emitter.fire(); assert.strictEqual(counter.count, 1); }); assert.strictEqual(counter.count, 3); emitter.fire(); assert.strictEqual(counter.count, 4); listener.dispose(); }); test('once', () => { const emitter = new Emitter<void>(); let counter1 = 0, counter2 = 0, counter3 = 0; const listener1 = emitter.event(() => counter1++); const listener2 = Event.once(emitter.event)(() => counter2++); const listener3 = Event.once(emitter.event)(() => counter3++); assert.strictEqual(counter1, 0); assert.strictEqual(counter2, 0); assert.strictEqual(counter3, 0); listener3.dispose(); emitter.fire(); assert.strictEqual(counter1, 1); assert.strictEqual(counter2, 1); assert.strictEqual(counter3, 0); emitter.fire(); assert.strictEqual(counter1, 2); assert.strictEqual(counter2, 1); assert.strictEqual(counter3, 0); listener1.dispose(); listener2.dispose(); }); }); suite('fromPromise', () => { test('should emit when done', async () => { let count = 0; const event = Event.fromPromise(Promise.resolve(null)); event(() => count++); assert.strictEqual(count, 0); await timeout(10); assert.strictEqual(count, 1); }); test('should emit when done - setTimeout', async () => { let count = 0; const promise = timeout(5); const event = Event.fromPromise(promise); event(() => count++); assert.strictEqual(count, 0); await promise; assert.strictEqual(count, 1); }); }); suite('stopwatch', () => { test('should emit', () => { const emitter = new Emitter<void>(); const event = Event.stopwatch(emitter.event); return new Promise((c, e) => { event(duration => { try { assert(duration > 0); } catch (err) { e(err); } c(undefined); }); setTimeout(() => emitter.fire(), 10); }); }); }); suite('buffer', () => { test('should buffer events', () => { const result: number[] = []; const emitter = new Emitter<number>(); const event = emitter.event; const bufferedEvent = Event.buffer(event); emitter.fire(1); emitter.fire(2); emitter.fire(3); assert.deepEqual(result, []); const listener = bufferedEvent(num => result.push(num)); assert.deepStrictEqual(result, [1, 2, 3]); emitter.fire(4); assert.deepStrictEqual(result, [1, 2, 3, 4]); listener.dispose(); emitter.fire(5); assert.deepStrictEqual(result, [1, 2, 3, 4]); }); test('should buffer events on next tick', async () => { const result: number[] = []; const emitter = new Emitter<number>(); const event = emitter.event; const bufferedEvent = Event.buffer(event, true); emitter.fire(1); emitter.fire(2); emitter.fire(3); assert.deepEqual(result, []); const listener = bufferedEvent(num => result.push(num)); assert.deepStrictEqual(result, []); await timeout(10); emitter.fire(4); assert.deepStrictEqual(result, [1, 2, 3, 4]); listener.dispose(); emitter.fire(5); assert.deepStrictEqual(result, [1, 2, 3, 4]); }); test('should fire initial buffer events', () => { const result: number[] = []; const emitter = new Emitter<number>(); const event = emitter.event; const bufferedEvent = Event.buffer(event, false, [-2, -1, 0]); emitter.fire(1); emitter.fire(2); emitter.fire(3); assert.deepEqual(result, []); bufferedEvent(num => result.push(num)); assert.deepStrictEqual(result, [-2, -1, 0, 1, 2, 3]); }); }); suite('EventMultiplexer', () => { test('works', () => { const result: number[] = []; const m = new EventMultiplexer<number>(); m.event(r => result.push(r)); const e1 = new Emitter<number>(); m.add(e1.event); assert.deepStrictEqual(result, []); e1.fire(0); assert.deepStrictEqual(result, [0]); }); test('multiplexer dispose works', () => { const result: number[] = []; const m = new EventMultiplexer<number>(); m.event(r => result.push(r)); const e1 = new Emitter<number>(); m.add(e1.event); assert.deepStrictEqual(result, []); e1.fire(0); assert.deepStrictEqual(result, [0]); m.dispose(); assert.deepStrictEqual(result, [0]); e1.fire(0); assert.deepStrictEqual(result, [0]); }); test('event dispose works', () => { const result: number[] = []; const m = new EventMultiplexer<number>(); m.event(r => result.push(r)); const e1 = new Emitter<number>(); m.add(e1.event); assert.deepStrictEqual(result, []); e1.fire(0); assert.deepStrictEqual(result, [0]); e1.dispose(); assert.deepStrictEqual(result, [0]); e1.fire(0); assert.deepStrictEqual(result, [0]); }); test('mutliplexer event dispose works', () => { const result: number[] = []; const m = new EventMultiplexer<number>(); m.event(r => result.push(r)); const e1 = new Emitter<number>(); const l1 = m.add(e1.event); assert.deepStrictEqual(result, []); e1.fire(0); assert.deepStrictEqual(result, [0]); l1.dispose(); assert.deepStrictEqual(result, [0]); e1.fire(0); assert.deepStrictEqual(result, [0]); }); test('hot start works', () => { const result: number[] = []; const m = new EventMultiplexer<number>(); m.event(r => result.push(r)); const e1 = new Emitter<number>(); m.add(e1.event); const e2 = new Emitter<number>(); m.add(e2.event); const e3 = new Emitter<number>(); m.add(e3.event); e1.fire(1); e2.fire(2); e3.fire(3); assert.deepStrictEqual(result, [1, 2, 3]); }); test('cold start works', () => { const result: number[] = []; const m = new EventMultiplexer<number>(); const e1 = new Emitter<number>(); m.add(e1.event); const e2 = new Emitter<number>(); m.add(e2.event); const e3 = new Emitter<number>(); m.add(e3.event); m.event(r => result.push(r)); e1.fire(1); e2.fire(2); e3.fire(3); assert.deepStrictEqual(result, [1, 2, 3]); }); test('late add works', () => { const result: number[] = []; const m = new EventMultiplexer<number>(); const e1 = new Emitter<number>(); m.add(e1.event); const e2 = new Emitter<number>(); m.add(e2.event); m.event(r => result.push(r)); e1.fire(1); e2.fire(2); const e3 = new Emitter<number>(); m.add(e3.event); e3.fire(3); assert.deepStrictEqual(result, [1, 2, 3]); }); test('add dispose works', () => { const result: number[] = []; const m = new EventMultiplexer<number>(); const e1 = new Emitter<number>(); m.add(e1.event); const e2 = new Emitter<number>(); m.add(e2.event); m.event(r => result.push(r)); e1.fire(1); e2.fire(2); const e3 = new Emitter<number>(); const l3 = m.add(e3.event); e3.fire(3); assert.deepStrictEqual(result, [1, 2, 3]); l3.dispose(); e3.fire(4); assert.deepStrictEqual(result, [1, 2, 3]); e2.fire(4); e1.fire(5); assert.deepStrictEqual(result, [1, 2, 3, 4, 5]); }); }); test('latch', () => { const emitter = new Emitter<number>(); const event = Event.latch(emitter.event); const result: number[] = []; const listener = event(num => result.push(num)); assert.deepStrictEqual(result, []); emitter.fire(1); assert.deepStrictEqual(result, [1]); emitter.fire(2); assert.deepStrictEqual(result, [1, 2]); emitter.fire(2); assert.deepStrictEqual(result, [1, 2]); emitter.fire(1); assert.deepStrictEqual(result, [1, 2, 1]); emitter.fire(1); assert.deepStrictEqual(result, [1, 2, 1]); emitter.fire(3); assert.deepStrictEqual(result, [1, 2, 1, 3]); emitter.fire(3); assert.deepStrictEqual(result, [1, 2, 1, 3]); emitter.fire(3); assert.deepStrictEqual(result, [1, 2, 1, 3]); listener.dispose(); }); });
src/vs/base/test/common/event.test.ts
0
https://github.com/microsoft/vscode/commit/07e3bcf7eacfb5a3f9c6e426fc977d176e40a726
[ 0.00017656793352216482, 0.0001736313133733347, 0.00016721960855647922, 0.00017388170817866921, 0.0000015987359347491292 ]
{ "id": 8, "code_window": [ "\t\t\t\tkeyboardNavigationLabelProvider: instantiationService.createInstance(TreeKeyboardNavigationLabelProvider),\n", "\t\t\t\taccessibilityProvider: instantiationService.createInstance(ListAccessibilityProvider),\n", "\t\t\t\tfilter: this.filter,\n", "\t\t\t}) as WorkbenchObjectTree<ITestTreeElement, FuzzyScore>;\n", "\n", "\t\tthis._register(Event.any(filterState.currentDocumentOnly.onDidChange, filterState.text.onDidChange)(this.tree.refilter, this.tree));\n", "\t\tthis._register(editorService.onDidActiveEditorChange(() => {\n", "\t\t\tif (filterState.currentDocumentOnly.value && editorService.activeEditor?.resource) {\n", "\t\t\t\tif (this.projection.hasTestInDocument(editorService.activeEditor.resource)) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis._register(Event.any(\n", "\t\t\tfilterState.currentDocumentOnly.onDidChange,\n", "\t\t\tfilterState.text.onDidChange,\n", "\t\t\tfilterState.stateFilter.onDidChange,\n", "\t\t)(this.tree.refilter, this.tree));\n" ], "file_path": "src/vs/workbench/contrib/testing/browser/testingExplorerView.ts", "type": "replace", "edit_start_line_idx": 259 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as dom from 'vs/base/browser/dom'; import { ActionBar } from 'vs/base/browser/ui/actionbar/actionbar'; import { BaseActionViewItem } from 'vs/base/browser/ui/actionbar/actionViewItems'; import { AnchorAlignment } from 'vs/base/browser/ui/contextview/contextview'; import { DropdownMenuActionViewItem } from 'vs/base/browser/ui/dropdown/dropdownActionViewItem'; import { HistoryInputBox } from 'vs/base/browser/ui/inputbox/inputBox'; import { Action, IAction, IActionRunner } from 'vs/base/common/actions'; import { Delayer } from 'vs/base/common/async'; import { Emitter, Event } from 'vs/base/common/event'; import { KeyCode } from 'vs/base/common/keyCodes'; import { localize } from 'vs/nls'; import { Action2, MenuId, registerAction2 } from 'vs/platform/actions/common/actions'; import { ContextScopedHistoryInputBox } from 'vs/platform/browser/contextScopedHistoryWidget'; import { ContextKeyEqualsExpr, ContextKeyExpr } from 'vs/platform/contextkey/common/contextkey'; import { IContextMenuService, IContextViewService } from 'vs/platform/contextview/browser/contextView'; import { createDecorator, IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IStorageService, StorageScope, StorageTarget } from 'vs/platform/storage/common/storage'; import { attachInputBoxStyler } from 'vs/platform/theme/common/styler'; import { IThemeService, ThemeIcon } from 'vs/platform/theme/common/themeService'; import { ViewContainerLocation } from 'vs/workbench/common/views'; import { testingFilterIcon } from 'vs/workbench/contrib/testing/browser/icons'; import { Testing } from 'vs/workbench/contrib/testing/common/constants'; import { ObservableValue } from 'vs/workbench/contrib/testing/common/observableValue'; import { StoredValue } from 'vs/workbench/contrib/testing/common/storedValue'; import { TestingContextKeys } from 'vs/workbench/contrib/testing/common/testingContextKeys'; export interface ITestExplorerFilterState { _serviceBrand: undefined; readonly text: ObservableValue<string>; /** Reveal request, the extId of the test to reveal */ readonly reveal: ObservableValue<string | undefined>; readonly currentDocumentOnly: ObservableValue<boolean>; readonly onDidRequestInputFocus: Event<void>; focusInput(): void; } export const ITestExplorerFilterState = createDecorator<ITestExplorerFilterState>('testingFilterState'); export class TestExplorerFilterState implements ITestExplorerFilterState { declare _serviceBrand: undefined; private readonly focusEmitter = new Emitter<void>(); public readonly text = new ObservableValue(''); public readonly currentDocumentOnly = ObservableValue.stored(new StoredValue<boolean>({ key: 'testsByCurrentDocumentOnly', scope: StorageScope.WORKSPACE, target: StorageTarget.USER }, this.storage), false); public readonly reveal = new ObservableValue<string | undefined>(undefined); public readonly onDidRequestInputFocus = this.focusEmitter.event; constructor(@IStorageService private readonly storage: IStorageService) { } public focusInput() { this.focusEmitter.fire(); } } export class TestingExplorerFilter extends BaseActionViewItem { private input!: HistoryInputBox; private readonly history: StoredValue<string[]> = this.instantiationService.createInstance(StoredValue, { key: 'testing.filterHistory', scope: StorageScope.WORKSPACE, target: StorageTarget.USER }); private readonly filtersAction = new Action('markersFiltersAction', localize('testing.filters.menu', "More Filters..."), 'testing-filter-button ' + ThemeIcon.asClassName(testingFilterIcon)); constructor( action: IAction, @ITestExplorerFilterState private readonly state: ITestExplorerFilterState, @IContextViewService private readonly contextViewService: IContextViewService, @IThemeService private readonly themeService: IThemeService, @IInstantiationService private readonly instantiationService: IInstantiationService, ) { super(null, action); this.updateFilterActiveState(); this._register(state.currentDocumentOnly.onDidChange(this.updateFilterActiveState, this)); } /** * @override */ public render(container: HTMLElement) { container.classList.add('testing-filter-action-item'); const updateDelayer = this._register(new Delayer<void>(400)); const wrapper = dom.$('.testing-filter-wrapper'); container.appendChild(wrapper); const input = this.input = this._register(this.instantiationService.createInstance(ContextScopedHistoryInputBox, wrapper, this.contextViewService, { placeholder: localize('testExplorerFilter', "Filter (e.g. text, !exclude)"), history: this.history.get([]), })); input.value = this.state.text.value; this._register(attachInputBoxStyler(input, this.themeService)); this._register(this.state.text.onDidChange(newValue => { input.value = newValue; })); this._register(this.state.onDidRequestInputFocus(() => { input.focus(); })); this._register(input.onDidChange(() => updateDelayer.trigger(() => { input.addToHistory(); this.state.text.value = input.value; }))); this._register(dom.addStandardDisposableListener(input.inputElement, dom.EventType.KEY_DOWN, e => { if (e.equals(KeyCode.Escape)) { input.value = ''; e.stopPropagation(); e.preventDefault(); } })); const actionbar = this._register(new ActionBar(container, { actionViewItemProvider: action => { if (action.id === this.filtersAction.id) { return this.instantiationService.createInstance(FiltersDropdownMenuActionViewItem, action, this.state, this.actionRunner); } return undefined; } })); actionbar.push(this.filtersAction, { icon: true, label: false }); } /** * Focuses the filter input. */ public focus(): void { this.input.focus(); } /** * Persists changes to the input history. */ public saveState() { const history = this.input.getHistory(); if (history.length) { this.history.store(history); } else { this.history.delete(); } } /** * @override */ public dispose() { this.saveState(); super.dispose(); } /** * Updates the 'checked' state of the filter submenu. */ private updateFilterActiveState() { this.filtersAction.checked = this.state.currentDocumentOnly.value; } } class FiltersDropdownMenuActionViewItem extends DropdownMenuActionViewItem { constructor( action: IAction, private readonly filters: ITestExplorerFilterState, actionRunner: IActionRunner, @IContextMenuService contextMenuService: IContextMenuService ) { super(action, { getActions: () => this.getActions() }, contextMenuService, { actionRunner, classNames: action.class, anchorAlignmentProvider: () => AnchorAlignment.RIGHT, menuAsChild: true } ); } render(container: HTMLElement): void { super.render(container); this.updateChecked(); } private getActions(): IAction[] { return [ { checked: this.filters.currentDocumentOnly.value, class: undefined, enabled: true, id: 'currentDocument', label: localize('testing.filters.currentFile', "Show in Active File Only"), run: async () => this.filters.currentDocumentOnly.value = !this.filters.currentDocumentOnly.value, tooltip: '', dispose: () => null }, ]; } updateChecked(): void { this.element!.classList.toggle('checked', this._action.checked); } } registerAction2(class extends Action2 { constructor() { super({ id: Testing.FilterActionId, title: localize('filter', "Filter"), menu: { id: MenuId.ViewTitle, when: ContextKeyExpr.and(ContextKeyEqualsExpr.create('view', Testing.ExplorerViewId), TestingContextKeys.explorerLocation.isEqualTo(ViewContainerLocation.Panel)), group: 'navigation', order: 1, }, }); } async run(): Promise<void> { } });
src/vs/workbench/contrib/testing/browser/testingExplorerFilter.ts
1
https://github.com/microsoft/vscode/commit/07e3bcf7eacfb5a3f9c6e426fc977d176e40a726
[ 0.0036218727473169565, 0.00035467231646180153, 0.00015981269825715572, 0.0001709731441223994, 0.0007039526244625449 ]
{ "id": 8, "code_window": [ "\t\t\t\tkeyboardNavigationLabelProvider: instantiationService.createInstance(TreeKeyboardNavigationLabelProvider),\n", "\t\t\t\taccessibilityProvider: instantiationService.createInstance(ListAccessibilityProvider),\n", "\t\t\t\tfilter: this.filter,\n", "\t\t\t}) as WorkbenchObjectTree<ITestTreeElement, FuzzyScore>;\n", "\n", "\t\tthis._register(Event.any(filterState.currentDocumentOnly.onDidChange, filterState.text.onDidChange)(this.tree.refilter, this.tree));\n", "\t\tthis._register(editorService.onDidActiveEditorChange(() => {\n", "\t\t\tif (filterState.currentDocumentOnly.value && editorService.activeEditor?.resource) {\n", "\t\t\t\tif (this.projection.hasTestInDocument(editorService.activeEditor.resource)) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis._register(Event.any(\n", "\t\t\tfilterState.currentDocumentOnly.onDidChange,\n", "\t\t\tfilterState.text.onDidChange,\n", "\t\t\tfilterState.stateFilter.onDidChange,\n", "\t\t)(this.tree.refilter, this.tree));\n" ], "file_path": "src/vs/workbench/contrib/testing/browser/testingExplorerView.ts", "type": "replace", "edit_start_line_idx": 259 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ .monaco-editor .goto-definition-link { text-decoration: underline; cursor: pointer; }
src/vs/editor/contrib/gotoSymbol/link/goToDefinitionAtPosition.css
0
https://github.com/microsoft/vscode/commit/07e3bcf7eacfb5a3f9c6e426fc977d176e40a726
[ 0.0001761797902872786, 0.0001761797902872786, 0.0001761797902872786, 0.0001761797902872786, 0 ]
{ "id": 8, "code_window": [ "\t\t\t\tkeyboardNavigationLabelProvider: instantiationService.createInstance(TreeKeyboardNavigationLabelProvider),\n", "\t\t\t\taccessibilityProvider: instantiationService.createInstance(ListAccessibilityProvider),\n", "\t\t\t\tfilter: this.filter,\n", "\t\t\t}) as WorkbenchObjectTree<ITestTreeElement, FuzzyScore>;\n", "\n", "\t\tthis._register(Event.any(filterState.currentDocumentOnly.onDidChange, filterState.text.onDidChange)(this.tree.refilter, this.tree));\n", "\t\tthis._register(editorService.onDidActiveEditorChange(() => {\n", "\t\t\tif (filterState.currentDocumentOnly.value && editorService.activeEditor?.resource) {\n", "\t\t\t\tif (this.projection.hasTestInDocument(editorService.activeEditor.resource)) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis._register(Event.any(\n", "\t\t\tfilterState.currentDocumentOnly.onDidChange,\n", "\t\t\tfilterState.text.onDidChange,\n", "\t\t\tfilterState.stateFilter.onDidChange,\n", "\t\t)(this.tree.refilter, this.tree));\n" ], "file_path": "src/vs/workbench/contrib/testing/browser/testingExplorerView.ts", "type": "replace", "edit_start_line_idx": 259 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as fs from 'fs'; import { createHash } from 'crypto'; import { join } from 'vs/base/common/path'; import { isLinux } from 'vs/base/common/platform'; import { writeFileSync, writeFile, readdir, exists, rimraf, RimRafMode } from 'vs/base/node/pfs'; import { IBackupMainService, IWorkspaceBackupInfo, isWorkspaceBackupInfo } from 'vs/platform/backup/electron-main/backup'; import { IBackupWorkspacesFormat, IEmptyWindowBackupInfo } from 'vs/platform/backup/node/backup'; import { IEnvironmentMainService } from 'vs/platform/environment/electron-main/environmentMainService'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IFilesConfiguration, HotExitConfiguration } from 'vs/platform/files/common/files'; import { ILogService } from 'vs/platform/log/common/log'; import { IWorkspaceIdentifier, isWorkspaceIdentifier } from 'vs/platform/workspaces/common/workspaces'; import { URI } from 'vs/base/common/uri'; import { isEqual } from 'vs/base/common/extpath'; import { Schemas } from 'vs/base/common/network'; import { extUriBiasedIgnorePathCase } from 'vs/base/common/resources'; export class BackupMainService implements IBackupMainService { declare readonly _serviceBrand: undefined; protected backupHome: string; protected workspacesJsonPath: string; private workspaces: IWorkspaceBackupInfo[] = []; private folders: URI[] = []; private emptyWindows: IEmptyWindowBackupInfo[] = []; // Comparers for paths and resources that will // - ignore path casing on Windows/macOS // - respect path casing on Linux private readonly backupUriComparer = extUriBiasedIgnorePathCase; private readonly backupPathComparer = { isEqual: (pathA: string, pathB: string) => isEqual(pathA, pathB, !isLinux) }; constructor( @IEnvironmentMainService environmentService: IEnvironmentMainService, @IConfigurationService private readonly configurationService: IConfigurationService, @ILogService private readonly logService: ILogService ) { this.backupHome = environmentService.backupHome; this.workspacesJsonPath = environmentService.backupWorkspacesPath; } async initialize(): Promise<void> { let backups: IBackupWorkspacesFormat; try { backups = JSON.parse(await fs.promises.readFile(this.workspacesJsonPath, 'utf8')); // invalid JSON or permission issue can happen here } catch (error) { backups = Object.create(null); } // read empty workspaces backups first if (backups.emptyWorkspaceInfos) { this.emptyWindows = await this.validateEmptyWorkspaces(backups.emptyWorkspaceInfos); } // read workspace backups let rootWorkspaces: IWorkspaceBackupInfo[] = []; try { if (Array.isArray(backups.rootURIWorkspaces)) { rootWorkspaces = backups.rootURIWorkspaces.map(workspace => ({ workspace: { id: workspace.id, configPath: URI.parse(workspace.configURIPath) }, remoteAuthority: workspace.remoteAuthority })); } } catch (e) { // ignore URI parsing exceptions } this.workspaces = await this.validateWorkspaces(rootWorkspaces); // read folder backups let workspaceFolders: URI[] = []; try { if (Array.isArray(backups.folderURIWorkspaces)) { workspaceFolders = backups.folderURIWorkspaces.map(folder => URI.parse(folder)); } } catch (e) { // ignore URI parsing exceptions } this.folders = await this.validateFolders(workspaceFolders); // save again in case some workspaces or folders have been removed await this.save(); } getWorkspaceBackups(): IWorkspaceBackupInfo[] { if (this.isHotExitOnExitAndWindowClose()) { // Only non-folder windows are restored on main process launch when // hot exit is configured as onExitAndWindowClose. return []; } return this.workspaces.slice(0); // return a copy } getFolderBackupPaths(): URI[] { if (this.isHotExitOnExitAndWindowClose()) { // Only non-folder windows are restored on main process launch when // hot exit is configured as onExitAndWindowClose. return []; } return this.folders.slice(0); // return a copy } isHotExitEnabled(): boolean { return this.getHotExitConfig() !== HotExitConfiguration.OFF; } private isHotExitOnExitAndWindowClose(): boolean { return this.getHotExitConfig() === HotExitConfiguration.ON_EXIT_AND_WINDOW_CLOSE; } private getHotExitConfig(): string { const config = this.configurationService.getValue<IFilesConfiguration>(); return config?.files?.hotExit || HotExitConfiguration.ON_EXIT; } getEmptyWindowBackupPaths(): IEmptyWindowBackupInfo[] { return this.emptyWindows.slice(0); // return a copy } registerWorkspaceBackupSync(workspaceInfo: IWorkspaceBackupInfo, migrateFrom?: string): string { if (!this.workspaces.some(workspace => workspaceInfo.workspace.id === workspace.workspace.id)) { this.workspaces.push(workspaceInfo); this.saveSync(); } const backupPath = this.getBackupPath(workspaceInfo.workspace.id); if (migrateFrom) { this.moveBackupFolderSync(backupPath, migrateFrom); } return backupPath; } private moveBackupFolderSync(backupPath: string, moveFromPath: string): void { // Target exists: make sure to convert existing backups to empty window backups if (fs.existsSync(backupPath)) { this.convertToEmptyWindowBackupSync(backupPath); } // When we have data to migrate from, move it over to the target location if (fs.existsSync(moveFromPath)) { try { fs.renameSync(moveFromPath, backupPath); } catch (error) { this.logService.error(`Backup: Could not move backup folder to new location: ${error.toString()}`); } } } unregisterWorkspaceBackupSync(workspace: IWorkspaceIdentifier): void { const id = workspace.id; const index = this.workspaces.findIndex(workspace => workspace.workspace.id === id); if (index !== -1) { this.workspaces.splice(index, 1); this.saveSync(); } } registerFolderBackupSync(folderUri: URI): string { if (!this.folders.some(folder => this.backupUriComparer.isEqual(folderUri, folder))) { this.folders.push(folderUri); this.saveSync(); } return this.getBackupPath(this.getFolderHash(folderUri)); } unregisterFolderBackupSync(folderUri: URI): void { const index = this.folders.findIndex(folder => this.backupUriComparer.isEqual(folderUri, folder)); if (index !== -1) { this.folders.splice(index, 1); this.saveSync(); } } registerEmptyWindowBackupSync(backupFolderCandidate?: string, remoteAuthority?: string): string { // Generate a new folder if this is a new empty workspace const backupFolder = backupFolderCandidate || this.getRandomEmptyWindowId(); if (!this.emptyWindows.some(emptyWindow => !!emptyWindow.backupFolder && this.backupPathComparer.isEqual(emptyWindow.backupFolder, backupFolder))) { this.emptyWindows.push({ backupFolder, remoteAuthority }); this.saveSync(); } return this.getBackupPath(backupFolder); } unregisterEmptyWindowBackupSync(backupFolder: string): void { const index = this.emptyWindows.findIndex(emptyWindow => !!emptyWindow.backupFolder && this.backupPathComparer.isEqual(emptyWindow.backupFolder, backupFolder)); if (index !== -1) { this.emptyWindows.splice(index, 1); this.saveSync(); } } private getBackupPath(oldFolderHash: string): string { return join(this.backupHome, oldFolderHash); } private async validateWorkspaces(rootWorkspaces: IWorkspaceBackupInfo[]): Promise<IWorkspaceBackupInfo[]> { if (!Array.isArray(rootWorkspaces)) { return []; } const seenIds: Set<string> = new Set(); const result: IWorkspaceBackupInfo[] = []; // Validate Workspaces for (let workspaceInfo of rootWorkspaces) { const workspace = workspaceInfo.workspace; if (!isWorkspaceIdentifier(workspace)) { return []; // wrong format, skip all entries } if (!seenIds.has(workspace.id)) { seenIds.add(workspace.id); const backupPath = this.getBackupPath(workspace.id); const hasBackups = await this.doHasBackups(backupPath); // If the workspace has no backups, ignore it if (hasBackups) { if (workspace.configPath.scheme !== Schemas.file || await exists(workspace.configPath.fsPath)) { result.push(workspaceInfo); } else { // If the workspace has backups, but the target workspace is missing, convert backups to empty ones await this.convertToEmptyWindowBackup(backupPath); } } else { await this.deleteStaleBackup(backupPath); } } } return result; } private async validateFolders(folderWorkspaces: URI[]): Promise<URI[]> { if (!Array.isArray(folderWorkspaces)) { return []; } const result: URI[] = []; const seenIds: Set<string> = new Set(); for (let folderURI of folderWorkspaces) { const key = this.backupUriComparer.getComparisonKey(folderURI); if (!seenIds.has(key)) { seenIds.add(key); const backupPath = this.getBackupPath(this.getFolderHash(folderURI)); const hasBackups = await this.doHasBackups(backupPath); // If the folder has no backups, ignore it if (hasBackups) { if (folderURI.scheme !== Schemas.file || await exists(folderURI.fsPath)) { result.push(folderURI); } else { // If the folder has backups, but the target workspace is missing, convert backups to empty ones await this.convertToEmptyWindowBackup(backupPath); } } else { await this.deleteStaleBackup(backupPath); } } } return result; } private async validateEmptyWorkspaces(emptyWorkspaces: IEmptyWindowBackupInfo[]): Promise<IEmptyWindowBackupInfo[]> { if (!Array.isArray(emptyWorkspaces)) { return []; } const result: IEmptyWindowBackupInfo[] = []; const seenIds: Set<string> = new Set(); // Validate Empty Windows for (let backupInfo of emptyWorkspaces) { const backupFolder = backupInfo.backupFolder; if (typeof backupFolder !== 'string') { return []; } if (!seenIds.has(backupFolder)) { seenIds.add(backupFolder); const backupPath = this.getBackupPath(backupFolder); if (await this.doHasBackups(backupPath)) { result.push(backupInfo); } else { await this.deleteStaleBackup(backupPath); } } } return result; } private async deleteStaleBackup(backupPath: string): Promise<void> { try { if (await exists(backupPath)) { await rimraf(backupPath, RimRafMode.MOVE); } } catch (error) { this.logService.error(`Backup: Could not delete stale backup: ${error.toString()}`); } } private async convertToEmptyWindowBackup(backupPath: string): Promise<boolean> { // New empty window backup let newBackupFolder = this.getRandomEmptyWindowId(); while (this.emptyWindows.some(emptyWindow => !!emptyWindow.backupFolder && this.backupPathComparer.isEqual(emptyWindow.backupFolder, newBackupFolder))) { newBackupFolder = this.getRandomEmptyWindowId(); } // Rename backupPath to new empty window backup path const newEmptyWindowBackupPath = this.getBackupPath(newBackupFolder); try { await fs.promises.rename(backupPath, newEmptyWindowBackupPath); } catch (error) { this.logService.error(`Backup: Could not rename backup folder: ${error.toString()}`); return false; } this.emptyWindows.push({ backupFolder: newBackupFolder }); return true; } private convertToEmptyWindowBackupSync(backupPath: string): boolean { // New empty window backup let newBackupFolder = this.getRandomEmptyWindowId(); while (this.emptyWindows.some(emptyWindow => !!emptyWindow.backupFolder && this.backupPathComparer.isEqual(emptyWindow.backupFolder, newBackupFolder))) { newBackupFolder = this.getRandomEmptyWindowId(); } // Rename backupPath to new empty window backup path const newEmptyWindowBackupPath = this.getBackupPath(newBackupFolder); try { fs.renameSync(backupPath, newEmptyWindowBackupPath); } catch (error) { this.logService.error(`Backup: Could not rename backup folder: ${error.toString()}`); return false; } this.emptyWindows.push({ backupFolder: newBackupFolder }); return true; } async getDirtyWorkspaces(): Promise<Array<IWorkspaceIdentifier | URI>> { const dirtyWorkspaces: Array<IWorkspaceIdentifier | URI> = []; // Workspaces with backups for (const workspace of this.workspaces) { if ((await this.hasBackups(workspace))) { dirtyWorkspaces.push(workspace.workspace); } } // Folders with backups for (const folder of this.folders) { if ((await this.hasBackups(folder))) { dirtyWorkspaces.push(folder); } } return dirtyWorkspaces; } private hasBackups(backupLocation: IWorkspaceBackupInfo | IEmptyWindowBackupInfo | URI): Promise<boolean> { let backupPath: string; // Folder if (URI.isUri(backupLocation)) { backupPath = this.getBackupPath(this.getFolderHash(backupLocation)); } // Workspace else if (isWorkspaceBackupInfo(backupLocation)) { backupPath = this.getBackupPath(backupLocation.workspace.id); } // Empty else { backupPath = backupLocation.backupFolder; } return this.doHasBackups(backupPath); } private async doHasBackups(backupPath: string): Promise<boolean> { try { const backupSchemas = await readdir(backupPath); for (const backupSchema of backupSchemas) { try { const backupSchemaChildren = await readdir(join(backupPath, backupSchema)); if (backupSchemaChildren.length > 0) { return true; } } catch (error) { // invalid folder } } } catch (error) { // backup path does not exist } return false; } private saveSync(): void { try { writeFileSync(this.workspacesJsonPath, JSON.stringify(this.serializeBackups())); } catch (error) { this.logService.error(`Backup: Could not save workspaces.json: ${error.toString()}`); } } private async save(): Promise<void> { try { await writeFile(this.workspacesJsonPath, JSON.stringify(this.serializeBackups())); } catch (error) { this.logService.error(`Backup: Could not save workspaces.json: ${error.toString()}`); } } private serializeBackups(): IBackupWorkspacesFormat { return { rootURIWorkspaces: this.workspaces.map(workspace => ({ id: workspace.workspace.id, configURIPath: workspace.workspace.configPath.toString(), remoteAuthority: workspace.remoteAuthority })), folderURIWorkspaces: this.folders.map(folder => folder.toString()), emptyWorkspaceInfos: this.emptyWindows }; } private getRandomEmptyWindowId(): string { return (Date.now() + Math.round(Math.random() * 1000)).toString(); } protected getFolderHash(folderUri: URI): string { let key: string; if (folderUri.scheme === Schemas.file) { // for backward compatibility, use the fspath as key key = isLinux ? folderUri.fsPath : folderUri.fsPath.toLowerCase(); } else { key = folderUri.toString().toLowerCase(); } return createHash('md5').update(key).digest('hex'); } }
src/vs/platform/backup/electron-main/backupMainService.ts
0
https://github.com/microsoft/vscode/commit/07e3bcf7eacfb5a3f9c6e426fc977d176e40a726
[ 0.0001765211345627904, 0.00017251604003831744, 0.00016160095401573926, 0.0001730291114654392, 0.0000029200366498116637 ]
{ "id": 8, "code_window": [ "\t\t\t\tkeyboardNavigationLabelProvider: instantiationService.createInstance(TreeKeyboardNavigationLabelProvider),\n", "\t\t\t\taccessibilityProvider: instantiationService.createInstance(ListAccessibilityProvider),\n", "\t\t\t\tfilter: this.filter,\n", "\t\t\t}) as WorkbenchObjectTree<ITestTreeElement, FuzzyScore>;\n", "\n", "\t\tthis._register(Event.any(filterState.currentDocumentOnly.onDidChange, filterState.text.onDidChange)(this.tree.refilter, this.tree));\n", "\t\tthis._register(editorService.onDidActiveEditorChange(() => {\n", "\t\t\tif (filterState.currentDocumentOnly.value && editorService.activeEditor?.resource) {\n", "\t\t\t\tif (this.projection.hasTestInDocument(editorService.activeEditor.resource)) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis._register(Event.any(\n", "\t\t\tfilterState.currentDocumentOnly.onDidChange,\n", "\t\t\tfilterState.text.onDidChange,\n", "\t\t\tfilterState.stateFilter.onDidChange,\n", "\t\t)(this.tree.refilter, this.tree));\n" ], "file_path": "src/vs/workbench/contrib/testing/browser/testingExplorerView.ts", "type": "replace", "edit_start_line_idx": 259 }
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="575" height="6px"> <style> circle { animation: ball 2.5s cubic-bezier(0.000, 1.000, 1.000, 0.000) infinite; fill: #bbb; } #balls { animation: balls 2.5s linear infinite; } #circle2 { animation-delay: 0.1s; } #circle3 { animation-delay: 0.2s; } #circle4 { animation-delay: 0.3s; } #circle5 { animation-delay: 0.4s; } @keyframes ball { from { transform: none; } 20% { transform: none; } 80% { transform: translateX(864px); } to { transform: translateX(864px); } } @keyframes balls { from { transform: translateX(-40px); } to { transform: translateX(30px); } } </style> <g id="balls"> <circle class="circle" id="circle1" cx="-115" cy="3" r="3"/> <circle class="circle" id="circle2" cx="-130" cy="3" r="3" /> <circle class="circle" id="circle3" cx="-145" cy="3" r="3" /> <circle class="circle" id="circle4" cx="-160" cy="3" r="3" /> <circle class="circle" id="circle5" cx="-175" cy="3" r="3" /> </g> </svg>
src/vs/workbench/contrib/extensions/browser/media/loading.svg
0
https://github.com/microsoft/vscode/commit/07e3bcf7eacfb5a3f9c6e426fc977d176e40a726
[ 0.00018005701713263988, 0.00017803847731556743, 0.00017386146646458656, 0.00017911772010847926, 0.000002479737304383889 ]
{ "id": 9, "code_window": [ "\tpublic filter(element: ITestTreeElement): TreeFilterResult<void> {\n", "\t\tif (this.state.text.value !== this.lastText) {\n", "\t\t\tthis.setFilter(this.state.text.value);\n", "\t\t}\n", "\n", "\t\tswitch (Math.min(this.testFilterText(element), this.testLocation(element))) {\n", "\t\t\tcase FilterResult.Exclude:\n", "\t\t\t\treturn TreeVisibility.Hidden;\n", "\t\t\tcase FilterResult.Include:\n", "\t\t\t\treturn TreeVisibility.Visible;\n", "\t\t\tdefault:\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tswitch (Math.min(this.testFilterText(element), this.testLocation(element), this.testState(element))) {\n" ], "file_path": "src/vs/workbench/contrib/testing/browser/testingExplorerView.ts", "type": "replace", "edit_start_line_idx": 525 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as dom from 'vs/base/browser/dom'; import { ActionBar } from 'vs/base/browser/ui/actionbar/actionbar'; import { BaseActionViewItem } from 'vs/base/browser/ui/actionbar/actionViewItems'; import { AnchorAlignment } from 'vs/base/browser/ui/contextview/contextview'; import { DropdownMenuActionViewItem } from 'vs/base/browser/ui/dropdown/dropdownActionViewItem'; import { HistoryInputBox } from 'vs/base/browser/ui/inputbox/inputBox'; import { Action, IAction, IActionRunner } from 'vs/base/common/actions'; import { Delayer } from 'vs/base/common/async'; import { Emitter, Event } from 'vs/base/common/event'; import { KeyCode } from 'vs/base/common/keyCodes'; import { localize } from 'vs/nls'; import { Action2, MenuId, registerAction2 } from 'vs/platform/actions/common/actions'; import { ContextScopedHistoryInputBox } from 'vs/platform/browser/contextScopedHistoryWidget'; import { ContextKeyEqualsExpr, ContextKeyExpr } from 'vs/platform/contextkey/common/contextkey'; import { IContextMenuService, IContextViewService } from 'vs/platform/contextview/browser/contextView'; import { createDecorator, IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IStorageService, StorageScope, StorageTarget } from 'vs/platform/storage/common/storage'; import { attachInputBoxStyler } from 'vs/platform/theme/common/styler'; import { IThemeService, ThemeIcon } from 'vs/platform/theme/common/themeService'; import { ViewContainerLocation } from 'vs/workbench/common/views'; import { testingFilterIcon } from 'vs/workbench/contrib/testing/browser/icons'; import { Testing } from 'vs/workbench/contrib/testing/common/constants'; import { ObservableValue } from 'vs/workbench/contrib/testing/common/observableValue'; import { StoredValue } from 'vs/workbench/contrib/testing/common/storedValue'; import { TestingContextKeys } from 'vs/workbench/contrib/testing/common/testingContextKeys'; export interface ITestExplorerFilterState { _serviceBrand: undefined; readonly text: ObservableValue<string>; /** Reveal request, the extId of the test to reveal */ readonly reveal: ObservableValue<string | undefined>; readonly currentDocumentOnly: ObservableValue<boolean>; readonly onDidRequestInputFocus: Event<void>; focusInput(): void; } export const ITestExplorerFilterState = createDecorator<ITestExplorerFilterState>('testingFilterState'); export class TestExplorerFilterState implements ITestExplorerFilterState { declare _serviceBrand: undefined; private readonly focusEmitter = new Emitter<void>(); public readonly text = new ObservableValue(''); public readonly currentDocumentOnly = ObservableValue.stored(new StoredValue<boolean>({ key: 'testsByCurrentDocumentOnly', scope: StorageScope.WORKSPACE, target: StorageTarget.USER }, this.storage), false); public readonly reveal = new ObservableValue<string | undefined>(undefined); public readonly onDidRequestInputFocus = this.focusEmitter.event; constructor(@IStorageService private readonly storage: IStorageService) { } public focusInput() { this.focusEmitter.fire(); } } export class TestingExplorerFilter extends BaseActionViewItem { private input!: HistoryInputBox; private readonly history: StoredValue<string[]> = this.instantiationService.createInstance(StoredValue, { key: 'testing.filterHistory', scope: StorageScope.WORKSPACE, target: StorageTarget.USER }); private readonly filtersAction = new Action('markersFiltersAction', localize('testing.filters.menu', "More Filters..."), 'testing-filter-button ' + ThemeIcon.asClassName(testingFilterIcon)); constructor( action: IAction, @ITestExplorerFilterState private readonly state: ITestExplorerFilterState, @IContextViewService private readonly contextViewService: IContextViewService, @IThemeService private readonly themeService: IThemeService, @IInstantiationService private readonly instantiationService: IInstantiationService, ) { super(null, action); this.updateFilterActiveState(); this._register(state.currentDocumentOnly.onDidChange(this.updateFilterActiveState, this)); } /** * @override */ public render(container: HTMLElement) { container.classList.add('testing-filter-action-item'); const updateDelayer = this._register(new Delayer<void>(400)); const wrapper = dom.$('.testing-filter-wrapper'); container.appendChild(wrapper); const input = this.input = this._register(this.instantiationService.createInstance(ContextScopedHistoryInputBox, wrapper, this.contextViewService, { placeholder: localize('testExplorerFilter', "Filter (e.g. text, !exclude)"), history: this.history.get([]), })); input.value = this.state.text.value; this._register(attachInputBoxStyler(input, this.themeService)); this._register(this.state.text.onDidChange(newValue => { input.value = newValue; })); this._register(this.state.onDidRequestInputFocus(() => { input.focus(); })); this._register(input.onDidChange(() => updateDelayer.trigger(() => { input.addToHistory(); this.state.text.value = input.value; }))); this._register(dom.addStandardDisposableListener(input.inputElement, dom.EventType.KEY_DOWN, e => { if (e.equals(KeyCode.Escape)) { input.value = ''; e.stopPropagation(); e.preventDefault(); } })); const actionbar = this._register(new ActionBar(container, { actionViewItemProvider: action => { if (action.id === this.filtersAction.id) { return this.instantiationService.createInstance(FiltersDropdownMenuActionViewItem, action, this.state, this.actionRunner); } return undefined; } })); actionbar.push(this.filtersAction, { icon: true, label: false }); } /** * Focuses the filter input. */ public focus(): void { this.input.focus(); } /** * Persists changes to the input history. */ public saveState() { const history = this.input.getHistory(); if (history.length) { this.history.store(history); } else { this.history.delete(); } } /** * @override */ public dispose() { this.saveState(); super.dispose(); } /** * Updates the 'checked' state of the filter submenu. */ private updateFilterActiveState() { this.filtersAction.checked = this.state.currentDocumentOnly.value; } } class FiltersDropdownMenuActionViewItem extends DropdownMenuActionViewItem { constructor( action: IAction, private readonly filters: ITestExplorerFilterState, actionRunner: IActionRunner, @IContextMenuService contextMenuService: IContextMenuService ) { super(action, { getActions: () => this.getActions() }, contextMenuService, { actionRunner, classNames: action.class, anchorAlignmentProvider: () => AnchorAlignment.RIGHT, menuAsChild: true } ); } render(container: HTMLElement): void { super.render(container); this.updateChecked(); } private getActions(): IAction[] { return [ { checked: this.filters.currentDocumentOnly.value, class: undefined, enabled: true, id: 'currentDocument', label: localize('testing.filters.currentFile', "Show in Active File Only"), run: async () => this.filters.currentDocumentOnly.value = !this.filters.currentDocumentOnly.value, tooltip: '', dispose: () => null }, ]; } updateChecked(): void { this.element!.classList.toggle('checked', this._action.checked); } } registerAction2(class extends Action2 { constructor() { super({ id: Testing.FilterActionId, title: localize('filter', "Filter"), menu: { id: MenuId.ViewTitle, when: ContextKeyExpr.and(ContextKeyEqualsExpr.create('view', Testing.ExplorerViewId), TestingContextKeys.explorerLocation.isEqualTo(ViewContainerLocation.Panel)), group: 'navigation', order: 1, }, }); } async run(): Promise<void> { } });
src/vs/workbench/contrib/testing/browser/testingExplorerFilter.ts
1
https://github.com/microsoft/vscode/commit/07e3bcf7eacfb5a3f9c6e426fc977d176e40a726
[ 0.0035323949996382, 0.00033874608925543725, 0.0001636106608202681, 0.0001704891910776496, 0.0006747656734660268 ]
{ "id": 9, "code_window": [ "\tpublic filter(element: ITestTreeElement): TreeFilterResult<void> {\n", "\t\tif (this.state.text.value !== this.lastText) {\n", "\t\t\tthis.setFilter(this.state.text.value);\n", "\t\t}\n", "\n", "\t\tswitch (Math.min(this.testFilterText(element), this.testLocation(element))) {\n", "\t\t\tcase FilterResult.Exclude:\n", "\t\t\t\treturn TreeVisibility.Hidden;\n", "\t\t\tcase FilterResult.Include:\n", "\t\t\t\treturn TreeVisibility.Visible;\n", "\t\t\tdefault:\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tswitch (Math.min(this.testFilterText(element), this.testLocation(element), this.testState(element))) {\n" ], "file_path": "src/vs/workbench/contrib/testing/browser/testingExplorerView.ts", "type": "replace", "edit_start_line_idx": 525 }
test/** cgmanifest.json
extensions/hlsl/.vscodeignore
0
https://github.com/microsoft/vscode/commit/07e3bcf7eacfb5a3f9c6e426fc977d176e40a726
[ 0.00017484401178080589, 0.00017484401178080589, 0.00017484401178080589, 0.00017484401178080589, 0 ]
{ "id": 9, "code_window": [ "\tpublic filter(element: ITestTreeElement): TreeFilterResult<void> {\n", "\t\tif (this.state.text.value !== this.lastText) {\n", "\t\t\tthis.setFilter(this.state.text.value);\n", "\t\t}\n", "\n", "\t\tswitch (Math.min(this.testFilterText(element), this.testLocation(element))) {\n", "\t\t\tcase FilterResult.Exclude:\n", "\t\t\t\treturn TreeVisibility.Hidden;\n", "\t\t\tcase FilterResult.Include:\n", "\t\t\t\treturn TreeVisibility.Visible;\n", "\t\t\tdefault:\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tswitch (Math.min(this.testFilterText(element), this.testLocation(element), this.testState(element))) {\n" ], "file_path": "src/vs/workbench/contrib/testing/browser/testingExplorerView.ts", "type": "replace", "edit_start_line_idx": 525 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { ParseError, Node, JSONPath, Segment, parseTree, findNodeAtLocation } from './json'; import { Edit, format, isEOL, FormattingOptions } from './jsonFormatter'; import { mergeSort } from 'vs/base/common/arrays'; export function removeProperty(text: string, path: JSONPath, formattingOptions: FormattingOptions): Edit[] { return setProperty(text, path, undefined, formattingOptions); } export function setProperty(text: string, originalPath: JSONPath, value: any, formattingOptions: FormattingOptions, getInsertionIndex?: (properties: string[]) => number): Edit[] { const path = originalPath.slice(); const errors: ParseError[] = []; const root = parseTree(text, errors); let parent: Node | undefined = undefined; let lastSegment: Segment | undefined = undefined; while (path.length > 0) { lastSegment = path.pop(); parent = findNodeAtLocation(root, path); if (parent === undefined && value !== undefined) { if (typeof lastSegment === 'string') { value = { [lastSegment]: value }; } else { value = [value]; } } else { break; } } if (!parent) { // empty document if (value === undefined) { // delete throw new Error('Can not delete in empty document'); } return withFormatting(text, { offset: root ? root.offset : 0, length: root ? root.length : 0, content: JSON.stringify(value) }, formattingOptions); } else if (parent.type === 'object' && typeof lastSegment === 'string' && Array.isArray(parent.children)) { const existing = findNodeAtLocation(parent, [lastSegment]); if (existing !== undefined) { if (value === undefined) { // delete if (!existing.parent) { throw new Error('Malformed AST'); } const propertyIndex = parent.children.indexOf(existing.parent); let removeBegin: number; let removeEnd = existing.parent.offset + existing.parent.length; if (propertyIndex > 0) { // remove the comma of the previous node const previous = parent.children[propertyIndex - 1]; removeBegin = previous.offset + previous.length; } else { removeBegin = parent.offset + 1; if (parent.children.length > 1) { // remove the comma of the next node const next = parent.children[1]; removeEnd = next.offset; } } return withFormatting(text, { offset: removeBegin, length: removeEnd - removeBegin, content: '' }, formattingOptions); } else { // set value of existing property return withFormatting(text, { offset: existing.offset, length: existing.length, content: JSON.stringify(value) }, formattingOptions); } } else { if (value === undefined) { // delete return []; // property does not exist, nothing to do } const newProperty = `${JSON.stringify(lastSegment)}: ${JSON.stringify(value)}`; const index = getInsertionIndex ? getInsertionIndex(parent.children.map(p => p.children![0].value)) : parent.children.length; let edit: Edit; if (index > 0) { const previous = parent.children[index - 1]; edit = { offset: previous.offset + previous.length, length: 0, content: ',' + newProperty }; } else if (parent.children.length === 0) { edit = { offset: parent.offset + 1, length: 0, content: newProperty }; } else { edit = { offset: parent.offset + 1, length: 0, content: newProperty + ',' }; } return withFormatting(text, edit, formattingOptions); } } else if (parent.type === 'array' && typeof lastSegment === 'number' && Array.isArray(parent.children)) { if (value !== undefined) { // Insert const newProperty = `${JSON.stringify(value)}`; let edit: Edit; if (parent.children.length === 0 || lastSegment === 0) { edit = { offset: parent.offset + 1, length: 0, content: parent.children.length === 0 ? newProperty : newProperty + ',' }; } else { const index = lastSegment === -1 || lastSegment > parent.children.length ? parent.children.length : lastSegment; const previous = parent.children[index - 1]; edit = { offset: previous.offset + previous.length, length: 0, content: ',' + newProperty }; } return withFormatting(text, edit, formattingOptions); } else { //Removal const removalIndex = lastSegment; const toRemove = parent.children[removalIndex]; let edit: Edit; if (parent.children.length === 1) { // only item edit = { offset: parent.offset + 1, length: parent.length - 2, content: '' }; } else if (parent.children.length - 1 === removalIndex) { // last item const previous = parent.children[removalIndex - 1]; const offset = previous.offset + previous.length; const parentEndOffset = parent.offset + parent.length; edit = { offset, length: parentEndOffset - 2 - offset, content: '' }; } else { edit = { offset: toRemove.offset, length: parent.children[removalIndex + 1].offset - toRemove.offset, content: '' }; } return withFormatting(text, edit, formattingOptions); } } else { throw new Error(`Can not add ${typeof lastSegment !== 'number' ? 'index' : 'property'} to parent of type ${parent.type}`); } } export function withFormatting(text: string, edit: Edit, formattingOptions: FormattingOptions): Edit[] { // apply the edit let newText = applyEdit(text, edit); // format the new text let begin = edit.offset; let end = edit.offset + edit.content.length; if (edit.length === 0 || edit.content.length === 0) { // insert or remove while (begin > 0 && !isEOL(newText, begin - 1)) { begin--; } while (end < newText.length && !isEOL(newText, end)) { end++; } } const edits = format(newText, { offset: begin, length: end - begin }, formattingOptions); // apply the formatting edits and track the begin and end offsets of the changes for (let i = edits.length - 1; i >= 0; i--) { const curr = edits[i]; newText = applyEdit(newText, curr); begin = Math.min(begin, curr.offset); end = Math.max(end, curr.offset + curr.length); end += curr.content.length - curr.length; } // create a single edit with all changes const editLength = text.length - (newText.length - end) - begin; return [{ offset: begin, length: editLength, content: newText.substring(begin, end) }]; } export function applyEdit(text: string, edit: Edit): string { return text.substring(0, edit.offset) + edit.content + text.substring(edit.offset + edit.length); } export function applyEdits(text: string, edits: Edit[]): string { let sortedEdits = mergeSort(edits, (a, b) => { const diff = a.offset - b.offset; if (diff === 0) { return a.length - b.length; } return diff; }); let lastModifiedOffset = text.length; for (let i = sortedEdits.length - 1; i >= 0; i--) { let e = sortedEdits[i]; if (e.offset + e.length <= lastModifiedOffset) { text = applyEdit(text, e); } else { throw new Error('Overlapping edit'); } lastModifiedOffset = e.offset; } return text; }
src/vs/base/common/jsonEdit.ts
0
https://github.com/microsoft/vscode/commit/07e3bcf7eacfb5a3f9c6e426fc977d176e40a726
[ 0.00017523020505905151, 0.00016997932107187808, 0.0001635262742638588, 0.0001700866559986025, 0.0000029060488486720715 ]
{ "id": 9, "code_window": [ "\tpublic filter(element: ITestTreeElement): TreeFilterResult<void> {\n", "\t\tif (this.state.text.value !== this.lastText) {\n", "\t\t\tthis.setFilter(this.state.text.value);\n", "\t\t}\n", "\n", "\t\tswitch (Math.min(this.testFilterText(element), this.testLocation(element))) {\n", "\t\t\tcase FilterResult.Exclude:\n", "\t\t\t\treturn TreeVisibility.Hidden;\n", "\t\t\tcase FilterResult.Include:\n", "\t\t\t\treturn TreeVisibility.Visible;\n", "\t\t\tdefault:\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tswitch (Math.min(this.testFilterText(element), this.testLocation(element), this.testState(element))) {\n" ], "file_path": "src/vs/workbench/contrib/testing/browser/testingExplorerView.ts", "type": "replace", "edit_start_line_idx": 525 }
{ "extends": "../shared.tsconfig.json", "compilerOptions": { "outDir": "./out" }, "include": [ "src/**/*" ] }
extensions/php-language-features/tsconfig.json
0
https://github.com/microsoft/vscode/commit/07e3bcf7eacfb5a3f9c6e426fc977d176e40a726
[ 0.00017338154430035502, 0.00017338154430035502, 0.00017338154430035502, 0.00017338154430035502, 0 ]
{ "id": 10, "code_window": [ "\t\t\t\treturn TreeVisibility.Recurse;\n", "\t\t}\n", "\t}\n", "\n", "\tprivate testLocation(element: ITestTreeElement): FilterResult {\n", "\t\tif (!this._filterToUri || !this.state.currentDocumentOnly.value) {\n", "\t\t\treturn FilterResult.Include;\n", "\t\t}\n", "\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tprivate testState(element: ITestTreeElement): FilterResult {\n", "\t\tswitch (this.state.stateFilter.value) {\n", "\t\t\tcase TestExplorerStateFilter.All:\n", "\t\t\t\treturn FilterResult.Include;\n", "\t\t\tcase TestExplorerStateFilter.OnlyExecuted:\n", "\t\t\t\treturn element.ownState !== TestRunState.Unset ? FilterResult.Include : FilterResult.Inherit;\n", "\t\t\tcase TestExplorerStateFilter.OnlyFailed:\n", "\t\t\t\treturn isFailedState(element.ownState) ? FilterResult.Include : FilterResult.Inherit;\n", "\t\t}\n", "\t}\n", "\n" ], "file_path": "src/vs/workbench/contrib/testing/browser/testingExplorerView.ts", "type": "add", "edit_start_line_idx": 535 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as dom from 'vs/base/browser/dom'; import { ActionBar } from 'vs/base/browser/ui/actionbar/actionbar'; import * as aria from 'vs/base/browser/ui/aria/aria'; import { IIdentityProvider, IKeyboardNavigationLabelProvider, IListVirtualDelegate } from 'vs/base/browser/ui/list/list'; import { DefaultKeyboardNavigationDelegate, IListAccessibilityProvider } from 'vs/base/browser/ui/list/listWidget'; import { ICompressedTreeNode } from 'vs/base/browser/ui/tree/compressedObjectTreeModel'; import { ObjectTree } from 'vs/base/browser/ui/tree/objectTree'; import { ITreeEvent, ITreeFilter, ITreeNode, ITreeRenderer, ITreeSorter, TreeFilterResult, TreeVisibility } from 'vs/base/browser/ui/tree/tree'; import { Action, IAction, IActionViewItem } from 'vs/base/common/actions'; import { DeferredPromise } from 'vs/base/common/async'; import { Color, RGBA } from 'vs/base/common/color'; import { throttle } from 'vs/base/common/decorators'; import { Event } from 'vs/base/common/event'; import { FuzzyScore } from 'vs/base/common/filters'; import { splitGlobAware } from 'vs/base/common/glob'; import { Iterable } from 'vs/base/common/iterator'; import { Disposable, DisposableStore, MutableDisposable, toDisposable } from 'vs/base/common/lifecycle'; import { URI } from 'vs/base/common/uri'; import 'vs/css!./media/testing'; import { ICodeEditor, isCodeEditor } from 'vs/editor/browser/editorBrowser'; import { ICodeEditorService } from 'vs/editor/browser/services/codeEditorService'; import { localize } from 'vs/nls'; import { MenuEntryActionViewItem } from 'vs/platform/actions/browser/menuEntryActionViewItem'; import { MenuItemAction } from 'vs/platform/actions/common/actions'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { IContextMenuService } from 'vs/platform/contextview/browser/contextView'; import { FileKind } from 'vs/platform/files/common/files'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { WorkbenchObjectTree } from 'vs/platform/list/browser/listService'; import { IOpenerService } from 'vs/platform/opener/common/opener'; import { IProgress, IProgressService, IProgressStep } from 'vs/platform/progress/common/progress'; import { IStorageService, StorageScope, StorageTarget } from 'vs/platform/storage/common/storage'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { foreground } from 'vs/platform/theme/common/colorRegistry'; import { IThemeService, registerThemingParticipant, ThemeIcon } from 'vs/platform/theme/common/themeService'; import { TestRunState } from 'vs/workbench/api/common/extHostTypes'; import { IResourceLabel, IResourceLabelOptions, IResourceLabelProps, ResourceLabels } from 'vs/workbench/browser/labels'; import { ViewPane } from 'vs/workbench/browser/parts/views/viewPane'; import { IViewletViewOptions } from 'vs/workbench/browser/parts/views/viewsViewlet'; import { IViewDescriptorService, ViewContainerLocation } from 'vs/workbench/common/views'; import { ITestTreeElement, ITestTreeProjection } from 'vs/workbench/contrib/testing/browser/explorerProjections'; import { HierarchicalByLocationProjection } from 'vs/workbench/contrib/testing/browser/explorerProjections/hierarchalByLocation'; import { HierarchicalByNameProjection } from 'vs/workbench/contrib/testing/browser/explorerProjections/hierarchalByName'; import { testingStatesToIcons } from 'vs/workbench/contrib/testing/browser/icons'; import { ITestExplorerFilterState, TestExplorerFilterState, TestingExplorerFilter } from 'vs/workbench/contrib/testing/browser/testingExplorerFilter'; import { ITestingPeekOpener, TestingOutputPeekController } from 'vs/workbench/contrib/testing/browser/testingOutputPeek'; import { TestExplorerViewMode, TestExplorerViewSorting, Testing, testStateNames } from 'vs/workbench/contrib/testing/common/constants'; import { TestingContextKeys } from 'vs/workbench/contrib/testing/common/testingContextKeys'; import { cmpPriority, isFailedState } from 'vs/workbench/contrib/testing/common/testingStates'; import { ITestResultService, sumCounts, TestStateCount } from 'vs/workbench/contrib/testing/common/testResultService'; import { ITestService } from 'vs/workbench/contrib/testing/common/testService'; import { IWorkspaceTestCollectionService, TestSubscriptionListener } from 'vs/workbench/contrib/testing/common/workspaceTestCollectionService'; import { IActivityService, NumberBadge, ProgressBadge } from 'vs/workbench/services/activity/common/activity'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { DebugAction, RunAction } from './testExplorerActions'; export class TestingExplorerView extends ViewPane { public viewModel!: TestingExplorerViewModel; private filterActionBar = this._register(new MutableDisposable()); private readonly currentSubscription = new MutableDisposable<TestSubscriptionListener>(); private container!: HTMLElement; private finishDiscovery?: () => void; private readonly location = TestingContextKeys.explorerLocation.bindTo(this.contextKeyService);; constructor( options: IViewletViewOptions, @IWorkspaceTestCollectionService private readonly testCollection: IWorkspaceTestCollectionService, @ITestService private readonly testService: ITestService, @IProgressService private readonly progress: IProgressService, @IContextMenuService contextMenuService: IContextMenuService, @IKeybindingService keybindingService: IKeybindingService, @IConfigurationService configurationService: IConfigurationService, @IInstantiationService instantiationService: IInstantiationService, @IViewDescriptorService viewDescriptorService: IViewDescriptorService, @IContextKeyService contextKeyService: IContextKeyService, @IOpenerService openerService: IOpenerService, @IThemeService themeService: IThemeService, @ITelemetryService telemetryService: ITelemetryService, ) { super(options, keybindingService, contextMenuService, configurationService, contextKeyService, viewDescriptorService, instantiationService, openerService, themeService, telemetryService); this._register(testService.onDidChangeProviders(() => this._onDidChangeViewWelcomeState.fire())); this.location.set(viewDescriptorService.getViewLocationById(Testing.ExplorerViewId) ?? ViewContainerLocation.Sidebar); } /** * @override */ public shouldShowWelcome() { return this.testService.providers === 0; } /** * @override */ protected renderBody(container: HTMLElement): void { super.renderBody(container); this.container = dom.append(container, dom.$('.test-explorer')); if (this.location.get() === ViewContainerLocation.Sidebar) { this.filterActionBar.value = this.createFilterActionBar(); } const messagesContainer = dom.append(this.container, dom.$('.test-explorer-messages')); this._register(this.instantiationService.createInstance(TestRunProgress, messagesContainer, this.getProgressLocation())); const listContainer = dom.append(this.container, dom.$('.test-explorer-tree')); this.viewModel = this.instantiationService.createInstance(TestingExplorerViewModel, listContainer, this.onDidChangeBodyVisibility, this.currentSubscription.value); this._register(this.viewModel); this._register(this.onDidChangeBodyVisibility(visible => { if (!visible && this.currentSubscription) { this.currentSubscription.value = undefined; this.viewModel.replaceSubscription(undefined); } else if (visible && !this.currentSubscription.value) { this.currentSubscription.value = this.createSubscription(); this.viewModel.replaceSubscription(this.currentSubscription.value); } })); } /** * @override */ public getActionViewItem(action: IAction): IActionViewItem | undefined { if (action.id === Testing.FilterActionId) { return this.instantiationService.createInstance(TestingExplorerFilter, action); } return super.getActionViewItem(action); } /** * @override */ public saveState() { super.saveState(); } private createFilterActionBar() { const bar = new ActionBar(this.container, { actionViewItemProvider: action => this.getActionViewItem(action) }); bar.push(new Action(Testing.FilterActionId)); bar.getContainer().classList.add('testing-filter-action-bar'); return bar; } private updateDiscoveryProgress(busy: number) { if (!busy && this.finishDiscovery) { this.finishDiscovery(); this.finishDiscovery = undefined; } else if (busy && !this.finishDiscovery) { const promise = new Promise<void>(resolve => { this.finishDiscovery = resolve; }); this.progress.withProgress({ location: this.getProgressLocation() }, () => promise); } } /** * @override */ protected layoutBody(height: number, width: number): void { super.layoutBody(height, width); this.container.style.height = `${height}px`; this.viewModel.layout(height, width); } private createSubscription() { const handle = this.testCollection.subscribeToWorkspaceTests(); handle.subscription.onBusyProvidersChange(() => this.updateDiscoveryProgress(handle.subscription.busyProviders)); return handle; } } export class TestingExplorerViewModel extends Disposable { public tree: ObjectTree<ITestTreeElement, FuzzyScore>; private filter: TestsFilter; public projection!: ITestTreeProjection; private readonly _viewMode = TestingContextKeys.viewMode.bindTo(this.contextKeyService); private readonly _viewSorting = TestingContextKeys.viewSorting.bindTo(this.contextKeyService); /** * Fires when the selected tests change. */ public readonly onDidChangeSelection: Event<ITreeEvent<ITestTreeElement | null>>; public get viewMode() { return this._viewMode.get() ?? TestExplorerViewMode.Tree; } public set viewMode(newMode: TestExplorerViewMode) { if (newMode === this._viewMode.get()) { return; } this._viewMode.set(newMode); this.updatePreferredProjection(); this.storageService.store('testing.viewMode', newMode, StorageScope.WORKSPACE, StorageTarget.USER); } public get viewSorting() { return this._viewSorting.get() ?? TestExplorerViewSorting.ByLocation; } public set viewSorting(newSorting: TestExplorerViewSorting) { if (newSorting === this._viewSorting.get()) { return; } this._viewSorting.set(newSorting); this.tree.resort(null); this.storageService.store('testing.viewSorting', newSorting, StorageScope.WORKSPACE, StorageTarget.USER); } constructor( listContainer: HTMLElement, onDidChangeVisibility: Event<boolean>, private listener: TestSubscriptionListener | undefined, @ITestExplorerFilterState filterState: TestExplorerFilterState, @IInstantiationService private readonly instantiationService: IInstantiationService, @IEditorService private readonly editorService: IEditorService, @IStorageService private readonly storageService: IStorageService, @IContextKeyService private readonly contextKeyService: IContextKeyService, @ITestResultService private readonly testResults: ITestResultService, @ITestingPeekOpener private readonly peekOpener: ITestingPeekOpener, ) { super(); this._viewMode.set(this.storageService.get('testing.viewMode', StorageScope.WORKSPACE, TestExplorerViewMode.Tree) as TestExplorerViewMode); this._viewSorting.set(this.storageService.get('testing.viewSorting', StorageScope.WORKSPACE, TestExplorerViewSorting.ByLocation) as TestExplorerViewSorting); const labels = this._register(instantiationService.createInstance(ResourceLabels, { onDidChangeVisibility: onDidChangeVisibility })); this.filter = this.instantiationService.createInstance(TestsFilter); this.tree = instantiationService.createInstance( WorkbenchObjectTree, 'Test Explorer List', listContainer, new ListDelegate(), [ instantiationService.createInstance(TestsRenderer, labels) ], { simpleKeyboardNavigation: true, identityProvider: instantiationService.createInstance(IdentityProvider), hideTwistiesOfChildlessElements: true, sorter: instantiationService.createInstance(TreeSorter, this), keyboardNavigationLabelProvider: instantiationService.createInstance(TreeKeyboardNavigationLabelProvider), accessibilityProvider: instantiationService.createInstance(ListAccessibilityProvider), filter: this.filter, }) as WorkbenchObjectTree<ITestTreeElement, FuzzyScore>; this._register(Event.any(filterState.currentDocumentOnly.onDidChange, filterState.text.onDidChange)(this.tree.refilter, this.tree)); this._register(editorService.onDidActiveEditorChange(() => { if (filterState.currentDocumentOnly.value && editorService.activeEditor?.resource) { if (this.projection.hasTestInDocument(editorService.activeEditor.resource)) { this.filter.filterToUri(editorService.activeEditor.resource); this.tree.refilter(); } } })); this._register(this.tree); this._register(dom.addStandardDisposableListener(this.tree.getHTMLElement(), 'keydown', evt => { if (DefaultKeyboardNavigationDelegate.mightProducePrintableCharacter(evt)) { filterState.text.value = evt.browserEvent.key; filterState.focusInput(); } })); this.updatePreferredProjection(); this.onDidChangeSelection = this.tree.onDidChangeSelection; this._register(this.tree.onDidChangeSelection(evt => { const selected = evt.elements[0]; if (selected && evt.browserEvent) { this.openEditorForItem(selected); } })); const tracker = this._register(this.instantiationService.createInstance(CodeEditorTracker, this)); this._register(onDidChangeVisibility(visible => { if (visible) { tracker.activate(); } else { tracker.deactivate(); } })); this._register(testResults.onResultsChanged(() => { this.tree.resort(null); })); } /** * Re-layout the tree. */ public layout(height: number, width: number): void { this.tree.layout(height, width); } /** * Replaces the test listener and recalculates the tree. */ public replaceSubscription(listener: TestSubscriptionListener | undefined) { this.listener = listener; this.updatePreferredProjection(); } /** * Reveals and moves focus to the item. */ public async revealItem(item: ITestTreeElement, reveal = true): Promise<void> { if (!this.tree.hasElement(item)) { return; } const chain: ITestTreeElement[] = []; for (let parent = item.parentItem; parent; parent = parent.parentItem) { chain.push(parent); } for (const parent of chain.reverse()) { try { this.tree.expand(parent); } catch { // ignore if not present } } if (reveal === true && this.tree.getRelativeTop(item) === null) { // Don't scroll to the item if it's already visible, or if set not to. this.tree.reveal(item, 0.5); } this.tree.setFocus([item]); this.tree.setSelection([item]); } /** * Collapse all items in the tree. */ public async collapseAll() { this.tree.collapseAll(); } /** * Opens an editor for the item. If there is a failure associated with the * test item, it will be shown. */ public async openEditorForItem(item: ITestTreeElement, preserveFocus = true) { if (await this.tryPeekError(item)) { return; } const location = item?.location; if (!location) { return; } const pane = await this.editorService.openEditor({ resource: location.uri, options: { selection: { startColumn: location.range.startColumn, startLineNumber: location.range.startLineNumber }, preserveFocus, }, }); // if the user selected a failed test and now they didn't, hide the peek const control = pane?.getControl(); if (isCodeEditor(control)) { TestingOutputPeekController.get(control).removePeek(); } } /** * Tries to peek the first test error, if the item is in a failed state. */ private async tryPeekError(item: ITestTreeElement) { const lookup = item.test && this.testResults.getStateByExtId(item.test.item.extId); return lookup && isFailedState(lookup[1].state.state) ? this.peekOpener.tryPeekFirstError(lookup[0], lookup[1], { preserveFocus: true }) : false; } private updatePreferredProjection() { this.projection?.dispose(); if (!this.listener) { this.tree.setChildren(null, []); return; } if (this._viewMode.get() === TestExplorerViewMode.List) { this.projection = this.instantiationService.createInstance(HierarchicalByNameProjection, this.listener); } else { this.projection = this.instantiationService.createInstance(HierarchicalByLocationProjection, this.listener); } this.projection.onUpdate(this.deferUpdate, this); this.projection.applyTo(this.tree); } @throttle(200) private deferUpdate() { this.projection.applyTo(this.tree); } /** * Gets the selected tests from the tree. */ public getSelectedTests() { return this.tree.getSelection(); } } class CodeEditorTracker { private store = new DisposableStore(); private lastRevealed?: ITestTreeElement; constructor( private readonly model: TestingExplorerViewModel, @ICodeEditorService private readonly codeEditorService: ICodeEditorService, ) { } public activate() { const editorStores = new Set<DisposableStore>(); this.store.add(toDisposable(() => { for (const store of editorStores) { store.dispose(); } })); const register = (editor: ICodeEditor) => { const store = new DisposableStore(); editorStores.add(store); store.add(editor.onDidChangeCursorPosition(evt => { const uri = editor.getModel()?.uri; if (!uri) { return; } const test = this.model.projection.getTestAtPosition(uri, evt.position); if (test && test !== this.lastRevealed) { this.model.revealItem(test); this.lastRevealed = test; } })); editor.onDidDispose(() => { store.dispose(); editorStores.delete(store); }); }; this.store.add(this.codeEditorService.onCodeEditorAdd(register)); this.codeEditorService.listCodeEditors().forEach(register); } public deactivate() { this.store.dispose(); this.store = new DisposableStore(); } public dispose() { this.store.dispose(); } } const enum FilterResult { Exclude, Inherit, Include, } class TestsFilter implements ITreeFilter<ITestTreeElement> { private lastText?: string; private filters: [include: boolean, value: string][] | undefined; private _filterToUri: string | undefined; constructor(@ITestExplorerFilterState private readonly state: ITestExplorerFilterState) { } /** * Parses and updates the tree filter. Supports lists of patterns that can be !negated. */ private setFilter(text: string) { this.lastText = text; text = text.trim(); if (!text) { this.filters = undefined; return; } this.filters = []; for (const filter of splitGlobAware(text, ',').map(s => s.trim()).filter(s => !!s.length)) { if (filter.startsWith('!')) { this.filters.push([false, filter.slice(1).toLowerCase()]); } else { this.filters.push([true, filter.toLowerCase()]); } } } public filterToUri(uri: URI) { this._filterToUri = uri.toString(); } /** * @inheritdoc */ public filter(element: ITestTreeElement): TreeFilterResult<void> { if (this.state.text.value !== this.lastText) { this.setFilter(this.state.text.value); } switch (Math.min(this.testFilterText(element), this.testLocation(element))) { case FilterResult.Exclude: return TreeVisibility.Hidden; case FilterResult.Include: return TreeVisibility.Visible; default: return TreeVisibility.Recurse; } } private testLocation(element: ITestTreeElement): FilterResult { if (!this._filterToUri || !this.state.currentDocumentOnly.value) { return FilterResult.Include; } for (let e: ITestTreeElement | null = element; e; e = e!.parentItem) { if (!e.location) { continue; } return e.location.uri.toString() === this._filterToUri ? FilterResult.Include : FilterResult.Exclude; } return FilterResult.Inherit; } private testFilterText(element: ITestTreeElement) { if (!this.filters) { return FilterResult.Include; } for (let e: ITestTreeElement | null = element; e; e = e.parentItem) { // start as included if the first glob is a negation let included = this.filters[0][0] === false ? FilterResult.Exclude : FilterResult.Inherit; const data = e.label.toLowerCase(); for (const [include, filter] of this.filters) { if (data.includes(filter)) { included = include ? FilterResult.Include : FilterResult.Exclude; } } if (included !== FilterResult.Inherit) { return included; } } return FilterResult.Inherit; } } class TreeSorter implements ITreeSorter<ITestTreeElement> { constructor(private readonly viewModel: TestingExplorerViewModel) { } public compare(a: ITestTreeElement, b: ITestTreeElement): number { let delta = cmpPriority(a.state, b.state); if (delta !== 0) { return delta; } if (this.viewModel.viewSorting === TestExplorerViewSorting.ByLocation && a.location && b.location && a.location.uri.toString() === b.location.uri.toString()) { delta = a.location.range.startLineNumber - b.location.range.startLineNumber; if (delta !== 0) { return delta; } } return a.label.localeCompare(b.label); } } class ListAccessibilityProvider implements IListAccessibilityProvider<ITestTreeElement> { getWidgetAriaLabel(): string { return localize('testExplorer', "Test Explorer"); } getAriaLabel(element: ITestTreeElement): string { let label = localize({ key: 'testing.treeElementLabel', comment: ['label then the unit tests state, for example "Addition Tests (Running)"'], }, '{0} ({1})', element.label, testStateNames[element.state]); if (element.retired) { label = localize({ key: 'testing.treeElementLabelOutdated', comment: ['{0} is the original label in testing.treeElementLabel'], }, '{0}, outdated result', label, testStateNames[element.state]); } return label; } } class TreeKeyboardNavigationLabelProvider implements IKeyboardNavigationLabelProvider<ITestTreeElement> { getKeyboardNavigationLabel(element: ITestTreeElement) { return element.label; } } class ListDelegate implements IListVirtualDelegate<ITestTreeElement> { getHeight(_element: ITestTreeElement) { return 22; } getTemplateId(_element: ITestTreeElement) { return TestsRenderer.ID; } } class IdentityProvider implements IIdentityProvider<ITestTreeElement> { public getId(element: ITestTreeElement) { return element.treeId; } } interface TestTemplateData { label: IResourceLabel; icon: HTMLElement; actionBar: ActionBar; } class TestsRenderer implements ITreeRenderer<ITestTreeElement, FuzzyScore, TestTemplateData> { public static readonly ID = 'testExplorer'; constructor( private labels: ResourceLabels, @IInstantiationService private readonly instantiationService: IInstantiationService ) { } renderCompressedElements(node: ITreeNode<ICompressedTreeNode<ITestTreeElement>, FuzzyScore>, index: number, templateData: TestTemplateData): void { const element = node.element.elements[node.element.elements.length - 1]; this.renderElementDirect(element, templateData); } get templateId(): string { return TestsRenderer.ID; } public renderTemplate(container: HTMLElement): TestTemplateData { const wrapper = dom.append(container, dom.$('.test-item')); const icon = dom.append(wrapper, dom.$('.computed-state')); const name = dom.append(wrapper, dom.$('.name')); const label = this.labels.create(name, { supportHighlights: true }); const actionBar = new ActionBar(wrapper, { actionViewItemProvider: action => action instanceof MenuItemAction ? this.instantiationService.createInstance(MenuEntryActionViewItem, action) : undefined }); return { label, actionBar, icon }; } public renderElement(node: ITreeNode<ITestTreeElement, FuzzyScore>, index: number, data: TestTemplateData): void { this.renderElementDirect(node.element, data); } private renderElementDirect(element: ITestTreeElement, data: TestTemplateData) { const label: IResourceLabelProps = { name: element.label }; const options: IResourceLabelOptions = {}; data.actionBar.clear(); const icon = testingStatesToIcons.get(element.state); data.icon.className = 'computed-state ' + (icon ? ThemeIcon.asClassName(icon) : ''); if (element.retired) { data.icon.className += ' retired'; } const test = element.test; if (test) { if (test.item.location) { label.resource = test.item.location.uri; } let title = element.label; for (let p = element.parentItem; p; p = p.parentItem) { title = `${p.label}, ${title}`; } options.title = title; options.fileKind = FileKind.FILE; label.description = element.description; } else { options.fileKind = FileKind.ROOT_FOLDER; } const running = element.state === TestRunState.Running; if (!Iterable.isEmpty(element.runnable)) { data.actionBar.push( this.instantiationService.createInstance(RunAction, element.runnable, running), { icon: true, label: false }, ); } if (!Iterable.isEmpty(element.debuggable)) { data.actionBar.push( this.instantiationService.createInstance(DebugAction, element.debuggable, running), { icon: true, label: false }, ); } data.label.setResource(label, options); } disposeTemplate(templateData: TestTemplateData): void { templateData.label.dispose(); templateData.actionBar.dispose(); } } type CountSummary = ReturnType<typeof collectCounts>; const collectCounts = (count: TestStateCount) => { const failed = count[TestRunState.Errored] + count[TestRunState.Failed]; const passed = count[TestRunState.Passed]; const skipped = count[TestRunState.Skipped]; return { passed, failed, runSoFar: passed + failed, totalWillBeRun: passed + failed + count[TestRunState.Queued] + count[TestRunState.Running], skipped, }; }; const getProgressText = ({ passed, runSoFar, skipped, failed }: CountSummary) => { let percent = passed / runSoFar * 100; if (failed > 0) { // fix: prevent from rounding to 100 if there's any failed test percent = Math.min(percent, 99.9); } if (skipped === 0) { return localize('testProgress', '{0}/{1} tests passed ({2}%)', passed, runSoFar, percent.toPrecision(3)); } else { return localize('testProgressWithSkip', '{0}/{1} tests passed ({2}%, {3} skipped)', passed, runSoFar, percent.toPrecision(3), skipped); } }; class TestRunProgress { private current?: { update: IProgress<IProgressStep>; deferred: DeferredPromise<void> }; private badge = new MutableDisposable(); private readonly resultLister = this.resultService.onResultsChanged(result => { if (!('started' in result)) { return; } this.updateProgress(); this.updateBadge(); result.started.onChange(this.throttledProgressUpdate, this); result.started.onComplete(() => { this.throttledProgressUpdate(); this.updateBadge(); }); }); constructor( private readonly messagesContainer: HTMLElement, private readonly location: string, @IProgressService private readonly progress: IProgressService, @ITestResultService private readonly resultService: ITestResultService, @IActivityService private readonly activityService: IActivityService, ) { } public dispose() { this.resultLister.dispose(); this.current?.deferred.complete(); this.badge.dispose(); } @throttle(200) private throttledProgressUpdate() { this.updateProgress(); } private updateProgress() { const running = this.resultService.results.filter(r => !r.isComplete); if (!running.length) { this.setIdleText(this.resultService.results[0]?.counts); this.current?.deferred.complete(); this.current = undefined; } else if (!this.current) { this.progress.withProgress({ location: this.location, total: 100 }, update => { this.current = { update, deferred: new DeferredPromise() }; this.updateProgress(); return this.current.deferred.p; }); } else { const counts = sumCounts(running.map(r => r.counts)); this.setRunningText(counts); const { runSoFar, totalWillBeRun } = collectCounts(counts); this.current.update.report({ increment: runSoFar, total: totalWillBeRun }); } } private setRunningText(counts: TestStateCount) { this.messagesContainer.dataset.state = 'running'; const collected = collectCounts(counts); if (collected.runSoFar === 0) { this.messagesContainer.innerText = localize('testResultStarting', 'Test run is starting...'); } else { this.messagesContainer.innerText = getProgressText(collected); } } private setIdleText(lastCount?: TestStateCount) { if (!lastCount) { this.messagesContainer.innerText = ''; } else { const collected = collectCounts(lastCount); this.messagesContainer.dataset.state = collected.failed ? 'failed' : 'running'; const doneMessage = getProgressText(collected); this.messagesContainer.innerText = doneMessage; aria.alert(doneMessage); } } private updateBadge() { this.badge.value = undefined; const result = this.resultService.results[0]; // currently running, or last run if (!result) { return; } if (!result.isComplete) { const badge = new ProgressBadge(() => localize('testBadgeRunning', 'Test run in progress')); this.badge.value = this.activityService.showViewActivity(Testing.ExplorerViewId, { badge, clazz: 'progress-badge' }); return; } const failures = result.counts[TestRunState.Failed] + result.counts[TestRunState.Errored]; if (failures === 0) { return; } const badge = new NumberBadge(failures, () => localize('testBadgeFailures', '{0} tests failed', failures)); this.badge.value = this.activityService.showViewActivity(Testing.ExplorerViewId, { badge }); } } registerThemingParticipant((theme, collector) => { if (theme.type === 'dark') { const foregroundColor = theme.getColor(foreground); if (foregroundColor) { const fgWithOpacity = new Color(new RGBA(foregroundColor.rgba.r, foregroundColor.rgba.g, foregroundColor.rgba.b, 0.65)); collector.addRule(`.test-explorer .test-explorer-messages { color: ${fgWithOpacity}; }`); } } });
src/vs/workbench/contrib/testing/browser/testingExplorerView.ts
1
https://github.com/microsoft/vscode/commit/07e3bcf7eacfb5a3f9c6e426fc977d176e40a726
[ 0.9990678429603577, 0.04388560727238655, 0.0001621807605260983, 0.00017530372133478522, 0.19896644353866577 ]
{ "id": 10, "code_window": [ "\t\t\t\treturn TreeVisibility.Recurse;\n", "\t\t}\n", "\t}\n", "\n", "\tprivate testLocation(element: ITestTreeElement): FilterResult {\n", "\t\tif (!this._filterToUri || !this.state.currentDocumentOnly.value) {\n", "\t\t\treturn FilterResult.Include;\n", "\t\t}\n", "\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tprivate testState(element: ITestTreeElement): FilterResult {\n", "\t\tswitch (this.state.stateFilter.value) {\n", "\t\t\tcase TestExplorerStateFilter.All:\n", "\t\t\t\treturn FilterResult.Include;\n", "\t\t\tcase TestExplorerStateFilter.OnlyExecuted:\n", "\t\t\t\treturn element.ownState !== TestRunState.Unset ? FilterResult.Include : FilterResult.Inherit;\n", "\t\t\tcase TestExplorerStateFilter.OnlyFailed:\n", "\t\t\t\treturn isFailedState(element.ownState) ? FilterResult.Include : FilterResult.Inherit;\n", "\t\t}\n", "\t}\n", "\n" ], "file_path": "src/vs/workbench/contrib/testing/browser/testingExplorerView.ts", "type": "add", "edit_start_line_idx": 535 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Piece, PieceTreeBase } from 'vs/editor/common/model/pieceTreeTextBuffer/pieceTreeBase'; export class TreeNode { parent: TreeNode; left: TreeNode; right: TreeNode; color: NodeColor; // Piece piece: Piece; size_left: number; // size of the left subtree (not inorder) lf_left: number; // line feeds cnt in the left subtree (not in order) constructor(piece: Piece, color: NodeColor) { this.piece = piece; this.color = color; this.size_left = 0; this.lf_left = 0; this.parent = this; this.left = this; this.right = this; } public next(): TreeNode { if (this.right !== SENTINEL) { return leftest(this.right); } let node: TreeNode = this; while (node.parent !== SENTINEL) { if (node.parent.left === node) { break; } node = node.parent; } if (node.parent === SENTINEL) { return SENTINEL; } else { return node.parent; } } public prev(): TreeNode { if (this.left !== SENTINEL) { return righttest(this.left); } let node: TreeNode = this; while (node.parent !== SENTINEL) { if (node.parent.right === node) { break; } node = node.parent; } if (node.parent === SENTINEL) { return SENTINEL; } else { return node.parent; } } public detach(): void { this.parent = null!; this.left = null!; this.right = null!; } } export const enum NodeColor { Black = 0, Red = 1, } export const SENTINEL: TreeNode = new TreeNode(null!, NodeColor.Black); SENTINEL.parent = SENTINEL; SENTINEL.left = SENTINEL; SENTINEL.right = SENTINEL; SENTINEL.color = NodeColor.Black; export function leftest(node: TreeNode): TreeNode { while (node.left !== SENTINEL) { node = node.left; } return node; } export function righttest(node: TreeNode): TreeNode { while (node.right !== SENTINEL) { node = node.right; } return node; } export function calculateSize(node: TreeNode): number { if (node === SENTINEL) { return 0; } return node.size_left + node.piece.length + calculateSize(node.right); } export function calculateLF(node: TreeNode): number { if (node === SENTINEL) { return 0; } return node.lf_left + node.piece.lineFeedCnt + calculateLF(node.right); } export function resetSentinel(): void { SENTINEL.parent = SENTINEL; } export function leftRotate(tree: PieceTreeBase, x: TreeNode) { let y = x.right; // fix size_left y.size_left += x.size_left + (x.piece ? x.piece.length : 0); y.lf_left += x.lf_left + (x.piece ? x.piece.lineFeedCnt : 0); x.right = y.left; if (y.left !== SENTINEL) { y.left.parent = x; } y.parent = x.parent; if (x.parent === SENTINEL) { tree.root = y; } else if (x.parent.left === x) { x.parent.left = y; } else { x.parent.right = y; } y.left = x; x.parent = y; } export function rightRotate(tree: PieceTreeBase, y: TreeNode) { let x = y.left; y.left = x.right; if (x.right !== SENTINEL) { x.right.parent = y; } x.parent = y.parent; // fix size_left y.size_left -= x.size_left + (x.piece ? x.piece.length : 0); y.lf_left -= x.lf_left + (x.piece ? x.piece.lineFeedCnt : 0); if (y.parent === SENTINEL) { tree.root = x; } else if (y === y.parent.right) { y.parent.right = x; } else { y.parent.left = x; } x.right = y; y.parent = x; } export function rbDelete(tree: PieceTreeBase, z: TreeNode) { let x: TreeNode; let y: TreeNode; if (z.left === SENTINEL) { y = z; x = y.right; } else if (z.right === SENTINEL) { y = z; x = y.left; } else { y = leftest(z.right); x = y.right; } if (y === tree.root) { tree.root = x; // if x is null, we are removing the only node x.color = NodeColor.Black; z.detach(); resetSentinel(); tree.root.parent = SENTINEL; return; } let yWasRed = (y.color === NodeColor.Red); if (y === y.parent.left) { y.parent.left = x; } else { y.parent.right = x; } if (y === z) { x.parent = y.parent; recomputeTreeMetadata(tree, x); } else { if (y.parent === z) { x.parent = y; } else { x.parent = y.parent; } // as we make changes to x's hierarchy, update size_left of subtree first recomputeTreeMetadata(tree, x); y.left = z.left; y.right = z.right; y.parent = z.parent; y.color = z.color; if (z === tree.root) { tree.root = y; } else { if (z === z.parent.left) { z.parent.left = y; } else { z.parent.right = y; } } if (y.left !== SENTINEL) { y.left.parent = y; } if (y.right !== SENTINEL) { y.right.parent = y; } // update metadata // we replace z with y, so in this sub tree, the length change is z.item.length y.size_left = z.size_left; y.lf_left = z.lf_left; recomputeTreeMetadata(tree, y); } z.detach(); if (x.parent.left === x) { let newSizeLeft = calculateSize(x); let newLFLeft = calculateLF(x); if (newSizeLeft !== x.parent.size_left || newLFLeft !== x.parent.lf_left) { let delta = newSizeLeft - x.parent.size_left; let lf_delta = newLFLeft - x.parent.lf_left; x.parent.size_left = newSizeLeft; x.parent.lf_left = newLFLeft; updateTreeMetadata(tree, x.parent, delta, lf_delta); } } recomputeTreeMetadata(tree, x.parent); if (yWasRed) { resetSentinel(); return; } // RB-DELETE-FIXUP let w: TreeNode; while (x !== tree.root && x.color === NodeColor.Black) { if (x === x.parent.left) { w = x.parent.right; if (w.color === NodeColor.Red) { w.color = NodeColor.Black; x.parent.color = NodeColor.Red; leftRotate(tree, x.parent); w = x.parent.right; } if (w.left.color === NodeColor.Black && w.right.color === NodeColor.Black) { w.color = NodeColor.Red; x = x.parent; } else { if (w.right.color === NodeColor.Black) { w.left.color = NodeColor.Black; w.color = NodeColor.Red; rightRotate(tree, w); w = x.parent.right; } w.color = x.parent.color; x.parent.color = NodeColor.Black; w.right.color = NodeColor.Black; leftRotate(tree, x.parent); x = tree.root; } } else { w = x.parent.left; if (w.color === NodeColor.Red) { w.color = NodeColor.Black; x.parent.color = NodeColor.Red; rightRotate(tree, x.parent); w = x.parent.left; } if (w.left.color === NodeColor.Black && w.right.color === NodeColor.Black) { w.color = NodeColor.Red; x = x.parent; } else { if (w.left.color === NodeColor.Black) { w.right.color = NodeColor.Black; w.color = NodeColor.Red; leftRotate(tree, w); w = x.parent.left; } w.color = x.parent.color; x.parent.color = NodeColor.Black; w.left.color = NodeColor.Black; rightRotate(tree, x.parent); x = tree.root; } } } x.color = NodeColor.Black; resetSentinel(); } export function fixInsert(tree: PieceTreeBase, x: TreeNode) { recomputeTreeMetadata(tree, x); while (x !== tree.root && x.parent.color === NodeColor.Red) { if (x.parent === x.parent.parent.left) { const y = x.parent.parent.right; if (y.color === NodeColor.Red) { x.parent.color = NodeColor.Black; y.color = NodeColor.Black; x.parent.parent.color = NodeColor.Red; x = x.parent.parent; } else { if (x === x.parent.right) { x = x.parent; leftRotate(tree, x); } x.parent.color = NodeColor.Black; x.parent.parent.color = NodeColor.Red; rightRotate(tree, x.parent.parent); } } else { const y = x.parent.parent.left; if (y.color === NodeColor.Red) { x.parent.color = NodeColor.Black; y.color = NodeColor.Black; x.parent.parent.color = NodeColor.Red; x = x.parent.parent; } else { if (x === x.parent.left) { x = x.parent; rightRotate(tree, x); } x.parent.color = NodeColor.Black; x.parent.parent.color = NodeColor.Red; leftRotate(tree, x.parent.parent); } } } tree.root.color = NodeColor.Black; } export function updateTreeMetadata(tree: PieceTreeBase, x: TreeNode, delta: number, lineFeedCntDelta: number): void { // node length change or line feed count change while (x !== tree.root && x !== SENTINEL) { if (x.parent.left === x) { x.parent.size_left += delta; x.parent.lf_left += lineFeedCntDelta; } x = x.parent; } } export function recomputeTreeMetadata(tree: PieceTreeBase, x: TreeNode) { let delta = 0; let lf_delta = 0; if (x === tree.root) { return; } if (delta === 0) { // go upwards till the node whose left subtree is changed. while (x !== tree.root && x === x.parent.right) { x = x.parent; } if (x === tree.root) { // well, it means we add a node to the end (inorder) return; } // x is the node whose right subtree is changed. x = x.parent; delta = calculateSize(x.left) - x.size_left; lf_delta = calculateLF(x.left) - x.lf_left; x.size_left += delta; x.lf_left += lf_delta; } // go upwards till root. O(logN) while (x !== tree.root && (delta !== 0 || lf_delta !== 0)) { if (x.parent.left === x) { x.parent.size_left += delta; x.parent.lf_left += lf_delta; } x = x.parent; } }
src/vs/editor/common/model/pieceTreeTextBuffer/rbTreeBase.ts
0
https://github.com/microsoft/vscode/commit/07e3bcf7eacfb5a3f9c6e426fc977d176e40a726
[ 0.00017890013987198472, 0.00017116173694375902, 0.00016305233293678612, 0.00017246545758098364, 0.000004490706032811431 ]
{ "id": 10, "code_window": [ "\t\t\t\treturn TreeVisibility.Recurse;\n", "\t\t}\n", "\t}\n", "\n", "\tprivate testLocation(element: ITestTreeElement): FilterResult {\n", "\t\tif (!this._filterToUri || !this.state.currentDocumentOnly.value) {\n", "\t\t\treturn FilterResult.Include;\n", "\t\t}\n", "\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tprivate testState(element: ITestTreeElement): FilterResult {\n", "\t\tswitch (this.state.stateFilter.value) {\n", "\t\t\tcase TestExplorerStateFilter.All:\n", "\t\t\t\treturn FilterResult.Include;\n", "\t\t\tcase TestExplorerStateFilter.OnlyExecuted:\n", "\t\t\t\treturn element.ownState !== TestRunState.Unset ? FilterResult.Include : FilterResult.Inherit;\n", "\t\t\tcase TestExplorerStateFilter.OnlyFailed:\n", "\t\t\t\treturn isFailedState(element.ownState) ? FilterResult.Include : FilterResult.Inherit;\n", "\t\t}\n", "\t}\n", "\n" ], "file_path": "src/vs/workbench/contrib/testing/browser/testingExplorerView.ts", "type": "add", "edit_start_line_idx": 535 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { StandardTokenType } from 'vs/editor/common/modes'; /** * Describes how comments for a language work. */ export interface CommentRule { /** * The line comment token, like `// this is a comment` */ lineComment?: string | null; /** * The block comment character pair, like `/* block comment *&#47;` */ blockComment?: CharacterPair | null; } /** * The language configuration interface defines the contract between extensions and * various editor features, like automatic bracket insertion, automatic indentation etc. */ export interface LanguageConfiguration { /** * The language's comment settings. */ comments?: CommentRule; /** * The language's brackets. * This configuration implicitly affects pressing Enter around these brackets. */ brackets?: CharacterPair[]; /** * The language's word definition. * If the language supports Unicode identifiers (e.g. JavaScript), it is preferable * to provide a word definition that uses exclusion of known separators. * e.g.: A regex that matches anything except known separators (and dot is allowed to occur in a floating point number): * /(-?\d*\.\d\w*)|([^\`\~\!\@\#\%\^\&\*\(\)\-\=\+\[\{\]\}\\\|\;\:\'\"\,\.\<\>\/\?\s]+)/g */ wordPattern?: RegExp; /** * The language's indentation settings. */ indentationRules?: IndentationRule; /** * The language's rules to be evaluated when pressing Enter. */ onEnterRules?: OnEnterRule[]; /** * The language's auto closing pairs. The 'close' character is automatically inserted with the * 'open' character is typed. If not set, the configured brackets will be used. */ autoClosingPairs?: IAutoClosingPairConditional[]; /** * The language's surrounding pairs. When the 'open' character is typed on a selection, the * selected string is surrounded by the open and close characters. If not set, the autoclosing pairs * settings will be used. */ surroundingPairs?: IAutoClosingPair[]; /** * Defines what characters must be after the cursor for bracket or quote autoclosing to occur when using the \'languageDefined\' autoclosing setting. * * This is typically the set of characters which can not start an expression, such as whitespace, closing brackets, non-unary operators, etc. */ autoCloseBefore?: string; /** * The language's folding rules. */ folding?: FoldingRules; /** * **Deprecated** Do not use. * * @deprecated Will be replaced by a better API soon. */ __electricCharacterSupport?: { docComment?: IDocComment; }; } /** * Describes indentation rules for a language. */ export interface IndentationRule { /** * If a line matches this pattern, then all the lines after it should be unindented once (until another rule matches). */ decreaseIndentPattern: RegExp; /** * If a line matches this pattern, then all the lines after it should be indented once (until another rule matches). */ increaseIndentPattern: RegExp; /** * If a line matches this pattern, then **only the next line** after it should be indented once. */ indentNextLinePattern?: RegExp | null; /** * If a line matches this pattern, then its indentation should not be changed and it should not be evaluated against the other rules. */ unIndentedLinePattern?: RegExp | null; } /** * Describes language specific folding markers such as '#region' and '#endregion'. * The start and end regexes will be tested against the contents of all lines and must be designed efficiently: * - the regex should start with '^' * - regexp flags (i, g) are ignored */ export interface FoldingMarkers { start: RegExp; end: RegExp; } /** * Describes folding rules for a language. */ export interface FoldingRules { /** * Used by the indentation based strategy to decide whether empty lines belong to the previous or the next block. * A language adheres to the off-side rule if blocks in that language are expressed by their indentation. * See [wikipedia](https://en.wikipedia.org/wiki/Off-side_rule) for more information. * If not set, `false` is used and empty lines belong to the previous block. */ offSide?: boolean; /** * Region markers used by the language. */ markers?: FoldingMarkers; } /** * Describes a rule to be evaluated when pressing Enter. */ export interface OnEnterRule { /** * This rule will only execute if the text before the cursor matches this regular expression. */ beforeText: RegExp; /** * This rule will only execute if the text after the cursor matches this regular expression. */ afterText?: RegExp; /** * This rule will only execute if the text above the this line matches this regular expression. */ previousLineText?: RegExp; /** * The action to execute. */ action: EnterAction; } /** * Definition of documentation comments (e.g. Javadoc/JSdoc) */ export interface IDocComment { /** * The string that starts a doc comment (e.g. '/**') */ open: string; /** * The string that appears on the last line and closes the doc comment (e.g. ' * /'). */ close?: string; } /** * A tuple of two characters, like a pair of * opening and closing brackets. */ export type CharacterPair = [string, string]; export interface IAutoClosingPair { open: string; close: string; } export interface IAutoClosingPairConditional extends IAutoClosingPair { notIn?: string[]; } /** * Describes what to do with the indentation when pressing Enter. */ export enum IndentAction { /** * Insert new line and copy the previous line's indentation. */ None = 0, /** * Insert new line and indent once (relative to the previous line's indentation). */ Indent = 1, /** * Insert two new lines: * - the first one indented which will hold the cursor * - the second one at the same indentation level */ IndentOutdent = 2, /** * Insert new line and outdent once (relative to the previous line's indentation). */ Outdent = 3 } /** * Describes what to do when pressing Enter. */ export interface EnterAction { /** * Describe what to do with the indentation. */ indentAction: IndentAction; /** * Describes text to be appended after the new line and after the indentation. */ appendText?: string; /** * Describes the number of characters to remove from the new line's indentation. */ removeText?: number; } /** * @internal */ export interface CompleteEnterAction { /** * Describe what to do with the indentation. */ indentAction: IndentAction; /** * Describes text to be appended after the new line and after the indentation. */ appendText: string; /** * Describes the number of characters to remove from the new line's indentation. */ removeText: number; /** * The line's indentation minus removeText */ indentation: string; } /** * @internal */ export class StandardAutoClosingPairConditional { _standardAutoClosingPairConditionalBrand: void; readonly open: string; readonly close: string; private readonly _standardTokenMask: number; constructor(source: IAutoClosingPairConditional) { this.open = source.open; this.close = source.close; // initially allowed in all tokens this._standardTokenMask = 0; if (Array.isArray(source.notIn)) { for (let i = 0, len = source.notIn.length; i < len; i++) { const notIn: string = source.notIn[i]; switch (notIn) { case 'string': this._standardTokenMask |= StandardTokenType.String; break; case 'comment': this._standardTokenMask |= StandardTokenType.Comment; break; case 'regex': this._standardTokenMask |= StandardTokenType.RegEx; break; } } } } public isOK(standardToken: StandardTokenType): boolean { return (this._standardTokenMask & <number>standardToken) === 0; } } /** * @internal */ export class AutoClosingPairs { // it is useful to be able to get pairs using either end of open and close /** Key is first character of open */ public readonly autoClosingPairsOpenByStart: Map<string, StandardAutoClosingPairConditional[]>; /** Key is last character of open */ public readonly autoClosingPairsOpenByEnd: Map<string, StandardAutoClosingPairConditional[]>; /** Key is first character of close */ public readonly autoClosingPairsCloseByStart: Map<string, StandardAutoClosingPairConditional[]>; /** Key is last character of close */ public readonly autoClosingPairsCloseByEnd: Map<string, StandardAutoClosingPairConditional[]>; /** Key is close. Only has pairs that are a single character */ public readonly autoClosingPairsCloseSingleChar: Map<string, StandardAutoClosingPairConditional[]>; constructor(autoClosingPairs: StandardAutoClosingPairConditional[]) { this.autoClosingPairsOpenByStart = new Map<string, StandardAutoClosingPairConditional[]>(); this.autoClosingPairsOpenByEnd = new Map<string, StandardAutoClosingPairConditional[]>(); this.autoClosingPairsCloseByStart = new Map<string, StandardAutoClosingPairConditional[]>(); this.autoClosingPairsCloseByEnd = new Map<string, StandardAutoClosingPairConditional[]>(); this.autoClosingPairsCloseSingleChar = new Map<string, StandardAutoClosingPairConditional[]>(); for (const pair of autoClosingPairs) { appendEntry(this.autoClosingPairsOpenByStart, pair.open.charAt(0), pair); appendEntry(this.autoClosingPairsOpenByEnd, pair.open.charAt(pair.open.length - 1), pair); appendEntry(this.autoClosingPairsCloseByStart, pair.close.charAt(0), pair); appendEntry(this.autoClosingPairsCloseByEnd, pair.close.charAt(pair.close.length - 1), pair); if (pair.close.length === 1 && pair.open.length === 1) { appendEntry(this.autoClosingPairsCloseSingleChar, pair.close, pair); } } } } function appendEntry<K, V>(target: Map<K, V[]>, key: K, value: V): void { if (target.has(key)) { target.get(key)!.push(value); } else { target.set(key, [value]); } }
src/vs/editor/common/modes/languageConfiguration.ts
0
https://github.com/microsoft/vscode/commit/07e3bcf7eacfb5a3f9c6e426fc977d176e40a726
[ 0.00027752749156206846, 0.00017512126942165196, 0.00016317675181198865, 0.000171555089764297, 0.00001870761116151698 ]
{ "id": 10, "code_window": [ "\t\t\t\treturn TreeVisibility.Recurse;\n", "\t\t}\n", "\t}\n", "\n", "\tprivate testLocation(element: ITestTreeElement): FilterResult {\n", "\t\tif (!this._filterToUri || !this.state.currentDocumentOnly.value) {\n", "\t\t\treturn FilterResult.Include;\n", "\t\t}\n", "\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tprivate testState(element: ITestTreeElement): FilterResult {\n", "\t\tswitch (this.state.stateFilter.value) {\n", "\t\t\tcase TestExplorerStateFilter.All:\n", "\t\t\t\treturn FilterResult.Include;\n", "\t\t\tcase TestExplorerStateFilter.OnlyExecuted:\n", "\t\t\t\treturn element.ownState !== TestRunState.Unset ? FilterResult.Include : FilterResult.Inherit;\n", "\t\t\tcase TestExplorerStateFilter.OnlyFailed:\n", "\t\t\t\treturn isFailedState(element.ownState) ? FilterResult.Include : FilterResult.Inherit;\n", "\t\t}\n", "\t}\n", "\n" ], "file_path": "src/vs/workbench/contrib/testing/browser/testingExplorerView.ts", "type": "add", "edit_start_line_idx": 535 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as nls from 'vs/nls'; import { registerEditorContribution, registerModelAndPositionCommand, EditorAction, EditorCommand, ServicesAccessor, registerEditorAction, registerEditorCommand } from 'vs/editor/browser/editorExtensions'; import * as arrays from 'vs/base/common/arrays'; import { IEditorContribution } from 'vs/editor/common/editorCommon'; import { Disposable, DisposableStore } from 'vs/base/common/lifecycle'; import { ICodeEditor } from 'vs/editor/browser/editorBrowser'; import { EditorOption } from 'vs/editor/common/config/editorOptions'; import { Position, IPosition } from 'vs/editor/common/core/position'; import { ITextModel, IModelDeltaDecoration, TrackedRangeStickiness, IIdentifiedSingleEditOperation } from 'vs/editor/common/model'; import { CancellationToken } from 'vs/base/common/cancellation'; import { IRange, Range } from 'vs/editor/common/core/range'; import { LinkedEditingRangeProviderRegistry, LinkedEditingRanges } from 'vs/editor/common/modes'; import { first, createCancelablePromise, CancelablePromise, Delayer } from 'vs/base/common/async'; import { ModelDecorationOptions } from 'vs/editor/common/model/textModel'; import { ContextKeyExpr, RawContextKey, IContextKeyService, IContextKey } from 'vs/platform/contextkey/common/contextkey'; import { EditorContextKeys } from 'vs/editor/common/editorContextKeys'; import { KeyCode, KeyMod } from 'vs/base/common/keyCodes'; import { KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry'; import { URI } from 'vs/base/common/uri'; import { ICodeEditorService } from 'vs/editor/browser/services/codeEditorService'; import { isPromiseCanceledError, onUnexpectedError, onUnexpectedExternalError } from 'vs/base/common/errors'; import * as strings from 'vs/base/common/strings'; import { registerColor } from 'vs/platform/theme/common/colorRegistry'; import { registerThemingParticipant } from 'vs/platform/theme/common/themeService'; import { Color } from 'vs/base/common/color'; import { LanguageConfigurationRegistry } from 'vs/editor/common/modes/languageConfigurationRegistry'; export const CONTEXT_ONTYPE_RENAME_INPUT_VISIBLE = new RawContextKey<boolean>('LinkedEditingInputVisible', false); const DECORATION_CLASS_NAME = 'linked-editing-decoration'; export class LinkedEditingContribution extends Disposable implements IEditorContribution { public static readonly ID = 'editor.contrib.linkedEditing'; private static readonly DECORATION = ModelDecorationOptions.register({ stickiness: TrackedRangeStickiness.AlwaysGrowsWhenTypingAtEdges, className: DECORATION_CLASS_NAME }); static get(editor: ICodeEditor): LinkedEditingContribution { return editor.getContribution<LinkedEditingContribution>(LinkedEditingContribution.ID); } private _debounceDuration = 200; private readonly _editor: ICodeEditor; private _enabled: boolean; private readonly _visibleContextKey: IContextKey<boolean>; private _rangeUpdateTriggerPromise: Promise<any> | null; private _rangeSyncTriggerPromise: Promise<any> | null; private _currentRequest: CancelablePromise<any> | null; private _currentRequestPosition: Position | null; private _currentRequestModelVersion: number | null; private _currentDecorations: string[]; // The one at index 0 is the reference one private _languageWordPattern: RegExp | null; private _currentWordPattern: RegExp | null; private _ignoreChangeEvent: boolean; private readonly _localToDispose = this._register(new DisposableStore()); constructor( editor: ICodeEditor, @IContextKeyService contextKeyService: IContextKeyService ) { super(); this._editor = editor; this._enabled = false; this._visibleContextKey = CONTEXT_ONTYPE_RENAME_INPUT_VISIBLE.bindTo(contextKeyService); this._currentDecorations = []; this._languageWordPattern = null; this._currentWordPattern = null; this._ignoreChangeEvent = false; this._localToDispose = this._register(new DisposableStore()); this._rangeUpdateTriggerPromise = null; this._rangeSyncTriggerPromise = null; this._currentRequest = null; this._currentRequestPosition = null; this._currentRequestModelVersion = null; this._register(this._editor.onDidChangeModel(() => this.reinitialize())); this._register(this._editor.onDidChangeConfiguration(e => { if (e.hasChanged(EditorOption.linkedEditing) || e.hasChanged(EditorOption.renameOnType)) { this.reinitialize(); } })); this._register(LinkedEditingRangeProviderRegistry.onDidChange(() => this.reinitialize())); this._register(this._editor.onDidChangeModelLanguage(() => this.reinitialize())); this.reinitialize(); } private reinitialize() { const model = this._editor.getModel(); const isEnabled = model !== null && (this._editor.getOption(EditorOption.linkedEditing) || this._editor.getOption(EditorOption.renameOnType)) && LinkedEditingRangeProviderRegistry.has(model); if (isEnabled === this._enabled) { return; } this._enabled = isEnabled; this.clearRanges(); this._localToDispose.clear(); if (!isEnabled || model === null) { return; } this._languageWordPattern = LanguageConfigurationRegistry.getWordDefinition(model.getLanguageIdentifier().id); this._localToDispose.add(model.onDidChangeLanguageConfiguration(() => { this._languageWordPattern = LanguageConfigurationRegistry.getWordDefinition(model.getLanguageIdentifier().id); })); const rangeUpdateScheduler = new Delayer(this._debounceDuration); const triggerRangeUpdate = () => { this._rangeUpdateTriggerPromise = rangeUpdateScheduler.trigger(() => this.updateRanges(), this._debounceDuration); }; const rangeSyncScheduler = new Delayer(0); const triggerRangeSync = (decorations: string[]) => { this._rangeSyncTriggerPromise = rangeSyncScheduler.trigger(() => this._syncRanges(decorations)); }; this._localToDispose.add(this._editor.onDidChangeCursorPosition(() => { triggerRangeUpdate(); })); this._localToDispose.add(this._editor.onDidChangeModelContent((e) => { if (!this._ignoreChangeEvent) { if (this._currentDecorations.length > 0) { const referenceRange = model.getDecorationRange(this._currentDecorations[0]); if (referenceRange && e.changes.every(c => referenceRange.intersectRanges(c.range))) { triggerRangeSync(this._currentDecorations); return; } } } triggerRangeUpdate(); })); this._localToDispose.add({ dispose: () => { rangeUpdateScheduler.cancel(); rangeSyncScheduler.cancel(); } }); this.updateRanges(); } private _syncRanges(decorations: string[]): void { // dalayed invocation, make sure we're still on if (!this._editor.hasModel() || decorations !== this._currentDecorations || decorations.length === 0) { // nothing to do return; } const model = this._editor.getModel(); const referenceRange = model.getDecorationRange(decorations[0]); if (!referenceRange || referenceRange.startLineNumber !== referenceRange.endLineNumber) { return this.clearRanges(); } const referenceValue = model.getValueInRange(referenceRange); if (this._currentWordPattern) { const match = referenceValue.match(this._currentWordPattern); const matchLength = match ? match[0].length : 0; if (matchLength !== referenceValue.length) { return this.clearRanges(); } } let edits: IIdentifiedSingleEditOperation[] = []; for (let i = 1, len = decorations.length; i < len; i++) { const mirrorRange = model.getDecorationRange(decorations[i]); if (!mirrorRange) { continue; } if (mirrorRange.startLineNumber !== mirrorRange.endLineNumber) { edits.push({ range: mirrorRange, text: referenceValue }); } else { let oldValue = model.getValueInRange(mirrorRange); let newValue = referenceValue; let rangeStartColumn = mirrorRange.startColumn; let rangeEndColumn = mirrorRange.endColumn; const commonPrefixLength = strings.commonPrefixLength(oldValue, newValue); rangeStartColumn += commonPrefixLength; oldValue = oldValue.substr(commonPrefixLength); newValue = newValue.substr(commonPrefixLength); const commonSuffixLength = strings.commonSuffixLength(oldValue, newValue); rangeEndColumn -= commonSuffixLength; oldValue = oldValue.substr(0, oldValue.length - commonSuffixLength); newValue = newValue.substr(0, newValue.length - commonSuffixLength); if (rangeStartColumn !== rangeEndColumn || newValue.length !== 0) { edits.push({ range: new Range(mirrorRange.startLineNumber, rangeStartColumn, mirrorRange.endLineNumber, rangeEndColumn), text: newValue }); } } } if (edits.length === 0) { return; } try { this._editor.popUndoStop(); this._ignoreChangeEvent = true; const prevEditOperationType = this._editor._getViewModel().getPrevEditOperationType(); this._editor.executeEdits('linkedEditing', edits); this._editor._getViewModel().setPrevEditOperationType(prevEditOperationType); } finally { this._ignoreChangeEvent = false; } } public dispose(): void { this.clearRanges(); super.dispose(); } public clearRanges(): void { this._visibleContextKey.set(false); this._currentDecorations = this._editor.deltaDecorations(this._currentDecorations, []); if (this._currentRequest) { this._currentRequest.cancel(); this._currentRequest = null; this._currentRequestPosition = null; } } public get currentUpdateTriggerPromise(): Promise<any> { return this._rangeUpdateTriggerPromise || Promise.resolve(); } public get currentSyncTriggerPromise(): Promise<any> { return this._rangeSyncTriggerPromise || Promise.resolve(); } public async updateRanges(force = false): Promise<void> { if (!this._editor.hasModel()) { this.clearRanges(); return; } const position = this._editor.getPosition(); if (!this._enabled && !force || this._editor.getSelections().length > 1) { // disabled or multicursor this.clearRanges(); return; } const model = this._editor.getModel(); const modelVersionId = model.getVersionId(); if (this._currentRequestPosition && this._currentRequestModelVersion === modelVersionId) { if (position.equals(this._currentRequestPosition)) { return; // same position } if (this._currentDecorations && this._currentDecorations.length > 0) { const range = model.getDecorationRange(this._currentDecorations[0]); if (range && range.containsPosition(position)) { return; // just moving inside the existing primary range } } } this._currentRequestPosition = position; this._currentRequestModelVersion = modelVersionId; const request = createCancelablePromise(async token => { try { const response = await getLinkedEditingRanges(model, position, token); if (request !== this._currentRequest) { return; } this._currentRequest = null; if (modelVersionId !== model.getVersionId()) { return; } let ranges: IRange[] = []; if (response?.ranges) { ranges = response.ranges; } this._currentWordPattern = response?.wordPattern || this._languageWordPattern; let foundReferenceRange = false; for (let i = 0, len = ranges.length; i < len; i++) { if (Range.containsPosition(ranges[i], position)) { foundReferenceRange = true; if (i !== 0) { const referenceRange = ranges[i]; ranges.splice(i, 1); ranges.unshift(referenceRange); } break; } } if (!foundReferenceRange) { // Cannot do linked editing if the ranges are not where the cursor is... this.clearRanges(); return; } const decorations: IModelDeltaDecoration[] = ranges.map(range => ({ range: range, options: LinkedEditingContribution.DECORATION })); this._visibleContextKey.set(true); this._currentDecorations = this._editor.deltaDecorations(this._currentDecorations, decorations); } catch (err) { if (!isPromiseCanceledError(err)) { onUnexpectedError(err); } if (this._currentRequest === request || !this._currentRequest) { // stop if we are still the latest request this.clearRanges(); } } }); this._currentRequest = request; return request; } // for testing public setDebounceDuration(timeInMS: number) { this._debounceDuration = timeInMS; } // private printDecorators(model: ITextModel) { // return this._currentDecorations.map(d => { // const range = model.getDecorationRange(d); // if (range) { // return this.printRange(range); // } // return 'invalid'; // }).join(','); // } // private printChanges(changes: IModelContentChange[]) { // return changes.map(c => { // return `${this.printRange(c.range)} - ${c.text}`; // } // ).join(','); // } // private printRange(range: IRange) { // return `${range.startLineNumber},${range.startColumn}/${range.endLineNumber},${range.endColumn}`; // } } export class LinkedEditingAction extends EditorAction { constructor() { super({ id: 'editor.action.linkedEditing', label: nls.localize('linkedEditing.label', "Start Linked Editing"), alias: 'Start Linked Editing', precondition: ContextKeyExpr.and(EditorContextKeys.writable, EditorContextKeys.hasRenameProvider), kbOpts: { kbExpr: EditorContextKeys.editorTextFocus, primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.F2, weight: KeybindingWeight.EditorContrib } }); } runCommand(accessor: ServicesAccessor, args: [URI, IPosition]): void | Promise<void> { const editorService = accessor.get(ICodeEditorService); const [uri, pos] = Array.isArray(args) && args || [undefined, undefined]; if (URI.isUri(uri) && Position.isIPosition(pos)) { return editorService.openCodeEditor({ resource: uri }, editorService.getActiveCodeEditor()).then(editor => { if (!editor) { return; } editor.setPosition(pos); editor.invokeWithinContext(accessor => { this.reportTelemetry(accessor, editor); return this.run(accessor, editor); }); }, onUnexpectedError); } return super.runCommand(accessor, args); } run(_accessor: ServicesAccessor, editor: ICodeEditor): Promise<void> { const controller = LinkedEditingContribution.get(editor); if (controller) { return Promise.resolve(controller.updateRanges(true)); } return Promise.resolve(); } } const LinkedEditingCommand = EditorCommand.bindToContribution<LinkedEditingContribution>(LinkedEditingContribution.get); registerEditorCommand(new LinkedEditingCommand({ id: 'cancelLinkedEditingInput', precondition: CONTEXT_ONTYPE_RENAME_INPUT_VISIBLE, handler: x => x.clearRanges(), kbOpts: { kbExpr: EditorContextKeys.editorTextFocus, weight: KeybindingWeight.EditorContrib + 99, primary: KeyCode.Escape, secondary: [KeyMod.Shift | KeyCode.Escape] } })); function getLinkedEditingRanges(model: ITextModel, position: Position, token: CancellationToken): Promise<LinkedEditingRanges | undefined | null> { const orderedByScore = LinkedEditingRangeProviderRegistry.ordered(model); // in order of score ask the linked editing range provider // until someone response with a good result // (good = not null) return first<LinkedEditingRanges | undefined | null>(orderedByScore.map(provider => async () => { try { return await provider.provideLinkedEditingRanges(model, position, token); } catch (e) { onUnexpectedExternalError(e); return undefined; } }), result => !!result && arrays.isNonEmptyArray(result?.ranges)); } export const editorLinkedEditingBackground = registerColor('editor.linkedEditingBackground', { dark: Color.fromHex('#f00').transparent(0.3), light: Color.fromHex('#f00').transparent(0.3), hc: Color.fromHex('#f00').transparent(0.3) }, nls.localize('editorLinkedEditingBackground', 'Background color when the editor auto renames on type.')); registerThemingParticipant((theme, collector) => { const editorLinkedEditingBackgroundColor = theme.getColor(editorLinkedEditingBackground); if (editorLinkedEditingBackgroundColor) { collector.addRule(`.monaco-editor .${DECORATION_CLASS_NAME} { background: ${editorLinkedEditingBackgroundColor}; border-left-color: ${editorLinkedEditingBackgroundColor}; }`); } }); registerModelAndPositionCommand('_executeLinkedEditingProvider', (model, position) => getLinkedEditingRanges(model, position, CancellationToken.None)); registerEditorContribution(LinkedEditingContribution.ID, LinkedEditingContribution); registerEditorAction(LinkedEditingAction);
src/vs/editor/contrib/linkedEditing/linkedEditing.ts
0
https://github.com/microsoft/vscode/commit/07e3bcf7eacfb5a3f9c6e426fc977d176e40a726
[ 0.00017838455096352845, 0.00017385535466019064, 0.00016587041318416595, 0.00017431165906600654, 0.0000024872515496099368 ]
{ "id": 11, "code_window": [ "\tByLocation = 'location',\n", "\tByName = 'name',\n", "}\n", "\n", "export const testStateNames: { [K in TestRunState]: string } = {\n", "\t[TestRunState.Errored]: localize('testState.errored', 'Errored'),\n", "\t[TestRunState.Failed]: localize('testState.failed', 'Failed'),\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "export const enum TestExplorerStateFilter {\n", "\tOnlyFailed = 'failed',\n", "\tOnlyExecuted = 'excuted',\n", "\tAll = 'all',\n", "}\n", "\n" ], "file_path": "src/vs/workbench/contrib/testing/common/constants.ts", "type": "add", "edit_start_line_idx": 27 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as dom from 'vs/base/browser/dom'; import { ActionBar } from 'vs/base/browser/ui/actionbar/actionbar'; import * as aria from 'vs/base/browser/ui/aria/aria'; import { IIdentityProvider, IKeyboardNavigationLabelProvider, IListVirtualDelegate } from 'vs/base/browser/ui/list/list'; import { DefaultKeyboardNavigationDelegate, IListAccessibilityProvider } from 'vs/base/browser/ui/list/listWidget'; import { ICompressedTreeNode } from 'vs/base/browser/ui/tree/compressedObjectTreeModel'; import { ObjectTree } from 'vs/base/browser/ui/tree/objectTree'; import { ITreeEvent, ITreeFilter, ITreeNode, ITreeRenderer, ITreeSorter, TreeFilterResult, TreeVisibility } from 'vs/base/browser/ui/tree/tree'; import { Action, IAction, IActionViewItem } from 'vs/base/common/actions'; import { DeferredPromise } from 'vs/base/common/async'; import { Color, RGBA } from 'vs/base/common/color'; import { throttle } from 'vs/base/common/decorators'; import { Event } from 'vs/base/common/event'; import { FuzzyScore } from 'vs/base/common/filters'; import { splitGlobAware } from 'vs/base/common/glob'; import { Iterable } from 'vs/base/common/iterator'; import { Disposable, DisposableStore, MutableDisposable, toDisposable } from 'vs/base/common/lifecycle'; import { URI } from 'vs/base/common/uri'; import 'vs/css!./media/testing'; import { ICodeEditor, isCodeEditor } from 'vs/editor/browser/editorBrowser'; import { ICodeEditorService } from 'vs/editor/browser/services/codeEditorService'; import { localize } from 'vs/nls'; import { MenuEntryActionViewItem } from 'vs/platform/actions/browser/menuEntryActionViewItem'; import { MenuItemAction } from 'vs/platform/actions/common/actions'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { IContextMenuService } from 'vs/platform/contextview/browser/contextView'; import { FileKind } from 'vs/platform/files/common/files'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { WorkbenchObjectTree } from 'vs/platform/list/browser/listService'; import { IOpenerService } from 'vs/platform/opener/common/opener'; import { IProgress, IProgressService, IProgressStep } from 'vs/platform/progress/common/progress'; import { IStorageService, StorageScope, StorageTarget } from 'vs/platform/storage/common/storage'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { foreground } from 'vs/platform/theme/common/colorRegistry'; import { IThemeService, registerThemingParticipant, ThemeIcon } from 'vs/platform/theme/common/themeService'; import { TestRunState } from 'vs/workbench/api/common/extHostTypes'; import { IResourceLabel, IResourceLabelOptions, IResourceLabelProps, ResourceLabels } from 'vs/workbench/browser/labels'; import { ViewPane } from 'vs/workbench/browser/parts/views/viewPane'; import { IViewletViewOptions } from 'vs/workbench/browser/parts/views/viewsViewlet'; import { IViewDescriptorService, ViewContainerLocation } from 'vs/workbench/common/views'; import { ITestTreeElement, ITestTreeProjection } from 'vs/workbench/contrib/testing/browser/explorerProjections'; import { HierarchicalByLocationProjection } from 'vs/workbench/contrib/testing/browser/explorerProjections/hierarchalByLocation'; import { HierarchicalByNameProjection } from 'vs/workbench/contrib/testing/browser/explorerProjections/hierarchalByName'; import { testingStatesToIcons } from 'vs/workbench/contrib/testing/browser/icons'; import { ITestExplorerFilterState, TestExplorerFilterState, TestingExplorerFilter } from 'vs/workbench/contrib/testing/browser/testingExplorerFilter'; import { ITestingPeekOpener, TestingOutputPeekController } from 'vs/workbench/contrib/testing/browser/testingOutputPeek'; import { TestExplorerViewMode, TestExplorerViewSorting, Testing, testStateNames } from 'vs/workbench/contrib/testing/common/constants'; import { TestingContextKeys } from 'vs/workbench/contrib/testing/common/testingContextKeys'; import { cmpPriority, isFailedState } from 'vs/workbench/contrib/testing/common/testingStates'; import { ITestResultService, sumCounts, TestStateCount } from 'vs/workbench/contrib/testing/common/testResultService'; import { ITestService } from 'vs/workbench/contrib/testing/common/testService'; import { IWorkspaceTestCollectionService, TestSubscriptionListener } from 'vs/workbench/contrib/testing/common/workspaceTestCollectionService'; import { IActivityService, NumberBadge, ProgressBadge } from 'vs/workbench/services/activity/common/activity'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { DebugAction, RunAction } from './testExplorerActions'; export class TestingExplorerView extends ViewPane { public viewModel!: TestingExplorerViewModel; private filterActionBar = this._register(new MutableDisposable()); private readonly currentSubscription = new MutableDisposable<TestSubscriptionListener>(); private container!: HTMLElement; private finishDiscovery?: () => void; private readonly location = TestingContextKeys.explorerLocation.bindTo(this.contextKeyService);; constructor( options: IViewletViewOptions, @IWorkspaceTestCollectionService private readonly testCollection: IWorkspaceTestCollectionService, @ITestService private readonly testService: ITestService, @IProgressService private readonly progress: IProgressService, @IContextMenuService contextMenuService: IContextMenuService, @IKeybindingService keybindingService: IKeybindingService, @IConfigurationService configurationService: IConfigurationService, @IInstantiationService instantiationService: IInstantiationService, @IViewDescriptorService viewDescriptorService: IViewDescriptorService, @IContextKeyService contextKeyService: IContextKeyService, @IOpenerService openerService: IOpenerService, @IThemeService themeService: IThemeService, @ITelemetryService telemetryService: ITelemetryService, ) { super(options, keybindingService, contextMenuService, configurationService, contextKeyService, viewDescriptorService, instantiationService, openerService, themeService, telemetryService); this._register(testService.onDidChangeProviders(() => this._onDidChangeViewWelcomeState.fire())); this.location.set(viewDescriptorService.getViewLocationById(Testing.ExplorerViewId) ?? ViewContainerLocation.Sidebar); } /** * @override */ public shouldShowWelcome() { return this.testService.providers === 0; } /** * @override */ protected renderBody(container: HTMLElement): void { super.renderBody(container); this.container = dom.append(container, dom.$('.test-explorer')); if (this.location.get() === ViewContainerLocation.Sidebar) { this.filterActionBar.value = this.createFilterActionBar(); } const messagesContainer = dom.append(this.container, dom.$('.test-explorer-messages')); this._register(this.instantiationService.createInstance(TestRunProgress, messagesContainer, this.getProgressLocation())); const listContainer = dom.append(this.container, dom.$('.test-explorer-tree')); this.viewModel = this.instantiationService.createInstance(TestingExplorerViewModel, listContainer, this.onDidChangeBodyVisibility, this.currentSubscription.value); this._register(this.viewModel); this._register(this.onDidChangeBodyVisibility(visible => { if (!visible && this.currentSubscription) { this.currentSubscription.value = undefined; this.viewModel.replaceSubscription(undefined); } else if (visible && !this.currentSubscription.value) { this.currentSubscription.value = this.createSubscription(); this.viewModel.replaceSubscription(this.currentSubscription.value); } })); } /** * @override */ public getActionViewItem(action: IAction): IActionViewItem | undefined { if (action.id === Testing.FilterActionId) { return this.instantiationService.createInstance(TestingExplorerFilter, action); } return super.getActionViewItem(action); } /** * @override */ public saveState() { super.saveState(); } private createFilterActionBar() { const bar = new ActionBar(this.container, { actionViewItemProvider: action => this.getActionViewItem(action) }); bar.push(new Action(Testing.FilterActionId)); bar.getContainer().classList.add('testing-filter-action-bar'); return bar; } private updateDiscoveryProgress(busy: number) { if (!busy && this.finishDiscovery) { this.finishDiscovery(); this.finishDiscovery = undefined; } else if (busy && !this.finishDiscovery) { const promise = new Promise<void>(resolve => { this.finishDiscovery = resolve; }); this.progress.withProgress({ location: this.getProgressLocation() }, () => promise); } } /** * @override */ protected layoutBody(height: number, width: number): void { super.layoutBody(height, width); this.container.style.height = `${height}px`; this.viewModel.layout(height, width); } private createSubscription() { const handle = this.testCollection.subscribeToWorkspaceTests(); handle.subscription.onBusyProvidersChange(() => this.updateDiscoveryProgress(handle.subscription.busyProviders)); return handle; } } export class TestingExplorerViewModel extends Disposable { public tree: ObjectTree<ITestTreeElement, FuzzyScore>; private filter: TestsFilter; public projection!: ITestTreeProjection; private readonly _viewMode = TestingContextKeys.viewMode.bindTo(this.contextKeyService); private readonly _viewSorting = TestingContextKeys.viewSorting.bindTo(this.contextKeyService); /** * Fires when the selected tests change. */ public readonly onDidChangeSelection: Event<ITreeEvent<ITestTreeElement | null>>; public get viewMode() { return this._viewMode.get() ?? TestExplorerViewMode.Tree; } public set viewMode(newMode: TestExplorerViewMode) { if (newMode === this._viewMode.get()) { return; } this._viewMode.set(newMode); this.updatePreferredProjection(); this.storageService.store('testing.viewMode', newMode, StorageScope.WORKSPACE, StorageTarget.USER); } public get viewSorting() { return this._viewSorting.get() ?? TestExplorerViewSorting.ByLocation; } public set viewSorting(newSorting: TestExplorerViewSorting) { if (newSorting === this._viewSorting.get()) { return; } this._viewSorting.set(newSorting); this.tree.resort(null); this.storageService.store('testing.viewSorting', newSorting, StorageScope.WORKSPACE, StorageTarget.USER); } constructor( listContainer: HTMLElement, onDidChangeVisibility: Event<boolean>, private listener: TestSubscriptionListener | undefined, @ITestExplorerFilterState filterState: TestExplorerFilterState, @IInstantiationService private readonly instantiationService: IInstantiationService, @IEditorService private readonly editorService: IEditorService, @IStorageService private readonly storageService: IStorageService, @IContextKeyService private readonly contextKeyService: IContextKeyService, @ITestResultService private readonly testResults: ITestResultService, @ITestingPeekOpener private readonly peekOpener: ITestingPeekOpener, ) { super(); this._viewMode.set(this.storageService.get('testing.viewMode', StorageScope.WORKSPACE, TestExplorerViewMode.Tree) as TestExplorerViewMode); this._viewSorting.set(this.storageService.get('testing.viewSorting', StorageScope.WORKSPACE, TestExplorerViewSorting.ByLocation) as TestExplorerViewSorting); const labels = this._register(instantiationService.createInstance(ResourceLabels, { onDidChangeVisibility: onDidChangeVisibility })); this.filter = this.instantiationService.createInstance(TestsFilter); this.tree = instantiationService.createInstance( WorkbenchObjectTree, 'Test Explorer List', listContainer, new ListDelegate(), [ instantiationService.createInstance(TestsRenderer, labels) ], { simpleKeyboardNavigation: true, identityProvider: instantiationService.createInstance(IdentityProvider), hideTwistiesOfChildlessElements: true, sorter: instantiationService.createInstance(TreeSorter, this), keyboardNavigationLabelProvider: instantiationService.createInstance(TreeKeyboardNavigationLabelProvider), accessibilityProvider: instantiationService.createInstance(ListAccessibilityProvider), filter: this.filter, }) as WorkbenchObjectTree<ITestTreeElement, FuzzyScore>; this._register(Event.any(filterState.currentDocumentOnly.onDidChange, filterState.text.onDidChange)(this.tree.refilter, this.tree)); this._register(editorService.onDidActiveEditorChange(() => { if (filterState.currentDocumentOnly.value && editorService.activeEditor?.resource) { if (this.projection.hasTestInDocument(editorService.activeEditor.resource)) { this.filter.filterToUri(editorService.activeEditor.resource); this.tree.refilter(); } } })); this._register(this.tree); this._register(dom.addStandardDisposableListener(this.tree.getHTMLElement(), 'keydown', evt => { if (DefaultKeyboardNavigationDelegate.mightProducePrintableCharacter(evt)) { filterState.text.value = evt.browserEvent.key; filterState.focusInput(); } })); this.updatePreferredProjection(); this.onDidChangeSelection = this.tree.onDidChangeSelection; this._register(this.tree.onDidChangeSelection(evt => { const selected = evt.elements[0]; if (selected && evt.browserEvent) { this.openEditorForItem(selected); } })); const tracker = this._register(this.instantiationService.createInstance(CodeEditorTracker, this)); this._register(onDidChangeVisibility(visible => { if (visible) { tracker.activate(); } else { tracker.deactivate(); } })); this._register(testResults.onResultsChanged(() => { this.tree.resort(null); })); } /** * Re-layout the tree. */ public layout(height: number, width: number): void { this.tree.layout(height, width); } /** * Replaces the test listener and recalculates the tree. */ public replaceSubscription(listener: TestSubscriptionListener | undefined) { this.listener = listener; this.updatePreferredProjection(); } /** * Reveals and moves focus to the item. */ public async revealItem(item: ITestTreeElement, reveal = true): Promise<void> { if (!this.tree.hasElement(item)) { return; } const chain: ITestTreeElement[] = []; for (let parent = item.parentItem; parent; parent = parent.parentItem) { chain.push(parent); } for (const parent of chain.reverse()) { try { this.tree.expand(parent); } catch { // ignore if not present } } if (reveal === true && this.tree.getRelativeTop(item) === null) { // Don't scroll to the item if it's already visible, or if set not to. this.tree.reveal(item, 0.5); } this.tree.setFocus([item]); this.tree.setSelection([item]); } /** * Collapse all items in the tree. */ public async collapseAll() { this.tree.collapseAll(); } /** * Opens an editor for the item. If there is a failure associated with the * test item, it will be shown. */ public async openEditorForItem(item: ITestTreeElement, preserveFocus = true) { if (await this.tryPeekError(item)) { return; } const location = item?.location; if (!location) { return; } const pane = await this.editorService.openEditor({ resource: location.uri, options: { selection: { startColumn: location.range.startColumn, startLineNumber: location.range.startLineNumber }, preserveFocus, }, }); // if the user selected a failed test and now they didn't, hide the peek const control = pane?.getControl(); if (isCodeEditor(control)) { TestingOutputPeekController.get(control).removePeek(); } } /** * Tries to peek the first test error, if the item is in a failed state. */ private async tryPeekError(item: ITestTreeElement) { const lookup = item.test && this.testResults.getStateByExtId(item.test.item.extId); return lookup && isFailedState(lookup[1].state.state) ? this.peekOpener.tryPeekFirstError(lookup[0], lookup[1], { preserveFocus: true }) : false; } private updatePreferredProjection() { this.projection?.dispose(); if (!this.listener) { this.tree.setChildren(null, []); return; } if (this._viewMode.get() === TestExplorerViewMode.List) { this.projection = this.instantiationService.createInstance(HierarchicalByNameProjection, this.listener); } else { this.projection = this.instantiationService.createInstance(HierarchicalByLocationProjection, this.listener); } this.projection.onUpdate(this.deferUpdate, this); this.projection.applyTo(this.tree); } @throttle(200) private deferUpdate() { this.projection.applyTo(this.tree); } /** * Gets the selected tests from the tree. */ public getSelectedTests() { return this.tree.getSelection(); } } class CodeEditorTracker { private store = new DisposableStore(); private lastRevealed?: ITestTreeElement; constructor( private readonly model: TestingExplorerViewModel, @ICodeEditorService private readonly codeEditorService: ICodeEditorService, ) { } public activate() { const editorStores = new Set<DisposableStore>(); this.store.add(toDisposable(() => { for (const store of editorStores) { store.dispose(); } })); const register = (editor: ICodeEditor) => { const store = new DisposableStore(); editorStores.add(store); store.add(editor.onDidChangeCursorPosition(evt => { const uri = editor.getModel()?.uri; if (!uri) { return; } const test = this.model.projection.getTestAtPosition(uri, evt.position); if (test && test !== this.lastRevealed) { this.model.revealItem(test); this.lastRevealed = test; } })); editor.onDidDispose(() => { store.dispose(); editorStores.delete(store); }); }; this.store.add(this.codeEditorService.onCodeEditorAdd(register)); this.codeEditorService.listCodeEditors().forEach(register); } public deactivate() { this.store.dispose(); this.store = new DisposableStore(); } public dispose() { this.store.dispose(); } } const enum FilterResult { Exclude, Inherit, Include, } class TestsFilter implements ITreeFilter<ITestTreeElement> { private lastText?: string; private filters: [include: boolean, value: string][] | undefined; private _filterToUri: string | undefined; constructor(@ITestExplorerFilterState private readonly state: ITestExplorerFilterState) { } /** * Parses and updates the tree filter. Supports lists of patterns that can be !negated. */ private setFilter(text: string) { this.lastText = text; text = text.trim(); if (!text) { this.filters = undefined; return; } this.filters = []; for (const filter of splitGlobAware(text, ',').map(s => s.trim()).filter(s => !!s.length)) { if (filter.startsWith('!')) { this.filters.push([false, filter.slice(1).toLowerCase()]); } else { this.filters.push([true, filter.toLowerCase()]); } } } public filterToUri(uri: URI) { this._filterToUri = uri.toString(); } /** * @inheritdoc */ public filter(element: ITestTreeElement): TreeFilterResult<void> { if (this.state.text.value !== this.lastText) { this.setFilter(this.state.text.value); } switch (Math.min(this.testFilterText(element), this.testLocation(element))) { case FilterResult.Exclude: return TreeVisibility.Hidden; case FilterResult.Include: return TreeVisibility.Visible; default: return TreeVisibility.Recurse; } } private testLocation(element: ITestTreeElement): FilterResult { if (!this._filterToUri || !this.state.currentDocumentOnly.value) { return FilterResult.Include; } for (let e: ITestTreeElement | null = element; e; e = e!.parentItem) { if (!e.location) { continue; } return e.location.uri.toString() === this._filterToUri ? FilterResult.Include : FilterResult.Exclude; } return FilterResult.Inherit; } private testFilterText(element: ITestTreeElement) { if (!this.filters) { return FilterResult.Include; } for (let e: ITestTreeElement | null = element; e; e = e.parentItem) { // start as included if the first glob is a negation let included = this.filters[0][0] === false ? FilterResult.Exclude : FilterResult.Inherit; const data = e.label.toLowerCase(); for (const [include, filter] of this.filters) { if (data.includes(filter)) { included = include ? FilterResult.Include : FilterResult.Exclude; } } if (included !== FilterResult.Inherit) { return included; } } return FilterResult.Inherit; } } class TreeSorter implements ITreeSorter<ITestTreeElement> { constructor(private readonly viewModel: TestingExplorerViewModel) { } public compare(a: ITestTreeElement, b: ITestTreeElement): number { let delta = cmpPriority(a.state, b.state); if (delta !== 0) { return delta; } if (this.viewModel.viewSorting === TestExplorerViewSorting.ByLocation && a.location && b.location && a.location.uri.toString() === b.location.uri.toString()) { delta = a.location.range.startLineNumber - b.location.range.startLineNumber; if (delta !== 0) { return delta; } } return a.label.localeCompare(b.label); } } class ListAccessibilityProvider implements IListAccessibilityProvider<ITestTreeElement> { getWidgetAriaLabel(): string { return localize('testExplorer', "Test Explorer"); } getAriaLabel(element: ITestTreeElement): string { let label = localize({ key: 'testing.treeElementLabel', comment: ['label then the unit tests state, for example "Addition Tests (Running)"'], }, '{0} ({1})', element.label, testStateNames[element.state]); if (element.retired) { label = localize({ key: 'testing.treeElementLabelOutdated', comment: ['{0} is the original label in testing.treeElementLabel'], }, '{0}, outdated result', label, testStateNames[element.state]); } return label; } } class TreeKeyboardNavigationLabelProvider implements IKeyboardNavigationLabelProvider<ITestTreeElement> { getKeyboardNavigationLabel(element: ITestTreeElement) { return element.label; } } class ListDelegate implements IListVirtualDelegate<ITestTreeElement> { getHeight(_element: ITestTreeElement) { return 22; } getTemplateId(_element: ITestTreeElement) { return TestsRenderer.ID; } } class IdentityProvider implements IIdentityProvider<ITestTreeElement> { public getId(element: ITestTreeElement) { return element.treeId; } } interface TestTemplateData { label: IResourceLabel; icon: HTMLElement; actionBar: ActionBar; } class TestsRenderer implements ITreeRenderer<ITestTreeElement, FuzzyScore, TestTemplateData> { public static readonly ID = 'testExplorer'; constructor( private labels: ResourceLabels, @IInstantiationService private readonly instantiationService: IInstantiationService ) { } renderCompressedElements(node: ITreeNode<ICompressedTreeNode<ITestTreeElement>, FuzzyScore>, index: number, templateData: TestTemplateData): void { const element = node.element.elements[node.element.elements.length - 1]; this.renderElementDirect(element, templateData); } get templateId(): string { return TestsRenderer.ID; } public renderTemplate(container: HTMLElement): TestTemplateData { const wrapper = dom.append(container, dom.$('.test-item')); const icon = dom.append(wrapper, dom.$('.computed-state')); const name = dom.append(wrapper, dom.$('.name')); const label = this.labels.create(name, { supportHighlights: true }); const actionBar = new ActionBar(wrapper, { actionViewItemProvider: action => action instanceof MenuItemAction ? this.instantiationService.createInstance(MenuEntryActionViewItem, action) : undefined }); return { label, actionBar, icon }; } public renderElement(node: ITreeNode<ITestTreeElement, FuzzyScore>, index: number, data: TestTemplateData): void { this.renderElementDirect(node.element, data); } private renderElementDirect(element: ITestTreeElement, data: TestTemplateData) { const label: IResourceLabelProps = { name: element.label }; const options: IResourceLabelOptions = {}; data.actionBar.clear(); const icon = testingStatesToIcons.get(element.state); data.icon.className = 'computed-state ' + (icon ? ThemeIcon.asClassName(icon) : ''); if (element.retired) { data.icon.className += ' retired'; } const test = element.test; if (test) { if (test.item.location) { label.resource = test.item.location.uri; } let title = element.label; for (let p = element.parentItem; p; p = p.parentItem) { title = `${p.label}, ${title}`; } options.title = title; options.fileKind = FileKind.FILE; label.description = element.description; } else { options.fileKind = FileKind.ROOT_FOLDER; } const running = element.state === TestRunState.Running; if (!Iterable.isEmpty(element.runnable)) { data.actionBar.push( this.instantiationService.createInstance(RunAction, element.runnable, running), { icon: true, label: false }, ); } if (!Iterable.isEmpty(element.debuggable)) { data.actionBar.push( this.instantiationService.createInstance(DebugAction, element.debuggable, running), { icon: true, label: false }, ); } data.label.setResource(label, options); } disposeTemplate(templateData: TestTemplateData): void { templateData.label.dispose(); templateData.actionBar.dispose(); } } type CountSummary = ReturnType<typeof collectCounts>; const collectCounts = (count: TestStateCount) => { const failed = count[TestRunState.Errored] + count[TestRunState.Failed]; const passed = count[TestRunState.Passed]; const skipped = count[TestRunState.Skipped]; return { passed, failed, runSoFar: passed + failed, totalWillBeRun: passed + failed + count[TestRunState.Queued] + count[TestRunState.Running], skipped, }; }; const getProgressText = ({ passed, runSoFar, skipped, failed }: CountSummary) => { let percent = passed / runSoFar * 100; if (failed > 0) { // fix: prevent from rounding to 100 if there's any failed test percent = Math.min(percent, 99.9); } if (skipped === 0) { return localize('testProgress', '{0}/{1} tests passed ({2}%)', passed, runSoFar, percent.toPrecision(3)); } else { return localize('testProgressWithSkip', '{0}/{1} tests passed ({2}%, {3} skipped)', passed, runSoFar, percent.toPrecision(3), skipped); } }; class TestRunProgress { private current?: { update: IProgress<IProgressStep>; deferred: DeferredPromise<void> }; private badge = new MutableDisposable(); private readonly resultLister = this.resultService.onResultsChanged(result => { if (!('started' in result)) { return; } this.updateProgress(); this.updateBadge(); result.started.onChange(this.throttledProgressUpdate, this); result.started.onComplete(() => { this.throttledProgressUpdate(); this.updateBadge(); }); }); constructor( private readonly messagesContainer: HTMLElement, private readonly location: string, @IProgressService private readonly progress: IProgressService, @ITestResultService private readonly resultService: ITestResultService, @IActivityService private readonly activityService: IActivityService, ) { } public dispose() { this.resultLister.dispose(); this.current?.deferred.complete(); this.badge.dispose(); } @throttle(200) private throttledProgressUpdate() { this.updateProgress(); } private updateProgress() { const running = this.resultService.results.filter(r => !r.isComplete); if (!running.length) { this.setIdleText(this.resultService.results[0]?.counts); this.current?.deferred.complete(); this.current = undefined; } else if (!this.current) { this.progress.withProgress({ location: this.location, total: 100 }, update => { this.current = { update, deferred: new DeferredPromise() }; this.updateProgress(); return this.current.deferred.p; }); } else { const counts = sumCounts(running.map(r => r.counts)); this.setRunningText(counts); const { runSoFar, totalWillBeRun } = collectCounts(counts); this.current.update.report({ increment: runSoFar, total: totalWillBeRun }); } } private setRunningText(counts: TestStateCount) { this.messagesContainer.dataset.state = 'running'; const collected = collectCounts(counts); if (collected.runSoFar === 0) { this.messagesContainer.innerText = localize('testResultStarting', 'Test run is starting...'); } else { this.messagesContainer.innerText = getProgressText(collected); } } private setIdleText(lastCount?: TestStateCount) { if (!lastCount) { this.messagesContainer.innerText = ''; } else { const collected = collectCounts(lastCount); this.messagesContainer.dataset.state = collected.failed ? 'failed' : 'running'; const doneMessage = getProgressText(collected); this.messagesContainer.innerText = doneMessage; aria.alert(doneMessage); } } private updateBadge() { this.badge.value = undefined; const result = this.resultService.results[0]; // currently running, or last run if (!result) { return; } if (!result.isComplete) { const badge = new ProgressBadge(() => localize('testBadgeRunning', 'Test run in progress')); this.badge.value = this.activityService.showViewActivity(Testing.ExplorerViewId, { badge, clazz: 'progress-badge' }); return; } const failures = result.counts[TestRunState.Failed] + result.counts[TestRunState.Errored]; if (failures === 0) { return; } const badge = new NumberBadge(failures, () => localize('testBadgeFailures', '{0} tests failed', failures)); this.badge.value = this.activityService.showViewActivity(Testing.ExplorerViewId, { badge }); } } registerThemingParticipant((theme, collector) => { if (theme.type === 'dark') { const foregroundColor = theme.getColor(foreground); if (foregroundColor) { const fgWithOpacity = new Color(new RGBA(foregroundColor.rgba.r, foregroundColor.rgba.g, foregroundColor.rgba.b, 0.65)); collector.addRule(`.test-explorer .test-explorer-messages { color: ${fgWithOpacity}; }`); } } });
src/vs/workbench/contrib/testing/browser/testingExplorerView.ts
1
https://github.com/microsoft/vscode/commit/07e3bcf7eacfb5a3f9c6e426fc977d176e40a726
[ 0.9988890290260315, 0.03371334820985794, 0.00016318717098329216, 0.00017491602920927107, 0.17915065586566925 ]
{ "id": 11, "code_window": [ "\tByLocation = 'location',\n", "\tByName = 'name',\n", "}\n", "\n", "export const testStateNames: { [K in TestRunState]: string } = {\n", "\t[TestRunState.Errored]: localize('testState.errored', 'Errored'),\n", "\t[TestRunState.Failed]: localize('testState.failed', 'Failed'),\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "export const enum TestExplorerStateFilter {\n", "\tOnlyFailed = 'failed',\n", "\tOnlyExecuted = 'excuted',\n", "\tAll = 'all',\n", "}\n", "\n" ], "file_path": "src/vs/workbench/contrib/testing/common/constants.ts", "type": "add", "edit_start_line_idx": 27 }
@echo off setlocal pushd %~dp0\.. set VSCODEUSERDATADIR=%TEMP%\vscodeuserfolder-%RANDOM%-%TIME:~6,2% set VSCODECRASHDIR=%~dp0\..\.build\crashes :: Figure out which Electron to use for running tests if "%INTEGRATION_TEST_ELECTRON_PATH%"=="" ( :: Run out of sources: no need to compile as code.bat takes care of it chcp 65001 set INTEGRATION_TEST_ELECTRON_PATH=.\scripts\code.bat set VSCODE_BUILD_BUILTIN_EXTENSIONS_SILENCE_PLEASE=1 echo Storing crash reports into '%VSCODECRASHDIR%'. echo Running integration tests out of sources. ) else ( :: Run from a built: need to compile all test extensions :: because we run extension tests from their source folders :: and the build bundles extensions into .build webpacked call yarn gulp compile-extension:vscode-api-tests^ compile-extension:vscode-colorize-tests^ compile-extension:markdown-language-features^ compile-extension:typescript-language-features^ compile-extension:vscode-custom-editor-tests^ compile-extension:vscode-notebook-tests^ compile-extension:emmet^ compile-extension:css-language-features-server^ compile-extension:html-language-features-server^ compile-extension:json-language-features-server^ compile-extension:git :: Configuration for more verbose output set VSCODE_CLI=1 set ELECTRON_ENABLE_LOGGING=1 echo Storing crash reports into '%VSCODECRASHDIR%'. echo Running integration tests with '%INTEGRATION_TEST_ELECTRON_PATH%' as build. ) :: Integration & performance tests in AMD @REM ::call .\scripts\test.bat --runGlob **\*.integrationTest.js %* @REM ::if %errorlevel% neq 0 exit /b %errorlevel% :: Tests in the extension host call "%INTEGRATION_TEST_ELECTRON_PATH%" %~dp0\..\extensions\vscode-api-tests\testWorkspace --enable-proposed-api=vscode.vscode-api-tests --extensionDevelopmentPath=%~dp0\..\extensions\vscode-api-tests --extensionTestsPath=%~dp0\..\extensions\vscode-api-tests\out\singlefolder-tests --disable-telemetry --crash-reporter-directory=%VSCODECRASHDIR% --no-cached-data --disable-updates --disable-extensions --user-data-dir=%VSCODEUSERDATADIR% if %errorlevel% neq 0 exit /b %errorlevel% call "%INTEGRATION_TEST_ELECTRON_PATH%" %~dp0\..\extensions\vscode-api-tests\testworkspace.code-workspace --enable-proposed-api=vscode.vscode-api-tests --extensionDevelopmentPath=%~dp0\..\extensions\vscode-api-tests --extensionTestsPath=%~dp0\..\extensions\vscode-api-tests\out\workspace-tests --disable-telemetry --crash-reporter-directory=%VSCODECRASHDIR% --no-cached-data --disable-updates --disable-extensions --user-data-dir=%VSCODEUSERDATADIR% if %errorlevel% neq 0 exit /b %errorlevel% call "%INTEGRATION_TEST_ELECTRON_PATH%" %~dp0\..\extensions\vscode-colorize-tests\test --extensionDevelopmentPath=%~dp0\..\extensions\vscode-colorize-tests --extensionTestsPath=%~dp0\..\extensions\vscode-colorize-tests\out --disable-telemetry --crash-reporter-directory=%VSCODECRASHDIR% --no-cached-data --disable-updates --disable-extensions --user-data-dir=%VSCODEUSERDATADIR% if %errorlevel% neq 0 exit /b %errorlevel% call "%INTEGRATION_TEST_ELECTRON_PATH%" %~dp0\..\extensions\typescript-language-features\test-workspace --extensionDevelopmentPath=%~dp0\..\extensions\typescript-language-features --extensionTestsPath=%~dp0\..\extensions\typescript-language-features\out\test\unit --disable-telemetry --crash-reporter-directory=%VSCODECRASHDIR% --no-cached-data --disable-updates --disable-extensions --user-data-dir=%VSCODEUSERDATADIR% if %errorlevel% neq 0 exit /b %errorlevel% call "%INTEGRATION_TEST_ELECTRON_PATH%" %~dp0\..\extensions\markdown-language-features\test-workspace --extensionDevelopmentPath=%~dp0\..\extensions\markdown-language-features --extensionTestsPath=%~dp0\..\extensions\markdown-language-features\out\test --disable-telemetry --crash-reporter-directory=%VSCODECRASHDIR% --no-cached-data --disable-updates --disable-extensions --user-data-dir=%VSCODEUSERDATADIR% if %errorlevel% neq 0 exit /b %errorlevel% call "%INTEGRATION_TEST_ELECTRON_PATH%" $%~dp0\..\extensions\emmet\out\test\test-fixtures --extensionDevelopmentPath=%~dp0\..\extensions\emmet --extensionTestsPath=%~dp0\..\extensions\emmet\out\test --disable-telemetry --crash-reporter-directory=%VSCODECRASHDIR% --no-cached-data --disable-updates --disable-extensions --user-data-dir=%VSCODEUSERDATADIR% . if %errorlevel% neq 0 exit /b %errorlevel% call "%INTEGRATION_TEST_ELECTRON_PATH%" %~dp0\..\extensions\vscode-notebook-tests\test --enable-proposed-api=vscode.vscode-notebook-tests --extensionDevelopmentPath=%~dp0\..\extensions\vscode-notebook-tests --extensionTestsPath=%~dp0\..\extensions\vscode-notebook-tests\out --disable-telemetry --crash-reporter-directory=%VSCODECRASHDIR% --no-cached-data --disable-updates --disable-extensions --user-data-dir=%VSCODEUSERDATADIR% if %errorlevel% neq 0 exit /b %errorlevel% for /f "delims=" %%i in ('node -p "require('fs').realpathSync.native(require('os').tmpdir())"') do set TEMPDIR=%%i set GITWORKSPACE=%TEMPDIR%\git-%RANDOM% mkdir %GITWORKSPACE% call "%INTEGRATION_TEST_ELECTRON_PATH%" %GITWORKSPACE% --extensionDevelopmentPath=%~dp0\..\extensions\git --extensionTestsPath=%~dp0\..\extensions\git\out\test --enable-proposed-api=vscode.git --disable-telemetry --crash-reporter-directory=%VSCODECRASHDIR% --no-cached-data --disable-updates --disable-extensions --user-data-dir=%VSCODEUSERDATADIR% if %errorlevel% neq 0 exit /b %errorlevel% :: Tests in commonJS (CSS, HTML) call %~dp0\node-electron.bat %~dp0\..\extensions\css-language-features/server/test/index.js if %errorlevel% neq 0 exit /b %errorlevel% call %~dp0\node-electron.bat %~dp0\..\extensions\html-language-features/server/test/index.js if %errorlevel% neq 0 exit /b %errorlevel% rmdir /s /q %VSCODEUSERDATADIR% popd endlocal
scripts/test-integration.bat
0
https://github.com/microsoft/vscode/commit/07e3bcf7eacfb5a3f9c6e426fc977d176e40a726
[ 0.000299877836368978, 0.0001855047303251922, 0.0001668483455432579, 0.0001713516394374892, 0.00004049705239594914 ]
{ "id": 11, "code_window": [ "\tByLocation = 'location',\n", "\tByName = 'name',\n", "}\n", "\n", "export const testStateNames: { [K in TestRunState]: string } = {\n", "\t[TestRunState.Errored]: localize('testState.errored', 'Errored'),\n", "\t[TestRunState.Failed]: localize('testState.failed', 'Failed'),\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "export const enum TestExplorerStateFilter {\n", "\tOnlyFailed = 'failed',\n", "\tOnlyExecuted = 'excuted',\n", "\tAll = 'all',\n", "}\n", "\n" ], "file_path": "src/vs/workbench/contrib/testing/common/constants.ts", "type": "add", "edit_start_line_idx": 27 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { IClipboardService } from 'vs/platform/clipboard/common/clipboardService'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IDialogHandler, IDialogResult, IDialogService } from 'vs/platform/dialogs/common/dialogs'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { ILayoutService } from 'vs/platform/layout/browser/layoutService'; import { ILogService } from 'vs/platform/log/common/log'; import { INativeHostService } from 'vs/platform/native/electron-sandbox/native'; import { IProductService } from 'vs/platform/product/common/productService'; import { Registry } from 'vs/platform/registry/common/platform'; import { IThemeService } from 'vs/platform/theme/common/themeService'; import { IWorkbenchContribution, IWorkbenchContributionsRegistry, Extensions as WorkbenchExtensions } from 'vs/workbench/common/contributions'; import { IDialogsModel, IDialogViewItem } from 'vs/workbench/common/dialogs'; import { BrowserDialogHandler } from 'vs/workbench/browser/parts/dialogs/dialogHandler'; import { NativeDialogHandler } from 'vs/workbench/electron-sandbox/parts/dialogs/dialogHandler'; import { DialogService } from 'vs/workbench/services/dialogs/common/dialogService'; import { LifecyclePhase } from 'vs/workbench/services/lifecycle/common/lifecycle'; import { Disposable } from 'vs/base/common/lifecycle'; export class DialogHandlerContribution extends Disposable implements IWorkbenchContribution { private nativeImpl: IDialogHandler; private browserImpl: IDialogHandler; private model: IDialogsModel; private currentDialog: IDialogViewItem | undefined; constructor( @IConfigurationService private configurationService: IConfigurationService, @IDialogService private dialogService: IDialogService, @ILogService logService: ILogService, @ILayoutService layoutService: ILayoutService, @IThemeService themeService: IThemeService, @IKeybindingService keybindingService: IKeybindingService, @IProductService productService: IProductService, @IClipboardService clipboardService: IClipboardService, @INativeHostService nativeHostService: INativeHostService ) { super(); this.browserImpl = new BrowserDialogHandler(logService, layoutService, themeService, keybindingService, productService, clipboardService); this.nativeImpl = new NativeDialogHandler(logService, nativeHostService, productService, clipboardService); this.model = (this.dialogService as DialogService).model; this._register(this.model.onDidShowDialog(() => { if (!this.currentDialog) { this.processDialogs(); } })); this.processDialogs(); } private async processDialogs(): Promise<void> { while (this.model.dialogs.length) { this.currentDialog = this.model.dialogs[0]; let result: IDialogResult | undefined = undefined; // Confirm if (this.currentDialog.args.confirmArgs) { const args = this.currentDialog.args.confirmArgs; result = this.useCustomDialog ? await this.browserImpl.confirm(args.confirmation) : await this.nativeImpl.confirm(args.confirmation); } // Input (custom only) else if (this.currentDialog.args.inputArgs) { const args = this.currentDialog.args.inputArgs; result = await this.browserImpl.input(args.severity, args.message, args.buttons, args.inputs, args.options); } // Message else if (this.currentDialog.args.showArgs) { const args = this.currentDialog.args.showArgs; result = this.useCustomDialog || args.options?.useCustom ? await this.browserImpl.show(args.severity, args.message, args.buttons, args.options) : await this.nativeImpl.show(args.severity, args.message, args.buttons, args.options); } // About else { await this.nativeImpl.about(); } this.currentDialog.close(result); this.currentDialog = undefined; } } private get useCustomDialog(): boolean { return this.configurationService.getValue('window.dialogStyle') === 'custom'; } } const workbenchRegistry = Registry.as<IWorkbenchContributionsRegistry>(WorkbenchExtensions.Workbench); workbenchRegistry.registerWorkbenchContribution(DialogHandlerContribution, LifecyclePhase.Starting);
src/vs/workbench/electron-sandbox/parts/dialogs/dialog.contribution.ts
0
https://github.com/microsoft/vscode/commit/07e3bcf7eacfb5a3f9c6e426fc977d176e40a726
[ 0.00017651726375333965, 0.00017356745956931263, 0.00016832725668791682, 0.00017454168119002134, 0.0000025058313894987805 ]
{ "id": 11, "code_window": [ "\tByLocation = 'location',\n", "\tByName = 'name',\n", "}\n", "\n", "export const testStateNames: { [K in TestRunState]: string } = {\n", "\t[TestRunState.Errored]: localize('testState.errored', 'Errored'),\n", "\t[TestRunState.Failed]: localize('testState.failed', 'Failed'),\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "export const enum TestExplorerStateFilter {\n", "\tOnlyFailed = 'failed',\n", "\tOnlyExecuted = 'excuted',\n", "\tAll = 'all',\n", "}\n", "\n" ], "file_path": "src/vs/workbench/contrib/testing/common/constants.ts", "type": "add", "edit_start_line_idx": 27 }
<h1>Comments</h1> <div id="comments"> {{#each comments}} <h2><a href="/posts/{{../permalink}}#{{id}}">{{title}}</a></h2> <div>{{body}}</div> {{/each}} <p>{{./name}} or {{this/name}} or {{this.name}}</p> </div> <div class="entry"> {{!-- only output author name if an author exists --}} {{#if author}} <h1>{{firstName}} {{lastName}}</h1> {{/if}} </div> <div class="post"> {{> userMessage tagName="h1" }} <h1>Comments</h1> {{#each comments}} {{> userMessage tagName="h2" }} {{/each}} </div>
extensions/vscode-colorize-tests/test/colorize-fixtures/test.hbs
0
https://github.com/microsoft/vscode/commit/07e3bcf7eacfb5a3f9c6e426fc977d176e40a726
[ 0.00017606896290089935, 0.00017435879271943122, 0.0001712603261694312, 0.0001757470890879631, 0.000002194883791162283 ]
{ "id": 0, "code_window": [ "\t\t}\n", "\t\tif proxy.ctx.Req.Request.Method == \"PUT\" {\n", "\t\t\treturn errors.New(\"non allow-listed PUTs not allowed on proxied Prometheus datasource\")\n", "\t\t}\n", "\t}\n", "\n", "\treturn nil\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tif proxy.ctx.Req.Request.Method == \"POST\" {\n", "\t\t\treturn errors.New(\"non allow-listed POSTs not allowed on proxied Prometheus datasource\")\n", "\t\t}\n" ], "file_path": "pkg/api/pluginproxy/ds_proxy.go", "type": "add", "edit_start_line_idx": 292 }
{ "type": "datasource", "name": "Prometheus", "id": "prometheus", "category": "tsdb", "routes": [ { "method": "POST", "path": "api/v1/query", "reqRole": "Viewer" }, { "method": "POST", "path": "api/v1/query_range", "reqRole": "Viewer" }, { "method": "POST", "path": "api/v1/series", "reqRole": "Viewer" }, { "method": "POST", "path": "api/v1/labels", "reqRole": "Viewer" }, { "method": "POST", "path": "api/v1/query_exemplars", "reqRole": "Viewer" }, { "method": "GET", "path": "api/v1/rules", "reqRole": "Viewer" }, { "method": "POST", "path": "api/v1/rules", "reqRole": "Editor" }, { "method": "DELETE", "path": "api/v1/rules", "reqRole": "Editor" } ], "includes": [ { "type": "dashboard", "name": "Prometheus Stats", "path": "dashboards/prometheus_stats.json" }, { "type": "dashboard", "name": "Prometheus 2.0 Stats", "path": "dashboards/prometheus_2_stats.json" }, { "type": "dashboard", "name": "Grafana Stats", "path": "dashboards/grafana_stats.json" } ], "metrics": true, "alerting": true, "annotations": true, "queryOptions": { "minInterval": true }, "info": { "description": "Open source time series database & alerting", "author": { "name": "Grafana Labs", "url": "https://grafana.com" }, "logos": { "small": "img/prometheus_logo.svg", "large": "img/prometheus_logo.svg" }, "links": [ { "name": "Learn more", "url": "https://prometheus.io/" } ] } }
public/app/plugins/datasource/prometheus/plugin.json
1
https://github.com/grafana/grafana/commit/fcd674ec586d31c28fdce026eb80085553d33554
[ 0.000199344998691231, 0.00017400547221768647, 0.000166909143445082, 0.00017180990835186094, 0.000009240456165571231 ]
{ "id": 0, "code_window": [ "\t\t}\n", "\t\tif proxy.ctx.Req.Request.Method == \"PUT\" {\n", "\t\t\treturn errors.New(\"non allow-listed PUTs not allowed on proxied Prometheus datasource\")\n", "\t\t}\n", "\t}\n", "\n", "\treturn nil\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tif proxy.ctx.Req.Request.Method == \"POST\" {\n", "\t\t\treturn errors.New(\"non allow-listed POSTs not allowed on proxied Prometheus datasource\")\n", "\t\t}\n" ], "file_path": "pkg/api/pluginproxy/ds_proxy.go", "type": "add", "edit_start_line_idx": 292 }
package util import ( "fmt" "testing" "github.com/stretchr/testify/assert" ) func TestIsEmail(t *testing.T) { t.Parallel() emails := map[string]struct { description string valid bool }{ "": {description: "the empty string", valid: false}, "@.": {description: "at dot", valid: false}, "me@": {description: "no domain", valid: false}, "abcdef.com": {description: "only a domain name", valid: false}, "@example.org": {description: "no recipient", valid: false}, "please\[email protected]": {description: "new line", valid: false}, "[email protected]": {description: "a simple valid email", valid: true}, "[email protected]": {description: "a gmail style alias", valid: true}, "ö[email protected]": {description: "non-ASCII characters", valid: true}, } for input, testcase := range emails { validity := "invalid" if testcase.valid { validity = "valid" } t.Run(fmt.Sprintf("validating that %s is %s", testcase.description, validity), func(t *testing.T) { assert.Equal(t, testcase.valid, IsEmail(input)) }) } }
pkg/util/validation_test.go
0
https://github.com/grafana/grafana/commit/fcd674ec586d31c28fdce026eb80085553d33554
[ 0.00017459310765843838, 0.0001724872417980805, 0.00016986866830848157, 0.00017274358833674341, 0.0000017436180996810435 ]
{ "id": 0, "code_window": [ "\t\t}\n", "\t\tif proxy.ctx.Req.Request.Method == \"PUT\" {\n", "\t\t\treturn errors.New(\"non allow-listed PUTs not allowed on proxied Prometheus datasource\")\n", "\t\t}\n", "\t}\n", "\n", "\treturn nil\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tif proxy.ctx.Req.Request.Method == \"POST\" {\n", "\t\t\treturn errors.New(\"non allow-listed POSTs not allowed on proxied Prometheus datasource\")\n", "\t\t}\n" ], "file_path": "pkg/api/pluginproxy/ds_proxy.go", "type": "add", "edit_start_line_idx": 292 }
package middleware import ( "crypto/rand" "encoding/base64" "fmt" "io" "net/http" "strings" "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/setting" macaron "gopkg.in/macaron.v1" ) // AddCSPHeader adds the Content Security Policy header. func AddCSPHeader(cfg *setting.Cfg, logger log.Logger) macaron.Handler { return func(w http.ResponseWriter, req *http.Request, c *macaron.Context) { if !cfg.CSPEnabled { return } logger.Debug("Adding CSP header to response", "cfg", fmt.Sprintf("%p", cfg)) ctx, ok := c.Data["ctx"].(*models.ReqContext) if !ok { panic("Failed to convert context into models.ReqContext") } if cfg.CSPTemplate == "" { logger.Debug("CSP template not configured, so returning 500") ctx.JsonApiErr(500, "CSP template has to be configured", nil) return } var buf [16]byte if _, err := io.ReadFull(rand.Reader, buf[:]); err != nil { logger.Error("Failed to generate CSP nonce", "err", err) ctx.JsonApiErr(500, "Failed to generate CSP nonce", err) } nonce := base64.RawStdEncoding.EncodeToString(buf[:]) val := strings.ReplaceAll(cfg.CSPTemplate, "$NONCE", fmt.Sprintf("'nonce-%s'", nonce)) w.Header().Set("Content-Security-Policy", val) ctx.RequestNonce = nonce logger.Debug("Successfully generated CSP nonce", "nonce", nonce) } }
pkg/middleware/csp.go
0
https://github.com/grafana/grafana/commit/fcd674ec586d31c28fdce026eb80085553d33554
[ 0.00034503897768445313, 0.00021027967159170657, 0.00016761693404987454, 0.0001764618937158957, 0.00006809685874031857 ]
{ "id": 0, "code_window": [ "\t\t}\n", "\t\tif proxy.ctx.Req.Request.Method == \"PUT\" {\n", "\t\t\treturn errors.New(\"non allow-listed PUTs not allowed on proxied Prometheus datasource\")\n", "\t\t}\n", "\t}\n", "\n", "\treturn nil\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tif proxy.ctx.Req.Request.Method == \"POST\" {\n", "\t\t\treturn errors.New(\"non allow-listed POSTs not allowed on proxied Prometheus datasource\")\n", "\t\t}\n" ], "file_path": "pkg/api/pluginproxy/ds_proxy.go", "type": "add", "edit_start_line_idx": 292 }
import React from 'react'; import { mount } from 'enzyme'; import { ConfirmModal } from './ConfirmModal'; describe('ConfirmModal', () => { it('renders without error', () => { mount( <ConfirmModal title="Some Title" body="Some Body" confirmText="Confirm" isOpen={true} onConfirm={() => {}} onDismiss={() => {}} /> ); }); it('renders nothing by default or when isOpen is false', () => { const wrapper = mount( <ConfirmModal title="Some Title" body="Some Body" confirmText="Confirm" isOpen={false} onConfirm={() => {}} onDismiss={() => {}} /> ); expect(wrapper.html()).toBe(''); wrapper.setProps({ ...wrapper.props(), isOpen: false }); expect(wrapper.html()).toBe(''); }); it('renders correct contents', () => { const wrapper = mount( <ConfirmModal title="Some Title" body="Content" confirmText="Confirm" isOpen={true} onConfirm={() => {}} onDismiss={() => {}} /> ); expect(wrapper.contains('Some Title')).toBeTruthy(); expect(wrapper.contains('Content')).toBeTruthy(); expect(wrapper.contains('Confirm')).toBeTruthy(); }); });
packages/grafana-ui/src/components/ConfirmModal/ConfirmModal.test.tsx
0
https://github.com/grafana/grafana/commit/fcd674ec586d31c28fdce026eb80085553d33554
[ 0.0001774685806594789, 0.00017510498582851142, 0.00017250000382773578, 0.0001749260409269482, 0.0000016919769905143767 ]
{ "id": 1, "code_window": [ " \"reqRole\": \"Viewer\"\n", " },\n", " {\n", " \"method\": \"GET\",\n", " \"path\": \"api/v1/rules\",\n", " \"reqRole\": \"Viewer\"\n", " },\n", " {\n", " \"method\": \"POST\",\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " \"path\": \"/rules\",\n" ], "file_path": "public/app/plugins/datasource/prometheus/plugin.json", "type": "replace", "edit_start_line_idx": 33 }
{ "type": "datasource", "name": "Prometheus", "id": "prometheus", "category": "tsdb", "routes": [ { "method": "POST", "path": "api/v1/query", "reqRole": "Viewer" }, { "method": "POST", "path": "api/v1/query_range", "reqRole": "Viewer" }, { "method": "POST", "path": "api/v1/series", "reqRole": "Viewer" }, { "method": "POST", "path": "api/v1/labels", "reqRole": "Viewer" }, { "method": "POST", "path": "api/v1/query_exemplars", "reqRole": "Viewer" }, { "method": "GET", "path": "api/v1/rules", "reqRole": "Viewer" }, { "method": "POST", "path": "api/v1/rules", "reqRole": "Editor" }, { "method": "DELETE", "path": "api/v1/rules", "reqRole": "Editor" } ], "includes": [ { "type": "dashboard", "name": "Prometheus Stats", "path": "dashboards/prometheus_stats.json" }, { "type": "dashboard", "name": "Prometheus 2.0 Stats", "path": "dashboards/prometheus_2_stats.json" }, { "type": "dashboard", "name": "Grafana Stats", "path": "dashboards/grafana_stats.json" } ], "metrics": true, "alerting": true, "annotations": true, "queryOptions": { "minInterval": true }, "info": { "description": "Open source time series database & alerting", "author": { "name": "Grafana Labs", "url": "https://grafana.com" }, "logos": { "small": "img/prometheus_logo.svg", "large": "img/prometheus_logo.svg" }, "links": [ { "name": "Learn more", "url": "https://prometheus.io/" } ] } }
public/app/plugins/datasource/prometheus/plugin.json
1
https://github.com/grafana/grafana/commit/fcd674ec586d31c28fdce026eb80085553d33554
[ 0.9781056642532349, 0.11090192198753357, 0.00016793000395409763, 0.0001725686015561223, 0.3066181242465973 ]
{ "id": 1, "code_window": [ " \"reqRole\": \"Viewer\"\n", " },\n", " {\n", " \"method\": \"GET\",\n", " \"path\": \"api/v1/rules\",\n", " \"reqRole\": \"Viewer\"\n", " },\n", " {\n", " \"method\": \"POST\",\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " \"path\": \"/rules\",\n" ], "file_path": "public/app/plugins/datasource/prometheus/plugin.json", "type": "replace", "edit_start_line_idx": 33 }
// Package gcsifaces provides interfaces for Google Cloud Storage. //go:generate mockgen -source $GOFILE -destination ../../mocks/mock_gcsifaces/mocks.go StorageClient package gcsifaces import ( "context" "io" "cloud.google.com/go/storage" "golang.org/x/oauth2/google" "golang.org/x/oauth2/jwt" ) // StorageClient represents a GCS client. type StorageClient interface { // Bucket gets a StorageBucket. Bucket(name string) StorageBucket // FindDefaultCredentials finds default Google credentials. FindDefaultCredentials(ctx context.Context, scope string) (*google.Credentials, error) // JWTConfigFromJSON gets JWT config from a JSON document. JWTConfigFromJSON(keyJSON []byte) (*jwt.Config, error) // SignedURL returns a signed URL for the specified object. SignedURL(bucket, name string, opts *storage.SignedURLOptions) (string, error) } // StorageBucket represents a GCS bucket. type StorageBucket interface { // Object returns a StorageObject for a key. Object(key string) StorageObject } // StorageObject represents a GCS object. type StorageObject interface { // NewWriter returns a new StorageWriter. NewWriter(ctx context.Context) StorageWriter } // StorageWriter represents a GCS writer. type StorageWriter interface { io.WriteCloser // SetACL sets a pre-defined ACL. SetACL(acl string) }
pkg/ifaces/gcsifaces/gcsifaces.go
0
https://github.com/grafana/grafana/commit/fcd674ec586d31c28fdce026eb80085553d33554
[ 0.00027590448735281825, 0.0002102956350427121, 0.00016481238708365709, 0.00020053324988111854, 0.000042267860408173874 ]
{ "id": 1, "code_window": [ " \"reqRole\": \"Viewer\"\n", " },\n", " {\n", " \"method\": \"GET\",\n", " \"path\": \"api/v1/rules\",\n", " \"reqRole\": \"Viewer\"\n", " },\n", " {\n", " \"method\": \"POST\",\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " \"path\": \"/rules\",\n" ], "file_path": "public/app/plugins/datasource/prometheus/plugin.json", "type": "replace", "edit_start_line_idx": 33 }
import React, { FC, memo, useState } from 'react'; import { css } from '@emotion/css'; import { HorizontalGroup, stylesFactory, useTheme, Spinner } from '@grafana/ui'; import { GrafanaTheme } from '@grafana/data'; import { contextSrv } from 'app/core/services/context_srv'; import EmptyListCTA from 'app/core/components/EmptyListCTA/EmptyListCTA'; import { FilterInput } from 'app/core/components/FilterInput/FilterInput'; import { FolderDTO } from 'app/types'; import { useManageDashboards } from '../hooks/useManageDashboards'; import { SearchLayout } from '../types'; import { ConfirmDeleteModal } from './ConfirmDeleteModal'; import { MoveToFolderModal } from './MoveToFolderModal'; import { useSearchQuery } from '../hooks/useSearchQuery'; import { SearchResultsFilter } from './SearchResultsFilter'; import { SearchResults } from './SearchResults'; import { DashboardActions } from './DashboardActions'; export interface Props { folder?: FolderDTO; } const { isEditor } = contextSrv; export const ManageDashboards: FC<Props> = memo(({ folder }) => { const folderId = folder?.id; const folderUid = folder?.uid; const theme = useTheme(); const styles = getStyles(theme); const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false); const [isMoveModalOpen, setIsMoveModalOpen] = useState(false); const defaultLayout = folderId ? SearchLayout.List : SearchLayout.Folders; const queryParamsDefaults = { skipRecent: true, skipStarred: true, folderIds: folderId ? [folderId] : [], layout: defaultLayout, }; const { query, hasFilters, onQueryChange, onTagFilterChange, onStarredFilterChange, onTagAdd, onSortChange, onLayoutChange, } = useSearchQuery(queryParamsDefaults); const { results, loading, initialLoading, canSave, allChecked, hasEditPermissionInFolders, canMove, canDelete, onToggleSection, onToggleChecked, onToggleAllChecked, onDeleteItems, onMoveItems, noFolders, } = useManageDashboards(query, {}, folder); const onMoveTo = () => { setIsMoveModalOpen(true); }; const onItemDelete = () => { setIsDeleteModalOpen(true); }; if (initialLoading) { return <Spinner className={styles.spinner} />; } if (noFolders && !hasFilters) { return ( <EmptyListCTA title="This folder doesn't have any dashboards yet" buttonIcon="plus" buttonTitle="Create Dashboard" buttonLink={`dashboard/new?folderId=${folderId}`} proTip="Add/move dashboards to your folder at ->" proTipLink="dashboards" proTipLinkTitle="Manage dashboards" proTipTarget="" /> ); } return ( <div className={styles.container}> <div> <HorizontalGroup justify="space-between"> <FilterInput value={query.query} onChange={onQueryChange} placeholder={'Search dashboards by name'} /> <DashboardActions isEditor={isEditor} canEdit={hasEditPermissionInFolders || canSave} folderId={folderId} /> </HorizontalGroup> </div> <div className={styles.results}> <SearchResultsFilter allChecked={allChecked} canDelete={hasEditPermissionInFolders && canDelete} canMove={hasEditPermissionInFolders && canMove} deleteItem={onItemDelete} moveTo={onMoveTo} onToggleAllChecked={onToggleAllChecked} onStarredFilterChange={onStarredFilterChange} onSortChange={onSortChange} onTagFilterChange={onTagFilterChange} query={query} hideLayout={!!folderUid} onLayoutChange={onLayoutChange} editable={hasEditPermissionInFolders} /> <SearchResults loading={loading} results={results} editable={hasEditPermissionInFolders} onTagSelected={onTagAdd} onToggleSection={onToggleSection} onToggleChecked={onToggleChecked} layout={query.layout} /> </div> <ConfirmDeleteModal onDeleteItems={onDeleteItems} results={results} isOpen={isDeleteModalOpen} onDismiss={() => setIsDeleteModalOpen(false)} /> <MoveToFolderModal onMoveItems={onMoveItems} results={results} isOpen={isMoveModalOpen} onDismiss={() => setIsMoveModalOpen(false)} /> </div> ); }); export default ManageDashboards; const getStyles = stylesFactory((theme: GrafanaTheme) => { return { container: css` height: 100%; `, results: css` display: flex; flex-direction: column; flex: 1; height: 100%; margin-top: ${theme.spacing.xl}; `, spinner: css` display: flex; justify-content: center; align-items: center; min-height: 200px; `, }; });
public/app/features/search/components/ManageDashboards.tsx
0
https://github.com/grafana/grafana/commit/fcd674ec586d31c28fdce026eb80085553d33554
[ 0.00017684121849015355, 0.0001712937228148803, 0.00016594523913227022, 0.00017180007125716656, 0.000003101298261753982 ]
{ "id": 1, "code_window": [ " \"reqRole\": \"Viewer\"\n", " },\n", " {\n", " \"method\": \"GET\",\n", " \"path\": \"api/v1/rules\",\n", " \"reqRole\": \"Viewer\"\n", " },\n", " {\n", " \"method\": \"POST\",\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " \"path\": \"/rules\",\n" ], "file_path": "public/app/plugins/datasource/prometheus/plugin.json", "type": "replace", "edit_start_line_idx": 33 }
+++ title = "Troubleshooting" description = "Guide to troubleshooting Grafana problems" keywords = ["grafana", "troubleshooting", "documentation", "guide"] weight = 180 +++ # Troubleshooting This page lists some tools and advice to help troubleshoot common Grafana issues. ## Troubleshoot with logs If you encounter an error or problem, then you can check the Grafana server log. Usually located at `/var/log/grafana/grafana.log` on Unix systems or in `<grafana_install_dir>/data/log` on other platforms and manual installations. You can enable more logging by changing log level in the Grafana configuration file. For more information, refer to [Enable debug logging in Grafana CLI]({{< relref "../administration/cli.md#enable-debug-logging" >}}) and the [log section in Configuration]({{< relref "../administration/configuration.md#log" >}}). ## Troubleshoot transformations Order of transformations matters. If the final data output from multiple transformations looks wrong, try changing the transformation order. Each transformation transforms data returned by the previous transformation, not the original raw data. For more information, refer to [Debug transformations]({{< relref "../panels/transformations/apply-transformations.md" >}}). ## Text missing with server-side image rendering (RPM-based Linux) Server-side image (png) rendering is a feature that is optional but very useful when sharing visualizations, for example in alert notifications. If the image is missing text, then make sure you have font packages installed. ```bash sudo yum install fontconfig sudo yum install freetype* sudo yum install urw-fonts ``` ## FAQs Check out the [FAQ section](https://community.grafana.com/c/howto/faq) on the Grafana Community page for answers to frequently asked questions.
docs/sources/troubleshooting/_index.md
0
https://github.com/grafana/grafana/commit/fcd674ec586d31c28fdce026eb80085553d33554
[ 0.00017111228953581303, 0.000166691213962622, 0.00016103197413031012, 0.00016628531739115715, 0.000003603298637244734 ]
{ "id": 2, "code_window": [ " \"reqRole\": \"Viewer\"\n", " },\n", " {\n", " \"method\": \"POST\",\n", " \"path\": \"api/v1/rules\",\n", " \"reqRole\": \"Editor\"\n", " },\n", " {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " \"path\": \"/rules\",\n" ], "file_path": "public/app/plugins/datasource/prometheus/plugin.json", "type": "replace", "edit_start_line_idx": 38 }
{ "type": "datasource", "name": "Prometheus", "id": "prometheus", "category": "tsdb", "routes": [ { "method": "POST", "path": "api/v1/query", "reqRole": "Viewer" }, { "method": "POST", "path": "api/v1/query_range", "reqRole": "Viewer" }, { "method": "POST", "path": "api/v1/series", "reqRole": "Viewer" }, { "method": "POST", "path": "api/v1/labels", "reqRole": "Viewer" }, { "method": "POST", "path": "api/v1/query_exemplars", "reqRole": "Viewer" }, { "method": "GET", "path": "api/v1/rules", "reqRole": "Viewer" }, { "method": "POST", "path": "api/v1/rules", "reqRole": "Editor" }, { "method": "DELETE", "path": "api/v1/rules", "reqRole": "Editor" } ], "includes": [ { "type": "dashboard", "name": "Prometheus Stats", "path": "dashboards/prometheus_stats.json" }, { "type": "dashboard", "name": "Prometheus 2.0 Stats", "path": "dashboards/prometheus_2_stats.json" }, { "type": "dashboard", "name": "Grafana Stats", "path": "dashboards/grafana_stats.json" } ], "metrics": true, "alerting": true, "annotations": true, "queryOptions": { "minInterval": true }, "info": { "description": "Open source time series database & alerting", "author": { "name": "Grafana Labs", "url": "https://grafana.com" }, "logos": { "small": "img/prometheus_logo.svg", "large": "img/prometheus_logo.svg" }, "links": [ { "name": "Learn more", "url": "https://prometheus.io/" } ] } }
public/app/plugins/datasource/prometheus/plugin.json
1
https://github.com/grafana/grafana/commit/fcd674ec586d31c28fdce026eb80085553d33554
[ 0.9941295385360718, 0.11233758926391602, 0.00016776772099547088, 0.0012753073824569583, 0.31177160143852234 ]
{ "id": 2, "code_window": [ " \"reqRole\": \"Viewer\"\n", " },\n", " {\n", " \"method\": \"POST\",\n", " \"path\": \"api/v1/rules\",\n", " \"reqRole\": \"Editor\"\n", " },\n", " {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " \"path\": \"/rules\",\n" ], "file_path": "public/app/plugins/datasource/prometheus/plugin.json", "type": "replace", "edit_start_line_idx": 38 }
import React from 'react'; import { range } from 'lodash'; import { LogRows, PREVIEW_LIMIT } from './LogRows'; import { mount } from 'enzyme'; import { LogLevel, LogRowModel, LogsDedupStrategy, MutableDataFrame, LogsSortOrder } from '@grafana/data'; import { LogRow } from './LogRow'; describe('LogRows', () => { it('renders rows', () => { const rows: LogRowModel[] = [makeLog({ uid: '1' }), makeLog({ uid: '2' }), makeLog({ uid: '3' })]; const wrapper = mount( <LogRows logRows={rows} dedupStrategy={LogsDedupStrategy.none} highlighterExpressions={[]} showLabels={false} showTime={false} wrapLogMessage={true} timeZone={'utc'} /> ); expect(wrapper.find(LogRow).length).toBe(3); expect(wrapper.contains('log message 1')).toBeTruthy(); expect(wrapper.contains('log message 2')).toBeTruthy(); expect(wrapper.contains('log message 3')).toBeTruthy(); }); it('renders rows only limited number of rows first', () => { const rows: LogRowModel[] = [makeLog({ uid: '1' }), makeLog({ uid: '2' }), makeLog({ uid: '3' })]; jest.useFakeTimers(); const wrapper = mount( <LogRows logRows={rows} dedupStrategy={LogsDedupStrategy.none} highlighterExpressions={[]} showLabels={false} showTime={false} wrapLogMessage={true} timeZone={'utc'} previewLimit={1} /> ); expect(wrapper.find(LogRow).length).toBe(1); expect(wrapper.contains('log message 1')).toBeTruthy(); jest.runAllTimers(); wrapper.update(); expect(wrapper.find(LogRow).length).toBe(3); expect(wrapper.contains('log message 1')).toBeTruthy(); expect(wrapper.contains('log message 2')).toBeTruthy(); expect(wrapper.contains('log message 3')).toBeTruthy(); jest.useRealTimers(); }); it('renders deduped rows if supplied', () => { const rows: LogRowModel[] = [makeLog({ uid: '1' }), makeLog({ uid: '2' }), makeLog({ uid: '3' })]; const dedupedRows: LogRowModel[] = [makeLog({ uid: '4' }), makeLog({ uid: '5' })]; const wrapper = mount( <LogRows logRows={rows} deduplicatedRows={dedupedRows} dedupStrategy={LogsDedupStrategy.none} highlighterExpressions={[]} showLabels={false} showTime={false} wrapLogMessage={true} timeZone={'utc'} /> ); expect(wrapper.find(LogRow).length).toBe(2); expect(wrapper.contains('log message 4')).toBeTruthy(); expect(wrapper.contains('log message 5')).toBeTruthy(); }); it('renders with default preview limit', () => { // PREVIEW_LIMIT * 2 is there because otherwise we just render all rows const rows: LogRowModel[] = range(PREVIEW_LIMIT * 2 + 1).map((num) => makeLog({ uid: num.toString() })); const wrapper = mount( <LogRows logRows={rows} dedupStrategy={LogsDedupStrategy.none} highlighterExpressions={[]} showLabels={false} showTime={false} wrapLogMessage={true} timeZone={'utc'} /> ); expect(wrapper.find(LogRow).length).toBe(100); }); it('renders asc ordered rows if order and function supplied', () => { const rows: LogRowModel[] = [ makeLog({ uid: '1', timeEpochMs: 1 }), makeLog({ uid: '3', timeEpochMs: 3 }), makeLog({ uid: '2', timeEpochMs: 2 }), ]; const wrapper = mount( <LogRows logRows={rows} dedupStrategy={LogsDedupStrategy.none} highlighterExpressions={[]} showLabels={false} showTime={false} wrapLogMessage={true} timeZone={'utc'} logsSortOrder={LogsSortOrder.Ascending} /> ); expect(wrapper.find(LogRow).at(0).text()).toBe('log message 1'); expect(wrapper.find(LogRow).at(1).text()).toBe('log message 2'); expect(wrapper.find(LogRow).at(2).text()).toBe('log message 3'); }); it('renders desc ordered rows if order and function supplied', () => { const rows: LogRowModel[] = [ makeLog({ uid: '1', timeEpochMs: 1 }), makeLog({ uid: '3', timeEpochMs: 3 }), makeLog({ uid: '2', timeEpochMs: 2 }), ]; const wrapper = mount( <LogRows logRows={rows} dedupStrategy={LogsDedupStrategy.none} highlighterExpressions={[]} showLabels={false} showTime={false} wrapLogMessage={true} timeZone={'utc'} logsSortOrder={LogsSortOrder.Descending} /> ); expect(wrapper.find(LogRow).at(0).text()).toBe('log message 3'); expect(wrapper.find(LogRow).at(1).text()).toBe('log message 2'); expect(wrapper.find(LogRow).at(2).text()).toBe('log message 1'); }); }); const makeLog = (overrides: Partial<LogRowModel>): LogRowModel => { const uid = overrides.uid || '1'; const timeEpochMs = overrides.timeEpochMs || 1; const entry = `log message ${uid}`; return { entryFieldIndex: 0, rowIndex: 0, // Does not need to be filled with current tests dataFrame: new MutableDataFrame(), uid, logLevel: LogLevel.debug, entry, hasAnsi: false, hasUnescapedContent: false, labels: {}, raw: entry, timeFromNow: '', timeEpochMs, timeEpochNs: (timeEpochMs * 1000000).toString(), timeLocal: '', timeUtc: '', searchWords: [], ...overrides, }; };
packages/grafana-ui/src/components/Logs/LogRows.test.tsx
0
https://github.com/grafana/grafana/commit/fcd674ec586d31c28fdce026eb80085553d33554
[ 0.0001731809607008472, 0.00017070246394723654, 0.000166314173839055, 0.00017076088988687843, 0.0000017584179659024812 ]
{ "id": 2, "code_window": [ " \"reqRole\": \"Viewer\"\n", " },\n", " {\n", " \"method\": \"POST\",\n", " \"path\": \"api/v1/rules\",\n", " \"reqRole\": \"Editor\"\n", " },\n", " {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " \"path\": \"/rules\",\n" ], "file_path": "public/app/plugins/datasource/prometheus/plugin.json", "type": "replace", "edit_start_line_idx": 38 }
package notifications import ( "bytes" "context" "crypto/tls" "fmt" "io" "io/ioutil" "net" "net/http" "time" "golang.org/x/net/context/ctxhttp" "github.com/grafana/grafana/pkg/util" ) type Webhook struct { Url string User string Password string Body string HttpMethod string HttpHeader map[string]string ContentType string } var netTransport = &http.Transport{ TLSClientConfig: &tls.Config{ Renegotiation: tls.RenegotiateFreelyAsClient, }, Proxy: http.ProxyFromEnvironment, Dial: (&net.Dialer{ Timeout: 30 * time.Second, }).Dial, TLSHandshakeTimeout: 5 * time.Second, } var netClient = &http.Client{ Timeout: time.Second * 30, Transport: netTransport, } func (ns *NotificationService) sendWebRequestSync(ctx context.Context, webhook *Webhook) error { ns.log.Debug("Sending webhook", "url", webhook.Url, "http method", webhook.HttpMethod) if webhook.HttpMethod == "" { webhook.HttpMethod = http.MethodPost } if webhook.HttpMethod != http.MethodPost && webhook.HttpMethod != http.MethodPut { return fmt.Errorf("webhook only supports HTTP methods PUT or POST") } request, err := http.NewRequest(webhook.HttpMethod, webhook.Url, bytes.NewReader([]byte(webhook.Body))) if err != nil { return err } if webhook.ContentType == "" { webhook.ContentType = "application/json" } request.Header.Set("Content-Type", webhook.ContentType) request.Header.Set("User-Agent", "Grafana") if webhook.User != "" && webhook.Password != "" { request.Header.Set("Authorization", util.GetBasicAuthHeader(webhook.User, webhook.Password)) } for k, v := range webhook.HttpHeader { request.Header.Set(k, v) } resp, err := ctxhttp.Do(ctx, netClient, request) if err != nil { return err } defer func() { if err := resp.Body.Close(); err != nil { ns.log.Warn("Failed to close response body", "err", err) } }() if resp.StatusCode/100 == 2 { ns.log.Debug("Webhook succeeded", "url", webhook.Url, "statuscode", resp.Status) // flushing the body enables the transport to reuse the same connection if _, err := io.Copy(ioutil.Discard, resp.Body); err != nil { ns.log.Error("Failed to copy resp.Body to ioutil.Discard", "err", err) } return nil } body, err := ioutil.ReadAll(resp.Body) if err != nil { return err } ns.log.Debug("Webhook failed", "url", webhook.Url, "statuscode", resp.Status, "body", string(body)) return fmt.Errorf("Webhook response status %v", resp.Status) }
pkg/services/notifications/webhook.go
0
https://github.com/grafana/grafana/commit/fcd674ec586d31c28fdce026eb80085553d33554
[ 0.000170726198120974, 0.00016778422286733985, 0.00016552882152609527, 0.00016791897360235453, 0.0000014989135479481774 ]
{ "id": 2, "code_window": [ " \"reqRole\": \"Viewer\"\n", " },\n", " {\n", " \"method\": \"POST\",\n", " \"path\": \"api/v1/rules\",\n", " \"reqRole\": \"Editor\"\n", " },\n", " {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " \"path\": \"/rules\",\n" ], "file_path": "public/app/plugins/datasource/prometheus/plugin.json", "type": "replace", "edit_start_line_idx": 38 }
export interface ApplicationState { logActions: boolean; }
public/app/types/application.ts
0
https://github.com/grafana/grafana/commit/fcd674ec586d31c28fdce026eb80085553d33554
[ 0.0001977840147446841, 0.0001977840147446841, 0.0001977840147446841, 0.0001977840147446841, 0 ]
{ "id": 3, "code_window": [ " },\n", " {\n", " \"method\": \"DELETE\",\n", " \"path\": \"api/v1/rules\",\n", " \"reqRole\": \"Editor\"\n", " }\n", " ],\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " \"path\": \"/rules\",\n" ], "file_path": "public/app/plugins/datasource/prometheus/plugin.json", "type": "replace", "edit_start_line_idx": 43 }
{ "type": "datasource", "name": "Prometheus", "id": "prometheus", "category": "tsdb", "routes": [ { "method": "POST", "path": "api/v1/query", "reqRole": "Viewer" }, { "method": "POST", "path": "api/v1/query_range", "reqRole": "Viewer" }, { "method": "POST", "path": "api/v1/series", "reqRole": "Viewer" }, { "method": "POST", "path": "api/v1/labels", "reqRole": "Viewer" }, { "method": "POST", "path": "api/v1/query_exemplars", "reqRole": "Viewer" }, { "method": "GET", "path": "api/v1/rules", "reqRole": "Viewer" }, { "method": "POST", "path": "api/v1/rules", "reqRole": "Editor" }, { "method": "DELETE", "path": "api/v1/rules", "reqRole": "Editor" } ], "includes": [ { "type": "dashboard", "name": "Prometheus Stats", "path": "dashboards/prometheus_stats.json" }, { "type": "dashboard", "name": "Prometheus 2.0 Stats", "path": "dashboards/prometheus_2_stats.json" }, { "type": "dashboard", "name": "Grafana Stats", "path": "dashboards/grafana_stats.json" } ], "metrics": true, "alerting": true, "annotations": true, "queryOptions": { "minInterval": true }, "info": { "description": "Open source time series database & alerting", "author": { "name": "Grafana Labs", "url": "https://grafana.com" }, "logos": { "small": "img/prometheus_logo.svg", "large": "img/prometheus_logo.svg" }, "links": [ { "name": "Learn more", "url": "https://prometheus.io/" } ] } }
public/app/plugins/datasource/prometheus/plugin.json
1
https://github.com/grafana/grafana/commit/fcd674ec586d31c28fdce026eb80085553d33554
[ 0.9893823862075806, 0.11011075973510742, 0.00016517864423803985, 0.0001696100371191278, 0.3108694851398468 ]
{ "id": 3, "code_window": [ " },\n", " {\n", " \"method\": \"DELETE\",\n", " \"path\": \"api/v1/rules\",\n", " \"reqRole\": \"Editor\"\n", " }\n", " ],\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " \"path\": \"/rules\",\n" ], "file_path": "public/app/plugins/datasource/prometheus/plugin.json", "type": "replace", "edit_start_line_idx": 43 }
package web import ( "fmt" "io" "net/http" "strings" "testing" "github.com/grafana/grafana/pkg/tests/testinfra" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) // TestIndexView tests the Grafana index view. func TestIndexView(t *testing.T) { t.Run("CSP enabled", func(t *testing.T) { grafDir, cfgPath := testinfra.CreateGrafDir(t, testinfra.GrafanaOpts{ EnableCSP: true, }) sqlStore := testinfra.SetUpDatabase(t, grafDir) addr := testinfra.StartGrafana(t, grafDir, cfgPath, sqlStore) // nolint:bodyclose resp, html := makeRequest(t, addr) assert.Regexp(t, "script-src 'unsafe-eval' 'strict-dynamic' 'nonce-[^']+';object-src 'none';font-src 'self';style-src 'self' 'unsafe-inline';img-src 'self' data:;base-uri 'self';connect-src 'self' grafana.com;manifest-src 'self';media-src 'none';form-action 'self';", resp.Header.Get("Content-Security-Policy")) assert.Regexp(t, `<script nonce="[^"]+"`, html) }) t.Run("CSP disabled", func(t *testing.T) { grafDir, cfgPath := testinfra.CreateGrafDir(t) sqlStore := testinfra.SetUpDatabase(t, grafDir) addr := testinfra.StartGrafana(t, grafDir, cfgPath, sqlStore) // nolint:bodyclose resp, html := makeRequest(t, addr) assert.Empty(t, resp.Header.Get("Content-Security-Policy")) assert.Regexp(t, `<script nonce=""`, html) }) } func makeRequest(t *testing.T, addr string) (*http.Response, string) { t.Helper() u := fmt.Sprintf("http://%s", addr) t.Logf("Making GET request to %s", u) // nolint:gosec resp, err := http.Get(u) require.NoError(t, err) require.NotNil(t, resp) t.Cleanup(func() { err := resp.Body.Close() assert.NoError(t, err) }) var b strings.Builder _, err = io.Copy(&b, resp.Body) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode) return resp, b.String() }
pkg/tests/web/index_view_test.go
0
https://github.com/grafana/grafana/commit/fcd674ec586d31c28fdce026eb80085553d33554
[ 0.00017402983212377876, 0.00017002105596475303, 0.00016345316544175148, 0.00017136945098172873, 0.0000035552061490307096 ]
{ "id": 3, "code_window": [ " },\n", " {\n", " \"method\": \"DELETE\",\n", " \"path\": \"api/v1/rules\",\n", " \"reqRole\": \"Editor\"\n", " }\n", " ],\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " \"path\": \"/rules\",\n" ], "file_path": "public/app/plugins/datasource/prometheus/plugin.json", "type": "replace", "edit_start_line_idx": 43 }
{ "trailingComma": "es5", "singleQuote": true, "printWidth": 120 }
packages/grafana-toolkit/src/config/prettier.plugin.config.json
0
https://github.com/grafana/grafana/commit/fcd674ec586d31c28fdce026eb80085553d33554
[ 0.00017156694957520813, 0.00017156694957520813, 0.00017156694957520813, 0.00017156694957520813, 0 ]
{ "id": 3, "code_window": [ " },\n", " {\n", " \"method\": \"DELETE\",\n", " \"path\": \"api/v1/rules\",\n", " \"reqRole\": \"Editor\"\n", " }\n", " ],\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " \"path\": \"/rules\",\n" ], "file_path": "public/app/plugins/datasource/prometheus/plugin.json", "type": "replace", "edit_start_line_idx": 43 }
e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
scripts/build/release_publisher/testdata/grafana-enterprise-5.4.0-123pre1.linux-amd64.tar.gz.sha256
0
https://github.com/grafana/grafana/commit/fcd674ec586d31c28fdce026eb80085553d33554
[ 0.00016654364299029112, 0.00016654364299029112, 0.00016654364299029112, 0.00016654364299029112, 0 ]
{ "id": 0, "code_window": [ " try {\n", " return await getSpecificNLS(resourceUrlTemplate, languageId, version);\n", " }\n", " catch (err) {\n", " if (/\\[404\\]/.test(err.message)) {\n", " console.warn(`Language pack ${languageId}@${version} is missing. Downloading previous version...`);\n", " return await getSpecificNLS(resourceUrlTemplate, languageId, previousVersion(version));\n", " }\n", " else {\n", " throw err;\n", " }\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " const thePreviousVersion = previousVersion(version);\n", " console.warn(`Language pack ${languageId}@${version} is missing. Downloading previous version ${thePreviousVersion}...`);\n", " try {\n", " return await getSpecificNLS(resourceUrlTemplate, languageId, thePreviousVersion);\n", " }\n", " catch (err) {\n", " if (/\\[404\\]/.test(err.message)) {\n", " console.warn(`Language pack ${languageId}@${thePreviousVersion} is missing. Downloading previous version...`);\n", " return await getSpecificNLS(resourceUrlTemplate, languageId, previousVersion(thePreviousVersion));\n", " }\n", " else {\n", " throw err;\n", " }\n", " }\n" ], "file_path": "build/lib/policies.js", "type": "replace", "edit_start_line_idx": 440 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { spawn } from 'child_process'; import { promises as fs } from 'fs'; import * as path from 'path'; import * as byline from 'byline'; import { rgPath } from '@vscode/ripgrep'; import * as Parser from 'tree-sitter'; import fetch from 'node-fetch'; const { typescript } = require('tree-sitter-typescript'); const product = require('../../product.json'); type NlsString = { value: string; nlsKey: string }; function isNlsString(value: string | NlsString | undefined): value is NlsString { return value ? typeof value !== 'string' : false; } function isStringArray(value: (string | NlsString)[]): value is string[] { return !value.some(s => isNlsString(s)); } function isNlsStringArray(value: (string | NlsString)[]): value is NlsString[] { return value.every(s => isNlsString(s)); } interface Category { readonly moduleName: string; readonly name: NlsString; } enum PolicyType { StringEnum } interface Policy { readonly category: Category; readonly minimumVersion: string; renderADMX(regKey: string): string[]; renderADMLStrings(translations?: LanguageTranslations): string[]; renderADMLPresentation(): string; } function renderADMLString(prefix: string, moduleName: string, nlsString: NlsString, translations?: LanguageTranslations): string { let value: string | undefined; if (translations) { const moduleTranslations = translations[moduleName]; if (moduleTranslations) { value = moduleTranslations[nlsString.nlsKey]; } } if (!value) { value = nlsString.value; } return `<string id="${prefix}_${nlsString.nlsKey}">${value}</string>`; } abstract class BasePolicy implements Policy { constructor( protected policyType: PolicyType, protected name: string, readonly category: Category, readonly minimumVersion: string, protected description: NlsString, protected moduleName: string, ) { } protected renderADMLString(nlsString: NlsString, translations?: LanguageTranslations): string { return renderADMLString(this.name, this.moduleName, nlsString, translations); } renderADMX(regKey: string) { return [ `<policy name="${this.name}" class="Both" displayName="$(string.${this.name})" explainText="$(string.${this.name}_${this.description.nlsKey})" key="Software\\Policies\\Microsoft\\${regKey}" presentation="$(presentation.${this.name})">`, ` <parentCategory ref="${this.category.name.nlsKey}" />`, ` <supportedOn ref="Supported_${this.minimumVersion.replace(/\./g, '_')}" />`, ` <elements>`, ...this.renderADMXElements(), ` </elements>`, `</policy>` ]; } protected abstract renderADMXElements(): string[]; renderADMLStrings(translations?: LanguageTranslations) { return [ `<string id="${this.name}">${this.name}</string>`, this.renderADMLString(this.description, translations) ]; } renderADMLPresentation(): string { return `<presentation id="${this.name}">${this.renderADMLPresentationContents()}</presentation>`; } protected abstract renderADMLPresentationContents(): string; } class BooleanPolicy extends BasePolicy { static from( name: string, category: Category, minimumVersion: string, description: NlsString, moduleName: string, settingNode: Parser.SyntaxNode ): BooleanPolicy | undefined { const type = getStringProperty(settingNode, 'type'); if (type !== 'boolean') { return undefined; } return new BooleanPolicy(name, category, minimumVersion, description, moduleName); } private constructor( name: string, category: Category, minimumVersion: string, description: NlsString, moduleName: string, ) { super(PolicyType.StringEnum, name, category, minimumVersion, description, moduleName); } protected renderADMXElements(): string[] { return [ `<boolean id="${this.name}" valueName="${this.name}">`, ` <trueValue><decimal value="1" /></trueValue><falseValue><decimal value="0" /></falseValue>`, `</boolean>` ]; } renderADMLPresentationContents() { return `<checkBox refId="${this.name}">${this.name}</checkBox>`; } } class IntPolicy extends BasePolicy { static from( name: string, category: Category, minimumVersion: string, description: NlsString, moduleName: string, settingNode: Parser.SyntaxNode ): IntPolicy | undefined { const type = getStringProperty(settingNode, 'type'); if (type !== 'number') { return undefined; } const defaultValue = getIntProperty(settingNode, 'default'); if (typeof defaultValue === 'undefined') { throw new Error(`Missing required 'default' property.`); } return new IntPolicy(name, category, minimumVersion, description, moduleName, defaultValue); } private constructor( name: string, category: Category, minimumVersion: string, description: NlsString, moduleName: string, protected readonly defaultValue: number, ) { super(PolicyType.StringEnum, name, category, minimumVersion, description, moduleName); } protected renderADMXElements(): string[] { return [ `<decimal id="${this.name}" valueName="${this.name}" />` // `<decimal id="Quarantine_PurgeItemsAfterDelay" valueName="PurgeItemsAfterDelay" minValue="0" maxValue="10000000" />` ]; } renderADMLPresentationContents() { return `<decimalTextBox refId="${this.name}" defaultValue="${this.defaultValue}">${this.name}</decimalTextBox>`; } } class StringPolicy extends BasePolicy { static from( name: string, category: Category, minimumVersion: string, description: NlsString, moduleName: string, settingNode: Parser.SyntaxNode ): StringPolicy | undefined { const type = getStringProperty(settingNode, 'type'); if (type !== 'string') { return undefined; } return new StringPolicy(name, category, minimumVersion, description, moduleName); } private constructor( name: string, category: Category, minimumVersion: string, description: NlsString, moduleName: string, ) { super(PolicyType.StringEnum, name, category, minimumVersion, description, moduleName); } protected renderADMXElements(): string[] { return [`<text id="${this.name}" valueName="${this.name}" required="true" />`]; } renderADMLPresentationContents() { return `<textBox refId="${this.name}"><label>${this.name}:</label></textBox>`; } } class StringEnumPolicy extends BasePolicy { static from( name: string, category: Category, minimumVersion: string, description: NlsString, moduleName: string, settingNode: Parser.SyntaxNode ): StringEnumPolicy | undefined { const type = getStringProperty(settingNode, 'type'); if (type !== 'string') { return undefined; } const enum_ = getStringArrayProperty(settingNode, 'enum'); if (!enum_) { return undefined; } if (!isStringArray(enum_)) { throw new Error(`Property 'enum' should not be localized.`); } const enumDescriptions = getStringArrayProperty(settingNode, 'enumDescriptions'); if (!enumDescriptions) { throw new Error(`Missing required 'enumDescriptions' property.`); } else if (!isNlsStringArray(enumDescriptions)) { throw new Error(`Property 'enumDescriptions' should be localized.`); } return new StringEnumPolicy(name, category, minimumVersion, description, moduleName, enum_, enumDescriptions); } private constructor( name: string, category: Category, minimumVersion: string, description: NlsString, moduleName: string, protected enum_: string[], protected enumDescriptions: NlsString[], ) { super(PolicyType.StringEnum, name, category, minimumVersion, description, moduleName); } protected renderADMXElements(): string[] { return [ `<enum id="${this.name}" valueName="${this.name}">`, ...this.enum_.map((value, index) => ` <item displayName="$(string.${this.name}_${this.enumDescriptions[index].nlsKey})"><value><string>${value}</string></value></item>`), `</enum>` ]; } renderADMLStrings(translations?: LanguageTranslations) { return [ ...super.renderADMLStrings(translations), ...this.enumDescriptions.map(e => this.renderADMLString(e, translations)) ]; } renderADMLPresentationContents() { return `<dropdownList refId="${this.name}" />`; } } interface QType<T> { Q: string; value(matches: Parser.QueryMatch[]): T | undefined; } const IntQ: QType<number> = { Q: `(number) @value`, value(matches: Parser.QueryMatch[]): number | undefined { const match = matches[0]; if (!match) { return undefined; } const value = match.captures.filter(c => c.name === 'value')[0]?.node.text; if (!value) { throw new Error(`Missing required 'value' property.`); } return parseInt(value); } }; const StringQ: QType<string | NlsString> = { Q: `[ (string (string_fragment) @value) (call_expression function: (identifier) @localizeFn arguments: (arguments (string (string_fragment) @nlsKey) (string (string_fragment) @value)) (#eq? @localizeFn localize)) ]`, value(matches: Parser.QueryMatch[]): string | NlsString | undefined { const match = matches[0]; if (!match) { return undefined; } const value = match.captures.filter(c => c.name === 'value')[0]?.node.text; if (!value) { throw new Error(`Missing required 'value' property.`); } const nlsKey = match.captures.filter(c => c.name === 'nlsKey')[0]?.node.text; if (nlsKey) { return { value, nlsKey }; } else { return value; } } }; const StringArrayQ: QType<(string | NlsString)[]> = { Q: `(array ${StringQ.Q})`, value(matches: Parser.QueryMatch[]): (string | NlsString)[] | undefined { if (matches.length === 0) { return undefined; } return matches.map(match => { return StringQ.value([match]) as string | NlsString; }); } }; function getProperty<T>(qtype: QType<T>, node: Parser.SyntaxNode, key: string): T | undefined { const query = new Parser.Query( typescript, `( (pair key: [(property_identifier)(string)] @key value: ${qtype.Q} ) (#eq? @key ${key}) )` ); return qtype.value(query.matches(node)); } function getIntProperty(node: Parser.SyntaxNode, key: string): number | undefined { return getProperty(IntQ, node, key); } function getStringProperty(node: Parser.SyntaxNode, key: string): string | NlsString | undefined { return getProperty(StringQ, node, key); } function getStringArrayProperty(node: Parser.SyntaxNode, key: string): (string | NlsString)[] | undefined { return getProperty(StringArrayQ, node, key); } // TODO: add more policy types const PolicyTypes = [ BooleanPolicy, IntPolicy, StringEnumPolicy, StringPolicy, ]; function getPolicy( moduleName: string, configurationNode: Parser.SyntaxNode, settingNode: Parser.SyntaxNode, policyNode: Parser.SyntaxNode, categories: Map<string, Category> ): Policy { const name = getStringProperty(policyNode, 'name'); if (!name) { throw new Error(`Missing required 'name' property.`); } else if (isNlsString(name)) { throw new Error(`Property 'name' should be a literal string.`); } const categoryName = getStringProperty(configurationNode, 'title'); if (!categoryName) { throw new Error(`Missing required 'title' property.`); } else if (!isNlsString(categoryName)) { throw new Error(`Property 'title' should be localized.`); } const categoryKey = `${categoryName.nlsKey}:${categoryName.value}`; let category = categories.get(categoryKey); if (!category) { category = { moduleName, name: categoryName }; categories.set(categoryKey, category); } const minimumVersion = getStringProperty(policyNode, 'minimumVersion'); if (!minimumVersion) { throw new Error(`Missing required 'minimumVersion' property.`); } else if (isNlsString(minimumVersion)) { throw new Error(`Property 'minimumVersion' should be a literal string.`); } const description = getStringProperty(settingNode, 'description'); if (!description) { throw new Error(`Missing required 'description' property.`); } if (!isNlsString(description)) { throw new Error(`Property 'description' should be localized.`); } let result: Policy | undefined; for (const policyType of PolicyTypes) { if (result = policyType.from(name, category, minimumVersion, description, moduleName, settingNode)) { break; } } if (!result) { throw new Error(`Failed to parse policy '${name}'.`); } return result; } function getPolicies(moduleName: string, node: Parser.SyntaxNode): Policy[] { const query = new Parser.Query(typescript, ` ( (call_expression function: (member_expression property: (property_identifier) @registerConfigurationFn) (#eq? @registerConfigurationFn registerConfiguration) arguments: (arguments (object (pair key: [(property_identifier)(string)] @propertiesKey (#eq? @propertiesKey properties) value: (object (pair key: [(property_identifier)(string)] value: (object (pair key: [(property_identifier)(string)] @policyKey (#eq? @policyKey policy) value: (object) @policy )) @setting )) )) @configuration) ) ) `); const categories = new Map<string, Category>(); return query.matches(node).map(m => { const configurationNode = m.captures.filter(c => c.name === 'configuration')[0].node; const settingNode = m.captures.filter(c => c.name === 'setting')[0].node; const policyNode = m.captures.filter(c => c.name === 'policy')[0].node; return getPolicy(moduleName, configurationNode, settingNode, policyNode, categories); }); } async function getFiles(root: string): Promise<string[]> { return new Promise((c, e) => { const result: string[] = []; const rg = spawn(rgPath, ['-l', 'registerConfiguration\\(', '-g', 'src/**/*.ts', '-g', '!src/**/test/**', root]); const stream = byline(rg.stdout.setEncoding('utf8')); stream.on('data', path => result.push(path)); stream.on('error', err => e(err)); stream.on('end', () => c(result)); }); } function renderADMX(regKey: string, versions: string[], categories: Category[], policies: Policy[]) { versions = versions.map(v => v.replace(/\./g, '_')); return `<?xml version="1.0" encoding="utf-8"?> <policyDefinitions revision="1.1" schemaVersion="1.0"> <policyNamespaces> <target prefix="${regKey}" namespace="Microsoft.Policies.${regKey}" /> </policyNamespaces> <resources minRequiredRevision="1.0" /> <supportedOn> <definitions> ${versions.map(v => `<definition name="Supported_${v}" displayName="$(string.Supported_${v})" />`).join(`\n `)} </definitions> </supportedOn> <categories> <category displayName="$(string.Application)" name="Application" /> ${categories.map(c => `<category displayName="$(string.Category_${c.name.nlsKey})" name="${c.name.nlsKey}"><parentCategory ref="Application" /></category>`).join(`\n `)} </categories> <policies> ${policies.map(p => p.renderADMX(regKey)).flat().join(`\n `)} </policies> </policyDefinitions> `; } function renderADML(appName: string, versions: string[], categories: Category[], policies: Policy[], translations?: LanguageTranslations) { return `<?xml version="1.0" encoding="utf-8"?> <policyDefinitionResources revision="1.0" schemaVersion="1.0"> <displayName /> <description /> <resources> <stringTable> <string id="Application">${appName}</string> ${versions.map(v => `<string id="Supported_${v.replace(/\./g, '_')}">${appName} &gt;= ${v}</string>`)} ${categories.map(c => renderADMLString('Category', c.moduleName, c.name, translations))} ${policies.map(p => p.renderADMLStrings(translations)).flat().join(`\n `)} </stringTable> <presentationTable> ${policies.map(p => p.renderADMLPresentation()).join(`\n `)} </presentationTable> </resources> </policyDefinitionResources> `; } function renderGP(policies: Policy[], translations: Translations) { const appName = product.nameLong; const regKey = product.win32RegValueName; const versions = [...new Set(policies.map(p => p.minimumVersion)).values()].sort(); const categories = [...new Set(policies.map(p => p.category))]; return { admx: renderADMX(regKey, versions, categories, policies), adml: [ { languageId: 'en-us', contents: renderADML(appName, versions, categories, policies) }, ...translations.map(({ languageId, languageTranslations }) => ({ languageId, contents: renderADML(appName, versions, categories, policies, languageTranslations) })) ] }; } const Languages = { 'fr': 'fr-fr', 'it': 'it-it', 'de': 'de-de', 'es': 'es-es', 'ru': 'ru-ru', 'zh-hans': 'zh-cn', 'zh-hant': 'zh-tw', 'ja': 'ja-jp', 'ko': 'ko-kr', 'cs': 'cs-cz', 'pt-br': 'pt-br', 'tr': 'tr-tr', 'pl': 'pl-pl', }; type LanguageTranslations = { [moduleName: string]: { [nlsKey: string]: string } }; type Translations = { languageId: string; languageTranslations: LanguageTranslations }[]; async function getLatestStableVersion(updateUrl: string) { const res = await fetch(`${updateUrl}/api/update/darwin/stable/latest`); const { name: version } = await res.json() as { name: string }; return version; } async function getSpecificNLS(resourceUrlTemplate: string, languageId: string, version: string) { const resource = { publisher: 'ms-ceintl', name: `vscode-language-pack-${languageId}`, version, path: 'extension/translations/main.i18n.json' }; const url = resourceUrlTemplate.replace(/\{([^}]+)\}/g, (_, key) => resource[key as keyof typeof resource]); const res = await fetch(url); if (res.status !== 200) { throw new Error(`[${res.status}] Error downloading language pack ${languageId}@${version}`); } const { contents: result } = await res.json() as { contents: LanguageTranslations }; return result; } function previousVersion(version: string): string { const [, major, minor, patch] = /^(\d+)\.(\d+)\.(\d+)$/.exec(version)!; return `${major}.${parseInt(minor) - 1}.${patch}`; } async function getNLS(resourceUrlTemplate: string, languageId: string, version: string) { try { return await getSpecificNLS(resourceUrlTemplate, languageId, version); } catch (err) { if (/\[404\]/.test(err.message)) { console.warn(`Language pack ${languageId}@${version} is missing. Downloading previous version...`); return await getSpecificNLS(resourceUrlTemplate, languageId, previousVersion(version)); } else { throw err; } } } async function parsePolicies(): Promise<Policy[]> { const parser = new Parser(); parser.setLanguage(typescript); const files = await getFiles(process.cwd()); const base = path.join(process.cwd(), 'src'); const policies = []; for (const file of files) { const moduleName = path.relative(base, file).replace(/\.ts$/i, '').replace(/\\/g, '/'); const contents = await fs.readFile(file, { encoding: 'utf8' }); const tree = parser.parse(contents); policies.push(...getPolicies(moduleName, tree.rootNode)); } return policies; } async function getTranslations(): Promise<Translations> { const updateUrl = product.updateUrl; if (!updateUrl) { console.warn(`Skipping policy localization: No 'updateUrl' found in 'product.json'.`); return []; } const resourceUrlTemplate = product.extensionsGallery?.resourceUrlTemplate; if (!resourceUrlTemplate) { console.warn(`Skipping policy localization: No 'resourceUrlTemplate' found in 'product.json'.`); return []; } const version = await getLatestStableVersion(updateUrl); const languageIds = Object.keys(Languages); return await Promise.all(languageIds.map( languageId => getNLS(resourceUrlTemplate, languageId, version) .then(languageTranslations => ({ languageId, languageTranslations })) )); } async function main() { const [policies, translations] = await Promise.all([parsePolicies(), getTranslations()]); const { admx, adml } = await renderGP(policies, translations); const root = '.build/policies/win32'; await fs.rm(root, { recursive: true, force: true }); await fs.mkdir(root, { recursive: true }); await fs.writeFile(path.join(root, `${product.win32RegValueName}.admx`), admx.replace(/\r?\n/g, '\n')); for (const { languageId, contents } of adml) { const languagePath = path.join(root, languageId === 'en-us' ? 'en-us' : Languages[languageId as keyof typeof Languages]); await fs.mkdir(languagePath, { recursive: true }); await fs.writeFile(path.join(languagePath, `${product.win32RegValueName}.adml`), contents.replace(/\r?\n/g, '\n')); } } if (require.main === module) { main().catch(err => { console.error(err); process.exit(1); }); }
build/lib/policies.ts
1
https://github.com/microsoft/vscode/commit/73fd3f11032e7b83c2ae011b5516e6ddd19e3db2
[ 0.9980218410491943, 0.014583851210772991, 0.00016645091818645597, 0.00017295120051130652, 0.11839444190263748 ]
{ "id": 0, "code_window": [ " try {\n", " return await getSpecificNLS(resourceUrlTemplate, languageId, version);\n", " }\n", " catch (err) {\n", " if (/\\[404\\]/.test(err.message)) {\n", " console.warn(`Language pack ${languageId}@${version} is missing. Downloading previous version...`);\n", " return await getSpecificNLS(resourceUrlTemplate, languageId, previousVersion(version));\n", " }\n", " else {\n", " throw err;\n", " }\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " const thePreviousVersion = previousVersion(version);\n", " console.warn(`Language pack ${languageId}@${version} is missing. Downloading previous version ${thePreviousVersion}...`);\n", " try {\n", " return await getSpecificNLS(resourceUrlTemplate, languageId, thePreviousVersion);\n", " }\n", " catch (err) {\n", " if (/\\[404\\]/.test(err.message)) {\n", " console.warn(`Language pack ${languageId}@${thePreviousVersion} is missing. Downloading previous version...`);\n", " return await getSpecificNLS(resourceUrlTemplate, languageId, previousVersion(thePreviousVersion));\n", " }\n", " else {\n", " throw err;\n", " }\n", " }\n" ], "file_path": "build/lib/policies.js", "type": "replace", "edit_start_line_idx": 440 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as platform from 'vs/base/common/platform'; import { EditorOptions, EditorOption, FindComputedEditorOptionValueById, EDITOR_FONT_DEFAULTS } from 'vs/editor/common/config/editorOptions'; import { EditorZoom } from 'vs/editor/common/config/editorZoom'; /** * Determined from empirical observations. * @internal */ const GOLDEN_LINE_HEIGHT_RATIO = platform.isMacintosh ? 1.5 : 1.35; /** * @internal */ const MINIMUM_LINE_HEIGHT = 8; /** * @internal */ export interface IValidatedEditorOptions { get<T extends EditorOption>(id: T): FindComputedEditorOptionValueById<T>; } export class BareFontInfo { readonly _bareFontInfoBrand: void = undefined; /** * @internal */ public static createFromValidatedSettings(options: IValidatedEditorOptions, pixelRatio: number, ignoreEditorZoom: boolean): BareFontInfo { const fontFamily = options.get(EditorOption.fontFamily); const fontWeight = options.get(EditorOption.fontWeight); const fontSize = options.get(EditorOption.fontSize); const fontFeatureSettings = options.get(EditorOption.fontLigatures); const lineHeight = options.get(EditorOption.lineHeight); const letterSpacing = options.get(EditorOption.letterSpacing); return BareFontInfo._create(fontFamily, fontWeight, fontSize, fontFeatureSettings, lineHeight, letterSpacing, pixelRatio, ignoreEditorZoom); } /** * @internal */ public static createFromRawSettings(opts: { fontFamily?: string; fontWeight?: string; fontSize?: number; fontLigatures?: boolean | string; lineHeight?: number; letterSpacing?: number }, pixelRatio: number, ignoreEditorZoom: boolean = false): BareFontInfo { const fontFamily = EditorOptions.fontFamily.validate(opts.fontFamily); const fontWeight = EditorOptions.fontWeight.validate(opts.fontWeight); const fontSize = EditorOptions.fontSize.validate(opts.fontSize); const fontFeatureSettings = EditorOptions.fontLigatures2.validate(opts.fontLigatures); const lineHeight = EditorOptions.lineHeight.validate(opts.lineHeight); const letterSpacing = EditorOptions.letterSpacing.validate(opts.letterSpacing); return BareFontInfo._create(fontFamily, fontWeight, fontSize, fontFeatureSettings, lineHeight, letterSpacing, pixelRatio, ignoreEditorZoom); } /** * @internal */ private static _create(fontFamily: string, fontWeight: string, fontSize: number, fontFeatureSettings: string, lineHeight: number, letterSpacing: number, pixelRatio: number, ignoreEditorZoom: boolean): BareFontInfo { if (lineHeight === 0) { lineHeight = GOLDEN_LINE_HEIGHT_RATIO * fontSize; } else if (lineHeight < MINIMUM_LINE_HEIGHT) { // Values too small to be line heights in pixels are in ems. lineHeight = lineHeight * fontSize; } // Enforce integer, minimum constraints lineHeight = Math.round(lineHeight); if (lineHeight < MINIMUM_LINE_HEIGHT) { lineHeight = MINIMUM_LINE_HEIGHT; } const editorZoomLevelMultiplier = 1 + (ignoreEditorZoom ? 0 : EditorZoom.getZoomLevel() * 0.1); fontSize *= editorZoomLevelMultiplier; lineHeight *= editorZoomLevelMultiplier; return new BareFontInfo({ pixelRatio: pixelRatio, fontFamily: fontFamily, fontWeight: fontWeight, fontSize: fontSize, fontFeatureSettings: fontFeatureSettings, lineHeight: lineHeight, letterSpacing: letterSpacing }); } readonly pixelRatio: number; readonly fontFamily: string; readonly fontWeight: string; readonly fontSize: number; readonly fontFeatureSettings: string; readonly lineHeight: number; readonly letterSpacing: number; /** * @internal */ protected constructor(opts: { pixelRatio: number; fontFamily: string; fontWeight: string; fontSize: number; fontFeatureSettings: string; lineHeight: number; letterSpacing: number; }) { this.pixelRatio = opts.pixelRatio; this.fontFamily = String(opts.fontFamily); this.fontWeight = String(opts.fontWeight); this.fontSize = opts.fontSize; this.fontFeatureSettings = opts.fontFeatureSettings; this.lineHeight = opts.lineHeight | 0; this.letterSpacing = opts.letterSpacing; } /** * @internal */ public getId(): string { return `${this.pixelRatio}-${this.fontFamily}-${this.fontWeight}-${this.fontSize}-${this.fontFeatureSettings}-${this.lineHeight}-${this.letterSpacing}`; } /** * @internal */ public getMassagedFontFamily(): string { const fallbackFontFamily = EDITOR_FONT_DEFAULTS.fontFamily; const fontFamily = BareFontInfo._wrapInQuotes(this.fontFamily); if (fallbackFontFamily && this.fontFamily !== fallbackFontFamily) { return `${fontFamily}, ${fallbackFontFamily}`; } return fontFamily; } private static _wrapInQuotes(fontFamily: string): string { if (/[,"']/.test(fontFamily)) { // Looks like the font family might be already escaped return fontFamily; } if (/[+ ]/.test(fontFamily)) { // Wrap a font family using + or <space> with quotes return `"${fontFamily}"`; } return fontFamily; } } // change this whenever `FontInfo` members are changed export const SERIALIZED_FONT_INFO_VERSION = 1; export class FontInfo extends BareFontInfo { readonly _editorStylingBrand: void = undefined; readonly version: number = SERIALIZED_FONT_INFO_VERSION; readonly isTrusted: boolean; readonly isMonospace: boolean; readonly typicalHalfwidthCharacterWidth: number; readonly typicalFullwidthCharacterWidth: number; readonly canUseHalfwidthRightwardsArrow: boolean; readonly spaceWidth: number; readonly middotWidth: number; readonly wsmiddotWidth: number; readonly maxDigitWidth: number; /** * @internal */ constructor(opts: { pixelRatio: number; fontFamily: string; fontWeight: string; fontSize: number; fontFeatureSettings: string; lineHeight: number; letterSpacing: number; isMonospace: boolean; typicalHalfwidthCharacterWidth: number; typicalFullwidthCharacterWidth: number; canUseHalfwidthRightwardsArrow: boolean; spaceWidth: number; middotWidth: number; wsmiddotWidth: number; maxDigitWidth: number; }, isTrusted: boolean) { super(opts); this.isTrusted = isTrusted; this.isMonospace = opts.isMonospace; this.typicalHalfwidthCharacterWidth = opts.typicalHalfwidthCharacterWidth; this.typicalFullwidthCharacterWidth = opts.typicalFullwidthCharacterWidth; this.canUseHalfwidthRightwardsArrow = opts.canUseHalfwidthRightwardsArrow; this.spaceWidth = opts.spaceWidth; this.middotWidth = opts.middotWidth; this.wsmiddotWidth = opts.wsmiddotWidth; this.maxDigitWidth = opts.maxDigitWidth; } /** * @internal */ public equals(other: FontInfo): boolean { return ( this.fontFamily === other.fontFamily && this.fontWeight === other.fontWeight && this.fontSize === other.fontSize && this.fontFeatureSettings === other.fontFeatureSettings && this.lineHeight === other.lineHeight && this.letterSpacing === other.letterSpacing && this.typicalHalfwidthCharacterWidth === other.typicalHalfwidthCharacterWidth && this.typicalFullwidthCharacterWidth === other.typicalFullwidthCharacterWidth && this.canUseHalfwidthRightwardsArrow === other.canUseHalfwidthRightwardsArrow && this.spaceWidth === other.spaceWidth && this.middotWidth === other.middotWidth && this.wsmiddotWidth === other.wsmiddotWidth && this.maxDigitWidth === other.maxDigitWidth ); } }
src/vs/editor/common/config/fontInfo.ts
0
https://github.com/microsoft/vscode/commit/73fd3f11032e7b83c2ae011b5516e6ddd19e3db2
[ 0.0001778768637450412, 0.0001735086989356205, 0.0001610676117707044, 0.00017428497085347772, 0.000004492833795666229 ]
{ "id": 0, "code_window": [ " try {\n", " return await getSpecificNLS(resourceUrlTemplate, languageId, version);\n", " }\n", " catch (err) {\n", " if (/\\[404\\]/.test(err.message)) {\n", " console.warn(`Language pack ${languageId}@${version} is missing. Downloading previous version...`);\n", " return await getSpecificNLS(resourceUrlTemplate, languageId, previousVersion(version));\n", " }\n", " else {\n", " throw err;\n", " }\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " const thePreviousVersion = previousVersion(version);\n", " console.warn(`Language pack ${languageId}@${version} is missing. Downloading previous version ${thePreviousVersion}...`);\n", " try {\n", " return await getSpecificNLS(resourceUrlTemplate, languageId, thePreviousVersion);\n", " }\n", " catch (err) {\n", " if (/\\[404\\]/.test(err.message)) {\n", " console.warn(`Language pack ${languageId}@${thePreviousVersion} is missing. Downloading previous version...`);\n", " return await getSpecificNLS(resourceUrlTemplate, languageId, previousVersion(thePreviousVersion));\n", " }\n", " else {\n", " throw err;\n", " }\n", " }\n" ], "file_path": "build/lib/policies.js", "type": "replace", "edit_start_line_idx": 440 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { DisposableStore } from 'vs/base/common/lifecycle'; import { isEqual } from 'vs/base/common/resources'; import { URI, UriComponents } from 'vs/base/common/uri'; import { IActiveCodeEditor, IViewZone } from 'vs/editor/browser/editorBrowser'; import { ICodeEditorService } from 'vs/editor/browser/services/codeEditorService'; import { ExtensionIdentifier } from 'vs/platform/extensions/common/extensions'; import { reviveWebviewContentOptions } from 'vs/workbench/api/browser/mainThreadWebviews'; import { ExtHostContext, ExtHostEditorInsetsShape, IWebviewContentOptions, MainContext, MainThreadEditorInsetsShape } from 'vs/workbench/api/common/extHost.protocol'; import { IWebviewService, IWebviewElement } from 'vs/workbench/contrib/webview/browser/webview'; import { extHostNamedCustomer, IExtHostContext } from 'vs/workbench/services/extensions/common/extHostCustomers'; // todo@jrieken move these things back into something like contrib/insets class EditorWebviewZone implements IViewZone { readonly domNode: HTMLElement; readonly afterLineNumber: number; readonly afterColumn: number; readonly heightInLines: number; private _id?: string; // suppressMouseDown?: boolean | undefined; // heightInPx?: number | undefined; // minWidthInPx?: number | undefined; // marginDomNode?: HTMLElement | null | undefined; // onDomNodeTop?: ((top: number) => void) | undefined; // onComputedHeight?: ((height: number) => void) | undefined; constructor( readonly editor: IActiveCodeEditor, readonly line: number, readonly height: number, readonly webview: IWebviewElement, ) { this.domNode = document.createElement('div'); this.domNode.style.zIndex = '10'; // without this, the webview is not interactive this.afterLineNumber = line; this.afterColumn = 1; this.heightInLines = height; editor.changeViewZones(accessor => this._id = accessor.addZone(this)); webview.mountTo(this.domNode); } dispose(): void { this.editor.changeViewZones(accessor => this._id && accessor.removeZone(this._id)); } } @extHostNamedCustomer(MainContext.MainThreadEditorInsets) export class MainThreadEditorInsets implements MainThreadEditorInsetsShape { private readonly _proxy: ExtHostEditorInsetsShape; private readonly _disposables = new DisposableStore(); private readonly _insets = new Map<number, EditorWebviewZone>(); constructor( context: IExtHostContext, @ICodeEditorService private readonly _editorService: ICodeEditorService, @IWebviewService private readonly _webviewService: IWebviewService, ) { this._proxy = context.getProxy(ExtHostContext.ExtHostEditorInsets); } dispose(): void { this._disposables.dispose(); } async $createEditorInset(handle: number, id: string, uri: UriComponents, line: number, height: number, options: IWebviewContentOptions, extensionId: ExtensionIdentifier, extensionLocation: UriComponents): Promise<void> { let editor: IActiveCodeEditor | undefined; id = id.substr(0, id.indexOf(',')); //todo@jrieken HACK for (const candidate of this._editorService.listCodeEditors()) { if (candidate.getId() === id && candidate.hasModel() && isEqual(candidate.getModel().uri, URI.revive(uri))) { editor = candidate; break; } } if (!editor) { setTimeout(() => this._proxy.$onDidDispose(handle)); return; } const disposables = new DisposableStore(); const webview = this._webviewService.createWebviewElement({ id: 'mainThreadCodeInsets_' + handle, options: { enableFindWidget: false, }, contentOptions: reviveWebviewContentOptions(options), extension: { id: extensionId, location: URI.revive(extensionLocation) } }); const webviewZone = new EditorWebviewZone(editor, line, height, webview); const remove = () => { disposables.dispose(); this._proxy.$onDidDispose(handle); this._insets.delete(handle); }; disposables.add(editor.onDidChangeModel(remove)); disposables.add(editor.onDidDispose(remove)); disposables.add(webviewZone); disposables.add(webview); disposables.add(webview.onMessage(msg => this._proxy.$onDidReceiveMessage(handle, msg.message))); this._insets.set(handle, webviewZone); } $disposeEditorInset(handle: number): void { const inset = this.getInset(handle); this._insets.delete(handle); inset.dispose(); } $setHtml(handle: number, value: string): void { const inset = this.getInset(handle); inset.webview.html = value; } $setOptions(handle: number, options: IWebviewContentOptions): void { const inset = this.getInset(handle); inset.webview.contentOptions = reviveWebviewContentOptions(options); } async $postMessage(handle: number, value: any): Promise<boolean> { const inset = this.getInset(handle); inset.webview.postMessage(value); return true; } private getInset(handle: number): EditorWebviewZone { const inset = this._insets.get(handle); if (!inset) { throw new Error('Unknown inset'); } return inset; } }
src/vs/workbench/api/browser/mainThreadCodeInsets.ts
0
https://github.com/microsoft/vscode/commit/73fd3f11032e7b83c2ae011b5516e6ddd19e3db2
[ 0.0001769435912137851, 0.00017397575720679015, 0.0001693920057732612, 0.00017385136743541807, 0.0000018990560874954099 ]
{ "id": 0, "code_window": [ " try {\n", " return await getSpecificNLS(resourceUrlTemplate, languageId, version);\n", " }\n", " catch (err) {\n", " if (/\\[404\\]/.test(err.message)) {\n", " console.warn(`Language pack ${languageId}@${version} is missing. Downloading previous version...`);\n", " return await getSpecificNLS(resourceUrlTemplate, languageId, previousVersion(version));\n", " }\n", " else {\n", " throw err;\n", " }\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " const thePreviousVersion = previousVersion(version);\n", " console.warn(`Language pack ${languageId}@${version} is missing. Downloading previous version ${thePreviousVersion}...`);\n", " try {\n", " return await getSpecificNLS(resourceUrlTemplate, languageId, thePreviousVersion);\n", " }\n", " catch (err) {\n", " if (/\\[404\\]/.test(err.message)) {\n", " console.warn(`Language pack ${languageId}@${thePreviousVersion} is missing. Downloading previous version...`);\n", " return await getSpecificNLS(resourceUrlTemplate, languageId, previousVersion(thePreviousVersion));\n", " }\n", " else {\n", " throw err;\n", " }\n", " }\n" ], "file_path": "build/lib/policies.js", "type": "replace", "edit_start_line_idx": 440 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Event, RelativePattern, Uri, workspace } from 'vscode'; import { IDisposable, anyEvent } from './util'; export interface IFileWatcher extends IDisposable { readonly event: Event<Uri>; } export function watch(location: string): IFileWatcher { const watcher = workspace.createFileSystemWatcher(new RelativePattern(location, '*')); return new class implements IFileWatcher { event = anyEvent(watcher.onDidCreate, watcher.onDidChange, watcher.onDidDelete); dispose() { watcher.dispose(); } }; }
extensions/git/src/watch.ts
0
https://github.com/microsoft/vscode/commit/73fd3f11032e7b83c2ae011b5516e6ddd19e3db2
[ 0.0001750772207742557, 0.00017253973055630922, 0.00017014570767059922, 0.0001723962341202423, 0.000002015836798818782 ]
{ "id": 1, "code_window": [ "async function getNLS(resourceUrlTemplate: string, languageId: string, version: string) {\n", "\ttry {\n", "\t\treturn await getSpecificNLS(resourceUrlTemplate, languageId, version);\n", "\t} catch (err) {\n", "\t\tif (/\\[404\\]/.test(err.message)) {\n", "\t\t\tconsole.warn(`Language pack ${languageId}@${version} is missing. Downloading previous version...`);\n", "\t\t\treturn await getSpecificNLS(resourceUrlTemplate, languageId, previousVersion(version));\n", "\t\t} else {\n", "\t\t\tthrow err;\n", "\t\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tconst thePreviousVersion = previousVersion(version);\n", "\t\t\tconsole.warn(`Language pack ${languageId}@${version} is missing. Downloading previous version ${thePreviousVersion}...`);\n", "\t\t\ttry {\n", "\t\t\t\treturn await getSpecificNLS(resourceUrlTemplate, languageId, thePreviousVersion);\n", "\t\t\t} catch (err) {\n", "\t\t\t\tif (/\\[404\\]/.test(err.message)) {\n", "\t\t\t\t\tconsole.warn(`Language pack ${languageId}@${thePreviousVersion} is missing. Downloading previous version...`);\n", "\t\t\t\t\treturn await getSpecificNLS(resourceUrlTemplate, languageId, previousVersion(thePreviousVersion));\n", "\t\t\t\t} else {\n", "\t\t\t\t\tthrow err;\n", "\t\t\t\t}\n", "\t\t\t}\n" ], "file_path": "build/lib/policies.ts", "type": "replace", "edit_start_line_idx": 624 }
"use strict"; /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ Object.defineProperty(exports, "__esModule", { value: true }); const child_process_1 = require("child_process"); const fs_1 = require("fs"); const path = require("path"); const byline = require("byline"); const ripgrep_1 = require("@vscode/ripgrep"); const Parser = require("tree-sitter"); const node_fetch_1 = require("node-fetch"); const { typescript } = require('tree-sitter-typescript'); const product = require('../../product.json'); function isNlsString(value) { return value ? typeof value !== 'string' : false; } function isStringArray(value) { return !value.some(s => isNlsString(s)); } function isNlsStringArray(value) { return value.every(s => isNlsString(s)); } var PolicyType; (function (PolicyType) { PolicyType[PolicyType["StringEnum"] = 0] = "StringEnum"; })(PolicyType || (PolicyType = {})); function renderADMLString(prefix, moduleName, nlsString, translations) { let value; if (translations) { const moduleTranslations = translations[moduleName]; if (moduleTranslations) { value = moduleTranslations[nlsString.nlsKey]; } } if (!value) { value = nlsString.value; } return `<string id="${prefix}_${nlsString.nlsKey}">${value}</string>`; } class BasePolicy { constructor(policyType, name, category, minimumVersion, description, moduleName) { this.policyType = policyType; this.name = name; this.category = category; this.minimumVersion = minimumVersion; this.description = description; this.moduleName = moduleName; } renderADMLString(nlsString, translations) { return renderADMLString(this.name, this.moduleName, nlsString, translations); } renderADMX(regKey) { return [ `<policy name="${this.name}" class="Both" displayName="$(string.${this.name})" explainText="$(string.${this.name}_${this.description.nlsKey})" key="Software\\Policies\\Microsoft\\${regKey}" presentation="$(presentation.${this.name})">`, ` <parentCategory ref="${this.category.name.nlsKey}" />`, ` <supportedOn ref="Supported_${this.minimumVersion.replace(/\./g, '_')}" />`, ` <elements>`, ...this.renderADMXElements(), ` </elements>`, `</policy>` ]; } renderADMLStrings(translations) { return [ `<string id="${this.name}">${this.name}</string>`, this.renderADMLString(this.description, translations) ]; } renderADMLPresentation() { return `<presentation id="${this.name}">${this.renderADMLPresentationContents()}</presentation>`; } } class BooleanPolicy extends BasePolicy { static from(name, category, minimumVersion, description, moduleName, settingNode) { const type = getStringProperty(settingNode, 'type'); if (type !== 'boolean') { return undefined; } return new BooleanPolicy(name, category, minimumVersion, description, moduleName); } constructor(name, category, minimumVersion, description, moduleName) { super(PolicyType.StringEnum, name, category, minimumVersion, description, moduleName); } renderADMXElements() { return [ `<boolean id="${this.name}" valueName="${this.name}">`, ` <trueValue><decimal value="1" /></trueValue><falseValue><decimal value="0" /></falseValue>`, `</boolean>` ]; } renderADMLPresentationContents() { return `<checkBox refId="${this.name}">${this.name}</checkBox>`; } } class IntPolicy extends BasePolicy { constructor(name, category, minimumVersion, description, moduleName, defaultValue) { super(PolicyType.StringEnum, name, category, minimumVersion, description, moduleName); this.defaultValue = defaultValue; } static from(name, category, minimumVersion, description, moduleName, settingNode) { const type = getStringProperty(settingNode, 'type'); if (type !== 'number') { return undefined; } const defaultValue = getIntProperty(settingNode, 'default'); if (typeof defaultValue === 'undefined') { throw new Error(`Missing required 'default' property.`); } return new IntPolicy(name, category, minimumVersion, description, moduleName, defaultValue); } renderADMXElements() { return [ `<decimal id="${this.name}" valueName="${this.name}" />` // `<decimal id="Quarantine_PurgeItemsAfterDelay" valueName="PurgeItemsAfterDelay" minValue="0" maxValue="10000000" />` ]; } renderADMLPresentationContents() { return `<decimalTextBox refId="${this.name}" defaultValue="${this.defaultValue}">${this.name}</decimalTextBox>`; } } class StringPolicy extends BasePolicy { static from(name, category, minimumVersion, description, moduleName, settingNode) { const type = getStringProperty(settingNode, 'type'); if (type !== 'string') { return undefined; } return new StringPolicy(name, category, minimumVersion, description, moduleName); } constructor(name, category, minimumVersion, description, moduleName) { super(PolicyType.StringEnum, name, category, minimumVersion, description, moduleName); } renderADMXElements() { return [`<text id="${this.name}" valueName="${this.name}" required="true" />`]; } renderADMLPresentationContents() { return `<textBox refId="${this.name}"><label>${this.name}:</label></textBox>`; } } class StringEnumPolicy extends BasePolicy { constructor(name, category, minimumVersion, description, moduleName, enum_, enumDescriptions) { super(PolicyType.StringEnum, name, category, minimumVersion, description, moduleName); this.enum_ = enum_; this.enumDescriptions = enumDescriptions; } static from(name, category, minimumVersion, description, moduleName, settingNode) { const type = getStringProperty(settingNode, 'type'); if (type !== 'string') { return undefined; } const enum_ = getStringArrayProperty(settingNode, 'enum'); if (!enum_) { return undefined; } if (!isStringArray(enum_)) { throw new Error(`Property 'enum' should not be localized.`); } const enumDescriptions = getStringArrayProperty(settingNode, 'enumDescriptions'); if (!enumDescriptions) { throw new Error(`Missing required 'enumDescriptions' property.`); } else if (!isNlsStringArray(enumDescriptions)) { throw new Error(`Property 'enumDescriptions' should be localized.`); } return new StringEnumPolicy(name, category, minimumVersion, description, moduleName, enum_, enumDescriptions); } renderADMXElements() { return [ `<enum id="${this.name}" valueName="${this.name}">`, ...this.enum_.map((value, index) => ` <item displayName="$(string.${this.name}_${this.enumDescriptions[index].nlsKey})"><value><string>${value}</string></value></item>`), `</enum>` ]; } renderADMLStrings(translations) { return [ ...super.renderADMLStrings(translations), ...this.enumDescriptions.map(e => this.renderADMLString(e, translations)) ]; } renderADMLPresentationContents() { return `<dropdownList refId="${this.name}" />`; } } const IntQ = { Q: `(number) @value`, value(matches) { const match = matches[0]; if (!match) { return undefined; } const value = match.captures.filter(c => c.name === 'value')[0]?.node.text; if (!value) { throw new Error(`Missing required 'value' property.`); } return parseInt(value); } }; const StringQ = { Q: `[ (string (string_fragment) @value) (call_expression function: (identifier) @localizeFn arguments: (arguments (string (string_fragment) @nlsKey) (string (string_fragment) @value)) (#eq? @localizeFn localize)) ]`, value(matches) { const match = matches[0]; if (!match) { return undefined; } const value = match.captures.filter(c => c.name === 'value')[0]?.node.text; if (!value) { throw new Error(`Missing required 'value' property.`); } const nlsKey = match.captures.filter(c => c.name === 'nlsKey')[0]?.node.text; if (nlsKey) { return { value, nlsKey }; } else { return value; } } }; const StringArrayQ = { Q: `(array ${StringQ.Q})`, value(matches) { if (matches.length === 0) { return undefined; } return matches.map(match => { return StringQ.value([match]); }); } }; function getProperty(qtype, node, key) { const query = new Parser.Query(typescript, `( (pair key: [(property_identifier)(string)] @key value: ${qtype.Q} ) (#eq? @key ${key}) )`); return qtype.value(query.matches(node)); } function getIntProperty(node, key) { return getProperty(IntQ, node, key); } function getStringProperty(node, key) { return getProperty(StringQ, node, key); } function getStringArrayProperty(node, key) { return getProperty(StringArrayQ, node, key); } // TODO: add more policy types const PolicyTypes = [ BooleanPolicy, IntPolicy, StringEnumPolicy, StringPolicy, ]; function getPolicy(moduleName, configurationNode, settingNode, policyNode, categories) { const name = getStringProperty(policyNode, 'name'); if (!name) { throw new Error(`Missing required 'name' property.`); } else if (isNlsString(name)) { throw new Error(`Property 'name' should be a literal string.`); } const categoryName = getStringProperty(configurationNode, 'title'); if (!categoryName) { throw new Error(`Missing required 'title' property.`); } else if (!isNlsString(categoryName)) { throw new Error(`Property 'title' should be localized.`); } const categoryKey = `${categoryName.nlsKey}:${categoryName.value}`; let category = categories.get(categoryKey); if (!category) { category = { moduleName, name: categoryName }; categories.set(categoryKey, category); } const minimumVersion = getStringProperty(policyNode, 'minimumVersion'); if (!minimumVersion) { throw new Error(`Missing required 'minimumVersion' property.`); } else if (isNlsString(minimumVersion)) { throw new Error(`Property 'minimumVersion' should be a literal string.`); } const description = getStringProperty(settingNode, 'description'); if (!description) { throw new Error(`Missing required 'description' property.`); } if (!isNlsString(description)) { throw new Error(`Property 'description' should be localized.`); } let result; for (const policyType of PolicyTypes) { if (result = policyType.from(name, category, minimumVersion, description, moduleName, settingNode)) { break; } } if (!result) { throw new Error(`Failed to parse policy '${name}'.`); } return result; } function getPolicies(moduleName, node) { const query = new Parser.Query(typescript, ` ( (call_expression function: (member_expression property: (property_identifier) @registerConfigurationFn) (#eq? @registerConfigurationFn registerConfiguration) arguments: (arguments (object (pair key: [(property_identifier)(string)] @propertiesKey (#eq? @propertiesKey properties) value: (object (pair key: [(property_identifier)(string)] value: (object (pair key: [(property_identifier)(string)] @policyKey (#eq? @policyKey policy) value: (object) @policy )) @setting )) )) @configuration) ) ) `); const categories = new Map(); return query.matches(node).map(m => { const configurationNode = m.captures.filter(c => c.name === 'configuration')[0].node; const settingNode = m.captures.filter(c => c.name === 'setting')[0].node; const policyNode = m.captures.filter(c => c.name === 'policy')[0].node; return getPolicy(moduleName, configurationNode, settingNode, policyNode, categories); }); } async function getFiles(root) { return new Promise((c, e) => { const result = []; const rg = (0, child_process_1.spawn)(ripgrep_1.rgPath, ['-l', 'registerConfiguration\\(', '-g', 'src/**/*.ts', '-g', '!src/**/test/**', root]); const stream = byline(rg.stdout.setEncoding('utf8')); stream.on('data', path => result.push(path)); stream.on('error', err => e(err)); stream.on('end', () => c(result)); }); } function renderADMX(regKey, versions, categories, policies) { versions = versions.map(v => v.replace(/\./g, '_')); return `<?xml version="1.0" encoding="utf-8"?> <policyDefinitions revision="1.1" schemaVersion="1.0"> <policyNamespaces> <target prefix="${regKey}" namespace="Microsoft.Policies.${regKey}" /> </policyNamespaces> <resources minRequiredRevision="1.0" /> <supportedOn> <definitions> ${versions.map(v => `<definition name="Supported_${v}" displayName="$(string.Supported_${v})" />`).join(`\n `)} </definitions> </supportedOn> <categories> <category displayName="$(string.Application)" name="Application" /> ${categories.map(c => `<category displayName="$(string.Category_${c.name.nlsKey})" name="${c.name.nlsKey}"><parentCategory ref="Application" /></category>`).join(`\n `)} </categories> <policies> ${policies.map(p => p.renderADMX(regKey)).flat().join(`\n `)} </policies> </policyDefinitions> `; } function renderADML(appName, versions, categories, policies, translations) { return `<?xml version="1.0" encoding="utf-8"?> <policyDefinitionResources revision="1.0" schemaVersion="1.0"> <displayName /> <description /> <resources> <stringTable> <string id="Application">${appName}</string> ${versions.map(v => `<string id="Supported_${v.replace(/\./g, '_')}">${appName} &gt;= ${v}</string>`)} ${categories.map(c => renderADMLString('Category', c.moduleName, c.name, translations))} ${policies.map(p => p.renderADMLStrings(translations)).flat().join(`\n `)} </stringTable> <presentationTable> ${policies.map(p => p.renderADMLPresentation()).join(`\n `)} </presentationTable> </resources> </policyDefinitionResources> `; } function renderGP(policies, translations) { const appName = product.nameLong; const regKey = product.win32RegValueName; const versions = [...new Set(policies.map(p => p.minimumVersion)).values()].sort(); const categories = [...new Set(policies.map(p => p.category))]; return { admx: renderADMX(regKey, versions, categories, policies), adml: [ { languageId: 'en-us', contents: renderADML(appName, versions, categories, policies) }, ...translations.map(({ languageId, languageTranslations }) => ({ languageId, contents: renderADML(appName, versions, categories, policies, languageTranslations) })) ] }; } const Languages = { 'fr': 'fr-fr', 'it': 'it-it', 'de': 'de-de', 'es': 'es-es', 'ru': 'ru-ru', 'zh-hans': 'zh-cn', 'zh-hant': 'zh-tw', 'ja': 'ja-jp', 'ko': 'ko-kr', 'cs': 'cs-cz', 'pt-br': 'pt-br', 'tr': 'tr-tr', 'pl': 'pl-pl', }; async function getLatestStableVersion(updateUrl) { const res = await (0, node_fetch_1.default)(`${updateUrl}/api/update/darwin/stable/latest`); const { name: version } = await res.json(); return version; } async function getSpecificNLS(resourceUrlTemplate, languageId, version) { const resource = { publisher: 'ms-ceintl', name: `vscode-language-pack-${languageId}`, version, path: 'extension/translations/main.i18n.json' }; const url = resourceUrlTemplate.replace(/\{([^}]+)\}/g, (_, key) => resource[key]); const res = await (0, node_fetch_1.default)(url); if (res.status !== 200) { throw new Error(`[${res.status}] Error downloading language pack ${languageId}@${version}`); } const { contents: result } = await res.json(); return result; } function previousVersion(version) { const [, major, minor, patch] = /^(\d+)\.(\d+)\.(\d+)$/.exec(version); return `${major}.${parseInt(minor) - 1}.${patch}`; } async function getNLS(resourceUrlTemplate, languageId, version) { try { return await getSpecificNLS(resourceUrlTemplate, languageId, version); } catch (err) { if (/\[404\]/.test(err.message)) { console.warn(`Language pack ${languageId}@${version} is missing. Downloading previous version...`); return await getSpecificNLS(resourceUrlTemplate, languageId, previousVersion(version)); } else { throw err; } } } async function parsePolicies() { const parser = new Parser(); parser.setLanguage(typescript); const files = await getFiles(process.cwd()); const base = path.join(process.cwd(), 'src'); const policies = []; for (const file of files) { const moduleName = path.relative(base, file).replace(/\.ts$/i, '').replace(/\\/g, '/'); const contents = await fs_1.promises.readFile(file, { encoding: 'utf8' }); const tree = parser.parse(contents); policies.push(...getPolicies(moduleName, tree.rootNode)); } return policies; } async function getTranslations() { const updateUrl = product.updateUrl; if (!updateUrl) { console.warn(`Skipping policy localization: No 'updateUrl' found in 'product.json'.`); return []; } const resourceUrlTemplate = product.extensionsGallery?.resourceUrlTemplate; if (!resourceUrlTemplate) { console.warn(`Skipping policy localization: No 'resourceUrlTemplate' found in 'product.json'.`); return []; } const version = await getLatestStableVersion(updateUrl); const languageIds = Object.keys(Languages); return await Promise.all(languageIds.map(languageId => getNLS(resourceUrlTemplate, languageId, version) .then(languageTranslations => ({ languageId, languageTranslations })))); } async function main() { const [policies, translations] = await Promise.all([parsePolicies(), getTranslations()]); const { admx, adml } = await renderGP(policies, translations); const root = '.build/policies/win32'; await fs_1.promises.rm(root, { recursive: true, force: true }); await fs_1.promises.mkdir(root, { recursive: true }); await fs_1.promises.writeFile(path.join(root, `${product.win32RegValueName}.admx`), admx.replace(/\r?\n/g, '\n')); for (const { languageId, contents } of adml) { const languagePath = path.join(root, languageId === 'en-us' ? 'en-us' : Languages[languageId]); await fs_1.promises.mkdir(languagePath, { recursive: true }); await fs_1.promises.writeFile(path.join(languagePath, `${product.win32RegValueName}.adml`), contents.replace(/\r?\n/g, '\n')); } } if (require.main === module) { main().catch(err => { console.error(err); process.exit(1); }); }
build/lib/policies.js
1
https://github.com/microsoft/vscode/commit/73fd3f11032e7b83c2ae011b5516e6ddd19e3db2
[ 0.9986652135848999, 0.03998294472694397, 0.0001660834241192788, 0.0001721771841403097, 0.19353576004505157 ]
{ "id": 1, "code_window": [ "async function getNLS(resourceUrlTemplate: string, languageId: string, version: string) {\n", "\ttry {\n", "\t\treturn await getSpecificNLS(resourceUrlTemplate, languageId, version);\n", "\t} catch (err) {\n", "\t\tif (/\\[404\\]/.test(err.message)) {\n", "\t\t\tconsole.warn(`Language pack ${languageId}@${version} is missing. Downloading previous version...`);\n", "\t\t\treturn await getSpecificNLS(resourceUrlTemplate, languageId, previousVersion(version));\n", "\t\t} else {\n", "\t\t\tthrow err;\n", "\t\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tconst thePreviousVersion = previousVersion(version);\n", "\t\t\tconsole.warn(`Language pack ${languageId}@${version} is missing. Downloading previous version ${thePreviousVersion}...`);\n", "\t\t\ttry {\n", "\t\t\t\treturn await getSpecificNLS(resourceUrlTemplate, languageId, thePreviousVersion);\n", "\t\t\t} catch (err) {\n", "\t\t\t\tif (/\\[404\\]/.test(err.message)) {\n", "\t\t\t\t\tconsole.warn(`Language pack ${languageId}@${thePreviousVersion} is missing. Downloading previous version...`);\n", "\t\t\t\t\treturn await getSpecificNLS(resourceUrlTemplate, languageId, previousVersion(thePreviousVersion));\n", "\t\t\t\t} else {\n", "\t\t\t\t\tthrow err;\n", "\t\t\t\t}\n", "\t\t\t}\n" ], "file_path": "build/lib/policies.ts", "type": "replace", "edit_start_line_idx": 624 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { INotificationsModel, INotificationChangeEvent, NotificationChangeType, IStatusMessageChangeEvent, StatusMessageChangeType, IStatusMessageViewItem } from 'vs/workbench/common/notifications'; import { IStatusbarService, StatusbarAlignment, IStatusbarEntryAccessor, IStatusbarEntry } from 'vs/workbench/services/statusbar/browser/statusbar'; import { Disposable, IDisposable, dispose } from 'vs/base/common/lifecycle'; import { HIDE_NOTIFICATIONS_CENTER, SHOW_NOTIFICATIONS_CENTER } from 'vs/workbench/browser/parts/notifications/notificationsCommands'; import { localize } from 'vs/nls'; import { INotificationService } from 'vs/platform/notification/common/notification'; export class NotificationsStatus extends Disposable { private notificationsCenterStatusItem: IStatusbarEntryAccessor | undefined; private newNotificationsCount = 0; private currentStatusMessage: [IStatusMessageViewItem, IDisposable] | undefined; private isNotificationsCenterVisible: boolean = false; private isNotificationsToastsVisible: boolean = false; constructor( private readonly model: INotificationsModel, @IStatusbarService private readonly statusbarService: IStatusbarService, @INotificationService private readonly notificationService: INotificationService ) { super(); this.updateNotificationsCenterStatusItem(); if (model.statusMessage) { this.doSetStatusMessage(model.statusMessage); } this.registerListeners(); } private registerListeners(): void { this._register(this.model.onDidChangeNotification(e => this.onDidChangeNotification(e))); this._register(this.model.onDidChangeStatusMessage(e => this.onDidChangeStatusMessage(e))); this._register(this.notificationService.onDidChangeDoNotDisturbMode(() => this.updateNotificationsCenterStatusItem())); } private onDidChangeNotification(e: INotificationChangeEvent): void { // Consider a notification as unread as long as it only // appeared as toast and not in the notification center if (!this.isNotificationsCenterVisible) { if (e.kind === NotificationChangeType.ADD) { this.newNotificationsCount++; } else if (e.kind === NotificationChangeType.REMOVE && this.newNotificationsCount > 0) { this.newNotificationsCount--; } } // Update in status bar this.updateNotificationsCenterStatusItem(); } private updateNotificationsCenterStatusItem(): void { // Figure out how many notifications have progress only if neither // toasts are visible nor center is visible. In that case we still // want to give a hint to the user that something is running. let notificationsInProgress = 0; if (!this.isNotificationsCenterVisible && !this.isNotificationsToastsVisible) { for (const notification of this.model.notifications) { if (notification.hasProgress) { notificationsInProgress++; } } } // Show the status bar entry depending on do not disturb setting let statusProperties: IStatusbarEntry = { name: localize('status.notifications', "Notifications"), text: `${notificationsInProgress > 0 || this.newNotificationsCount > 0 ? '$(bell-dot)' : '$(bell)'}`, ariaLabel: localize('status.notifications', "Notifications"), command: this.isNotificationsCenterVisible ? HIDE_NOTIFICATIONS_CENTER : SHOW_NOTIFICATIONS_CENTER, tooltip: this.getTooltip(notificationsInProgress), showBeak: this.isNotificationsCenterVisible }; if (this.notificationService.doNotDisturbMode) { statusProperties = { ...statusProperties, text: `${notificationsInProgress > 0 || this.newNotificationsCount > 0 ? '$(bell-slash-dot)' : '$(bell-slash)'}`, ariaLabel: localize('status.doNotDisturb', "Do Not Disturb"), tooltip: localize('status.doNotDisturbTooltip', "Do Not Disturb Mode is Enabled") }; } if (!this.notificationsCenterStatusItem) { this.notificationsCenterStatusItem = this.statusbarService.addEntry( statusProperties, 'status.notifications', StatusbarAlignment.RIGHT, -Number.MAX_VALUE /* towards the far end of the right hand side */ ); } else { this.notificationsCenterStatusItem.update(statusProperties); } } private getTooltip(notificationsInProgress: number): string { if (this.isNotificationsCenterVisible) { return localize('hideNotifications', "Hide Notifications"); } if (this.model.notifications.length === 0) { return localize('zeroNotifications', "No Notifications"); } if (notificationsInProgress === 0) { if (this.newNotificationsCount === 0) { return localize('noNotifications', "No New Notifications"); } if (this.newNotificationsCount === 1) { return localize('oneNotification', "1 New Notification"); } return localize({ key: 'notifications', comment: ['{0} will be replaced by a number'] }, "{0} New Notifications", this.newNotificationsCount); } if (this.newNotificationsCount === 0) { return localize({ key: 'noNotificationsWithProgress', comment: ['{0} will be replaced by a number'] }, "No New Notifications ({0} in progress)", notificationsInProgress); } if (this.newNotificationsCount === 1) { return localize({ key: 'oneNotificationWithProgress', comment: ['{0} will be replaced by a number'] }, "1 New Notification ({0} in progress)", notificationsInProgress); } return localize({ key: 'notificationsWithProgress', comment: ['{0} and {1} will be replaced by a number'] }, "{0} New Notifications ({1} in progress)", this.newNotificationsCount, notificationsInProgress); } update(isCenterVisible: boolean, isToastsVisible: boolean): void { let updateNotificationsCenterStatusItem = false; if (this.isNotificationsCenterVisible !== isCenterVisible) { this.isNotificationsCenterVisible = isCenterVisible; this.newNotificationsCount = 0; // Showing the notification center resets the unread counter to 0 updateNotificationsCenterStatusItem = true; } if (this.isNotificationsToastsVisible !== isToastsVisible) { this.isNotificationsToastsVisible = isToastsVisible; updateNotificationsCenterStatusItem = true; } // Update in status bar as needed if (updateNotificationsCenterStatusItem) { this.updateNotificationsCenterStatusItem(); } } private onDidChangeStatusMessage(e: IStatusMessageChangeEvent): void { const statusItem = e.item; switch (e.kind) { // Show status notification case StatusMessageChangeType.ADD: this.doSetStatusMessage(statusItem); break; // Hide status notification (if its still the current one) case StatusMessageChangeType.REMOVE: if (this.currentStatusMessage && this.currentStatusMessage[0] === statusItem) { dispose(this.currentStatusMessage[1]); this.currentStatusMessage = undefined; } break; } } private doSetStatusMessage(item: IStatusMessageViewItem): void { const message = item.message; const showAfter = item.options && typeof item.options.showAfter === 'number' ? item.options.showAfter : 0; const hideAfter = item.options && typeof item.options.hideAfter === 'number' ? item.options.hideAfter : -1; // Dismiss any previous if (this.currentStatusMessage) { dispose(this.currentStatusMessage[1]); } // Create new let statusMessageEntry: IStatusbarEntryAccessor; let showHandle: any = setTimeout(() => { statusMessageEntry = this.statusbarService.addEntry( { name: localize('status.message', "Status Message"), text: message, ariaLabel: message }, 'status.message', StatusbarAlignment.LEFT, -Number.MAX_VALUE /* far right on left hand side */ ); showHandle = null; }, showAfter); // Dispose function takes care of timeouts and actual entry let hideHandle: any; const statusMessageDispose = { dispose: () => { if (showHandle) { clearTimeout(showHandle); } if (hideHandle) { clearTimeout(hideHandle); } statusMessageEntry?.dispose(); } }; if (hideAfter > 0) { hideHandle = setTimeout(() => statusMessageDispose.dispose(), hideAfter); } // Remember as current status message this.currentStatusMessage = [item, statusMessageDispose]; } }
src/vs/workbench/browser/parts/notifications/notificationsStatus.ts
0
https://github.com/microsoft/vscode/commit/73fd3f11032e7b83c2ae011b5516e6ddd19e3db2
[ 0.00017537728126626462, 0.0001723577588563785, 0.000166657060617581, 0.00017313234275206923, 0.000002103282213283819 ]
{ "id": 1, "code_window": [ "async function getNLS(resourceUrlTemplate: string, languageId: string, version: string) {\n", "\ttry {\n", "\t\treturn await getSpecificNLS(resourceUrlTemplate, languageId, version);\n", "\t} catch (err) {\n", "\t\tif (/\\[404\\]/.test(err.message)) {\n", "\t\t\tconsole.warn(`Language pack ${languageId}@${version} is missing. Downloading previous version...`);\n", "\t\t\treturn await getSpecificNLS(resourceUrlTemplate, languageId, previousVersion(version));\n", "\t\t} else {\n", "\t\t\tthrow err;\n", "\t\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tconst thePreviousVersion = previousVersion(version);\n", "\t\t\tconsole.warn(`Language pack ${languageId}@${version} is missing. Downloading previous version ${thePreviousVersion}...`);\n", "\t\t\ttry {\n", "\t\t\t\treturn await getSpecificNLS(resourceUrlTemplate, languageId, thePreviousVersion);\n", "\t\t\t} catch (err) {\n", "\t\t\t\tif (/\\[404\\]/.test(err.message)) {\n", "\t\t\t\t\tconsole.warn(`Language pack ${languageId}@${thePreviousVersion} is missing. Downloading previous version...`);\n", "\t\t\t\t\treturn await getSpecificNLS(resourceUrlTemplate, languageId, previousVersion(thePreviousVersion));\n", "\t\t\t\t} else {\n", "\t\t\t\t\tthrow err;\n", "\t\t\t\t}\n", "\t\t\t}\n" ], "file_path": "build/lib/policies.ts", "type": "replace", "edit_start_line_idx": 624 }
[ { "c": "@", "t": "source.batchfile keyword.operator.at.batchfile", "r": { "dark_plus": "keyword.operator: #D4D4D4", "light_plus": "keyword.operator: #000000", "dark_vs": "keyword.operator: #D4D4D4", "light_vs": "keyword.operator: #000000", "hc_black": "keyword.operator: #D4D4D4", "hc_light": "keyword.operator: #000000" } }, { "c": "echo", "t": "source.batchfile keyword.command.batchfile", "r": { "dark_plus": "keyword: #569CD6", "light_plus": "keyword: #0000FF", "dark_vs": "keyword: #569CD6", "light_vs": "keyword: #0000FF", "hc_black": "keyword: #569CD6", "hc_light": "keyword: #0F4A85" } }, { "c": " ", "t": "source.batchfile", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "hc_light": "default: #292929" } }, { "c": "off", "t": "source.batchfile keyword.other.special-method.batchfile", "r": { "dark_plus": "keyword: #569CD6", "light_plus": "keyword: #0000FF", "dark_vs": "keyword: #569CD6", "light_vs": "keyword: #0000FF", "hc_black": "keyword: #569CD6", "hc_light": "keyword: #0F4A85" } }, { "c": "setlocal", "t": "source.batchfile keyword.command.batchfile", "r": { "dark_plus": "keyword: #569CD6", "light_plus": "keyword: #0000FF", "dark_vs": "keyword: #569CD6", "light_vs": "keyword: #0000FF", "hc_black": "keyword: #569CD6", "hc_light": "keyword: #0F4A85" } }, { "c": "title", "t": "source.batchfile keyword.command.batchfile", "r": { "dark_plus": "keyword: #569CD6", "light_plus": "keyword: #0000FF", "dark_vs": "keyword: #569CD6", "light_vs": "keyword: #0000FF", "hc_black": "keyword: #569CD6", "hc_light": "keyword: #0F4A85" } }, { "c": " VSCode Dev", "t": "source.batchfile", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "hc_light": "default: #292929" } }, { "c": "pushd", "t": "source.batchfile keyword.command.batchfile", "r": { "dark_plus": "keyword: #569CD6", "light_plus": "keyword: #0000FF", "dark_vs": "keyword: #569CD6", "light_vs": "keyword: #0000FF", "hc_black": "keyword: #569CD6", "hc_light": "keyword: #0F4A85" } }, { "c": " ", "t": "source.batchfile", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "hc_light": "default: #292929" } }, { "c": "%", "t": "source.batchfile variable.parameter.batchfile punctuation.definition.variable.batchfile", "r": { "dark_plus": "variable: #9CDCFE", "light_plus": "variable: #001080", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "variable: #9CDCFE", "hc_light": "variable: #001080" } }, { "c": "~dp0", "t": "source.batchfile variable.parameter.batchfile", "r": { "dark_plus": "variable: #9CDCFE", "light_plus": "variable: #001080", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "variable: #9CDCFE", "hc_light": "variable: #001080" } }, { "c": "\\..", "t": "source.batchfile", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "hc_light": "default: #292929" } }, { "c": "::", "t": "source.batchfile comment.line.colon.batchfile punctuation.definition.comment.batchfile", "r": { "dark_plus": "comment: #6A9955", "light_plus": "comment: #008000", "dark_vs": "comment: #6A9955", "light_vs": "comment: #008000", "hc_black": "comment: #7CA668", "hc_light": "comment: #515151" } }, { "c": " Node modules", "t": "source.batchfile comment.line.colon.batchfile", "r": { "dark_plus": "comment: #6A9955", "light_plus": "comment: #008000", "dark_vs": "comment: #6A9955", "light_vs": "comment: #008000", "hc_black": "comment: #7CA668", "hc_light": "comment: #515151" } }, { "c": "if", "t": "source.batchfile keyword.control.conditional.batchfile", "r": { "dark_plus": "keyword.control: #C586C0", "light_plus": "keyword.control: #AF00DB", "dark_vs": "keyword.control: #569CD6", "light_vs": "keyword.control: #0000FF", "hc_black": "keyword.control: #C586C0", "hc_light": "keyword.control: #B5200D" } }, { "c": " ", "t": "source.batchfile", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "hc_light": "default: #292929" } }, { "c": "not", "t": "source.batchfile keyword.operator.logical.batchfile", "r": { "dark_plus": "keyword.operator: #D4D4D4", "light_plus": "keyword.operator: #000000", "dark_vs": "keyword.operator: #D4D4D4", "light_vs": "keyword.operator: #000000", "hc_black": "keyword.operator: #D4D4D4", "hc_light": "keyword.operator: #000000" } }, { "c": " ", "t": "source.batchfile", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "hc_light": "default: #292929" } }, { "c": "exist", "t": "source.batchfile keyword.other.special-method.batchfile", "r": { "dark_plus": "keyword: #569CD6", "light_plus": "keyword: #0000FF", "dark_vs": "keyword: #569CD6", "light_vs": "keyword: #0000FF", "hc_black": "keyword: #569CD6", "hc_light": "keyword: #0F4A85" } }, { "c": " node_modules ", "t": "source.batchfile", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "hc_light": "default: #292929" } }, { "c": "call", "t": "source.batchfile keyword.control.statement.batchfile", "r": { "dark_plus": "keyword.control: #C586C0", "light_plus": "keyword.control: #AF00DB", "dark_vs": "keyword.control: #569CD6", "light_vs": "keyword.control: #0000FF", "hc_black": "keyword.control: #C586C0", "hc_light": "keyword.control: #B5200D" } }, { "c": " .\\scripts\\npm.bat install", "t": "source.batchfile", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "hc_light": "default: #292929" } }, { "c": "::", "t": "source.batchfile comment.line.colon.batchfile punctuation.definition.comment.batchfile", "r": { "dark_plus": "comment: #6A9955", "light_plus": "comment: #008000", "dark_vs": "comment: #6A9955", "light_vs": "comment: #008000", "hc_black": "comment: #7CA668", "hc_light": "comment: #515151" } }, { "c": " Get electron", "t": "source.batchfile comment.line.colon.batchfile", "r": { "dark_plus": "comment: #6A9955", "light_plus": "comment: #008000", "dark_vs": "comment: #6A9955", "light_vs": "comment: #008000", "hc_black": "comment: #7CA668", "hc_light": "comment: #515151" } }, { "c": "node .\\node_modules\\gulp\\bin\\gulp.js electron", "t": "source.batchfile", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "hc_light": "default: #292929" } }, { "c": "::", "t": "source.batchfile comment.line.colon.batchfile punctuation.definition.comment.batchfile", "r": { "dark_plus": "comment: #6A9955", "light_plus": "comment: #008000", "dark_vs": "comment: #6A9955", "light_vs": "comment: #008000", "hc_black": "comment: #7CA668", "hc_light": "comment: #515151" } }, { "c": " Build", "t": "source.batchfile comment.line.colon.batchfile", "r": { "dark_plus": "comment: #6A9955", "light_plus": "comment: #008000", "dark_vs": "comment: #6A9955", "light_vs": "comment: #008000", "hc_black": "comment: #7CA668", "hc_light": "comment: #515151" } }, { "c": "if", "t": "source.batchfile keyword.control.conditional.batchfile", "r": { "dark_plus": "keyword.control: #C586C0", "light_plus": "keyword.control: #AF00DB", "dark_vs": "keyword.control: #569CD6", "light_vs": "keyword.control: #0000FF", "hc_black": "keyword.control: #C586C0", "hc_light": "keyword.control: #B5200D" } }, { "c": " ", "t": "source.batchfile", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "hc_light": "default: #292929" } }, { "c": "not", "t": "source.batchfile keyword.operator.logical.batchfile", "r": { "dark_plus": "keyword.operator: #D4D4D4", "light_plus": "keyword.operator: #000000", "dark_vs": "keyword.operator: #D4D4D4", "light_vs": "keyword.operator: #000000", "hc_black": "keyword.operator: #D4D4D4", "hc_light": "keyword.operator: #000000" } }, { "c": " ", "t": "source.batchfile", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "hc_light": "default: #292929" } }, { "c": "exist", "t": "source.batchfile keyword.other.special-method.batchfile", "r": { "dark_plus": "keyword: #569CD6", "light_plus": "keyword: #0000FF", "dark_vs": "keyword: #569CD6", "light_vs": "keyword: #0000FF", "hc_black": "keyword: #569CD6", "hc_light": "keyword: #0F4A85" } }, { "c": " out node .\\node_modules\\gulp\\bin\\gulp.js compile", "t": "source.batchfile", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "hc_light": "default: #292929" } }, { "c": "::", "t": "source.batchfile comment.line.colon.batchfile punctuation.definition.comment.batchfile", "r": { "dark_plus": "comment: #6A9955", "light_plus": "comment: #008000", "dark_vs": "comment: #6A9955", "light_vs": "comment: #008000", "hc_black": "comment: #7CA668", "hc_light": "comment: #515151" } }, { "c": " Configuration", "t": "source.batchfile comment.line.colon.batchfile", "r": { "dark_plus": "comment: #6A9955", "light_plus": "comment: #008000", "dark_vs": "comment: #6A9955", "light_vs": "comment: #008000", "hc_black": "comment: #7CA668", "hc_light": "comment: #515151" } }, { "c": "set", "t": "source.batchfile keyword.command.batchfile", "r": { "dark_plus": "keyword: #569CD6", "light_plus": "keyword: #0000FF", "dark_vs": "keyword: #569CD6", "light_vs": "keyword: #0000FF", "hc_black": "keyword: #569CD6", "hc_light": "keyword: #0F4A85" } }, { "c": " ", "t": "source.batchfile", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "hc_light": "default: #292929" } }, { "c": "NODE_ENV", "t": "source.batchfile variable.other.readwrite.batchfile", "r": { "dark_plus": "variable: #9CDCFE", "light_plus": "variable: #001080", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "variable: #9CDCFE", "hc_light": "variable: #001080" } }, { "c": "=", "t": "source.batchfile keyword.operator.assignment.batchfile", "r": { "dark_plus": "keyword.operator: #D4D4D4", "light_plus": "keyword.operator: #000000", "dark_vs": "keyword.operator: #D4D4D4", "light_vs": "keyword.operator: #000000", "hc_black": "keyword.operator: #D4D4D4", "hc_light": "keyword.operator: #000000" } }, { "c": "development", "t": "source.batchfile", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "hc_light": "default: #292929" } }, { "c": "call", "t": "source.batchfile keyword.control.statement.batchfile", "r": { "dark_plus": "keyword.control: #C586C0", "light_plus": "keyword.control: #AF00DB", "dark_vs": "keyword.control: #569CD6", "light_vs": "keyword.control: #0000FF", "hc_black": "keyword.control: #C586C0", "hc_light": "keyword.control: #B5200D" } }, { "c": " ", "t": "source.batchfile", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "hc_light": "default: #292929" } }, { "c": "echo", "t": "source.batchfile keyword.command.batchfile", "r": { "dark_plus": "keyword: #569CD6", "light_plus": "keyword: #0000FF", "dark_vs": "keyword: #569CD6", "light_vs": "keyword: #0000FF", "hc_black": "keyword: #569CD6", "hc_light": "keyword: #0F4A85" } }, { "c": " ", "t": "source.batchfile", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "hc_light": "default: #292929" } }, { "c": "%%", "t": "source.batchfile constant.character.escape.batchfile", "r": { "dark_plus": "constant.character.escape: #D7BA7D", "light_plus": "constant.character.escape: #EE0000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "constant.character: #569CD6", "hc_light": "constant.character.escape: #EE0000" } }, { "c": "LINE:rem +=", "t": "source.batchfile", "r": { "dark_plus": "default: #D4D4D4", "light_plus": "default: #000000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "default: #FFFFFF", "hc_light": "default: #292929" } }, { "c": "%%", "t": "source.batchfile constant.character.escape.batchfile", "r": { "dark_plus": "constant.character.escape: #D7BA7D", "light_plus": "constant.character.escape: #EE0000", "dark_vs": "default: #D4D4D4", "light_vs": "default: #000000", "hc_black": "constant.character: #569CD6", "hc_light": "constant.character.escape: #EE0000" } }, { "c": "popd", "t": "source.batchfile keyword.command.batchfile", "r": { "dark_plus": "keyword: #569CD6", "light_plus": "keyword: #0000FF", "dark_vs": "keyword: #569CD6", "light_vs": "keyword: #0000FF", "hc_black": "keyword: #569CD6", "hc_light": "keyword: #0F4A85" } }, { "c": "endlocal", "t": "source.batchfile keyword.command.batchfile", "r": { "dark_plus": "keyword: #569CD6", "light_plus": "keyword: #0000FF", "dark_vs": "keyword: #569CD6", "light_vs": "keyword: #0000FF", "hc_black": "keyword: #569CD6", "hc_light": "keyword: #0F4A85" } } ]
extensions/vscode-colorize-tests/test/colorize-results/test_bat.json
0
https://github.com/microsoft/vscode/commit/73fd3f11032e7b83c2ae011b5516e6ddd19e3db2
[ 0.00017620465951040387, 0.00017342700448352844, 0.0001692302612354979, 0.00017348077381029725, 0.00000115415855361789 ]
{ "id": 1, "code_window": [ "async function getNLS(resourceUrlTemplate: string, languageId: string, version: string) {\n", "\ttry {\n", "\t\treturn await getSpecificNLS(resourceUrlTemplate, languageId, version);\n", "\t} catch (err) {\n", "\t\tif (/\\[404\\]/.test(err.message)) {\n", "\t\t\tconsole.warn(`Language pack ${languageId}@${version} is missing. Downloading previous version...`);\n", "\t\t\treturn await getSpecificNLS(resourceUrlTemplate, languageId, previousVersion(version));\n", "\t\t} else {\n", "\t\t\tthrow err;\n", "\t\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tconst thePreviousVersion = previousVersion(version);\n", "\t\t\tconsole.warn(`Language pack ${languageId}@${version} is missing. Downloading previous version ${thePreviousVersion}...`);\n", "\t\t\ttry {\n", "\t\t\t\treturn await getSpecificNLS(resourceUrlTemplate, languageId, thePreviousVersion);\n", "\t\t\t} catch (err) {\n", "\t\t\t\tif (/\\[404\\]/.test(err.message)) {\n", "\t\t\t\t\tconsole.warn(`Language pack ${languageId}@${thePreviousVersion} is missing. Downloading previous version...`);\n", "\t\t\t\t\treturn await getSpecificNLS(resourceUrlTemplate, languageId, previousVersion(thePreviousVersion));\n", "\t\t\t\t} else {\n", "\t\t\t\t\tthrow err;\n", "\t\t\t\t}\n", "\t\t\t}\n" ], "file_path": "build/lib/policies.ts", "type": "replace", "edit_start_line_idx": 624 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/
extensions/css-language-features/server/test/pathCompletionFixtures/src/data/foo.asar
0
https://github.com/microsoft/vscode/commit/73fd3f11032e7b83c2ae011b5516e6ddd19e3db2
[ 0.00017485115677118301, 0.00017485115677118301, 0.00017485115677118301, 0.00017485115677118301, 0 ]
{ "id": 2, "code_window": [ "\n", "\t\tawait document.save();\n", "\t\tassert.strictEqual(document.isDirty, false);\n", "\t});\n", "\n", "\ttest('onDidOpenNotebookDocument - emit event only once when opened in two editors', async function () {\n", "\t\tconst uri = await utils.createRandomFile(undefined, undefined, '.nbdtest');\n", "\t\tlet counter = 0;\n", "\t\ttestDisposables.push(vscode.workspace.onDidOpenNotebookDocument(nb => {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\ttest.skip('onDidOpenNotebookDocument - emit event only once when opened in two editors', async function () { // TODO@rebornix https://github.com/microsoft/vscode/issues/157222\n" ], "file_path": "extensions/vscode-api-tests/src/singlefolder-tests/notebook.document.test.ts", "type": "replace", "edit_start_line_idx": 425 }
"use strict"; /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ Object.defineProperty(exports, "__esModule", { value: true }); const child_process_1 = require("child_process"); const fs_1 = require("fs"); const path = require("path"); const byline = require("byline"); const ripgrep_1 = require("@vscode/ripgrep"); const Parser = require("tree-sitter"); const node_fetch_1 = require("node-fetch"); const { typescript } = require('tree-sitter-typescript'); const product = require('../../product.json'); function isNlsString(value) { return value ? typeof value !== 'string' : false; } function isStringArray(value) { return !value.some(s => isNlsString(s)); } function isNlsStringArray(value) { return value.every(s => isNlsString(s)); } var PolicyType; (function (PolicyType) { PolicyType[PolicyType["StringEnum"] = 0] = "StringEnum"; })(PolicyType || (PolicyType = {})); function renderADMLString(prefix, moduleName, nlsString, translations) { let value; if (translations) { const moduleTranslations = translations[moduleName]; if (moduleTranslations) { value = moduleTranslations[nlsString.nlsKey]; } } if (!value) { value = nlsString.value; } return `<string id="${prefix}_${nlsString.nlsKey}">${value}</string>`; } class BasePolicy { constructor(policyType, name, category, minimumVersion, description, moduleName) { this.policyType = policyType; this.name = name; this.category = category; this.minimumVersion = minimumVersion; this.description = description; this.moduleName = moduleName; } renderADMLString(nlsString, translations) { return renderADMLString(this.name, this.moduleName, nlsString, translations); } renderADMX(regKey) { return [ `<policy name="${this.name}" class="Both" displayName="$(string.${this.name})" explainText="$(string.${this.name}_${this.description.nlsKey})" key="Software\\Policies\\Microsoft\\${regKey}" presentation="$(presentation.${this.name})">`, ` <parentCategory ref="${this.category.name.nlsKey}" />`, ` <supportedOn ref="Supported_${this.minimumVersion.replace(/\./g, '_')}" />`, ` <elements>`, ...this.renderADMXElements(), ` </elements>`, `</policy>` ]; } renderADMLStrings(translations) { return [ `<string id="${this.name}">${this.name}</string>`, this.renderADMLString(this.description, translations) ]; } renderADMLPresentation() { return `<presentation id="${this.name}">${this.renderADMLPresentationContents()}</presentation>`; } } class BooleanPolicy extends BasePolicy { static from(name, category, minimumVersion, description, moduleName, settingNode) { const type = getStringProperty(settingNode, 'type'); if (type !== 'boolean') { return undefined; } return new BooleanPolicy(name, category, minimumVersion, description, moduleName); } constructor(name, category, minimumVersion, description, moduleName) { super(PolicyType.StringEnum, name, category, minimumVersion, description, moduleName); } renderADMXElements() { return [ `<boolean id="${this.name}" valueName="${this.name}">`, ` <trueValue><decimal value="1" /></trueValue><falseValue><decimal value="0" /></falseValue>`, `</boolean>` ]; } renderADMLPresentationContents() { return `<checkBox refId="${this.name}">${this.name}</checkBox>`; } } class IntPolicy extends BasePolicy { constructor(name, category, minimumVersion, description, moduleName, defaultValue) { super(PolicyType.StringEnum, name, category, minimumVersion, description, moduleName); this.defaultValue = defaultValue; } static from(name, category, minimumVersion, description, moduleName, settingNode) { const type = getStringProperty(settingNode, 'type'); if (type !== 'number') { return undefined; } const defaultValue = getIntProperty(settingNode, 'default'); if (typeof defaultValue === 'undefined') { throw new Error(`Missing required 'default' property.`); } return new IntPolicy(name, category, minimumVersion, description, moduleName, defaultValue); } renderADMXElements() { return [ `<decimal id="${this.name}" valueName="${this.name}" />` // `<decimal id="Quarantine_PurgeItemsAfterDelay" valueName="PurgeItemsAfterDelay" minValue="0" maxValue="10000000" />` ]; } renderADMLPresentationContents() { return `<decimalTextBox refId="${this.name}" defaultValue="${this.defaultValue}">${this.name}</decimalTextBox>`; } } class StringPolicy extends BasePolicy { static from(name, category, minimumVersion, description, moduleName, settingNode) { const type = getStringProperty(settingNode, 'type'); if (type !== 'string') { return undefined; } return new StringPolicy(name, category, minimumVersion, description, moduleName); } constructor(name, category, minimumVersion, description, moduleName) { super(PolicyType.StringEnum, name, category, minimumVersion, description, moduleName); } renderADMXElements() { return [`<text id="${this.name}" valueName="${this.name}" required="true" />`]; } renderADMLPresentationContents() { return `<textBox refId="${this.name}"><label>${this.name}:</label></textBox>`; } } class StringEnumPolicy extends BasePolicy { constructor(name, category, minimumVersion, description, moduleName, enum_, enumDescriptions) { super(PolicyType.StringEnum, name, category, minimumVersion, description, moduleName); this.enum_ = enum_; this.enumDescriptions = enumDescriptions; } static from(name, category, minimumVersion, description, moduleName, settingNode) { const type = getStringProperty(settingNode, 'type'); if (type !== 'string') { return undefined; } const enum_ = getStringArrayProperty(settingNode, 'enum'); if (!enum_) { return undefined; } if (!isStringArray(enum_)) { throw new Error(`Property 'enum' should not be localized.`); } const enumDescriptions = getStringArrayProperty(settingNode, 'enumDescriptions'); if (!enumDescriptions) { throw new Error(`Missing required 'enumDescriptions' property.`); } else if (!isNlsStringArray(enumDescriptions)) { throw new Error(`Property 'enumDescriptions' should be localized.`); } return new StringEnumPolicy(name, category, minimumVersion, description, moduleName, enum_, enumDescriptions); } renderADMXElements() { return [ `<enum id="${this.name}" valueName="${this.name}">`, ...this.enum_.map((value, index) => ` <item displayName="$(string.${this.name}_${this.enumDescriptions[index].nlsKey})"><value><string>${value}</string></value></item>`), `</enum>` ]; } renderADMLStrings(translations) { return [ ...super.renderADMLStrings(translations), ...this.enumDescriptions.map(e => this.renderADMLString(e, translations)) ]; } renderADMLPresentationContents() { return `<dropdownList refId="${this.name}" />`; } } const IntQ = { Q: `(number) @value`, value(matches) { const match = matches[0]; if (!match) { return undefined; } const value = match.captures.filter(c => c.name === 'value')[0]?.node.text; if (!value) { throw new Error(`Missing required 'value' property.`); } return parseInt(value); } }; const StringQ = { Q: `[ (string (string_fragment) @value) (call_expression function: (identifier) @localizeFn arguments: (arguments (string (string_fragment) @nlsKey) (string (string_fragment) @value)) (#eq? @localizeFn localize)) ]`, value(matches) { const match = matches[0]; if (!match) { return undefined; } const value = match.captures.filter(c => c.name === 'value')[0]?.node.text; if (!value) { throw new Error(`Missing required 'value' property.`); } const nlsKey = match.captures.filter(c => c.name === 'nlsKey')[0]?.node.text; if (nlsKey) { return { value, nlsKey }; } else { return value; } } }; const StringArrayQ = { Q: `(array ${StringQ.Q})`, value(matches) { if (matches.length === 0) { return undefined; } return matches.map(match => { return StringQ.value([match]); }); } }; function getProperty(qtype, node, key) { const query = new Parser.Query(typescript, `( (pair key: [(property_identifier)(string)] @key value: ${qtype.Q} ) (#eq? @key ${key}) )`); return qtype.value(query.matches(node)); } function getIntProperty(node, key) { return getProperty(IntQ, node, key); } function getStringProperty(node, key) { return getProperty(StringQ, node, key); } function getStringArrayProperty(node, key) { return getProperty(StringArrayQ, node, key); } // TODO: add more policy types const PolicyTypes = [ BooleanPolicy, IntPolicy, StringEnumPolicy, StringPolicy, ]; function getPolicy(moduleName, configurationNode, settingNode, policyNode, categories) { const name = getStringProperty(policyNode, 'name'); if (!name) { throw new Error(`Missing required 'name' property.`); } else if (isNlsString(name)) { throw new Error(`Property 'name' should be a literal string.`); } const categoryName = getStringProperty(configurationNode, 'title'); if (!categoryName) { throw new Error(`Missing required 'title' property.`); } else if (!isNlsString(categoryName)) { throw new Error(`Property 'title' should be localized.`); } const categoryKey = `${categoryName.nlsKey}:${categoryName.value}`; let category = categories.get(categoryKey); if (!category) { category = { moduleName, name: categoryName }; categories.set(categoryKey, category); } const minimumVersion = getStringProperty(policyNode, 'minimumVersion'); if (!minimumVersion) { throw new Error(`Missing required 'minimumVersion' property.`); } else if (isNlsString(minimumVersion)) { throw new Error(`Property 'minimumVersion' should be a literal string.`); } const description = getStringProperty(settingNode, 'description'); if (!description) { throw new Error(`Missing required 'description' property.`); } if (!isNlsString(description)) { throw new Error(`Property 'description' should be localized.`); } let result; for (const policyType of PolicyTypes) { if (result = policyType.from(name, category, minimumVersion, description, moduleName, settingNode)) { break; } } if (!result) { throw new Error(`Failed to parse policy '${name}'.`); } return result; } function getPolicies(moduleName, node) { const query = new Parser.Query(typescript, ` ( (call_expression function: (member_expression property: (property_identifier) @registerConfigurationFn) (#eq? @registerConfigurationFn registerConfiguration) arguments: (arguments (object (pair key: [(property_identifier)(string)] @propertiesKey (#eq? @propertiesKey properties) value: (object (pair key: [(property_identifier)(string)] value: (object (pair key: [(property_identifier)(string)] @policyKey (#eq? @policyKey policy) value: (object) @policy )) @setting )) )) @configuration) ) ) `); const categories = new Map(); return query.matches(node).map(m => { const configurationNode = m.captures.filter(c => c.name === 'configuration')[0].node; const settingNode = m.captures.filter(c => c.name === 'setting')[0].node; const policyNode = m.captures.filter(c => c.name === 'policy')[0].node; return getPolicy(moduleName, configurationNode, settingNode, policyNode, categories); }); } async function getFiles(root) { return new Promise((c, e) => { const result = []; const rg = (0, child_process_1.spawn)(ripgrep_1.rgPath, ['-l', 'registerConfiguration\\(', '-g', 'src/**/*.ts', '-g', '!src/**/test/**', root]); const stream = byline(rg.stdout.setEncoding('utf8')); stream.on('data', path => result.push(path)); stream.on('error', err => e(err)); stream.on('end', () => c(result)); }); } function renderADMX(regKey, versions, categories, policies) { versions = versions.map(v => v.replace(/\./g, '_')); return `<?xml version="1.0" encoding="utf-8"?> <policyDefinitions revision="1.1" schemaVersion="1.0"> <policyNamespaces> <target prefix="${regKey}" namespace="Microsoft.Policies.${regKey}" /> </policyNamespaces> <resources minRequiredRevision="1.0" /> <supportedOn> <definitions> ${versions.map(v => `<definition name="Supported_${v}" displayName="$(string.Supported_${v})" />`).join(`\n `)} </definitions> </supportedOn> <categories> <category displayName="$(string.Application)" name="Application" /> ${categories.map(c => `<category displayName="$(string.Category_${c.name.nlsKey})" name="${c.name.nlsKey}"><parentCategory ref="Application" /></category>`).join(`\n `)} </categories> <policies> ${policies.map(p => p.renderADMX(regKey)).flat().join(`\n `)} </policies> </policyDefinitions> `; } function renderADML(appName, versions, categories, policies, translations) { return `<?xml version="1.0" encoding="utf-8"?> <policyDefinitionResources revision="1.0" schemaVersion="1.0"> <displayName /> <description /> <resources> <stringTable> <string id="Application">${appName}</string> ${versions.map(v => `<string id="Supported_${v.replace(/\./g, '_')}">${appName} &gt;= ${v}</string>`)} ${categories.map(c => renderADMLString('Category', c.moduleName, c.name, translations))} ${policies.map(p => p.renderADMLStrings(translations)).flat().join(`\n `)} </stringTable> <presentationTable> ${policies.map(p => p.renderADMLPresentation()).join(`\n `)} </presentationTable> </resources> </policyDefinitionResources> `; } function renderGP(policies, translations) { const appName = product.nameLong; const regKey = product.win32RegValueName; const versions = [...new Set(policies.map(p => p.minimumVersion)).values()].sort(); const categories = [...new Set(policies.map(p => p.category))]; return { admx: renderADMX(regKey, versions, categories, policies), adml: [ { languageId: 'en-us', contents: renderADML(appName, versions, categories, policies) }, ...translations.map(({ languageId, languageTranslations }) => ({ languageId, contents: renderADML(appName, versions, categories, policies, languageTranslations) })) ] }; } const Languages = { 'fr': 'fr-fr', 'it': 'it-it', 'de': 'de-de', 'es': 'es-es', 'ru': 'ru-ru', 'zh-hans': 'zh-cn', 'zh-hant': 'zh-tw', 'ja': 'ja-jp', 'ko': 'ko-kr', 'cs': 'cs-cz', 'pt-br': 'pt-br', 'tr': 'tr-tr', 'pl': 'pl-pl', }; async function getLatestStableVersion(updateUrl) { const res = await (0, node_fetch_1.default)(`${updateUrl}/api/update/darwin/stable/latest`); const { name: version } = await res.json(); return version; } async function getSpecificNLS(resourceUrlTemplate, languageId, version) { const resource = { publisher: 'ms-ceintl', name: `vscode-language-pack-${languageId}`, version, path: 'extension/translations/main.i18n.json' }; const url = resourceUrlTemplate.replace(/\{([^}]+)\}/g, (_, key) => resource[key]); const res = await (0, node_fetch_1.default)(url); if (res.status !== 200) { throw new Error(`[${res.status}] Error downloading language pack ${languageId}@${version}`); } const { contents: result } = await res.json(); return result; } function previousVersion(version) { const [, major, minor, patch] = /^(\d+)\.(\d+)\.(\d+)$/.exec(version); return `${major}.${parseInt(minor) - 1}.${patch}`; } async function getNLS(resourceUrlTemplate, languageId, version) { try { return await getSpecificNLS(resourceUrlTemplate, languageId, version); } catch (err) { if (/\[404\]/.test(err.message)) { console.warn(`Language pack ${languageId}@${version} is missing. Downloading previous version...`); return await getSpecificNLS(resourceUrlTemplate, languageId, previousVersion(version)); } else { throw err; } } } async function parsePolicies() { const parser = new Parser(); parser.setLanguage(typescript); const files = await getFiles(process.cwd()); const base = path.join(process.cwd(), 'src'); const policies = []; for (const file of files) { const moduleName = path.relative(base, file).replace(/\.ts$/i, '').replace(/\\/g, '/'); const contents = await fs_1.promises.readFile(file, { encoding: 'utf8' }); const tree = parser.parse(contents); policies.push(...getPolicies(moduleName, tree.rootNode)); } return policies; } async function getTranslations() { const updateUrl = product.updateUrl; if (!updateUrl) { console.warn(`Skipping policy localization: No 'updateUrl' found in 'product.json'.`); return []; } const resourceUrlTemplate = product.extensionsGallery?.resourceUrlTemplate; if (!resourceUrlTemplate) { console.warn(`Skipping policy localization: No 'resourceUrlTemplate' found in 'product.json'.`); return []; } const version = await getLatestStableVersion(updateUrl); const languageIds = Object.keys(Languages); return await Promise.all(languageIds.map(languageId => getNLS(resourceUrlTemplate, languageId, version) .then(languageTranslations => ({ languageId, languageTranslations })))); } async function main() { const [policies, translations] = await Promise.all([parsePolicies(), getTranslations()]); const { admx, adml } = await renderGP(policies, translations); const root = '.build/policies/win32'; await fs_1.promises.rm(root, { recursive: true, force: true }); await fs_1.promises.mkdir(root, { recursive: true }); await fs_1.promises.writeFile(path.join(root, `${product.win32RegValueName}.admx`), admx.replace(/\r?\n/g, '\n')); for (const { languageId, contents } of adml) { const languagePath = path.join(root, languageId === 'en-us' ? 'en-us' : Languages[languageId]); await fs_1.promises.mkdir(languagePath, { recursive: true }); await fs_1.promises.writeFile(path.join(languagePath, `${product.win32RegValueName}.adml`), contents.replace(/\r?\n/g, '\n')); } } if (require.main === module) { main().catch(err => { console.error(err); process.exit(1); }); }
build/lib/policies.js
1
https://github.com/microsoft/vscode/commit/73fd3f11032e7b83c2ae011b5516e6ddd19e3db2
[ 0.00017792743165045977, 0.00017159087292384356, 0.00016180540842469782, 0.0001712496450636536, 0.000003166921942465706 ]
{ "id": 2, "code_window": [ "\n", "\t\tawait document.save();\n", "\t\tassert.strictEqual(document.isDirty, false);\n", "\t});\n", "\n", "\ttest('onDidOpenNotebookDocument - emit event only once when opened in two editors', async function () {\n", "\t\tconst uri = await utils.createRandomFile(undefined, undefined, '.nbdtest');\n", "\t\tlet counter = 0;\n", "\t\ttestDisposables.push(vscode.workspace.onDidOpenNotebookDocument(nb => {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\ttest.skip('onDidOpenNotebookDocument - emit event only once when opened in two editors', async function () { // TODO@rebornix https://github.com/microsoft/vscode/issues/157222\n" ], "file_path": "extensions/vscode-api-tests/src/singlefolder-tests/notebook.document.test.ts", "type": "replace", "edit_start_line_idx": 425 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as dom from 'vs/base/browser/dom'; import { Selection } from 'vs/editor/common/core/selection'; import { FastDomNode, createFastDomNode } from 'vs/base/browser/fastDomNode'; import { onUnexpectedError } from 'vs/base/common/errors'; import { IDisposable } from 'vs/base/common/lifecycle'; import { IPointerHandlerHelper } from 'vs/editor/browser/controller/mouseHandler'; import { PointerHandler } from 'vs/editor/browser/controller/pointerHandler'; import { IVisibleRangeProvider, TextAreaHandler } from 'vs/editor/browser/controller/textAreaHandler'; import { IContentWidget, IContentWidgetPosition, IOverlayWidget, IOverlayWidgetPosition, IMouseTarget, IViewZoneChangeAccessor, IEditorAriaOptions } from 'vs/editor/browser/editorBrowser'; import { ICommandDelegate, ViewController } from 'vs/editor/browser/view/viewController'; import { ViewUserInputEvents } from 'vs/editor/browser/view/viewUserInputEvents'; import { ContentViewOverlays, MarginViewOverlays } from 'vs/editor/browser/view/viewOverlays'; import { PartFingerprint, PartFingerprints, ViewPart } from 'vs/editor/browser/view/viewPart'; import { ViewContentWidgets } from 'vs/editor/browser/viewParts/contentWidgets/contentWidgets'; import { CurrentLineHighlightOverlay, CurrentLineMarginHighlightOverlay } from 'vs/editor/browser/viewParts/currentLineHighlight/currentLineHighlight'; import { DecorationsOverlay } from 'vs/editor/browser/viewParts/decorations/decorations'; import { EditorScrollbar } from 'vs/editor/browser/viewParts/editorScrollbar/editorScrollbar'; import { GlyphMarginOverlay } from 'vs/editor/browser/viewParts/glyphMargin/glyphMargin'; import { IndentGuidesOverlay } from 'vs/editor/browser/viewParts/indentGuides/indentGuides'; import { LineNumbersOverlay } from 'vs/editor/browser/viewParts/lineNumbers/lineNumbers'; import { ViewLines } from 'vs/editor/browser/viewParts/lines/viewLines'; import { LinesDecorationsOverlay } from 'vs/editor/browser/viewParts/linesDecorations/linesDecorations'; import { Margin } from 'vs/editor/browser/viewParts/margin/margin'; import { MarginViewLineDecorationsOverlay } from 'vs/editor/browser/viewParts/marginDecorations/marginDecorations'; import { Minimap } from 'vs/editor/browser/viewParts/minimap/minimap'; import { ViewOverlayWidgets } from 'vs/editor/browser/viewParts/overlayWidgets/overlayWidgets'; import { DecorationsOverviewRuler } from 'vs/editor/browser/viewParts/overviewRuler/decorationsOverviewRuler'; import { OverviewRuler } from 'vs/editor/browser/viewParts/overviewRuler/overviewRuler'; import { Rulers } from 'vs/editor/browser/viewParts/rulers/rulers'; import { ScrollDecorationViewPart } from 'vs/editor/browser/viewParts/scrollDecoration/scrollDecoration'; import { SelectionsOverlay } from 'vs/editor/browser/viewParts/selections/selections'; import { ViewCursors } from 'vs/editor/browser/viewParts/viewCursors/viewCursors'; import { ViewZones } from 'vs/editor/browser/viewParts/viewZones/viewZones'; import { Position } from 'vs/editor/common/core/position'; import { Range } from 'vs/editor/common/core/range'; import { ScrollType } from 'vs/editor/common/editorCommon'; import { IEditorConfiguration } from 'vs/editor/common/config/editorConfiguration'; import { RenderingContext } from 'vs/editor/browser/view/renderingContext'; import { ViewContext } from 'vs/editor/common/viewModel/viewContext'; import * as viewEvents from 'vs/editor/common/viewEvents'; import { ViewportData } from 'vs/editor/common/viewLayout/viewLinesViewportData'; import { ViewEventHandler } from 'vs/editor/common/viewEventHandler'; import { IViewModel } from 'vs/editor/common/viewModel'; import { getThemeTypeSelector, IColorTheme } from 'vs/platform/theme/common/themeService'; import { EditorOption } from 'vs/editor/common/config/editorOptions'; import { PointerHandlerLastRenderData } from 'vs/editor/browser/controller/mouseTarget'; import { BlockDecorations } from 'vs/editor/browser/viewParts/blockDecorations/blockDecorations'; export interface IContentWidgetData { widget: IContentWidget; position: IContentWidgetPosition | null; } export interface IOverlayWidgetData { widget: IOverlayWidget; position: IOverlayWidgetPosition | null; } export class View extends ViewEventHandler { private readonly _scrollbar: EditorScrollbar; private readonly _context: ViewContext; private _selections: Selection[]; // The view lines private readonly _viewLines: ViewLines; // These are parts, but we must do some API related calls on them, so we keep a reference private readonly _viewZones: ViewZones; private readonly _contentWidgets: ViewContentWidgets; private readonly _overlayWidgets: ViewOverlayWidgets; private readonly _viewCursors: ViewCursors; private readonly _viewParts: ViewPart[]; private readonly _textAreaHandler: TextAreaHandler; private readonly _pointerHandler: PointerHandler; // Dom nodes private readonly _linesContent: FastDomNode<HTMLElement>; public readonly domNode: FastDomNode<HTMLElement>; private readonly _overflowGuardContainer: FastDomNode<HTMLElement>; // Actual mutable state private _renderAnimationFrame: IDisposable | null; constructor( commandDelegate: ICommandDelegate, configuration: IEditorConfiguration, colorTheme: IColorTheme, model: IViewModel, userInputEvents: ViewUserInputEvents, overflowWidgetsDomNode: HTMLElement | undefined ) { super(); this._selections = [new Selection(1, 1, 1, 1)]; this._renderAnimationFrame = null; const viewController = new ViewController(configuration, model, userInputEvents, commandDelegate); // The view context is passed on to most classes (basically to reduce param. counts in ctors) this._context = new ViewContext(configuration, colorTheme, model); // Ensure the view is the first event handler in order to update the layout this._context.addEventHandler(this); this._viewParts = []; // Keyboard handler this._textAreaHandler = new TextAreaHandler(this._context, viewController, this._createTextAreaHandlerHelper()); this._viewParts.push(this._textAreaHandler); // These two dom nodes must be constructed up front, since references are needed in the layout provider (scrolling & co.) this._linesContent = createFastDomNode(document.createElement('div')); this._linesContent.setClassName('lines-content' + ' monaco-editor-background'); this._linesContent.setPosition('absolute'); this.domNode = createFastDomNode(document.createElement('div')); this.domNode.setClassName(this._getEditorClassName()); // Set role 'code' for better screen reader support https://github.com/microsoft/vscode/issues/93438 this.domNode.setAttribute('role', 'code'); this._overflowGuardContainer = createFastDomNode(document.createElement('div')); PartFingerprints.write(this._overflowGuardContainer, PartFingerprint.OverflowGuard); this._overflowGuardContainer.setClassName('overflow-guard'); this._scrollbar = new EditorScrollbar(this._context, this._linesContent, this.domNode, this._overflowGuardContainer); this._viewParts.push(this._scrollbar); // View Lines this._viewLines = new ViewLines(this._context, this._linesContent); // View Zones this._viewZones = new ViewZones(this._context); this._viewParts.push(this._viewZones); // Decorations overview ruler const decorationsOverviewRuler = new DecorationsOverviewRuler(this._context); this._viewParts.push(decorationsOverviewRuler); const scrollDecoration = new ScrollDecorationViewPart(this._context); this._viewParts.push(scrollDecoration); const contentViewOverlays = new ContentViewOverlays(this._context); this._viewParts.push(contentViewOverlays); contentViewOverlays.addDynamicOverlay(new CurrentLineHighlightOverlay(this._context)); contentViewOverlays.addDynamicOverlay(new SelectionsOverlay(this._context)); contentViewOverlays.addDynamicOverlay(new IndentGuidesOverlay(this._context)); contentViewOverlays.addDynamicOverlay(new DecorationsOverlay(this._context)); const marginViewOverlays = new MarginViewOverlays(this._context); this._viewParts.push(marginViewOverlays); marginViewOverlays.addDynamicOverlay(new CurrentLineMarginHighlightOverlay(this._context)); marginViewOverlays.addDynamicOverlay(new GlyphMarginOverlay(this._context)); marginViewOverlays.addDynamicOverlay(new MarginViewLineDecorationsOverlay(this._context)); marginViewOverlays.addDynamicOverlay(new LinesDecorationsOverlay(this._context)); marginViewOverlays.addDynamicOverlay(new LineNumbersOverlay(this._context)); const margin = new Margin(this._context); margin.getDomNode().appendChild(this._viewZones.marginDomNode); margin.getDomNode().appendChild(marginViewOverlays.getDomNode()); this._viewParts.push(margin); // Content widgets this._contentWidgets = new ViewContentWidgets(this._context, this.domNode); this._viewParts.push(this._contentWidgets); this._viewCursors = new ViewCursors(this._context); this._viewParts.push(this._viewCursors); // Overlay widgets this._overlayWidgets = new ViewOverlayWidgets(this._context); this._viewParts.push(this._overlayWidgets); const rulers = new Rulers(this._context); this._viewParts.push(rulers); const blockOutline = new BlockDecorations(this._context); this._viewParts.push(blockOutline); const minimap = new Minimap(this._context); this._viewParts.push(minimap); // -------------- Wire dom nodes up if (decorationsOverviewRuler) { const overviewRulerData = this._scrollbar.getOverviewRulerLayoutInfo(); overviewRulerData.parent.insertBefore(decorationsOverviewRuler.getDomNode(), overviewRulerData.insertBefore); } this._linesContent.appendChild(contentViewOverlays.getDomNode()); this._linesContent.appendChild(rulers.domNode); this._linesContent.appendChild(blockOutline.domNode); this._linesContent.appendChild(this._viewZones.domNode); this._linesContent.appendChild(this._viewLines.getDomNode()); this._linesContent.appendChild(this._contentWidgets.domNode); this._linesContent.appendChild(this._viewCursors.getDomNode()); this._overflowGuardContainer.appendChild(margin.getDomNode()); this._overflowGuardContainer.appendChild(this._scrollbar.getDomNode()); this._overflowGuardContainer.appendChild(scrollDecoration.getDomNode()); this._overflowGuardContainer.appendChild(this._textAreaHandler.textArea); this._overflowGuardContainer.appendChild(this._textAreaHandler.textAreaCover); this._overflowGuardContainer.appendChild(this._overlayWidgets.getDomNode()); this._overflowGuardContainer.appendChild(minimap.getDomNode()); this.domNode.appendChild(this._overflowGuardContainer); if (overflowWidgetsDomNode) { overflowWidgetsDomNode.appendChild(this._contentWidgets.overflowingContentWidgetsDomNode.domNode); } else { this.domNode.appendChild(this._contentWidgets.overflowingContentWidgetsDomNode); } this._applyLayout(); // Pointer handler this._pointerHandler = this._register(new PointerHandler(this._context, viewController, this._createPointerHandlerHelper())); } private _flushAccumulatedAndRenderNow(): void { this._renderNow(); } private _createPointerHandlerHelper(): IPointerHandlerHelper { return { viewDomNode: this.domNode.domNode, linesContentDomNode: this._linesContent.domNode, viewLinesDomNode: this._viewLines.getDomNode().domNode, focusTextArea: () => { this.focus(); }, dispatchTextAreaEvent: (event: CustomEvent) => { this._textAreaHandler.textArea.domNode.dispatchEvent(event); }, getLastRenderData: (): PointerHandlerLastRenderData => { const lastViewCursorsRenderData = this._viewCursors.getLastRenderData() || []; const lastTextareaPosition = this._textAreaHandler.getLastRenderData(); return new PointerHandlerLastRenderData(lastViewCursorsRenderData, lastTextareaPosition); }, shouldSuppressMouseDownOnViewZone: (viewZoneId: string) => { return this._viewZones.shouldSuppressMouseDownOnViewZone(viewZoneId); }, shouldSuppressMouseDownOnWidget: (widgetId: string) => { return this._contentWidgets.shouldSuppressMouseDownOnWidget(widgetId); }, getPositionFromDOMInfo: (spanNode: HTMLElement, offset: number) => { this._flushAccumulatedAndRenderNow(); return this._viewLines.getPositionFromDOMInfo(spanNode, offset); }, visibleRangeForPosition: (lineNumber: number, column: number) => { this._flushAccumulatedAndRenderNow(); return this._viewLines.visibleRangeForPosition(new Position(lineNumber, column)); }, getLineWidth: (lineNumber: number) => { this._flushAccumulatedAndRenderNow(); return this._viewLines.getLineWidth(lineNumber); } }; } private _createTextAreaHandlerHelper(): IVisibleRangeProvider { return { visibleRangeForPosition: (position: Position) => { this._flushAccumulatedAndRenderNow(); return this._viewLines.visibleRangeForPosition(position); } }; } private _applyLayout(): void { const options = this._context.configuration.options; const layoutInfo = options.get(EditorOption.layoutInfo); this.domNode.setWidth(layoutInfo.width); this.domNode.setHeight(layoutInfo.height); this._overflowGuardContainer.setWidth(layoutInfo.width); this._overflowGuardContainer.setHeight(layoutInfo.height); this._linesContent.setWidth(1000000); this._linesContent.setHeight(1000000); } private _getEditorClassName() { const focused = this._textAreaHandler.isFocused() ? ' focused' : ''; return this._context.configuration.options.get(EditorOption.editorClassName) + ' ' + getThemeTypeSelector(this._context.theme.type) + focused; } // --- begin event handlers public override handleEvents(events: viewEvents.ViewEvent[]): void { super.handleEvents(events); this._scheduleRender(); } public override onConfigurationChanged(e: viewEvents.ViewConfigurationChangedEvent): boolean { this.domNode.setClassName(this._getEditorClassName()); this._applyLayout(); return false; } public override onCursorStateChanged(e: viewEvents.ViewCursorStateChangedEvent): boolean { this._selections = e.selections; return false; } public override onFocusChanged(e: viewEvents.ViewFocusChangedEvent): boolean { this.domNode.setClassName(this._getEditorClassName()); return false; } public override onThemeChanged(e: viewEvents.ViewThemeChangedEvent): boolean { this._context.theme.update(e.theme); this.domNode.setClassName(this._getEditorClassName()); return false; } // --- end event handlers public override dispose(): void { if (this._renderAnimationFrame !== null) { this._renderAnimationFrame.dispose(); this._renderAnimationFrame = null; } this._contentWidgets.overflowingContentWidgetsDomNode.domNode.remove(); this._context.removeEventHandler(this); this._viewLines.dispose(); // Destroy view parts for (const viewPart of this._viewParts) { viewPart.dispose(); } super.dispose(); } private _scheduleRender(): void { if (this._renderAnimationFrame === null) { this._renderAnimationFrame = dom.runAtThisOrScheduleAtNextAnimationFrame(this._onRenderScheduled.bind(this), 100); } } private _onRenderScheduled(): void { this._renderAnimationFrame = null; this._flushAccumulatedAndRenderNow(); } private _renderNow(): void { safeInvokeNoArg(() => this._actualRender()); } private _getViewPartsToRender(): ViewPart[] { const result: ViewPart[] = []; let resultLen = 0; for (const viewPart of this._viewParts) { if (viewPart.shouldRender()) { result[resultLen++] = viewPart; } } return result; } private _actualRender(): void { if (!dom.isInDOM(this.domNode.domNode)) { return; } let viewPartsToRender = this._getViewPartsToRender(); if (!this._viewLines.shouldRender() && viewPartsToRender.length === 0) { // Nothing to render return; } const partialViewportData = this._context.viewLayout.getLinesViewportData(); this._context.viewModel.setViewport(partialViewportData.startLineNumber, partialViewportData.endLineNumber, partialViewportData.centeredLineNumber); const viewportData = new ViewportData( this._selections, partialViewportData, this._context.viewLayout.getWhitespaceViewportData(), this._context.viewModel ); if (this._contentWidgets.shouldRender()) { // Give the content widgets a chance to set their max width before a possible synchronous layout this._contentWidgets.onBeforeRender(viewportData); } if (this._viewLines.shouldRender()) { this._viewLines.renderText(viewportData); this._viewLines.onDidRender(); // Rendering of viewLines might cause scroll events to occur, so collect view parts to render again viewPartsToRender = this._getViewPartsToRender(); } const renderingContext = new RenderingContext(this._context.viewLayout, viewportData, this._viewLines); // Render the rest of the parts for (const viewPart of viewPartsToRender) { viewPart.prepareRender(renderingContext); } for (const viewPart of viewPartsToRender) { viewPart.render(renderingContext); viewPart.onDidRender(); } } // --- BEGIN CodeEditor helpers public delegateVerticalScrollbarPointerDown(browserEvent: PointerEvent): void { this._scrollbar.delegateVerticalScrollbarPointerDown(browserEvent); } public restoreState(scrollPosition: { scrollLeft: number; scrollTop: number }): void { this._context.viewModel.viewLayout.setScrollPosition({ scrollTop: scrollPosition.scrollTop }, ScrollType.Immediate); this._context.viewModel.tokenizeViewport(); this._renderNow(); this._viewLines.updateLineWidths(); this._context.viewModel.viewLayout.setScrollPosition({ scrollLeft: scrollPosition.scrollLeft }, ScrollType.Immediate); } public getOffsetForColumn(modelLineNumber: number, modelColumn: number): number { const modelPosition = this._context.viewModel.model.validatePosition({ lineNumber: modelLineNumber, column: modelColumn }); const viewPosition = this._context.viewModel.coordinatesConverter.convertModelPositionToViewPosition(modelPosition); this._flushAccumulatedAndRenderNow(); const visibleRange = this._viewLines.visibleRangeForPosition(new Position(viewPosition.lineNumber, viewPosition.column)); if (!visibleRange) { return -1; } return visibleRange.left; } public getTargetAtClientPoint(clientX: number, clientY: number): IMouseTarget | null { const mouseTarget = this._pointerHandler.getTargetAtClientPoint(clientX, clientY); if (!mouseTarget) { return null; } return ViewUserInputEvents.convertViewToModelMouseTarget(mouseTarget, this._context.viewModel.coordinatesConverter); } public createOverviewRuler(cssClassName: string): OverviewRuler { return new OverviewRuler(this._context, cssClassName); } public change(callback: (changeAccessor: IViewZoneChangeAccessor) => any): void { this._viewZones.changeViewZones(callback); this._scheduleRender(); } public render(now: boolean, everything: boolean): void { if (everything) { // Force everything to render... this._viewLines.forceShouldRender(); for (const viewPart of this._viewParts) { viewPart.forceShouldRender(); } } if (now) { this._flushAccumulatedAndRenderNow(); } else { this._scheduleRender(); } } public focus(): void { this._textAreaHandler.focusTextArea(); } public isFocused(): boolean { return this._textAreaHandler.isFocused(); } public refreshFocusState() { this._textAreaHandler.refreshFocusState(); } public setAriaOptions(options: IEditorAriaOptions): void { this._textAreaHandler.setAriaOptions(options); } public addContentWidget(widgetData: IContentWidgetData): void { this._contentWidgets.addWidget(widgetData.widget); this.layoutContentWidget(widgetData); this._scheduleRender(); } public layoutContentWidget(widgetData: IContentWidgetData): void { let newRange = widgetData.position ? widgetData.position.range || null : null; if (newRange === null) { const newPosition = widgetData.position ? widgetData.position.position : null; if (newPosition !== null) { newRange = new Range(newPosition.lineNumber, newPosition.column, newPosition.lineNumber, newPosition.column); } } const newPreference = widgetData.position ? widgetData.position.preference : null; this._contentWidgets.setWidgetPosition(widgetData.widget, newRange, newPreference, widgetData.position?.positionAffinity ?? null); this._scheduleRender(); } public removeContentWidget(widgetData: IContentWidgetData): void { this._contentWidgets.removeWidget(widgetData.widget); this._scheduleRender(); } public addOverlayWidget(widgetData: IOverlayWidgetData): void { this._overlayWidgets.addWidget(widgetData.widget); this.layoutOverlayWidget(widgetData); this._scheduleRender(); } public layoutOverlayWidget(widgetData: IOverlayWidgetData): void { const newPreference = widgetData.position ? widgetData.position.preference : null; const shouldRender = this._overlayWidgets.setWidgetPosition(widgetData.widget, newPreference); if (shouldRender) { this._scheduleRender(); } } public removeOverlayWidget(widgetData: IOverlayWidgetData): void { this._overlayWidgets.removeWidget(widgetData.widget); this._scheduleRender(); } // --- END CodeEditor helpers } function safeInvokeNoArg(func: Function): any { try { return func(); } catch (e) { onUnexpectedError(e); } }
src/vs/editor/browser/view.ts
0
https://github.com/microsoft/vscode/commit/73fd3f11032e7b83c2ae011b5516e6ddd19e3db2
[ 0.0003846943727694452, 0.00017691904213279486, 0.0001633229258004576, 0.00017257517902180552, 0.00003015941911144182 ]
{ "id": 2, "code_window": [ "\n", "\t\tawait document.save();\n", "\t\tassert.strictEqual(document.isDirty, false);\n", "\t});\n", "\n", "\ttest('onDidOpenNotebookDocument - emit event only once when opened in two editors', async function () {\n", "\t\tconst uri = await utils.createRandomFile(undefined, undefined, '.nbdtest');\n", "\t\tlet counter = 0;\n", "\t\ttestDisposables.push(vscode.workspace.onDidOpenNotebookDocument(nb => {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\ttest.skip('onDidOpenNotebookDocument - emit event only once when opened in two editors', async function () { // TODO@rebornix https://github.com/microsoft/vscode/issues/157222\n" ], "file_path": "extensions/vscode-api-tests/src/singlefolder-tests/notebook.document.test.ts", "type": "replace", "edit_start_line_idx": 425 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ .monaco-workbench .part.activitybar { width: 48px; height: 100%; } .monaco-workbench .activitybar.bordered::before { content: ''; float: left; position: absolute; box-sizing: border-box; height: 100%; width: 0px; border-color: inherit; } .monaco-workbench .activitybar.left.bordered::before { right: 0; border-right-style: solid; border-right-width: 1px; } .monaco-workbench .activitybar.right.bordered::before { left: 0; border-left-style: solid; border-left-width: 1px; } .monaco-workbench .activitybar > .content { height: 100%; display: flex; flex-direction: column; justify-content: space-between; } /** Viewlet Switcher */ .monaco-workbench .activitybar > .content .monaco-action-bar { text-align: left; background-color: inherit; } .monaco-workbench .activitybar .action-item:focus { outline: 0 !important; /* activity bar indicates focus custom */ } .monaco-workbench .activitybar > .content > .composite-bar { margin-bottom: auto; } /** Menu Bar */ .monaco-workbench .activitybar .menubar { width: 100%; height: 35px; } .monaco-workbench .activitybar .menubar.compact .toolbar-toggle-more { width: 100%; height: 35px; }
src/vs/workbench/browser/parts/activitybar/media/activitybarpart.css
0
https://github.com/microsoft/vscode/commit/73fd3f11032e7b83c2ae011b5516e6ddd19e3db2
[ 0.00017585033492650837, 0.00017421782831661403, 0.0001726303162286058, 0.0001742684398777783, 0.0000010596587571853888 ]
{ "id": 2, "code_window": [ "\n", "\t\tawait document.save();\n", "\t\tassert.strictEqual(document.isDirty, false);\n", "\t});\n", "\n", "\ttest('onDidOpenNotebookDocument - emit event only once when opened in two editors', async function () {\n", "\t\tconst uri = await utils.createRandomFile(undefined, undefined, '.nbdtest');\n", "\t\tlet counter = 0;\n", "\t\ttestDisposables.push(vscode.workspace.onDidOpenNotebookDocument(nb => {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\ttest.skip('onDidOpenNotebookDocument - emit event only once when opened in two editors', async function () { // TODO@rebornix https://github.com/microsoft/vscode/issues/157222\n" ], "file_path": "extensions/vscode-api-tests/src/singlefolder-tests/notebook.document.test.ts", "type": "replace", "edit_start_line_idx": 425 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { localize } from 'vs/nls'; import { MenuId, Action2, registerAction2 } from 'vs/platform/actions/common/actions'; import { KeyMod, KeyCode } from 'vs/base/common/keyCodes'; import { KeybindingsRegistry, KeybindingWeight, IKeybindingRule } from 'vs/platform/keybinding/common/keybindingsRegistry'; import { IQuickInputService, ItemActivation } from 'vs/platform/quickinput/common/quickInput'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { CommandsRegistry } from 'vs/platform/commands/common/commands'; import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation'; import { inQuickPickContext, defaultQuickAccessContext, getQuickNavigateHandler } from 'vs/workbench/browser/quickaccess'; import { ILocalizedString } from 'vs/platform/action/common/action'; //#region Quick access management commands and keys const globalQuickAccessKeybinding = { primary: KeyMod.CtrlCmd | KeyCode.KeyP, secondary: [KeyMod.CtrlCmd | KeyCode.KeyE], mac: { primary: KeyMod.CtrlCmd | KeyCode.KeyP, secondary: undefined } }; KeybindingsRegistry.registerCommandAndKeybindingRule({ id: 'workbench.action.closeQuickOpen', weight: KeybindingWeight.WorkbenchContrib, when: inQuickPickContext, primary: KeyCode.Escape, secondary: [KeyMod.Shift | KeyCode.Escape], handler: accessor => { const quickInputService = accessor.get(IQuickInputService); return quickInputService.cancel(); } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: 'workbench.action.acceptSelectedQuickOpenItem', weight: KeybindingWeight.WorkbenchContrib, when: inQuickPickContext, primary: 0, handler: accessor => { const quickInputService = accessor.get(IQuickInputService); return quickInputService.accept(); } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: 'workbench.action.alternativeAcceptSelectedQuickOpenItem', weight: KeybindingWeight.WorkbenchContrib, when: inQuickPickContext, primary: 0, handler: accessor => { const quickInputService = accessor.get(IQuickInputService); return quickInputService.accept({ ctrlCmd: true, alt: false }); } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: 'workbench.action.focusQuickOpen', weight: KeybindingWeight.WorkbenchContrib, when: inQuickPickContext, primary: 0, handler: accessor => { const quickInputService = accessor.get(IQuickInputService); quickInputService.focus(); } }); const quickAccessNavigateNextInFilePickerId = 'workbench.action.quickOpenNavigateNextInFilePicker'; KeybindingsRegistry.registerCommandAndKeybindingRule({ id: quickAccessNavigateNextInFilePickerId, weight: KeybindingWeight.WorkbenchContrib + 50, handler: getQuickNavigateHandler(quickAccessNavigateNextInFilePickerId, true), when: defaultQuickAccessContext, primary: globalQuickAccessKeybinding.primary, secondary: globalQuickAccessKeybinding.secondary, mac: globalQuickAccessKeybinding.mac }); const quickAccessNavigatePreviousInFilePickerId = 'workbench.action.quickOpenNavigatePreviousInFilePicker'; KeybindingsRegistry.registerCommandAndKeybindingRule({ id: quickAccessNavigatePreviousInFilePickerId, weight: KeybindingWeight.WorkbenchContrib + 50, handler: getQuickNavigateHandler(quickAccessNavigatePreviousInFilePickerId, false), when: defaultQuickAccessContext, primary: globalQuickAccessKeybinding.primary | KeyMod.Shift, secondary: [globalQuickAccessKeybinding.secondary[0] | KeyMod.Shift], mac: { primary: globalQuickAccessKeybinding.mac.primary | KeyMod.Shift, secondary: undefined } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: 'workbench.action.quickPickManyToggle', weight: KeybindingWeight.WorkbenchContrib, when: inQuickPickContext, primary: 0, handler: accessor => { const quickInputService = accessor.get(IQuickInputService); quickInputService.toggle(); } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: 'workbench.action.quickInputBack', weight: KeybindingWeight.WorkbenchContrib + 50, when: inQuickPickContext, primary: 0, win: { primary: KeyMod.Alt | KeyCode.LeftArrow }, mac: { primary: KeyMod.WinCtrl | KeyCode.Minus }, linux: { primary: KeyMod.CtrlCmd | KeyMod.Alt | KeyCode.Minus }, handler: accessor => { const quickInputService = accessor.get(IQuickInputService); quickInputService.back(); } }); registerAction2(class QuickAccessAction extends Action2 { constructor() { super({ id: 'workbench.action.quickOpen', title: { value: localize('quickOpen', "Go to File..."), original: 'Go to File...' }, description: { description: `Quick access`, args: [{ name: 'prefix', schema: { 'type': 'string' } }] }, keybinding: { weight: KeybindingWeight.WorkbenchContrib, primary: globalQuickAccessKeybinding.primary, secondary: globalQuickAccessKeybinding.secondary, mac: globalQuickAccessKeybinding.mac }, f1: true, menu: { id: MenuId.CommandCenter, order: 100 } }); } run(accessor: ServicesAccessor, prefix: undefined): void { const quickInputService = accessor.get(IQuickInputService); quickInputService.quickAccess.show(typeof prefix === 'string' ? prefix : undefined, { preserveValue: typeof prefix === 'string' /* preserve as is if provided */ }); } }); CommandsRegistry.registerCommand('workbench.action.quickOpenPreviousEditor', async accessor => { const quickInputService = accessor.get(IQuickInputService); quickInputService.quickAccess.show('', { itemActivation: ItemActivation.SECOND }); }); //#endregion //#region Workbench actions class BaseQuickAccessNavigateAction extends Action2 { constructor( private id: string, title: ILocalizedString, private next: boolean, private quickNavigate: boolean, keybinding?: Omit<IKeybindingRule, 'id'> ) { super({ id, title, f1: true, keybinding }); } async run(accessor: ServicesAccessor): Promise<void> { const keybindingService = accessor.get(IKeybindingService); const quickInputService = accessor.get(IQuickInputService); const keys = keybindingService.lookupKeybindings(this.id); const quickNavigate = this.quickNavigate ? { keybindings: keys } : undefined; quickInputService.navigate(this.next, quickNavigate); } } class QuickAccessNavigateNextAction extends BaseQuickAccessNavigateAction { constructor() { super('workbench.action.quickOpenNavigateNext', { value: localize('quickNavigateNext', "Navigate Next in Quick Open"), original: 'Navigate Next in Quick Open' }, true, true); } } class QuickAccessNavigatePreviousAction extends BaseQuickAccessNavigateAction { constructor() { super('workbench.action.quickOpenNavigatePrevious', { value: localize('quickNavigatePrevious', "Navigate Previous in Quick Open"), original: 'Navigate Previous in Quick Open' }, false, true); } } class QuickAccessSelectNextAction extends BaseQuickAccessNavigateAction { constructor() { super( 'workbench.action.quickOpenSelectNext', { value: localize('quickSelectNext', "Select Next in Quick Open"), original: 'Select Next in Quick Open' }, true, false, { weight: KeybindingWeight.WorkbenchContrib + 50, when: inQuickPickContext, primary: 0, mac: { primary: KeyMod.WinCtrl | KeyCode.KeyN } } ); } } class QuickAccessSelectPreviousAction extends BaseQuickAccessNavigateAction { constructor() { super( 'workbench.action.quickOpenSelectPrevious', { value: localize('quickSelectPrevious', "Select Previous in Quick Open"), original: 'Select Previous in Quick Open' }, false, false, { weight: KeybindingWeight.WorkbenchContrib + 50, when: inQuickPickContext, primary: 0, mac: { primary: KeyMod.WinCtrl | KeyCode.KeyP } } ); } } registerAction2(QuickAccessSelectNextAction); registerAction2(QuickAccessSelectPreviousAction); registerAction2(QuickAccessNavigateNextAction); registerAction2(QuickAccessNavigatePreviousAction); //#endregion
src/vs/workbench/browser/actions/quickAccessActions.ts
0
https://github.com/microsoft/vscode/commit/73fd3f11032e7b83c2ae011b5516e6ddd19e3db2
[ 0.0001751668896758929, 0.00017135852249339223, 0.00016500626225024462, 0.0001721301523502916, 0.0000029396953777904855 ]
{ "id": 0, "code_window": [ " }\n", "\n", " printAndIndentOnComments(node, parent) {\n", " const indent = !!node.leadingComments;\n", " if (indent) this.indent();\n", " this.print(node, parent);\n", " if (indent) this.dedent();\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " const indent = node.leadingComments && node.leadingComments.length > 0;\n" ], "file_path": "packages/babel-generator/src/printer.js", "type": "replace", "edit_start_line_idx": 445 }
import isInteger from "lodash/isInteger"; import repeat from "lodash/repeat"; import Buffer from "./buffer"; import * as n from "./node"; import * as t from "babel-types"; import * as generatorFunctions from "./generators"; const SCIENTIFIC_NOTATION = /e/i; const ZERO_DECIMAL_INTEGER = /\.0+$/; const NON_DECIMAL_LITERAL = /^0[box]/; export type Format = { shouldPrintComment: (comment: string) => boolean, retainLines: boolean, retainFunctionParens: boolean, comments: boolean, auxiliaryCommentBefore: string, auxiliaryCommentAfter: string, compact: boolean | "auto", minified: boolean, quotes: "single" | "double", concise: boolean, indent: { adjustMultilineComment: boolean, style: string, base: number, }, }; export default class Printer { constructor(format, map) { this.format = format || {}; this._buf = new Buffer(map); } format: Format; inForStatementInitCounter: number = 0; _buf: Buffer; _printStack: Array<Node> = []; _indent: number = 0; _insideAux: boolean = false; _printedCommentStarts: Object = {}; _parenPushNewlineState: ?Object = null; _noLineTerminator: boolean = false; _printAuxAfterOnNextUserNode: boolean = false; _printedComments: WeakSet = new WeakSet(); _endsWithInteger = false; _endsWithWord = false; generate(ast) { this.print(ast); this._maybeAddAuxComment(); return this._buf.get(); } /** * Increment indent size. */ indent(): void { if (this.format.compact || this.format.concise) return; this._indent++; } /** * Decrement indent size. */ dedent(): void { if (this.format.compact || this.format.concise) return; this._indent--; } /** * Add a semicolon to the buffer. */ semicolon(force: boolean = false): void { this._maybeAddAuxComment(); this._append(";", !force /* queue */); } /** * Add a right brace to the buffer. */ rightBrace(): void { if (this.format.minified) { this._buf.removeLastSemicolon(); } this.token("}"); } /** * Add a space to the buffer unless it is compact. */ space(force: boolean = false): void { if (this.format.compact) return; if ( (this._buf.hasContent() && !this.endsWith(" ") && !this.endsWith("\n")) || force ) { this._space(); } } /** * Writes a token that can't be safely parsed without taking whitespace into account. */ word(str: string): void { if (this._endsWithWord) this._space(); this._maybeAddAuxComment(); this._append(str); this._endsWithWord = true; } /** * Writes a number token so that we can validate if it is an integer. */ number(str: string): void { this.word(str); // Integer tokens need special handling because they cannot have '.'s inserted // immediately after them. this._endsWithInteger = isInteger(+str) && !NON_DECIMAL_LITERAL.test(str) && !SCIENTIFIC_NOTATION.test(str) && !ZERO_DECIMAL_INTEGER.test(str) && str[str.length - 1] !== "."; } /** * Writes a simple token. */ token(str: string): void { // space is mandatory to avoid outputting <!-- // http://javascript.spec.whatwg.org/#comment-syntax if ( (str === "--" && this.endsWith("!")) || // Need spaces for operators of the same kind to avoid: `a+++b` (str[0] === "+" && this.endsWith("+")) || (str[0] === "-" && this.endsWith("-")) || // Needs spaces to avoid changing '34' to '34.', which would still be a valid number. (str[0] === "." && this._endsWithInteger) ) { this._space(); } this._maybeAddAuxComment(); this._append(str); } /** * Add a newline (or many newlines), maintaining formatting. */ newline(i?: number): void { if (this.format.retainLines || this.format.compact) return; if (this.format.concise) { this.space(); return; } // never allow more than two lines if (this.endsWith("\n\n")) return; if (typeof i !== "number") i = 1; i = Math.min(2, i); if (this.endsWith("{\n") || this.endsWith(":\n")) i--; if (i <= 0) return; for (let j = 0; j < i; j++) { this._newline(); } } endsWith(str: string): boolean { return this._buf.endsWith(str); } removeTrailingNewline(): void { this._buf.removeTrailingNewline(); } source(prop: string, loc: Object): void { this._catchUp(prop, loc); this._buf.source(prop, loc); } withSource(prop: string, loc: Object, cb: () => void): void { this._catchUp(prop, loc); this._buf.withSource(prop, loc, cb); } _space(): void { this._append(" ", true /* queue */); } _newline(): void { this._append("\n", true /* queue */); } _append(str: string, queue: boolean = false) { this._maybeAddParen(str); this._maybeIndent(str); if (queue) this._buf.queue(str); else this._buf.append(str); this._endsWithWord = false; this._endsWithInteger = false; } _maybeIndent(str: string): void { // we've got a newline before us so prepend on the indentation if (this._indent && this.endsWith("\n") && str[0] !== "\n") { this._buf.queue(this._getIndent()); } } _maybeAddParen(str: string): void { // see startTerminatorless() instance method const parenPushNewlineState = this._parenPushNewlineState; if (!parenPushNewlineState) return; this._parenPushNewlineState = null; let i; for (i = 0; i < str.length && str[i] === " "; i++) continue; if (i === str.length) return; const cha = str[i]; if (cha === "\n" || cha === "/") { // we're going to break this terminator expression so we need to add a parentheses this.token("("); this.indent(); parenPushNewlineState.printed = true; } } _catchUp(prop: string, loc: Object) { if (!this.format.retainLines) return; // catch up to this nodes newline if we're behind const pos = loc ? loc[prop] : null; if (pos && pos.line !== null) { const count = pos.line - this._buf.getCurrentLine(); for (let i = 0; i < count; i++) { this._newline(); } } } /** * Get the current indent. */ _getIndent(): string { return repeat(this.format.indent.style, this._indent); } /** * Set some state that will be modified if a newline has been inserted before any * non-space characters. * * This is to prevent breaking semantics for terminatorless separator nodes. eg: * * return foo; * * returns `foo`. But if we do: * * return * foo; * * `undefined` will be returned and not `foo` due to the terminator. */ startTerminatorless(isLabel: boolean = false): Object { if (isLabel) { this._noLineTerminator = true; return null; } else { return (this._parenPushNewlineState = { printed: false, }); } } /** * Print an ending parentheses if a starting one has been printed. */ endTerminatorless(state: Object) { this._noLineTerminator = false; if (state && state.printed) { this.dedent(); this.newline(); this.token(")"); } } print(node, parent) { if (!node) return; const oldConcise = this.format.concise; if (node._compact) { this.format.concise = true; } const printMethod = this[node.type]; if (!printMethod) { throw new ReferenceError( `unknown node of type ${JSON.stringify( node.type, )} with constructor ${JSON.stringify(node && node.constructor.name)}`, ); } this._printStack.push(node); const oldInAux = this._insideAux; this._insideAux = !node.loc; this._maybeAddAuxComment(this._insideAux && !oldInAux); let needsParens = n.needsParens(node, parent, this._printStack); if ( this.format.retainFunctionParens && node.type === "FunctionExpression" && node.extra && node.extra.parenthesized ) { needsParens = true; } if (needsParens) this.token("("); this._printLeadingComments(node, parent); const loc = t.isProgram(node) || t.isFile(node) ? null : node.loc; this.withSource("start", loc, () => { this[node.type](node, parent); }); this._printTrailingComments(node, parent); if (needsParens) this.token(")"); // end this._printStack.pop(); this.format.concise = oldConcise; this._insideAux = oldInAux; } _maybeAddAuxComment(enteredPositionlessNode) { if (enteredPositionlessNode) this._printAuxBeforeComment(); if (!this._insideAux) this._printAuxAfterComment(); } _printAuxBeforeComment() { if (this._printAuxAfterOnNextUserNode) return; this._printAuxAfterOnNextUserNode = true; const comment = this.format.auxiliaryCommentBefore; if (comment) { this._printComment({ type: "CommentBlock", value: comment, }); } } _printAuxAfterComment() { if (!this._printAuxAfterOnNextUserNode) return; this._printAuxAfterOnNextUserNode = false; const comment = this.format.auxiliaryCommentAfter; if (comment) { this._printComment({ type: "CommentBlock", value: comment, }); } } getPossibleRaw(node) { const extra = node.extra; if ( extra && extra.raw != null && extra.rawValue != null && node.value === extra.rawValue ) { return extra.raw; } } printJoin(nodes: ?Array, parent: Object, opts = {}) { if (!nodes || !nodes.length) return; if (opts.indent) this.indent(); const newlineOpts = { addNewlines: opts.addNewlines, }; for (let i = 0; i < nodes.length; i++) { const node = nodes[i]; if (!node) continue; if (opts.statement) this._printNewline(true, node, parent, newlineOpts); this.print(node, parent); if (opts.iterator) { opts.iterator(node, i); } if (opts.separator && i < nodes.length - 1) { opts.separator.call(this); } if (opts.statement) this._printNewline(false, node, parent, newlineOpts); } if (opts.indent) this.dedent(); } printAndIndentOnComments(node, parent) { const indent = !!node.leadingComments; if (indent) this.indent(); this.print(node, parent); if (indent) this.dedent(); } printBlock(parent) { const node = parent.body; if (!t.isEmptyStatement(node)) { this.space(); } this.print(node, parent); } _printTrailingComments(node, parent) { this._printComments(this._getComments(false, node, parent)); } _printLeadingComments(node, parent) { this._printComments(this._getComments(true, node, parent)); } printInnerComments(node, indent = true) { if (!node.innerComments) return; if (indent) this.indent(); this._printComments(node.innerComments); if (indent) this.dedent(); } printSequence(nodes, parent, opts = {}) { opts.statement = true; return this.printJoin(nodes, parent, opts); } printList(items, parent, opts = {}) { if (opts.separator == null) { opts.separator = commaSeparator; } return this.printJoin(items, parent, opts); } _printNewline(leading, node, parent, opts) { // Fast path since 'this.newline' does nothing when not tracking lines. if (this.format.retainLines || this.format.compact) return; // Fast path for concise since 'this.newline' just inserts a space when // concise formatting is in use. if (this.format.concise) { this.space(); return; } let lines = 0; // don't add newlines at the beginning of the file if (this._buf.hasContent()) { if (!leading) lines++; // always include at least a single line after if (opts.addNewlines) lines += opts.addNewlines(leading, node) || 0; const needs = leading ? n.needsWhitespaceBefore : n.needsWhitespaceAfter; if (needs(node, parent)) lines++; } this.newline(lines); } _getComments(leading, node) { // Note, we use a boolean flag here instead of passing in the attribute name as it is faster // because this is called extremely frequently. return ( (node && (leading ? node.leadingComments : node.trailingComments)) || [] ); } _printComment(comment) { if (!this.format.shouldPrintComment(comment.value)) return; // Some plugins use this to mark comments as removed using the AST-root 'comments' property, // where they can't manually mutate the AST node comment lists. if (comment.ignore) return; if (this._printedComments.has(comment)) return; this._printedComments.add(comment); if (comment.start != null) { if (this._printedCommentStarts[comment.start]) return; this._printedCommentStarts[comment.start] = true; } const isBlockComment = comment.type === "CommentBlock"; // Always add a newline before a block comment this.newline( this._buf.hasContent() && !this._noLineTerminator && isBlockComment ? 1 : 0, ); if (!this.endsWith("[") && !this.endsWith("{")) this.space(); let val = !isBlockComment && !this._noLineTerminator ? `//${comment.value}\n` : `/*${comment.value}*/`; if (isBlockComment && this.format.indent.adjustMultilineComment) { const offset = comment.loc && comment.loc.start.column; if (offset) { const newlineRegex = new RegExp("\\n\\s{1," + offset + "}", "g"); val = val.replace(newlineRegex, "\n"); } const indentSize = Math.max( this._getIndent().length, this._buf.getCurrentColumn(), ); val = val.replace(/\n(?!$)/g, `\n${repeat(" ", indentSize)}`); } // Avoid creating //* comments if (this.endsWith("/")) this._space(); this.withSource("start", comment.loc, () => { this._append(val); }); // Always add a newline after a block comment this.newline(isBlockComment && !this._noLineTerminator ? 1 : 0); } _printComments(comments?: Array<Object>) { if (!comments || !comments.length) return; for (const comment of comments) { this._printComment(comment); } } } // Expose the node type functions and helpers on the prototype for easy usage. Object.assign(Printer.prototype, generatorFunctions); function commaSeparator() { this.token(","); this.space(); }
packages/babel-generator/src/printer.js
1
https://github.com/babel/babel/commit/ca117e08cb20d3e110757d5060e8d1661eca78eb
[ 0.9983795881271362, 0.06648486107587814, 0.0001639737602090463, 0.00027851914637722075, 0.22227124869823456 ]
{ "id": 0, "code_window": [ " }\n", "\n", " printAndIndentOnComments(node, parent) {\n", " const indent = !!node.leadingComments;\n", " if (indent) this.indent();\n", " this.print(node, parent);\n", " if (indent) this.dedent();\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " const indent = node.leadingComments && node.leadingComments.length > 0;\n" ], "file_path": "packages/babel-generator/src/printer.js", "type": "replace", "edit_start_line_idx": 445 }
import {bar} from "foo"; import {bar2, baz} from "foo"; import {bar as baz2} from "foo"; import {bar as baz3, xyz} from "foo"; bar; bar2; baz; baz2; baz3; xyz;
packages/babel-plugin-transform-es2015-modules-commonjs/test/fixtures/interop/imports-named/actual.js
0
https://github.com/babel/babel/commit/ca117e08cb20d3e110757d5060e8d1661eca78eb
[ 0.0001767230569384992, 0.0001766579516697675, 0.00017659286095295101, 0.0001766579516697675, 6.509799277409911e-8 ]
{ "id": 0, "code_window": [ " }\n", "\n", " printAndIndentOnComments(node, parent) {\n", " const indent = !!node.leadingComments;\n", " if (indent) this.indent();\n", " this.print(node, parent);\n", " if (indent) this.dedent();\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " const indent = node.leadingComments && node.leadingComments.length > 0;\n" ], "file_path": "packages/babel-generator/src/printer.js", "type": "replace", "edit_start_line_idx": 445 }
const obj = { *gen() { return function.sent; }, };
packages/babel-plugin-transform-function-sent/test/fixtures/generator-kinds/object-method/actual.js
0
https://github.com/babel/babel/commit/ca117e08cb20d3e110757d5060e8d1661eca78eb
[ 0.0001742779277265072, 0.0001742779277265072, 0.0001742779277265072, 0.0001742779277265072, 0 ]
{ "id": 0, "code_window": [ " }\n", "\n", " printAndIndentOnComments(node, parent) {\n", " const indent = !!node.leadingComments;\n", " if (indent) this.indent();\n", " this.print(node, parent);\n", " if (indent) this.dedent();\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " const indent = node.leadingComments && node.leadingComments.length > 0;\n" ], "file_path": "packages/babel-generator/src/printer.js", "type": "replace", "edit_start_line_idx": 445 }
(class implements X.Y<T> {}); (class C implements X.Y<T> {});
packages/babel-generator/test/fixtures/typescript/class-expression-implements/expected.js
0
https://github.com/babel/babel/commit/ca117e08cb20d3e110757d5060e8d1661eca78eb
[ 0.00017182808369398117, 0.00017182808369398117, 0.00017182808369398117, 0.00017182808369398117, 0 ]
{ "id": 1, "code_window": [ " }\n", "\n", " printInnerComments(node, indent = true) {\n", " if (!node.innerComments) return;\n", " if (indent) this.indent();\n", " this._printComments(node.innerComments);\n", " if (indent) this.dedent();\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " if (!node.innerComments || !node.innerComments.length) return;\n" ], "file_path": "packages/babel-generator/src/printer.js", "type": "replace", "edit_start_line_idx": 470 }
// This file contains methods that modify the path/node in some ways. import { path as pathCache } from "../cache"; import PathHoister from "./lib/hoister"; import NodePath from "./index"; import * as t from "babel-types"; /** * Insert the provided nodes before the current one. */ export function insertBefore(nodes) { this._assertUnremoved(); nodes = this._verifyNodeList(nodes); if ( this.parentPath.isExpressionStatement() || this.parentPath.isLabeledStatement() ) { return this.parentPath.insertBefore(nodes); } else if ( (this.isNodeType("Expression") && this.listKey !== "params") || (this.parentPath.isForStatement() && this.key === "init") ) { if (this.node) nodes.push(this.node); this.replaceExpressionWithStatements(nodes); } else if (Array.isArray(this.container)) { return this._containerInsertBefore(nodes); } else if (this.isStatementOrBlock()) { if (this.node) nodes.push(this.node); this._replaceWith(t.blockStatement(nodes)); } else { throw new Error( "We don't know what to do with this node type. " + "We were previously a Statement but we can't fit in here?", ); } return [this]; } export function _containerInsert(from, nodes) { this.updateSiblingKeys(from, nodes.length); const paths = []; for (let i = 0; i < nodes.length; i++) { const to = from + i; const node = nodes[i]; this.container.splice(to, 0, node); if (this.context) { const path = this.context.create( this.parent, this.container, to, this.listKey, ); // While this path may have a context, there is currently no guarantee that the context // will be the active context, because `popContext` may leave a final context in place. // We should remove this `if` and always push once #4145 has been resolved. if (this.context.queue) path.pushContext(this.context); paths.push(path); } else { paths.push( NodePath.get({ parentPath: this.parentPath, parent: this.parent, container: this.container, listKey: this.listKey, key: to, }), ); } } const contexts = this._getQueueContexts(); for (const path of paths) { path.setScope(); path.debug(() => "Inserted."); for (const context of contexts) { context.maybeQueue(path, true); } } return paths; } export function _containerInsertBefore(nodes) { return this._containerInsert(this.key, nodes); } export function _containerInsertAfter(nodes) { return this._containerInsert(this.key + 1, nodes); } /** * Insert the provided nodes after the current one. When inserting nodes after an * expression, ensure that the completion record is correct by pushing the current node. */ export function insertAfter(nodes) { return this._insertAfter(nodes); } export function _insertAfter(nodes, shouldRequeue = false) { this._assertUnremoved(); nodes = this._verifyNodeList(nodes); if ( this.parentPath.isExpressionStatement() || this.parentPath.isLabeledStatement() ) { // `replaceWithMultiple` requeues if there's a replacement for this.node, // but not for an ancestor's. Set `shouldRequeue` to true so that any replacement // for an ancestor node can be enqueued. Fix #5628 and #5023. return this.parentPath._insertAfter(nodes, true); } else if ( this.isNodeType("Expression") || (this.parentPath.isForStatement() && this.key === "init") ) { if (this.node) { const temp = this.scope.generateDeclaredUidIdentifier(); nodes.unshift( t.expressionStatement(t.assignmentExpression("=", temp, this.node)), ); nodes.push(t.expressionStatement(temp)); } this.replaceExpressionWithStatements(nodes); } else if (Array.isArray(this.container)) { return this._containerInsertAfter(nodes); } else if (this.isStatementOrBlock()) { // Unshift current node if it's not an empty expression if ( this.node && (!this.isExpressionStatement() || this.node.expression != null) ) { nodes.unshift(this.node); } this._replaceWith(t.blockStatement(nodes)); if (shouldRequeue) { this.requeue(); } } else { throw new Error( "We don't know what to do with this node type. " + "We were previously a Statement but we can't fit in here?", ); } return [this]; } /** * Update all sibling node paths after `fromIndex` by `incrementBy`. */ export function updateSiblingKeys(fromIndex, incrementBy) { if (!this.parent) return; const paths = pathCache.get(this.parent); for (let i = 0; i < paths.length; i++) { const path = paths[i]; if (path.key >= fromIndex) { path.key += incrementBy; } } } export function _verifyNodeList(nodes) { if (!nodes) { return []; } if (nodes.constructor !== Array) { nodes = [nodes]; } for (let i = 0; i < nodes.length; i++) { const node = nodes[i]; let msg; if (!node) { msg = "has falsy node"; } else if (typeof node !== "object") { msg = "contains a non-object node"; } else if (!node.type) { msg = "without a type"; } else if (node instanceof NodePath) { msg = "has a NodePath when it expected a raw object"; } if (msg) { const type = Array.isArray(node) ? "array" : typeof node; throw new Error( `Node list ${msg} with the index of ${i} and type of ${type}`, ); } } return nodes; } export function unshiftContainer(listKey, nodes) { this._assertUnremoved(); nodes = this._verifyNodeList(nodes); // get the first path and insert our nodes before it, if it doesn't exist then it // doesn't matter, our nodes will be inserted anyway const path = NodePath.get({ parentPath: this, parent: this.node, container: this.node[listKey], listKey, key: 0, }); return path.insertBefore(nodes); } export function pushContainer(listKey, nodes) { this._assertUnremoved(); nodes = this._verifyNodeList(nodes); // get an invisible path that represents the last node + 1 and replace it with our // nodes, effectively inlining it const container = this.node[listKey]; const path = NodePath.get({ parentPath: this, parent: this.node, container: container, listKey, key: container.length, }); return path.replaceWithMultiple(nodes); } /** * Hoist the current node to the highest scope possible and return a UID * referencing it. */ export function hoist(scope = this.scope) { const hoister = new PathHoister(this, scope); return hoister.run(); }
packages/babel-traverse/src/path/modification.js
1
https://github.com/babel/babel/commit/ca117e08cb20d3e110757d5060e8d1661eca78eb
[ 0.0013662264682352543, 0.00034144200617447495, 0.00016590520681347698, 0.0001757606805767864, 0.0002822809328790754 ]
{ "id": 1, "code_window": [ " }\n", "\n", " printInnerComments(node, indent = true) {\n", " if (!node.innerComments) return;\n", " if (indent) this.indent();\n", " this._printComments(node.innerComments);\n", " if (indent) this.dedent();\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " if (!node.innerComments || !node.innerComments.length) return;\n" ], "file_path": "packages/babel-generator/src/printer.js", "type": "replace", "edit_start_line_idx": 470 }
import _regeneratorRuntime from "foo/regenerator"; import _Symbol from "foo/core-js/symbol"; var _marked = /*#__PURE__*/ _regeneratorRuntime.mark(giveWord); import foo, * as bar from "someModule"; export const myWord = _Symbol("abc"); export function giveWord() { return _regeneratorRuntime.wrap(function giveWord$(_context) { while (1) switch (_context.prev = _context.next) { case 0: _context.next = 2; return myWord; case 2: case "end": return _context.stop(); } }, _marked, this); } foo; bar;
packages/babel-plugin-transform-runtime/test/fixtures/runtime/custom-runtime/expected.js
0
https://github.com/babel/babel/commit/ca117e08cb20d3e110757d5060e8d1661eca78eb
[ 0.00017686265346128494, 0.00017420091899111867, 0.00017196314001921564, 0.0001737769489409402, 0.000002022559101533261 ]
{ "id": 1, "code_window": [ " }\n", "\n", " printInnerComments(node, indent = true) {\n", " if (!node.innerComments) return;\n", " if (indent) this.indent();\n", " this._printComments(node.innerComments);\n", " if (indent) this.dedent();\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " if (!node.innerComments || !node.innerComments.length) return;\n" ], "file_path": "packages/babel-generator/src/printer.js", "type": "replace", "edit_start_line_idx": 470 }
var p = Promise.resolve(42); assert.equal(p, Promise.resolve(p));
packages/babel-preset-es2015/test/fixtures/traceur/Misc/PromiseResolve.js
0
https://github.com/babel/babel/commit/ca117e08cb20d3e110757d5060e8d1661eca78eb
[ 0.00017757252498995513, 0.00017757252498995513, 0.00017757252498995513, 0.00017757252498995513, 0 ]
{ "id": 1, "code_window": [ " }\n", "\n", " printInnerComments(node, indent = true) {\n", " if (!node.innerComments) return;\n", " if (indent) this.indent();\n", " this._printComments(node.innerComments);\n", " if (indent) this.dedent();\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " if (!node.innerComments || !node.innerComments.length) return;\n" ], "file_path": "packages/babel-generator/src/printer.js", "type": "replace", "edit_start_line_idx": 470 }
# babel-helper-optimise-call-expression ## Usage TODO
packages/babel-helper-optimise-call-expression/README.md
0
https://github.com/babel/babel/commit/ca117e08cb20d3e110757d5060e8d1661eca78eb
[ 0.00017635105177760124, 0.00017635105177760124, 0.00017635105177760124, 0.00017635105177760124, 0 ]
{ "id": 2, "code_window": [ " this.replaceExpressionWithStatements(nodes);\n", " } else if (Array.isArray(this.container)) {\n", " return this._containerInsertBefore(nodes);\n", " } else if (this.isStatementOrBlock()) {\n", " if (this.node) nodes.push(this.node);\n", " this._replaceWith(t.blockStatement(nodes));\n", " } else {\n", " throw new Error(\n", " \"We don't know what to do with this node type. \" +\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " this.replaceWith(t.blockStatement(nodes));\n" ], "file_path": "packages/babel-traverse/src/path/modification.js", "type": "replace", "edit_start_line_idx": 31 }
import isInteger from "lodash/isInteger"; import repeat from "lodash/repeat"; import Buffer from "./buffer"; import * as n from "./node"; import * as t from "babel-types"; import * as generatorFunctions from "./generators"; const SCIENTIFIC_NOTATION = /e/i; const ZERO_DECIMAL_INTEGER = /\.0+$/; const NON_DECIMAL_LITERAL = /^0[box]/; export type Format = { shouldPrintComment: (comment: string) => boolean, retainLines: boolean, retainFunctionParens: boolean, comments: boolean, auxiliaryCommentBefore: string, auxiliaryCommentAfter: string, compact: boolean | "auto", minified: boolean, quotes: "single" | "double", concise: boolean, indent: { adjustMultilineComment: boolean, style: string, base: number, }, }; export default class Printer { constructor(format, map) { this.format = format || {}; this._buf = new Buffer(map); } format: Format; inForStatementInitCounter: number = 0; _buf: Buffer; _printStack: Array<Node> = []; _indent: number = 0; _insideAux: boolean = false; _printedCommentStarts: Object = {}; _parenPushNewlineState: ?Object = null; _noLineTerminator: boolean = false; _printAuxAfterOnNextUserNode: boolean = false; _printedComments: WeakSet = new WeakSet(); _endsWithInteger = false; _endsWithWord = false; generate(ast) { this.print(ast); this._maybeAddAuxComment(); return this._buf.get(); } /** * Increment indent size. */ indent(): void { if (this.format.compact || this.format.concise) return; this._indent++; } /** * Decrement indent size. */ dedent(): void { if (this.format.compact || this.format.concise) return; this._indent--; } /** * Add a semicolon to the buffer. */ semicolon(force: boolean = false): void { this._maybeAddAuxComment(); this._append(";", !force /* queue */); } /** * Add a right brace to the buffer. */ rightBrace(): void { if (this.format.minified) { this._buf.removeLastSemicolon(); } this.token("}"); } /** * Add a space to the buffer unless it is compact. */ space(force: boolean = false): void { if (this.format.compact) return; if ( (this._buf.hasContent() && !this.endsWith(" ") && !this.endsWith("\n")) || force ) { this._space(); } } /** * Writes a token that can't be safely parsed without taking whitespace into account. */ word(str: string): void { if (this._endsWithWord) this._space(); this._maybeAddAuxComment(); this._append(str); this._endsWithWord = true; } /** * Writes a number token so that we can validate if it is an integer. */ number(str: string): void { this.word(str); // Integer tokens need special handling because they cannot have '.'s inserted // immediately after them. this._endsWithInteger = isInteger(+str) && !NON_DECIMAL_LITERAL.test(str) && !SCIENTIFIC_NOTATION.test(str) && !ZERO_DECIMAL_INTEGER.test(str) && str[str.length - 1] !== "."; } /** * Writes a simple token. */ token(str: string): void { // space is mandatory to avoid outputting <!-- // http://javascript.spec.whatwg.org/#comment-syntax if ( (str === "--" && this.endsWith("!")) || // Need spaces for operators of the same kind to avoid: `a+++b` (str[0] === "+" && this.endsWith("+")) || (str[0] === "-" && this.endsWith("-")) || // Needs spaces to avoid changing '34' to '34.', which would still be a valid number. (str[0] === "." && this._endsWithInteger) ) { this._space(); } this._maybeAddAuxComment(); this._append(str); } /** * Add a newline (or many newlines), maintaining formatting. */ newline(i?: number): void { if (this.format.retainLines || this.format.compact) return; if (this.format.concise) { this.space(); return; } // never allow more than two lines if (this.endsWith("\n\n")) return; if (typeof i !== "number") i = 1; i = Math.min(2, i); if (this.endsWith("{\n") || this.endsWith(":\n")) i--; if (i <= 0) return; for (let j = 0; j < i; j++) { this._newline(); } } endsWith(str: string): boolean { return this._buf.endsWith(str); } removeTrailingNewline(): void { this._buf.removeTrailingNewline(); } source(prop: string, loc: Object): void { this._catchUp(prop, loc); this._buf.source(prop, loc); } withSource(prop: string, loc: Object, cb: () => void): void { this._catchUp(prop, loc); this._buf.withSource(prop, loc, cb); } _space(): void { this._append(" ", true /* queue */); } _newline(): void { this._append("\n", true /* queue */); } _append(str: string, queue: boolean = false) { this._maybeAddParen(str); this._maybeIndent(str); if (queue) this._buf.queue(str); else this._buf.append(str); this._endsWithWord = false; this._endsWithInteger = false; } _maybeIndent(str: string): void { // we've got a newline before us so prepend on the indentation if (this._indent && this.endsWith("\n") && str[0] !== "\n") { this._buf.queue(this._getIndent()); } } _maybeAddParen(str: string): void { // see startTerminatorless() instance method const parenPushNewlineState = this._parenPushNewlineState; if (!parenPushNewlineState) return; this._parenPushNewlineState = null; let i; for (i = 0; i < str.length && str[i] === " "; i++) continue; if (i === str.length) return; const cha = str[i]; if (cha === "\n" || cha === "/") { // we're going to break this terminator expression so we need to add a parentheses this.token("("); this.indent(); parenPushNewlineState.printed = true; } } _catchUp(prop: string, loc: Object) { if (!this.format.retainLines) return; // catch up to this nodes newline if we're behind const pos = loc ? loc[prop] : null; if (pos && pos.line !== null) { const count = pos.line - this._buf.getCurrentLine(); for (let i = 0; i < count; i++) { this._newline(); } } } /** * Get the current indent. */ _getIndent(): string { return repeat(this.format.indent.style, this._indent); } /** * Set some state that will be modified if a newline has been inserted before any * non-space characters. * * This is to prevent breaking semantics for terminatorless separator nodes. eg: * * return foo; * * returns `foo`. But if we do: * * return * foo; * * `undefined` will be returned and not `foo` due to the terminator. */ startTerminatorless(isLabel: boolean = false): Object { if (isLabel) { this._noLineTerminator = true; return null; } else { return (this._parenPushNewlineState = { printed: false, }); } } /** * Print an ending parentheses if a starting one has been printed. */ endTerminatorless(state: Object) { this._noLineTerminator = false; if (state && state.printed) { this.dedent(); this.newline(); this.token(")"); } } print(node, parent) { if (!node) return; const oldConcise = this.format.concise; if (node._compact) { this.format.concise = true; } const printMethod = this[node.type]; if (!printMethod) { throw new ReferenceError( `unknown node of type ${JSON.stringify( node.type, )} with constructor ${JSON.stringify(node && node.constructor.name)}`, ); } this._printStack.push(node); const oldInAux = this._insideAux; this._insideAux = !node.loc; this._maybeAddAuxComment(this._insideAux && !oldInAux); let needsParens = n.needsParens(node, parent, this._printStack); if ( this.format.retainFunctionParens && node.type === "FunctionExpression" && node.extra && node.extra.parenthesized ) { needsParens = true; } if (needsParens) this.token("("); this._printLeadingComments(node, parent); const loc = t.isProgram(node) || t.isFile(node) ? null : node.loc; this.withSource("start", loc, () => { this[node.type](node, parent); }); this._printTrailingComments(node, parent); if (needsParens) this.token(")"); // end this._printStack.pop(); this.format.concise = oldConcise; this._insideAux = oldInAux; } _maybeAddAuxComment(enteredPositionlessNode) { if (enteredPositionlessNode) this._printAuxBeforeComment(); if (!this._insideAux) this._printAuxAfterComment(); } _printAuxBeforeComment() { if (this._printAuxAfterOnNextUserNode) return; this._printAuxAfterOnNextUserNode = true; const comment = this.format.auxiliaryCommentBefore; if (comment) { this._printComment({ type: "CommentBlock", value: comment, }); } } _printAuxAfterComment() { if (!this._printAuxAfterOnNextUserNode) return; this._printAuxAfterOnNextUserNode = false; const comment = this.format.auxiliaryCommentAfter; if (comment) { this._printComment({ type: "CommentBlock", value: comment, }); } } getPossibleRaw(node) { const extra = node.extra; if ( extra && extra.raw != null && extra.rawValue != null && node.value === extra.rawValue ) { return extra.raw; } } printJoin(nodes: ?Array, parent: Object, opts = {}) { if (!nodes || !nodes.length) return; if (opts.indent) this.indent(); const newlineOpts = { addNewlines: opts.addNewlines, }; for (let i = 0; i < nodes.length; i++) { const node = nodes[i]; if (!node) continue; if (opts.statement) this._printNewline(true, node, parent, newlineOpts); this.print(node, parent); if (opts.iterator) { opts.iterator(node, i); } if (opts.separator && i < nodes.length - 1) { opts.separator.call(this); } if (opts.statement) this._printNewline(false, node, parent, newlineOpts); } if (opts.indent) this.dedent(); } printAndIndentOnComments(node, parent) { const indent = !!node.leadingComments; if (indent) this.indent(); this.print(node, parent); if (indent) this.dedent(); } printBlock(parent) { const node = parent.body; if (!t.isEmptyStatement(node)) { this.space(); } this.print(node, parent); } _printTrailingComments(node, parent) { this._printComments(this._getComments(false, node, parent)); } _printLeadingComments(node, parent) { this._printComments(this._getComments(true, node, parent)); } printInnerComments(node, indent = true) { if (!node.innerComments) return; if (indent) this.indent(); this._printComments(node.innerComments); if (indent) this.dedent(); } printSequence(nodes, parent, opts = {}) { opts.statement = true; return this.printJoin(nodes, parent, opts); } printList(items, parent, opts = {}) { if (opts.separator == null) { opts.separator = commaSeparator; } return this.printJoin(items, parent, opts); } _printNewline(leading, node, parent, opts) { // Fast path since 'this.newline' does nothing when not tracking lines. if (this.format.retainLines || this.format.compact) return; // Fast path for concise since 'this.newline' just inserts a space when // concise formatting is in use. if (this.format.concise) { this.space(); return; } let lines = 0; // don't add newlines at the beginning of the file if (this._buf.hasContent()) { if (!leading) lines++; // always include at least a single line after if (opts.addNewlines) lines += opts.addNewlines(leading, node) || 0; const needs = leading ? n.needsWhitespaceBefore : n.needsWhitespaceAfter; if (needs(node, parent)) lines++; } this.newline(lines); } _getComments(leading, node) { // Note, we use a boolean flag here instead of passing in the attribute name as it is faster // because this is called extremely frequently. return ( (node && (leading ? node.leadingComments : node.trailingComments)) || [] ); } _printComment(comment) { if (!this.format.shouldPrintComment(comment.value)) return; // Some plugins use this to mark comments as removed using the AST-root 'comments' property, // where they can't manually mutate the AST node comment lists. if (comment.ignore) return; if (this._printedComments.has(comment)) return; this._printedComments.add(comment); if (comment.start != null) { if (this._printedCommentStarts[comment.start]) return; this._printedCommentStarts[comment.start] = true; } const isBlockComment = comment.type === "CommentBlock"; // Always add a newline before a block comment this.newline( this._buf.hasContent() && !this._noLineTerminator && isBlockComment ? 1 : 0, ); if (!this.endsWith("[") && !this.endsWith("{")) this.space(); let val = !isBlockComment && !this._noLineTerminator ? `//${comment.value}\n` : `/*${comment.value}*/`; if (isBlockComment && this.format.indent.adjustMultilineComment) { const offset = comment.loc && comment.loc.start.column; if (offset) { const newlineRegex = new RegExp("\\n\\s{1," + offset + "}", "g"); val = val.replace(newlineRegex, "\n"); } const indentSize = Math.max( this._getIndent().length, this._buf.getCurrentColumn(), ); val = val.replace(/\n(?!$)/g, `\n${repeat(" ", indentSize)}`); } // Avoid creating //* comments if (this.endsWith("/")) this._space(); this.withSource("start", comment.loc, () => { this._append(val); }); // Always add a newline after a block comment this.newline(isBlockComment && !this._noLineTerminator ? 1 : 0); } _printComments(comments?: Array<Object>) { if (!comments || !comments.length) return; for (const comment of comments) { this._printComment(comment); } } } // Expose the node type functions and helpers on the prototype for easy usage. Object.assign(Printer.prototype, generatorFunctions); function commaSeparator() { this.token(","); this.space(); }
packages/babel-generator/src/printer.js
1
https://github.com/babel/babel/commit/ca117e08cb20d3e110757d5060e8d1661eca78eb
[ 0.003219420788809657, 0.0002711274428293109, 0.00016275611415039748, 0.00016987384879030287, 0.0004118332581128925 ]
{ "id": 2, "code_window": [ " this.replaceExpressionWithStatements(nodes);\n", " } else if (Array.isArray(this.container)) {\n", " return this._containerInsertBefore(nodes);\n", " } else if (this.isStatementOrBlock()) {\n", " if (this.node) nodes.push(this.node);\n", " this._replaceWith(t.blockStatement(nodes));\n", " } else {\n", " throw new Error(\n", " \"We don't know what to do with this node type. \" +\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " this.replaceWith(t.blockStatement(nodes));\n" ], "file_path": "packages/babel-traverse/src/path/modification.js", "type": "replace", "edit_start_line_idx": 31 }
class Foo extends Bar { constructor() { this.foo = "bar"; super(); } }
packages/babel-plugin-transform-es2015-classes/test/fixtures/spec/this-not-allowed-before-super-in-derived-classes/actual.js
0
https://github.com/babel/babel/commit/ca117e08cb20d3e110757d5060e8d1661eca78eb
[ 0.0001656147069297731, 0.0001656147069297731, 0.0001656147069297731, 0.0001656147069297731, 0 ]
{ "id": 2, "code_window": [ " this.replaceExpressionWithStatements(nodes);\n", " } else if (Array.isArray(this.container)) {\n", " return this._containerInsertBefore(nodes);\n", " } else if (this.isStatementOrBlock()) {\n", " if (this.node) nodes.push(this.node);\n", " this._replaceWith(t.blockStatement(nodes));\n", " } else {\n", " throw new Error(\n", " \"We don't know what to do with this node type. \" +\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " this.replaceWith(t.blockStatement(nodes));\n" ], "file_path": "packages/babel-traverse/src/path/modification.js", "type": "replace", "edit_start_line_idx": 31 }
class C { x; x?; x: number; x: number = 1; }
packages/babel-generator/test/fixtures/typescript/class-properties/actual.js
0
https://github.com/babel/babel/commit/ca117e08cb20d3e110757d5060e8d1661eca78eb
[ 0.00017165939789265394, 0.00017165939789265394, 0.00017165939789265394, 0.00017165939789265394, 0 ]
{ "id": 2, "code_window": [ " this.replaceExpressionWithStatements(nodes);\n", " } else if (Array.isArray(this.container)) {\n", " return this._containerInsertBefore(nodes);\n", " } else if (this.isStatementOrBlock()) {\n", " if (this.node) nodes.push(this.node);\n", " this._replaceWith(t.blockStatement(nodes));\n", " } else {\n", " throw new Error(\n", " \"We don't know what to do with this node type. \" +\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " this.replaceWith(t.blockStatement(nodes));\n" ], "file_path": "packages/babel-traverse/src/path/modification.js", "type": "replace", "edit_start_line_idx": 31 }
{ "plugins": ["external-helpers", "transform-es2015-function-name", "transform-es2015-arrow-functions"] }
packages/babel-plugin-transform-es2015-function-name/test/fixtures/function-name/with-arrow-functions-transform/options.json
0
https://github.com/babel/babel/commit/ca117e08cb20d3e110757d5060e8d1661eca78eb
[ 0.00017318277969025075, 0.00017318277969025075, 0.00017318277969025075, 0.00017318277969025075, 0 ]
{ "id": 3, "code_window": [ " * expression, ensure that the completion record is correct by pushing the current node.\n", " */\n", "\n", "export function insertAfter(nodes) {\n", " return this._insertAfter(nodes);\n", "}\n", "\n", "export function _insertAfter(nodes, shouldRequeue = false) {\n", " this._assertUnremoved();\n", "\n", " nodes = this._verifyNodeList(nodes);\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/babel-traverse/src/path/modification.js", "type": "replace", "edit_start_line_idx": 106 }
// This file contains methods that modify the path/node in some ways. import { path as pathCache } from "../cache"; import PathHoister from "./lib/hoister"; import NodePath from "./index"; import * as t from "babel-types"; /** * Insert the provided nodes before the current one. */ export function insertBefore(nodes) { this._assertUnremoved(); nodes = this._verifyNodeList(nodes); if ( this.parentPath.isExpressionStatement() || this.parentPath.isLabeledStatement() ) { return this.parentPath.insertBefore(nodes); } else if ( (this.isNodeType("Expression") && this.listKey !== "params") || (this.parentPath.isForStatement() && this.key === "init") ) { if (this.node) nodes.push(this.node); this.replaceExpressionWithStatements(nodes); } else if (Array.isArray(this.container)) { return this._containerInsertBefore(nodes); } else if (this.isStatementOrBlock()) { if (this.node) nodes.push(this.node); this._replaceWith(t.blockStatement(nodes)); } else { throw new Error( "We don't know what to do with this node type. " + "We were previously a Statement but we can't fit in here?", ); } return [this]; } export function _containerInsert(from, nodes) { this.updateSiblingKeys(from, nodes.length); const paths = []; for (let i = 0; i < nodes.length; i++) { const to = from + i; const node = nodes[i]; this.container.splice(to, 0, node); if (this.context) { const path = this.context.create( this.parent, this.container, to, this.listKey, ); // While this path may have a context, there is currently no guarantee that the context // will be the active context, because `popContext` may leave a final context in place. // We should remove this `if` and always push once #4145 has been resolved. if (this.context.queue) path.pushContext(this.context); paths.push(path); } else { paths.push( NodePath.get({ parentPath: this.parentPath, parent: this.parent, container: this.container, listKey: this.listKey, key: to, }), ); } } const contexts = this._getQueueContexts(); for (const path of paths) { path.setScope(); path.debug(() => "Inserted."); for (const context of contexts) { context.maybeQueue(path, true); } } return paths; } export function _containerInsertBefore(nodes) { return this._containerInsert(this.key, nodes); } export function _containerInsertAfter(nodes) { return this._containerInsert(this.key + 1, nodes); } /** * Insert the provided nodes after the current one. When inserting nodes after an * expression, ensure that the completion record is correct by pushing the current node. */ export function insertAfter(nodes) { return this._insertAfter(nodes); } export function _insertAfter(nodes, shouldRequeue = false) { this._assertUnremoved(); nodes = this._verifyNodeList(nodes); if ( this.parentPath.isExpressionStatement() || this.parentPath.isLabeledStatement() ) { // `replaceWithMultiple` requeues if there's a replacement for this.node, // but not for an ancestor's. Set `shouldRequeue` to true so that any replacement // for an ancestor node can be enqueued. Fix #5628 and #5023. return this.parentPath._insertAfter(nodes, true); } else if ( this.isNodeType("Expression") || (this.parentPath.isForStatement() && this.key === "init") ) { if (this.node) { const temp = this.scope.generateDeclaredUidIdentifier(); nodes.unshift( t.expressionStatement(t.assignmentExpression("=", temp, this.node)), ); nodes.push(t.expressionStatement(temp)); } this.replaceExpressionWithStatements(nodes); } else if (Array.isArray(this.container)) { return this._containerInsertAfter(nodes); } else if (this.isStatementOrBlock()) { // Unshift current node if it's not an empty expression if ( this.node && (!this.isExpressionStatement() || this.node.expression != null) ) { nodes.unshift(this.node); } this._replaceWith(t.blockStatement(nodes)); if (shouldRequeue) { this.requeue(); } } else { throw new Error( "We don't know what to do with this node type. " + "We were previously a Statement but we can't fit in here?", ); } return [this]; } /** * Update all sibling node paths after `fromIndex` by `incrementBy`. */ export function updateSiblingKeys(fromIndex, incrementBy) { if (!this.parent) return; const paths = pathCache.get(this.parent); for (let i = 0; i < paths.length; i++) { const path = paths[i]; if (path.key >= fromIndex) { path.key += incrementBy; } } } export function _verifyNodeList(nodes) { if (!nodes) { return []; } if (nodes.constructor !== Array) { nodes = [nodes]; } for (let i = 0; i < nodes.length; i++) { const node = nodes[i]; let msg; if (!node) { msg = "has falsy node"; } else if (typeof node !== "object") { msg = "contains a non-object node"; } else if (!node.type) { msg = "without a type"; } else if (node instanceof NodePath) { msg = "has a NodePath when it expected a raw object"; } if (msg) { const type = Array.isArray(node) ? "array" : typeof node; throw new Error( `Node list ${msg} with the index of ${i} and type of ${type}`, ); } } return nodes; } export function unshiftContainer(listKey, nodes) { this._assertUnremoved(); nodes = this._verifyNodeList(nodes); // get the first path and insert our nodes before it, if it doesn't exist then it // doesn't matter, our nodes will be inserted anyway const path = NodePath.get({ parentPath: this, parent: this.node, container: this.node[listKey], listKey, key: 0, }); return path.insertBefore(nodes); } export function pushContainer(listKey, nodes) { this._assertUnremoved(); nodes = this._verifyNodeList(nodes); // get an invisible path that represents the last node + 1 and replace it with our // nodes, effectively inlining it const container = this.node[listKey]; const path = NodePath.get({ parentPath: this, parent: this.node, container: container, listKey, key: container.length, }); return path.replaceWithMultiple(nodes); } /** * Hoist the current node to the highest scope possible and return a UID * referencing it. */ export function hoist(scope = this.scope) { const hoister = new PathHoister(this, scope); return hoister.run(); }
packages/babel-traverse/src/path/modification.js
1
https://github.com/babel/babel/commit/ca117e08cb20d3e110757d5060e8d1661eca78eb
[ 0.9989683628082275, 0.2510695159435272, 0.00016453336866106838, 0.004171040840446949, 0.4122781753540039 ]
{ "id": 3, "code_window": [ " * expression, ensure that the completion record is correct by pushing the current node.\n", " */\n", "\n", "export function insertAfter(nodes) {\n", " return this._insertAfter(nodes);\n", "}\n", "\n", "export function _insertAfter(nodes, shouldRequeue = false) {\n", " this._assertUnremoved();\n", "\n", " nodes = this._verifyNodeList(nodes);\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/babel-traverse/src/path/modification.js", "type": "replace", "edit_start_line_idx": 106 }
var f0 = function (a, b = a, c = b) { return [a, b, c]; }; assert.deepEqual(f0(1), [1, 1, 1]); var f1 = function ({a}, b = a, c = b) { return [a, b, c]; }; assert.deepEqual(f1({a: 1}), [1, 1, 1]); var f2 = function ({a}, b = a, c = a) { return [a, b, c]; }; assert.deepEqual(f2({a: 1}), [1, 1, 1]);
packages/babel-plugin-transform-es2015-destructuring/test/fixtures/destructuring/default-precedence/exec.js
0
https://github.com/babel/babel/commit/ca117e08cb20d3e110757d5060e8d1661eca78eb
[ 0.000176589164766483, 0.00017542630666866899, 0.0001742634631227702, 0.00017542630666866899, 0.0000011628508218564093 ]
{ "id": 3, "code_window": [ " * expression, ensure that the completion record is correct by pushing the current node.\n", " */\n", "\n", "export function insertAfter(nodes) {\n", " return this._insertAfter(nodes);\n", "}\n", "\n", "export function _insertAfter(nodes, shouldRequeue = false) {\n", " this._assertUnremoved();\n", "\n", " nodes = this._verifyNodeList(nodes);\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/babel-traverse/src/path/modification.js", "type": "replace", "edit_start_line_idx": 106 }
var _ref = <div>child</div>; var _ref3 = <p>Parent</p>; (function () { const AppItem = () => { return _ref; }; var _ref2 = <div> {_ref3} <AppItem /> </div>; class App extends React.Component { render() { return _ref2; } } });
packages/babel-plugin-transform-react-constant-elements/test/fixtures/constant-elements/append-to-end-when-declared-in-scope-4/expected.js
0
https://github.com/babel/babel/commit/ca117e08cb20d3e110757d5060e8d1661eca78eb
[ 0.00017619121354073286, 0.00017065131396520883, 0.00016634682833682746, 0.0001694159145699814, 0.000004112796887056902 ]
{ "id": 3, "code_window": [ " * expression, ensure that the completion record is correct by pushing the current node.\n", " */\n", "\n", "export function insertAfter(nodes) {\n", " return this._insertAfter(nodes);\n", "}\n", "\n", "export function _insertAfter(nodes, shouldRequeue = false) {\n", " this._assertUnremoved();\n", "\n", " nodes = this._verifyNodeList(nodes);\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/babel-traverse/src/path/modification.js", "type": "replace", "edit_start_line_idx": 106 }
<Namespace.DeepNamespace.Component />;
packages/babel-plugin-transform-react-jsx/test/fixtures/react/should-allow-deeper-js-namespacing/actual.js
0
https://github.com/babel/babel/commit/ca117e08cb20d3e110757d5060e8d1661eca78eb
[ 0.00017046203720383346, 0.00017046203720383346, 0.00017046203720383346, 0.00017046203720383346, 0 ]
{ "id": 4, "code_window": [ " if (\n", " this.parentPath.isExpressionStatement() ||\n", " this.parentPath.isLabeledStatement()\n", " ) {\n", " // `replaceWithMultiple` requeues if there's a replacement for this.node,\n", " // but not for an ancestor's. Set `shouldRequeue` to true so that any replacement\n", " // for an ancestor node can be enqueued. Fix #5628 and #5023.\n", " return this.parentPath._insertAfter(nodes, true);\n", " } else if (\n", " this.isNodeType(\"Expression\") ||\n", " (this.parentPath.isForStatement() && this.key === \"init\")\n", " ) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " return this.parentPath.insertAfter(nodes);\n" ], "file_path": "packages/babel-traverse/src/path/modification.js", "type": "replace", "edit_start_line_idx": 118 }
import isInteger from "lodash/isInteger"; import repeat from "lodash/repeat"; import Buffer from "./buffer"; import * as n from "./node"; import * as t from "babel-types"; import * as generatorFunctions from "./generators"; const SCIENTIFIC_NOTATION = /e/i; const ZERO_DECIMAL_INTEGER = /\.0+$/; const NON_DECIMAL_LITERAL = /^0[box]/; export type Format = { shouldPrintComment: (comment: string) => boolean, retainLines: boolean, retainFunctionParens: boolean, comments: boolean, auxiliaryCommentBefore: string, auxiliaryCommentAfter: string, compact: boolean | "auto", minified: boolean, quotes: "single" | "double", concise: boolean, indent: { adjustMultilineComment: boolean, style: string, base: number, }, }; export default class Printer { constructor(format, map) { this.format = format || {}; this._buf = new Buffer(map); } format: Format; inForStatementInitCounter: number = 0; _buf: Buffer; _printStack: Array<Node> = []; _indent: number = 0; _insideAux: boolean = false; _printedCommentStarts: Object = {}; _parenPushNewlineState: ?Object = null; _noLineTerminator: boolean = false; _printAuxAfterOnNextUserNode: boolean = false; _printedComments: WeakSet = new WeakSet(); _endsWithInteger = false; _endsWithWord = false; generate(ast) { this.print(ast); this._maybeAddAuxComment(); return this._buf.get(); } /** * Increment indent size. */ indent(): void { if (this.format.compact || this.format.concise) return; this._indent++; } /** * Decrement indent size. */ dedent(): void { if (this.format.compact || this.format.concise) return; this._indent--; } /** * Add a semicolon to the buffer. */ semicolon(force: boolean = false): void { this._maybeAddAuxComment(); this._append(";", !force /* queue */); } /** * Add a right brace to the buffer. */ rightBrace(): void { if (this.format.minified) { this._buf.removeLastSemicolon(); } this.token("}"); } /** * Add a space to the buffer unless it is compact. */ space(force: boolean = false): void { if (this.format.compact) return; if ( (this._buf.hasContent() && !this.endsWith(" ") && !this.endsWith("\n")) || force ) { this._space(); } } /** * Writes a token that can't be safely parsed without taking whitespace into account. */ word(str: string): void { if (this._endsWithWord) this._space(); this._maybeAddAuxComment(); this._append(str); this._endsWithWord = true; } /** * Writes a number token so that we can validate if it is an integer. */ number(str: string): void { this.word(str); // Integer tokens need special handling because they cannot have '.'s inserted // immediately after them. this._endsWithInteger = isInteger(+str) && !NON_DECIMAL_LITERAL.test(str) && !SCIENTIFIC_NOTATION.test(str) && !ZERO_DECIMAL_INTEGER.test(str) && str[str.length - 1] !== "."; } /** * Writes a simple token. */ token(str: string): void { // space is mandatory to avoid outputting <!-- // http://javascript.spec.whatwg.org/#comment-syntax if ( (str === "--" && this.endsWith("!")) || // Need spaces for operators of the same kind to avoid: `a+++b` (str[0] === "+" && this.endsWith("+")) || (str[0] === "-" && this.endsWith("-")) || // Needs spaces to avoid changing '34' to '34.', which would still be a valid number. (str[0] === "." && this._endsWithInteger) ) { this._space(); } this._maybeAddAuxComment(); this._append(str); } /** * Add a newline (or many newlines), maintaining formatting. */ newline(i?: number): void { if (this.format.retainLines || this.format.compact) return; if (this.format.concise) { this.space(); return; } // never allow more than two lines if (this.endsWith("\n\n")) return; if (typeof i !== "number") i = 1; i = Math.min(2, i); if (this.endsWith("{\n") || this.endsWith(":\n")) i--; if (i <= 0) return; for (let j = 0; j < i; j++) { this._newline(); } } endsWith(str: string): boolean { return this._buf.endsWith(str); } removeTrailingNewline(): void { this._buf.removeTrailingNewline(); } source(prop: string, loc: Object): void { this._catchUp(prop, loc); this._buf.source(prop, loc); } withSource(prop: string, loc: Object, cb: () => void): void { this._catchUp(prop, loc); this._buf.withSource(prop, loc, cb); } _space(): void { this._append(" ", true /* queue */); } _newline(): void { this._append("\n", true /* queue */); } _append(str: string, queue: boolean = false) { this._maybeAddParen(str); this._maybeIndent(str); if (queue) this._buf.queue(str); else this._buf.append(str); this._endsWithWord = false; this._endsWithInteger = false; } _maybeIndent(str: string): void { // we've got a newline before us so prepend on the indentation if (this._indent && this.endsWith("\n") && str[0] !== "\n") { this._buf.queue(this._getIndent()); } } _maybeAddParen(str: string): void { // see startTerminatorless() instance method const parenPushNewlineState = this._parenPushNewlineState; if (!parenPushNewlineState) return; this._parenPushNewlineState = null; let i; for (i = 0; i < str.length && str[i] === " "; i++) continue; if (i === str.length) return; const cha = str[i]; if (cha === "\n" || cha === "/") { // we're going to break this terminator expression so we need to add a parentheses this.token("("); this.indent(); parenPushNewlineState.printed = true; } } _catchUp(prop: string, loc: Object) { if (!this.format.retainLines) return; // catch up to this nodes newline if we're behind const pos = loc ? loc[prop] : null; if (pos && pos.line !== null) { const count = pos.line - this._buf.getCurrentLine(); for (let i = 0; i < count; i++) { this._newline(); } } } /** * Get the current indent. */ _getIndent(): string { return repeat(this.format.indent.style, this._indent); } /** * Set some state that will be modified if a newline has been inserted before any * non-space characters. * * This is to prevent breaking semantics for terminatorless separator nodes. eg: * * return foo; * * returns `foo`. But if we do: * * return * foo; * * `undefined` will be returned and not `foo` due to the terminator. */ startTerminatorless(isLabel: boolean = false): Object { if (isLabel) { this._noLineTerminator = true; return null; } else { return (this._parenPushNewlineState = { printed: false, }); } } /** * Print an ending parentheses if a starting one has been printed. */ endTerminatorless(state: Object) { this._noLineTerminator = false; if (state && state.printed) { this.dedent(); this.newline(); this.token(")"); } } print(node, parent) { if (!node) return; const oldConcise = this.format.concise; if (node._compact) { this.format.concise = true; } const printMethod = this[node.type]; if (!printMethod) { throw new ReferenceError( `unknown node of type ${JSON.stringify( node.type, )} with constructor ${JSON.stringify(node && node.constructor.name)}`, ); } this._printStack.push(node); const oldInAux = this._insideAux; this._insideAux = !node.loc; this._maybeAddAuxComment(this._insideAux && !oldInAux); let needsParens = n.needsParens(node, parent, this._printStack); if ( this.format.retainFunctionParens && node.type === "FunctionExpression" && node.extra && node.extra.parenthesized ) { needsParens = true; } if (needsParens) this.token("("); this._printLeadingComments(node, parent); const loc = t.isProgram(node) || t.isFile(node) ? null : node.loc; this.withSource("start", loc, () => { this[node.type](node, parent); }); this._printTrailingComments(node, parent); if (needsParens) this.token(")"); // end this._printStack.pop(); this.format.concise = oldConcise; this._insideAux = oldInAux; } _maybeAddAuxComment(enteredPositionlessNode) { if (enteredPositionlessNode) this._printAuxBeforeComment(); if (!this._insideAux) this._printAuxAfterComment(); } _printAuxBeforeComment() { if (this._printAuxAfterOnNextUserNode) return; this._printAuxAfterOnNextUserNode = true; const comment = this.format.auxiliaryCommentBefore; if (comment) { this._printComment({ type: "CommentBlock", value: comment, }); } } _printAuxAfterComment() { if (!this._printAuxAfterOnNextUserNode) return; this._printAuxAfterOnNextUserNode = false; const comment = this.format.auxiliaryCommentAfter; if (comment) { this._printComment({ type: "CommentBlock", value: comment, }); } } getPossibleRaw(node) { const extra = node.extra; if ( extra && extra.raw != null && extra.rawValue != null && node.value === extra.rawValue ) { return extra.raw; } } printJoin(nodes: ?Array, parent: Object, opts = {}) { if (!nodes || !nodes.length) return; if (opts.indent) this.indent(); const newlineOpts = { addNewlines: opts.addNewlines, }; for (let i = 0; i < nodes.length; i++) { const node = nodes[i]; if (!node) continue; if (opts.statement) this._printNewline(true, node, parent, newlineOpts); this.print(node, parent); if (opts.iterator) { opts.iterator(node, i); } if (opts.separator && i < nodes.length - 1) { opts.separator.call(this); } if (opts.statement) this._printNewline(false, node, parent, newlineOpts); } if (opts.indent) this.dedent(); } printAndIndentOnComments(node, parent) { const indent = !!node.leadingComments; if (indent) this.indent(); this.print(node, parent); if (indent) this.dedent(); } printBlock(parent) { const node = parent.body; if (!t.isEmptyStatement(node)) { this.space(); } this.print(node, parent); } _printTrailingComments(node, parent) { this._printComments(this._getComments(false, node, parent)); } _printLeadingComments(node, parent) { this._printComments(this._getComments(true, node, parent)); } printInnerComments(node, indent = true) { if (!node.innerComments) return; if (indent) this.indent(); this._printComments(node.innerComments); if (indent) this.dedent(); } printSequence(nodes, parent, opts = {}) { opts.statement = true; return this.printJoin(nodes, parent, opts); } printList(items, parent, opts = {}) { if (opts.separator == null) { opts.separator = commaSeparator; } return this.printJoin(items, parent, opts); } _printNewline(leading, node, parent, opts) { // Fast path since 'this.newline' does nothing when not tracking lines. if (this.format.retainLines || this.format.compact) return; // Fast path for concise since 'this.newline' just inserts a space when // concise formatting is in use. if (this.format.concise) { this.space(); return; } let lines = 0; // don't add newlines at the beginning of the file if (this._buf.hasContent()) { if (!leading) lines++; // always include at least a single line after if (opts.addNewlines) lines += opts.addNewlines(leading, node) || 0; const needs = leading ? n.needsWhitespaceBefore : n.needsWhitespaceAfter; if (needs(node, parent)) lines++; } this.newline(lines); } _getComments(leading, node) { // Note, we use a boolean flag here instead of passing in the attribute name as it is faster // because this is called extremely frequently. return ( (node && (leading ? node.leadingComments : node.trailingComments)) || [] ); } _printComment(comment) { if (!this.format.shouldPrintComment(comment.value)) return; // Some plugins use this to mark comments as removed using the AST-root 'comments' property, // where they can't manually mutate the AST node comment lists. if (comment.ignore) return; if (this._printedComments.has(comment)) return; this._printedComments.add(comment); if (comment.start != null) { if (this._printedCommentStarts[comment.start]) return; this._printedCommentStarts[comment.start] = true; } const isBlockComment = comment.type === "CommentBlock"; // Always add a newline before a block comment this.newline( this._buf.hasContent() && !this._noLineTerminator && isBlockComment ? 1 : 0, ); if (!this.endsWith("[") && !this.endsWith("{")) this.space(); let val = !isBlockComment && !this._noLineTerminator ? `//${comment.value}\n` : `/*${comment.value}*/`; if (isBlockComment && this.format.indent.adjustMultilineComment) { const offset = comment.loc && comment.loc.start.column; if (offset) { const newlineRegex = new RegExp("\\n\\s{1," + offset + "}", "g"); val = val.replace(newlineRegex, "\n"); } const indentSize = Math.max( this._getIndent().length, this._buf.getCurrentColumn(), ); val = val.replace(/\n(?!$)/g, `\n${repeat(" ", indentSize)}`); } // Avoid creating //* comments if (this.endsWith("/")) this._space(); this.withSource("start", comment.loc, () => { this._append(val); }); // Always add a newline after a block comment this.newline(isBlockComment && !this._noLineTerminator ? 1 : 0); } _printComments(comments?: Array<Object>) { if (!comments || !comments.length) return; for (const comment of comments) { this._printComment(comment); } } } // Expose the node type functions and helpers on the prototype for easy usage. Object.assign(Printer.prototype, generatorFunctions); function commaSeparator() { this.token(","); this.space(); }
packages/babel-generator/src/printer.js
1
https://github.com/babel/babel/commit/ca117e08cb20d3e110757d5060e8d1661eca78eb
[ 0.0006208287086337805, 0.00019188292208127677, 0.00016221277473960072, 0.00016898487228900194, 0.00006778095848858356 ]
{ "id": 4, "code_window": [ " if (\n", " this.parentPath.isExpressionStatement() ||\n", " this.parentPath.isLabeledStatement()\n", " ) {\n", " // `replaceWithMultiple` requeues if there's a replacement for this.node,\n", " // but not for an ancestor's. Set `shouldRequeue` to true so that any replacement\n", " // for an ancestor node can be enqueued. Fix #5628 and #5023.\n", " return this.parentPath._insertAfter(nodes, true);\n", " } else if (\n", " this.isNodeType(\"Expression\") ||\n", " (this.parentPath.isForStatement() && this.key === \"init\")\n", " ) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " return this.parentPath.insertAfter(nodes);\n" ], "file_path": "packages/babel-traverse/src/path/modification.js", "type": "replace", "edit_start_line_idx": 118 }
var obj = { ["x" + foo]: "heh" };
packages/babel-plugin-transform-es2015-computed-properties/test/fixtures/spec/single/actual.js
0
https://github.com/babel/babel/commit/ca117e08cb20d3e110757d5060e8d1661eca78eb
[ 0.00016867848171386868, 0.00016867848171386868, 0.00016867848171386868, 0.00016867848171386868, 0 ]