hunk
dict
file
stringlengths
0
11.8M
file_path
stringlengths
2
234
label
int64
0
1
commit_url
stringlengths
74
103
dependency_score
listlengths
5
5
{ "id": 4, "code_window": [ " this.linenums = element.getAttribute('linenums');\n", " this.path = element.getAttribute('path') || '';\n", " this.region = element.getAttribute('region') || '';\n", " this.title = element.getAttribute('title') || '';\n", " }\n", "\n", " ngOnInit() {\n", " // The `codeExampleContent` property is set by the DocViewer when it builds this component.\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " this.hideCopy = element.getAttribute('hideCopy') === 'true';\n" ], "file_path": "aio/src/app/embedded/code/code-example.component.ts", "type": "add", "edit_start_line_idx": 39 }
<!doctype html> <html> <title>WebWorker Input Tests</title> <style> </style> <body> <input-app> Loading... </input-app> <script src="../../bootstrap.js"></script> </body> </html>
modules/playground/src/web_workers/input/index.html
0
https://github.com/angular/angular/commit/a0b9c231008825adef6155ab39c3cc5a98c1f478
[ 0.00017339643090963364, 0.00017230771481990814, 0.00017121901328209788, 0.00017230771481990814, 0.0000010887088137678802 ]
{ "id": 4, "code_window": [ " this.linenums = element.getAttribute('linenums');\n", " this.path = element.getAttribute('path') || '';\n", " this.region = element.getAttribute('region') || '';\n", " this.title = element.getAttribute('title') || '';\n", " }\n", "\n", " ngOnInit() {\n", " // The `codeExampleContent` property is set by the DocViewer when it builds this component.\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " this.hideCopy = element.getAttribute('hideCopy') === 'true';\n" ], "file_path": "aio/src/app/embedded/code/code-example.component.ts", "type": "add", "edit_start_line_idx": 39 }
{ "additionalFeatures": "", "android": { "os": "Android 2.2", "ui": "MOTOBLUR" }, "availability": [ "AT&T" ], "battery": { "standbyTime": "400 hours", "talkTime": "5 hours", "type": "Lithium Ion (Li-Ion) (1930 mAH)" }, "camera": { "features": [ "" ], "primary": "" }, "connectivity": { "bluetooth": "Bluetooth 2.1", "cell": "WCDMA 850/1900/2100, GSM 850/900/1800/1900, HSDPA 14Mbps (Category 10) Edge Class 12, GPRS Class 12, eCompass, AGPS", "gps": true, "infrared": false, "wifi": "802.11 a/b/g/n" }, "description": "MOTOROLA ATRIX 4G gives you dual-core processing power and the revolutionary webtop application. With webtop and a compatible Motorola docking station, sold separately, you can surf the Internet with a full Firefox browser, create and edit docs, or access multimedia on a large screen almost anywhere.", "display": { "screenResolution": "QHD (960 x 540)", "screenSize": "4.0 inches", "touchScreen": true }, "hardware": { "accelerometer": true, "audioJack": "3.5mm", "cpu": "1 GHz Dual Core", "fmRadio": false, "physicalKeyboard": false, "usb": "USB 2.0" }, "id": "motorola-atrix-4g", "images": [ "img/phones/motorola-atrix-4g.0.jpg", "img/phones/motorola-atrix-4g.1.jpg", "img/phones/motorola-atrix-4g.2.jpg", "img/phones/motorola-atrix-4g.3.jpg" ], "name": "MOTOROLA ATRIX\u2122 4G", "sizeAndWeight": { "dimensions": [ "63.5 mm (w)", "117.75 mm (h)", "10.95 mm (d)" ], "weight": "135.0 grams" }, "storage": { "flash": "", "ram": "" } }
aio/content/examples/upgrade-phonecat-4-final/app/phones/motorola-atrix-4g.json
0
https://github.com/angular/angular/commit/a0b9c231008825adef6155ab39c3cc5a98c1f478
[ 0.00017689385276753455, 0.00017428770661354065, 0.00017054853378795087, 0.00017420033691450953, 0.0000021423024918476585 ]
{ "id": 5, "code_window": [ " expect(getErrorMessage()).toMatch(/missing.$/);\n", " });\n", " });\n", "\n", " describe('copy button', () => {\n", " it('should call copier service when clicked', () => {\n", " const copierService: CopierService = TestBed.get(CopierService);\n", " const spy = spyOn(copierService, 'copyText');\n", " const button = fixture.debugElement.query(By.css('button')).nativeElement as HTMLButtonElement;\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n", " it('should be hidden if the `hideCopy` input is true', () => {\n", " hostComponent.hideCopy = true;\n", " fixture.detectChanges();\n", " expect(fixture.debugElement.query(By.css('button'))).toBe(null);\n", " });\n", "\n" ], "file_path": "aio/src/app/embedded/code/code.component.spec.ts", "type": "add", "edit_start_line_idx": 181 }
import { Component, ElementRef, ViewChild, OnChanges, OnDestroy, Input } from '@angular/core'; import { Logger } from 'app/shared/logger.service'; import { PrettyPrinter } from './pretty-printer.service'; import { CopierService } from 'app/shared/copier.service'; import { MdSnackBar } from '@angular/material'; const originalLabel = 'Copy Code'; const copiedLabel = 'Copied!'; const defaultLineNumsCount = 10; // by default, show linenums over this number /** * Formatted Code Block * * Pretty renders a code block, used in the docs and API reference by the code-example and * code-tabs embedded components. * It includes a "copy" button that will send the content to the clipboard when clicked * * Example usage: * * ``` * <aio-code * [code]="variableContainingCode" * [language]="ts" * [linenums]="true" * [path]="ts-to-js/ts/src/app/app.module.ts" * [region]="ng2import"> * </aio-code> * ``` */ @Component({ selector: 'aio-code', template: ` <pre class="prettyprint lang-{{language}}"> <button *ngIf="code" class="material-icons copy-button" (click)="doCopy()">content_copy</button> <code class="animated fadeIn" #codeContainer></code> </pre> ` }) export class CodeComponent implements OnChanges { /** * The code to be formatted, this should already be HTML encoded */ @Input() code: string; /** * The language of the code to render * (could be javascript, dart, typescript, etc) */ @Input() language: string; /** * Whether to display line numbers: * - false: don't display * - true: do display * - number: do display but start at the given number */ @Input() linenums: boolean | number | string; /** * path to the source of the code being displayed */ @Input() path: string; /** * region of the source of the code being displayed */ @Input() region: string; /** * The element in the template that will display the formatted code */ @ViewChild('codeContainer') codeContainer: ElementRef; constructor( private snackbar: MdSnackBar, private pretty: PrettyPrinter, private copier: CopierService, private logger: Logger) {} ngOnChanges() { this.code = this.code && leftAlign(this.code); if (!this.code) { const src = this.path ? this.path + (this.region ? '#' + this.region : '') : ''; const srcMsg = src ? ` for<br>${src}` : '.'; this.setCodeHtml(`<p class="code-missing">The code sample is missing${srcMsg}</p>`); return; } const linenums = this.getLinenums(); this.setCodeHtml(this.code); // start with unformatted code this.pretty.formatCode(this.code, this.language, linenums).subscribe( formattedCode => this.setCodeHtml(formattedCode), err => { /* ignore failure to format */ } ); } private setCodeHtml(formattedCode: string) { // **Security:** `codeExampleContent` is provided by docs authors and as such its considered to // be safe for innerHTML purposes. this.codeContainer.nativeElement.innerHTML = formattedCode; } doCopy() { // We take the innerText because we don't want it to be HTML encoded const code = this.codeContainer.nativeElement.innerText; if (this.copier.copyText(code)) { this.logger.log('Copied code to clipboard:', code); // success snackbar alert this.snackbar.open('Code Copied', '', { duration: 800, }); } else { this.logger.error('ERROR copying code to clipboard:', code); // failure snackbar alert this.snackbar.open('Copy failed. Please try again!', '', { duration: 800, }); } } getLinenums() { const linenums = typeof this.linenums === 'boolean' ? this.linenums : this.linenums === 'true' ? true : this.linenums === 'false' ? false : typeof this.linenums === 'string' ? parseInt(this.linenums, 10) : this.linenums; // if no linenums, enable line numbers if more than one line return linenums == null || linenums === NaN ? (this.code.match(/\n/g) || []).length > defaultLineNumsCount : linenums; } } function leftAlign(text) { let indent = Number.MAX_VALUE; const lines = text.split('\n'); lines.forEach(line => { const lineIndent = line.search(/\S/); if (lineIndent !== -1) { indent = Math.min(lineIndent, indent); } }); return lines.map(line => line.substr(indent)).join('\n').trim(); }
aio/src/app/embedded/code/code.component.ts
1
https://github.com/angular/angular/commit/a0b9c231008825adef6155ab39c3cc5a98c1f478
[ 0.6330799460411072, 0.03980632498860359, 0.00016141415107995272, 0.00017316013691015542, 0.15318284928798676 ]
{ "id": 5, "code_window": [ " expect(getErrorMessage()).toMatch(/missing.$/);\n", " });\n", " });\n", "\n", " describe('copy button', () => {\n", " it('should call copier service when clicked', () => {\n", " const copierService: CopierService = TestBed.get(CopierService);\n", " const spy = spyOn(copierService, 'copyText');\n", " const button = fixture.debugElement.query(By.css('button')).nativeElement as HTMLButtonElement;\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n", " it('should be hidden if the `hideCopy` input is true', () => {\n", " hostComponent.hideCopy = true;\n", " fixture.detectChanges();\n", " expect(fixture.debugElement.query(By.css('button'))).toBe(null);\n", " });\n", "\n" ], "file_path": "aio/src/app/embedded/code/code.component.spec.ts", "type": "add", "edit_start_line_idx": 181 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ importScripts( '../../../vendor/core.js', '../../../vendor/zone.js', '../../../vendor/long-stack-trace-zone.js', '../../../vendor/system.src.js', '../../../vendor/Reflect.js'); System.config({ baseURL: '/all', map: { 'rxjs': '/all/playground/vendor/rxjs', 'base64-js': '/all/playground/vendor/base64-js', }, packages: { '@angular/core': {main: 'index.js', defaultExtension: 'js'}, '@angular/compiler': {main: 'index.js', defaultExtension: 'js'}, '@angular/common': {main: 'index.js', defaultExtension: 'js'}, '@angular/platform-browser': {main: 'index.js', defaultExtension: 'js'}, '@angular/platform-browser-dynamic': {main: 'index.js', defaultExtension: 'js'}, '@angular/platform-webworker': {main: 'index.js', defaultExtension: 'js'}, '@angular/platform-webworker-dynamic': {main: 'index.js', defaultExtension: 'js'}, '@angular/router': {main: 'index.js', defaultExtension: 'js'}, 'rxjs': {defaultExtension: 'js'}, 'base64-js': {main: 'index.js', defaultExtension: 'js'}, }, defaultJSExtensions: true }); System.import('playground/src/web_workers/images/background_index') .then( function(m) { try { m.main(); } catch (e) { console.error(e); } }, function(error) { console.error('error loading background', error); });
modules/playground/src/web_workers/images/loader.js
0
https://github.com/angular/angular/commit/a0b9c231008825adef6155ab39c3cc5a98c1f478
[ 0.0001773040130501613, 0.00017394727910868824, 0.00016992099699564278, 0.00017386596300639212, 0.000002473268068570178 ]
{ "id": 5, "code_window": [ " expect(getErrorMessage()).toMatch(/missing.$/);\n", " });\n", " });\n", "\n", " describe('copy button', () => {\n", " it('should call copier service when clicked', () => {\n", " const copierService: CopierService = TestBed.get(CopierService);\n", " const spy = spyOn(copierService, 'copyText');\n", " const button = fixture.debugElement.query(By.css('button')).nativeElement as HTMLButtonElement;\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n", " it('should be hidden if the `hideCopy` input is true', () => {\n", " hostComponent.hideCopy = true;\n", " fixture.detectChanges();\n", " expect(fixture.debugElement.query(By.css('button'))).toBe(null);\n", " });\n", "\n" ], "file_path": "aio/src/app/embedded/code/code.component.spec.ts", "type": "add", "edit_start_line_idx": 181 }
<!-- #docplaster--> <!-- #docregion --> <h2>{{title}}</h2> <p> <!-- #docregion template-1 --> New hero: <input type="text" #box (keyup.enter)="addHero(box.value); box.value=''" placeholder="hero name"> <!-- #enddocregion template-1 --> <input id="can-fly" type="checkbox" [(ngModel)]="canFly"> can fly </p> <p> <input id="mutate" type="checkbox" [(ngModel)]="mutate">Mutate array <!-- #docregion template-1 --> <button (click)="reset()">Reset</button> <!-- #enddocregion template-1 --> </p> <h4>Heroes who fly (piped)</h4> <div id="flyers"> <!-- #docregion template-flying-heroes --> <div *ngFor="let hero of (heroes | flyingHeroes)"> {{hero.name}} </div> <!-- #enddocregion template-flying-heroes --> </div> <h4>All Heroes (no pipe)</h4> <div id="all"> <!-- #docregion template-1 --> <!-- #docregion template-all-heroes --> <div *ngFor="let hero of heroes"> {{hero.name}} </div> <!-- #enddocregion template-all-heroes --> <!-- #enddocregion template-1 --> </div>
aio/content/examples/pipes/src/app/flying-heroes.component.html
0
https://github.com/angular/angular/commit/a0b9c231008825adef6155ab39c3cc5a98c1f478
[ 0.00017749769904185086, 0.00017458590446040034, 0.00017177549307234585, 0.0001745352055877447, 0.000002084354264297872 ]
{ "id": 5, "code_window": [ " expect(getErrorMessage()).toMatch(/missing.$/);\n", " });\n", " });\n", "\n", " describe('copy button', () => {\n", " it('should call copier service when clicked', () => {\n", " const copierService: CopierService = TestBed.get(CopierService);\n", " const spy = spyOn(copierService, 'copyText');\n", " const button = fixture.debugElement.query(By.css('button')).nativeElement as HTMLButtonElement;\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n", " it('should be hidden if the `hideCopy` input is true', () => {\n", " hostComponent.hideCopy = true;\n", " fixture.detectChanges();\n", " expect(fixture.debugElement.query(By.css('button'))).toBe(null);\n", " });\n", "\n" ], "file_path": "aio/src/app/embedded/code/code.component.spec.ts", "type": "add", "edit_start_line_idx": 181 }
import { Component, OnInit } from '@angular/core'; import { Hero, HeroService } from './heroes'; import { ExceptionService, SpinnerService, ToastService } from './core'; @Component({ selector: 'sg-app', templateUrl: './app.component.html', providers: [HeroService, ExceptionService, SpinnerService, ToastService] }) export class AppComponent implements OnInit { favorite: Hero; heroes: Hero[]; constructor(private heroService: HeroService) { } ngOnInit() { this.heroService.getHero(1).subscribe(hero => this.favorite = hero); this.heroService.getHeroes().subscribe(heroes => this.heroes = heroes); } }
aio/content/examples/styleguide/src/03-06/app/app.component.ts
0
https://github.com/angular/angular/commit/a0b9c231008825adef6155ab39c3cc5a98c1f478
[ 0.00017616970581002533, 0.0001734603865770623, 0.00017087635933421552, 0.0001733351091388613, 0.0000021628147806040943 ]
{ "id": 6, "code_window": [ "@Component({\n", " selector: 'aio-host-comp',\n", " template: `\n", " <aio-code md-no-ink [code]=\"code\" [language]=\"language\"\n", " [linenums]=\"linenums\" [path]=\"path\" [region]=\"region\"></aio-code>\n", " `\n", "})\n", "class HostComponent {\n", " code = oneLineCode;\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " [linenums]=\"linenums\" [path]=\"path\" [region]=\"region\" [hideCopy]=\"hideCopy\"></aio-code>\n" ], "file_path": "aio/src/app/embedded/code/code.component.spec.ts", "type": "replace", "edit_start_line_idx": 226 }
/* tslint:disable component-selector */ import { Component, ElementRef, OnInit } from '@angular/core'; /** * An embeddable code block that displays nicely formatted code. * Example usage: * * ``` * <code-example language="ts" linenums="2" class="special" title="Do Stuff"> * // a code block * console.log('do stuff'); * </code-example> * ``` */ @Component({ selector: 'code-example', template: ` <header *ngIf="title">{{title}}</header> <aio-code [ngClass]="{'headed-code':title, 'simple-code':!title}" [code]="code" [language]="language" [linenums]="linenums" [path]="path" [region]="region"></aio-code> ` }) export class CodeExampleComponent implements OnInit { code: string; language: string; linenums: boolean | number; path: string; region: string; title: string; constructor(private elementRef: ElementRef) { const element = this.elementRef.nativeElement; this.language = element.getAttribute('language') || ''; this.linenums = element.getAttribute('linenums'); this.path = element.getAttribute('path') || ''; this.region = element.getAttribute('region') || ''; this.title = element.getAttribute('title') || ''; } ngOnInit() { // The `codeExampleContent` property is set by the DocViewer when it builds this component. // It is the original innerHTML of the host element. this.code = this.elementRef.nativeElement.codeExampleContent; } }
aio/src/app/embedded/code/code-example.component.ts
1
https://github.com/angular/angular/commit/a0b9c231008825adef6155ab39c3cc5a98c1f478
[ 0.008202211000025272, 0.002522860886529088, 0.00016448396490886807, 0.0014645946212112904, 0.002965517109259963 ]
{ "id": 6, "code_window": [ "@Component({\n", " selector: 'aio-host-comp',\n", " template: `\n", " <aio-code md-no-ink [code]=\"code\" [language]=\"language\"\n", " [linenums]=\"linenums\" [path]=\"path\" [region]=\"region\"></aio-code>\n", " `\n", "})\n", "class HostComponent {\n", " code = oneLineCode;\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " [linenums]=\"linenums\" [path]=\"path\" [region]=\"region\" [hideCopy]=\"hideCopy\"></aio-code>\n" ], "file_path": "aio/src/app/embedded/code/code.component.spec.ts", "type": "replace", "edit_start_line_idx": 226 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {APP_BASE_HREF, HashLocationStrategy, LOCATION_INITIALIZED, Location, LocationStrategy, PathLocationStrategy, PlatformLocation} from '@angular/common'; import {ANALYZE_FOR_ENTRY_COMPONENTS, APP_BOOTSTRAP_LISTENER, APP_INITIALIZER, ApplicationRef, Compiler, ComponentRef, Inject, Injectable, InjectionToken, Injector, ModuleWithProviders, NgModule, NgModuleFactoryLoader, NgProbeToken, Optional, Provider, SkipSelf, SystemJsNgModuleLoader} from '@angular/core'; import {ɵgetDOM as getDOM} from '@angular/platform-browser'; import {Subject} from 'rxjs/Subject'; import {of } from 'rxjs/observable/of'; import {Route, Routes} from './config'; import {RouterLink, RouterLinkWithHref} from './directives/router_link'; import {RouterLinkActive} from './directives/router_link_active'; import {RouterOutlet} from './directives/router_outlet'; import {RouteReuseStrategy} from './route_reuse_strategy'; import {ErrorHandler, Router} from './router'; import {ROUTES} from './router_config_loader'; import {RouterOutletMap} from './router_outlet_map'; import {NoPreloading, PreloadAllModules, PreloadingStrategy, RouterPreloader} from './router_preloader'; import {ActivatedRoute} from './router_state'; import {UrlHandlingStrategy} from './url_handling_strategy'; import {DefaultUrlSerializer, UrlSerializer} from './url_tree'; import {flatten} from './utils/collection'; /** * @whatItDoes Contains a list of directives * @stable */ const ROUTER_DIRECTIVES = [RouterOutlet, RouterLink, RouterLinkWithHref, RouterLinkActive]; /** * @whatItDoes Is used in DI to configure the router. * @stable */ export const ROUTER_CONFIGURATION = new InjectionToken<ExtraOptions>('ROUTER_CONFIGURATION'); /** * @docsNotRequired */ export const ROUTER_FORROOT_GUARD = new InjectionToken<void>('ROUTER_FORROOT_GUARD'); export const ROUTER_PROVIDERS: Provider[] = [ Location, {provide: UrlSerializer, useClass: DefaultUrlSerializer}, { provide: Router, useFactory: setupRouter, deps: [ ApplicationRef, UrlSerializer, RouterOutletMap, Location, Injector, NgModuleFactoryLoader, Compiler, ROUTES, ROUTER_CONFIGURATION, [UrlHandlingStrategy, new Optional()], [RouteReuseStrategy, new Optional()] ] }, RouterOutletMap, {provide: ActivatedRoute, useFactory: rootRoute, deps: [Router]}, {provide: NgModuleFactoryLoader, useClass: SystemJsNgModuleLoader}, RouterPreloader, NoPreloading, PreloadAllModules, {provide: ROUTER_CONFIGURATION, useValue: {enableTracing: false}}, ]; export function routerNgProbeToken() { return new NgProbeToken('Router', Router); } /** * @whatItDoes Adds router directives and providers. * * @howToUse * * RouterModule can be imported multiple times: once per lazily-loaded bundle. * Since the router deals with a global shared resource--location, we cannot have * more than one router service active. * * That is why there are two ways to create the module: `RouterModule.forRoot` and * `RouterModule.forChild`. * * * `forRoot` creates a module that contains all the directives, the given routes, and the router * service itself. * * `forChild` creates a module that contains all the directives and the given routes, but does not * include the router service. * * When registered at the root, the module should be used as follows * * ``` * @NgModule({ * imports: [RouterModule.forRoot(ROUTES)] * }) * class MyNgModule {} * ``` * * For submodules and lazy loaded submodules the module should be used as follows: * * ``` * @NgModule({ * imports: [RouterModule.forChild(ROUTES)] * }) * class MyNgModule {} * ``` * * @description * * Managing state transitions is one of the hardest parts of building applications. This is * especially true on the web, where you also need to ensure that the state is reflected in the URL. * In addition, we often want to split applications into multiple bundles and load them on demand. * Doing this transparently is not trivial. * * The Angular router solves these problems. Using the router, you can declaratively specify * application states, manage state transitions while taking care of the URL, and load bundles on * demand. * * [Read this developer guide](https://angular.io/docs/ts/latest/guide/router.html) to get an * overview of how the router should be used. * * @stable */ @NgModule({declarations: ROUTER_DIRECTIVES, exports: ROUTER_DIRECTIVES}) export class RouterModule { // Note: We are injecting the Router so it gets created eagerly... constructor(@Optional() @Inject(ROUTER_FORROOT_GUARD) guard: any, @Optional() router: Router) {} /** * Creates a module with all the router providers and directives. It also optionally sets up an * application listener to perform an initial navigation. * * Options: * * `enableTracing` makes the router log all its internal events to the console. * * `useHash` enables the location strategy that uses the URL fragment instead of the history * API. * * `initialNavigation` disables the initial navigation. * * `errorHandler` provides a custom error handler. */ static forRoot(routes: Routes, config?: ExtraOptions): ModuleWithProviders { return { ngModule: RouterModule, providers: [ ROUTER_PROVIDERS, provideRoutes(routes), { provide: ROUTER_FORROOT_GUARD, useFactory: provideForRootGuard, deps: [[Router, new Optional(), new SkipSelf()]] }, {provide: ROUTER_CONFIGURATION, useValue: config ? config : {}}, { provide: LocationStrategy, useFactory: provideLocationStrategy, deps: [ PlatformLocation, [new Inject(APP_BASE_HREF), new Optional()], ROUTER_CONFIGURATION ] }, { provide: PreloadingStrategy, useExisting: config && config.preloadingStrategy ? config.preloadingStrategy : NoPreloading }, {provide: NgProbeToken, multi: true, useFactory: routerNgProbeToken}, provideRouterInitializer(), ], }; } /** * Creates a module with all the router directives and a provider registering routes. */ static forChild(routes: Routes): ModuleWithProviders { return {ngModule: RouterModule, providers: [provideRoutes(routes)]}; } } export function provideLocationStrategy( platformLocationStrategy: PlatformLocation, baseHref: string, options: ExtraOptions = {}) { return options.useHash ? new HashLocationStrategy(platformLocationStrategy, baseHref) : new PathLocationStrategy(platformLocationStrategy, baseHref); } export function provideForRootGuard(router: Router): any { if (router) { throw new Error( `RouterModule.forRoot() called twice. Lazy loaded modules should use RouterModule.forChild() instead.`); } return 'guarded'; } /** * @whatItDoes Registers routes. * * @howToUse * * ``` * @NgModule({ * imports: [RouterModule.forChild(ROUTES)], * providers: [provideRoutes(EXTRA_ROUTES)] * }) * class MyNgModule {} * ``` * * @stable */ export function provideRoutes(routes: Routes): any { return [ {provide: ANALYZE_FOR_ENTRY_COMPONENTS, multi: true, useValue: routes}, {provide: ROUTES, multi: true, useValue: routes}, ]; } /** * @whatItDoes Represents an option to configure when the initial navigation is performed. * * @description * * 'enabled' - the initial navigation starts before the root component is created. * The bootstrap is blocked until the initial navigation is complete. * * 'disabled' - the initial navigation is not performed. The location listener is set up before * the root component gets created. * * 'legacy_enabled'- the initial navigation starts after the root component has been created. * The bootstrap is not blocked until the initial navigation is complete. @deprecated * * 'legacy_disabled'- the initial navigation is not performed. The location listener is set up * after @deprecated * the root component gets created. * * `true` - same as 'legacy_enabled'. @deprecated since v4 * * `false` - same as 'legacy_disabled'. @deprecated since v4 * * The 'enabled' option should be used for applications unless there is a reason to have * more control over when the router starts its initial navigation due to some complex * initialization logic. In this case, 'disabled' should be used. * * The 'legacy_enabled' and 'legacy_disabled' should not be used for new applications. * * @experimental */ export type InitialNavigation = true | false | 'enabled' | 'disabled' | 'legacy_enabled' | 'legacy_disabled'; /** * @whatItDoes Represents options to configure the router. * * @stable */ export interface ExtraOptions { /** * Makes the router log all its internal events to the console. */ enableTracing?: boolean; /** * Enables the location strategy that uses the URL fragment instead of the history API. */ useHash?: boolean; /** * Disables the initial navigation. */ initialNavigation?: InitialNavigation; /** * A custom error handler. */ errorHandler?: ErrorHandler; /** * Configures a preloading strategy. See {@link PreloadAllModules}. */ preloadingStrategy?: any; } export function setupRouter( ref: ApplicationRef, urlSerializer: UrlSerializer, outletMap: RouterOutletMap, location: Location, injector: Injector, loader: NgModuleFactoryLoader, compiler: Compiler, config: Route[][], opts: ExtraOptions = {}, urlHandlingStrategy?: UrlHandlingStrategy, routeReuseStrategy?: RouteReuseStrategy) { const router = new Router( null, urlSerializer, outletMap, location, injector, loader, compiler, flatten(config)); if (urlHandlingStrategy) { router.urlHandlingStrategy = urlHandlingStrategy; } if (routeReuseStrategy) { router.routeReuseStrategy = routeReuseStrategy; } if (opts.errorHandler) { router.errorHandler = opts.errorHandler; } if (opts.enableTracing) { const dom = getDOM(); router.events.subscribe(e => { dom.logGroup(`Router Event: ${(<any>e.constructor).name}`); dom.log(e.toString()); dom.log(e); dom.logGroupEnd(); }); } return router; } export function rootRoute(router: Router): ActivatedRoute { return router.routerState.root; } /** * To initialize the router properly we need to do in two steps: * * We need to start the navigation in a APP_INITIALIZER to block the bootstrap if * a resolver or a guards executes asynchronously. Second, we need to actually run * activation in a BOOTSTRAP_LISTENER. We utilize the afterPreactivation * hook provided by the router to do that. * * The router navigation starts, reaches the point when preactivation is done, and then * pauses. It waits for the hook to be resolved. We then resolve it only in a bootstrap listener. */ @Injectable() export class RouterInitializer { private initNavigation: boolean = false; private resultOfPreactivationDone = new Subject<void>(); constructor(private injector: Injector) {} appInitializer(): Promise<any> { const p: Promise<any> = this.injector.get(LOCATION_INITIALIZED, Promise.resolve(null)); return p.then(() => { let resolve: Function = null !; const res = new Promise(r => resolve = r); const router = this.injector.get(Router); const opts = this.injector.get(ROUTER_CONFIGURATION); if (this.isLegacyDisabled(opts) || this.isLegacyEnabled(opts)) { resolve(true); } else if (opts.initialNavigation === 'disabled') { router.setUpLocationChangeListener(); resolve(true); } else if (opts.initialNavigation === 'enabled') { router.hooks.afterPreactivation = () => { // only the initial navigation should be delayed if (!this.initNavigation) { this.initNavigation = true; resolve(true); return this.resultOfPreactivationDone; // subsequent navigations should not be delayed } else { return of (null) as any; } }; router.initialNavigation(); } else { throw new Error(`Invalid initialNavigation options: '${opts.initialNavigation}'`); } return res; }); } bootstrapListener(bootstrappedComponentRef: ComponentRef<any>): void { const opts = this.injector.get(ROUTER_CONFIGURATION); const preloader = this.injector.get(RouterPreloader); const router = this.injector.get(Router); const ref = this.injector.get(ApplicationRef); if (bootstrappedComponentRef !== ref.components[0]) { return; } if (this.isLegacyEnabled(opts)) { router.initialNavigation(); } else if (this.isLegacyDisabled(opts)) { router.setUpLocationChangeListener(); } preloader.setUpPreloading(); router.resetRootComponentType(ref.componentTypes[0]); this.resultOfPreactivationDone.next(null !); this.resultOfPreactivationDone.complete(); } private isLegacyEnabled(opts: ExtraOptions): boolean { return opts.initialNavigation === 'legacy_enabled' || opts.initialNavigation === true || opts.initialNavigation === undefined; } private isLegacyDisabled(opts: ExtraOptions): boolean { return opts.initialNavigation === 'legacy_disabled' || opts.initialNavigation === false; } } export function getAppInitializer(r: RouterInitializer) { return r.appInitializer.bind(r); } export function getBootstrapListener(r: RouterInitializer) { return r.bootstrapListener.bind(r); } /** * A token for the router initializer that will be called after the app is bootstrapped. * * @experimental */ export const ROUTER_INITIALIZER = new InjectionToken<(compRef: ComponentRef<any>) => void>('Router Initializer'); export function provideRouterInitializer() { return [ RouterInitializer, { provide: APP_INITIALIZER, multi: true, useFactory: getAppInitializer, deps: [RouterInitializer] }, {provide: ROUTER_INITIALIZER, useFactory: getBootstrapListener, deps: [RouterInitializer]}, {provide: APP_BOOTSTRAP_LISTENER, multi: true, useExisting: ROUTER_INITIALIZER}, ]; }
packages/router/src/router_module.ts
0
https://github.com/angular/angular/commit/a0b9c231008825adef6155ab39c3cc5a98c1f478
[ 0.0003008138737641275, 0.00017426199337933213, 0.00016165644046850502, 0.00016878658789210021, 0.00002792715713439975 ]
{ "id": 6, "code_window": [ "@Component({\n", " selector: 'aio-host-comp',\n", " template: `\n", " <aio-code md-no-ink [code]=\"code\" [language]=\"language\"\n", " [linenums]=\"linenums\" [path]=\"path\" [region]=\"region\"></aio-code>\n", " `\n", "})\n", "class HostComponent {\n", " code = oneLineCode;\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " [linenums]=\"linenums\" [path]=\"path\" [region]=\"region\" [hideCopy]=\"hideCopy\"></aio-code>\n" ], "file_path": "aio/src/app/embedded/code/code.component.spec.ts", "type": "replace", "edit_start_line_idx": 226 }
// #docregion , init import { InMemoryDbService } from 'angular-in-memory-web-api'; export class InMemoryDataService implements InMemoryDbService { createDb() { let heroes = [ {id: 11, name: 'Mr. Nice'}, {id: 12, name: 'Narco'}, {id: 13, name: 'Bombasto'}, {id: 14, name: 'Celeritas'}, {id: 15, name: 'Magneta'}, {id: 16, name: 'RubberMan'}, {id: 17, name: 'Dynama'}, {id: 18, name: 'Dr IQ'}, {id: 19, name: 'Magma'}, {id: 20, name: 'Tornado'} ]; return {heroes}; } }
aio/content/examples/universal/src/app/in-memory-data.service.ts
0
https://github.com/angular/angular/commit/a0b9c231008825adef6155ab39c3cc5a98c1f478
[ 0.0001755397388478741, 0.00017117708921432495, 0.00016681445413269103, 0.00017117708921432495, 0.00000436264235759154 ]
{ "id": 6, "code_window": [ "@Component({\n", " selector: 'aio-host-comp',\n", " template: `\n", " <aio-code md-no-ink [code]=\"code\" [language]=\"language\"\n", " [linenums]=\"linenums\" [path]=\"path\" [region]=\"region\"></aio-code>\n", " `\n", "})\n", "class HostComponent {\n", " code = oneLineCode;\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " [linenums]=\"linenums\" [path]=\"path\" [region]=\"region\" [hideCopy]=\"hideCopy\"></aio-code>\n" ], "file_path": "aio/src/app/embedded/code/code.component.spec.ts", "type": "replace", "edit_start_line_idx": 226 }
<!doctype html> <html> <head> <meta charset="utf-8"> <title>Hello World</title> <base href="/"> </head> <body> <hello-world-app>Loading...</hello-world-app> <script src="dist/bundle.js"></script> </body> </html>
integration/hello_world__closure/src/index.html
0
https://github.com/angular/angular/commit/a0b9c231008825adef6155ab39c3cc5a98c1f478
[ 0.0001727052149362862, 0.00017154925444629043, 0.00017039329395629466, 0.00017154925444629043, 0.0000011559604899957776 ]
{ "id": 7, "code_window": [ " linenums: boolean | number | string;\n", " path: string;\n", " region: string;\n", "}\n", "\n", "class TestLogger {\n", " log = jasmine.createSpy('log');\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " hideCopy: boolean;\n" ], "file_path": "aio/src/app/embedded/code/code.component.spec.ts", "type": "add", "edit_start_line_idx": 235 }
/* tslint:disable component-selector */ import { Component, ElementRef, OnInit } from '@angular/core'; /** * An embeddable code block that displays nicely formatted code. * Example usage: * * ``` * <code-example language="ts" linenums="2" class="special" title="Do Stuff"> * // a code block * console.log('do stuff'); * </code-example> * ``` */ @Component({ selector: 'code-example', template: ` <header *ngIf="title">{{title}}</header> <aio-code [ngClass]="{'headed-code':title, 'simple-code':!title}" [code]="code" [language]="language" [linenums]="linenums" [path]="path" [region]="region"></aio-code> ` }) export class CodeExampleComponent implements OnInit { code: string; language: string; linenums: boolean | number; path: string; region: string; title: string; constructor(private elementRef: ElementRef) { const element = this.elementRef.nativeElement; this.language = element.getAttribute('language') || ''; this.linenums = element.getAttribute('linenums'); this.path = element.getAttribute('path') || ''; this.region = element.getAttribute('region') || ''; this.title = element.getAttribute('title') || ''; } ngOnInit() { // The `codeExampleContent` property is set by the DocViewer when it builds this component. // It is the original innerHTML of the host element. this.code = this.elementRef.nativeElement.codeExampleContent; } }
aio/src/app/embedded/code/code-example.component.ts
1
https://github.com/angular/angular/commit/a0b9c231008825adef6155ab39c3cc5a98c1f478
[ 0.38245177268981934, 0.0776553675532341, 0.00016508542466908693, 0.0022154345642775297, 0.15240292251110077 ]
{ "id": 7, "code_window": [ " linenums: boolean | number | string;\n", " path: string;\n", " region: string;\n", "}\n", "\n", "class TestLogger {\n", " log = jasmine.createSpy('log');\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " hideCopy: boolean;\n" ], "file_path": "aio/src/app/embedded/code/code.component.spec.ts", "type": "add", "edit_start_line_idx": 235 }
/* tslint:disable:no-unused-variable member-ordering */ // #docplaster // #docregion import { Directive, ElementRef, HostListener, Input } from '@angular/core'; @Directive({ selector: '[myHighlight]' }) export class HighlightDirective { // #docregion ctor constructor(private el: ElementRef) { } // #enddocregion ctor // #docregion mouse-methods, host @HostListener('mouseenter') onMouseEnter() { // #enddocregion host this.highlight('yellow'); // #docregion host } @HostListener('mouseleave') onMouseLeave() { // #enddocregion host this.highlight(null); // #docregion host } // #enddocregion host private highlight(color: string) { this.el.nativeElement.style.backgroundColor = color; } // #enddocregion mouse-methods, // #docregion color @Input() highlightColor: string; // #enddocregion color // #docregion color-2 @Input() myHighlight: string; // #enddocregion color-2 }
aio/content/examples/attribute-directives/src/app/highlight.directive.2.ts
0
https://github.com/angular/angular/commit/a0b9c231008825adef6155ab39c3cc5a98c1f478
[ 0.0007994065526872873, 0.0003657463821582496, 0.00017555331578478217, 0.0003027187194675207, 0.00022971055295784026 ]
{ "id": 7, "code_window": [ " linenums: boolean | number | string;\n", " path: string;\n", " region: string;\n", "}\n", "\n", "class TestLogger {\n", " log = jasmine.createSpy('log');\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " hideCopy: boolean;\n" ], "file_path": "aio/src/app/embedded/code/code.component.spec.ts", "type": "add", "edit_start_line_idx": 235 }
// Imports import {runTests} from '../common/run-tests'; // Run const specFiles = [`${__dirname}/**/*.e2e.js`]; runTests(specFiles);
aio/aio-builds-setup/dockerbuild/scripts-js/lib/verify-setup/index.ts
0
https://github.com/angular/angular/commit/a0b9c231008825adef6155ab39c3cc5a98c1f478
[ 0.00017384822422172874, 0.00017384822422172874, 0.00017384822422172874, 0.00017384822422172874, 0 ]
{ "id": 7, "code_window": [ " linenums: boolean | number | string;\n", " path: string;\n", " region: string;\n", "}\n", "\n", "class TestLogger {\n", " log = jasmine.createSpy('log');\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " hideCopy: boolean;\n" ], "file_path": "aio/src/app/embedded/code/code.component.spec.ts", "type": "add", "edit_start_line_idx": 235 }
import { Component, Input } from '@angular/core'; import { NavigationNode, VersionInfo } from 'app/navigation/navigation.service'; @Component({ selector: 'aio-footer', templateUrl: 'footer.component.html' }) export class FooterComponent { @Input() nodes: NavigationNode[]; @Input() versionInfo: VersionInfo; }
aio/src/app/layout/footer/footer.component.ts
0
https://github.com/angular/angular/commit/a0b9c231008825adef6155ab39c3cc5a98c1f478
[ 0.00017386146646458656, 0.00017307652160525322, 0.00017229156219400465, 0.00017307652160525322, 7.849521352909505e-7 ]
{ "id": 8, "code_window": [ " */\n", "@Component({\n", " selector: 'aio-code',\n", " template: `\n", " <pre class=\"prettyprint lang-{{language}}\">\n", " <button *ngIf=\"code\" class=\"material-icons copy-button\" (click)=\"doCopy()\">content_copy</button>\n", " <code class=\"animated fadeIn\" #codeContainer></code>\n", " </pre>\n", " `\n", "})\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " <button *ngIf=\"!hideCopy\" class=\"material-icons copy-button\" (click)=\"doCopy()\">content_copy</button>\n" ], "file_path": "aio/src/app/embedded/code/code.component.ts", "type": "replace", "edit_start_line_idx": 33 }
/* tslint:disable:no-unused-variable */ import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { Component, DebugElement } from '@angular/core'; import { MdSnackBarModule, MdSnackBar } from '@angular/material'; import { NoopAnimationsModule } from '@angular/platform-browser/animations'; import { CodeComponent } from './code.component'; import { CopierService } from 'app/shared//copier.service'; import { Logger } from 'app/shared/logger.service'; import { PrettyPrinter } from './pretty-printer.service'; const oneLineCode = 'const foo = "bar";'; const smallMultiLineCode = ` &lt;hero-details&gt; &lt;h2&gt;Bah Dah Bing&lt;/h2&gt; &lt;hero-team&gt; &lt;h3&gt;NYC Team&lt;/h3&gt; &lt;/hero-team&gt; &lt;/hero-details&gt;`; const bigMultiLineCode = smallMultiLineCode + smallMultiLineCode + smallMultiLineCode; describe('CodeComponent', () => { let codeComponentDe: DebugElement; let codeComponent: CodeComponent; let hostComponent: HostComponent; let fixture: ComponentFixture<HostComponent>; // WARNING: Chance of cross-test pollution // CodeComponent injects PrettyPrintService // Once PrettyPrintService runs once _anywhere_, its ctor loads `prettify.js` // which sets `window['prettyPrintOne']` // That global survives these tests unless // we take strict measures to wipe it out in the `afterAll` // and make sure THAT runs after the tests by making component creation async afterAll(() => { delete window['prettyPrint']; delete window['prettyPrintOne']; }); beforeEach(async(() => { TestBed.configureTestingModule({ imports: [ MdSnackBarModule, NoopAnimationsModule ], declarations: [ CodeComponent, HostComponent ], providers: [ PrettyPrinter, CopierService, {provide: Logger, useClass: TestLogger } ] }) .compileComponents(); })); // Must be async because // CodeComponent creates PrettyPrintService which async loads `prettify.js`. // If not async, `afterAll` finishes before tests do! beforeEach(async(() => { fixture = TestBed.createComponent(HostComponent); hostComponent = fixture.componentInstance; codeComponentDe = fixture.debugElement.children[0]; codeComponent = codeComponentDe.componentInstance; fixture.detectChanges(); })); it('should create CodeComponent', () => { expect(codeComponentDe.name).toBe('aio-code', 'selector'); expect(codeComponent).toBeTruthy('CodeComponent'); }); describe('pretty printing', () => { it('should format a one-line code sample', () => { // 'pln' spans are a tell-tale for syntax highlighing const spans = codeComponentDe.nativeElement.querySelectorAll('span.pln'); expect(spans.length).toBeGreaterThan(0, 'formatted spans'); }); function hasLineNumbers() { // presence of `<li>`s are a tell-tale for line numbers return 0 < codeComponentDe.nativeElement.querySelectorAll('li').length; } it('should format a one-line code sample without linenums by default', () => { expect(hasLineNumbers()).toBe(false); }); it('should add line numbers to one-line code sample when linenums set true', () => { hostComponent.linenums = 'true'; fixture.detectChanges(); expect(hasLineNumbers()).toBe(true); }); it('should format a small multi-line code without linenums by default', () => { hostComponent.code = smallMultiLineCode; fixture.detectChanges(); expect(hasLineNumbers()).toBe(false); }); it('should add line numbers to a big multi-line code by default', () => { hostComponent.code = bigMultiLineCode; fixture.detectChanges(); expect(hasLineNumbers()).toBe(true); }); it('should format big multi-line code without linenums when linenums set false', () => { hostComponent.linenums = false; hostComponent.code = bigMultiLineCode; fixture.detectChanges(); expect(hasLineNumbers()).toBe(false); }); }); describe('whitespace handling', () => { it('should remove common indentation from the code before rendering', () => { hostComponent.linenums = false; hostComponent.code = ' abc\n let x = text.split(\'\\n\');\n ghi\n\n jkl\n'; fixture.detectChanges(); const codeContent = codeComponentDe.nativeElement.querySelector('code').innerText; expect(codeContent).toEqual('abc\n let x = text.split(\'\\n\');\nghi\n\njkl'); }); it('should trim whitespace from the code before rendering', () => { hostComponent.linenums = false; hostComponent.code = '\n\n\n' + smallMultiLineCode + '\n\n\n'; fixture.detectChanges(); const codeContent = codeComponentDe.nativeElement.querySelector('code').innerText; expect(codeContent).toEqual(codeContent.trim()); }); it('should trim whitespace from code before computing whether to format linenums', () => { hostComponent.code = '\n\n\n' + hostComponent.code + '\n\n\n'; fixture.detectChanges(); // `<li>`s are a tell-tale for line numbers const lis = codeComponentDe.nativeElement.querySelectorAll('li'); expect(lis.length).toBe(0, 'should be no linenums'); }); }); describe('error message', () => { function getErrorMessage() { const missing: HTMLElement = codeComponentDe.nativeElement.querySelector('.code-missing'); return missing ? missing.innerText : null; } it('should not display "code-missing" class when there is some code', () => { fixture.detectChanges(); expect(getErrorMessage()).toBeNull('should not have element with "code-missing" class'); }); it('should display error message when there is no code (after trimming)', () => { hostComponent.code = ' \n '; fixture.detectChanges(); expect(getErrorMessage()).toContain('missing'); }); it('should show path and region in missing-code error message', () => { hostComponent.code = ' \n '; hostComponent.path = 'fizz/buzz/foo.html'; hostComponent.region = 'something'; fixture.detectChanges(); expect(getErrorMessage()).toMatch(/for[\s\S]fizz\/buzz\/foo\.html#something$/); }); it('should show path only in missing-code error message when no region', () => { hostComponent.code = ' \n '; hostComponent.path = 'fizz/buzz/foo.html'; fixture.detectChanges(); expect(getErrorMessage()).toMatch(/for[\s\S]fizz\/buzz\/foo\.html$/); }); it('should show simple missing-code error message when no path/region', () => { hostComponent.code = ' \n '; fixture.detectChanges(); expect(getErrorMessage()).toMatch(/missing.$/); }); }); describe('copy button', () => { it('should call copier service when clicked', () => { const copierService: CopierService = TestBed.get(CopierService); const spy = spyOn(copierService, 'copyText'); const button = fixture.debugElement.query(By.css('button')).nativeElement as HTMLButtonElement; expect(spy.calls.count()).toBe(0, 'before click'); button.click(); expect(spy.calls.count()).toBe(1, 'after click'); }); it('should copy code text when clicked', () => { const copierService: CopierService = TestBed.get(CopierService); const spy = spyOn(copierService, 'copyText'); const button = fixture.debugElement.query(By.css('button')).nativeElement as HTMLButtonElement; button.click(); expect(spy.calls.argsFor(0)[0]).toEqual(oneLineCode, 'after click'); }); it('should display a message when copy succeeds', () => { const snackBar: MdSnackBar = TestBed.get(MdSnackBar); const copierService: CopierService = TestBed.get(CopierService); spyOn(snackBar, 'open'); spyOn(copierService, 'copyText').and.returnValue(true); const button = fixture.debugElement.query(By.css('button')).nativeElement as HTMLButtonElement; button.click(); expect(snackBar.open).toHaveBeenCalledWith('Code Copied', '', { duration: 800 }); }); it('should display an error when copy fails', () => { const snackBar: MdSnackBar = TestBed.get(MdSnackBar); const copierService: CopierService = TestBed.get(CopierService); spyOn(snackBar, 'open'); spyOn(copierService, 'copyText').and.returnValue(false); const button = fixture.debugElement.query(By.css('button')).nativeElement as HTMLButtonElement; button.click(); expect(snackBar.open).toHaveBeenCalledWith('Copy failed. Please try again!', '', { duration: 800 }); }); }); }); //// Test helpers //// // tslint:disable:member-ordering @Component({ selector: 'aio-host-comp', template: ` <aio-code md-no-ink [code]="code" [language]="language" [linenums]="linenums" [path]="path" [region]="region"></aio-code> ` }) class HostComponent { code = oneLineCode; language: string; linenums: boolean | number | string; path: string; region: string; } class TestLogger { log = jasmine.createSpy('log'); error = jasmine.createSpy('error'); }
aio/src/app/embedded/code/code.component.spec.ts
1
https://github.com/angular/angular/commit/a0b9c231008825adef6155ab39c3cc5a98c1f478
[ 0.00025924743385985494, 0.00017341572674922645, 0.00016381374734919518, 0.00016887868696358055, 0.000018293421817361377 ]
{ "id": 8, "code_window": [ " */\n", "@Component({\n", " selector: 'aio-code',\n", " template: `\n", " <pre class=\"prettyprint lang-{{language}}\">\n", " <button *ngIf=\"code\" class=\"material-icons copy-button\" (click)=\"doCopy()\">content_copy</button>\n", " <code class=\"animated fadeIn\" #codeContainer></code>\n", " </pre>\n", " `\n", "})\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " <button *ngIf=\"!hideCopy\" class=\"material-icons copy-button\" (click)=\"doCopy()\">content_copy</button>\n" ], "file_path": "aio/src/app/embedded/code/code.component.ts", "type": "replace", "edit_start_line_idx": 33 }
import { NO_ERRORS_SCHEMA } from '@angular/core'; import { async, inject, ComponentFixture, TestBed } from '@angular/core/testing'; import { Title } from '@angular/platform-browser'; import { APP_BASE_HREF } from '@angular/common'; import { Http } from '@angular/http'; import { By } from '@angular/platform-browser'; import { BehaviorSubject} from 'rxjs/BehaviorSubject'; import { of } from 'rxjs/observable/of'; import { AppComponent } from './app.component'; import { AppModule } from './app.module'; import { AutoScrollService } from 'app/shared/auto-scroll.service'; import { DocViewerComponent } from 'app/layout/doc-viewer/doc-viewer.component'; import { GaService } from 'app/shared/ga.service'; import { LocationService } from 'app/shared/location.service'; import { Logger } from 'app/shared/logger.service'; import { MockLocationService } from 'testing/location.service'; import { MockLogger } from 'testing/logger.service'; import { MockSearchService } from 'testing/search.service'; import { MockSwUpdateNotificationsService } from 'testing/sw-update-notifications.service'; import { NavigationNode } from 'app/navigation/navigation.service'; import { SearchBoxComponent } from 'app/search/search-box/search-box.component'; import { SearchResultsComponent } from 'app/search/search-results/search-results.component'; import { SearchService } from 'app/search/search.service'; import { SwUpdateNotificationsService } from 'app/sw-updates/sw-update-notifications.service'; describe('AppComponent', () => { let component: AppComponent; let fixture: ComponentFixture<AppComponent>; let docViewer: HTMLElement; let hamburger: HTMLButtonElement; let locationService: MockLocationService; let sidenav: HTMLElement; beforeEach(async(() => { createTestingModule('a/b'); TestBed.compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(AppComponent); component = fixture.componentInstance; fixture.detectChanges(); component.onResize(1033); // wide by default docViewer = fixture.debugElement.query(By.css('aio-doc-viewer')).nativeElement; hamburger = fixture.debugElement.query(By.css('.hamburger')).nativeElement; locationService = fixture.debugElement.injector.get(LocationService) as any; sidenav = fixture.debugElement.query(By.css('md-sidenav')).nativeElement; }); it('should create', () => { expect(component).toBeDefined(); }); describe('ServiceWorker update notifications', () => { it('should be enabled', () => { const swUpdateNotifications = TestBed.get(SwUpdateNotificationsService) as SwUpdateNotificationsService; expect(swUpdateNotifications.enable).toHaveBeenCalled(); }); }); describe('onResize', () => { it('should update `isSideBySide` accordingly', () => { component.onResize(1033); expect(component.isSideBySide).toBe(true); component.onResize(500); expect(component.isSideBySide).toBe(false); }); }); describe('SideNav when side-by-side (wide)', () => { beforeEach(() => { component.onResize(1033); // side-by-side }); it('should open when nav to a guide page (guide/pipes)', () => { locationService.go('guide/pipes'); fixture.detectChanges(); expect(sidenav.className).toMatch(/sidenav-open/); }); it('should open when nav to an api page', () => { locationService.go('api/a/b/c/d'); fixture.detectChanges(); expect(sidenav.className).toMatch(/sidenav-open/); }); it('should be closed when nav to a marketing page (features)', () => { locationService.go('features'); fixture.detectChanges(); expect(sidenav.className).toMatch(/sidenav-clos/); }); describe('when manually closed', () => { beforeEach(() => { locationService.go('guide/pipes'); fixture.detectChanges(); hamburger.click(); fixture.detectChanges(); }); it('should be closed', () => { expect(sidenav.className).toMatch(/sidenav-clos/); }); it('should stay closed when nav to another guide page', () => { locationService.go('guide/bags'); fixture.detectChanges(); expect(sidenav.className).toMatch(/sidenav-clos/); }); it('should stay closed when nav to api page', () => { locationService.go('api'); fixture.detectChanges(); expect(sidenav.className).toMatch(/sidenav-clos/); }); it('should reopen when nav to market page and back to guide page', () => { locationService.go('features'); fixture.detectChanges(); locationService.go('guide/bags'); fixture.detectChanges(); expect(sidenav.className).toMatch(/sidenav-open/); }); }); }); describe('SideNav when NOT side-by-side (narrow)', () => { beforeEach(() => { component.onResize(1000); // NOT side-by-side }); it('should be closed when nav to a guide page (guide/pipes)', () => { locationService.go('guide/pipes'); fixture.detectChanges(); expect(sidenav.className).toMatch(/sidenav-clos/); }); it('should be closed when nav to an api page', () => { locationService.go('api/a/b/c/d'); fixture.detectChanges(); expect(sidenav.className).toMatch(/sidenav-clos/); }); it('should be closed when nav to a marketing page (features)', () => { locationService.go('features'); fixture.detectChanges(); expect(sidenav.className).toMatch(/sidenav-clos/); }); describe('when manually opened', () => { beforeEach(() => { locationService.go('guide/pipes'); fixture.detectChanges(); hamburger.click(); fixture.detectChanges(); }); it('should be open', () => { expect(sidenav.className).toMatch(/sidenav-open/); }); it('should close when click in gray content area overlay', () => { const sidenavBackdrop = fixture.debugElement.query(By.css('.mat-sidenav-backdrop')).nativeElement; sidenavBackdrop.click(); fixture.detectChanges(); expect(sidenav.className).toMatch(/sidenav-clos/); }); it('should stay open when nav to another guide page', () => { locationService.go('guide/bags'); fixture.detectChanges(); expect(sidenav.className).toMatch(/sidenav-open/); }); it('should stay open when nav to api page', () => { locationService.go('api'); fixture.detectChanges(); expect(sidenav.className).toMatch(/sidenav-open/); }); it('should close again when nav to market page', () => { locationService.go('features'); fixture.detectChanges(); expect(sidenav.className).toMatch(/sidenav-clos/); }); }); }); describe('SideNav version selector', () => { beforeEach(() => { component.onResize(1033); // side-by-side }); it('should pick first (current) version by default', () => { const versionSelector = sidenav.querySelector('select'); expect(versionSelector.value).toEqual(TestHttp.docVersions[0].title); expect(versionSelector.selectedIndex).toEqual(0); }); // Older docs versions have an href it('should navigate when change to a version with an href', () => { component.onDocVersionChange(1); expect(locationService.go).toHaveBeenCalledWith(TestHttp.docVersions[1].url); }); // The current docs version should not have an href // This may change when we perfect our docs versioning approach it('should not navigate when change to a version without an href', () => { component.onDocVersionChange(0); expect(locationService.go).not.toHaveBeenCalled(); }); }); describe('pageId', () => { it('should set the id of the doc viewer container based on the current doc', () => { const container = fixture.debugElement.query(By.css('section.sidenav-content')); locationService.go('guide/pipes'); fixture.detectChanges(); expect(component.pageId).toEqual('guide-pipes'); expect(container.properties['id']).toEqual('guide-pipes'); locationService.go('news'); fixture.detectChanges(); expect(component.pageId).toEqual('news'); expect(container.properties['id']).toEqual('news'); locationService.go(''); fixture.detectChanges(); expect(component.pageId).toEqual('home'); expect(container.properties['id']).toEqual('home'); }); it('should not be affected by changes to the query', () => { const container = fixture.debugElement.query(By.css('section.sidenav-content')); locationService.go('guide/pipes'); fixture.detectChanges(); locationService.go('guide/other?search=http'); fixture.detectChanges(); expect(component.pageId).toEqual('guide-other'); expect(container.properties['id']).toEqual('guide-other'); }); }); describe('currentDocument', () => { it('should display a guide page (guide/pipes)', () => { locationService.go('guide/pipes'); fixture.detectChanges(); expect(docViewer.innerText).toMatch(/Pipes/i); }); it('should display the api page', () => { locationService.go('api'); fixture.detectChanges(); expect(docViewer.innerText).toMatch(/API/i); }); it('should display a marketing page', () => { locationService.go('features'); fixture.detectChanges(); expect(docViewer.innerText).toMatch(/Features/i); }); const marketingClassName = 'marketing'; it('should not have marketing CSS class on host element for a guide page (guide/pipes)', () => { locationService.go('guide/pipes'); fixture.detectChanges(); const classes: string[] = fixture.nativeElement.className; expect(classes).not.toContain(marketingClassName); }); it('should have marketing CSS class on host element for a marketing page', () => { locationService.go('features'); fixture.detectChanges(); const classes: string[] = fixture.nativeElement.className; expect(classes).toContain(marketingClassName); }); it('should update the document title', () => { const titleService = TestBed.get(Title); spyOn(titleService, 'setTitle'); locationService.go('guide/pipes'); fixture.detectChanges(); expect(titleService.setTitle).toHaveBeenCalledWith('Angular - Pipes'); }); it('should update the document title, with a default value if the document has no title', () => { const titleService = TestBed.get(Title); spyOn(titleService, 'setTitle'); locationService.go('no-title'); fixture.detectChanges(); expect(titleService.setTitle).toHaveBeenCalledWith('Angular'); }); }); describe('autoScrolling with AutoScrollService', () => { let scrollService: AutoScrollService; let scrollSpy: jasmine.Spy; beforeEach(() => { scrollService = fixture.debugElement.injector.get(AutoScrollService); scrollSpy = spyOn(scrollService, 'scroll'); }); it('should not scroll immediately when the docId (path) changes', () => { locationService.go('guide/pipes'); // deliberately not calling `fixture.detectChanges` because don't want `onDocRendered` expect(scrollSpy).not.toHaveBeenCalled(); }); it('should scroll when just the hash changes (# alone)', () => { locationService.go('guide/pipes'); locationService.go('guide/pipes#somewhere'); expect(scrollSpy).toHaveBeenCalled(); }); it('should scroll when just the hash changes (/#)', () => { locationService.go('guide/pipes'); locationService.go('guide/pipes/#somewhere'); expect(scrollSpy).toHaveBeenCalled(); }); it('should scroll again when nav to the same hash twice in succession', () => { locationService.go('guide/pipes'); locationService.go('guide/pipes#somewhere'); locationService.go('guide/pipes#somewhere'); expect(scrollSpy.calls.count()).toBe(2); }); it('should scroll when call onDocRendered directly', () => { component.onDocRendered(); expect(scrollSpy).toHaveBeenCalled(); }); it('should scroll (via onDocRendered) when finish navigating to a new doc', () => { locationService.go('guide/pipes'); fixture.detectChanges(); // triggers the event that calls onDocRendered expect(scrollSpy).toHaveBeenCalled(); }); }); describe('search worker', () => { it('should initialize the search worker', inject([SearchService], (searchService: SearchService) => { fixture.detectChanges(); // triggers ngOnInit expect(searchService.initWorker).toHaveBeenCalled(); expect(searchService.loadIndex).toHaveBeenCalled(); })); }); describe('initial rendering', () => { beforeEach(async(() => { createTestingModule('a/b'); // Remove the DocViewer for this test and hide the missing component message TestBed.overrideModule(AppModule, { remove: { declarations: [DocViewerComponent] }, add: { schemas: [NO_ERRORS_SCHEMA] } }); TestBed.compileComponents(); })); it('should initially add the starting class until the first document is rendered', () => { fixture = TestBed.createComponent(AppComponent); fixture.detectChanges(); expect(fixture.componentInstance.isStarting).toBe(true); expect(fixture.debugElement.query(By.css('md-sidenav-container')).classes['starting']).toBe(true); fixture.debugElement.query(By.css('aio-doc-viewer')).triggerEventHandler('docRendered', {}); fixture.detectChanges(); expect(fixture.componentInstance.isStarting).toBe(false); expect(fixture.debugElement.query(By.css('md-sidenav-container')).classes['starting']).toBe(false); }); }); describe('click intercepting', () => { it('should intercept clicks on anchors and call `location.handleAnchorClick()`', inject([LocationService], (location: LocationService) => { const el = fixture.nativeElement as Element; el.innerHTML = '<a href="some/local/url">click me</a>'; const anchorElement = el.getElementsByTagName('a')[0]; anchorElement.click(); expect(location.handleAnchorClick).toHaveBeenCalledWith(anchorElement, 0, false, false); })); it('should intercept clicks on elements deep within an anchor tag', inject([LocationService], (location: LocationService) => { const el = fixture.nativeElement as Element; el.innerHTML = '<a href="some/local/url"><div><img></div></a>'; const imageElement = el.getElementsByTagName('img')[0]; const anchorElement = el.getElementsByTagName('a')[0]; imageElement.click(); expect(location.handleAnchorClick).toHaveBeenCalledWith(anchorElement, 0, false, false); })); it('should ignore clicks on elements without an anchor ancestor', inject([LocationService], (location: LocationService) => { const el = fixture.nativeElement as Element; el.innerHTML = '<div><p><div><img></div></p></div>'; const imageElement = el.getElementsByTagName('img')[0]; imageElement.click(); expect(location.handleAnchorClick).not.toHaveBeenCalled(); })); it('should intercept clicks not on the search elements and hide the search results', () => { const searchResults: SearchResultsComponent = fixture.debugElement.query(By.directive(SearchResultsComponent)).componentInstance; spyOn(searchResults, 'hideResults'); // docViewer is a commonly-clicked, non-search element docViewer.click(); expect(searchResults.hideResults).toHaveBeenCalled(); }); it('should not intercept clicks on any of the search elements', () => { const searchResults = fixture.debugElement.query(By.directive(SearchResultsComponent)); const searchResultsComponent: SearchResultsComponent = searchResults.componentInstance; const searchBox = fixture.debugElement.query(By.directive(SearchBoxComponent)); spyOn(searchResultsComponent, 'hideResults'); searchResults.nativeElement.click(); expect(searchResultsComponent.hideResults).not.toHaveBeenCalled(); searchBox.nativeElement.click(); expect(searchResultsComponent.hideResults).not.toHaveBeenCalled(); }); }); describe('footer', () => { it('should have version number', () => { const versionEl: HTMLElement = fixture.debugElement.query(By.css('aio-footer')).nativeElement; expect(versionEl.innerText).toContain(TestHttp.versionFull); }); }); }); //// test helpers //// function createTestingModule(initialUrl: string) { TestBed.resetTestingModule(); TestBed.configureTestingModule({ imports: [ AppModule ], providers: [ { provide: APP_BASE_HREF, useValue: '/' }, { provide: GaService, useClass: TestGaService }, { provide: Http, useClass: TestHttp }, { provide: LocationService, useFactory: () => new MockLocationService(initialUrl) }, { provide: Logger, useClass: MockLogger }, { provide: SearchService, useClass: MockSearchService }, { provide: SwUpdateNotificationsService, useClass: MockSwUpdateNotificationsService }, ] }); } class TestGaService { locationChanged = jasmine.createSpy('locationChanged'); } class TestSearchService { initWorker = jasmine.createSpy('initWorker'); loadIndex = jasmine.createSpy('loadIndex'); } class TestHttp { static versionFull = '4.0.0-local+sha.73808dd'; static docVersions: NavigationNode[] = [ { title: 'v4.0.0' }, { title: 'v2', url: 'https://v2.angular.io' } ]; // tslint:disable:quotemark navJson = { "TopBar": [ { "url": "features", "title": "Features" }, { "url": "no-title", "title": "No Title" }, ], "SideNav": [ { "title": "Core", "tooltip": "Learn the core capabilities of Angular", "children": [ { "url": "guide/pipes", "title": "Pipes", "tooltip": "Pipes transform displayed values within a template." }, { "url": "guide/bags", "title": "Bags", "tooltip": "Pack your bags for a code adventure." } ] }, { "url": "api", "title": "API", "tooltip": "Details of the Angular classes and values." } ], "docVersions": TestHttp.docVersions, "__versionInfo": { "raw": "4.0.0-rc.6", "major": 4, "minor": 0, "patch": 0, "prerelease": [ "local" ], "build": "sha.73808dd", "version": "4.0.0-local", "codeName": "snapshot", "isSnapshot": true, "full": TestHttp.versionFull, "branch": "master", "commitSHA": "73808dd38b5ccd729404936834d1568bd066de81" } }; get(url: string) { let data; if (/navigation\.json/.test(url)) { data = this.navJson; } else { const match = /content\/docs\/(.+)\.json/.exec(url); const id = match[1]; // Make up a title for test purposes const title = id.split('/').pop().replace(/^([a-z])/, (_, letter) => letter.toUpperCase()); const h1 = (id === 'no-title') ? '' : `<h1>${title}</h1>`; const contents = `${h1}<h2 id="#somewhere">Some heading</h2>`; data = { id, contents }; } return of({ json: () => data }); } }
aio/src/app/app.component.spec.ts
0
https://github.com/angular/angular/commit/a0b9c231008825adef6155ab39c3cc5a98c1f478
[ 0.00017852525343187153, 0.0001720493019092828, 0.0001636257948121056, 0.0001726322079775855, 0.000003992442543676589 ]
{ "id": 8, "code_window": [ " */\n", "@Component({\n", " selector: 'aio-code',\n", " template: `\n", " <pre class=\"prettyprint lang-{{language}}\">\n", " <button *ngIf=\"code\" class=\"material-icons copy-button\" (click)=\"doCopy()\">content_copy</button>\n", " <code class=\"animated fadeIn\" #codeContainer></code>\n", " </pre>\n", " `\n", "})\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " <button *ngIf=\"!hideCopy\" class=\"material-icons copy-button\" (click)=\"doCopy()\">content_copy</button>\n" ], "file_path": "aio/src/app/embedded/code/code.component.ts", "type": "replace", "edit_start_line_idx": 33 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {AsyncTestCompleter, beforeEach, describe, expect, inject, it} from '@angular/core/testing/src/testing_internal'; import {ResourceLoaderImpl} from '../../src/resource_loader/resource_loader_impl'; export function main() { describe('ResourceLoaderImpl', () => { let resourceLoader: ResourceLoaderImpl; // TODO(juliemr): This file currently won't work with dart unit tests run using // exclusive it or describe (iit or ddescribe). This is because when // pub run test is executed against this specific file the relative paths // will be relative to here, so url200 should look like // static_assets/200.html. // We currently have no way of detecting this. const url200 = '/base/packages/platform-browser/test/browser/static_assets/200.html'; const url404 = '/bad/path/404.html'; beforeEach(() => { resourceLoader = new ResourceLoaderImpl(); }); it('should resolve the Promise with the file content on success', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { resourceLoader.get(url200).then((text) => { expect(text.trim()).toEqual('<p>hey</p>'); async.done(); }); }), 10000); it('should reject the Promise on failure', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { resourceLoader.get(url404).catch((e) => { expect(e).toEqual(`Failed to load ${url404}`); async.done(); return null; }); }), 10000); }); }
packages/platform-browser-dynamic/test/resource_loader/resource_loader_impl_spec.ts
0
https://github.com/angular/angular/commit/a0b9c231008825adef6155ab39c3cc5a98c1f478
[ 0.0001742878812365234, 0.0001712548837531358, 0.00016844317724462599, 0.00017117462994065136, 0.000002276492750752368 ]
{ "id": 8, "code_window": [ " */\n", "@Component({\n", " selector: 'aio-code',\n", " template: `\n", " <pre class=\"prettyprint lang-{{language}}\">\n", " <button *ngIf=\"code\" class=\"material-icons copy-button\" (click)=\"doCopy()\">content_copy</button>\n", " <code class=\"animated fadeIn\" #codeContainer></code>\n", " </pre>\n", " `\n", "})\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " <button *ngIf=\"!hideCopy\" class=\"material-icons copy-button\" (click)=\"doCopy()\">content_copy</button>\n" ], "file_path": "aio/src/app/embedded/code/code.component.ts", "type": "replace", "edit_start_line_idx": 33 }
// returns the script path for the current platform module.exports = function platformScriptPath(path) { const os = require('os'); return /^win/.test(os.platform()) ? `${path}.cmd` : path; };
tools/gulp-tasks/platform-script-path.js
0
https://github.com/angular/angular/commit/a0b9c231008825adef6155ab39c3cc5a98c1f478
[ 0.00017125069280155003, 0.00017125069280155003, 0.00017125069280155003, 0.00017125069280155003, 0 ]
{ "id": 9, "code_window": [ " */\n", " @Input()\n", " region: string;\n", "\n", " /**\n", " * The element in the template that will display the formatted code\n", " */\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " /**\n", " * set to true if the copy button is not to be shown\n", " */\n", " @Input()\n", " hideCopy: boolean;\n", "\n" ], "file_path": "aio/src/app/embedded/code/code.component.ts", "type": "add", "edit_start_line_idx": 74 }
/* tslint:disable:no-unused-variable */ import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { Component, DebugElement } from '@angular/core'; import { MdSnackBarModule, MdSnackBar } from '@angular/material'; import { NoopAnimationsModule } from '@angular/platform-browser/animations'; import { CodeComponent } from './code.component'; import { CopierService } from 'app/shared//copier.service'; import { Logger } from 'app/shared/logger.service'; import { PrettyPrinter } from './pretty-printer.service'; const oneLineCode = 'const foo = "bar";'; const smallMultiLineCode = ` &lt;hero-details&gt; &lt;h2&gt;Bah Dah Bing&lt;/h2&gt; &lt;hero-team&gt; &lt;h3&gt;NYC Team&lt;/h3&gt; &lt;/hero-team&gt; &lt;/hero-details&gt;`; const bigMultiLineCode = smallMultiLineCode + smallMultiLineCode + smallMultiLineCode; describe('CodeComponent', () => { let codeComponentDe: DebugElement; let codeComponent: CodeComponent; let hostComponent: HostComponent; let fixture: ComponentFixture<HostComponent>; // WARNING: Chance of cross-test pollution // CodeComponent injects PrettyPrintService // Once PrettyPrintService runs once _anywhere_, its ctor loads `prettify.js` // which sets `window['prettyPrintOne']` // That global survives these tests unless // we take strict measures to wipe it out in the `afterAll` // and make sure THAT runs after the tests by making component creation async afterAll(() => { delete window['prettyPrint']; delete window['prettyPrintOne']; }); beforeEach(async(() => { TestBed.configureTestingModule({ imports: [ MdSnackBarModule, NoopAnimationsModule ], declarations: [ CodeComponent, HostComponent ], providers: [ PrettyPrinter, CopierService, {provide: Logger, useClass: TestLogger } ] }) .compileComponents(); })); // Must be async because // CodeComponent creates PrettyPrintService which async loads `prettify.js`. // If not async, `afterAll` finishes before tests do! beforeEach(async(() => { fixture = TestBed.createComponent(HostComponent); hostComponent = fixture.componentInstance; codeComponentDe = fixture.debugElement.children[0]; codeComponent = codeComponentDe.componentInstance; fixture.detectChanges(); })); it('should create CodeComponent', () => { expect(codeComponentDe.name).toBe('aio-code', 'selector'); expect(codeComponent).toBeTruthy('CodeComponent'); }); describe('pretty printing', () => { it('should format a one-line code sample', () => { // 'pln' spans are a tell-tale for syntax highlighing const spans = codeComponentDe.nativeElement.querySelectorAll('span.pln'); expect(spans.length).toBeGreaterThan(0, 'formatted spans'); }); function hasLineNumbers() { // presence of `<li>`s are a tell-tale for line numbers return 0 < codeComponentDe.nativeElement.querySelectorAll('li').length; } it('should format a one-line code sample without linenums by default', () => { expect(hasLineNumbers()).toBe(false); }); it('should add line numbers to one-line code sample when linenums set true', () => { hostComponent.linenums = 'true'; fixture.detectChanges(); expect(hasLineNumbers()).toBe(true); }); it('should format a small multi-line code without linenums by default', () => { hostComponent.code = smallMultiLineCode; fixture.detectChanges(); expect(hasLineNumbers()).toBe(false); }); it('should add line numbers to a big multi-line code by default', () => { hostComponent.code = bigMultiLineCode; fixture.detectChanges(); expect(hasLineNumbers()).toBe(true); }); it('should format big multi-line code without linenums when linenums set false', () => { hostComponent.linenums = false; hostComponent.code = bigMultiLineCode; fixture.detectChanges(); expect(hasLineNumbers()).toBe(false); }); }); describe('whitespace handling', () => { it('should remove common indentation from the code before rendering', () => { hostComponent.linenums = false; hostComponent.code = ' abc\n let x = text.split(\'\\n\');\n ghi\n\n jkl\n'; fixture.detectChanges(); const codeContent = codeComponentDe.nativeElement.querySelector('code').innerText; expect(codeContent).toEqual('abc\n let x = text.split(\'\\n\');\nghi\n\njkl'); }); it('should trim whitespace from the code before rendering', () => { hostComponent.linenums = false; hostComponent.code = '\n\n\n' + smallMultiLineCode + '\n\n\n'; fixture.detectChanges(); const codeContent = codeComponentDe.nativeElement.querySelector('code').innerText; expect(codeContent).toEqual(codeContent.trim()); }); it('should trim whitespace from code before computing whether to format linenums', () => { hostComponent.code = '\n\n\n' + hostComponent.code + '\n\n\n'; fixture.detectChanges(); // `<li>`s are a tell-tale for line numbers const lis = codeComponentDe.nativeElement.querySelectorAll('li'); expect(lis.length).toBe(0, 'should be no linenums'); }); }); describe('error message', () => { function getErrorMessage() { const missing: HTMLElement = codeComponentDe.nativeElement.querySelector('.code-missing'); return missing ? missing.innerText : null; } it('should not display "code-missing" class when there is some code', () => { fixture.detectChanges(); expect(getErrorMessage()).toBeNull('should not have element with "code-missing" class'); }); it('should display error message when there is no code (after trimming)', () => { hostComponent.code = ' \n '; fixture.detectChanges(); expect(getErrorMessage()).toContain('missing'); }); it('should show path and region in missing-code error message', () => { hostComponent.code = ' \n '; hostComponent.path = 'fizz/buzz/foo.html'; hostComponent.region = 'something'; fixture.detectChanges(); expect(getErrorMessage()).toMatch(/for[\s\S]fizz\/buzz\/foo\.html#something$/); }); it('should show path only in missing-code error message when no region', () => { hostComponent.code = ' \n '; hostComponent.path = 'fizz/buzz/foo.html'; fixture.detectChanges(); expect(getErrorMessage()).toMatch(/for[\s\S]fizz\/buzz\/foo\.html$/); }); it('should show simple missing-code error message when no path/region', () => { hostComponent.code = ' \n '; fixture.detectChanges(); expect(getErrorMessage()).toMatch(/missing.$/); }); }); describe('copy button', () => { it('should call copier service when clicked', () => { const copierService: CopierService = TestBed.get(CopierService); const spy = spyOn(copierService, 'copyText'); const button = fixture.debugElement.query(By.css('button')).nativeElement as HTMLButtonElement; expect(spy.calls.count()).toBe(0, 'before click'); button.click(); expect(spy.calls.count()).toBe(1, 'after click'); }); it('should copy code text when clicked', () => { const copierService: CopierService = TestBed.get(CopierService); const spy = spyOn(copierService, 'copyText'); const button = fixture.debugElement.query(By.css('button')).nativeElement as HTMLButtonElement; button.click(); expect(spy.calls.argsFor(0)[0]).toEqual(oneLineCode, 'after click'); }); it('should display a message when copy succeeds', () => { const snackBar: MdSnackBar = TestBed.get(MdSnackBar); const copierService: CopierService = TestBed.get(CopierService); spyOn(snackBar, 'open'); spyOn(copierService, 'copyText').and.returnValue(true); const button = fixture.debugElement.query(By.css('button')).nativeElement as HTMLButtonElement; button.click(); expect(snackBar.open).toHaveBeenCalledWith('Code Copied', '', { duration: 800 }); }); it('should display an error when copy fails', () => { const snackBar: MdSnackBar = TestBed.get(MdSnackBar); const copierService: CopierService = TestBed.get(CopierService); spyOn(snackBar, 'open'); spyOn(copierService, 'copyText').and.returnValue(false); const button = fixture.debugElement.query(By.css('button')).nativeElement as HTMLButtonElement; button.click(); expect(snackBar.open).toHaveBeenCalledWith('Copy failed. Please try again!', '', { duration: 800 }); }); }); }); //// Test helpers //// // tslint:disable:member-ordering @Component({ selector: 'aio-host-comp', template: ` <aio-code md-no-ink [code]="code" [language]="language" [linenums]="linenums" [path]="path" [region]="region"></aio-code> ` }) class HostComponent { code = oneLineCode; language: string; linenums: boolean | number | string; path: string; region: string; } class TestLogger { log = jasmine.createSpy('log'); error = jasmine.createSpy('error'); }
aio/src/app/embedded/code/code.component.spec.ts
1
https://github.com/angular/angular/commit/a0b9c231008825adef6155ab39c3cc5a98c1f478
[ 0.0001927558914758265, 0.00016974091704469174, 0.00016554018657188863, 0.0001685239840298891, 0.000005495387995324563 ]
{ "id": 9, "code_window": [ " */\n", " @Input()\n", " region: string;\n", "\n", " /**\n", " * The element in the template that will display the formatted code\n", " */\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " /**\n", " * set to true if the copy button is not to be shown\n", " */\n", " @Input()\n", " hideCopy: boolean;\n", "\n" ], "file_path": "aio/src/app/embedded/code/code.component.ts", "type": "add", "edit_start_line_idx": 74 }
aio/content/examples/upgrade-phonecat-1-typescript/app/img/.gitkeep
0
https://github.com/angular/angular/commit/a0b9c231008825adef6155ab39c3cc5a98c1f478
[ 0.00017986416060011834, 0.00017986416060011834, 0.00017986416060011834, 0.00017986416060011834, 0 ]
{ "id": 9, "code_window": [ " */\n", " @Input()\n", " region: string;\n", "\n", " /**\n", " * The element in the template that will display the formatted code\n", " */\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " /**\n", " * set to true if the copy button is not to be shown\n", " */\n", " @Input()\n", " hideCopy: boolean;\n", "\n" ], "file_path": "aio/src/app/embedded/code/code.component.ts", "type": "add", "edit_start_line_idx": 74 }
#!/usr/bin/env node /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /* tslint:disable:no-console */ // Must be imported first, because Angular decorators throw on load. import 'reflect-metadata'; import * as path from 'path'; import * as ts from 'typescript'; import * as assert from 'assert'; import {tsc} from '@angular/tsc-wrapped/src/tsc'; import {AngularCompilerOptions, CodeGenerator, CompilerHostContext, NodeCompilerHostContext} from '@angular/compiler-cli'; /** * Main method. * Standalone program that executes the real codegen and tests that * ngsummary.json files are used for libraries. */ function main() { console.log(`testing usage of ngsummary.json files in libraries...`); const basePath = path.resolve(__dirname, '..'); const project = path.resolve(basePath, 'tsconfig-build.json'); const readFiles: string[] = []; const writtenFiles: {fileName: string, content: string}[] = []; class AssertingHostContext extends NodeCompilerHostContext { readFile(fileName: string): string { if (/.*\/node_modules\/.*/.test(fileName) && !/.*ngsummary\.json$/.test(fileName) && !/package\.json$/.test(fileName)) { // Only allow to read summaries and package.json files from node_modules // TODO (mhevery): Fix this. TypeScript.d.ts does not allow returning null. return null !; } readFiles.push(path.relative(basePath, fileName)); return super.readFile(fileName); } readResource(s: string): Promise<string> { readFiles.push(path.relative(basePath, s)); return super.readResource(s); } } const config = tsc.readConfiguration(project, basePath); config.ngOptions.basePath = basePath; // This flag tells ngc do not recompile libraries. config.ngOptions.generateCodeForLibraries = false; console.log(`>>> running codegen for ${project}`); codegen( config, (host) => { host.writeFile = (fileName: string, content: string) => { fileName = path.relative(basePath, fileName); writtenFiles.push({fileName, content}); }; return new AssertingHostContext(); }) .then((exitCode: any) => { console.log(`>>> codegen done, asserting read files`); assertSomeFileMatch(readFiles, /^node_modules\/.*\.ngsummary\.json$/); assertNoFileMatch(readFiles, /^node_modules\/.*\.metadata.json$/); assertNoFileMatch(readFiles, /^node_modules\/.*\.html$/); assertNoFileMatch(readFiles, /^node_modules\/.*\.css$/); assertNoFileMatch(readFiles, /^src\/.*\.ngsummary\.json$/); assertSomeFileMatch(readFiles, /^src\/.*\.html$/); assertSomeFileMatch(readFiles, /^src\/.*\.css$/); console.log(`>>> asserting written files`); assertWrittenFile(writtenFiles, /^src\/module\.ngfactory\.ts$/, /class MainModuleInjector/); console.log(`done, no errors.`); process.exit(exitCode); }) .catch((e: any) => { console.error(e.stack); console.error('Compilation failed'); process.exit(1); }); } /** * Simple adaption of tsc-wrapped main to just run codegen with a CompilerHostContext */ function codegen( config: {parsed: ts.ParsedCommandLine, ngOptions: AngularCompilerOptions}, hostContextFactory: (host: ts.CompilerHost) => CompilerHostContext) { const host = ts.createCompilerHost(config.parsed.options, true); // HACK: patch the realpath to solve symlink issue here: // https://github.com/Microsoft/TypeScript/issues/9552 // todo(misko): remove once facade symlinks are removed host.realpath = (path) => path; const program = ts.createProgram(config.parsed.fileNames, config.parsed.options, host); return CodeGenerator.create(config.ngOptions, { } as any, program, host, hostContextFactory(host)).codegen(); } function assertSomeFileMatch(fileNames: string[], pattern: RegExp) { assert( fileNames.some(fileName => pattern.test(fileName)), `Expected some read files match ${pattern}`); } function assertNoFileMatch(fileNames: string[], pattern: RegExp) { const matches = fileNames.filter(fileName => pattern.test(fileName)); assert( matches.length === 0, `Expected no read files match ${pattern}, but found: \n${matches.join('\n')}`); } function assertWrittenFile( files: {fileName: string, content: string}[], filePattern: RegExp, contentPattern: RegExp) { assert( files.some(file => filePattern.test(file.fileName) && contentPattern.test(file.content)), `Expected some written files for ${filePattern} and content ${contentPattern}`); } main();
packages/compiler-cli/integrationtest/test/test_summaries.ts
0
https://github.com/angular/angular/commit/a0b9c231008825adef6155ab39c3cc5a98c1f478
[ 0.0001714183163130656, 0.00016823573969304562, 0.00016493249859195203, 0.00016806216444820166, 0.0000016625040188955609 ]
{ "id": 9, "code_window": [ " */\n", " @Input()\n", " region: string;\n", "\n", " /**\n", " * The element in the template that will display the formatted code\n", " */\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " /**\n", " * set to true if the copy button is not to be shown\n", " */\n", " @Input()\n", " hideCopy: boolean;\n", "\n" ], "file_path": "aio/src/app/embedded/code/code.component.ts", "type": "add", "edit_start_line_idx": 74 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ export {PlatformState} from './platform_state'; export {ServerModule, platformDynamicServer, platformServer} from './server'; export {INITIAL_CONFIG, PlatformConfig} from './tokens'; export {renderModule, renderModuleFactory} from './utils'; export * from './private_export'; export {VERSION} from './version';
packages/platform-server/src/platform-server.ts
0
https://github.com/angular/angular/commit/a0b9c231008825adef6155ab39c3cc5a98c1f478
[ 0.00017254128761123866, 0.00016893820429686457, 0.00016533512098249048, 0.00016893820429686457, 0.0000036030833143740892 ]
{ "id": 0, "code_window": [ "import { CancellationTokenSource } from 'vs/base/common/cancellation';\n", "\n", "const DEBUG_BREAKPOINTS_KEY = 'debug.breakpoint';\n", "const DEBUG_BREAKPOINTS_ACTIVATED_KEY = 'debug.breakpointactivated';\n", "const DEBUG_FUNCTION_BREAKPOINTS_KEY = 'debug.functionbreakpoint';\n", "const DEBUG_DATA_BREAKPOINTS_KEY = 'debug.databreakpoint';\n", "const DEBUG_EXCEPTION_BREAKPOINTS_KEY = 'debug.exceptionbreakpoint';\n", "const DEBUG_WATCH_EXPRESSIONS_KEY = 'debug.watchexpressions';\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/debug/browser/debugService.ts", "type": "replace", "edit_start_line_idx": 52 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as nls from 'vs/nls'; import { Event, Emitter } from 'vs/base/common/event'; import { URI as uri } from 'vs/base/common/uri'; import { first, distinct } from 'vs/base/common/arrays'; import * as errors from 'vs/base/common/errors'; import severity from 'vs/base/common/severity'; import * as aria from 'vs/base/browser/ui/aria/aria'; import { IContextKeyService, IContextKey } from 'vs/platform/contextkey/common/contextkey'; import { IMarkerService } from 'vs/platform/markers/common/markers'; import { ILifecycleService } from 'vs/platform/lifecycle/common/lifecycle'; import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { FileChangesEvent, FileChangeType, IFileService } from 'vs/platform/files/common/files'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage'; import { DebugModel, ExceptionBreakpoint, FunctionBreakpoint, Breakpoint, Expression, DataBreakpoint } from 'vs/workbench/contrib/debug/common/debugModel'; import { ViewModel } from 'vs/workbench/contrib/debug/common/debugViewModel'; import * as debugactions from 'vs/workbench/contrib/debug/browser/debugActions'; import { ConfigurationManager } from 'vs/workbench/contrib/debug/browser/debugConfigurationManager'; import Constants from 'vs/workbench/contrib/markers/browser/constants'; import { ITaskService, ITaskSummary } from 'vs/workbench/contrib/tasks/common/taskService'; import { TaskError } from 'vs/workbench/contrib/tasks/common/taskSystem'; import { VIEWLET_ID as EXPLORER_VIEWLET_ID } from 'vs/workbench/contrib/files/common/files'; import { IViewletService } from 'vs/workbench/services/viewlet/browser/viewlet'; import { IPanelService } from 'vs/workbench/services/panel/common/panelService'; import { IWorkbenchLayoutService, Parts } from 'vs/workbench/services/layout/browser/layoutService'; import { ITextFileService } from 'vs/workbench/services/textfile/common/textfiles'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IWorkspaceContextService, WorkbenchState, IWorkspaceFolder } from 'vs/platform/workspace/common/workspace'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { parse, getFirstFrame } from 'vs/base/common/console'; import { TaskEvent, TaskEventKind, TaskIdentifier } from 'vs/workbench/contrib/tasks/common/tasks'; import { IDialogService } from 'vs/platform/dialogs/common/dialogs'; import { INotificationService } from 'vs/platform/notification/common/notification'; import { IAction, Action } from 'vs/base/common/actions'; import { deepClone, equals } from 'vs/base/common/objects'; import { DebugSession } from 'vs/workbench/contrib/debug/browser/debugSession'; import { dispose, IDisposable } from 'vs/base/common/lifecycle'; import { IDebugService, State, IDebugSession, CONTEXT_DEBUG_TYPE, CONTEXT_DEBUG_STATE, CONTEXT_IN_DEBUG_MODE, IThread, IDebugConfiguration, VIEWLET_ID, REPL_ID, IConfig, ILaunch, IViewModel, IConfigurationManager, IDebugModel, IEnablement, IBreakpoint, IBreakpointData, ICompound, IGlobalConfig, IStackFrame, AdapterEndEvent, getStateLabel } from 'vs/workbench/contrib/debug/common/debug'; import { isExtensionHostDebugging } from 'vs/workbench/contrib/debug/common/debugUtils'; import { isErrorWithActions, createErrorWithActions } from 'vs/base/common/errorsWithActions'; import { RunOnceScheduler } from 'vs/base/common/async'; import { IExtensionHostDebugService } from 'vs/platform/debug/common/extensionHostDebug'; import { isCodeEditor } from 'vs/editor/browser/editorBrowser'; import { CancellationTokenSource } from 'vs/base/common/cancellation'; const DEBUG_BREAKPOINTS_KEY = 'debug.breakpoint'; const DEBUG_BREAKPOINTS_ACTIVATED_KEY = 'debug.breakpointactivated'; const DEBUG_FUNCTION_BREAKPOINTS_KEY = 'debug.functionbreakpoint'; const DEBUG_DATA_BREAKPOINTS_KEY = 'debug.databreakpoint'; const DEBUG_EXCEPTION_BREAKPOINTS_KEY = 'debug.exceptionbreakpoint'; const DEBUG_WATCH_EXPRESSIONS_KEY = 'debug.watchexpressions'; function once(match: (e: TaskEvent) => boolean, event: Event<TaskEvent>): Event<TaskEvent> { return (listener, thisArgs = null, disposables?) => { const result = event(e => { if (match(e)) { result.dispose(); return listener.call(thisArgs, e); } }, null, disposables); return result; }; } const enum TaskRunResult { Failure, Success } export class DebugService implements IDebugService { _serviceBrand: any; private readonly _onDidChangeState: Emitter<State>; private readonly _onDidNewSession: Emitter<IDebugSession>; private readonly _onWillNewSession: Emitter<IDebugSession>; private readonly _onDidEndSession: Emitter<IDebugSession>; private model: DebugModel; private viewModel: ViewModel; private configurationManager: ConfigurationManager; private toDispose: IDisposable[]; private debugType: IContextKey<string>; private debugState: IContextKey<string>; private inDebugMode: IContextKey<boolean>; private breakpointsToSendOnResourceSaved: Set<string>; private initializing = false; private previousState: State | undefined; private initCancellationToken: CancellationTokenSource | undefined; constructor( @IStorageService private readonly storageService: IStorageService, @IEditorService private readonly editorService: IEditorService, @ITextFileService private readonly textFileService: ITextFileService, @IViewletService private readonly viewletService: IViewletService, @IPanelService private readonly panelService: IPanelService, @INotificationService private readonly notificationService: INotificationService, @IDialogService private readonly dialogService: IDialogService, @IWorkbenchLayoutService private readonly layoutService: IWorkbenchLayoutService, @ITelemetryService private readonly telemetryService: ITelemetryService, @IWorkspaceContextService private readonly contextService: IWorkspaceContextService, @IContextKeyService contextKeyService: IContextKeyService, @ILifecycleService private readonly lifecycleService: ILifecycleService, @IInstantiationService private readonly instantiationService: IInstantiationService, @IExtensionService private readonly extensionService: IExtensionService, @IMarkerService private readonly markerService: IMarkerService, @ITaskService private readonly taskService: ITaskService, @IFileService private readonly fileService: IFileService, @IConfigurationService private readonly configurationService: IConfigurationService, @IExtensionHostDebugService private readonly extensionHostDebugService: IExtensionHostDebugService ) { this.toDispose = []; this.breakpointsToSendOnResourceSaved = new Set<string>(); this._onDidChangeState = new Emitter<State>(); this._onDidNewSession = new Emitter<IDebugSession>(); this._onWillNewSession = new Emitter<IDebugSession>(); this._onDidEndSession = new Emitter<IDebugSession>(); this.configurationManager = this.instantiationService.createInstance(ConfigurationManager, this); this.toDispose.push(this.configurationManager); this.debugType = CONTEXT_DEBUG_TYPE.bindTo(contextKeyService); this.debugState = CONTEXT_DEBUG_STATE.bindTo(contextKeyService); this.inDebugMode = CONTEXT_IN_DEBUG_MODE.bindTo(contextKeyService); this.model = new DebugModel(this.loadBreakpoints(), this.storageService.getBoolean(DEBUG_BREAKPOINTS_ACTIVATED_KEY, StorageScope.WORKSPACE, true), this.loadFunctionBreakpoints(), this.loadExceptionBreakpoints(), this.loadDataBreakpoints(), this.loadWatchExpressions(), this.textFileService); this.toDispose.push(this.model); this.viewModel = new ViewModel(contextKeyService); this.toDispose.push(this.fileService.onFileChanges(e => this.onFileChanges(e))); this.lifecycleService.onShutdown(this.dispose, this); this.toDispose.push(this.extensionHostDebugService.onAttachSession(event => { const session = this.model.getSession(event.sessionId, true); if (session) { // EH was started in debug mode -> attach to it session.configuration.request = 'attach'; session.configuration.port = event.port; session.setSubId(event.subId); this.launchOrAttachToSession(session).then(undefined, errors.onUnexpectedError); } })); this.toDispose.push(this.extensionHostDebugService.onTerminateSession(event => { const session = this.model.getSession(event.sessionId); if (session && session.subId === event.subId) { session.disconnect().then(undefined, errors.onUnexpectedError); } })); this.toDispose.push(this.extensionHostDebugService.onLogToSession(event => { const session = this.model.getSession(event.sessionId, true); if (session) { // extension logged output -> show it in REPL const sev = event.log.severity === 'warn' ? severity.Warning : event.log.severity === 'error' ? severity.Error : severity.Info; const { args, stack } = parse(event.log); const frame = !!stack ? getFirstFrame(stack) : undefined; session.logToRepl(sev, args, frame); } })); this.toDispose.push(this.viewModel.onDidFocusStackFrame(() => { this.onStateChange(); })); this.toDispose.push(this.viewModel.onDidFocusSession(session => { const id = session ? session.getId() : undefined; this.model.setBreakpointsSessionId(id); this.onStateChange(); })); } getModel(): IDebugModel { return this.model; } getViewModel(): IViewModel { return this.viewModel; } getConfigurationManager(): IConfigurationManager { return this.configurationManager; } sourceIsNotAvailable(uri: uri): void { this.model.sourceIsNotAvailable(uri); } dispose(): void { this.toDispose = dispose(this.toDispose); } //---- state management get state(): State { const focusedSession = this.viewModel.focusedSession; if (focusedSession) { return focusedSession.state; } return this.initializing ? State.Initializing : State.Inactive; } private startInitializingState() { if (!this.initializing) { this.initializing = true; this.onStateChange(); } } private endInitializingState() { if (this.initCancellationToken) { this.initCancellationToken.cancel(); this.initCancellationToken = undefined; } if (this.initializing) { this.initializing = false; this.onStateChange(); } } private onStateChange(): void { const state = this.state; if (this.previousState !== state) { this.debugState.set(getStateLabel(state)); this.inDebugMode.set(state !== State.Inactive); this.previousState = state; this._onDidChangeState.fire(state); } } get onDidChangeState(): Event<State> { return this._onDidChangeState.event; } get onDidNewSession(): Event<IDebugSession> { return this._onDidNewSession.event; } get onWillNewSession(): Event<IDebugSession> { return this._onWillNewSession.event; } get onDidEndSession(): Event<IDebugSession> { return this._onDidEndSession.event; } //---- life cycle management /** * main entry point * properly manages compounds, checks for errors and handles the initializing state. */ startDebugging(launch: ILaunch | undefined, configOrName?: IConfig | string, noDebug = false, parentSession?: IDebugSession): Promise<boolean> { this.startInitializingState(); // make sure to save all files and that the configuration is up to date return this.extensionService.activateByEvent('onDebug').then(() => { return this.textFileService.saveAll().then(() => this.configurationService.reloadConfiguration(launch ? launch.workspace : undefined).then(() => { return this.extensionService.whenInstalledExtensionsRegistered().then(() => { let config: IConfig | undefined; let compound: ICompound | undefined; if (!configOrName) { configOrName = this.configurationManager.selectedConfiguration.name; } if (typeof configOrName === 'string' && launch) { config = launch.getConfiguration(configOrName); compound = launch.getCompound(configOrName); const sessions = this.model.getSessions(); const alreadyRunningMessage = nls.localize('configurationAlreadyRunning', "There is already a debug configuration \"{0}\" running.", configOrName); if (sessions.some(s => s.configuration.name === configOrName && (!launch || !launch.workspace || !s.root || s.root.uri.toString() === launch.workspace.uri.toString()))) { return Promise.reject(new Error(alreadyRunningMessage)); } if (compound && compound.configurations && sessions.some(p => compound!.configurations.indexOf(p.configuration.name) !== -1)) { return Promise.reject(new Error(alreadyRunningMessage)); } } else if (typeof configOrName !== 'string') { config = configOrName; } if (compound) { // we are starting a compound debug, first do some error checking and than start each configuration in the compound if (!compound.configurations) { return Promise.reject(new Error(nls.localize({ key: 'compoundMustHaveConfigurations', comment: ['compound indicates a "compounds" configuration item', '"configurations" is an attribute and should not be localized'] }, "Compound must have \"configurations\" attribute set in order to start multiple configurations."))); } return Promise.all(compound.configurations.map(configData => { const name = typeof configData === 'string' ? configData : configData.name; if (name === compound!.name) { return Promise.resolve(false); } let launchForName: ILaunch | undefined; if (typeof configData === 'string') { const launchesContainingName = this.configurationManager.getLaunches().filter(l => !!l.getConfiguration(name)); if (launchesContainingName.length === 1) { launchForName = launchesContainingName[0]; } else if (launch && launchesContainingName.length > 1 && launchesContainingName.indexOf(launch) >= 0) { // If there are multiple launches containing the configuration give priority to the configuration in the current launch launchForName = launch; } else { return Promise.reject(new Error(launchesContainingName.length === 0 ? nls.localize('noConfigurationNameInWorkspace', "Could not find launch configuration '{0}' in the workspace.", name) : nls.localize('multipleConfigurationNamesInWorkspace', "There are multiple launch configurations '{0}' in the workspace. Use folder name to qualify the configuration.", name))); } } else if (configData.folder) { const launchesMatchingConfigData = this.configurationManager.getLaunches().filter(l => l.workspace && l.workspace.name === configData.folder && !!l.getConfiguration(configData.name)); if (launchesMatchingConfigData.length === 1) { launchForName = launchesMatchingConfigData[0]; } else { return Promise.reject(new Error(nls.localize('noFolderWithName', "Can not find folder with name '{0}' for configuration '{1}' in compound '{2}'.", configData.folder, configData.name, compound!.name))); } } return this.createSession(launchForName, launchForName!.getConfiguration(name), noDebug, parentSession); })).then(values => values.every(success => !!success)); // Compound launch is a success only if each configuration launched successfully } if (configOrName && !config) { const message = !!launch ? nls.localize('configMissing', "Configuration '{0}' is missing in 'launch.json'.", typeof configOrName === 'string' ? configOrName : JSON.stringify(configOrName)) : nls.localize('launchJsonDoesNotExist', "'launch.json' does not exist."); return Promise.reject(new Error(message)); } return this.createSession(launch, config, noDebug, parentSession); }); })); }).then(success => { // make sure to get out of initializing state, and propagate the result this.endInitializingState(); return success; }, err => { this.endInitializingState(); return Promise.reject(err); }); } /** * gets the debugger for the type, resolves configurations by providers, substitutes variables and runs prelaunch tasks */ private createSession(launch: ILaunch | undefined, config: IConfig | undefined, noDebug: boolean, parentSession?: IDebugSession): Promise<boolean> { // We keep the debug type in a separate variable 'type' so that a no-folder config has no attributes. // Storing the type in the config would break extensions that assume that the no-folder case is indicated by an empty config. let type: string | undefined; if (config) { type = config.type; } else { // a no-folder workspace has no launch.config config = Object.create(null); } const unresolvedConfig = deepClone(config); if (noDebug) { config!.noDebug = true; } const debuggerThenable: Promise<void> = type ? Promise.resolve() : this.configurationManager.guessDebugger().then(dbgr => { type = dbgr && dbgr.type; }); return debuggerThenable.then(() => { this.initCancellationToken = new CancellationTokenSource(); return this.configurationManager.resolveConfigurationByProviders(launch && launch.workspace ? launch.workspace.uri : undefined, type, config!, this.initCancellationToken.token).then(config => { // a falsy config indicates an aborted launch if (config && config.type) { return this.substituteVariables(launch, config).then(resolvedConfig => { if (!resolvedConfig) { // User canceled resolving of interactive variables, silently return return false; } if (!this.configurationManager.getDebugger(resolvedConfig.type) || (config.request !== 'attach' && config.request !== 'launch')) { let message: string; if (config.request !== 'attach' && config.request !== 'launch') { message = config.request ? nls.localize('debugRequestNotSupported', "Attribute '{0}' has an unsupported value '{1}' in the chosen debug configuration.", 'request', config.request) : nls.localize('debugRequesMissing', "Attribute '{0}' is missing from the chosen debug configuration.", 'request'); } else { message = resolvedConfig.type ? nls.localize('debugTypeNotSupported', "Configured debug type '{0}' is not supported.", resolvedConfig.type) : nls.localize('debugTypeMissing', "Missing property 'type' for the chosen launch configuration."); } return this.showError(message).then(() => false); } const workspace = launch ? launch.workspace : undefined; return this.runTaskAndCheckErrors(workspace, resolvedConfig.preLaunchTask).then(result => { if (result === TaskRunResult.Success) { return this.doCreateSession(workspace, { resolved: resolvedConfig, unresolved: unresolvedConfig }, parentSession); } return false; }); }, err => { if (err && err.message) { return this.showError(err.message).then(() => false); } if (this.contextService.getWorkbenchState() === WorkbenchState.EMPTY) { return this.showError(nls.localize('noFolderWorkspaceDebugError', "The active file can not be debugged. Make sure it is saved and that you have a debug extension installed for that file type.")) .then(() => false); } return !!launch && launch.openConfigFile(false, true, undefined, this.initCancellationToken ? this.initCancellationToken.token : undefined).then(() => false); }); } if (launch && type && config === null) { // show launch.json only for "config" being "null". return launch.openConfigFile(false, true, type, this.initCancellationToken ? this.initCancellationToken.token : undefined).then(() => false); } return false; }); }); } /** * instantiates the new session, initializes the session, registers session listeners and reports telemetry */ private doCreateSession(root: IWorkspaceFolder | undefined, configuration: { resolved: IConfig, unresolved: IConfig | undefined }, parentSession?: IDebugSession): Promise<boolean> { const session = this.instantiationService.createInstance(DebugSession, configuration, root, this.model, parentSession); this.model.addSession(session); // register listeners as the very first thing! this.registerSessionListeners(session); // since the Session is now properly registered under its ID and hooked, we can announce it // this event doesn't go to extensions this._onWillNewSession.fire(session); const openDebug = this.configurationService.getValue<IDebugConfiguration>('debug').openDebug; // Open debug viewlet based on the visibility of the side bar and openDebug setting. Do not open for 'run without debug' if (!configuration.resolved.noDebug && (openDebug === 'openOnSessionStart' || (openDebug === 'openOnFirstSessionStart' && this.viewModel.firstSessionStart))) { this.viewletService.openViewlet(VIEWLET_ID).then(undefined, errors.onUnexpectedError); } return this.launchOrAttachToSession(session).then(() => { const internalConsoleOptions = session.configuration.internalConsoleOptions || this.configurationService.getValue<IDebugConfiguration>('debug').internalConsoleOptions; if (internalConsoleOptions === 'openOnSessionStart' || (this.viewModel.firstSessionStart && internalConsoleOptions === 'openOnFirstSessionStart')) { this.panelService.openPanel(REPL_ID, false); } this.viewModel.firstSessionStart = false; const showSubSessions = this.configurationService.getValue<IDebugConfiguration>('debug').showSubSessionsInToolBar; const sessions = this.model.getSessions(); const shownSessions = showSubSessions ? sessions : sessions.filter(s => !s.parentSession); if (shownSessions.length > 1) { this.viewModel.setMultiSessionView(true); } // since the initialized response has arrived announce the new Session (including extensions) this._onDidNewSession.fire(session); return this.telemetryDebugSessionStart(root, session.configuration.type); }).then(() => true, (error: Error | string) => { if (errors.isPromiseCanceledError(error)) { // don't show 'canceled' error messages to the user #7906 return Promise.resolve(false); } // Show the repl if some error got logged there #5870 if (session && session.getReplElements().length > 0) { this.panelService.openPanel(REPL_ID, false); } if (session.configuration && session.configuration.request === 'attach' && session.configuration.__autoAttach) { // ignore attach timeouts in auto attach mode return Promise.resolve(false); } const errorMessage = error instanceof Error ? error.message : error; this.telemetryDebugMisconfiguration(session.configuration ? session.configuration.type : undefined, errorMessage); return this.showError(errorMessage, isErrorWithActions(error) ? error.actions : []).then(() => false); }); } private launchOrAttachToSession(session: IDebugSession, forceFocus = false): Promise<void> { const dbgr = this.configurationManager.getDebugger(session.configuration.type); return session.initialize(dbgr!).then(() => { return session.launchOrAttach(session.configuration).then(() => { if (forceFocus || !this.viewModel.focusedSession) { this.focusStackFrame(undefined, undefined, session); } }); }).then(undefined, err => { session.shutdown(); return Promise.reject(err); }); } private registerSessionListeners(session: IDebugSession): void { const sessionRunningScheduler = new RunOnceScheduler(() => { // Do not immediatly defocus the stack frame if the session is running if (session.state === State.Running && this.viewModel.focusedSession === session) { this.viewModel.setFocus(undefined, this.viewModel.focusedThread, session, false); } }, 200); this.toDispose.push(session.onDidChangeState(() => { if (session.state === State.Running && this.viewModel.focusedSession === session) { sessionRunningScheduler.schedule(); } if (session === this.viewModel.focusedSession) { this.onStateChange(); } })); this.toDispose.push(session.onDidEndAdapter(adapterExitEvent => { if (adapterExitEvent.error) { this.notificationService.error(nls.localize('debugAdapterCrash', "Debug adapter process has terminated unexpectedly ({0})", adapterExitEvent.error.message || adapterExitEvent.error.toString())); } // 'Run without debugging' mode VSCode must terminate the extension host. More details: #3905 if (isExtensionHostDebugging(session.configuration) && session.state === State.Running && session.configuration.noDebug) { this.extensionHostDebugService.close(session.getId()); } this.telemetryDebugSessionStop(session, adapterExitEvent); if (session.configuration.postDebugTask) { this.runTask(session.root, session.configuration.postDebugTask).then(undefined, err => this.notificationService.error(err) ); } session.shutdown(); this.endInitializingState(); this._onDidEndSession.fire(session); const focusedSession = this.viewModel.focusedSession; if (focusedSession && focusedSession.getId() === session.getId()) { this.focusStackFrame(undefined); } if (this.model.getSessions().length === 0) { this.viewModel.setMultiSessionView(false); if (this.layoutService.isVisible(Parts.SIDEBAR_PART) && this.configurationService.getValue<IDebugConfiguration>('debug').openExplorerOnEnd) { this.viewletService.openViewlet(EXPLORER_VIEWLET_ID); } // Data breakpoints that can not be persisted should be cleared when a session ends const dataBreakpoints = this.model.getDataBreakpoints().filter(dbp => !dbp.canPersist); dataBreakpoints.forEach(dbp => this.model.removeDataBreakpoints(dbp.getId())); } })); } restartSession(session: IDebugSession, restartData?: any): Promise<any> { return this.textFileService.saveAll().then(() => { const isAutoRestart = !!restartData; const runTasks: () => Promise<TaskRunResult> = () => { if (isAutoRestart) { // Do not run preLaunch and postDebug tasks for automatic restarts return Promise.resolve(TaskRunResult.Success); } return this.runTask(session.root, session.configuration.postDebugTask) .then(() => this.runTaskAndCheckErrors(session.root, session.configuration.preLaunchTask)); }; if (session.capabilities.supportsRestartRequest) { return runTasks().then(taskResult => taskResult === TaskRunResult.Success ? session.restart() : undefined); } if (isExtensionHostDebugging(session.configuration)) { return runTasks().then(taskResult => taskResult === TaskRunResult.Success ? this.extensionHostDebugService.reload(session.getId()) : undefined); } const shouldFocus = !!this.viewModel.focusedSession && session.getId() === this.viewModel.focusedSession.getId(); // If the restart is automatic -> disconnect, otherwise -> terminate #55064 return (isAutoRestart ? session.disconnect(true) : session.terminate(true)).then(() => { return new Promise<void>((c, e) => { setTimeout(() => { runTasks().then(taskResult => { if (taskResult !== TaskRunResult.Success) { return; } // Read the configuration again if a launch.json has been changed, if not just use the inmemory configuration let needsToSubstitute = false; let unresolved: IConfig | undefined; const launch = session.root ? this.configurationManager.getLaunch(session.root.uri) : undefined; if (launch) { unresolved = launch.getConfiguration(session.configuration.name); if (unresolved && !equals(unresolved, session.unresolvedConfiguration)) { // Take the type from the session since the debug extension might overwrite it #21316 unresolved.type = session.configuration.type; unresolved.noDebug = session.configuration.noDebug; needsToSubstitute = true; } } let substitutionThenable: Promise<IConfig | null | undefined> = Promise.resolve(session.configuration); if (launch && needsToSubstitute && unresolved) { this.initCancellationToken = new CancellationTokenSource(); substitutionThenable = this.configurationManager.resolveConfigurationByProviders(launch.workspace ? launch.workspace.uri : undefined, unresolved.type, unresolved, this.initCancellationToken.token) .then(resolved => { if (resolved) { // start debugging return this.substituteVariables(launch, resolved); } else if (resolved === null) { // abort debugging silently and open launch.json return Promise.resolve(null); } else { // abort debugging silently return Promise.resolve(undefined); } }); } substitutionThenable.then(resolved => { if (!resolved) { return c(undefined); } session.setConfiguration({ resolved, unresolved }); session.configuration.__restart = restartData; this.launchOrAttachToSession(session, shouldFocus).then(() => { this._onDidNewSession.fire(session); c(undefined); }, err => e(err)); }); }); }, 300); }); }); }); } stopSession(session: IDebugSession): Promise<any> { if (session) { return session.terminate(); } const sessions = this.model.getSessions(); if (sessions.length === 0) { this.endInitializingState(); } return Promise.all(sessions.map(s => s.terminate())); } private substituteVariables(launch: ILaunch | undefined, config: IConfig): Promise<IConfig | undefined> { const dbg = this.configurationManager.getDebugger(config.type); if (dbg) { let folder: IWorkspaceFolder | undefined = undefined; if (launch && launch.workspace) { folder = launch.workspace; } else { const folders = this.contextService.getWorkspace().folders; if (folders.length === 1) { folder = folders[0]; } } return dbg.substituteVariables(folder, config).then(config => { return config; }, (err: Error) => { this.showError(err.message); return undefined; // bail out }); } return Promise.resolve(config); } private showError(message: string, errorActions: ReadonlyArray<IAction> = []): Promise<void> { const configureAction = this.instantiationService.createInstance(debugactions.ConfigureAction, debugactions.ConfigureAction.ID, debugactions.ConfigureAction.LABEL); const actions = [...errorActions, configureAction]; return this.dialogService.show(severity.Error, message, actions.map(a => a.label).concat(nls.localize('cancel', "Cancel")), { cancelId: actions.length }).then(choice => { if (choice < actions.length) { return actions[choice].run(); } return undefined; }); } //---- task management private runTaskAndCheckErrors(root: IWorkspaceFolder | undefined, taskId: string | TaskIdentifier | undefined): Promise<TaskRunResult> { const debugAnywayAction = new Action('debug.debugAnyway', nls.localize('debugAnyway', "Debug Anyway"), undefined, true, () => Promise.resolve(TaskRunResult.Success)); return this.runTask(root, taskId).then((taskSummary: ITaskSummary) => { const errorCount = taskId ? this.markerService.getStatistics().errors : 0; const successExitCode = taskSummary && taskSummary.exitCode === 0; const failureExitCode = taskSummary && taskSummary.exitCode !== undefined && taskSummary.exitCode !== 0; if (successExitCode || (errorCount === 0 && !failureExitCode)) { return <any>TaskRunResult.Success; } const taskLabel = typeof taskId === 'string' ? taskId : taskId ? taskId.name : ''; const message = errorCount > 1 ? nls.localize('preLaunchTaskErrors', "Errors exist after running preLaunchTask '{0}'.", taskLabel) : errorCount === 1 ? nls.localize('preLaunchTaskError', "Error exists after running preLaunchTask '{0}'.", taskLabel) : nls.localize('preLaunchTaskExitCode', "The preLaunchTask '{0}' terminated with exit code {1}.", taskLabel, taskSummary.exitCode); const showErrorsAction = new Action('debug.showErrors', nls.localize('showErrors', "Show Errors"), undefined, true, () => { this.panelService.openPanel(Constants.MARKERS_PANEL_ID); return Promise.resolve(TaskRunResult.Failure); }); return this.showError(message, [debugAnywayAction, showErrorsAction]); }, (err: TaskError) => { return this.showError(err.message, [debugAnywayAction, this.taskService.configureAction()]); }); } private runTask(root: IWorkspaceFolder | undefined, taskId: string | TaskIdentifier | undefined): Promise<ITaskSummary | null> { if (!taskId) { return Promise.resolve(null); } if (!root) { return Promise.reject(new Error(nls.localize('invalidTaskReference', "Task '{0}' can not be referenced from a launch configuration that is in a different workspace folder.", typeof taskId === 'string' ? taskId : taskId.type))); } // run a task before starting a debug session return this.taskService.getTask(root, taskId).then(task => { if (!task) { const errorMessage = typeof taskId === 'string' ? nls.localize('DebugTaskNotFoundWithTaskId', "Could not find the task '{0}'.", taskId) : nls.localize('DebugTaskNotFound', "Could not find the specified task."); return Promise.reject(createErrorWithActions(errorMessage)); } // If a task is missing the problem matcher the promise will never complete, so we need to have a workaround #35340 let taskStarted = false; const promise: Promise<ITaskSummary | null> = this.taskService.getActiveTasks().then(tasks => { if (tasks.filter(t => t._id === task._id).length) { // task is already running - nothing to do. return Promise.resolve(null); } once(e => ((e.kind === TaskEventKind.Active) || (e.kind === TaskEventKind.DependsOnStarted)) && e.taskId === task._id, this.taskService.onDidStateChange)(() => { // Task is active, so everything seems to be fine, no need to prompt after 10 seconds // Use case being a slow running task should not be prompted even though it takes more than 10 seconds taskStarted = true; }); const taskPromise = this.taskService.run(task); if (task.configurationProperties.isBackground) { return new Promise((c, e) => once(e => e.kind === TaskEventKind.Inactive && e.taskId === task._id, this.taskService.onDidStateChange)(() => { taskStarted = true; c(null); })); } return taskPromise; }); return new Promise((c, e) => { promise.then(result => { taskStarted = true; c(result); }, error => e(error)); setTimeout(() => { if (!taskStarted) { const errorMessage = typeof taskId === 'string' ? nls.localize('taskNotTrackedWithTaskId', "The specified task cannot be tracked.") : nls.localize('taskNotTracked', "The task '{0}' cannot be tracked.", JSON.stringify(taskId)); e({ severity: severity.Error, message: errorMessage }); } }, 10000); }); }); } //---- focus management focusStackFrame(stackFrame: IStackFrame | undefined, thread?: IThread, session?: IDebugSession, explicit?: boolean): void { if (!session) { if (stackFrame || thread) { session = stackFrame ? stackFrame.thread.session : thread!.session; } else { const sessions = this.model.getSessions(); const stoppedSession = sessions.filter(s => s.state === State.Stopped).shift(); session = stoppedSession || (sessions.length ? sessions[0] : undefined); } } if (!thread) { if (stackFrame) { thread = stackFrame.thread; } else { const threads = session ? session.getAllThreads() : undefined; const stoppedThread = threads && threads.filter(t => t.stopped).shift(); thread = stoppedThread || (threads && threads.length ? threads[0] : undefined); } } if (!stackFrame) { if (thread) { const callStack = thread.getCallStack(); stackFrame = first(callStack, sf => !!(sf && sf.source && sf.source.available && sf.source.presentationHint !== 'deemphasize'), undefined); } } if (stackFrame) { stackFrame.openInEditor(this.editorService, true).then(editor => { if (editor) { const control = editor.getControl(); if (stackFrame && isCodeEditor(control) && control.hasModel()) { const model = control.getModel(); if (stackFrame.range.startLineNumber <= model.getLineCount()) { const lineContent = control.getModel().getLineContent(stackFrame.range.startLineNumber); aria.alert(nls.localize('debuggingPaused', "Debugging paused {0}, {1} {2} {3}", thread && thread.stoppedDetails ? `, reason ${thread.stoppedDetails.reason}` : '', stackFrame.source ? stackFrame.source.name : '', stackFrame.range.startLineNumber, lineContent)); } } } }); } if (session) { this.debugType.set(session.configuration.type); } else { this.debugType.reset(); } this.viewModel.setFocus(stackFrame, thread, session, !!explicit); } //---- watches addWatchExpression(name: string): void { const we = this.model.addWatchExpression(name); this.viewModel.setSelectedExpression(we); this.storeWatchExpressions(); } renameWatchExpression(id: string, newName: string): void { this.model.renameWatchExpression(id, newName); this.storeWatchExpressions(); } moveWatchExpression(id: string, position: number): void { this.model.moveWatchExpression(id, position); this.storeWatchExpressions(); } removeWatchExpressions(id?: string): void { this.model.removeWatchExpressions(id); this.storeWatchExpressions(); } //---- breakpoints async enableOrDisableBreakpoints(enable: boolean, breakpoint?: IEnablement): Promise<void> { if (breakpoint) { this.model.setEnablement(breakpoint, enable); if (breakpoint instanceof Breakpoint) { await this.sendBreakpoints(breakpoint.uri); } else if (breakpoint instanceof FunctionBreakpoint) { await this.sendFunctionBreakpoints(); } else if (breakpoint instanceof DataBreakpoint) { await this.sendDataBreakpoints(); } else { await this.sendExceptionBreakpoints(); } } else { this.model.enableOrDisableAllBreakpoints(enable); await this.sendAllBreakpoints(); } this.storeBreakpoints(); } async addBreakpoints(uri: uri, rawBreakpoints: IBreakpointData[], context: string): Promise<IBreakpoint[]> { const breakpoints = this.model.addBreakpoints(uri, rawBreakpoints); breakpoints.forEach(bp => aria.status(nls.localize('breakpointAdded', "Added breakpoint, line {0}, file {1}", bp.lineNumber, uri.fsPath))); breakpoints.forEach(bp => this.telemetryDebugAddBreakpoint(bp, context)); await this.sendBreakpoints(uri); this.storeBreakpoints(); return breakpoints; } async updateBreakpoints(uri: uri, data: Map<string, DebugProtocol.Breakpoint>, sendOnResourceSaved: boolean): Promise<void> { this.model.updateBreakpoints(data); if (sendOnResourceSaved) { this.breakpointsToSendOnResourceSaved.add(uri.toString()); } else { await this.sendBreakpoints(uri); } this.storeBreakpoints(); } async removeBreakpoints(id?: string): Promise<void> { const toRemove = this.model.getBreakpoints().filter(bp => !id || bp.getId() === id); toRemove.forEach(bp => aria.status(nls.localize('breakpointRemoved', "Removed breakpoint, line {0}, file {1}", bp.lineNumber, bp.uri.fsPath))); const urisToClear = distinct(toRemove, bp => bp.uri.toString()).map(bp => bp.uri); this.model.removeBreakpoints(toRemove); await Promise.all(urisToClear.map(uri => this.sendBreakpoints(uri))); this.storeBreakpoints(); } setBreakpointsActivated(activated: boolean): Promise<void> { this.model.setBreakpointsActivated(activated); if (activated) { this.storageService.store(DEBUG_BREAKPOINTS_ACTIVATED_KEY, 'false', StorageScope.WORKSPACE); } else { this.storageService.remove(DEBUG_BREAKPOINTS_ACTIVATED_KEY, StorageScope.WORKSPACE); } return this.sendAllBreakpoints(); } addFunctionBreakpoint(name?: string, id?: string): void { const newFunctionBreakpoint = this.model.addFunctionBreakpoint(name || '', id); this.viewModel.setSelectedFunctionBreakpoint(newFunctionBreakpoint); } async renameFunctionBreakpoint(id: string, newFunctionName: string): Promise<void> { this.model.renameFunctionBreakpoint(id, newFunctionName); await this.sendFunctionBreakpoints(); this.storeBreakpoints(); } async removeFunctionBreakpoints(id?: string): Promise<void> { this.model.removeFunctionBreakpoints(id); await this.sendFunctionBreakpoints(); this.storeBreakpoints(); } async addDataBreakpoint(label: string, dataId: string, canPersist: boolean): Promise<void> { this.model.addDataBreakpoint(label, dataId, canPersist); await this.sendDataBreakpoints(); this.storeBreakpoints(); } async removeDataBreakpoints(id?: string): Promise<void> { this.model.removeDataBreakpoints(id); await this.sendDataBreakpoints(); this.storeBreakpoints(); } sendAllBreakpoints(session?: IDebugSession): Promise<any> { return Promise.all(distinct(this.model.getBreakpoints(), bp => bp.uri.toString()).map(bp => this.sendBreakpoints(bp.uri, false, session))) .then(() => this.sendFunctionBreakpoints(session)) // send exception breakpoints at the end since some debug adapters rely on the order .then(() => this.sendExceptionBreakpoints(session)) .then(() => this.sendDataBreakpoints(session)); } private sendBreakpoints(modelUri: uri, sourceModified = false, session?: IDebugSession): Promise<void> { const breakpointsToSend = this.model.getBreakpoints({ uri: modelUri, enabledOnly: true }); return this.sendToOneOrAllSessions(session, s => s.sendBreakpoints(modelUri, breakpointsToSend, sourceModified) ); } private sendFunctionBreakpoints(session?: IDebugSession): Promise<void> { const breakpointsToSend = this.model.getFunctionBreakpoints().filter(fbp => fbp.enabled && this.model.areBreakpointsActivated()); return this.sendToOneOrAllSessions(session, s => { return s.capabilities.supportsFunctionBreakpoints ? s.sendFunctionBreakpoints(breakpointsToSend) : Promise.resolve(undefined); }); } private sendDataBreakpoints(session?: IDebugSession): Promise<void> { const breakpointsToSend = this.model.getDataBreakpoints().filter(fbp => fbp.enabled && this.model.areBreakpointsActivated()); return this.sendToOneOrAllSessions(session, s => { return s.capabilities.supportsDataBreakpoints ? s.sendDataBreakpoints(breakpointsToSend) : Promise.resolve(undefined); }); } private sendExceptionBreakpoints(session?: IDebugSession): Promise<void> { const enabledExceptionBps = this.model.getExceptionBreakpoints().filter(exb => exb.enabled); return this.sendToOneOrAllSessions(session, s => { return s.sendExceptionBreakpoints(enabledExceptionBps); }); } private sendToOneOrAllSessions(session: IDebugSession | undefined, send: (session: IDebugSession) => Promise<void>): Promise<void> { if (session) { return send(session); } return Promise.all(this.model.getSessions().map(s => send(s))).then(() => undefined); } private onFileChanges(fileChangesEvent: FileChangesEvent): void { const toRemove = this.model.getBreakpoints().filter(bp => fileChangesEvent.contains(bp.uri, FileChangeType.DELETED)); if (toRemove.length) { this.model.removeBreakpoints(toRemove); } fileChangesEvent.getUpdated().forEach(event => { if (this.breakpointsToSendOnResourceSaved.delete(event.resource.toString())) { this.sendBreakpoints(event.resource, true); } }); } private loadBreakpoints(): Breakpoint[] { let result: Breakpoint[] | undefined; try { result = JSON.parse(this.storageService.get(DEBUG_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((breakpoint: any) => { return new Breakpoint(uri.parse(breakpoint.uri.external || breakpoint.source.uri.external), breakpoint.lineNumber, breakpoint.column, breakpoint.enabled, breakpoint.condition, breakpoint.hitCondition, breakpoint.logMessage, breakpoint.adapterData, this.textFileService); }); } catch (e) { } return result || []; } private loadFunctionBreakpoints(): FunctionBreakpoint[] { let result: FunctionBreakpoint[] | undefined; try { result = JSON.parse(this.storageService.get(DEBUG_FUNCTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((fb: any) => { return new FunctionBreakpoint(fb.name, fb.enabled, fb.hitCondition, fb.condition, fb.logMessage); }); } catch (e) { } return result || []; } private loadExceptionBreakpoints(): ExceptionBreakpoint[] { let result: ExceptionBreakpoint[] | undefined; try { result = JSON.parse(this.storageService.get(DEBUG_EXCEPTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((exBreakpoint: any) => { return new ExceptionBreakpoint(exBreakpoint.filter, exBreakpoint.label, exBreakpoint.enabled); }); } catch (e) { } return result || []; } private loadDataBreakpoints(): DataBreakpoint[] { let result: DataBreakpoint[] | undefined; try { result = JSON.parse(this.storageService.get(DEBUG_DATA_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((dbp: any) => { return new DataBreakpoint(dbp.label, dbp.dataId, true, dbp.enabled, dbp.hitCondition, dbp.condition, dbp.logMessage); }); } catch (e) { } return result || []; } private loadWatchExpressions(): Expression[] { let result: Expression[] | undefined; try { result = JSON.parse(this.storageService.get(DEBUG_WATCH_EXPRESSIONS_KEY, StorageScope.WORKSPACE, '[]')).map((watchStoredData: { name: string, id: string }) => { return new Expression(watchStoredData.name, watchStoredData.id); }); } catch (e) { } return result || []; } private storeWatchExpressions(): void { const watchExpressions = this.model.getWatchExpressions(); if (watchExpressions.length) { this.storageService.store(DEBUG_WATCH_EXPRESSIONS_KEY, JSON.stringify(watchExpressions.map(we => ({ name: we.name, id: we.getId() }))), StorageScope.WORKSPACE); } else { this.storageService.remove(DEBUG_WATCH_EXPRESSIONS_KEY, StorageScope.WORKSPACE); } } private storeBreakpoints(): void { const breakpoints = this.model.getBreakpoints(); if (breakpoints.length) { this.storageService.store(DEBUG_BREAKPOINTS_KEY, JSON.stringify(breakpoints), StorageScope.WORKSPACE); } else { this.storageService.remove(DEBUG_BREAKPOINTS_KEY, StorageScope.WORKSPACE); } const functionBreakpoints = this.model.getFunctionBreakpoints(); if (functionBreakpoints.length) { this.storageService.store(DEBUG_FUNCTION_BREAKPOINTS_KEY, JSON.stringify(functionBreakpoints), StorageScope.WORKSPACE); } else { this.storageService.remove(DEBUG_FUNCTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE); } const dataBreakpoints = this.model.getDataBreakpoints().filter(dbp => dbp.canPersist); if (dataBreakpoints.length) { this.storageService.store(DEBUG_DATA_BREAKPOINTS_KEY, JSON.stringify(dataBreakpoints), StorageScope.WORKSPACE); } else { this.storageService.remove(DEBUG_DATA_BREAKPOINTS_KEY, StorageScope.WORKSPACE); } const exceptionBreakpoints = this.model.getExceptionBreakpoints(); if (exceptionBreakpoints.length) { this.storageService.store(DEBUG_EXCEPTION_BREAKPOINTS_KEY, JSON.stringify(exceptionBreakpoints), StorageScope.WORKSPACE); } else { this.storageService.remove(DEBUG_EXCEPTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE); } } //---- telemetry private telemetryDebugSessionStart(root: IWorkspaceFolder | undefined, type: string): Promise<void> { const dbgr = this.configurationManager.getDebugger(type); if (!dbgr) { return Promise.resolve(); } const extension = dbgr.getMainExtensionDescriptor(); /* __GDPR__ "debugSessionStart" : { "type": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "breakpointCount": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "exceptionBreakpoints": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "watchExpressionsCount": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "extensionName": { "classification": "PublicNonPersonalData", "purpose": "FeatureInsight" }, "isBuiltin": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true}, "launchJsonExists": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true } } */ return this.telemetryService.publicLog('debugSessionStart', { type: type, breakpointCount: this.model.getBreakpoints().length, exceptionBreakpoints: this.model.getExceptionBreakpoints(), watchExpressionsCount: this.model.getWatchExpressions().length, extensionName: extension.identifier.value, isBuiltin: extension.isBuiltin, launchJsonExists: root && !!this.configurationService.getValue<IGlobalConfig>('launch', { resource: root.uri }) }); } private telemetryDebugSessionStop(session: IDebugSession, adapterExitEvent: AdapterEndEvent): Promise<any> { const breakpoints = this.model.getBreakpoints(); /* __GDPR__ "debugSessionStop" : { "type" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "success": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "sessionLengthInSeconds": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "breakpointCount": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "watchExpressionsCount": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true } } */ return this.telemetryService.publicLog('debugSessionStop', { type: session && session.configuration.type, success: adapterExitEvent.emittedStopped || breakpoints.length === 0, sessionLengthInSeconds: adapterExitEvent.sessionLengthInSeconds, breakpointCount: breakpoints.length, watchExpressionsCount: this.model.getWatchExpressions().length }); } private telemetryDebugMisconfiguration(debugType: string | undefined, message: string): Promise<any> { /* __GDPR__ "debugMisconfiguration" : { "type" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "error": { "classification": "CallstackOrException", "purpose": "FeatureInsight" } } */ return this.telemetryService.publicLog('debugMisconfiguration', { type: debugType, error: message }); } private telemetryDebugAddBreakpoint(breakpoint: IBreakpoint, context: string): Promise<any> { /* __GDPR__ "debugAddBreakpoint" : { "context": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "hasCondition": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "hasHitCondition": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "hasLogMessage": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true } } */ return this.telemetryService.publicLog('debugAddBreakpoint', { context: context, hasCondition: !!breakpoint.condition, hasHitCondition: !!breakpoint.hitCondition, hasLogMessage: !!breakpoint.logMessage }); } }
src/vs/workbench/contrib/debug/browser/debugService.ts
1
https://github.com/microsoft/vscode/commit/20e24e879acc220cbb9b365001b5d1427824edaf
[ 0.9993869066238403, 0.10101892799139023, 0.00016697407409083098, 0.00018000722047872841, 0.30064335465431213 ]
{ "id": 0, "code_window": [ "import { CancellationTokenSource } from 'vs/base/common/cancellation';\n", "\n", "const DEBUG_BREAKPOINTS_KEY = 'debug.breakpoint';\n", "const DEBUG_BREAKPOINTS_ACTIVATED_KEY = 'debug.breakpointactivated';\n", "const DEBUG_FUNCTION_BREAKPOINTS_KEY = 'debug.functionbreakpoint';\n", "const DEBUG_DATA_BREAKPOINTS_KEY = 'debug.databreakpoint';\n", "const DEBUG_EXCEPTION_BREAKPOINTS_KEY = 'debug.exceptionbreakpoint';\n", "const DEBUG_WATCH_EXPRESSIONS_KEY = 'debug.watchexpressions';\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/debug/browser/debugService.ts", "type": "replace", "edit_start_line_idx": 52 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { IInstantiationService, IConstructorSignature0, ServicesAccessor } from 'vs/platform/instantiation/common/instantiation'; import { ILifecycleService, LifecyclePhase } from 'vs/platform/lifecycle/common/lifecycle'; import { Registry } from 'vs/platform/registry/common/platform'; import { runWhenIdle, IdleDeadline } from 'vs/base/common/async'; /** * A workbench contribution that will be loaded when the workbench starts and disposed when the workbench shuts down. */ export interface IWorkbenchContribution { // Marker Interface } export namespace Extensions { export const Workbench = 'workbench.contributions.kind'; } export type IWorkbenchContributionSignature = IConstructorSignature0<IWorkbenchContribution>; export interface IWorkbenchContributionsRegistry { /** * Registers a workbench contribution to the platform that will be loaded when the workbench starts and disposed when * the workbench shuts down. * * @param phase the lifecycle phase when to instantiate the contribution. */ registerWorkbenchContribution(contribution: IWorkbenchContributionSignature, phase: LifecyclePhase): void; /** * Starts the registry by providing the required services. */ start(accessor: ServicesAccessor): void; } class WorkbenchContributionsRegistry implements IWorkbenchContributionsRegistry { private instantiationService: IInstantiationService | undefined; private lifecycleService: ILifecycleService | undefined; private readonly toBeInstantiated: Map<LifecyclePhase, IConstructorSignature0<IWorkbenchContribution>[]> = new Map<LifecyclePhase, IConstructorSignature0<IWorkbenchContribution>[]>(); registerWorkbenchContribution(ctor: IWorkbenchContributionSignature, phase: LifecyclePhase = LifecyclePhase.Starting): void { // Instantiate directly if we are already matching the provided phase if (this.instantiationService && this.lifecycleService && this.lifecycleService.phase >= phase) { this.instantiationService.createInstance(ctor); } // Otherwise keep contributions by lifecycle phase else { let toBeInstantiated = this.toBeInstantiated.get(phase); if (!toBeInstantiated) { toBeInstantiated = []; this.toBeInstantiated.set(phase, toBeInstantiated); } toBeInstantiated.push(ctor); } } start(accessor: ServicesAccessor): void { this.instantiationService = accessor.get(IInstantiationService); this.lifecycleService = accessor.get(ILifecycleService); [LifecyclePhase.Starting, LifecyclePhase.Ready, LifecyclePhase.Restored, LifecyclePhase.Eventually].forEach(phase => { this.instantiateByPhase(this.instantiationService!, this.lifecycleService!, phase); }); } private instantiateByPhase(instantiationService: IInstantiationService, lifecycleService: ILifecycleService, phase: LifecyclePhase): void { // Instantiate contributions directly when phase is already reached if (lifecycleService.phase >= phase) { this.doInstantiateByPhase(instantiationService, phase); } // Otherwise wait for phase to be reached else { lifecycleService.when(phase).then(() => this.doInstantiateByPhase(instantiationService, phase)); } } private doInstantiateByPhase(instantiationService: IInstantiationService, phase: LifecyclePhase): void { const toBeInstantiated = this.toBeInstantiated.get(phase); if (toBeInstantiated) { this.toBeInstantiated.delete(phase); if (phase !== LifecyclePhase.Eventually) { // instantiate everything synchronously and blocking for (const ctor of toBeInstantiated) { instantiationService.createInstance(ctor); } } else { // for the Eventually-phase we instantiate contributions // only when idle. this might take a few idle-busy-cycles // but will finish within the timeouts let forcedTimeout = 3000; let i = 0; let instantiateSome = (idle: IdleDeadline) => { while (i < toBeInstantiated.length) { const ctor = toBeInstantiated[i++]; instantiationService.createInstance(ctor); if (idle.timeRemaining() < 1) { // time is up -> reschedule runWhenIdle(instantiateSome, forcedTimeout); break; } } }; runWhenIdle(instantiateSome, forcedTimeout); } } } } Registry.add(Extensions.Workbench, new WorkbenchContributionsRegistry());
src/vs/workbench/common/contributions.ts
0
https://github.com/microsoft/vscode/commit/20e24e879acc220cbb9b365001b5d1427824edaf
[ 0.0002819235669448972, 0.00019025662913918495, 0.0001639722177060321, 0.00018123036716133356, 0.00003101866241195239 ]
{ "id": 0, "code_window": [ "import { CancellationTokenSource } from 'vs/base/common/cancellation';\n", "\n", "const DEBUG_BREAKPOINTS_KEY = 'debug.breakpoint';\n", "const DEBUG_BREAKPOINTS_ACTIVATED_KEY = 'debug.breakpointactivated';\n", "const DEBUG_FUNCTION_BREAKPOINTS_KEY = 'debug.functionbreakpoint';\n", "const DEBUG_DATA_BREAKPOINTS_KEY = 'debug.databreakpoint';\n", "const DEBUG_EXCEPTION_BREAKPOINTS_KEY = 'debug.exceptionbreakpoint';\n", "const DEBUG_WATCH_EXPRESSIONS_KEY = 'debug.watchexpressions';\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/debug/browser/debugService.ts", "type": "replace", "edit_start_line_idx": 52 }
{ "Region Start": { "prefix": "#region", "body": [ "#region $0" ], "description": "Folding Region Start" }, "Region End": { "prefix": "#endregion", "body": [ "#endregion" ], "description": "Folding Region End" } }
extensions/csharp/snippets/csharp.json
0
https://github.com/microsoft/vscode/commit/20e24e879acc220cbb9b365001b5d1427824edaf
[ 0.00029339970205910504, 0.00027028139447793365, 0.00024716308689676225, 0.00027028139447793365, 0.000023118307581171393 ]
{ "id": 0, "code_window": [ "import { CancellationTokenSource } from 'vs/base/common/cancellation';\n", "\n", "const DEBUG_BREAKPOINTS_KEY = 'debug.breakpoint';\n", "const DEBUG_BREAKPOINTS_ACTIVATED_KEY = 'debug.breakpointactivated';\n", "const DEBUG_FUNCTION_BREAKPOINTS_KEY = 'debug.functionbreakpoint';\n", "const DEBUG_DATA_BREAKPOINTS_KEY = 'debug.databreakpoint';\n", "const DEBUG_EXCEPTION_BREAKPOINTS_KEY = 'debug.exceptionbreakpoint';\n", "const DEBUG_WATCH_EXPRESSIONS_KEY = 'debug.watchexpressions';\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/debug/browser/debugService.ts", "type": "replace", "edit_start_line_idx": 52 }
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M15 4H10V3H15V4ZM14 7H12V8H14V7ZM10 7H1V8H10V7ZM12 13H1V14H12V13ZM7 10H1V11H7V10ZM15 10H10V11H15V10ZM8 2V5H1V2H8ZM7 3H2V4H7V3Z" fill="#C5C5C5"/> </svg>
src/vs/editor/contrib/suggest/media/keyword-dark.svg
0
https://github.com/microsoft/vscode/commit/20e24e879acc220cbb9b365001b5d1427824edaf
[ 0.0001728561328491196, 0.0001728561328491196, 0.0001728561328491196, 0.0001728561328491196, 0 ]
{ "id": 1, "code_window": [ "\t\tthis.debugType = CONTEXT_DEBUG_TYPE.bindTo(contextKeyService);\n", "\t\tthis.debugState = CONTEXT_DEBUG_STATE.bindTo(contextKeyService);\n", "\t\tthis.inDebugMode = CONTEXT_IN_DEBUG_MODE.bindTo(contextKeyService);\n", "\n", "\t\tthis.model = new DebugModel(this.loadBreakpoints(), this.storageService.getBoolean(DEBUG_BREAKPOINTS_ACTIVATED_KEY, StorageScope.WORKSPACE, true), this.loadFunctionBreakpoints(),\n", "\t\t\tthis.loadExceptionBreakpoints(), this.loadDataBreakpoints(), this.loadWatchExpressions(), this.textFileService);\n", "\t\tthis.toDispose.push(this.model);\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis.model = new DebugModel(this.loadBreakpoints(), this.loadFunctionBreakpoints(),\n" ], "file_path": "src/vs/workbench/contrib/debug/browser/debugService.ts", "type": "replace", "edit_start_line_idx": 131 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as nls from 'vs/nls'; import { Event, Emitter } from 'vs/base/common/event'; import { URI as uri } from 'vs/base/common/uri'; import { first, distinct } from 'vs/base/common/arrays'; import * as errors from 'vs/base/common/errors'; import severity from 'vs/base/common/severity'; import * as aria from 'vs/base/browser/ui/aria/aria'; import { IContextKeyService, IContextKey } from 'vs/platform/contextkey/common/contextkey'; import { IMarkerService } from 'vs/platform/markers/common/markers'; import { ILifecycleService } from 'vs/platform/lifecycle/common/lifecycle'; import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { FileChangesEvent, FileChangeType, IFileService } from 'vs/platform/files/common/files'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage'; import { DebugModel, ExceptionBreakpoint, FunctionBreakpoint, Breakpoint, Expression, DataBreakpoint } from 'vs/workbench/contrib/debug/common/debugModel'; import { ViewModel } from 'vs/workbench/contrib/debug/common/debugViewModel'; import * as debugactions from 'vs/workbench/contrib/debug/browser/debugActions'; import { ConfigurationManager } from 'vs/workbench/contrib/debug/browser/debugConfigurationManager'; import Constants from 'vs/workbench/contrib/markers/browser/constants'; import { ITaskService, ITaskSummary } from 'vs/workbench/contrib/tasks/common/taskService'; import { TaskError } from 'vs/workbench/contrib/tasks/common/taskSystem'; import { VIEWLET_ID as EXPLORER_VIEWLET_ID } from 'vs/workbench/contrib/files/common/files'; import { IViewletService } from 'vs/workbench/services/viewlet/browser/viewlet'; import { IPanelService } from 'vs/workbench/services/panel/common/panelService'; import { IWorkbenchLayoutService, Parts } from 'vs/workbench/services/layout/browser/layoutService'; import { ITextFileService } from 'vs/workbench/services/textfile/common/textfiles'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IWorkspaceContextService, WorkbenchState, IWorkspaceFolder } from 'vs/platform/workspace/common/workspace'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { parse, getFirstFrame } from 'vs/base/common/console'; import { TaskEvent, TaskEventKind, TaskIdentifier } from 'vs/workbench/contrib/tasks/common/tasks'; import { IDialogService } from 'vs/platform/dialogs/common/dialogs'; import { INotificationService } from 'vs/platform/notification/common/notification'; import { IAction, Action } from 'vs/base/common/actions'; import { deepClone, equals } from 'vs/base/common/objects'; import { DebugSession } from 'vs/workbench/contrib/debug/browser/debugSession'; import { dispose, IDisposable } from 'vs/base/common/lifecycle'; import { IDebugService, State, IDebugSession, CONTEXT_DEBUG_TYPE, CONTEXT_DEBUG_STATE, CONTEXT_IN_DEBUG_MODE, IThread, IDebugConfiguration, VIEWLET_ID, REPL_ID, IConfig, ILaunch, IViewModel, IConfigurationManager, IDebugModel, IEnablement, IBreakpoint, IBreakpointData, ICompound, IGlobalConfig, IStackFrame, AdapterEndEvent, getStateLabel } from 'vs/workbench/contrib/debug/common/debug'; import { isExtensionHostDebugging } from 'vs/workbench/contrib/debug/common/debugUtils'; import { isErrorWithActions, createErrorWithActions } from 'vs/base/common/errorsWithActions'; import { RunOnceScheduler } from 'vs/base/common/async'; import { IExtensionHostDebugService } from 'vs/platform/debug/common/extensionHostDebug'; import { isCodeEditor } from 'vs/editor/browser/editorBrowser'; import { CancellationTokenSource } from 'vs/base/common/cancellation'; const DEBUG_BREAKPOINTS_KEY = 'debug.breakpoint'; const DEBUG_BREAKPOINTS_ACTIVATED_KEY = 'debug.breakpointactivated'; const DEBUG_FUNCTION_BREAKPOINTS_KEY = 'debug.functionbreakpoint'; const DEBUG_DATA_BREAKPOINTS_KEY = 'debug.databreakpoint'; const DEBUG_EXCEPTION_BREAKPOINTS_KEY = 'debug.exceptionbreakpoint'; const DEBUG_WATCH_EXPRESSIONS_KEY = 'debug.watchexpressions'; function once(match: (e: TaskEvent) => boolean, event: Event<TaskEvent>): Event<TaskEvent> { return (listener, thisArgs = null, disposables?) => { const result = event(e => { if (match(e)) { result.dispose(); return listener.call(thisArgs, e); } }, null, disposables); return result; }; } const enum TaskRunResult { Failure, Success } export class DebugService implements IDebugService { _serviceBrand: any; private readonly _onDidChangeState: Emitter<State>; private readonly _onDidNewSession: Emitter<IDebugSession>; private readonly _onWillNewSession: Emitter<IDebugSession>; private readonly _onDidEndSession: Emitter<IDebugSession>; private model: DebugModel; private viewModel: ViewModel; private configurationManager: ConfigurationManager; private toDispose: IDisposable[]; private debugType: IContextKey<string>; private debugState: IContextKey<string>; private inDebugMode: IContextKey<boolean>; private breakpointsToSendOnResourceSaved: Set<string>; private initializing = false; private previousState: State | undefined; private initCancellationToken: CancellationTokenSource | undefined; constructor( @IStorageService private readonly storageService: IStorageService, @IEditorService private readonly editorService: IEditorService, @ITextFileService private readonly textFileService: ITextFileService, @IViewletService private readonly viewletService: IViewletService, @IPanelService private readonly panelService: IPanelService, @INotificationService private readonly notificationService: INotificationService, @IDialogService private readonly dialogService: IDialogService, @IWorkbenchLayoutService private readonly layoutService: IWorkbenchLayoutService, @ITelemetryService private readonly telemetryService: ITelemetryService, @IWorkspaceContextService private readonly contextService: IWorkspaceContextService, @IContextKeyService contextKeyService: IContextKeyService, @ILifecycleService private readonly lifecycleService: ILifecycleService, @IInstantiationService private readonly instantiationService: IInstantiationService, @IExtensionService private readonly extensionService: IExtensionService, @IMarkerService private readonly markerService: IMarkerService, @ITaskService private readonly taskService: ITaskService, @IFileService private readonly fileService: IFileService, @IConfigurationService private readonly configurationService: IConfigurationService, @IExtensionHostDebugService private readonly extensionHostDebugService: IExtensionHostDebugService ) { this.toDispose = []; this.breakpointsToSendOnResourceSaved = new Set<string>(); this._onDidChangeState = new Emitter<State>(); this._onDidNewSession = new Emitter<IDebugSession>(); this._onWillNewSession = new Emitter<IDebugSession>(); this._onDidEndSession = new Emitter<IDebugSession>(); this.configurationManager = this.instantiationService.createInstance(ConfigurationManager, this); this.toDispose.push(this.configurationManager); this.debugType = CONTEXT_DEBUG_TYPE.bindTo(contextKeyService); this.debugState = CONTEXT_DEBUG_STATE.bindTo(contextKeyService); this.inDebugMode = CONTEXT_IN_DEBUG_MODE.bindTo(contextKeyService); this.model = new DebugModel(this.loadBreakpoints(), this.storageService.getBoolean(DEBUG_BREAKPOINTS_ACTIVATED_KEY, StorageScope.WORKSPACE, true), this.loadFunctionBreakpoints(), this.loadExceptionBreakpoints(), this.loadDataBreakpoints(), this.loadWatchExpressions(), this.textFileService); this.toDispose.push(this.model); this.viewModel = new ViewModel(contextKeyService); this.toDispose.push(this.fileService.onFileChanges(e => this.onFileChanges(e))); this.lifecycleService.onShutdown(this.dispose, this); this.toDispose.push(this.extensionHostDebugService.onAttachSession(event => { const session = this.model.getSession(event.sessionId, true); if (session) { // EH was started in debug mode -> attach to it session.configuration.request = 'attach'; session.configuration.port = event.port; session.setSubId(event.subId); this.launchOrAttachToSession(session).then(undefined, errors.onUnexpectedError); } })); this.toDispose.push(this.extensionHostDebugService.onTerminateSession(event => { const session = this.model.getSession(event.sessionId); if (session && session.subId === event.subId) { session.disconnect().then(undefined, errors.onUnexpectedError); } })); this.toDispose.push(this.extensionHostDebugService.onLogToSession(event => { const session = this.model.getSession(event.sessionId, true); if (session) { // extension logged output -> show it in REPL const sev = event.log.severity === 'warn' ? severity.Warning : event.log.severity === 'error' ? severity.Error : severity.Info; const { args, stack } = parse(event.log); const frame = !!stack ? getFirstFrame(stack) : undefined; session.logToRepl(sev, args, frame); } })); this.toDispose.push(this.viewModel.onDidFocusStackFrame(() => { this.onStateChange(); })); this.toDispose.push(this.viewModel.onDidFocusSession(session => { const id = session ? session.getId() : undefined; this.model.setBreakpointsSessionId(id); this.onStateChange(); })); } getModel(): IDebugModel { return this.model; } getViewModel(): IViewModel { return this.viewModel; } getConfigurationManager(): IConfigurationManager { return this.configurationManager; } sourceIsNotAvailable(uri: uri): void { this.model.sourceIsNotAvailable(uri); } dispose(): void { this.toDispose = dispose(this.toDispose); } //---- state management get state(): State { const focusedSession = this.viewModel.focusedSession; if (focusedSession) { return focusedSession.state; } return this.initializing ? State.Initializing : State.Inactive; } private startInitializingState() { if (!this.initializing) { this.initializing = true; this.onStateChange(); } } private endInitializingState() { if (this.initCancellationToken) { this.initCancellationToken.cancel(); this.initCancellationToken = undefined; } if (this.initializing) { this.initializing = false; this.onStateChange(); } } private onStateChange(): void { const state = this.state; if (this.previousState !== state) { this.debugState.set(getStateLabel(state)); this.inDebugMode.set(state !== State.Inactive); this.previousState = state; this._onDidChangeState.fire(state); } } get onDidChangeState(): Event<State> { return this._onDidChangeState.event; } get onDidNewSession(): Event<IDebugSession> { return this._onDidNewSession.event; } get onWillNewSession(): Event<IDebugSession> { return this._onWillNewSession.event; } get onDidEndSession(): Event<IDebugSession> { return this._onDidEndSession.event; } //---- life cycle management /** * main entry point * properly manages compounds, checks for errors and handles the initializing state. */ startDebugging(launch: ILaunch | undefined, configOrName?: IConfig | string, noDebug = false, parentSession?: IDebugSession): Promise<boolean> { this.startInitializingState(); // make sure to save all files and that the configuration is up to date return this.extensionService.activateByEvent('onDebug').then(() => { return this.textFileService.saveAll().then(() => this.configurationService.reloadConfiguration(launch ? launch.workspace : undefined).then(() => { return this.extensionService.whenInstalledExtensionsRegistered().then(() => { let config: IConfig | undefined; let compound: ICompound | undefined; if (!configOrName) { configOrName = this.configurationManager.selectedConfiguration.name; } if (typeof configOrName === 'string' && launch) { config = launch.getConfiguration(configOrName); compound = launch.getCompound(configOrName); const sessions = this.model.getSessions(); const alreadyRunningMessage = nls.localize('configurationAlreadyRunning', "There is already a debug configuration \"{0}\" running.", configOrName); if (sessions.some(s => s.configuration.name === configOrName && (!launch || !launch.workspace || !s.root || s.root.uri.toString() === launch.workspace.uri.toString()))) { return Promise.reject(new Error(alreadyRunningMessage)); } if (compound && compound.configurations && sessions.some(p => compound!.configurations.indexOf(p.configuration.name) !== -1)) { return Promise.reject(new Error(alreadyRunningMessage)); } } else if (typeof configOrName !== 'string') { config = configOrName; } if (compound) { // we are starting a compound debug, first do some error checking and than start each configuration in the compound if (!compound.configurations) { return Promise.reject(new Error(nls.localize({ key: 'compoundMustHaveConfigurations', comment: ['compound indicates a "compounds" configuration item', '"configurations" is an attribute and should not be localized'] }, "Compound must have \"configurations\" attribute set in order to start multiple configurations."))); } return Promise.all(compound.configurations.map(configData => { const name = typeof configData === 'string' ? configData : configData.name; if (name === compound!.name) { return Promise.resolve(false); } let launchForName: ILaunch | undefined; if (typeof configData === 'string') { const launchesContainingName = this.configurationManager.getLaunches().filter(l => !!l.getConfiguration(name)); if (launchesContainingName.length === 1) { launchForName = launchesContainingName[0]; } else if (launch && launchesContainingName.length > 1 && launchesContainingName.indexOf(launch) >= 0) { // If there are multiple launches containing the configuration give priority to the configuration in the current launch launchForName = launch; } else { return Promise.reject(new Error(launchesContainingName.length === 0 ? nls.localize('noConfigurationNameInWorkspace', "Could not find launch configuration '{0}' in the workspace.", name) : nls.localize('multipleConfigurationNamesInWorkspace', "There are multiple launch configurations '{0}' in the workspace. Use folder name to qualify the configuration.", name))); } } else if (configData.folder) { const launchesMatchingConfigData = this.configurationManager.getLaunches().filter(l => l.workspace && l.workspace.name === configData.folder && !!l.getConfiguration(configData.name)); if (launchesMatchingConfigData.length === 1) { launchForName = launchesMatchingConfigData[0]; } else { return Promise.reject(new Error(nls.localize('noFolderWithName', "Can not find folder with name '{0}' for configuration '{1}' in compound '{2}'.", configData.folder, configData.name, compound!.name))); } } return this.createSession(launchForName, launchForName!.getConfiguration(name), noDebug, parentSession); })).then(values => values.every(success => !!success)); // Compound launch is a success only if each configuration launched successfully } if (configOrName && !config) { const message = !!launch ? nls.localize('configMissing', "Configuration '{0}' is missing in 'launch.json'.", typeof configOrName === 'string' ? configOrName : JSON.stringify(configOrName)) : nls.localize('launchJsonDoesNotExist', "'launch.json' does not exist."); return Promise.reject(new Error(message)); } return this.createSession(launch, config, noDebug, parentSession); }); })); }).then(success => { // make sure to get out of initializing state, and propagate the result this.endInitializingState(); return success; }, err => { this.endInitializingState(); return Promise.reject(err); }); } /** * gets the debugger for the type, resolves configurations by providers, substitutes variables and runs prelaunch tasks */ private createSession(launch: ILaunch | undefined, config: IConfig | undefined, noDebug: boolean, parentSession?: IDebugSession): Promise<boolean> { // We keep the debug type in a separate variable 'type' so that a no-folder config has no attributes. // Storing the type in the config would break extensions that assume that the no-folder case is indicated by an empty config. let type: string | undefined; if (config) { type = config.type; } else { // a no-folder workspace has no launch.config config = Object.create(null); } const unresolvedConfig = deepClone(config); if (noDebug) { config!.noDebug = true; } const debuggerThenable: Promise<void> = type ? Promise.resolve() : this.configurationManager.guessDebugger().then(dbgr => { type = dbgr && dbgr.type; }); return debuggerThenable.then(() => { this.initCancellationToken = new CancellationTokenSource(); return this.configurationManager.resolveConfigurationByProviders(launch && launch.workspace ? launch.workspace.uri : undefined, type, config!, this.initCancellationToken.token).then(config => { // a falsy config indicates an aborted launch if (config && config.type) { return this.substituteVariables(launch, config).then(resolvedConfig => { if (!resolvedConfig) { // User canceled resolving of interactive variables, silently return return false; } if (!this.configurationManager.getDebugger(resolvedConfig.type) || (config.request !== 'attach' && config.request !== 'launch')) { let message: string; if (config.request !== 'attach' && config.request !== 'launch') { message = config.request ? nls.localize('debugRequestNotSupported', "Attribute '{0}' has an unsupported value '{1}' in the chosen debug configuration.", 'request', config.request) : nls.localize('debugRequesMissing', "Attribute '{0}' is missing from the chosen debug configuration.", 'request'); } else { message = resolvedConfig.type ? nls.localize('debugTypeNotSupported', "Configured debug type '{0}' is not supported.", resolvedConfig.type) : nls.localize('debugTypeMissing', "Missing property 'type' for the chosen launch configuration."); } return this.showError(message).then(() => false); } const workspace = launch ? launch.workspace : undefined; return this.runTaskAndCheckErrors(workspace, resolvedConfig.preLaunchTask).then(result => { if (result === TaskRunResult.Success) { return this.doCreateSession(workspace, { resolved: resolvedConfig, unresolved: unresolvedConfig }, parentSession); } return false; }); }, err => { if (err && err.message) { return this.showError(err.message).then(() => false); } if (this.contextService.getWorkbenchState() === WorkbenchState.EMPTY) { return this.showError(nls.localize('noFolderWorkspaceDebugError', "The active file can not be debugged. Make sure it is saved and that you have a debug extension installed for that file type.")) .then(() => false); } return !!launch && launch.openConfigFile(false, true, undefined, this.initCancellationToken ? this.initCancellationToken.token : undefined).then(() => false); }); } if (launch && type && config === null) { // show launch.json only for "config" being "null". return launch.openConfigFile(false, true, type, this.initCancellationToken ? this.initCancellationToken.token : undefined).then(() => false); } return false; }); }); } /** * instantiates the new session, initializes the session, registers session listeners and reports telemetry */ private doCreateSession(root: IWorkspaceFolder | undefined, configuration: { resolved: IConfig, unresolved: IConfig | undefined }, parentSession?: IDebugSession): Promise<boolean> { const session = this.instantiationService.createInstance(DebugSession, configuration, root, this.model, parentSession); this.model.addSession(session); // register listeners as the very first thing! this.registerSessionListeners(session); // since the Session is now properly registered under its ID and hooked, we can announce it // this event doesn't go to extensions this._onWillNewSession.fire(session); const openDebug = this.configurationService.getValue<IDebugConfiguration>('debug').openDebug; // Open debug viewlet based on the visibility of the side bar and openDebug setting. Do not open for 'run without debug' if (!configuration.resolved.noDebug && (openDebug === 'openOnSessionStart' || (openDebug === 'openOnFirstSessionStart' && this.viewModel.firstSessionStart))) { this.viewletService.openViewlet(VIEWLET_ID).then(undefined, errors.onUnexpectedError); } return this.launchOrAttachToSession(session).then(() => { const internalConsoleOptions = session.configuration.internalConsoleOptions || this.configurationService.getValue<IDebugConfiguration>('debug').internalConsoleOptions; if (internalConsoleOptions === 'openOnSessionStart' || (this.viewModel.firstSessionStart && internalConsoleOptions === 'openOnFirstSessionStart')) { this.panelService.openPanel(REPL_ID, false); } this.viewModel.firstSessionStart = false; const showSubSessions = this.configurationService.getValue<IDebugConfiguration>('debug').showSubSessionsInToolBar; const sessions = this.model.getSessions(); const shownSessions = showSubSessions ? sessions : sessions.filter(s => !s.parentSession); if (shownSessions.length > 1) { this.viewModel.setMultiSessionView(true); } // since the initialized response has arrived announce the new Session (including extensions) this._onDidNewSession.fire(session); return this.telemetryDebugSessionStart(root, session.configuration.type); }).then(() => true, (error: Error | string) => { if (errors.isPromiseCanceledError(error)) { // don't show 'canceled' error messages to the user #7906 return Promise.resolve(false); } // Show the repl if some error got logged there #5870 if (session && session.getReplElements().length > 0) { this.panelService.openPanel(REPL_ID, false); } if (session.configuration && session.configuration.request === 'attach' && session.configuration.__autoAttach) { // ignore attach timeouts in auto attach mode return Promise.resolve(false); } const errorMessage = error instanceof Error ? error.message : error; this.telemetryDebugMisconfiguration(session.configuration ? session.configuration.type : undefined, errorMessage); return this.showError(errorMessage, isErrorWithActions(error) ? error.actions : []).then(() => false); }); } private launchOrAttachToSession(session: IDebugSession, forceFocus = false): Promise<void> { const dbgr = this.configurationManager.getDebugger(session.configuration.type); return session.initialize(dbgr!).then(() => { return session.launchOrAttach(session.configuration).then(() => { if (forceFocus || !this.viewModel.focusedSession) { this.focusStackFrame(undefined, undefined, session); } }); }).then(undefined, err => { session.shutdown(); return Promise.reject(err); }); } private registerSessionListeners(session: IDebugSession): void { const sessionRunningScheduler = new RunOnceScheduler(() => { // Do not immediatly defocus the stack frame if the session is running if (session.state === State.Running && this.viewModel.focusedSession === session) { this.viewModel.setFocus(undefined, this.viewModel.focusedThread, session, false); } }, 200); this.toDispose.push(session.onDidChangeState(() => { if (session.state === State.Running && this.viewModel.focusedSession === session) { sessionRunningScheduler.schedule(); } if (session === this.viewModel.focusedSession) { this.onStateChange(); } })); this.toDispose.push(session.onDidEndAdapter(adapterExitEvent => { if (adapterExitEvent.error) { this.notificationService.error(nls.localize('debugAdapterCrash', "Debug adapter process has terminated unexpectedly ({0})", adapterExitEvent.error.message || adapterExitEvent.error.toString())); } // 'Run without debugging' mode VSCode must terminate the extension host. More details: #3905 if (isExtensionHostDebugging(session.configuration) && session.state === State.Running && session.configuration.noDebug) { this.extensionHostDebugService.close(session.getId()); } this.telemetryDebugSessionStop(session, adapterExitEvent); if (session.configuration.postDebugTask) { this.runTask(session.root, session.configuration.postDebugTask).then(undefined, err => this.notificationService.error(err) ); } session.shutdown(); this.endInitializingState(); this._onDidEndSession.fire(session); const focusedSession = this.viewModel.focusedSession; if (focusedSession && focusedSession.getId() === session.getId()) { this.focusStackFrame(undefined); } if (this.model.getSessions().length === 0) { this.viewModel.setMultiSessionView(false); if (this.layoutService.isVisible(Parts.SIDEBAR_PART) && this.configurationService.getValue<IDebugConfiguration>('debug').openExplorerOnEnd) { this.viewletService.openViewlet(EXPLORER_VIEWLET_ID); } // Data breakpoints that can not be persisted should be cleared when a session ends const dataBreakpoints = this.model.getDataBreakpoints().filter(dbp => !dbp.canPersist); dataBreakpoints.forEach(dbp => this.model.removeDataBreakpoints(dbp.getId())); } })); } restartSession(session: IDebugSession, restartData?: any): Promise<any> { return this.textFileService.saveAll().then(() => { const isAutoRestart = !!restartData; const runTasks: () => Promise<TaskRunResult> = () => { if (isAutoRestart) { // Do not run preLaunch and postDebug tasks for automatic restarts return Promise.resolve(TaskRunResult.Success); } return this.runTask(session.root, session.configuration.postDebugTask) .then(() => this.runTaskAndCheckErrors(session.root, session.configuration.preLaunchTask)); }; if (session.capabilities.supportsRestartRequest) { return runTasks().then(taskResult => taskResult === TaskRunResult.Success ? session.restart() : undefined); } if (isExtensionHostDebugging(session.configuration)) { return runTasks().then(taskResult => taskResult === TaskRunResult.Success ? this.extensionHostDebugService.reload(session.getId()) : undefined); } const shouldFocus = !!this.viewModel.focusedSession && session.getId() === this.viewModel.focusedSession.getId(); // If the restart is automatic -> disconnect, otherwise -> terminate #55064 return (isAutoRestart ? session.disconnect(true) : session.terminate(true)).then(() => { return new Promise<void>((c, e) => { setTimeout(() => { runTasks().then(taskResult => { if (taskResult !== TaskRunResult.Success) { return; } // Read the configuration again if a launch.json has been changed, if not just use the inmemory configuration let needsToSubstitute = false; let unresolved: IConfig | undefined; const launch = session.root ? this.configurationManager.getLaunch(session.root.uri) : undefined; if (launch) { unresolved = launch.getConfiguration(session.configuration.name); if (unresolved && !equals(unresolved, session.unresolvedConfiguration)) { // Take the type from the session since the debug extension might overwrite it #21316 unresolved.type = session.configuration.type; unresolved.noDebug = session.configuration.noDebug; needsToSubstitute = true; } } let substitutionThenable: Promise<IConfig | null | undefined> = Promise.resolve(session.configuration); if (launch && needsToSubstitute && unresolved) { this.initCancellationToken = new CancellationTokenSource(); substitutionThenable = this.configurationManager.resolveConfigurationByProviders(launch.workspace ? launch.workspace.uri : undefined, unresolved.type, unresolved, this.initCancellationToken.token) .then(resolved => { if (resolved) { // start debugging return this.substituteVariables(launch, resolved); } else if (resolved === null) { // abort debugging silently and open launch.json return Promise.resolve(null); } else { // abort debugging silently return Promise.resolve(undefined); } }); } substitutionThenable.then(resolved => { if (!resolved) { return c(undefined); } session.setConfiguration({ resolved, unresolved }); session.configuration.__restart = restartData; this.launchOrAttachToSession(session, shouldFocus).then(() => { this._onDidNewSession.fire(session); c(undefined); }, err => e(err)); }); }); }, 300); }); }); }); } stopSession(session: IDebugSession): Promise<any> { if (session) { return session.terminate(); } const sessions = this.model.getSessions(); if (sessions.length === 0) { this.endInitializingState(); } return Promise.all(sessions.map(s => s.terminate())); } private substituteVariables(launch: ILaunch | undefined, config: IConfig): Promise<IConfig | undefined> { const dbg = this.configurationManager.getDebugger(config.type); if (dbg) { let folder: IWorkspaceFolder | undefined = undefined; if (launch && launch.workspace) { folder = launch.workspace; } else { const folders = this.contextService.getWorkspace().folders; if (folders.length === 1) { folder = folders[0]; } } return dbg.substituteVariables(folder, config).then(config => { return config; }, (err: Error) => { this.showError(err.message); return undefined; // bail out }); } return Promise.resolve(config); } private showError(message: string, errorActions: ReadonlyArray<IAction> = []): Promise<void> { const configureAction = this.instantiationService.createInstance(debugactions.ConfigureAction, debugactions.ConfigureAction.ID, debugactions.ConfigureAction.LABEL); const actions = [...errorActions, configureAction]; return this.dialogService.show(severity.Error, message, actions.map(a => a.label).concat(nls.localize('cancel', "Cancel")), { cancelId: actions.length }).then(choice => { if (choice < actions.length) { return actions[choice].run(); } return undefined; }); } //---- task management private runTaskAndCheckErrors(root: IWorkspaceFolder | undefined, taskId: string | TaskIdentifier | undefined): Promise<TaskRunResult> { const debugAnywayAction = new Action('debug.debugAnyway', nls.localize('debugAnyway', "Debug Anyway"), undefined, true, () => Promise.resolve(TaskRunResult.Success)); return this.runTask(root, taskId).then((taskSummary: ITaskSummary) => { const errorCount = taskId ? this.markerService.getStatistics().errors : 0; const successExitCode = taskSummary && taskSummary.exitCode === 0; const failureExitCode = taskSummary && taskSummary.exitCode !== undefined && taskSummary.exitCode !== 0; if (successExitCode || (errorCount === 0 && !failureExitCode)) { return <any>TaskRunResult.Success; } const taskLabel = typeof taskId === 'string' ? taskId : taskId ? taskId.name : ''; const message = errorCount > 1 ? nls.localize('preLaunchTaskErrors', "Errors exist after running preLaunchTask '{0}'.", taskLabel) : errorCount === 1 ? nls.localize('preLaunchTaskError', "Error exists after running preLaunchTask '{0}'.", taskLabel) : nls.localize('preLaunchTaskExitCode', "The preLaunchTask '{0}' terminated with exit code {1}.", taskLabel, taskSummary.exitCode); const showErrorsAction = new Action('debug.showErrors', nls.localize('showErrors', "Show Errors"), undefined, true, () => { this.panelService.openPanel(Constants.MARKERS_PANEL_ID); return Promise.resolve(TaskRunResult.Failure); }); return this.showError(message, [debugAnywayAction, showErrorsAction]); }, (err: TaskError) => { return this.showError(err.message, [debugAnywayAction, this.taskService.configureAction()]); }); } private runTask(root: IWorkspaceFolder | undefined, taskId: string | TaskIdentifier | undefined): Promise<ITaskSummary | null> { if (!taskId) { return Promise.resolve(null); } if (!root) { return Promise.reject(new Error(nls.localize('invalidTaskReference', "Task '{0}' can not be referenced from a launch configuration that is in a different workspace folder.", typeof taskId === 'string' ? taskId : taskId.type))); } // run a task before starting a debug session return this.taskService.getTask(root, taskId).then(task => { if (!task) { const errorMessage = typeof taskId === 'string' ? nls.localize('DebugTaskNotFoundWithTaskId', "Could not find the task '{0}'.", taskId) : nls.localize('DebugTaskNotFound', "Could not find the specified task."); return Promise.reject(createErrorWithActions(errorMessage)); } // If a task is missing the problem matcher the promise will never complete, so we need to have a workaround #35340 let taskStarted = false; const promise: Promise<ITaskSummary | null> = this.taskService.getActiveTasks().then(tasks => { if (tasks.filter(t => t._id === task._id).length) { // task is already running - nothing to do. return Promise.resolve(null); } once(e => ((e.kind === TaskEventKind.Active) || (e.kind === TaskEventKind.DependsOnStarted)) && e.taskId === task._id, this.taskService.onDidStateChange)(() => { // Task is active, so everything seems to be fine, no need to prompt after 10 seconds // Use case being a slow running task should not be prompted even though it takes more than 10 seconds taskStarted = true; }); const taskPromise = this.taskService.run(task); if (task.configurationProperties.isBackground) { return new Promise((c, e) => once(e => e.kind === TaskEventKind.Inactive && e.taskId === task._id, this.taskService.onDidStateChange)(() => { taskStarted = true; c(null); })); } return taskPromise; }); return new Promise((c, e) => { promise.then(result => { taskStarted = true; c(result); }, error => e(error)); setTimeout(() => { if (!taskStarted) { const errorMessage = typeof taskId === 'string' ? nls.localize('taskNotTrackedWithTaskId', "The specified task cannot be tracked.") : nls.localize('taskNotTracked', "The task '{0}' cannot be tracked.", JSON.stringify(taskId)); e({ severity: severity.Error, message: errorMessage }); } }, 10000); }); }); } //---- focus management focusStackFrame(stackFrame: IStackFrame | undefined, thread?: IThread, session?: IDebugSession, explicit?: boolean): void { if (!session) { if (stackFrame || thread) { session = stackFrame ? stackFrame.thread.session : thread!.session; } else { const sessions = this.model.getSessions(); const stoppedSession = sessions.filter(s => s.state === State.Stopped).shift(); session = stoppedSession || (sessions.length ? sessions[0] : undefined); } } if (!thread) { if (stackFrame) { thread = stackFrame.thread; } else { const threads = session ? session.getAllThreads() : undefined; const stoppedThread = threads && threads.filter(t => t.stopped).shift(); thread = stoppedThread || (threads && threads.length ? threads[0] : undefined); } } if (!stackFrame) { if (thread) { const callStack = thread.getCallStack(); stackFrame = first(callStack, sf => !!(sf && sf.source && sf.source.available && sf.source.presentationHint !== 'deemphasize'), undefined); } } if (stackFrame) { stackFrame.openInEditor(this.editorService, true).then(editor => { if (editor) { const control = editor.getControl(); if (stackFrame && isCodeEditor(control) && control.hasModel()) { const model = control.getModel(); if (stackFrame.range.startLineNumber <= model.getLineCount()) { const lineContent = control.getModel().getLineContent(stackFrame.range.startLineNumber); aria.alert(nls.localize('debuggingPaused', "Debugging paused {0}, {1} {2} {3}", thread && thread.stoppedDetails ? `, reason ${thread.stoppedDetails.reason}` : '', stackFrame.source ? stackFrame.source.name : '', stackFrame.range.startLineNumber, lineContent)); } } } }); } if (session) { this.debugType.set(session.configuration.type); } else { this.debugType.reset(); } this.viewModel.setFocus(stackFrame, thread, session, !!explicit); } //---- watches addWatchExpression(name: string): void { const we = this.model.addWatchExpression(name); this.viewModel.setSelectedExpression(we); this.storeWatchExpressions(); } renameWatchExpression(id: string, newName: string): void { this.model.renameWatchExpression(id, newName); this.storeWatchExpressions(); } moveWatchExpression(id: string, position: number): void { this.model.moveWatchExpression(id, position); this.storeWatchExpressions(); } removeWatchExpressions(id?: string): void { this.model.removeWatchExpressions(id); this.storeWatchExpressions(); } //---- breakpoints async enableOrDisableBreakpoints(enable: boolean, breakpoint?: IEnablement): Promise<void> { if (breakpoint) { this.model.setEnablement(breakpoint, enable); if (breakpoint instanceof Breakpoint) { await this.sendBreakpoints(breakpoint.uri); } else if (breakpoint instanceof FunctionBreakpoint) { await this.sendFunctionBreakpoints(); } else if (breakpoint instanceof DataBreakpoint) { await this.sendDataBreakpoints(); } else { await this.sendExceptionBreakpoints(); } } else { this.model.enableOrDisableAllBreakpoints(enable); await this.sendAllBreakpoints(); } this.storeBreakpoints(); } async addBreakpoints(uri: uri, rawBreakpoints: IBreakpointData[], context: string): Promise<IBreakpoint[]> { const breakpoints = this.model.addBreakpoints(uri, rawBreakpoints); breakpoints.forEach(bp => aria.status(nls.localize('breakpointAdded', "Added breakpoint, line {0}, file {1}", bp.lineNumber, uri.fsPath))); breakpoints.forEach(bp => this.telemetryDebugAddBreakpoint(bp, context)); await this.sendBreakpoints(uri); this.storeBreakpoints(); return breakpoints; } async updateBreakpoints(uri: uri, data: Map<string, DebugProtocol.Breakpoint>, sendOnResourceSaved: boolean): Promise<void> { this.model.updateBreakpoints(data); if (sendOnResourceSaved) { this.breakpointsToSendOnResourceSaved.add(uri.toString()); } else { await this.sendBreakpoints(uri); } this.storeBreakpoints(); } async removeBreakpoints(id?: string): Promise<void> { const toRemove = this.model.getBreakpoints().filter(bp => !id || bp.getId() === id); toRemove.forEach(bp => aria.status(nls.localize('breakpointRemoved', "Removed breakpoint, line {0}, file {1}", bp.lineNumber, bp.uri.fsPath))); const urisToClear = distinct(toRemove, bp => bp.uri.toString()).map(bp => bp.uri); this.model.removeBreakpoints(toRemove); await Promise.all(urisToClear.map(uri => this.sendBreakpoints(uri))); this.storeBreakpoints(); } setBreakpointsActivated(activated: boolean): Promise<void> { this.model.setBreakpointsActivated(activated); if (activated) { this.storageService.store(DEBUG_BREAKPOINTS_ACTIVATED_KEY, 'false', StorageScope.WORKSPACE); } else { this.storageService.remove(DEBUG_BREAKPOINTS_ACTIVATED_KEY, StorageScope.WORKSPACE); } return this.sendAllBreakpoints(); } addFunctionBreakpoint(name?: string, id?: string): void { const newFunctionBreakpoint = this.model.addFunctionBreakpoint(name || '', id); this.viewModel.setSelectedFunctionBreakpoint(newFunctionBreakpoint); } async renameFunctionBreakpoint(id: string, newFunctionName: string): Promise<void> { this.model.renameFunctionBreakpoint(id, newFunctionName); await this.sendFunctionBreakpoints(); this.storeBreakpoints(); } async removeFunctionBreakpoints(id?: string): Promise<void> { this.model.removeFunctionBreakpoints(id); await this.sendFunctionBreakpoints(); this.storeBreakpoints(); } async addDataBreakpoint(label: string, dataId: string, canPersist: boolean): Promise<void> { this.model.addDataBreakpoint(label, dataId, canPersist); await this.sendDataBreakpoints(); this.storeBreakpoints(); } async removeDataBreakpoints(id?: string): Promise<void> { this.model.removeDataBreakpoints(id); await this.sendDataBreakpoints(); this.storeBreakpoints(); } sendAllBreakpoints(session?: IDebugSession): Promise<any> { return Promise.all(distinct(this.model.getBreakpoints(), bp => bp.uri.toString()).map(bp => this.sendBreakpoints(bp.uri, false, session))) .then(() => this.sendFunctionBreakpoints(session)) // send exception breakpoints at the end since some debug adapters rely on the order .then(() => this.sendExceptionBreakpoints(session)) .then(() => this.sendDataBreakpoints(session)); } private sendBreakpoints(modelUri: uri, sourceModified = false, session?: IDebugSession): Promise<void> { const breakpointsToSend = this.model.getBreakpoints({ uri: modelUri, enabledOnly: true }); return this.sendToOneOrAllSessions(session, s => s.sendBreakpoints(modelUri, breakpointsToSend, sourceModified) ); } private sendFunctionBreakpoints(session?: IDebugSession): Promise<void> { const breakpointsToSend = this.model.getFunctionBreakpoints().filter(fbp => fbp.enabled && this.model.areBreakpointsActivated()); return this.sendToOneOrAllSessions(session, s => { return s.capabilities.supportsFunctionBreakpoints ? s.sendFunctionBreakpoints(breakpointsToSend) : Promise.resolve(undefined); }); } private sendDataBreakpoints(session?: IDebugSession): Promise<void> { const breakpointsToSend = this.model.getDataBreakpoints().filter(fbp => fbp.enabled && this.model.areBreakpointsActivated()); return this.sendToOneOrAllSessions(session, s => { return s.capabilities.supportsDataBreakpoints ? s.sendDataBreakpoints(breakpointsToSend) : Promise.resolve(undefined); }); } private sendExceptionBreakpoints(session?: IDebugSession): Promise<void> { const enabledExceptionBps = this.model.getExceptionBreakpoints().filter(exb => exb.enabled); return this.sendToOneOrAllSessions(session, s => { return s.sendExceptionBreakpoints(enabledExceptionBps); }); } private sendToOneOrAllSessions(session: IDebugSession | undefined, send: (session: IDebugSession) => Promise<void>): Promise<void> { if (session) { return send(session); } return Promise.all(this.model.getSessions().map(s => send(s))).then(() => undefined); } private onFileChanges(fileChangesEvent: FileChangesEvent): void { const toRemove = this.model.getBreakpoints().filter(bp => fileChangesEvent.contains(bp.uri, FileChangeType.DELETED)); if (toRemove.length) { this.model.removeBreakpoints(toRemove); } fileChangesEvent.getUpdated().forEach(event => { if (this.breakpointsToSendOnResourceSaved.delete(event.resource.toString())) { this.sendBreakpoints(event.resource, true); } }); } private loadBreakpoints(): Breakpoint[] { let result: Breakpoint[] | undefined; try { result = JSON.parse(this.storageService.get(DEBUG_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((breakpoint: any) => { return new Breakpoint(uri.parse(breakpoint.uri.external || breakpoint.source.uri.external), breakpoint.lineNumber, breakpoint.column, breakpoint.enabled, breakpoint.condition, breakpoint.hitCondition, breakpoint.logMessage, breakpoint.adapterData, this.textFileService); }); } catch (e) { } return result || []; } private loadFunctionBreakpoints(): FunctionBreakpoint[] { let result: FunctionBreakpoint[] | undefined; try { result = JSON.parse(this.storageService.get(DEBUG_FUNCTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((fb: any) => { return new FunctionBreakpoint(fb.name, fb.enabled, fb.hitCondition, fb.condition, fb.logMessage); }); } catch (e) { } return result || []; } private loadExceptionBreakpoints(): ExceptionBreakpoint[] { let result: ExceptionBreakpoint[] | undefined; try { result = JSON.parse(this.storageService.get(DEBUG_EXCEPTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((exBreakpoint: any) => { return new ExceptionBreakpoint(exBreakpoint.filter, exBreakpoint.label, exBreakpoint.enabled); }); } catch (e) { } return result || []; } private loadDataBreakpoints(): DataBreakpoint[] { let result: DataBreakpoint[] | undefined; try { result = JSON.parse(this.storageService.get(DEBUG_DATA_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((dbp: any) => { return new DataBreakpoint(dbp.label, dbp.dataId, true, dbp.enabled, dbp.hitCondition, dbp.condition, dbp.logMessage); }); } catch (e) { } return result || []; } private loadWatchExpressions(): Expression[] { let result: Expression[] | undefined; try { result = JSON.parse(this.storageService.get(DEBUG_WATCH_EXPRESSIONS_KEY, StorageScope.WORKSPACE, '[]')).map((watchStoredData: { name: string, id: string }) => { return new Expression(watchStoredData.name, watchStoredData.id); }); } catch (e) { } return result || []; } private storeWatchExpressions(): void { const watchExpressions = this.model.getWatchExpressions(); if (watchExpressions.length) { this.storageService.store(DEBUG_WATCH_EXPRESSIONS_KEY, JSON.stringify(watchExpressions.map(we => ({ name: we.name, id: we.getId() }))), StorageScope.WORKSPACE); } else { this.storageService.remove(DEBUG_WATCH_EXPRESSIONS_KEY, StorageScope.WORKSPACE); } } private storeBreakpoints(): void { const breakpoints = this.model.getBreakpoints(); if (breakpoints.length) { this.storageService.store(DEBUG_BREAKPOINTS_KEY, JSON.stringify(breakpoints), StorageScope.WORKSPACE); } else { this.storageService.remove(DEBUG_BREAKPOINTS_KEY, StorageScope.WORKSPACE); } const functionBreakpoints = this.model.getFunctionBreakpoints(); if (functionBreakpoints.length) { this.storageService.store(DEBUG_FUNCTION_BREAKPOINTS_KEY, JSON.stringify(functionBreakpoints), StorageScope.WORKSPACE); } else { this.storageService.remove(DEBUG_FUNCTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE); } const dataBreakpoints = this.model.getDataBreakpoints().filter(dbp => dbp.canPersist); if (dataBreakpoints.length) { this.storageService.store(DEBUG_DATA_BREAKPOINTS_KEY, JSON.stringify(dataBreakpoints), StorageScope.WORKSPACE); } else { this.storageService.remove(DEBUG_DATA_BREAKPOINTS_KEY, StorageScope.WORKSPACE); } const exceptionBreakpoints = this.model.getExceptionBreakpoints(); if (exceptionBreakpoints.length) { this.storageService.store(DEBUG_EXCEPTION_BREAKPOINTS_KEY, JSON.stringify(exceptionBreakpoints), StorageScope.WORKSPACE); } else { this.storageService.remove(DEBUG_EXCEPTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE); } } //---- telemetry private telemetryDebugSessionStart(root: IWorkspaceFolder | undefined, type: string): Promise<void> { const dbgr = this.configurationManager.getDebugger(type); if (!dbgr) { return Promise.resolve(); } const extension = dbgr.getMainExtensionDescriptor(); /* __GDPR__ "debugSessionStart" : { "type": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "breakpointCount": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "exceptionBreakpoints": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "watchExpressionsCount": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "extensionName": { "classification": "PublicNonPersonalData", "purpose": "FeatureInsight" }, "isBuiltin": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true}, "launchJsonExists": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true } } */ return this.telemetryService.publicLog('debugSessionStart', { type: type, breakpointCount: this.model.getBreakpoints().length, exceptionBreakpoints: this.model.getExceptionBreakpoints(), watchExpressionsCount: this.model.getWatchExpressions().length, extensionName: extension.identifier.value, isBuiltin: extension.isBuiltin, launchJsonExists: root && !!this.configurationService.getValue<IGlobalConfig>('launch', { resource: root.uri }) }); } private telemetryDebugSessionStop(session: IDebugSession, adapterExitEvent: AdapterEndEvent): Promise<any> { const breakpoints = this.model.getBreakpoints(); /* __GDPR__ "debugSessionStop" : { "type" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "success": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "sessionLengthInSeconds": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "breakpointCount": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "watchExpressionsCount": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true } } */ return this.telemetryService.publicLog('debugSessionStop', { type: session && session.configuration.type, success: adapterExitEvent.emittedStopped || breakpoints.length === 0, sessionLengthInSeconds: adapterExitEvent.sessionLengthInSeconds, breakpointCount: breakpoints.length, watchExpressionsCount: this.model.getWatchExpressions().length }); } private telemetryDebugMisconfiguration(debugType: string | undefined, message: string): Promise<any> { /* __GDPR__ "debugMisconfiguration" : { "type" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "error": { "classification": "CallstackOrException", "purpose": "FeatureInsight" } } */ return this.telemetryService.publicLog('debugMisconfiguration', { type: debugType, error: message }); } private telemetryDebugAddBreakpoint(breakpoint: IBreakpoint, context: string): Promise<any> { /* __GDPR__ "debugAddBreakpoint" : { "context": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "hasCondition": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "hasHitCondition": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "hasLogMessage": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true } } */ return this.telemetryService.publicLog('debugAddBreakpoint', { context: context, hasCondition: !!breakpoint.condition, hasHitCondition: !!breakpoint.hitCondition, hasLogMessage: !!breakpoint.logMessage }); } }
src/vs/workbench/contrib/debug/browser/debugService.ts
1
https://github.com/microsoft/vscode/commit/20e24e879acc220cbb9b365001b5d1427824edaf
[ 0.9967671632766724, 0.019280195236206055, 0.00016233004862442613, 0.00017389265121892095, 0.12801362574100494 ]
{ "id": 1, "code_window": [ "\t\tthis.debugType = CONTEXT_DEBUG_TYPE.bindTo(contextKeyService);\n", "\t\tthis.debugState = CONTEXT_DEBUG_STATE.bindTo(contextKeyService);\n", "\t\tthis.inDebugMode = CONTEXT_IN_DEBUG_MODE.bindTo(contextKeyService);\n", "\n", "\t\tthis.model = new DebugModel(this.loadBreakpoints(), this.storageService.getBoolean(DEBUG_BREAKPOINTS_ACTIVATED_KEY, StorageScope.WORKSPACE, true), this.loadFunctionBreakpoints(),\n", "\t\t\tthis.loadExceptionBreakpoints(), this.loadDataBreakpoints(), this.loadWatchExpressions(), this.textFileService);\n", "\t\tthis.toDispose.push(this.model);\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis.model = new DebugModel(this.loadBreakpoints(), this.loadFunctionBreakpoints(),\n" ], "file_path": "src/vs/workbench/contrib/debug/browser/debugService.ts", "type": "replace", "edit_start_line_idx": 131 }
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M10 12.6L10.7 13.3L12.3 11.7L13.9 13.3L14.7 12.6L13 11L14.7 9.40005L13.9 8.60005L12.3 10.3L10.7 8.60005L10 9.40005L11.6 11L10 12.6Z" fill="white"/> <path d="M1 4L15 4L15 3L1 3L1 4Z" fill="white"/> <path d="M1 7L15 7L15 6L1 6L1 7Z" fill="white"/> <path d="M9 9.5L9 9L0.999999 9L0.999999 10L9 10L9 9.5Z" fill="white"/> <path d="M9 13L9 12.5L9 12L1 12L1 13L9 13Z" fill="white"/> </svg>
src/vs/workbench/contrib/search/browser/media/clear-hc.svg
0
https://github.com/microsoft/vscode/commit/20e24e879acc220cbb9b365001b5d1427824edaf
[ 0.00017524541181046516, 0.00017524541181046516, 0.00017524541181046516, 0.00017524541181046516, 0 ]
{ "id": 1, "code_window": [ "\t\tthis.debugType = CONTEXT_DEBUG_TYPE.bindTo(contextKeyService);\n", "\t\tthis.debugState = CONTEXT_DEBUG_STATE.bindTo(contextKeyService);\n", "\t\tthis.inDebugMode = CONTEXT_IN_DEBUG_MODE.bindTo(contextKeyService);\n", "\n", "\t\tthis.model = new DebugModel(this.loadBreakpoints(), this.storageService.getBoolean(DEBUG_BREAKPOINTS_ACTIVATED_KEY, StorageScope.WORKSPACE, true), this.loadFunctionBreakpoints(),\n", "\t\t\tthis.loadExceptionBreakpoints(), this.loadDataBreakpoints(), this.loadWatchExpressions(), this.textFileService);\n", "\t\tthis.toDispose.push(this.model);\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis.model = new DebugModel(this.loadBreakpoints(), this.loadFunctionBreakpoints(),\n" ], "file_path": "src/vs/workbench/contrib/debug/browser/debugService.ts", "type": "replace", "edit_start_line_idx": 131 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as assert from 'assert'; import * as path from 'vs/base/common/path'; import { getPathFromAmdModule } from 'vs/base/common/amd'; import * as platform from 'vs/base/common/platform'; import { joinPath } from 'vs/base/common/resources'; import { URI } from 'vs/base/common/uri'; import { IFolderQuery, QueryType, IRawFileMatch } from 'vs/workbench/services/search/common/search'; import { Engine as FileSearchEngine, FileWalker } from 'vs/workbench/services/search/node/fileSearch'; const TEST_FIXTURES = path.normalize(getPathFromAmdModule(require, './fixtures')); const EXAMPLES_FIXTURES = URI.file(path.join(TEST_FIXTURES, 'examples')); const MORE_FIXTURES = URI.file(path.join(TEST_FIXTURES, 'more')); const TEST_ROOT_FOLDER: IFolderQuery = { folder: URI.file(TEST_FIXTURES) }; const ROOT_FOLDER_QUERY: IFolderQuery[] = [ TEST_ROOT_FOLDER ]; const ROOT_FOLDER_QUERY_36438: IFolderQuery[] = [ { folder: URI.file(path.normalize(getPathFromAmdModule(require, './fixtures2/36438'))) } ]; const MULTIROOT_QUERIES: IFolderQuery[] = [ { folder: EXAMPLES_FIXTURES }, { folder: MORE_FIXTURES } ]; const testTimeout = 5000; suite('FileSearchEngine', () => { test('Files: *.js', function (done: () => void) { this.timeout(testTimeout); const engine = new FileSearchEngine({ type: QueryType.File, folderQueries: ROOT_FOLDER_QUERY, filePattern: '*.js' }); let count = 0; engine.search((result) => { if (result) { count++; } }, () => { }, (error) => { assert.ok(!error); assert.equal(count, 4); done(); }); }); test('Files: maxResults', function (done: () => void) { this.timeout(testTimeout); const engine = new FileSearchEngine({ type: QueryType.File, folderQueries: ROOT_FOLDER_QUERY, maxResults: 1 }); let count = 0; engine.search((result) => { if (result) { count++; } }, () => { }, (error) => { assert.ok(!error); assert.equal(count, 1); done(); }); }); test('Files: maxResults without Ripgrep', function (done: () => void) { this.timeout(testTimeout); const engine = new FileSearchEngine({ type: QueryType.File, folderQueries: ROOT_FOLDER_QUERY, maxResults: 1, }); let count = 0; engine.search((result) => { if (result) { count++; } }, () => { }, (error) => { assert.ok(!error); assert.equal(count, 1); done(); }); }); test('Files: exists', function (done: () => void) { this.timeout(testTimeout); const engine = new FileSearchEngine({ type: QueryType.File, folderQueries: ROOT_FOLDER_QUERY, includePattern: { '**/file.txt': true }, exists: true }); let count = 0; engine.search((result) => { if (result) { count++; } }, () => { }, (error, complete) => { assert.ok(!error); assert.equal(count, 0); assert.ok(complete.limitHit); done(); }); }); test('Files: not exists', function (done: () => void) { this.timeout(testTimeout); const engine = new FileSearchEngine({ type: QueryType.File, folderQueries: ROOT_FOLDER_QUERY, includePattern: { '**/nofile.txt': true }, exists: true }); let count = 0; engine.search((result) => { if (result) { count++; } }, () => { }, (error, complete) => { assert.ok(!error); assert.equal(count, 0); assert.ok(!complete.limitHit); done(); }); }); test('Files: exists without Ripgrep', function (done: () => void) { this.timeout(testTimeout); const engine = new FileSearchEngine({ type: QueryType.File, folderQueries: ROOT_FOLDER_QUERY, includePattern: { '**/file.txt': true }, exists: true, }); let count = 0; engine.search((result) => { if (result) { count++; } }, () => { }, (error, complete) => { assert.ok(!error); assert.equal(count, 0); assert.ok(complete.limitHit); done(); }); }); test('Files: not exists without Ripgrep', function (done: () => void) { this.timeout(testTimeout); const engine = new FileSearchEngine({ type: QueryType.File, folderQueries: ROOT_FOLDER_QUERY, includePattern: { '**/nofile.txt': true }, exists: true, }); let count = 0; engine.search((result) => { if (result) { count++; } }, () => { }, (error, complete) => { assert.ok(!error); assert.equal(count, 0); assert.ok(!complete.limitHit); done(); }); }); test('Files: examples/com*', function (done: () => void) { this.timeout(testTimeout); const engine = new FileSearchEngine({ type: QueryType.File, folderQueries: ROOT_FOLDER_QUERY, filePattern: path.join('examples', 'com*') }); let count = 0; engine.search((result) => { if (result) { count++; } }, () => { }, (error) => { assert.ok(!error); assert.equal(count, 1); done(); }); }); test('Files: examples (fuzzy)', function (done: () => void) { this.timeout(testTimeout); const engine = new FileSearchEngine({ type: QueryType.File, folderQueries: ROOT_FOLDER_QUERY, filePattern: 'xl' }); let count = 0; engine.search((result) => { if (result) { count++; } }, () => { }, (error) => { assert.ok(!error); assert.equal(count, 7); done(); }); }); test('Files: multiroot', function (done: () => void) { this.timeout(testTimeout); const engine = new FileSearchEngine({ type: QueryType.File, folderQueries: MULTIROOT_QUERIES, filePattern: 'file' }); let count = 0; engine.search((result) => { if (result) { count++; } }, () => { }, (error) => { assert.ok(!error); assert.equal(count, 3); done(); }); }); test('Files: multiroot with includePattern and maxResults', function (done: () => void) { this.timeout(testTimeout); const engine = new FileSearchEngine({ type: QueryType.File, folderQueries: MULTIROOT_QUERIES, maxResults: 1, includePattern: { '*.txt': true, '*.js': true }, }); let count = 0; engine.search((result) => { if (result) { count++; } }, () => { }, (error, complete) => { assert.ok(!error); assert.equal(count, 1); done(); }); }); test('Files: multiroot with includePattern and exists', function (done: () => void) { this.timeout(testTimeout); const engine = new FileSearchEngine({ type: QueryType.File, folderQueries: MULTIROOT_QUERIES, exists: true, includePattern: { '*.txt': true, '*.js': true }, }); let count = 0; engine.search((result) => { if (result) { count++; } }, () => { }, (error, complete) => { assert.ok(!error); assert.equal(count, 0); assert.ok(complete.limitHit); done(); }); }); test('Files: NPE (CamelCase)', function (done: () => void) { this.timeout(testTimeout); const engine = new FileSearchEngine({ type: QueryType.File, folderQueries: ROOT_FOLDER_QUERY, filePattern: 'NullPE' }); let count = 0; engine.search((result) => { if (result) { count++; } }, () => { }, (error) => { assert.ok(!error); assert.equal(count, 1); done(); }); }); test('Files: *.*', function (done: () => void) { this.timeout(testTimeout); const engine = new FileSearchEngine({ type: QueryType.File, folderQueries: ROOT_FOLDER_QUERY, filePattern: '*.*' }); let count = 0; engine.search((result) => { if (result) { count++; } }, () => { }, (error) => { assert.ok(!error); assert.equal(count, 14); done(); }); }); test('Files: *.as', function (done: () => void) { this.timeout(testTimeout); const engine = new FileSearchEngine({ type: QueryType.File, folderQueries: ROOT_FOLDER_QUERY, filePattern: '*.as' }); let count = 0; engine.search((result) => { if (result) { count++; } }, () => { }, (error) => { assert.ok(!error); assert.equal(count, 0); done(); }); }); test('Files: *.* without derived', function (done: () => void) { this.timeout(testTimeout); const engine = new FileSearchEngine({ type: QueryType.File, folderQueries: ROOT_FOLDER_QUERY, filePattern: 'site.*', excludePattern: { '**/*.css': { 'when': '$(basename).less' } } }); let count = 0; let res: IRawFileMatch; engine.search((result) => { if (result) { count++; } res = result; }, () => { }, (error) => { assert.ok(!error); assert.equal(count, 1); assert.strictEqual(path.basename(res.relativePath), 'site.less'); done(); }); }); test('Files: *.* exclude folder without wildcard', function (done: () => void) { this.timeout(testTimeout); const engine = new FileSearchEngine({ type: QueryType.File, folderQueries: ROOT_FOLDER_QUERY, filePattern: '*.*', excludePattern: { 'examples': true } }); let count = 0; engine.search((result) => { if (result) { count++; } }, () => { }, (error) => { assert.ok(!error); assert.equal(count, 8); done(); }); }); test('Files: exclude folder without wildcard #36438', function (done: () => void) { this.timeout(testTimeout); const engine = new FileSearchEngine({ type: QueryType.File, folderQueries: ROOT_FOLDER_QUERY_36438, excludePattern: { 'modules': true } }); let count = 0; engine.search((result) => { if (result) { count++; } }, () => { }, (error) => { assert.ok(!error); assert.equal(count, 1); done(); }); }); test('Files: include folder without wildcard #36438', function (done: () => void) { this.timeout(testTimeout); const engine = new FileSearchEngine({ type: QueryType.File, folderQueries: ROOT_FOLDER_QUERY_36438, includePattern: { 'modules/**': true } }); let count = 0; engine.search((result) => { if (result) { count++; } }, () => { }, (error) => { assert.ok(!error); assert.equal(count, 1); done(); }); }); test('Files: *.* exclude folder with leading wildcard', function (done: () => void) { this.timeout(testTimeout); const engine = new FileSearchEngine({ type: QueryType.File, folderQueries: ROOT_FOLDER_QUERY, filePattern: '*.*', excludePattern: { '**/examples': true } }); let count = 0; engine.search((result) => { if (result) { count++; } }, () => { }, (error) => { assert.ok(!error); assert.equal(count, 8); done(); }); }); test('Files: *.* exclude folder with trailing wildcard', function (done: () => void) { this.timeout(testTimeout); const engine = new FileSearchEngine({ type: QueryType.File, folderQueries: ROOT_FOLDER_QUERY, filePattern: '*.*', excludePattern: { 'examples/**': true } }); let count = 0; engine.search((result) => { if (result) { count++; } }, () => { }, (error) => { assert.ok(!error); assert.equal(count, 8); done(); }); }); test('Files: *.* exclude with unicode', function (done: () => void) { this.timeout(testTimeout); const engine = new FileSearchEngine({ type: QueryType.File, folderQueries: ROOT_FOLDER_QUERY, filePattern: '*.*', excludePattern: { '**/üm laut汉语': true } }); let count = 0; engine.search((result) => { if (result) { count++; } }, () => { }, (error) => { assert.ok(!error); assert.equal(count, 13); done(); }); }); test('Files: *.* include with unicode', function (done: () => void) { this.timeout(testTimeout); const engine = new FileSearchEngine({ type: QueryType.File, folderQueries: ROOT_FOLDER_QUERY, filePattern: '*.*', includePattern: { '**/üm laut汉语/*': true } }); let count = 0; engine.search((result) => { if (result) { count++; } }, () => { }, (error) => { assert.ok(!error); assert.equal(count, 1); done(); }); }); test('Files: multiroot with exclude', function (done: () => void) { this.timeout(testTimeout); const folderQueries: IFolderQuery[] = [ { folder: EXAMPLES_FIXTURES, excludePattern: { '**/anotherfile.txt': true } }, { folder: MORE_FIXTURES, excludePattern: { '**/file.txt': true } } ]; const engine = new FileSearchEngine({ type: QueryType.File, folderQueries, filePattern: '*' }); let count = 0; engine.search((result) => { if (result) { count++; } }, () => { }, (error) => { assert.ok(!error); assert.equal(count, 5); done(); }); }); test('Files: Unicode and Spaces', function (done: () => void) { this.timeout(testTimeout); const engine = new FileSearchEngine({ type: QueryType.File, folderQueries: ROOT_FOLDER_QUERY, filePattern: '汉语' }); let count = 0; let res: IRawFileMatch; engine.search((result) => { if (result) { count++; } res = result; }, () => { }, (error) => { assert.ok(!error); assert.equal(count, 1); assert.equal(path.basename(res.relativePath), '汉语.txt'); done(); }); }); test('Files: no results', function (done: () => void) { this.timeout(testTimeout); const engine = new FileSearchEngine({ type: QueryType.File, folderQueries: ROOT_FOLDER_QUERY, filePattern: 'nofilematch' }); let count = 0; engine.search((result) => { if (result) { count++; } }, () => { }, (error) => { assert.ok(!error); assert.equal(count, 0); done(); }); }); test('Files: relative path matched once', function (done: () => void) { this.timeout(testTimeout); const engine = new FileSearchEngine({ type: QueryType.File, folderQueries: ROOT_FOLDER_QUERY, filePattern: path.normalize(path.join('examples', 'company.js')) }); let count = 0; let res: IRawFileMatch; engine.search((result) => { if (result) { count++; } res = result; }, () => { }, (error) => { assert.ok(!error); assert.equal(count, 1); assert.equal(path.basename(res.relativePath), 'company.js'); done(); }); }); test('Files: Include pattern, single files', function (done: () => void) { this.timeout(testTimeout); const engine = new FileSearchEngine({ type: QueryType.File, folderQueries: ROOT_FOLDER_QUERY, includePattern: { 'site.css': true, 'examples/company.js': true, 'examples/subfolder/subfile.txt': true } }); const res: IRawFileMatch[] = []; engine.search((result) => { res.push(result); }, () => { }, (error) => { assert.ok(!error); const basenames = res.map(r => path.basename(r.relativePath)); assert.ok(basenames.indexOf('site.css') !== -1, `site.css missing in ${JSON.stringify(basenames)}`); assert.ok(basenames.indexOf('company.js') !== -1, `company.js missing in ${JSON.stringify(basenames)}`); assert.ok(basenames.indexOf('subfile.txt') !== -1, `subfile.txt missing in ${JSON.stringify(basenames)}`); done(); }); }); test('Files: extraFiles only', function (done: () => void) { this.timeout(testTimeout); const engine = new FileSearchEngine({ type: QueryType.File, folderQueries: [], extraFileResources: [ URI.file(path.normalize(path.join(getPathFromAmdModule(require, './fixtures'), 'site.css'))), URI.file(path.normalize(path.join(getPathFromAmdModule(require, './fixtures'), 'examples', 'company.js'))), URI.file(path.normalize(path.join(getPathFromAmdModule(require, './fixtures'), 'index.html'))) ], filePattern: '*.js' }); let count = 0; let res: IRawFileMatch; engine.search((result) => { if (result) { count++; } res = result; }, () => { }, (error) => { assert.ok(!error); assert.equal(count, 1); assert.equal(path.basename(res.relativePath), 'company.js'); done(); }); }); test('Files: extraFiles only (with include)', function (done: () => void) { this.timeout(testTimeout); const engine = new FileSearchEngine({ type: QueryType.File, folderQueries: [], extraFileResources: [ URI.file(path.normalize(path.join(getPathFromAmdModule(require, './fixtures'), 'site.css'))), URI.file(path.normalize(path.join(getPathFromAmdModule(require, './fixtures'), 'examples', 'company.js'))), URI.file(path.normalize(path.join(getPathFromAmdModule(require, './fixtures'), 'index.html'))) ], filePattern: '*.*', includePattern: { '**/*.css': true } }); let count = 0; let res: IRawFileMatch; engine.search((result) => { if (result) { count++; } res = result; }, () => { }, (error) => { assert.ok(!error); assert.equal(count, 1); assert.equal(path.basename(res.relativePath), 'site.css'); done(); }); }); test('Files: extraFiles only (with exclude)', function (done: () => void) { this.timeout(testTimeout); const engine = new FileSearchEngine({ type: QueryType.File, folderQueries: [], extraFileResources: [ URI.file(path.normalize(path.join(getPathFromAmdModule(require, './fixtures'), 'site.css'))), URI.file(path.normalize(path.join(getPathFromAmdModule(require, './fixtures'), 'examples', 'company.js'))), URI.file(path.normalize(path.join(getPathFromAmdModule(require, './fixtures'), 'index.html'))) ], filePattern: '*.*', excludePattern: { '**/*.css': true } }); let count = 0; engine.search((result) => { if (result) { count++; } }, () => { }, (error) => { assert.ok(!error); assert.equal(count, 2); done(); }); }); test('Files: no dupes in nested folders', function (done: () => void) { this.timeout(testTimeout); const engine = new FileSearchEngine({ type: QueryType.File, folderQueries: [ { folder: EXAMPLES_FIXTURES }, { folder: joinPath(EXAMPLES_FIXTURES, 'subfolder') } ], filePattern: 'subfile.txt' }); let count = 0; engine.search((result) => { if (result) { count++; } }, () => { }, (error) => { assert.ok(!error); assert.equal(count, 1); done(); }); }); }); suite('FileWalker', () => { test('Find: exclude subfolder', function (done: () => void) { this.timeout(testTimeout); if (platform.isWindows) { done(); return; } const file0 = './more/file.txt'; const file1 = './examples/subfolder/subfile.txt'; const walker = new FileWalker({ type: QueryType.File, folderQueries: ROOT_FOLDER_QUERY, excludePattern: { '**/something': true } }); const cmd1 = walker.spawnFindCmd(TEST_ROOT_FOLDER); walker.readStdout(cmd1, 'utf8', (err1, stdout1) => { assert.equal(err1, null); assert.notStrictEqual(stdout1!.split('\n').indexOf(file0), -1, stdout1); assert.notStrictEqual(stdout1!.split('\n').indexOf(file1), -1, stdout1); const walker = new FileWalker({ type: QueryType.File, folderQueries: ROOT_FOLDER_QUERY, excludePattern: { '**/subfolder': true } }); const cmd2 = walker.spawnFindCmd(TEST_ROOT_FOLDER); walker.readStdout(cmd2, 'utf8', (err2, stdout2) => { assert.equal(err2, null); assert.notStrictEqual(stdout1!.split('\n').indexOf(file0), -1, stdout1); assert.strictEqual(stdout2!.split('\n').indexOf(file1), -1, stdout2); done(); }); }); }); test('Find: folder excludes', function (done: () => void) { this.timeout(testTimeout); if (platform.isWindows) { done(); return; } const folderQueries: IFolderQuery[] = [ { folder: URI.file(TEST_FIXTURES), excludePattern: { '**/subfolder': true } } ]; const file0 = './more/file.txt'; const file1 = './examples/subfolder/subfile.txt'; const walker = new FileWalker({ type: QueryType.File, folderQueries }); const cmd1 = walker.spawnFindCmd(folderQueries[0]); walker.readStdout(cmd1, 'utf8', (err1, stdout1) => { assert.equal(err1, null); assert(outputContains(stdout1!, file0), stdout1); assert(!outputContains(stdout1!, file1), stdout1); done(); }); }); test('Find: exclude multiple folders', function (done: () => void) { this.timeout(testTimeout); if (platform.isWindows) { done(); return; } const file0 = './index.html'; const file1 = './examples/small.js'; const file2 = './more/file.txt'; const walker = new FileWalker({ type: QueryType.File, folderQueries: ROOT_FOLDER_QUERY, excludePattern: { '**/something': true } }); const cmd1 = walker.spawnFindCmd(TEST_ROOT_FOLDER); walker.readStdout(cmd1, 'utf8', (err1, stdout1) => { assert.equal(err1, null); assert.notStrictEqual(stdout1!.split('\n').indexOf(file0), -1, stdout1); assert.notStrictEqual(stdout1!.split('\n').indexOf(file1), -1, stdout1); assert.notStrictEqual(stdout1!.split('\n').indexOf(file2), -1, stdout1); const walker = new FileWalker({ type: QueryType.File, folderQueries: ROOT_FOLDER_QUERY, excludePattern: { '{**/examples,**/more}': true } }); const cmd2 = walker.spawnFindCmd(TEST_ROOT_FOLDER); walker.readStdout(cmd2, 'utf8', (err2, stdout2) => { assert.equal(err2, null); assert.notStrictEqual(stdout1!.split('\n').indexOf(file0), -1, stdout1); assert.strictEqual(stdout2!.split('\n').indexOf(file1), -1, stdout2); assert.strictEqual(stdout2!.split('\n').indexOf(file2), -1, stdout2); done(); }); }); }); test('Find: exclude folder path suffix', function (done: () => void) { this.timeout(testTimeout); if (platform.isWindows) { done(); return; } const file0 = './examples/company.js'; const file1 = './examples/subfolder/subfile.txt'; const walker = new FileWalker({ type: QueryType.File, folderQueries: ROOT_FOLDER_QUERY, excludePattern: { '**/examples/something': true } }); const cmd1 = walker.spawnFindCmd(TEST_ROOT_FOLDER); walker.readStdout(cmd1, 'utf8', (err1, stdout1) => { assert.equal(err1, null); assert.notStrictEqual(stdout1!.split('\n').indexOf(file0), -1, stdout1); assert.notStrictEqual(stdout1!.split('\n').indexOf(file1), -1, stdout1); const walker = new FileWalker({ type: QueryType.File, folderQueries: ROOT_FOLDER_QUERY, excludePattern: { '**/examples/subfolder': true } }); const cmd2 = walker.spawnFindCmd(TEST_ROOT_FOLDER); walker.readStdout(cmd2, 'utf8', (err2, stdout2) => { assert.equal(err2, null); assert.notStrictEqual(stdout1!.split('\n').indexOf(file0), -1, stdout1); assert.strictEqual(stdout2!.split('\n').indexOf(file1), -1, stdout2); done(); }); }); }); test('Find: exclude subfolder path suffix', function (done: () => void) { this.timeout(testTimeout); if (platform.isWindows) { done(); return; } const file0 = './examples/subfolder/subfile.txt'; const file1 = './examples/subfolder/anotherfolder/anotherfile.txt'; const walker = new FileWalker({ type: QueryType.File, folderQueries: ROOT_FOLDER_QUERY, excludePattern: { '**/subfolder/something': true } }); const cmd1 = walker.spawnFindCmd(TEST_ROOT_FOLDER); walker.readStdout(cmd1, 'utf8', (err1, stdout1) => { assert.equal(err1, null); assert.notStrictEqual(stdout1!.split('\n').indexOf(file0), -1, stdout1); assert.notStrictEqual(stdout1!.split('\n').indexOf(file1), -1, stdout1); const walker = new FileWalker({ type: QueryType.File, folderQueries: ROOT_FOLDER_QUERY, excludePattern: { '**/subfolder/anotherfolder': true } }); const cmd2 = walker.spawnFindCmd(TEST_ROOT_FOLDER); walker.readStdout(cmd2, 'utf8', (err2, stdout2) => { assert.equal(err2, null); assert.notStrictEqual(stdout1!.split('\n').indexOf(file0), -1, stdout1); assert.strictEqual(stdout2!.split('\n').indexOf(file1), -1, stdout2); done(); }); }); }); test('Find: exclude folder path', function (done: () => void) { this.timeout(testTimeout); if (platform.isWindows) { done(); return; } const file0 = './examples/company.js'; const file1 = './examples/subfolder/subfile.txt'; const walker = new FileWalker({ type: QueryType.File, folderQueries: ROOT_FOLDER_QUERY, excludePattern: { 'examples/something': true } }); const cmd1 = walker.spawnFindCmd(TEST_ROOT_FOLDER); walker.readStdout(cmd1, 'utf8', (err1, stdout1) => { assert.equal(err1, null); assert.notStrictEqual(stdout1!.split('\n').indexOf(file0), -1, stdout1); assert.notStrictEqual(stdout1!.split('\n').indexOf(file1), -1, stdout1); const walker = new FileWalker({ type: QueryType.File, folderQueries: ROOT_FOLDER_QUERY, excludePattern: { 'examples/subfolder': true } }); const cmd2 = walker.spawnFindCmd(TEST_ROOT_FOLDER); walker.readStdout(cmd2, 'utf8', (err2, stdout2) => { assert.equal(err2, null); assert.notStrictEqual(stdout1!.split('\n').indexOf(file0), -1, stdout1); assert.strictEqual(stdout2!.split('\n').indexOf(file1), -1, stdout2); done(); }); }); }); test('Find: exclude combination of paths', function (done: () => void) { this.timeout(testTimeout); if (platform.isWindows) { done(); return; } const filesIn = [ './examples/subfolder/subfile.txt', './examples/company.js', './index.html' ]; const filesOut = [ './examples/subfolder/anotherfolder/anotherfile.txt', './more/file.txt' ]; const walker = new FileWalker({ type: QueryType.File, folderQueries: ROOT_FOLDER_QUERY, excludePattern: { '**/subfolder/anotherfolder': true, '**/something/else': true, '**/more': true, '**/andmore': true } }); const cmd1 = walker.spawnFindCmd(TEST_ROOT_FOLDER); walker.readStdout(cmd1, 'utf8', (err1, stdout1) => { assert.equal(err1, null); for (const fileIn of filesIn) { assert.notStrictEqual(stdout1!.split('\n').indexOf(fileIn), -1, stdout1); } for (const fileOut of filesOut) { assert.strictEqual(stdout1!.split('\n').indexOf(fileOut), -1, stdout1); } done(); }); }); function outputContains(stdout: string, ...files: string[]): boolean { const lines = stdout.split('\n'); return files.every(file => lines.indexOf(file) >= 0); } });
src/vs/workbench/services/search/test/node/search.test.ts
0
https://github.com/microsoft/vscode/commit/20e24e879acc220cbb9b365001b5d1427824edaf
[ 0.0001770051894709468, 0.00017246192146558315, 0.00016883375064935535, 0.00017230321827810258, 0.0000014951544926589122 ]
{ "id": 1, "code_window": [ "\t\tthis.debugType = CONTEXT_DEBUG_TYPE.bindTo(contextKeyService);\n", "\t\tthis.debugState = CONTEXT_DEBUG_STATE.bindTo(contextKeyService);\n", "\t\tthis.inDebugMode = CONTEXT_IN_DEBUG_MODE.bindTo(contextKeyService);\n", "\n", "\t\tthis.model = new DebugModel(this.loadBreakpoints(), this.storageService.getBoolean(DEBUG_BREAKPOINTS_ACTIVATED_KEY, StorageScope.WORKSPACE, true), this.loadFunctionBreakpoints(),\n", "\t\t\tthis.loadExceptionBreakpoints(), this.loadDataBreakpoints(), this.loadWatchExpressions(), this.textFileService);\n", "\t\tthis.toDispose.push(this.model);\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis.model = new DebugModel(this.loadBreakpoints(), this.loadFunctionBreakpoints(),\n" ], "file_path": "src/vs/workbench/contrib/debug/browser/debugService.ts", "type": "replace", "edit_start_line_idx": 131 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Command } from '../commandManager'; import { MarkdownEngine } from '../markdownEngine'; import { SkinnyTextDocument } from '../tableOfContentsProvider'; export class RenderDocument implements Command { public readonly id = 'markdown.api.render'; public constructor( private readonly engine: MarkdownEngine ) { } public async execute(document: SkinnyTextDocument | string): Promise<string> { return this.engine.render(document); } }
extensions/markdown-language-features/src/commands/renderDocument.ts
0
https://github.com/microsoft/vscode/commit/20e24e879acc220cbb9b365001b5d1427824edaf
[ 0.0001753885007929057, 0.00017159373965114355, 0.00016909089754335582, 0.0001703018497209996, 0.000002728455456235679 ]
{ "id": 2, "code_window": [ "\t\tthis.storeBreakpoints();\n", "\t}\n", "\n", "\tsetBreakpointsActivated(activated: boolean): Promise<void> {\n", "\t\tthis.model.setBreakpointsActivated(activated);\n", "\t\tif (activated) {\n", "\t\t\tthis.storageService.store(DEBUG_BREAKPOINTS_ACTIVATED_KEY, 'false', StorageScope.WORKSPACE);\n", "\t\t} else {\n", "\t\t\tthis.storageService.remove(DEBUG_BREAKPOINTS_ACTIVATED_KEY, StorageScope.WORKSPACE);\n", "\t\t}\n", "\n", "\t\treturn this.sendAllBreakpoints();\n", "\t}\n", "\n", "\taddFunctionBreakpoint(name?: string, id?: string): void {\n", "\t\tconst newFunctionBreakpoint = this.model.addFunctionBreakpoint(name || '', id);\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/debug/browser/debugService.ts", "type": "replace", "edit_start_line_idx": 903 }
/*--------------------------------------------------------------------------------------------- * 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 { URI as uri } from 'vs/base/common/uri'; import * as resources from 'vs/base/common/resources'; import * as lifecycle from 'vs/base/common/lifecycle'; import { Event, Emitter } from 'vs/base/common/event'; import { generateUuid } from 'vs/base/common/uuid'; import { RunOnceScheduler } from 'vs/base/common/async'; import severity from 'vs/base/common/severity'; import { isObject, isString, isUndefinedOrNull } from 'vs/base/common/types'; import { distinct, lastIndex } from 'vs/base/common/arrays'; import { Range, IRange } from 'vs/editor/common/core/range'; import { ITreeElement, IExpression, IExpressionContainer, IDebugSession, IStackFrame, IExceptionBreakpoint, IBreakpoint, IFunctionBreakpoint, IDebugModel, IReplElementSource, IThread, IRawModelUpdate, IScope, IRawStoppedDetails, IEnablement, IBreakpointData, IExceptionInfo, IReplElement, IBreakpointsChangeEvent, IBreakpointUpdateData, IBaseBreakpoint, State, IDataBreakpoint } from 'vs/workbench/contrib/debug/common/debug'; import { Source, UNKNOWN_SOURCE_LABEL } from 'vs/workbench/contrib/debug/common/debugSource'; import { commonSuffixLength } from 'vs/base/common/strings'; import { posix } from 'vs/base/common/path'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { ITextFileService } from 'vs/workbench/services/textfile/common/textfiles'; import { ITextEditor } from 'vs/workbench/common/editor'; export class SimpleReplElement implements IReplElement { constructor( private id: string, public value: string, public severity: severity, public sourceData?: IReplElementSource, ) { } toString(): string { return this.value; } getId(): string { return this.id; } } export class RawObjectReplElement implements IExpression { private static readonly MAX_CHILDREN = 1000; // upper bound of children per value constructor(private id: string, public name: string, public valueObj: any, public sourceData?: IReplElementSource, public annotation?: string) { } getId(): string { return this.id; } get value(): string { if (this.valueObj === null) { return 'null'; } else if (Array.isArray(this.valueObj)) { return `Array[${this.valueObj.length}]`; } else if (isObject(this.valueObj)) { return 'Object'; } else if (isString(this.valueObj)) { return `"${this.valueObj}"`; } return String(this.valueObj) || ''; } get hasChildren(): boolean { return (Array.isArray(this.valueObj) && this.valueObj.length > 0) || (isObject(this.valueObj) && Object.getOwnPropertyNames(this.valueObj).length > 0); } getChildren(): Promise<IExpression[]> { let result: IExpression[] = []; if (Array.isArray(this.valueObj)) { result = (<any[]>this.valueObj).slice(0, RawObjectReplElement.MAX_CHILDREN) .map((v, index) => new RawObjectReplElement(`${this.id}:${index}`, String(index), v)); } else if (isObject(this.valueObj)) { result = Object.getOwnPropertyNames(this.valueObj).slice(0, RawObjectReplElement.MAX_CHILDREN) .map((key, index) => new RawObjectReplElement(`${this.id}:${index}`, key, this.valueObj[key])); } return Promise.resolve(result); } toString(): string { return `${this.name}\n${this.value}`; } } export class ExpressionContainer implements IExpressionContainer { public static allValues = new Map<string, string>(); // Use chunks to support variable paging #9537 private static readonly BASE_CHUNK_SIZE = 100; public valueChanged = false; private _value: string = ''; protected children?: Promise<IExpression[]>; constructor( protected session: IDebugSession | undefined, private _reference: number | undefined, private id: string, public namedVariables: number | undefined = 0, public indexedVariables: number | undefined = 0, private startOfVariables: number | undefined = 0 ) { } get reference(): number | undefined { return this._reference; } set reference(value: number | undefined) { this._reference = value; this.children = undefined; // invalidate children cache } getChildren(): Promise<IExpression[]> { if (!this.children) { this.children = this.doGetChildren(); } return this.children; } private async doGetChildren(): Promise<IExpression[]> { if (!this.hasChildren) { return Promise.resolve([]); } if (!this.getChildrenInChunks) { return this.fetchVariables(undefined, undefined, undefined); } // Check if object has named variables, fetch them independent from indexed variables #9670 const children = this.namedVariables ? await this.fetchVariables(undefined, undefined, 'named') : []; // Use a dynamic chunk size based on the number of elements #9774 let chunkSize = ExpressionContainer.BASE_CHUNK_SIZE; while (!!this.indexedVariables && this.indexedVariables > chunkSize * ExpressionContainer.BASE_CHUNK_SIZE) { chunkSize *= ExpressionContainer.BASE_CHUNK_SIZE; } if (!!this.indexedVariables && this.indexedVariables > chunkSize) { // There are a lot of children, create fake intermediate values that represent chunks #9537 const numberOfChunks = Math.ceil(this.indexedVariables / chunkSize); for (let i = 0; i < numberOfChunks; i++) { const start = (this.startOfVariables || 0) + i * chunkSize; const count = Math.min(chunkSize, this.indexedVariables - i * chunkSize); children.push(new Variable(this.session, this, this.reference, `[${start}..${start + count - 1}]`, '', '', undefined, count, { kind: 'virtual' }, undefined, true, start)); } return children; } const variables = await this.fetchVariables(this.startOfVariables, this.indexedVariables, 'indexed'); return children.concat(variables); } getId(): string { return this.id; } get value(): string { return this._value; } get hasChildren(): boolean { // only variables with reference > 0 have children. return !!this.reference && this.reference > 0; } private fetchVariables(start: number | undefined, count: number | undefined, filter: 'indexed' | 'named' | undefined): Promise<Variable[]> { return this.session!.variables(this.reference || 0, filter, start, count).then(response => { return response && response.body && response.body.variables ? distinct(response.body.variables.filter(v => !!v && isString(v.name)), (v: DebugProtocol.Variable) => v.name).map((v: DebugProtocol.Variable) => new Variable(this.session, this, v.variablesReference, v.name, v.evaluateName, v.value, v.namedVariables, v.indexedVariables, v.presentationHint, v.type)) : []; }, (e: Error) => [new Variable(this.session, this, 0, e.message, e.message, '', 0, 0, { kind: 'virtual' }, undefined, false)]); } // The adapter explicitly sents the children count of an expression only if there are lots of children which should be chunked. private get getChildrenInChunks(): boolean { return !!this.indexedVariables; } set value(value: string) { this._value = value; this.valueChanged = !!ExpressionContainer.allValues.get(this.getId()) && ExpressionContainer.allValues.get(this.getId()) !== Expression.DEFAULT_VALUE && ExpressionContainer.allValues.get(this.getId()) !== value; ExpressionContainer.allValues.set(this.getId(), value); } toString(): string { return this.value; } } export class Expression extends ExpressionContainer implements IExpression { static DEFAULT_VALUE = nls.localize('notAvailable', "not available"); public available: boolean; public type: string | undefined; constructor(public name: string, id = generateUuid()) { super(undefined, 0, id); this.available = false; // name is not set if the expression is just being added // in that case do not set default value to prevent flashing #14499 if (name) { this.value = Expression.DEFAULT_VALUE; } } async evaluate(session: IDebugSession | undefined, stackFrame: IStackFrame | undefined, context: string): Promise<void> { if (!session || (!stackFrame && context !== 'repl')) { this.value = context === 'repl' ? nls.localize('startDebugFirst', "Please start a debug session to evaluate expressions") : Expression.DEFAULT_VALUE; this.available = false; this.reference = 0; return Promise.resolve(undefined); } this.session = session; try { const response = await session.evaluate(this.name, stackFrame ? stackFrame.frameId : undefined, context); this.available = !!(response && response.body); if (response && response.body) { this.value = response.body.result || ''; this.reference = response.body.variablesReference; this.namedVariables = response.body.namedVariables; this.indexedVariables = response.body.indexedVariables; this.type = response.body.type || this.type; } } catch (e) { this.value = e.message || ''; this.available = false; this.reference = 0; } } toString(): string { return `${this.name}\n${this.value}`; } } export class Variable extends ExpressionContainer implements IExpression { // Used to show the error message coming from the adapter when setting the value #7807 public errorMessage: string | undefined; constructor( session: IDebugSession | undefined, public parent: IExpressionContainer, reference: number | undefined, public name: string, public evaluateName: string | undefined, value: string | undefined, namedVariables: number | undefined, indexedVariables: number | undefined, public presentationHint: DebugProtocol.VariablePresentationHint | undefined, public type: string | undefined = undefined, public available = true, startOfVariables = 0 ) { super(session, reference, `variable:${parent.getId()}:${name}`, namedVariables, indexedVariables, startOfVariables); this.value = value || ''; } async setVariable(value: string): Promise<any> { if (!this.session) { return Promise.resolve(undefined); } try { const response = await this.session.setVariable((<ExpressionContainer>this.parent).reference, this.name, value); if (response && response.body) { this.value = response.body.value || ''; this.type = response.body.type || this.type; this.reference = response.body.variablesReference; this.namedVariables = response.body.namedVariables; this.indexedVariables = response.body.indexedVariables; } } catch (err) { this.errorMessage = err.message; } } toString(): string { return `${this.name}: ${this.value}`; } } export class Scope extends ExpressionContainer implements IScope { constructor( stackFrame: IStackFrame, index: number, public name: string, reference: number, public expensive: boolean, namedVariables?: number, indexedVariables?: number, public range?: IRange ) { super(stackFrame.thread.session, reference, `scope:${name}:${index}`, namedVariables, indexedVariables); } toString(): string { return this.name; } } export class StackFrame implements IStackFrame { private scopes: Promise<Scope[]> | undefined; constructor( public thread: IThread, public frameId: number, public source: Source, public name: string, public presentationHint: string | undefined, public range: IRange, private index: number ) { } getId(): string { return `stackframe:${this.thread.getId()}:${this.frameId}:${this.index}`; } getScopes(): Promise<IScope[]> { if (!this.scopes) { this.scopes = this.thread.session.scopes(this.frameId).then(response => { return response && response.body && response.body.scopes ? response.body.scopes.map((rs, index) => new Scope(this, index, rs.name, rs.variablesReference, rs.expensive, rs.namedVariables, rs.indexedVariables, rs.line && rs.column && rs.endLine && rs.endColumn ? new Range(rs.line, rs.column, rs.endLine, rs.endColumn) : undefined)) : []; }, err => []); } return this.scopes; } getSpecificSourceName(): string { // To reduce flashing of the path name and the way we fetch stack frames // We need to compute the source name based on the other frames in the stale call stack let callStack = (<Thread>this.thread).getStaleCallStack(); callStack = callStack.length > 0 ? callStack : this.thread.getCallStack(); const otherSources = callStack.map(sf => sf.source).filter(s => s !== this.source); let suffixLength = 0; otherSources.forEach(s => { if (s.name === this.source.name) { suffixLength = Math.max(suffixLength, commonSuffixLength(this.source.uri.path, s.uri.path)); } }); if (suffixLength === 0) { return this.source.name; } const from = Math.max(0, this.source.uri.path.lastIndexOf(posix.sep, this.source.uri.path.length - suffixLength - 1)); return (from > 0 ? '...' : '') + this.source.uri.path.substr(from); } getMostSpecificScopes(range: IRange): Promise<IScope[]> { return this.getScopes().then(scopes => { scopes = scopes.filter(s => !s.expensive); const haveRangeInfo = scopes.some(s => !!s.range); if (!haveRangeInfo) { return scopes; } const scopesContainingRange = scopes.filter(scope => scope.range && Range.containsRange(scope.range, range)) .sort((first, second) => (first.range!.endLineNumber - first.range!.startLineNumber) - (second.range!.endLineNumber - second.range!.startLineNumber)); return scopesContainingRange.length ? scopesContainingRange : scopes; }); } restart(): Promise<void> { return this.thread.session.restartFrame(this.frameId, this.thread.threadId); } forgetScopes(): void { this.scopes = undefined; } toString(): string { const lineNumberToString = typeof this.range.startLineNumber === 'number' ? `:${this.range.startLineNumber}` : ''; const sourceToString = `${this.source.inMemory ? this.source.name : this.source.uri.fsPath}${lineNumberToString}`; return sourceToString === UNKNOWN_SOURCE_LABEL ? this.name : `${this.name} (${sourceToString})`; } openInEditor(editorService: IEditorService, preserveFocus?: boolean, sideBySide?: boolean, pinned?: boolean): Promise<ITextEditor | null> { return !this.source.available ? Promise.resolve(null) : this.source.openInEditor(editorService, this.range, preserveFocus, sideBySide, pinned); } } export class Thread implements IThread { private callStack: IStackFrame[]; private staleCallStack: IStackFrame[]; public stoppedDetails: IRawStoppedDetails | undefined; public stopped: boolean; constructor(public session: IDebugSession, public name: string, public threadId: number) { this.callStack = []; this.staleCallStack = []; this.stopped = false; } getId(): string { return `thread:${this.session.getId()}:${this.threadId}`; } clearCallStack(): void { if (this.callStack.length) { this.staleCallStack = this.callStack; } this.callStack = []; } getCallStack(): IStackFrame[] { return this.callStack; } getStaleCallStack(): ReadonlyArray<IStackFrame> { return this.staleCallStack; } get stateLabel(): string { if (this.stoppedDetails) { return this.stoppedDetails.description || this.stoppedDetails.reason ? nls.localize({ key: 'pausedOn', comment: ['indicates reason for program being paused'] }, "Paused on {0}", this.stoppedDetails.reason) : nls.localize('paused', "Paused"); } return nls.localize({ key: 'running', comment: ['indicates state'] }, "Running"); } /** * Queries the debug adapter for the callstack and returns a promise * which completes once the call stack has been retrieved. * If the thread is not stopped, it returns a promise to an empty array. * Only fetches the first stack frame for performance reasons. Calling this method consecutive times * gets the remainder of the call stack. */ fetchCallStack(levels = 20): Promise<void> { if (!this.stopped) { return Promise.resolve(undefined); } const start = this.callStack.length; return this.getCallStackImpl(start, levels).then(callStack => { if (start < this.callStack.length) { // Set the stack frames for exact position we requested. To make sure no concurrent requests create duplicate stack frames #30660 this.callStack.splice(start, this.callStack.length - start); } this.callStack = this.callStack.concat(callStack || []); }); } private getCallStackImpl(startFrame: number, levels: number): Promise<IStackFrame[]> { return this.session.stackTrace(this.threadId, startFrame, levels).then(response => { if (!response || !response.body) { return []; } if (this.stoppedDetails) { this.stoppedDetails.totalFrames = response.body.totalFrames; } return response.body.stackFrames.map((rsf, index) => { const source = this.session.getSource(rsf.source); return new StackFrame(this, rsf.id, source, rsf.name, rsf.presentationHint, new Range( rsf.line, rsf.column, rsf.endLine || rsf.line, rsf.endColumn || rsf.column ), startFrame + index); }); }, (err: Error) => { if (this.stoppedDetails) { this.stoppedDetails.framesErrorMessage = err.message; } return []; }); } /** * Returns exception info promise if the exception was thrown, otherwise undefined */ get exceptionInfo(): Promise<IExceptionInfo | undefined> { if (this.stoppedDetails && this.stoppedDetails.reason === 'exception') { if (this.session.capabilities.supportsExceptionInfoRequest) { return this.session.exceptionInfo(this.threadId); } return Promise.resolve({ description: this.stoppedDetails.text, breakMode: null }); } return Promise.resolve(undefined); } next(): Promise<any> { return this.session.next(this.threadId); } stepIn(): Promise<any> { return this.session.stepIn(this.threadId); } stepOut(): Promise<any> { return this.session.stepOut(this.threadId); } stepBack(): Promise<any> { return this.session.stepBack(this.threadId); } continue(): Promise<any> { return this.session.continue(this.threadId); } pause(): Promise<any> { return this.session.pause(this.threadId); } terminate(): Promise<any> { return this.session.terminateThreads([this.threadId]); } reverseContinue(): Promise<any> { return this.session.reverseContinue(this.threadId); } } export class Enablement implements IEnablement { constructor( public enabled: boolean, private id: string ) { } getId(): string { return this.id; } } export class BaseBreakpoint extends Enablement implements IBaseBreakpoint { private sessionData = new Map<string, DebugProtocol.Breakpoint>(); private sessionId: string | undefined; constructor( enabled: boolean, public hitCondition: string | undefined, public condition: string | undefined, public logMessage: string | undefined, id: string ) { super(enabled, id); if (enabled === undefined) { this.enabled = true; } } protected getSessionData(): DebugProtocol.Breakpoint | undefined { return this.sessionId ? this.sessionData.get(this.sessionId) : undefined; } setSessionData(sessionId: string, data: DebugProtocol.Breakpoint): void { this.sessionData.set(sessionId, data); } setSessionId(sessionId: string | undefined): void { this.sessionId = sessionId; } get verified(): boolean { const data = this.getSessionData(); return data ? data.verified : true; } get idFromAdapter(): number | undefined { const data = this.getSessionData(); return data ? data.id : undefined; } toJSON(): any { const result = Object.create(null); result.enabled = this.enabled; result.condition = this.condition; result.hitCondition = this.hitCondition; result.logMessage = this.logMessage; return result; } } export class Breakpoint extends BaseBreakpoint implements IBreakpoint { constructor( public uri: uri, private _lineNumber: number, private _column: number | undefined, enabled: boolean, condition: string | undefined, hitCondition: string | undefined, logMessage: string | undefined, private _adapterData: any, private textFileService: ITextFileService, id = generateUuid() ) { super(enabled, hitCondition, condition, logMessage, id); } get lineNumber(): number { const data = this.getSessionData(); return this.verified && data && typeof data.line === 'number' ? data.line : this._lineNumber; } get verified(): boolean { const data = this.getSessionData(); if (data) { return data.verified && !this.textFileService.isDirty(this.uri); } return true; } get column(): number | undefined { const data = this.getSessionData(); // Only respect the column if the user explictly set the column to have an inline breakpoint return data && typeof data.column === 'number' && typeof this._column === 'number' ? data.column : this._column; } get message(): string | undefined { const data = this.getSessionData(); if (!data) { return undefined; } if (this.textFileService.isDirty(this.uri)) { return nls.localize('breakpointDirtydHover', "Unverified breakpoint. File is modified, please restart debug session."); } return data.message; } get adapterData(): any { const data = this.getSessionData(); return data && data.source && data.source.adapterData ? data.source.adapterData : this._adapterData; } get endLineNumber(): number | undefined { const data = this.getSessionData(); return data ? data.endLine : undefined; } get endColumn(): number | undefined { const data = this.getSessionData(); return data ? data.endColumn : undefined; } get sessionAgnosticData(): { lineNumber: number, column: number | undefined } { return { lineNumber: this._lineNumber, column: this._column }; } setSessionData(sessionId: string, data: DebugProtocol.Breakpoint): void { super.setSessionData(sessionId, data); if (!this._adapterData) { this._adapterData = this.adapterData; } } toJSON(): any { const result = super.toJSON(); result.uri = this.uri; result.lineNumber = this._lineNumber; result.column = this._column; result.adapterData = this.adapterData; return result; } toString(): string { return resources.basenameOrAuthority(this.uri); } update(data: IBreakpointUpdateData): void { if (!isUndefinedOrNull(data.lineNumber)) { this._lineNumber = data.lineNumber; } if (!isUndefinedOrNull(data.column)) { this._column = data.column; } if (!isUndefinedOrNull(data.condition)) { this.condition = data.condition; } if (!isUndefinedOrNull(data.hitCondition)) { this.hitCondition = data.hitCondition; } if (!isUndefinedOrNull(data.logMessage)) { this.logMessage = data.logMessage; } } } export class FunctionBreakpoint extends BaseBreakpoint implements IFunctionBreakpoint { constructor( public name: string, enabled: boolean, hitCondition: string | undefined, condition: string | undefined, logMessage: string | undefined, id = generateUuid() ) { super(enabled, hitCondition, condition, logMessage, id); } toJSON(): any { const result = super.toJSON(); result.name = this.name; return result; } toString(): string { return this.name; } } export class DataBreakpoint extends BaseBreakpoint implements IDataBreakpoint { constructor( public label: string, public dataId: string, public canPersist: boolean, enabled: boolean, hitCondition: string | undefined, condition: string | undefined, logMessage: string | undefined, id = generateUuid() ) { super(enabled, hitCondition, condition, logMessage, id); } toJSON(): any { const result = super.toJSON(); result.label = this.label; result.dataid = this.dataId; return result; } toString(): string { return this.label; } } export class ExceptionBreakpoint extends Enablement implements IExceptionBreakpoint { constructor(public filter: string, public label: string, enabled: boolean) { super(enabled, generateUuid()); } toJSON(): any { const result = Object.create(null); result.filter = this.filter; result.label = this.label; result.enabled = this.enabled; return result; } toString(): string { return this.label; } } export class ThreadAndSessionIds implements ITreeElement { constructor(public sessionId: string, public threadId: number) { } getId(): string { return `${this.sessionId}:${this.threadId}`; } } export class DebugModel implements IDebugModel { private sessions: IDebugSession[]; private toDispose: lifecycle.IDisposable[]; private schedulers = new Map<string, RunOnceScheduler>(); private breakpointsSessionId: string | undefined; private readonly _onDidChangeBreakpoints: Emitter<IBreakpointsChangeEvent | undefined>; private readonly _onDidChangeCallStack: Emitter<void>; private readonly _onDidChangeWatchExpressions: Emitter<IExpression | undefined>; constructor( private breakpoints: Breakpoint[], private breakpointsActivated: boolean, private functionBreakpoints: FunctionBreakpoint[], private exceptionBreakpoints: ExceptionBreakpoint[], private dataBreakopints: DataBreakpoint[], private watchExpressions: Expression[], private textFileService: ITextFileService ) { this.sessions = []; this.toDispose = []; this._onDidChangeBreakpoints = new Emitter<IBreakpointsChangeEvent>(); this._onDidChangeCallStack = new Emitter<void>(); this._onDidChangeWatchExpressions = new Emitter<IExpression>(); } getId(): string { return 'root'; } getSession(sessionId: string | undefined, includeInactive = false): IDebugSession | undefined { if (sessionId) { return this.getSessions(includeInactive).filter(s => s.getId() === sessionId).pop(); } return undefined; } getSessions(includeInactive = false): IDebugSession[] { // By default do not return inactive sesions. // However we are still holding onto inactive sessions due to repl and debug service session revival (eh scenario) return this.sessions.filter(s => includeInactive || s.state !== State.Inactive); } addSession(session: IDebugSession): void { this.sessions = this.sessions.filter(s => { if (s.getId() === session.getId()) { // Make sure to de-dupe if a session is re-intialized. In case of EH debugging we are adding a session again after an attach. return false; } if (s.state === State.Inactive && s.configuration.name === session.configuration.name) { // Make sure to remove all inactive sessions that are using the same configuration as the new session return false; } return true; }); let index = -1; if (session.parentSession) { // Make sure that child sessions are placed after the parent session index = lastIndex(this.sessions, s => s.parentSession === session.parentSession || s === session.parentSession); } if (index >= 0) { this.sessions.splice(index + 1, 0, session); } else { this.sessions.push(session); } this._onDidChangeCallStack.fire(undefined); } get onDidChangeBreakpoints(): Event<IBreakpointsChangeEvent | undefined> { return this._onDidChangeBreakpoints.event; } get onDidChangeCallStack(): Event<void> { return this._onDidChangeCallStack.event; } get onDidChangeWatchExpressions(): Event<IExpression | undefined> { return this._onDidChangeWatchExpressions.event; } rawUpdate(data: IRawModelUpdate): void { let session = this.sessions.filter(p => p.getId() === data.sessionId).pop(); if (session) { session.rawUpdate(data); this._onDidChangeCallStack.fire(undefined); } } clearThreads(id: string, removeThreads: boolean, reference: number | undefined = undefined): void { const session = this.sessions.filter(p => p.getId() === id).pop(); this.schedulers.forEach(scheduler => scheduler.dispose()); this.schedulers.clear(); if (session) { session.clearThreads(removeThreads, reference); this._onDidChangeCallStack.fire(undefined); } } fetchCallStack(thread: Thread): { topCallStack: Promise<void>, wholeCallStack: Promise<void> } { if (thread.session.capabilities.supportsDelayedStackTraceLoading) { // For improved performance load the first stack frame and then load the rest async. let topCallStack = Promise.resolve(); const wholeCallStack = new Promise<void>((c, e) => { topCallStack = thread.fetchCallStack(1).then(() => { if (!this.schedulers.has(thread.getId())) { this.schedulers.set(thread.getId(), new RunOnceScheduler(() => { thread.fetchCallStack(19).then(() => { this._onDidChangeCallStack.fire(); c(); }); }, 420)); } this.schedulers.get(thread.getId())!.schedule(); }); this._onDidChangeCallStack.fire(); }); return { topCallStack, wholeCallStack }; } const wholeCallStack = thread.fetchCallStack(); return { wholeCallStack, topCallStack: wholeCallStack }; } getBreakpoints(filter?: { uri?: uri, lineNumber?: number, column?: number, enabledOnly?: boolean }): IBreakpoint[] { if (filter) { const uriStr = filter.uri ? filter.uri.toString() : undefined; return this.breakpoints.filter(bp => { if (uriStr && bp.uri.toString() !== uriStr) { return false; } if (filter.lineNumber && bp.lineNumber !== filter.lineNumber) { return false; } if (filter.column && bp.column !== filter.column) { return false; } if (filter.enabledOnly && (!this.breakpointsActivated || !bp.enabled)) { return false; } return true; }); } return this.breakpoints; } getFunctionBreakpoints(): IFunctionBreakpoint[] { return this.functionBreakpoints; } getDataBreakpoints(): IDataBreakpoint[] { return this.dataBreakopints; } getExceptionBreakpoints(): IExceptionBreakpoint[] { return this.exceptionBreakpoints; } setExceptionBreakpoints(data: DebugProtocol.ExceptionBreakpointsFilter[]): void { if (data) { if (this.exceptionBreakpoints.length === data.length && this.exceptionBreakpoints.every((exbp, i) => exbp.filter === data[i].filter && exbp.label === data[i].label)) { // No change return; } this.exceptionBreakpoints = data.map(d => { const ebp = this.exceptionBreakpoints.filter(ebp => ebp.filter === d.filter).pop(); return new ExceptionBreakpoint(d.filter, d.label, ebp ? ebp.enabled : !!d.default); }); this._onDidChangeBreakpoints.fire(undefined); } } areBreakpointsActivated(): boolean { return this.breakpointsActivated; } setBreakpointsActivated(activated: boolean): void { this.breakpointsActivated = activated; this._onDidChangeBreakpoints.fire(undefined); } addBreakpoints(uri: uri, rawData: IBreakpointData[], fireEvent = true): IBreakpoint[] { const newBreakpoints = rawData.map(rawBp => new Breakpoint(uri, rawBp.lineNumber, rawBp.column, rawBp.enabled === false ? false : true, rawBp.condition, rawBp.hitCondition, rawBp.logMessage, undefined, this.textFileService, rawBp.id)); newBreakpoints.forEach(bp => bp.setSessionId(this.breakpointsSessionId)); this.breakpoints = this.breakpoints.concat(newBreakpoints); this.breakpointsActivated = true; this.sortAndDeDup(); if (fireEvent) { this._onDidChangeBreakpoints.fire({ added: newBreakpoints }); } return newBreakpoints; } removeBreakpoints(toRemove: IBreakpoint[]): void { this.breakpoints = this.breakpoints.filter(bp => !toRemove.some(toRemove => toRemove.getId() === bp.getId())); this._onDidChangeBreakpoints.fire({ removed: toRemove }); } updateBreakpoints(data: Map<string, IBreakpointUpdateData>): void { const updated: IBreakpoint[] = []; this.breakpoints.forEach(bp => { const bpData = data.get(bp.getId()); if (bpData) { bp.update(bpData); updated.push(bp); } }); this.sortAndDeDup(); this._onDidChangeBreakpoints.fire({ changed: updated }); } setBreakpointSessionData(sessionId: string, data: Map<string, DebugProtocol.Breakpoint>): void { this.breakpoints.forEach(bp => { const bpData = data.get(bp.getId()); if (bpData) { bp.setSessionData(sessionId, bpData); } }); this.functionBreakpoints.forEach(fbp => { const fbpData = data.get(fbp.getId()); if (fbpData) { fbp.setSessionData(sessionId, fbpData); } }); this.dataBreakopints.forEach(dbp => { const dbpData = data.get(dbp.getId()); if (dbpData) { dbp.setSessionData(sessionId, dbpData); } }); this._onDidChangeBreakpoints.fire({ sessionOnly: true }); } setBreakpointsSessionId(sessionId: string | undefined): void { this.breakpointsSessionId = sessionId; this.breakpoints.forEach(bp => bp.setSessionId(sessionId)); this.functionBreakpoints.forEach(fbp => fbp.setSessionId(sessionId)); this.dataBreakopints.forEach(dbp => dbp.setSessionId(sessionId)); this._onDidChangeBreakpoints.fire({ sessionOnly: true }); } private sortAndDeDup(): void { this.breakpoints = this.breakpoints.sort((first, second) => { if (first.uri.toString() !== second.uri.toString()) { return resources.basenameOrAuthority(first.uri).localeCompare(resources.basenameOrAuthority(second.uri)); } if (first.lineNumber === second.lineNumber) { if (first.column && second.column) { return first.column - second.column; } return -1; } return first.lineNumber - second.lineNumber; }); this.breakpoints = distinct(this.breakpoints, bp => `${bp.uri.toString()}:${bp.lineNumber}:${bp.column}`); } setEnablement(element: IEnablement, enable: boolean): void { if (element instanceof Breakpoint || element instanceof FunctionBreakpoint || element instanceof ExceptionBreakpoint || element instanceof DataBreakpoint) { const changed: Array<IBreakpoint | IFunctionBreakpoint | IDataBreakpoint> = []; if (element.enabled !== enable && (element instanceof Breakpoint || element instanceof FunctionBreakpoint || element instanceof DataBreakpoint)) { changed.push(element); } element.enabled = enable; this._onDidChangeBreakpoints.fire({ changed: changed }); } } enableOrDisableAllBreakpoints(enable: boolean): void { const changed: Array<IBreakpoint | IFunctionBreakpoint | IDataBreakpoint> = []; this.breakpoints.forEach(bp => { if (bp.enabled !== enable) { changed.push(bp); } bp.enabled = enable; }); this.functionBreakpoints.forEach(fbp => { if (fbp.enabled !== enable) { changed.push(fbp); } fbp.enabled = enable; }); this.dataBreakopints.forEach(dbp => { if (dbp.enabled !== enable) { changed.push(dbp); } dbp.enabled = enable; }); this._onDidChangeBreakpoints.fire({ changed: changed }); } addFunctionBreakpoint(functionName: string, id?: string): IFunctionBreakpoint { const newFunctionBreakpoint = new FunctionBreakpoint(functionName, true, undefined, undefined, undefined, id); this.functionBreakpoints.push(newFunctionBreakpoint); this._onDidChangeBreakpoints.fire({ added: [newFunctionBreakpoint] }); return newFunctionBreakpoint; } renameFunctionBreakpoint(id: string, name: string): void { const functionBreakpoint = this.functionBreakpoints.filter(fbp => fbp.getId() === id).pop(); if (functionBreakpoint) { functionBreakpoint.name = name; this._onDidChangeBreakpoints.fire({ changed: [functionBreakpoint] }); } } removeFunctionBreakpoints(id?: string): void { let removed: FunctionBreakpoint[]; if (id) { removed = this.functionBreakpoints.filter(fbp => fbp.getId() === id); this.functionBreakpoints = this.functionBreakpoints.filter(fbp => fbp.getId() !== id); } else { removed = this.functionBreakpoints; this.functionBreakpoints = []; } this._onDidChangeBreakpoints.fire({ removed }); } addDataBreakpoint(label: string, dataId: string, canPersist: boolean): void { const newDataBreakpoint = new DataBreakpoint(label, dataId, canPersist, true, undefined, undefined, undefined); this.dataBreakopints.push(newDataBreakpoint); this._onDidChangeBreakpoints.fire({ added: [newDataBreakpoint] }); } removeDataBreakpoints(id?: string): void { let removed: DataBreakpoint[]; if (id) { removed = this.dataBreakopints.filter(fbp => fbp.getId() === id); this.dataBreakopints = this.dataBreakopints.filter(fbp => fbp.getId() !== id); } else { removed = this.dataBreakopints; this.dataBreakopints = []; } this._onDidChangeBreakpoints.fire({ removed }); } getWatchExpressions(): Expression[] { return this.watchExpressions; } addWatchExpression(name: string): IExpression { const we = new Expression(name); this.watchExpressions.push(we); this._onDidChangeWatchExpressions.fire(we); return we; } renameWatchExpression(id: string, newName: string): void { const filtered = this.watchExpressions.filter(we => we.getId() === id); if (filtered.length === 1) { filtered[0].name = newName; this._onDidChangeWatchExpressions.fire(filtered[0]); } } removeWatchExpressions(id: string | null = null): void { this.watchExpressions = id ? this.watchExpressions.filter(we => we.getId() !== id) : []; this._onDidChangeWatchExpressions.fire(undefined); } moveWatchExpression(id: string, position: number): void { const we = this.watchExpressions.filter(we => we.getId() === id).pop(); if (we) { this.watchExpressions = this.watchExpressions.filter(we => we.getId() !== id); this.watchExpressions = this.watchExpressions.slice(0, position).concat(we, this.watchExpressions.slice(position)); this._onDidChangeWatchExpressions.fire(undefined); } } sourceIsNotAvailable(uri: uri): void { this.sessions.forEach(s => { const source = s.getSourceForUri(uri); if (source) { source.available = false; } }); this._onDidChangeCallStack.fire(undefined); } dispose(): void { // Make sure to shutdown each session, such that no debugged process is left laying around this.sessions.forEach(s => s.shutdown()); this.toDispose = lifecycle.dispose(this.toDispose); } }
src/vs/workbench/contrib/debug/common/debugModel.ts
1
https://github.com/microsoft/vscode/commit/20e24e879acc220cbb9b365001b5d1427824edaf
[ 0.2340097725391388, 0.002909046597778797, 0.0001580496464157477, 0.0001737164711812511, 0.02138097770512104 ]
{ "id": 2, "code_window": [ "\t\tthis.storeBreakpoints();\n", "\t}\n", "\n", "\tsetBreakpointsActivated(activated: boolean): Promise<void> {\n", "\t\tthis.model.setBreakpointsActivated(activated);\n", "\t\tif (activated) {\n", "\t\t\tthis.storageService.store(DEBUG_BREAKPOINTS_ACTIVATED_KEY, 'false', StorageScope.WORKSPACE);\n", "\t\t} else {\n", "\t\t\tthis.storageService.remove(DEBUG_BREAKPOINTS_ACTIVATED_KEY, StorageScope.WORKSPACE);\n", "\t\t}\n", "\n", "\t\treturn this.sendAllBreakpoints();\n", "\t}\n", "\n", "\taddFunctionBreakpoint(name?: string, id?: string): void {\n", "\t\tconst newFunctionBreakpoint = this.model.addFunctionBreakpoint(name || '', id);\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/debug/browser/debugService.ts", "type": "replace", "edit_start_line_idx": 903 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as vscode from 'vscode'; import { runScript, findScriptAtPosition } from './tasks'; import * as nls from 'vscode-nls'; const localize = nls.loadMessageBundle(); export function runSelectedScript() { let editor = vscode.window.activeTextEditor; if (!editor) { return; } let document = editor.document; let contents = document.getText(); let selection = editor.selection; let offset = document.offsetAt(selection.anchor); let script = findScriptAtPosition(contents, offset); if (script) { runScript(script, document); } else { let message = localize('noScriptFound', 'Could not find a valid npm script at the selection.'); vscode.window.showErrorMessage(message); } }
extensions/npm/src/commands.ts
0
https://github.com/microsoft/vscode/commit/20e24e879acc220cbb9b365001b5d1427824edaf
[ 0.0001777525758370757, 0.00017553797806613147, 0.0001728785427985713, 0.00017576038953848183, 0.0000020189406768622575 ]
{ "id": 2, "code_window": [ "\t\tthis.storeBreakpoints();\n", "\t}\n", "\n", "\tsetBreakpointsActivated(activated: boolean): Promise<void> {\n", "\t\tthis.model.setBreakpointsActivated(activated);\n", "\t\tif (activated) {\n", "\t\t\tthis.storageService.store(DEBUG_BREAKPOINTS_ACTIVATED_KEY, 'false', StorageScope.WORKSPACE);\n", "\t\t} else {\n", "\t\t\tthis.storageService.remove(DEBUG_BREAKPOINTS_ACTIVATED_KEY, StorageScope.WORKSPACE);\n", "\t\t}\n", "\n", "\t\treturn this.sendAllBreakpoints();\n", "\t}\n", "\n", "\taddFunctionBreakpoint(name?: string, id?: string): void {\n", "\t\tconst newFunctionBreakpoint = this.model.addFunctionBreakpoint(name || '', id);\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/debug/browser/debugService.ts", "type": "replace", "edit_start_line_idx": 903 }
{ "name": "code-oss-dev-smoke-test", "version": "0.1.0", "main": "./src/main.js", "scripts": { "postinstall": "npm run compile", "compile": "npm run copy-driver && npm run copy-driver-definition && tsc", "watch": "concurrently \"npm run watch-driver\" \"npm run watch-driver-definition\" \"tsc --watch\"", "copy-driver": "cpx src/vscode/driver.js out/vscode", "watch-driver": "cpx src/vscode/driver.js out/vscode -w", "copy-driver-definition": "node tools/copy-driver-definition.js", "watch-driver-definition": "watch \"node tools/copy-driver-definition.js\" ../../src/vs/platform/driver/node", "mocha": "mocha" }, "devDependencies": { "@types/htmlparser2": "3.7.29", "@types/mkdirp": "0.5.1", "@types/mocha": "2.2.41", "@types/ncp": "2.0.1", "@types/node": "^10.14.8", "@types/puppeteer": "^1.19.0", "@types/rimraf": "2.0.2", "@types/webdriverio": "4.6.1", "concurrently": "^3.5.1", "cpx": "^1.5.0", "electron": "4.2.9", "htmlparser2": "^3.9.2", "mkdirp": "^0.5.1", "mocha": "^5.2.0", "mocha-junit-reporter": "^1.17.0", "mocha-multi-reporters": "^1.1.7", "ncp": "^2.0.0", "portastic": "^1.0.1", "rimraf": "^2.6.1", "strip-json-comments": "^2.0.1", "tmp": "0.0.33", "typescript": "2.9.2", "watch": "^1.0.2" }, "dependencies": { "vscode-uri": "^2.0.3" } }
test/smoke/package.json
0
https://github.com/microsoft/vscode/commit/20e24e879acc220cbb9b365001b5d1427824edaf
[ 0.00017653830582275987, 0.00017384039529133588, 0.0001722912274999544, 0.0001733984099701047, 0.0000015055048834256013 ]
{ "id": 2, "code_window": [ "\t\tthis.storeBreakpoints();\n", "\t}\n", "\n", "\tsetBreakpointsActivated(activated: boolean): Promise<void> {\n", "\t\tthis.model.setBreakpointsActivated(activated);\n", "\t\tif (activated) {\n", "\t\t\tthis.storageService.store(DEBUG_BREAKPOINTS_ACTIVATED_KEY, 'false', StorageScope.WORKSPACE);\n", "\t\t} else {\n", "\t\t\tthis.storageService.remove(DEBUG_BREAKPOINTS_ACTIVATED_KEY, StorageScope.WORKSPACE);\n", "\t\t}\n", "\n", "\t\treturn this.sendAllBreakpoints();\n", "\t}\n", "\n", "\taddFunctionBreakpoint(name?: string, id?: string): void {\n", "\t\tconst newFunctionBreakpoint = this.model.addFunctionBreakpoint(name || '', id);\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/debug/browser/debugService.ts", "type": "replace", "edit_start_line_idx": 903 }
/*--------------------------------------------------------------------------------------------- * 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 { Event } from 'vs/base/common/event'; import { Color } from 'vs/base/common/color'; import { ITheme, IThemeService, IIconTheme } from 'vs/platform/theme/common/themeService'; import { ConfigurationTarget } from 'vs/platform/configuration/common/configuration'; export const IWorkbenchThemeService = createDecorator<IWorkbenchThemeService>('themeService'); export const VS_LIGHT_THEME = 'vs'; export const VS_DARK_THEME = 'vs-dark'; export const VS_HC_THEME = 'hc-black'; export const HC_THEME_ID = 'Default High Contrast'; export const COLOR_THEME_SETTING = 'workbench.colorTheme'; export const DETECT_HC_SETTING = 'window.autoDetectHighContrast'; export const ICON_THEME_SETTING = 'workbench.iconTheme'; export const CUSTOM_WORKBENCH_COLORS_SETTING = 'workbench.colorCustomizations'; export const CUSTOM_EDITOR_COLORS_SETTING = 'editor.tokenColorCustomizations'; export interface IColorTheme extends ITheme { readonly id: string; readonly label: string; readonly settingsId: string; readonly extensionData?: ExtensionData; readonly description?: string; readonly isLoaded: boolean; readonly tokenColors: ITokenColorizationRule[]; } export interface IColorMap { [id: string]: Color; } export interface IFileIconTheme extends IIconTheme { readonly id: string; readonly label: string; readonly settingsId: string | null; readonly description?: string; readonly extensionData?: ExtensionData; readonly isLoaded: boolean; readonly hasFileIcons: boolean; readonly hasFolderIcons: boolean; readonly hidesExplorerArrows: boolean; } export interface IWorkbenchThemeService extends IThemeService { _serviceBrand: any; setColorTheme(themeId: string | undefined, settingsTarget: ConfigurationTarget | undefined): Promise<IColorTheme | null>; getColorTheme(): IColorTheme; getColorThemes(): Promise<IColorTheme[]>; onDidColorThemeChange: Event<IColorTheme>; restoreColorTheme(): void; setFileIconTheme(iconThemeId: string | undefined, settingsTarget: ConfigurationTarget | undefined): Promise<IFileIconTheme>; getFileIconTheme(): IFileIconTheme; getFileIconThemes(): Promise<IFileIconTheme[]>; onDidFileIconThemeChange: Event<IFileIconTheme>; } export interface IColorCustomizations { [colorIdOrThemeSettingsId: string]: string | IColorCustomizations; } export interface ITokenColorCustomizations { [groupIdOrThemeSettingsId: string]: string | ITokenColorizationSetting | ITokenColorCustomizations | undefined | ITokenColorizationRule[]; comments?: string | ITokenColorizationSetting; strings?: string | ITokenColorizationSetting; numbers?: string | ITokenColorizationSetting; keywords?: string | ITokenColorizationSetting; types?: string | ITokenColorizationSetting; functions?: string | ITokenColorizationSetting; variables?: string | ITokenColorizationSetting; textMateRules?: ITokenColorizationRule[]; } export interface ITokenColorizationRule { name?: string; scope?: string | string[]; settings: ITokenColorizationSetting; } export interface ITokenColorizationSetting { foreground?: string; background?: string; fontStyle?: string; // italic, underline, bold } export interface ExtensionData { extensionId: string; extensionPublisher: string; extensionName: string; extensionIsBuiltin: boolean; } export interface IThemeExtensionPoint { id: string; label?: string; description?: string; path: string; uiTheme?: typeof VS_LIGHT_THEME | typeof VS_DARK_THEME | typeof VS_HC_THEME; _watch: boolean; // unsupported options to watch location }
src/vs/workbench/services/themes/common/workbenchThemeService.ts
0
https://github.com/microsoft/vscode/commit/20e24e879acc220cbb9b365001b5d1427824edaf
[ 0.00017672372632659972, 0.000173231223016046, 0.00016627786681056023, 0.00017440675583202392, 0.0000031845993362367153 ]
{ "id": 3, "code_window": [ "\tprivate sessions: IDebugSession[];\n", "\tprivate toDispose: lifecycle.IDisposable[];\n", "\tprivate schedulers = new Map<string, RunOnceScheduler>();\n", "\tprivate breakpointsSessionId: string | undefined;\n", "\tprivate readonly _onDidChangeBreakpoints: Emitter<IBreakpointsChangeEvent | undefined>;\n", "\tprivate readonly _onDidChangeCallStack: Emitter<void>;\n", "\tprivate readonly _onDidChangeWatchExpressions: Emitter<IExpression | undefined>;\n", "\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tprivate breakpointsActivated = true;\n" ], "file_path": "src/vs/workbench/contrib/debug/common/debugModel.ts", "type": "add", "edit_start_line_idx": 799 }
/*--------------------------------------------------------------------------------------------- * 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 { URI as uri } from 'vs/base/common/uri'; import * as resources from 'vs/base/common/resources'; import * as lifecycle from 'vs/base/common/lifecycle'; import { Event, Emitter } from 'vs/base/common/event'; import { generateUuid } from 'vs/base/common/uuid'; import { RunOnceScheduler } from 'vs/base/common/async'; import severity from 'vs/base/common/severity'; import { isObject, isString, isUndefinedOrNull } from 'vs/base/common/types'; import { distinct, lastIndex } from 'vs/base/common/arrays'; import { Range, IRange } from 'vs/editor/common/core/range'; import { ITreeElement, IExpression, IExpressionContainer, IDebugSession, IStackFrame, IExceptionBreakpoint, IBreakpoint, IFunctionBreakpoint, IDebugModel, IReplElementSource, IThread, IRawModelUpdate, IScope, IRawStoppedDetails, IEnablement, IBreakpointData, IExceptionInfo, IReplElement, IBreakpointsChangeEvent, IBreakpointUpdateData, IBaseBreakpoint, State, IDataBreakpoint } from 'vs/workbench/contrib/debug/common/debug'; import { Source, UNKNOWN_SOURCE_LABEL } from 'vs/workbench/contrib/debug/common/debugSource'; import { commonSuffixLength } from 'vs/base/common/strings'; import { posix } from 'vs/base/common/path'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { ITextFileService } from 'vs/workbench/services/textfile/common/textfiles'; import { ITextEditor } from 'vs/workbench/common/editor'; export class SimpleReplElement implements IReplElement { constructor( private id: string, public value: string, public severity: severity, public sourceData?: IReplElementSource, ) { } toString(): string { return this.value; } getId(): string { return this.id; } } export class RawObjectReplElement implements IExpression { private static readonly MAX_CHILDREN = 1000; // upper bound of children per value constructor(private id: string, public name: string, public valueObj: any, public sourceData?: IReplElementSource, public annotation?: string) { } getId(): string { return this.id; } get value(): string { if (this.valueObj === null) { return 'null'; } else if (Array.isArray(this.valueObj)) { return `Array[${this.valueObj.length}]`; } else if (isObject(this.valueObj)) { return 'Object'; } else if (isString(this.valueObj)) { return `"${this.valueObj}"`; } return String(this.valueObj) || ''; } get hasChildren(): boolean { return (Array.isArray(this.valueObj) && this.valueObj.length > 0) || (isObject(this.valueObj) && Object.getOwnPropertyNames(this.valueObj).length > 0); } getChildren(): Promise<IExpression[]> { let result: IExpression[] = []; if (Array.isArray(this.valueObj)) { result = (<any[]>this.valueObj).slice(0, RawObjectReplElement.MAX_CHILDREN) .map((v, index) => new RawObjectReplElement(`${this.id}:${index}`, String(index), v)); } else if (isObject(this.valueObj)) { result = Object.getOwnPropertyNames(this.valueObj).slice(0, RawObjectReplElement.MAX_CHILDREN) .map((key, index) => new RawObjectReplElement(`${this.id}:${index}`, key, this.valueObj[key])); } return Promise.resolve(result); } toString(): string { return `${this.name}\n${this.value}`; } } export class ExpressionContainer implements IExpressionContainer { public static allValues = new Map<string, string>(); // Use chunks to support variable paging #9537 private static readonly BASE_CHUNK_SIZE = 100; public valueChanged = false; private _value: string = ''; protected children?: Promise<IExpression[]>; constructor( protected session: IDebugSession | undefined, private _reference: number | undefined, private id: string, public namedVariables: number | undefined = 0, public indexedVariables: number | undefined = 0, private startOfVariables: number | undefined = 0 ) { } get reference(): number | undefined { return this._reference; } set reference(value: number | undefined) { this._reference = value; this.children = undefined; // invalidate children cache } getChildren(): Promise<IExpression[]> { if (!this.children) { this.children = this.doGetChildren(); } return this.children; } private async doGetChildren(): Promise<IExpression[]> { if (!this.hasChildren) { return Promise.resolve([]); } if (!this.getChildrenInChunks) { return this.fetchVariables(undefined, undefined, undefined); } // Check if object has named variables, fetch them independent from indexed variables #9670 const children = this.namedVariables ? await this.fetchVariables(undefined, undefined, 'named') : []; // Use a dynamic chunk size based on the number of elements #9774 let chunkSize = ExpressionContainer.BASE_CHUNK_SIZE; while (!!this.indexedVariables && this.indexedVariables > chunkSize * ExpressionContainer.BASE_CHUNK_SIZE) { chunkSize *= ExpressionContainer.BASE_CHUNK_SIZE; } if (!!this.indexedVariables && this.indexedVariables > chunkSize) { // There are a lot of children, create fake intermediate values that represent chunks #9537 const numberOfChunks = Math.ceil(this.indexedVariables / chunkSize); for (let i = 0; i < numberOfChunks; i++) { const start = (this.startOfVariables || 0) + i * chunkSize; const count = Math.min(chunkSize, this.indexedVariables - i * chunkSize); children.push(new Variable(this.session, this, this.reference, `[${start}..${start + count - 1}]`, '', '', undefined, count, { kind: 'virtual' }, undefined, true, start)); } return children; } const variables = await this.fetchVariables(this.startOfVariables, this.indexedVariables, 'indexed'); return children.concat(variables); } getId(): string { return this.id; } get value(): string { return this._value; } get hasChildren(): boolean { // only variables with reference > 0 have children. return !!this.reference && this.reference > 0; } private fetchVariables(start: number | undefined, count: number | undefined, filter: 'indexed' | 'named' | undefined): Promise<Variable[]> { return this.session!.variables(this.reference || 0, filter, start, count).then(response => { return response && response.body && response.body.variables ? distinct(response.body.variables.filter(v => !!v && isString(v.name)), (v: DebugProtocol.Variable) => v.name).map((v: DebugProtocol.Variable) => new Variable(this.session, this, v.variablesReference, v.name, v.evaluateName, v.value, v.namedVariables, v.indexedVariables, v.presentationHint, v.type)) : []; }, (e: Error) => [new Variable(this.session, this, 0, e.message, e.message, '', 0, 0, { kind: 'virtual' }, undefined, false)]); } // The adapter explicitly sents the children count of an expression only if there are lots of children which should be chunked. private get getChildrenInChunks(): boolean { return !!this.indexedVariables; } set value(value: string) { this._value = value; this.valueChanged = !!ExpressionContainer.allValues.get(this.getId()) && ExpressionContainer.allValues.get(this.getId()) !== Expression.DEFAULT_VALUE && ExpressionContainer.allValues.get(this.getId()) !== value; ExpressionContainer.allValues.set(this.getId(), value); } toString(): string { return this.value; } } export class Expression extends ExpressionContainer implements IExpression { static DEFAULT_VALUE = nls.localize('notAvailable', "not available"); public available: boolean; public type: string | undefined; constructor(public name: string, id = generateUuid()) { super(undefined, 0, id); this.available = false; // name is not set if the expression is just being added // in that case do not set default value to prevent flashing #14499 if (name) { this.value = Expression.DEFAULT_VALUE; } } async evaluate(session: IDebugSession | undefined, stackFrame: IStackFrame | undefined, context: string): Promise<void> { if (!session || (!stackFrame && context !== 'repl')) { this.value = context === 'repl' ? nls.localize('startDebugFirst', "Please start a debug session to evaluate expressions") : Expression.DEFAULT_VALUE; this.available = false; this.reference = 0; return Promise.resolve(undefined); } this.session = session; try { const response = await session.evaluate(this.name, stackFrame ? stackFrame.frameId : undefined, context); this.available = !!(response && response.body); if (response && response.body) { this.value = response.body.result || ''; this.reference = response.body.variablesReference; this.namedVariables = response.body.namedVariables; this.indexedVariables = response.body.indexedVariables; this.type = response.body.type || this.type; } } catch (e) { this.value = e.message || ''; this.available = false; this.reference = 0; } } toString(): string { return `${this.name}\n${this.value}`; } } export class Variable extends ExpressionContainer implements IExpression { // Used to show the error message coming from the adapter when setting the value #7807 public errorMessage: string | undefined; constructor( session: IDebugSession | undefined, public parent: IExpressionContainer, reference: number | undefined, public name: string, public evaluateName: string | undefined, value: string | undefined, namedVariables: number | undefined, indexedVariables: number | undefined, public presentationHint: DebugProtocol.VariablePresentationHint | undefined, public type: string | undefined = undefined, public available = true, startOfVariables = 0 ) { super(session, reference, `variable:${parent.getId()}:${name}`, namedVariables, indexedVariables, startOfVariables); this.value = value || ''; } async setVariable(value: string): Promise<any> { if (!this.session) { return Promise.resolve(undefined); } try { const response = await this.session.setVariable((<ExpressionContainer>this.parent).reference, this.name, value); if (response && response.body) { this.value = response.body.value || ''; this.type = response.body.type || this.type; this.reference = response.body.variablesReference; this.namedVariables = response.body.namedVariables; this.indexedVariables = response.body.indexedVariables; } } catch (err) { this.errorMessage = err.message; } } toString(): string { return `${this.name}: ${this.value}`; } } export class Scope extends ExpressionContainer implements IScope { constructor( stackFrame: IStackFrame, index: number, public name: string, reference: number, public expensive: boolean, namedVariables?: number, indexedVariables?: number, public range?: IRange ) { super(stackFrame.thread.session, reference, `scope:${name}:${index}`, namedVariables, indexedVariables); } toString(): string { return this.name; } } export class StackFrame implements IStackFrame { private scopes: Promise<Scope[]> | undefined; constructor( public thread: IThread, public frameId: number, public source: Source, public name: string, public presentationHint: string | undefined, public range: IRange, private index: number ) { } getId(): string { return `stackframe:${this.thread.getId()}:${this.frameId}:${this.index}`; } getScopes(): Promise<IScope[]> { if (!this.scopes) { this.scopes = this.thread.session.scopes(this.frameId).then(response => { return response && response.body && response.body.scopes ? response.body.scopes.map((rs, index) => new Scope(this, index, rs.name, rs.variablesReference, rs.expensive, rs.namedVariables, rs.indexedVariables, rs.line && rs.column && rs.endLine && rs.endColumn ? new Range(rs.line, rs.column, rs.endLine, rs.endColumn) : undefined)) : []; }, err => []); } return this.scopes; } getSpecificSourceName(): string { // To reduce flashing of the path name and the way we fetch stack frames // We need to compute the source name based on the other frames in the stale call stack let callStack = (<Thread>this.thread).getStaleCallStack(); callStack = callStack.length > 0 ? callStack : this.thread.getCallStack(); const otherSources = callStack.map(sf => sf.source).filter(s => s !== this.source); let suffixLength = 0; otherSources.forEach(s => { if (s.name === this.source.name) { suffixLength = Math.max(suffixLength, commonSuffixLength(this.source.uri.path, s.uri.path)); } }); if (suffixLength === 0) { return this.source.name; } const from = Math.max(0, this.source.uri.path.lastIndexOf(posix.sep, this.source.uri.path.length - suffixLength - 1)); return (from > 0 ? '...' : '') + this.source.uri.path.substr(from); } getMostSpecificScopes(range: IRange): Promise<IScope[]> { return this.getScopes().then(scopes => { scopes = scopes.filter(s => !s.expensive); const haveRangeInfo = scopes.some(s => !!s.range); if (!haveRangeInfo) { return scopes; } const scopesContainingRange = scopes.filter(scope => scope.range && Range.containsRange(scope.range, range)) .sort((first, second) => (first.range!.endLineNumber - first.range!.startLineNumber) - (second.range!.endLineNumber - second.range!.startLineNumber)); return scopesContainingRange.length ? scopesContainingRange : scopes; }); } restart(): Promise<void> { return this.thread.session.restartFrame(this.frameId, this.thread.threadId); } forgetScopes(): void { this.scopes = undefined; } toString(): string { const lineNumberToString = typeof this.range.startLineNumber === 'number' ? `:${this.range.startLineNumber}` : ''; const sourceToString = `${this.source.inMemory ? this.source.name : this.source.uri.fsPath}${lineNumberToString}`; return sourceToString === UNKNOWN_SOURCE_LABEL ? this.name : `${this.name} (${sourceToString})`; } openInEditor(editorService: IEditorService, preserveFocus?: boolean, sideBySide?: boolean, pinned?: boolean): Promise<ITextEditor | null> { return !this.source.available ? Promise.resolve(null) : this.source.openInEditor(editorService, this.range, preserveFocus, sideBySide, pinned); } } export class Thread implements IThread { private callStack: IStackFrame[]; private staleCallStack: IStackFrame[]; public stoppedDetails: IRawStoppedDetails | undefined; public stopped: boolean; constructor(public session: IDebugSession, public name: string, public threadId: number) { this.callStack = []; this.staleCallStack = []; this.stopped = false; } getId(): string { return `thread:${this.session.getId()}:${this.threadId}`; } clearCallStack(): void { if (this.callStack.length) { this.staleCallStack = this.callStack; } this.callStack = []; } getCallStack(): IStackFrame[] { return this.callStack; } getStaleCallStack(): ReadonlyArray<IStackFrame> { return this.staleCallStack; } get stateLabel(): string { if (this.stoppedDetails) { return this.stoppedDetails.description || this.stoppedDetails.reason ? nls.localize({ key: 'pausedOn', comment: ['indicates reason for program being paused'] }, "Paused on {0}", this.stoppedDetails.reason) : nls.localize('paused', "Paused"); } return nls.localize({ key: 'running', comment: ['indicates state'] }, "Running"); } /** * Queries the debug adapter for the callstack and returns a promise * which completes once the call stack has been retrieved. * If the thread is not stopped, it returns a promise to an empty array. * Only fetches the first stack frame for performance reasons. Calling this method consecutive times * gets the remainder of the call stack. */ fetchCallStack(levels = 20): Promise<void> { if (!this.stopped) { return Promise.resolve(undefined); } const start = this.callStack.length; return this.getCallStackImpl(start, levels).then(callStack => { if (start < this.callStack.length) { // Set the stack frames for exact position we requested. To make sure no concurrent requests create duplicate stack frames #30660 this.callStack.splice(start, this.callStack.length - start); } this.callStack = this.callStack.concat(callStack || []); }); } private getCallStackImpl(startFrame: number, levels: number): Promise<IStackFrame[]> { return this.session.stackTrace(this.threadId, startFrame, levels).then(response => { if (!response || !response.body) { return []; } if (this.stoppedDetails) { this.stoppedDetails.totalFrames = response.body.totalFrames; } return response.body.stackFrames.map((rsf, index) => { const source = this.session.getSource(rsf.source); return new StackFrame(this, rsf.id, source, rsf.name, rsf.presentationHint, new Range( rsf.line, rsf.column, rsf.endLine || rsf.line, rsf.endColumn || rsf.column ), startFrame + index); }); }, (err: Error) => { if (this.stoppedDetails) { this.stoppedDetails.framesErrorMessage = err.message; } return []; }); } /** * Returns exception info promise if the exception was thrown, otherwise undefined */ get exceptionInfo(): Promise<IExceptionInfo | undefined> { if (this.stoppedDetails && this.stoppedDetails.reason === 'exception') { if (this.session.capabilities.supportsExceptionInfoRequest) { return this.session.exceptionInfo(this.threadId); } return Promise.resolve({ description: this.stoppedDetails.text, breakMode: null }); } return Promise.resolve(undefined); } next(): Promise<any> { return this.session.next(this.threadId); } stepIn(): Promise<any> { return this.session.stepIn(this.threadId); } stepOut(): Promise<any> { return this.session.stepOut(this.threadId); } stepBack(): Promise<any> { return this.session.stepBack(this.threadId); } continue(): Promise<any> { return this.session.continue(this.threadId); } pause(): Promise<any> { return this.session.pause(this.threadId); } terminate(): Promise<any> { return this.session.terminateThreads([this.threadId]); } reverseContinue(): Promise<any> { return this.session.reverseContinue(this.threadId); } } export class Enablement implements IEnablement { constructor( public enabled: boolean, private id: string ) { } getId(): string { return this.id; } } export class BaseBreakpoint extends Enablement implements IBaseBreakpoint { private sessionData = new Map<string, DebugProtocol.Breakpoint>(); private sessionId: string | undefined; constructor( enabled: boolean, public hitCondition: string | undefined, public condition: string | undefined, public logMessage: string | undefined, id: string ) { super(enabled, id); if (enabled === undefined) { this.enabled = true; } } protected getSessionData(): DebugProtocol.Breakpoint | undefined { return this.sessionId ? this.sessionData.get(this.sessionId) : undefined; } setSessionData(sessionId: string, data: DebugProtocol.Breakpoint): void { this.sessionData.set(sessionId, data); } setSessionId(sessionId: string | undefined): void { this.sessionId = sessionId; } get verified(): boolean { const data = this.getSessionData(); return data ? data.verified : true; } get idFromAdapter(): number | undefined { const data = this.getSessionData(); return data ? data.id : undefined; } toJSON(): any { const result = Object.create(null); result.enabled = this.enabled; result.condition = this.condition; result.hitCondition = this.hitCondition; result.logMessage = this.logMessage; return result; } } export class Breakpoint extends BaseBreakpoint implements IBreakpoint { constructor( public uri: uri, private _lineNumber: number, private _column: number | undefined, enabled: boolean, condition: string | undefined, hitCondition: string | undefined, logMessage: string | undefined, private _adapterData: any, private textFileService: ITextFileService, id = generateUuid() ) { super(enabled, hitCondition, condition, logMessage, id); } get lineNumber(): number { const data = this.getSessionData(); return this.verified && data && typeof data.line === 'number' ? data.line : this._lineNumber; } get verified(): boolean { const data = this.getSessionData(); if (data) { return data.verified && !this.textFileService.isDirty(this.uri); } return true; } get column(): number | undefined { const data = this.getSessionData(); // Only respect the column if the user explictly set the column to have an inline breakpoint return data && typeof data.column === 'number' && typeof this._column === 'number' ? data.column : this._column; } get message(): string | undefined { const data = this.getSessionData(); if (!data) { return undefined; } if (this.textFileService.isDirty(this.uri)) { return nls.localize('breakpointDirtydHover', "Unverified breakpoint. File is modified, please restart debug session."); } return data.message; } get adapterData(): any { const data = this.getSessionData(); return data && data.source && data.source.adapterData ? data.source.adapterData : this._adapterData; } get endLineNumber(): number | undefined { const data = this.getSessionData(); return data ? data.endLine : undefined; } get endColumn(): number | undefined { const data = this.getSessionData(); return data ? data.endColumn : undefined; } get sessionAgnosticData(): { lineNumber: number, column: number | undefined } { return { lineNumber: this._lineNumber, column: this._column }; } setSessionData(sessionId: string, data: DebugProtocol.Breakpoint): void { super.setSessionData(sessionId, data); if (!this._adapterData) { this._adapterData = this.adapterData; } } toJSON(): any { const result = super.toJSON(); result.uri = this.uri; result.lineNumber = this._lineNumber; result.column = this._column; result.adapterData = this.adapterData; return result; } toString(): string { return resources.basenameOrAuthority(this.uri); } update(data: IBreakpointUpdateData): void { if (!isUndefinedOrNull(data.lineNumber)) { this._lineNumber = data.lineNumber; } if (!isUndefinedOrNull(data.column)) { this._column = data.column; } if (!isUndefinedOrNull(data.condition)) { this.condition = data.condition; } if (!isUndefinedOrNull(data.hitCondition)) { this.hitCondition = data.hitCondition; } if (!isUndefinedOrNull(data.logMessage)) { this.logMessage = data.logMessage; } } } export class FunctionBreakpoint extends BaseBreakpoint implements IFunctionBreakpoint { constructor( public name: string, enabled: boolean, hitCondition: string | undefined, condition: string | undefined, logMessage: string | undefined, id = generateUuid() ) { super(enabled, hitCondition, condition, logMessage, id); } toJSON(): any { const result = super.toJSON(); result.name = this.name; return result; } toString(): string { return this.name; } } export class DataBreakpoint extends BaseBreakpoint implements IDataBreakpoint { constructor( public label: string, public dataId: string, public canPersist: boolean, enabled: boolean, hitCondition: string | undefined, condition: string | undefined, logMessage: string | undefined, id = generateUuid() ) { super(enabled, hitCondition, condition, logMessage, id); } toJSON(): any { const result = super.toJSON(); result.label = this.label; result.dataid = this.dataId; return result; } toString(): string { return this.label; } } export class ExceptionBreakpoint extends Enablement implements IExceptionBreakpoint { constructor(public filter: string, public label: string, enabled: boolean) { super(enabled, generateUuid()); } toJSON(): any { const result = Object.create(null); result.filter = this.filter; result.label = this.label; result.enabled = this.enabled; return result; } toString(): string { return this.label; } } export class ThreadAndSessionIds implements ITreeElement { constructor(public sessionId: string, public threadId: number) { } getId(): string { return `${this.sessionId}:${this.threadId}`; } } export class DebugModel implements IDebugModel { private sessions: IDebugSession[]; private toDispose: lifecycle.IDisposable[]; private schedulers = new Map<string, RunOnceScheduler>(); private breakpointsSessionId: string | undefined; private readonly _onDidChangeBreakpoints: Emitter<IBreakpointsChangeEvent | undefined>; private readonly _onDidChangeCallStack: Emitter<void>; private readonly _onDidChangeWatchExpressions: Emitter<IExpression | undefined>; constructor( private breakpoints: Breakpoint[], private breakpointsActivated: boolean, private functionBreakpoints: FunctionBreakpoint[], private exceptionBreakpoints: ExceptionBreakpoint[], private dataBreakopints: DataBreakpoint[], private watchExpressions: Expression[], private textFileService: ITextFileService ) { this.sessions = []; this.toDispose = []; this._onDidChangeBreakpoints = new Emitter<IBreakpointsChangeEvent>(); this._onDidChangeCallStack = new Emitter<void>(); this._onDidChangeWatchExpressions = new Emitter<IExpression>(); } getId(): string { return 'root'; } getSession(sessionId: string | undefined, includeInactive = false): IDebugSession | undefined { if (sessionId) { return this.getSessions(includeInactive).filter(s => s.getId() === sessionId).pop(); } return undefined; } getSessions(includeInactive = false): IDebugSession[] { // By default do not return inactive sesions. // However we are still holding onto inactive sessions due to repl and debug service session revival (eh scenario) return this.sessions.filter(s => includeInactive || s.state !== State.Inactive); } addSession(session: IDebugSession): void { this.sessions = this.sessions.filter(s => { if (s.getId() === session.getId()) { // Make sure to de-dupe if a session is re-intialized. In case of EH debugging we are adding a session again after an attach. return false; } if (s.state === State.Inactive && s.configuration.name === session.configuration.name) { // Make sure to remove all inactive sessions that are using the same configuration as the new session return false; } return true; }); let index = -1; if (session.parentSession) { // Make sure that child sessions are placed after the parent session index = lastIndex(this.sessions, s => s.parentSession === session.parentSession || s === session.parentSession); } if (index >= 0) { this.sessions.splice(index + 1, 0, session); } else { this.sessions.push(session); } this._onDidChangeCallStack.fire(undefined); } get onDidChangeBreakpoints(): Event<IBreakpointsChangeEvent | undefined> { return this._onDidChangeBreakpoints.event; } get onDidChangeCallStack(): Event<void> { return this._onDidChangeCallStack.event; } get onDidChangeWatchExpressions(): Event<IExpression | undefined> { return this._onDidChangeWatchExpressions.event; } rawUpdate(data: IRawModelUpdate): void { let session = this.sessions.filter(p => p.getId() === data.sessionId).pop(); if (session) { session.rawUpdate(data); this._onDidChangeCallStack.fire(undefined); } } clearThreads(id: string, removeThreads: boolean, reference: number | undefined = undefined): void { const session = this.sessions.filter(p => p.getId() === id).pop(); this.schedulers.forEach(scheduler => scheduler.dispose()); this.schedulers.clear(); if (session) { session.clearThreads(removeThreads, reference); this._onDidChangeCallStack.fire(undefined); } } fetchCallStack(thread: Thread): { topCallStack: Promise<void>, wholeCallStack: Promise<void> } { if (thread.session.capabilities.supportsDelayedStackTraceLoading) { // For improved performance load the first stack frame and then load the rest async. let topCallStack = Promise.resolve(); const wholeCallStack = new Promise<void>((c, e) => { topCallStack = thread.fetchCallStack(1).then(() => { if (!this.schedulers.has(thread.getId())) { this.schedulers.set(thread.getId(), new RunOnceScheduler(() => { thread.fetchCallStack(19).then(() => { this._onDidChangeCallStack.fire(); c(); }); }, 420)); } this.schedulers.get(thread.getId())!.schedule(); }); this._onDidChangeCallStack.fire(); }); return { topCallStack, wholeCallStack }; } const wholeCallStack = thread.fetchCallStack(); return { wholeCallStack, topCallStack: wholeCallStack }; } getBreakpoints(filter?: { uri?: uri, lineNumber?: number, column?: number, enabledOnly?: boolean }): IBreakpoint[] { if (filter) { const uriStr = filter.uri ? filter.uri.toString() : undefined; return this.breakpoints.filter(bp => { if (uriStr && bp.uri.toString() !== uriStr) { return false; } if (filter.lineNumber && bp.lineNumber !== filter.lineNumber) { return false; } if (filter.column && bp.column !== filter.column) { return false; } if (filter.enabledOnly && (!this.breakpointsActivated || !bp.enabled)) { return false; } return true; }); } return this.breakpoints; } getFunctionBreakpoints(): IFunctionBreakpoint[] { return this.functionBreakpoints; } getDataBreakpoints(): IDataBreakpoint[] { return this.dataBreakopints; } getExceptionBreakpoints(): IExceptionBreakpoint[] { return this.exceptionBreakpoints; } setExceptionBreakpoints(data: DebugProtocol.ExceptionBreakpointsFilter[]): void { if (data) { if (this.exceptionBreakpoints.length === data.length && this.exceptionBreakpoints.every((exbp, i) => exbp.filter === data[i].filter && exbp.label === data[i].label)) { // No change return; } this.exceptionBreakpoints = data.map(d => { const ebp = this.exceptionBreakpoints.filter(ebp => ebp.filter === d.filter).pop(); return new ExceptionBreakpoint(d.filter, d.label, ebp ? ebp.enabled : !!d.default); }); this._onDidChangeBreakpoints.fire(undefined); } } areBreakpointsActivated(): boolean { return this.breakpointsActivated; } setBreakpointsActivated(activated: boolean): void { this.breakpointsActivated = activated; this._onDidChangeBreakpoints.fire(undefined); } addBreakpoints(uri: uri, rawData: IBreakpointData[], fireEvent = true): IBreakpoint[] { const newBreakpoints = rawData.map(rawBp => new Breakpoint(uri, rawBp.lineNumber, rawBp.column, rawBp.enabled === false ? false : true, rawBp.condition, rawBp.hitCondition, rawBp.logMessage, undefined, this.textFileService, rawBp.id)); newBreakpoints.forEach(bp => bp.setSessionId(this.breakpointsSessionId)); this.breakpoints = this.breakpoints.concat(newBreakpoints); this.breakpointsActivated = true; this.sortAndDeDup(); if (fireEvent) { this._onDidChangeBreakpoints.fire({ added: newBreakpoints }); } return newBreakpoints; } removeBreakpoints(toRemove: IBreakpoint[]): void { this.breakpoints = this.breakpoints.filter(bp => !toRemove.some(toRemove => toRemove.getId() === bp.getId())); this._onDidChangeBreakpoints.fire({ removed: toRemove }); } updateBreakpoints(data: Map<string, IBreakpointUpdateData>): void { const updated: IBreakpoint[] = []; this.breakpoints.forEach(bp => { const bpData = data.get(bp.getId()); if (bpData) { bp.update(bpData); updated.push(bp); } }); this.sortAndDeDup(); this._onDidChangeBreakpoints.fire({ changed: updated }); } setBreakpointSessionData(sessionId: string, data: Map<string, DebugProtocol.Breakpoint>): void { this.breakpoints.forEach(bp => { const bpData = data.get(bp.getId()); if (bpData) { bp.setSessionData(sessionId, bpData); } }); this.functionBreakpoints.forEach(fbp => { const fbpData = data.get(fbp.getId()); if (fbpData) { fbp.setSessionData(sessionId, fbpData); } }); this.dataBreakopints.forEach(dbp => { const dbpData = data.get(dbp.getId()); if (dbpData) { dbp.setSessionData(sessionId, dbpData); } }); this._onDidChangeBreakpoints.fire({ sessionOnly: true }); } setBreakpointsSessionId(sessionId: string | undefined): void { this.breakpointsSessionId = sessionId; this.breakpoints.forEach(bp => bp.setSessionId(sessionId)); this.functionBreakpoints.forEach(fbp => fbp.setSessionId(sessionId)); this.dataBreakopints.forEach(dbp => dbp.setSessionId(sessionId)); this._onDidChangeBreakpoints.fire({ sessionOnly: true }); } private sortAndDeDup(): void { this.breakpoints = this.breakpoints.sort((first, second) => { if (first.uri.toString() !== second.uri.toString()) { return resources.basenameOrAuthority(first.uri).localeCompare(resources.basenameOrAuthority(second.uri)); } if (first.lineNumber === second.lineNumber) { if (first.column && second.column) { return first.column - second.column; } return -1; } return first.lineNumber - second.lineNumber; }); this.breakpoints = distinct(this.breakpoints, bp => `${bp.uri.toString()}:${bp.lineNumber}:${bp.column}`); } setEnablement(element: IEnablement, enable: boolean): void { if (element instanceof Breakpoint || element instanceof FunctionBreakpoint || element instanceof ExceptionBreakpoint || element instanceof DataBreakpoint) { const changed: Array<IBreakpoint | IFunctionBreakpoint | IDataBreakpoint> = []; if (element.enabled !== enable && (element instanceof Breakpoint || element instanceof FunctionBreakpoint || element instanceof DataBreakpoint)) { changed.push(element); } element.enabled = enable; this._onDidChangeBreakpoints.fire({ changed: changed }); } } enableOrDisableAllBreakpoints(enable: boolean): void { const changed: Array<IBreakpoint | IFunctionBreakpoint | IDataBreakpoint> = []; this.breakpoints.forEach(bp => { if (bp.enabled !== enable) { changed.push(bp); } bp.enabled = enable; }); this.functionBreakpoints.forEach(fbp => { if (fbp.enabled !== enable) { changed.push(fbp); } fbp.enabled = enable; }); this.dataBreakopints.forEach(dbp => { if (dbp.enabled !== enable) { changed.push(dbp); } dbp.enabled = enable; }); this._onDidChangeBreakpoints.fire({ changed: changed }); } addFunctionBreakpoint(functionName: string, id?: string): IFunctionBreakpoint { const newFunctionBreakpoint = new FunctionBreakpoint(functionName, true, undefined, undefined, undefined, id); this.functionBreakpoints.push(newFunctionBreakpoint); this._onDidChangeBreakpoints.fire({ added: [newFunctionBreakpoint] }); return newFunctionBreakpoint; } renameFunctionBreakpoint(id: string, name: string): void { const functionBreakpoint = this.functionBreakpoints.filter(fbp => fbp.getId() === id).pop(); if (functionBreakpoint) { functionBreakpoint.name = name; this._onDidChangeBreakpoints.fire({ changed: [functionBreakpoint] }); } } removeFunctionBreakpoints(id?: string): void { let removed: FunctionBreakpoint[]; if (id) { removed = this.functionBreakpoints.filter(fbp => fbp.getId() === id); this.functionBreakpoints = this.functionBreakpoints.filter(fbp => fbp.getId() !== id); } else { removed = this.functionBreakpoints; this.functionBreakpoints = []; } this._onDidChangeBreakpoints.fire({ removed }); } addDataBreakpoint(label: string, dataId: string, canPersist: boolean): void { const newDataBreakpoint = new DataBreakpoint(label, dataId, canPersist, true, undefined, undefined, undefined); this.dataBreakopints.push(newDataBreakpoint); this._onDidChangeBreakpoints.fire({ added: [newDataBreakpoint] }); } removeDataBreakpoints(id?: string): void { let removed: DataBreakpoint[]; if (id) { removed = this.dataBreakopints.filter(fbp => fbp.getId() === id); this.dataBreakopints = this.dataBreakopints.filter(fbp => fbp.getId() !== id); } else { removed = this.dataBreakopints; this.dataBreakopints = []; } this._onDidChangeBreakpoints.fire({ removed }); } getWatchExpressions(): Expression[] { return this.watchExpressions; } addWatchExpression(name: string): IExpression { const we = new Expression(name); this.watchExpressions.push(we); this._onDidChangeWatchExpressions.fire(we); return we; } renameWatchExpression(id: string, newName: string): void { const filtered = this.watchExpressions.filter(we => we.getId() === id); if (filtered.length === 1) { filtered[0].name = newName; this._onDidChangeWatchExpressions.fire(filtered[0]); } } removeWatchExpressions(id: string | null = null): void { this.watchExpressions = id ? this.watchExpressions.filter(we => we.getId() !== id) : []; this._onDidChangeWatchExpressions.fire(undefined); } moveWatchExpression(id: string, position: number): void { const we = this.watchExpressions.filter(we => we.getId() === id).pop(); if (we) { this.watchExpressions = this.watchExpressions.filter(we => we.getId() !== id); this.watchExpressions = this.watchExpressions.slice(0, position).concat(we, this.watchExpressions.slice(position)); this._onDidChangeWatchExpressions.fire(undefined); } } sourceIsNotAvailable(uri: uri): void { this.sessions.forEach(s => { const source = s.getSourceForUri(uri); if (source) { source.available = false; } }); this._onDidChangeCallStack.fire(undefined); } dispose(): void { // Make sure to shutdown each session, such that no debugged process is left laying around this.sessions.forEach(s => s.shutdown()); this.toDispose = lifecycle.dispose(this.toDispose); } }
src/vs/workbench/contrib/debug/common/debugModel.ts
1
https://github.com/microsoft/vscode/commit/20e24e879acc220cbb9b365001b5d1427824edaf
[ 0.9987351298332214, 0.21393094956874847, 0.00016226613661274314, 0.00019649566092994064, 0.407071977853775 ]
{ "id": 3, "code_window": [ "\tprivate sessions: IDebugSession[];\n", "\tprivate toDispose: lifecycle.IDisposable[];\n", "\tprivate schedulers = new Map<string, RunOnceScheduler>();\n", "\tprivate breakpointsSessionId: string | undefined;\n", "\tprivate readonly _onDidChangeBreakpoints: Emitter<IBreakpointsChangeEvent | undefined>;\n", "\tprivate readonly _onDidChangeCallStack: Emitter<void>;\n", "\tprivate readonly _onDidChangeWatchExpressions: Emitter<IExpression | undefined>;\n", "\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tprivate breakpointsActivated = true;\n" ], "file_path": "src/vs/workbench/contrib/debug/common/debugModel.ts", "type": "add", "edit_start_line_idx": 799 }
out node_modules
extensions/vscode-colorize-tests/.gitignore
0
https://github.com/microsoft/vscode/commit/20e24e879acc220cbb9b365001b5d1427824edaf
[ 0.00016809228691272438, 0.00016809228691272438, 0.00016809228691272438, 0.00016809228691272438, 0 ]
{ "id": 3, "code_window": [ "\tprivate sessions: IDebugSession[];\n", "\tprivate toDispose: lifecycle.IDisposable[];\n", "\tprivate schedulers = new Map<string, RunOnceScheduler>();\n", "\tprivate breakpointsSessionId: string | undefined;\n", "\tprivate readonly _onDidChangeBreakpoints: Emitter<IBreakpointsChangeEvent | undefined>;\n", "\tprivate readonly _onDidChangeCallStack: Emitter<void>;\n", "\tprivate readonly _onDidChangeWatchExpressions: Emitter<IExpression | undefined>;\n", "\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tprivate breakpointsActivated = true;\n" ], "file_path": "src/vs/workbench/contrib/debug/common/debugModel.ts", "type": "add", "edit_start_line_idx": 799 }
for(var i=0;i<9;i++){for(var j;j<i;j++){if(j+i<3)return i<j;}}
extensions/javascript/test/colorize-fixtures/test6916.js
0
https://github.com/microsoft/vscode/commit/20e24e879acc220cbb9b365001b5d1427824edaf
[ 0.00017434290202800184, 0.00017434290202800184, 0.00017434290202800184, 0.00017434290202800184, 0 ]
{ "id": 3, "code_window": [ "\tprivate sessions: IDebugSession[];\n", "\tprivate toDispose: lifecycle.IDisposable[];\n", "\tprivate schedulers = new Map<string, RunOnceScheduler>();\n", "\tprivate breakpointsSessionId: string | undefined;\n", "\tprivate readonly _onDidChangeBreakpoints: Emitter<IBreakpointsChangeEvent | undefined>;\n", "\tprivate readonly _onDidChangeCallStack: Emitter<void>;\n", "\tprivate readonly _onDidChangeWatchExpressions: Emitter<IExpression | undefined>;\n", "\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tprivate breakpointsActivated = true;\n" ], "file_path": "src/vs/workbench/contrib/debug/common/debugModel.ts", "type": "add", "edit_start_line_idx": 799 }
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16"><polygon fill="#C5C5C5" points="10,2 7.414,2 8.414,3 9,3 9,3.586 9,4 9,4.414 9,6 12,6 12,13 4,13 4,8 3,8 3,14 13,14 13,5"/><polygon fill="#75BEFF" points="5,1 3,1 5,3 1,3 1,5 5,5 3,7 5,7 8,4"/></svg>
src/vs/workbench/contrib/preferences/browser/media/open-file-inverse.svg
0
https://github.com/microsoft/vscode/commit/20e24e879acc220cbb9b365001b5d1427824edaf
[ 0.00017359245975967497, 0.00017359245975967497, 0.00017359245975967497, 0.00017359245975967497, 0 ]
{ "id": 4, "code_window": [ "\tprivate readonly _onDidChangeCallStack: Emitter<void>;\n", "\tprivate readonly _onDidChangeWatchExpressions: Emitter<IExpression | undefined>;\n", "\n", "\tconstructor(\n", "\t\tprivate breakpoints: Breakpoint[],\n", "\t\tprivate breakpointsActivated: boolean,\n", "\t\tprivate functionBreakpoints: FunctionBreakpoint[],\n", "\t\tprivate exceptionBreakpoints: ExceptionBreakpoint[],\n", "\t\tprivate dataBreakopints: DataBreakpoint[],\n", "\t\tprivate watchExpressions: Expression[],\n", "\t\tprivate textFileService: ITextFileService\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/debug/common/debugModel.ts", "type": "replace", "edit_start_line_idx": 805 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as assert from 'assert'; import { URI as uri } from 'vs/base/common/uri'; import severity from 'vs/base/common/severity'; import { SimpleReplElement, DebugModel, Expression, RawObjectReplElement, StackFrame, Thread } from 'vs/workbench/contrib/debug/common/debugModel'; import * as sinon from 'sinon'; import { MockRawSession } from 'vs/workbench/contrib/debug/test/common/mockDebug'; import { Source } from 'vs/workbench/contrib/debug/common/debugSource'; import { DebugSession } from 'vs/workbench/contrib/debug/browser/debugSession'; import { ReplModel } from 'vs/workbench/contrib/debug/common/replModel'; import { IBreakpointUpdateData } from 'vs/workbench/contrib/debug/common/debug'; import { NullOpenerService } from 'vs/platform/opener/common/opener'; function createMockSession(model: DebugModel, name = 'mockSession', parentSession?: DebugSession | undefined): DebugSession { return new DebugSession({ resolved: { name, type: 'node', request: 'launch' }, unresolved: undefined }, undefined!, model, parentSession, undefined!, undefined!, undefined!, undefined!, undefined!, undefined!, undefined!, undefined!, undefined!, NullOpenerService); } suite('Debug - Model', () => { let model: DebugModel; let rawSession: MockRawSession; setup(() => { model = new DebugModel([], true, [], [], [], [], <any>{ isDirty: (e: any) => false }); rawSession = new MockRawSession(); }); // Breakpoints test('breakpoints simple', () => { const modelUri = uri.file('/myfolder/myfile.js'); model.addBreakpoints(modelUri, [{ lineNumber: 5, enabled: true }, { lineNumber: 10, enabled: false }]); assert.equal(model.areBreakpointsActivated(), true); assert.equal(model.getBreakpoints().length, 2); model.removeBreakpoints(model.getBreakpoints()); assert.equal(model.getBreakpoints().length, 0); }); test('breakpoints toggling', () => { const modelUri = uri.file('/myfolder/myfile.js'); model.addBreakpoints(modelUri, [{ lineNumber: 5, enabled: true }, { lineNumber: 10, enabled: false }]); model.addBreakpoints(modelUri, [{ lineNumber: 12, enabled: true, condition: 'fake condition' }]); assert.equal(model.getBreakpoints().length, 3); const bp = model.getBreakpoints().pop(); if (bp) { model.removeBreakpoints([bp]); } assert.equal(model.getBreakpoints().length, 2); model.setBreakpointsActivated(false); assert.equal(model.areBreakpointsActivated(), false); model.setBreakpointsActivated(true); assert.equal(model.areBreakpointsActivated(), true); }); test('breakpoints two files', () => { const modelUri1 = uri.file('/myfolder/my file first.js'); const modelUri2 = uri.file('/secondfolder/second/second file.js'); model.addBreakpoints(modelUri1, [{ lineNumber: 5, enabled: true }, { lineNumber: 10, enabled: false }]); model.addBreakpoints(modelUri2, [{ lineNumber: 1, enabled: true }, { lineNumber: 2, enabled: true }, { lineNumber: 3, enabled: false }]); assert.equal(model.getBreakpoints().length, 5); const bp = model.getBreakpoints()[0]; const update = new Map<string, IBreakpointUpdateData>(); update.set(bp.getId(), { lineNumber: 100 }); model.updateBreakpoints(update); assert.equal(bp.lineNumber, 100); model.enableOrDisableAllBreakpoints(false); model.getBreakpoints().forEach(bp => { assert.equal(bp.enabled, false); }); model.setEnablement(bp, true); assert.equal(bp.enabled, true); model.removeBreakpoints(model.getBreakpoints({ uri: modelUri1 })); assert.equal(model.getBreakpoints().length, 3); }); test('breakpoints conditions', () => { const modelUri1 = uri.file('/myfolder/my file first.js'); model.addBreakpoints(modelUri1, [{ lineNumber: 5, condition: 'i < 5', hitCondition: '17' }, { lineNumber: 10, condition: 'j < 3' }]); const breakpoints = model.getBreakpoints(); assert.equal(breakpoints[0].condition, 'i < 5'); assert.equal(breakpoints[0].hitCondition, '17'); assert.equal(breakpoints[1].condition, 'j < 3'); assert.equal(!!breakpoints[1].hitCondition, false); assert.equal(model.getBreakpoints().length, 2); model.removeBreakpoints(model.getBreakpoints()); assert.equal(model.getBreakpoints().length, 0); }); test('function breakpoints', () => { model.addFunctionBreakpoint('foo', '1'); model.addFunctionBreakpoint('bar', '2'); model.renameFunctionBreakpoint('1', 'fooUpdated'); model.renameFunctionBreakpoint('2', 'barUpdated'); const functionBps = model.getFunctionBreakpoints(); assert.equal(functionBps[0].name, 'fooUpdated'); assert.equal(functionBps[1].name, 'barUpdated'); model.removeFunctionBreakpoints(); assert.equal(model.getFunctionBreakpoints().length, 0); }); // Threads test('threads simple', () => { const threadId = 1; const threadName = 'firstThread'; const session = createMockSession(model); model.addSession(session); assert.equal(model.getSessions(true).length, 1); model.rawUpdate({ sessionId: session.getId(), threads: [{ id: threadId, name: threadName }] }); assert.equal(session.getThread(threadId)!.name, threadName); model.clearThreads(session.getId(), true); assert.equal(session.getThread(threadId), undefined); assert.equal(model.getSessions(true).length, 1); }); test('threads multiple wtih allThreadsStopped', () => { const threadId1 = 1; const threadName1 = 'firstThread'; const threadId2 = 2; const threadName2 = 'secondThread'; const stoppedReason = 'breakpoint'; // Add the threads const session = createMockSession(model); model.addSession(session); session['raw'] = <any>rawSession; model.rawUpdate({ sessionId: session.getId(), threads: [{ id: threadId1, name: threadName1 }] }); // Stopped event with all threads stopped model.rawUpdate({ sessionId: session.getId(), threads: [{ id: threadId1, name: threadName1 }, { id: threadId2, name: threadName2 }], stoppedDetails: { reason: stoppedReason, threadId: 1, allThreadsStopped: true }, }); const thread1 = session.getThread(threadId1)!; const thread2 = session.getThread(threadId2)!; // at the beginning, callstacks are obtainable but not available assert.equal(session.getAllThreads().length, 2); assert.equal(thread1.name, threadName1); assert.equal(thread1.stopped, true); assert.equal(thread1.getCallStack().length, 0); assert.equal(thread1.stoppedDetails!.reason, stoppedReason); assert.equal(thread2.name, threadName2); assert.equal(thread2.stopped, true); assert.equal(thread2.getCallStack().length, 0); assert.equal(thread2.stoppedDetails!.reason, undefined); // after calling getCallStack, the callstack becomes available // and results in a request for the callstack in the debug adapter thread1.fetchCallStack().then(() => { assert.notEqual(thread1.getCallStack().length, 0); }); thread2.fetchCallStack().then(() => { assert.notEqual(thread2.getCallStack().length, 0); }); // calling multiple times getCallStack doesn't result in multiple calls // to the debug adapter thread1.fetchCallStack().then(() => { return thread2.fetchCallStack(); }); // clearing the callstack results in the callstack not being available thread1.clearCallStack(); assert.equal(thread1.stopped, true); assert.equal(thread1.getCallStack().length, 0); thread2.clearCallStack(); assert.equal(thread2.stopped, true); assert.equal(thread2.getCallStack().length, 0); model.clearThreads(session.getId(), true); assert.equal(session.getThread(threadId1), undefined); assert.equal(session.getThread(threadId2), undefined); assert.equal(session.getAllThreads().length, 0); }); test('threads mutltiple without allThreadsStopped', () => { const sessionStub = sinon.spy(rawSession, 'stackTrace'); const stoppedThreadId = 1; const stoppedThreadName = 'stoppedThread'; const runningThreadId = 2; const runningThreadName = 'runningThread'; const stoppedReason = 'breakpoint'; const session = createMockSession(model); model.addSession(session); session['raw'] = <any>rawSession; // Add the threads model.rawUpdate({ sessionId: session.getId(), threads: [{ id: stoppedThreadId, name: stoppedThreadName }] }); // Stopped event with only one thread stopped model.rawUpdate({ sessionId: session.getId(), threads: [{ id: 1, name: stoppedThreadName }, { id: runningThreadId, name: runningThreadName }], stoppedDetails: { reason: stoppedReason, threadId: 1, allThreadsStopped: false } }); const stoppedThread = session.getThread(stoppedThreadId)!; const runningThread = session.getThread(runningThreadId)!; // the callstack for the stopped thread is obtainable but not available // the callstack for the running thread is not obtainable nor available assert.equal(stoppedThread.name, stoppedThreadName); assert.equal(stoppedThread.stopped, true); assert.equal(session.getAllThreads().length, 2); assert.equal(stoppedThread.getCallStack().length, 0); assert.equal(stoppedThread.stoppedDetails!.reason, stoppedReason); assert.equal(runningThread.name, runningThreadName); assert.equal(runningThread.stopped, false); assert.equal(runningThread.getCallStack().length, 0); assert.equal(runningThread.stoppedDetails, undefined); // after calling getCallStack, the callstack becomes available // and results in a request for the callstack in the debug adapter stoppedThread.fetchCallStack().then(() => { assert.notEqual(stoppedThread.getCallStack().length, 0); assert.equal(runningThread.getCallStack().length, 0); assert.equal(sessionStub.callCount, 1); }); // calling getCallStack on the running thread returns empty array // and does not return in a request for the callstack in the debug // adapter runningThread.fetchCallStack().then(() => { assert.equal(runningThread.getCallStack().length, 0); assert.equal(sessionStub.callCount, 1); }); // clearing the callstack results in the callstack not being available stoppedThread.clearCallStack(); assert.equal(stoppedThread.stopped, true); assert.equal(stoppedThread.getCallStack().length, 0); model.clearThreads(session.getId(), true); assert.equal(session.getThread(stoppedThreadId), undefined); assert.equal(session.getThread(runningThreadId), undefined); assert.equal(session.getAllThreads().length, 0); }); // Expressions function assertWatchExpressions(watchExpressions: Expression[], expectedName: string) { assert.equal(watchExpressions.length, 2); watchExpressions.forEach(we => { assert.equal(we.available, false); assert.equal(we.reference, 0); assert.equal(we.name, expectedName); }); } test('watch expressions', () => { assert.equal(model.getWatchExpressions().length, 0); model.addWatchExpression('console'); model.addWatchExpression('console'); let watchExpressions = model.getWatchExpressions(); assertWatchExpressions(watchExpressions, 'console'); model.renameWatchExpression(watchExpressions[0].getId(), 'new_name'); model.renameWatchExpression(watchExpressions[1].getId(), 'new_name'); assertWatchExpressions(model.getWatchExpressions(), 'new_name'); assertWatchExpressions(model.getWatchExpressions(), 'new_name'); model.addWatchExpression('mockExpression'); model.moveWatchExpression(model.getWatchExpressions()[2].getId(), 1); watchExpressions = model.getWatchExpressions(); assert.equal(watchExpressions[0].name, 'new_name'); assert.equal(watchExpressions[1].name, 'mockExpression'); assert.equal(watchExpressions[2].name, 'new_name'); model.removeWatchExpressions(); assert.equal(model.getWatchExpressions().length, 0); }); test('repl expressions', () => { const session = createMockSession(model); assert.equal(session.getReplElements().length, 0); model.addSession(session); session['raw'] = <any>rawSession; const thread = new Thread(session, 'mockthread', 1); const stackFrame = new StackFrame(thread, 1, <any>undefined, 'app.js', 'normal', { startLineNumber: 1, startColumn: 1, endLineNumber: 1, endColumn: 10 }, 1); const replModel = new ReplModel(session); replModel.addReplExpression(stackFrame, 'myVariable').then(); replModel.addReplExpression(stackFrame, 'myVariable').then(); replModel.addReplExpression(stackFrame, 'myVariable').then(); assert.equal(replModel.getReplElements().length, 3); replModel.getReplElements().forEach(re => { assert.equal((<Expression>re).available, false); assert.equal((<Expression>re).name, 'myVariable'); assert.equal((<Expression>re).reference, 0); }); replModel.removeReplExpressions(); assert.equal(replModel.getReplElements().length, 0); }); test('stack frame get specific source name', () => { const session = createMockSession(model); model.addSession(session); let firstStackFrame: StackFrame; let secondStackFrame: StackFrame; const thread = new class extends Thread { public getCallStack(): StackFrame[] { return [firstStackFrame, secondStackFrame]; } }(session, 'mockthread', 1); const firstSource = new Source({ name: 'internalModule.js', path: 'a/b/c/d/internalModule.js', sourceReference: 10, }, 'aDebugSessionId'); const secondSource = new Source({ name: 'internalModule.js', path: 'z/x/c/d/internalModule.js', sourceReference: 11, }, 'aDebugSessionId'); firstStackFrame = new StackFrame(thread, 1, firstSource, 'app.js', 'normal', { startLineNumber: 1, startColumn: 1, endLineNumber: 1, endColumn: 10 }, 1); secondStackFrame = new StackFrame(thread, 1, secondSource, 'app.js', 'normal', { startLineNumber: 1, startColumn: 1, endLineNumber: 1, endColumn: 10 }, 1); assert.equal(firstStackFrame.getSpecificSourceName(), '.../b/c/d/internalModule.js'); assert.equal(secondStackFrame.getSpecificSourceName(), '.../x/c/d/internalModule.js'); }); test('stack frame toString()', () => { const session = createMockSession(model); const thread = new Thread(session, 'mockthread', 1); const firstSource = new Source({ name: 'internalModule.js', path: 'a/b/c/d/internalModule.js', sourceReference: 10, }, 'aDebugSessionId'); const stackFrame = new StackFrame(thread, 1, firstSource, 'app', 'normal', { startLineNumber: 1, startColumn: 1, endLineNumber: 1, endColumn: 10 }, 1); assert.equal(stackFrame.toString(), 'app (internalModule.js:1)'); const secondSource = new Source(undefined, 'aDebugSessionId'); const stackFrame2 = new StackFrame(thread, 2, secondSource, 'module', 'normal', { startLineNumber: undefined!, startColumn: undefined!, endLineNumber: undefined!, endColumn: undefined! }, 2); assert.equal(stackFrame2.toString(), 'module'); }); test('debug child sessions are added in correct order', () => { const session = createMockSession(model); model.addSession(session); const secondSession = createMockSession(model, 'mockSession2'); model.addSession(secondSession); const firstChild = createMockSession(model, 'firstChild', session); model.addSession(firstChild); const secondChild = createMockSession(model, 'secondChild', session); model.addSession(secondChild); const thirdSession = createMockSession(model, 'mockSession3'); model.addSession(thirdSession); const anotherChild = createMockSession(model, 'secondChild', secondSession); model.addSession(anotherChild); const sessions = model.getSessions(); assert.equal(sessions[0].getId(), session.getId()); assert.equal(sessions[1].getId(), firstChild.getId()); assert.equal(sessions[2].getId(), secondChild.getId()); assert.equal(sessions[3].getId(), secondSession.getId()); assert.equal(sessions[4].getId(), anotherChild.getId()); assert.equal(sessions[5].getId(), thirdSession.getId()); }); // Repl output test('repl output', () => { const session = new DebugSession({ resolved: { name: 'mockSession', type: 'node', request: 'launch' }, unresolved: undefined }, undefined!, model, undefined, undefined!, undefined!, undefined!, undefined!, undefined!, undefined!, undefined!, undefined!, undefined!, NullOpenerService); const repl = new ReplModel(session); repl.appendToRepl('first line\n', severity.Error); repl.appendToRepl('second line ', severity.Error); repl.appendToRepl('third line ', severity.Error); repl.appendToRepl('fourth line', severity.Error); let elements = <SimpleReplElement[]>repl.getReplElements(); assert.equal(elements.length, 2); assert.equal(elements[0].value, 'first line\n'); assert.equal(elements[0].severity, severity.Error); assert.equal(elements[1].value, 'second line third line fourth line'); assert.equal(elements[1].severity, severity.Error); repl.appendToRepl('1', severity.Warning); elements = <SimpleReplElement[]>repl.getReplElements(); assert.equal(elements.length, 3); assert.equal(elements[2].value, '1'); assert.equal(elements[2].severity, severity.Warning); const keyValueObject = { 'key1': 2, 'key2': 'value' }; repl.appendToRepl(new RawObjectReplElement('fakeid', 'fake', keyValueObject), severity.Info); const element = <RawObjectReplElement>repl.getReplElements()[3]; assert.equal(element.value, 'Object'); assert.deepEqual(element.valueObj, keyValueObject); repl.removeReplExpressions(); assert.equal(repl.getReplElements().length, 0); repl.appendToRepl('1\n', severity.Info); repl.appendToRepl('2', severity.Info); repl.appendToRepl('3\n4', severity.Info); repl.appendToRepl('5\n', severity.Info); repl.appendToRepl('6', severity.Info); elements = <SimpleReplElement[]>repl.getReplElements(); assert.equal(elements.length, 3); assert.equal(elements[0], '1\n'); assert.equal(elements[1], '23\n45\n'); assert.equal(elements[2], '6'); }); });
src/vs/workbench/contrib/debug/test/browser/debugModel.test.ts
1
https://github.com/microsoft/vscode/commit/20e24e879acc220cbb9b365001b5d1427824edaf
[ 0.002473218133673072, 0.0002399352379143238, 0.00016440602485090494, 0.00017398610361851752, 0.00033673329744488 ]
{ "id": 4, "code_window": [ "\tprivate readonly _onDidChangeCallStack: Emitter<void>;\n", "\tprivate readonly _onDidChangeWatchExpressions: Emitter<IExpression | undefined>;\n", "\n", "\tconstructor(\n", "\t\tprivate breakpoints: Breakpoint[],\n", "\t\tprivate breakpointsActivated: boolean,\n", "\t\tprivate functionBreakpoints: FunctionBreakpoint[],\n", "\t\tprivate exceptionBreakpoints: ExceptionBreakpoint[],\n", "\t\tprivate dataBreakopints: DataBreakpoint[],\n", "\t\tprivate watchExpressions: Expression[],\n", "\t\tprivate textFileService: ITextFileService\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/debug/common/debugModel.ts", "type": "replace", "edit_start_line_idx": 805 }
{ "name": "shaderlab", "displayName": "%displayName%", "description": "%description%", "version": "1.0.0", "publisher": "vscode", "license": "MIT", "engines": { "vscode": "*" }, "scripts": { "update-grammar": "node ../../build/npm/update-grammar.js tgjones/shaders-tmLanguage grammars/shaderlab.json ./syntaxes/shaderlab.tmLanguage.json" }, "contributes": { "languages": [ { "id": "shaderlab", "extensions": [ ".shader" ], "aliases": [ "ShaderLab", "shaderlab" ], "configuration": "./language-configuration.json" } ], "grammars": [ { "language": "shaderlab", "path": "./syntaxes/shaderlab.tmLanguage.json", "scopeName": "source.shaderlab" } ] } }
extensions/shaderlab/package.json
0
https://github.com/microsoft/vscode/commit/20e24e879acc220cbb9b365001b5d1427824edaf
[ 0.00017720210598781705, 0.00017531347111798823, 0.00017397955525666475, 0.00017503611161373556, 0.0000013215812941780314 ]
{ "id": 4, "code_window": [ "\tprivate readonly _onDidChangeCallStack: Emitter<void>;\n", "\tprivate readonly _onDidChangeWatchExpressions: Emitter<IExpression | undefined>;\n", "\n", "\tconstructor(\n", "\t\tprivate breakpoints: Breakpoint[],\n", "\t\tprivate breakpointsActivated: boolean,\n", "\t\tprivate functionBreakpoints: FunctionBreakpoint[],\n", "\t\tprivate exceptionBreakpoints: ExceptionBreakpoint[],\n", "\t\tprivate dataBreakopints: DataBreakpoint[],\n", "\t\tprivate watchExpressions: Expression[],\n", "\t\tprivate textFileService: ITextFileService\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/debug/common/debugModel.ts", "type": "replace", "edit_start_line_idx": 805 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { KeyboardLayoutContribution } from 'vs/workbench/services/keybinding/browser/keyboardLayouts/_.contribution'; KeyboardLayoutContribution.INSTANCE.registerKeyboardLayout({ layout: { name: '0000041F', id: '', text: 'Turkish Q' }, secondaryLayouts: [], mapping: { Sleep: [], WakeUp: [], KeyA: ['a', 'A', 'æ', 'Æ', 0, 'VK_A'], KeyB: ['b', 'B', '', '', 0, 'VK_B'], KeyC: ['c', 'C', '', '', 0, 'VK_C'], KeyD: ['d', 'D', '', '', 0, 'VK_D'], KeyE: ['e', 'E', '€', '', 0, 'VK_E'], KeyF: ['f', 'F', '', '', 0, 'VK_F'], KeyG: ['g', 'G', '', '', 0, 'VK_G'], KeyH: ['h', 'H', '', '', 0, 'VK_H'], KeyI: ['ı', 'I', 'i', 'İ', 0, 'VK_I'], KeyJ: ['j', 'J', '', '', 0, 'VK_J'], KeyK: ['k', 'K', '', '', 0, 'VK_K'], KeyL: ['l', 'L', '', '', 0, 'VK_L'], KeyM: ['m', 'M', '', '', 0, 'VK_M'], KeyN: ['n', 'N', '', '', 0, 'VK_N'], KeyO: ['o', 'O', '', '', 0, 'VK_O'], KeyP: ['p', 'P', '', '', 0, 'VK_P'], KeyQ: ['q', 'Q', '@', '', 0, 'VK_Q'], KeyR: ['r', 'R', '', '', 0, 'VK_R'], KeyS: ['s', 'S', 'ß', '', 0, 'VK_S'], KeyT: ['t', 'T', '₺', '', 0, 'VK_T'], KeyU: ['u', 'U', '', '', 0, 'VK_U'], KeyV: ['v', 'V', '', '', 0, 'VK_V'], KeyW: ['w', 'W', '', '', 0, 'VK_W'], KeyX: ['x', 'X', '', '', 0, 'VK_X'], KeyY: ['y', 'Y', '', '', 0, 'VK_Y'], KeyZ: ['z', 'Z', '', '', 0, 'VK_Z'], Digit1: ['1', '!', '>', '', 0, 'VK_1'], Digit2: ['2', '\'', '£', '', 0, 'VK_2'], Digit3: ['3', '^', '#', '', 0, 'VK_3'], Digit4: ['4', '+', '$', '', 0, 'VK_4'], Digit5: ['5', '%', '½', '', 0, 'VK_5'], Digit6: ['6', '&', '', '', 0, 'VK_6'], Digit7: ['7', '/', '{', '', 0, 'VK_7'], Digit8: ['8', '(', '[', '', 0, 'VK_8'], Digit9: ['9', ')', ']', '', 0, 'VK_9'], Digit0: ['0', '=', '}', '', 0, 'VK_0'], Enter: [], Escape: [], Backspace: [], Tab: [], Space: [' ', ' ', '', '', 0, 'VK_SPACE'], Minus: ['*', '?', '\\', '', 0, 'VK_OEM_8'], Equal: ['-', '_', '|', '', 0, 'VK_OEM_MINUS'], BracketLeft: ['ğ', 'Ğ', '¨', '', 0, 'VK_OEM_4'], BracketRight: ['ü', 'Ü', '~', '', 0, 'VK_OEM_6'], Backslash: [',', ';', '`', '', 0, 'VK_OEM_COMMA'], Semicolon: ['ş', 'Ş', '´', '', 0, 'VK_OEM_1'], Quote: ['i', 'İ', '', '', 0, 'VK_OEM_7'], Backquote: ['"', 'é', '<', '', 0, 'VK_OEM_3'], Comma: ['ö', 'Ö', '', '', 0, 'VK_OEM_2'], Period: ['ç', 'Ç', '', '', 0, 'VK_OEM_5'], Slash: ['.', ':', '', '', 0, 'VK_OEM_PERIOD'], CapsLock: [], F1: [], F2: [], F3: [], F4: [], F5: [], F6: [], F7: [], F8: [], F9: [], F10: [], F11: [], F12: [], PrintScreen: [], ScrollLock: [], Pause: [], Insert: [], Home: [], PageUp: [], Delete: [], End: [], PageDown: [], ArrowRight: [], ArrowLeft: [], ArrowDown: [], ArrowUp: [], NumLock: [], NumpadDivide: ['/', '/', '', '', 0, 'VK_DIVIDE'], NumpadMultiply: ['*', '*', '', '', 0, 'VK_MULTIPLY'], NumpadSubtract: ['-', '-', '', '', 0, 'VK_SUBTRACT'], NumpadAdd: ['+', '+', '', '', 0, 'VK_ADD'], NumpadEnter: [], Numpad1: [], Numpad2: [], Numpad3: [], Numpad4: [], Numpad5: [], Numpad6: [], Numpad7: [], Numpad8: [], Numpad9: [], Numpad0: [], NumpadDecimal: [], IntlBackslash: ['<', '>', '|', '', 0, 'VK_OEM_102'], ContextMenu: [], Power: [], NumpadEqual: [], F13: [], F14: [], F15: [], F16: [], F17: [], F18: [], F19: [], F20: [], F21: [], F22: [], F23: [], F24: [], Help: [], Undo: [], Cut: [], Copy: [], Paste: [], AudioVolumeMute: [], AudioVolumeUp: [], AudioVolumeDown: [], NumpadComma: [], IntlRo: [], KanaMode: [], IntlYen: [], Convert: [], NonConvert: [], Lang1: [], Lang2: [], Lang3: [], Lang4: [], ControlLeft: [], ShiftLeft: [], AltLeft: [], MetaLeft: [], ControlRight: [], ShiftRight: [], AltRight: [], MetaRight: [], MediaTrackNext: [], MediaTrackPrevious: [], MediaStop: [], Eject: [], MediaPlayPause: [], MediaSelect: [], LaunchMail: [], LaunchApp2: [], LaunchApp1: [], BrowserSearch: [], BrowserHome: [], BrowserBack: [], BrowserForward: [], BrowserStop: [], BrowserRefresh: [], BrowserFavorites: [] } });
src/vs/workbench/services/keybinding/browser/keyboardLayouts/tr.win.ts
0
https://github.com/microsoft/vscode/commit/20e24e879acc220cbb9b365001b5d1427824edaf
[ 0.00017575897800270468, 0.0001736207923386246, 0.0001709011266939342, 0.00017351831775158644, 0.0000013199844488553936 ]
{ "id": 4, "code_window": [ "\tprivate readonly _onDidChangeCallStack: Emitter<void>;\n", "\tprivate readonly _onDidChangeWatchExpressions: Emitter<IExpression | undefined>;\n", "\n", "\tconstructor(\n", "\t\tprivate breakpoints: Breakpoint[],\n", "\t\tprivate breakpointsActivated: boolean,\n", "\t\tprivate functionBreakpoints: FunctionBreakpoint[],\n", "\t\tprivate exceptionBreakpoints: ExceptionBreakpoint[],\n", "\t\tprivate dataBreakopints: DataBreakpoint[],\n", "\t\tprivate watchExpressions: Expression[],\n", "\t\tprivate textFileService: ITextFileService\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/debug/common/debugModel.ts", "type": "replace", "edit_start_line_idx": 805 }
{ "registrations": [ { "component": { "type": "git", "git": { "name": "textmate/ini.tmbundle", "repositoryUrl": "https://github.com/textmate/ini.tmbundle", "commitHash": "2af0cbb0704940f967152616f2f1ff0aae6287a6" } }, "licenseDetail": [ "Copyright (c) textmate-ini.tmbundle project authors", "", "If not otherwise specified (see below), files in this folder fall under the following license: ", "", "Permission to copy, use, modify, sell and distribute this", "software is granted. This software is provided \"as is\" without", "express or implied warranty, and with no claim as to its", "suitability for any purpose.", "", "An exception is made for files in readable text which contain their own license information, ", "or files where an accompanying file exists (in the same directory) with a \"-license\" suffix added ", "to the base-name name of the original file, and an extension of txt, html, or similar. For example ", "\"tidy\" is accompanied by \"tidy-license.txt\"." ], "license": "TextMate Bundle License", "version": "0.0.0" } ], "version": 1 }
extensions/ini/cgmanifest.json
0
https://github.com/microsoft/vscode/commit/20e24e879acc220cbb9b365001b5d1427824edaf
[ 0.00017547297466080636, 0.00017320300685241818, 0.00017026920977514237, 0.00017353490693494678, 0.000002046760300800088 ]
{ "id": 5, "code_window": [ "\tlet model: DebugModel;\n", "\tlet rawSession: MockRawSession;\n", "\n", "\tsetup(() => {\n", "\t\tmodel = new DebugModel([], true, [], [], [], [], <any>{ isDirty: (e: any) => false });\n", "\t\trawSession = new MockRawSession();\n", "\t});\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tmodel = new DebugModel([], [], [], [], [], <any>{ isDirty: (e: any) => false });\n" ], "file_path": "src/vs/workbench/contrib/debug/test/browser/debugModel.test.ts", "type": "replace", "edit_start_line_idx": 26 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as nls from 'vs/nls'; import { Event, Emitter } from 'vs/base/common/event'; import { URI as uri } from 'vs/base/common/uri'; import { first, distinct } from 'vs/base/common/arrays'; import * as errors from 'vs/base/common/errors'; import severity from 'vs/base/common/severity'; import * as aria from 'vs/base/browser/ui/aria/aria'; import { IContextKeyService, IContextKey } from 'vs/platform/contextkey/common/contextkey'; import { IMarkerService } from 'vs/platform/markers/common/markers'; import { ILifecycleService } from 'vs/platform/lifecycle/common/lifecycle'; import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { FileChangesEvent, FileChangeType, IFileService } from 'vs/platform/files/common/files'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage'; import { DebugModel, ExceptionBreakpoint, FunctionBreakpoint, Breakpoint, Expression, DataBreakpoint } from 'vs/workbench/contrib/debug/common/debugModel'; import { ViewModel } from 'vs/workbench/contrib/debug/common/debugViewModel'; import * as debugactions from 'vs/workbench/contrib/debug/browser/debugActions'; import { ConfigurationManager } from 'vs/workbench/contrib/debug/browser/debugConfigurationManager'; import Constants from 'vs/workbench/contrib/markers/browser/constants'; import { ITaskService, ITaskSummary } from 'vs/workbench/contrib/tasks/common/taskService'; import { TaskError } from 'vs/workbench/contrib/tasks/common/taskSystem'; import { VIEWLET_ID as EXPLORER_VIEWLET_ID } from 'vs/workbench/contrib/files/common/files'; import { IViewletService } from 'vs/workbench/services/viewlet/browser/viewlet'; import { IPanelService } from 'vs/workbench/services/panel/common/panelService'; import { IWorkbenchLayoutService, Parts } from 'vs/workbench/services/layout/browser/layoutService'; import { ITextFileService } from 'vs/workbench/services/textfile/common/textfiles'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IWorkspaceContextService, WorkbenchState, IWorkspaceFolder } from 'vs/platform/workspace/common/workspace'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { parse, getFirstFrame } from 'vs/base/common/console'; import { TaskEvent, TaskEventKind, TaskIdentifier } from 'vs/workbench/contrib/tasks/common/tasks'; import { IDialogService } from 'vs/platform/dialogs/common/dialogs'; import { INotificationService } from 'vs/platform/notification/common/notification'; import { IAction, Action } from 'vs/base/common/actions'; import { deepClone, equals } from 'vs/base/common/objects'; import { DebugSession } from 'vs/workbench/contrib/debug/browser/debugSession'; import { dispose, IDisposable } from 'vs/base/common/lifecycle'; import { IDebugService, State, IDebugSession, CONTEXT_DEBUG_TYPE, CONTEXT_DEBUG_STATE, CONTEXT_IN_DEBUG_MODE, IThread, IDebugConfiguration, VIEWLET_ID, REPL_ID, IConfig, ILaunch, IViewModel, IConfigurationManager, IDebugModel, IEnablement, IBreakpoint, IBreakpointData, ICompound, IGlobalConfig, IStackFrame, AdapterEndEvent, getStateLabel } from 'vs/workbench/contrib/debug/common/debug'; import { isExtensionHostDebugging } from 'vs/workbench/contrib/debug/common/debugUtils'; import { isErrorWithActions, createErrorWithActions } from 'vs/base/common/errorsWithActions'; import { RunOnceScheduler } from 'vs/base/common/async'; import { IExtensionHostDebugService } from 'vs/platform/debug/common/extensionHostDebug'; import { isCodeEditor } from 'vs/editor/browser/editorBrowser'; import { CancellationTokenSource } from 'vs/base/common/cancellation'; const DEBUG_BREAKPOINTS_KEY = 'debug.breakpoint'; const DEBUG_BREAKPOINTS_ACTIVATED_KEY = 'debug.breakpointactivated'; const DEBUG_FUNCTION_BREAKPOINTS_KEY = 'debug.functionbreakpoint'; const DEBUG_DATA_BREAKPOINTS_KEY = 'debug.databreakpoint'; const DEBUG_EXCEPTION_BREAKPOINTS_KEY = 'debug.exceptionbreakpoint'; const DEBUG_WATCH_EXPRESSIONS_KEY = 'debug.watchexpressions'; function once(match: (e: TaskEvent) => boolean, event: Event<TaskEvent>): Event<TaskEvent> { return (listener, thisArgs = null, disposables?) => { const result = event(e => { if (match(e)) { result.dispose(); return listener.call(thisArgs, e); } }, null, disposables); return result; }; } const enum TaskRunResult { Failure, Success } export class DebugService implements IDebugService { _serviceBrand: any; private readonly _onDidChangeState: Emitter<State>; private readonly _onDidNewSession: Emitter<IDebugSession>; private readonly _onWillNewSession: Emitter<IDebugSession>; private readonly _onDidEndSession: Emitter<IDebugSession>; private model: DebugModel; private viewModel: ViewModel; private configurationManager: ConfigurationManager; private toDispose: IDisposable[]; private debugType: IContextKey<string>; private debugState: IContextKey<string>; private inDebugMode: IContextKey<boolean>; private breakpointsToSendOnResourceSaved: Set<string>; private initializing = false; private previousState: State | undefined; private initCancellationToken: CancellationTokenSource | undefined; constructor( @IStorageService private readonly storageService: IStorageService, @IEditorService private readonly editorService: IEditorService, @ITextFileService private readonly textFileService: ITextFileService, @IViewletService private readonly viewletService: IViewletService, @IPanelService private readonly panelService: IPanelService, @INotificationService private readonly notificationService: INotificationService, @IDialogService private readonly dialogService: IDialogService, @IWorkbenchLayoutService private readonly layoutService: IWorkbenchLayoutService, @ITelemetryService private readonly telemetryService: ITelemetryService, @IWorkspaceContextService private readonly contextService: IWorkspaceContextService, @IContextKeyService contextKeyService: IContextKeyService, @ILifecycleService private readonly lifecycleService: ILifecycleService, @IInstantiationService private readonly instantiationService: IInstantiationService, @IExtensionService private readonly extensionService: IExtensionService, @IMarkerService private readonly markerService: IMarkerService, @ITaskService private readonly taskService: ITaskService, @IFileService private readonly fileService: IFileService, @IConfigurationService private readonly configurationService: IConfigurationService, @IExtensionHostDebugService private readonly extensionHostDebugService: IExtensionHostDebugService ) { this.toDispose = []; this.breakpointsToSendOnResourceSaved = new Set<string>(); this._onDidChangeState = new Emitter<State>(); this._onDidNewSession = new Emitter<IDebugSession>(); this._onWillNewSession = new Emitter<IDebugSession>(); this._onDidEndSession = new Emitter<IDebugSession>(); this.configurationManager = this.instantiationService.createInstance(ConfigurationManager, this); this.toDispose.push(this.configurationManager); this.debugType = CONTEXT_DEBUG_TYPE.bindTo(contextKeyService); this.debugState = CONTEXT_DEBUG_STATE.bindTo(contextKeyService); this.inDebugMode = CONTEXT_IN_DEBUG_MODE.bindTo(contextKeyService); this.model = new DebugModel(this.loadBreakpoints(), this.storageService.getBoolean(DEBUG_BREAKPOINTS_ACTIVATED_KEY, StorageScope.WORKSPACE, true), this.loadFunctionBreakpoints(), this.loadExceptionBreakpoints(), this.loadDataBreakpoints(), this.loadWatchExpressions(), this.textFileService); this.toDispose.push(this.model); this.viewModel = new ViewModel(contextKeyService); this.toDispose.push(this.fileService.onFileChanges(e => this.onFileChanges(e))); this.lifecycleService.onShutdown(this.dispose, this); this.toDispose.push(this.extensionHostDebugService.onAttachSession(event => { const session = this.model.getSession(event.sessionId, true); if (session) { // EH was started in debug mode -> attach to it session.configuration.request = 'attach'; session.configuration.port = event.port; session.setSubId(event.subId); this.launchOrAttachToSession(session).then(undefined, errors.onUnexpectedError); } })); this.toDispose.push(this.extensionHostDebugService.onTerminateSession(event => { const session = this.model.getSession(event.sessionId); if (session && session.subId === event.subId) { session.disconnect().then(undefined, errors.onUnexpectedError); } })); this.toDispose.push(this.extensionHostDebugService.onLogToSession(event => { const session = this.model.getSession(event.sessionId, true); if (session) { // extension logged output -> show it in REPL const sev = event.log.severity === 'warn' ? severity.Warning : event.log.severity === 'error' ? severity.Error : severity.Info; const { args, stack } = parse(event.log); const frame = !!stack ? getFirstFrame(stack) : undefined; session.logToRepl(sev, args, frame); } })); this.toDispose.push(this.viewModel.onDidFocusStackFrame(() => { this.onStateChange(); })); this.toDispose.push(this.viewModel.onDidFocusSession(session => { const id = session ? session.getId() : undefined; this.model.setBreakpointsSessionId(id); this.onStateChange(); })); } getModel(): IDebugModel { return this.model; } getViewModel(): IViewModel { return this.viewModel; } getConfigurationManager(): IConfigurationManager { return this.configurationManager; } sourceIsNotAvailable(uri: uri): void { this.model.sourceIsNotAvailable(uri); } dispose(): void { this.toDispose = dispose(this.toDispose); } //---- state management get state(): State { const focusedSession = this.viewModel.focusedSession; if (focusedSession) { return focusedSession.state; } return this.initializing ? State.Initializing : State.Inactive; } private startInitializingState() { if (!this.initializing) { this.initializing = true; this.onStateChange(); } } private endInitializingState() { if (this.initCancellationToken) { this.initCancellationToken.cancel(); this.initCancellationToken = undefined; } if (this.initializing) { this.initializing = false; this.onStateChange(); } } private onStateChange(): void { const state = this.state; if (this.previousState !== state) { this.debugState.set(getStateLabel(state)); this.inDebugMode.set(state !== State.Inactive); this.previousState = state; this._onDidChangeState.fire(state); } } get onDidChangeState(): Event<State> { return this._onDidChangeState.event; } get onDidNewSession(): Event<IDebugSession> { return this._onDidNewSession.event; } get onWillNewSession(): Event<IDebugSession> { return this._onWillNewSession.event; } get onDidEndSession(): Event<IDebugSession> { return this._onDidEndSession.event; } //---- life cycle management /** * main entry point * properly manages compounds, checks for errors and handles the initializing state. */ startDebugging(launch: ILaunch | undefined, configOrName?: IConfig | string, noDebug = false, parentSession?: IDebugSession): Promise<boolean> { this.startInitializingState(); // make sure to save all files and that the configuration is up to date return this.extensionService.activateByEvent('onDebug').then(() => { return this.textFileService.saveAll().then(() => this.configurationService.reloadConfiguration(launch ? launch.workspace : undefined).then(() => { return this.extensionService.whenInstalledExtensionsRegistered().then(() => { let config: IConfig | undefined; let compound: ICompound | undefined; if (!configOrName) { configOrName = this.configurationManager.selectedConfiguration.name; } if (typeof configOrName === 'string' && launch) { config = launch.getConfiguration(configOrName); compound = launch.getCompound(configOrName); const sessions = this.model.getSessions(); const alreadyRunningMessage = nls.localize('configurationAlreadyRunning', "There is already a debug configuration \"{0}\" running.", configOrName); if (sessions.some(s => s.configuration.name === configOrName && (!launch || !launch.workspace || !s.root || s.root.uri.toString() === launch.workspace.uri.toString()))) { return Promise.reject(new Error(alreadyRunningMessage)); } if (compound && compound.configurations && sessions.some(p => compound!.configurations.indexOf(p.configuration.name) !== -1)) { return Promise.reject(new Error(alreadyRunningMessage)); } } else if (typeof configOrName !== 'string') { config = configOrName; } if (compound) { // we are starting a compound debug, first do some error checking and than start each configuration in the compound if (!compound.configurations) { return Promise.reject(new Error(nls.localize({ key: 'compoundMustHaveConfigurations', comment: ['compound indicates a "compounds" configuration item', '"configurations" is an attribute and should not be localized'] }, "Compound must have \"configurations\" attribute set in order to start multiple configurations."))); } return Promise.all(compound.configurations.map(configData => { const name = typeof configData === 'string' ? configData : configData.name; if (name === compound!.name) { return Promise.resolve(false); } let launchForName: ILaunch | undefined; if (typeof configData === 'string') { const launchesContainingName = this.configurationManager.getLaunches().filter(l => !!l.getConfiguration(name)); if (launchesContainingName.length === 1) { launchForName = launchesContainingName[0]; } else if (launch && launchesContainingName.length > 1 && launchesContainingName.indexOf(launch) >= 0) { // If there are multiple launches containing the configuration give priority to the configuration in the current launch launchForName = launch; } else { return Promise.reject(new Error(launchesContainingName.length === 0 ? nls.localize('noConfigurationNameInWorkspace', "Could not find launch configuration '{0}' in the workspace.", name) : nls.localize('multipleConfigurationNamesInWorkspace', "There are multiple launch configurations '{0}' in the workspace. Use folder name to qualify the configuration.", name))); } } else if (configData.folder) { const launchesMatchingConfigData = this.configurationManager.getLaunches().filter(l => l.workspace && l.workspace.name === configData.folder && !!l.getConfiguration(configData.name)); if (launchesMatchingConfigData.length === 1) { launchForName = launchesMatchingConfigData[0]; } else { return Promise.reject(new Error(nls.localize('noFolderWithName', "Can not find folder with name '{0}' for configuration '{1}' in compound '{2}'.", configData.folder, configData.name, compound!.name))); } } return this.createSession(launchForName, launchForName!.getConfiguration(name), noDebug, parentSession); })).then(values => values.every(success => !!success)); // Compound launch is a success only if each configuration launched successfully } if (configOrName && !config) { const message = !!launch ? nls.localize('configMissing', "Configuration '{0}' is missing in 'launch.json'.", typeof configOrName === 'string' ? configOrName : JSON.stringify(configOrName)) : nls.localize('launchJsonDoesNotExist', "'launch.json' does not exist."); return Promise.reject(new Error(message)); } return this.createSession(launch, config, noDebug, parentSession); }); })); }).then(success => { // make sure to get out of initializing state, and propagate the result this.endInitializingState(); return success; }, err => { this.endInitializingState(); return Promise.reject(err); }); } /** * gets the debugger for the type, resolves configurations by providers, substitutes variables and runs prelaunch tasks */ private createSession(launch: ILaunch | undefined, config: IConfig | undefined, noDebug: boolean, parentSession?: IDebugSession): Promise<boolean> { // We keep the debug type in a separate variable 'type' so that a no-folder config has no attributes. // Storing the type in the config would break extensions that assume that the no-folder case is indicated by an empty config. let type: string | undefined; if (config) { type = config.type; } else { // a no-folder workspace has no launch.config config = Object.create(null); } const unresolvedConfig = deepClone(config); if (noDebug) { config!.noDebug = true; } const debuggerThenable: Promise<void> = type ? Promise.resolve() : this.configurationManager.guessDebugger().then(dbgr => { type = dbgr && dbgr.type; }); return debuggerThenable.then(() => { this.initCancellationToken = new CancellationTokenSource(); return this.configurationManager.resolveConfigurationByProviders(launch && launch.workspace ? launch.workspace.uri : undefined, type, config!, this.initCancellationToken.token).then(config => { // a falsy config indicates an aborted launch if (config && config.type) { return this.substituteVariables(launch, config).then(resolvedConfig => { if (!resolvedConfig) { // User canceled resolving of interactive variables, silently return return false; } if (!this.configurationManager.getDebugger(resolvedConfig.type) || (config.request !== 'attach' && config.request !== 'launch')) { let message: string; if (config.request !== 'attach' && config.request !== 'launch') { message = config.request ? nls.localize('debugRequestNotSupported', "Attribute '{0}' has an unsupported value '{1}' in the chosen debug configuration.", 'request', config.request) : nls.localize('debugRequesMissing', "Attribute '{0}' is missing from the chosen debug configuration.", 'request'); } else { message = resolvedConfig.type ? nls.localize('debugTypeNotSupported', "Configured debug type '{0}' is not supported.", resolvedConfig.type) : nls.localize('debugTypeMissing', "Missing property 'type' for the chosen launch configuration."); } return this.showError(message).then(() => false); } const workspace = launch ? launch.workspace : undefined; return this.runTaskAndCheckErrors(workspace, resolvedConfig.preLaunchTask).then(result => { if (result === TaskRunResult.Success) { return this.doCreateSession(workspace, { resolved: resolvedConfig, unresolved: unresolvedConfig }, parentSession); } return false; }); }, err => { if (err && err.message) { return this.showError(err.message).then(() => false); } if (this.contextService.getWorkbenchState() === WorkbenchState.EMPTY) { return this.showError(nls.localize('noFolderWorkspaceDebugError', "The active file can not be debugged. Make sure it is saved and that you have a debug extension installed for that file type.")) .then(() => false); } return !!launch && launch.openConfigFile(false, true, undefined, this.initCancellationToken ? this.initCancellationToken.token : undefined).then(() => false); }); } if (launch && type && config === null) { // show launch.json only for "config" being "null". return launch.openConfigFile(false, true, type, this.initCancellationToken ? this.initCancellationToken.token : undefined).then(() => false); } return false; }); }); } /** * instantiates the new session, initializes the session, registers session listeners and reports telemetry */ private doCreateSession(root: IWorkspaceFolder | undefined, configuration: { resolved: IConfig, unresolved: IConfig | undefined }, parentSession?: IDebugSession): Promise<boolean> { const session = this.instantiationService.createInstance(DebugSession, configuration, root, this.model, parentSession); this.model.addSession(session); // register listeners as the very first thing! this.registerSessionListeners(session); // since the Session is now properly registered under its ID and hooked, we can announce it // this event doesn't go to extensions this._onWillNewSession.fire(session); const openDebug = this.configurationService.getValue<IDebugConfiguration>('debug').openDebug; // Open debug viewlet based on the visibility of the side bar and openDebug setting. Do not open for 'run without debug' if (!configuration.resolved.noDebug && (openDebug === 'openOnSessionStart' || (openDebug === 'openOnFirstSessionStart' && this.viewModel.firstSessionStart))) { this.viewletService.openViewlet(VIEWLET_ID).then(undefined, errors.onUnexpectedError); } return this.launchOrAttachToSession(session).then(() => { const internalConsoleOptions = session.configuration.internalConsoleOptions || this.configurationService.getValue<IDebugConfiguration>('debug').internalConsoleOptions; if (internalConsoleOptions === 'openOnSessionStart' || (this.viewModel.firstSessionStart && internalConsoleOptions === 'openOnFirstSessionStart')) { this.panelService.openPanel(REPL_ID, false); } this.viewModel.firstSessionStart = false; const showSubSessions = this.configurationService.getValue<IDebugConfiguration>('debug').showSubSessionsInToolBar; const sessions = this.model.getSessions(); const shownSessions = showSubSessions ? sessions : sessions.filter(s => !s.parentSession); if (shownSessions.length > 1) { this.viewModel.setMultiSessionView(true); } // since the initialized response has arrived announce the new Session (including extensions) this._onDidNewSession.fire(session); return this.telemetryDebugSessionStart(root, session.configuration.type); }).then(() => true, (error: Error | string) => { if (errors.isPromiseCanceledError(error)) { // don't show 'canceled' error messages to the user #7906 return Promise.resolve(false); } // Show the repl if some error got logged there #5870 if (session && session.getReplElements().length > 0) { this.panelService.openPanel(REPL_ID, false); } if (session.configuration && session.configuration.request === 'attach' && session.configuration.__autoAttach) { // ignore attach timeouts in auto attach mode return Promise.resolve(false); } const errorMessage = error instanceof Error ? error.message : error; this.telemetryDebugMisconfiguration(session.configuration ? session.configuration.type : undefined, errorMessage); return this.showError(errorMessage, isErrorWithActions(error) ? error.actions : []).then(() => false); }); } private launchOrAttachToSession(session: IDebugSession, forceFocus = false): Promise<void> { const dbgr = this.configurationManager.getDebugger(session.configuration.type); return session.initialize(dbgr!).then(() => { return session.launchOrAttach(session.configuration).then(() => { if (forceFocus || !this.viewModel.focusedSession) { this.focusStackFrame(undefined, undefined, session); } }); }).then(undefined, err => { session.shutdown(); return Promise.reject(err); }); } private registerSessionListeners(session: IDebugSession): void { const sessionRunningScheduler = new RunOnceScheduler(() => { // Do not immediatly defocus the stack frame if the session is running if (session.state === State.Running && this.viewModel.focusedSession === session) { this.viewModel.setFocus(undefined, this.viewModel.focusedThread, session, false); } }, 200); this.toDispose.push(session.onDidChangeState(() => { if (session.state === State.Running && this.viewModel.focusedSession === session) { sessionRunningScheduler.schedule(); } if (session === this.viewModel.focusedSession) { this.onStateChange(); } })); this.toDispose.push(session.onDidEndAdapter(adapterExitEvent => { if (adapterExitEvent.error) { this.notificationService.error(nls.localize('debugAdapterCrash', "Debug adapter process has terminated unexpectedly ({0})", adapterExitEvent.error.message || adapterExitEvent.error.toString())); } // 'Run without debugging' mode VSCode must terminate the extension host. More details: #3905 if (isExtensionHostDebugging(session.configuration) && session.state === State.Running && session.configuration.noDebug) { this.extensionHostDebugService.close(session.getId()); } this.telemetryDebugSessionStop(session, adapterExitEvent); if (session.configuration.postDebugTask) { this.runTask(session.root, session.configuration.postDebugTask).then(undefined, err => this.notificationService.error(err) ); } session.shutdown(); this.endInitializingState(); this._onDidEndSession.fire(session); const focusedSession = this.viewModel.focusedSession; if (focusedSession && focusedSession.getId() === session.getId()) { this.focusStackFrame(undefined); } if (this.model.getSessions().length === 0) { this.viewModel.setMultiSessionView(false); if (this.layoutService.isVisible(Parts.SIDEBAR_PART) && this.configurationService.getValue<IDebugConfiguration>('debug').openExplorerOnEnd) { this.viewletService.openViewlet(EXPLORER_VIEWLET_ID); } // Data breakpoints that can not be persisted should be cleared when a session ends const dataBreakpoints = this.model.getDataBreakpoints().filter(dbp => !dbp.canPersist); dataBreakpoints.forEach(dbp => this.model.removeDataBreakpoints(dbp.getId())); } })); } restartSession(session: IDebugSession, restartData?: any): Promise<any> { return this.textFileService.saveAll().then(() => { const isAutoRestart = !!restartData; const runTasks: () => Promise<TaskRunResult> = () => { if (isAutoRestart) { // Do not run preLaunch and postDebug tasks for automatic restarts return Promise.resolve(TaskRunResult.Success); } return this.runTask(session.root, session.configuration.postDebugTask) .then(() => this.runTaskAndCheckErrors(session.root, session.configuration.preLaunchTask)); }; if (session.capabilities.supportsRestartRequest) { return runTasks().then(taskResult => taskResult === TaskRunResult.Success ? session.restart() : undefined); } if (isExtensionHostDebugging(session.configuration)) { return runTasks().then(taskResult => taskResult === TaskRunResult.Success ? this.extensionHostDebugService.reload(session.getId()) : undefined); } const shouldFocus = !!this.viewModel.focusedSession && session.getId() === this.viewModel.focusedSession.getId(); // If the restart is automatic -> disconnect, otherwise -> terminate #55064 return (isAutoRestart ? session.disconnect(true) : session.terminate(true)).then(() => { return new Promise<void>((c, e) => { setTimeout(() => { runTasks().then(taskResult => { if (taskResult !== TaskRunResult.Success) { return; } // Read the configuration again if a launch.json has been changed, if not just use the inmemory configuration let needsToSubstitute = false; let unresolved: IConfig | undefined; const launch = session.root ? this.configurationManager.getLaunch(session.root.uri) : undefined; if (launch) { unresolved = launch.getConfiguration(session.configuration.name); if (unresolved && !equals(unresolved, session.unresolvedConfiguration)) { // Take the type from the session since the debug extension might overwrite it #21316 unresolved.type = session.configuration.type; unresolved.noDebug = session.configuration.noDebug; needsToSubstitute = true; } } let substitutionThenable: Promise<IConfig | null | undefined> = Promise.resolve(session.configuration); if (launch && needsToSubstitute && unresolved) { this.initCancellationToken = new CancellationTokenSource(); substitutionThenable = this.configurationManager.resolveConfigurationByProviders(launch.workspace ? launch.workspace.uri : undefined, unresolved.type, unresolved, this.initCancellationToken.token) .then(resolved => { if (resolved) { // start debugging return this.substituteVariables(launch, resolved); } else if (resolved === null) { // abort debugging silently and open launch.json return Promise.resolve(null); } else { // abort debugging silently return Promise.resolve(undefined); } }); } substitutionThenable.then(resolved => { if (!resolved) { return c(undefined); } session.setConfiguration({ resolved, unresolved }); session.configuration.__restart = restartData; this.launchOrAttachToSession(session, shouldFocus).then(() => { this._onDidNewSession.fire(session); c(undefined); }, err => e(err)); }); }); }, 300); }); }); }); } stopSession(session: IDebugSession): Promise<any> { if (session) { return session.terminate(); } const sessions = this.model.getSessions(); if (sessions.length === 0) { this.endInitializingState(); } return Promise.all(sessions.map(s => s.terminate())); } private substituteVariables(launch: ILaunch | undefined, config: IConfig): Promise<IConfig | undefined> { const dbg = this.configurationManager.getDebugger(config.type); if (dbg) { let folder: IWorkspaceFolder | undefined = undefined; if (launch && launch.workspace) { folder = launch.workspace; } else { const folders = this.contextService.getWorkspace().folders; if (folders.length === 1) { folder = folders[0]; } } return dbg.substituteVariables(folder, config).then(config => { return config; }, (err: Error) => { this.showError(err.message); return undefined; // bail out }); } return Promise.resolve(config); } private showError(message: string, errorActions: ReadonlyArray<IAction> = []): Promise<void> { const configureAction = this.instantiationService.createInstance(debugactions.ConfigureAction, debugactions.ConfigureAction.ID, debugactions.ConfigureAction.LABEL); const actions = [...errorActions, configureAction]; return this.dialogService.show(severity.Error, message, actions.map(a => a.label).concat(nls.localize('cancel', "Cancel")), { cancelId: actions.length }).then(choice => { if (choice < actions.length) { return actions[choice].run(); } return undefined; }); } //---- task management private runTaskAndCheckErrors(root: IWorkspaceFolder | undefined, taskId: string | TaskIdentifier | undefined): Promise<TaskRunResult> { const debugAnywayAction = new Action('debug.debugAnyway', nls.localize('debugAnyway', "Debug Anyway"), undefined, true, () => Promise.resolve(TaskRunResult.Success)); return this.runTask(root, taskId).then((taskSummary: ITaskSummary) => { const errorCount = taskId ? this.markerService.getStatistics().errors : 0; const successExitCode = taskSummary && taskSummary.exitCode === 0; const failureExitCode = taskSummary && taskSummary.exitCode !== undefined && taskSummary.exitCode !== 0; if (successExitCode || (errorCount === 0 && !failureExitCode)) { return <any>TaskRunResult.Success; } const taskLabel = typeof taskId === 'string' ? taskId : taskId ? taskId.name : ''; const message = errorCount > 1 ? nls.localize('preLaunchTaskErrors', "Errors exist after running preLaunchTask '{0}'.", taskLabel) : errorCount === 1 ? nls.localize('preLaunchTaskError', "Error exists after running preLaunchTask '{0}'.", taskLabel) : nls.localize('preLaunchTaskExitCode', "The preLaunchTask '{0}' terminated with exit code {1}.", taskLabel, taskSummary.exitCode); const showErrorsAction = new Action('debug.showErrors', nls.localize('showErrors', "Show Errors"), undefined, true, () => { this.panelService.openPanel(Constants.MARKERS_PANEL_ID); return Promise.resolve(TaskRunResult.Failure); }); return this.showError(message, [debugAnywayAction, showErrorsAction]); }, (err: TaskError) => { return this.showError(err.message, [debugAnywayAction, this.taskService.configureAction()]); }); } private runTask(root: IWorkspaceFolder | undefined, taskId: string | TaskIdentifier | undefined): Promise<ITaskSummary | null> { if (!taskId) { return Promise.resolve(null); } if (!root) { return Promise.reject(new Error(nls.localize('invalidTaskReference', "Task '{0}' can not be referenced from a launch configuration that is in a different workspace folder.", typeof taskId === 'string' ? taskId : taskId.type))); } // run a task before starting a debug session return this.taskService.getTask(root, taskId).then(task => { if (!task) { const errorMessage = typeof taskId === 'string' ? nls.localize('DebugTaskNotFoundWithTaskId', "Could not find the task '{0}'.", taskId) : nls.localize('DebugTaskNotFound', "Could not find the specified task."); return Promise.reject(createErrorWithActions(errorMessage)); } // If a task is missing the problem matcher the promise will never complete, so we need to have a workaround #35340 let taskStarted = false; const promise: Promise<ITaskSummary | null> = this.taskService.getActiveTasks().then(tasks => { if (tasks.filter(t => t._id === task._id).length) { // task is already running - nothing to do. return Promise.resolve(null); } once(e => ((e.kind === TaskEventKind.Active) || (e.kind === TaskEventKind.DependsOnStarted)) && e.taskId === task._id, this.taskService.onDidStateChange)(() => { // Task is active, so everything seems to be fine, no need to prompt after 10 seconds // Use case being a slow running task should not be prompted even though it takes more than 10 seconds taskStarted = true; }); const taskPromise = this.taskService.run(task); if (task.configurationProperties.isBackground) { return new Promise((c, e) => once(e => e.kind === TaskEventKind.Inactive && e.taskId === task._id, this.taskService.onDidStateChange)(() => { taskStarted = true; c(null); })); } return taskPromise; }); return new Promise((c, e) => { promise.then(result => { taskStarted = true; c(result); }, error => e(error)); setTimeout(() => { if (!taskStarted) { const errorMessage = typeof taskId === 'string' ? nls.localize('taskNotTrackedWithTaskId', "The specified task cannot be tracked.") : nls.localize('taskNotTracked', "The task '{0}' cannot be tracked.", JSON.stringify(taskId)); e({ severity: severity.Error, message: errorMessage }); } }, 10000); }); }); } //---- focus management focusStackFrame(stackFrame: IStackFrame | undefined, thread?: IThread, session?: IDebugSession, explicit?: boolean): void { if (!session) { if (stackFrame || thread) { session = stackFrame ? stackFrame.thread.session : thread!.session; } else { const sessions = this.model.getSessions(); const stoppedSession = sessions.filter(s => s.state === State.Stopped).shift(); session = stoppedSession || (sessions.length ? sessions[0] : undefined); } } if (!thread) { if (stackFrame) { thread = stackFrame.thread; } else { const threads = session ? session.getAllThreads() : undefined; const stoppedThread = threads && threads.filter(t => t.stopped).shift(); thread = stoppedThread || (threads && threads.length ? threads[0] : undefined); } } if (!stackFrame) { if (thread) { const callStack = thread.getCallStack(); stackFrame = first(callStack, sf => !!(sf && sf.source && sf.source.available && sf.source.presentationHint !== 'deemphasize'), undefined); } } if (stackFrame) { stackFrame.openInEditor(this.editorService, true).then(editor => { if (editor) { const control = editor.getControl(); if (stackFrame && isCodeEditor(control) && control.hasModel()) { const model = control.getModel(); if (stackFrame.range.startLineNumber <= model.getLineCount()) { const lineContent = control.getModel().getLineContent(stackFrame.range.startLineNumber); aria.alert(nls.localize('debuggingPaused', "Debugging paused {0}, {1} {2} {3}", thread && thread.stoppedDetails ? `, reason ${thread.stoppedDetails.reason}` : '', stackFrame.source ? stackFrame.source.name : '', stackFrame.range.startLineNumber, lineContent)); } } } }); } if (session) { this.debugType.set(session.configuration.type); } else { this.debugType.reset(); } this.viewModel.setFocus(stackFrame, thread, session, !!explicit); } //---- watches addWatchExpression(name: string): void { const we = this.model.addWatchExpression(name); this.viewModel.setSelectedExpression(we); this.storeWatchExpressions(); } renameWatchExpression(id: string, newName: string): void { this.model.renameWatchExpression(id, newName); this.storeWatchExpressions(); } moveWatchExpression(id: string, position: number): void { this.model.moveWatchExpression(id, position); this.storeWatchExpressions(); } removeWatchExpressions(id?: string): void { this.model.removeWatchExpressions(id); this.storeWatchExpressions(); } //---- breakpoints async enableOrDisableBreakpoints(enable: boolean, breakpoint?: IEnablement): Promise<void> { if (breakpoint) { this.model.setEnablement(breakpoint, enable); if (breakpoint instanceof Breakpoint) { await this.sendBreakpoints(breakpoint.uri); } else if (breakpoint instanceof FunctionBreakpoint) { await this.sendFunctionBreakpoints(); } else if (breakpoint instanceof DataBreakpoint) { await this.sendDataBreakpoints(); } else { await this.sendExceptionBreakpoints(); } } else { this.model.enableOrDisableAllBreakpoints(enable); await this.sendAllBreakpoints(); } this.storeBreakpoints(); } async addBreakpoints(uri: uri, rawBreakpoints: IBreakpointData[], context: string): Promise<IBreakpoint[]> { const breakpoints = this.model.addBreakpoints(uri, rawBreakpoints); breakpoints.forEach(bp => aria.status(nls.localize('breakpointAdded', "Added breakpoint, line {0}, file {1}", bp.lineNumber, uri.fsPath))); breakpoints.forEach(bp => this.telemetryDebugAddBreakpoint(bp, context)); await this.sendBreakpoints(uri); this.storeBreakpoints(); return breakpoints; } async updateBreakpoints(uri: uri, data: Map<string, DebugProtocol.Breakpoint>, sendOnResourceSaved: boolean): Promise<void> { this.model.updateBreakpoints(data); if (sendOnResourceSaved) { this.breakpointsToSendOnResourceSaved.add(uri.toString()); } else { await this.sendBreakpoints(uri); } this.storeBreakpoints(); } async removeBreakpoints(id?: string): Promise<void> { const toRemove = this.model.getBreakpoints().filter(bp => !id || bp.getId() === id); toRemove.forEach(bp => aria.status(nls.localize('breakpointRemoved', "Removed breakpoint, line {0}, file {1}", bp.lineNumber, bp.uri.fsPath))); const urisToClear = distinct(toRemove, bp => bp.uri.toString()).map(bp => bp.uri); this.model.removeBreakpoints(toRemove); await Promise.all(urisToClear.map(uri => this.sendBreakpoints(uri))); this.storeBreakpoints(); } setBreakpointsActivated(activated: boolean): Promise<void> { this.model.setBreakpointsActivated(activated); if (activated) { this.storageService.store(DEBUG_BREAKPOINTS_ACTIVATED_KEY, 'false', StorageScope.WORKSPACE); } else { this.storageService.remove(DEBUG_BREAKPOINTS_ACTIVATED_KEY, StorageScope.WORKSPACE); } return this.sendAllBreakpoints(); } addFunctionBreakpoint(name?: string, id?: string): void { const newFunctionBreakpoint = this.model.addFunctionBreakpoint(name || '', id); this.viewModel.setSelectedFunctionBreakpoint(newFunctionBreakpoint); } async renameFunctionBreakpoint(id: string, newFunctionName: string): Promise<void> { this.model.renameFunctionBreakpoint(id, newFunctionName); await this.sendFunctionBreakpoints(); this.storeBreakpoints(); } async removeFunctionBreakpoints(id?: string): Promise<void> { this.model.removeFunctionBreakpoints(id); await this.sendFunctionBreakpoints(); this.storeBreakpoints(); } async addDataBreakpoint(label: string, dataId: string, canPersist: boolean): Promise<void> { this.model.addDataBreakpoint(label, dataId, canPersist); await this.sendDataBreakpoints(); this.storeBreakpoints(); } async removeDataBreakpoints(id?: string): Promise<void> { this.model.removeDataBreakpoints(id); await this.sendDataBreakpoints(); this.storeBreakpoints(); } sendAllBreakpoints(session?: IDebugSession): Promise<any> { return Promise.all(distinct(this.model.getBreakpoints(), bp => bp.uri.toString()).map(bp => this.sendBreakpoints(bp.uri, false, session))) .then(() => this.sendFunctionBreakpoints(session)) // send exception breakpoints at the end since some debug adapters rely on the order .then(() => this.sendExceptionBreakpoints(session)) .then(() => this.sendDataBreakpoints(session)); } private sendBreakpoints(modelUri: uri, sourceModified = false, session?: IDebugSession): Promise<void> { const breakpointsToSend = this.model.getBreakpoints({ uri: modelUri, enabledOnly: true }); return this.sendToOneOrAllSessions(session, s => s.sendBreakpoints(modelUri, breakpointsToSend, sourceModified) ); } private sendFunctionBreakpoints(session?: IDebugSession): Promise<void> { const breakpointsToSend = this.model.getFunctionBreakpoints().filter(fbp => fbp.enabled && this.model.areBreakpointsActivated()); return this.sendToOneOrAllSessions(session, s => { return s.capabilities.supportsFunctionBreakpoints ? s.sendFunctionBreakpoints(breakpointsToSend) : Promise.resolve(undefined); }); } private sendDataBreakpoints(session?: IDebugSession): Promise<void> { const breakpointsToSend = this.model.getDataBreakpoints().filter(fbp => fbp.enabled && this.model.areBreakpointsActivated()); return this.sendToOneOrAllSessions(session, s => { return s.capabilities.supportsDataBreakpoints ? s.sendDataBreakpoints(breakpointsToSend) : Promise.resolve(undefined); }); } private sendExceptionBreakpoints(session?: IDebugSession): Promise<void> { const enabledExceptionBps = this.model.getExceptionBreakpoints().filter(exb => exb.enabled); return this.sendToOneOrAllSessions(session, s => { return s.sendExceptionBreakpoints(enabledExceptionBps); }); } private sendToOneOrAllSessions(session: IDebugSession | undefined, send: (session: IDebugSession) => Promise<void>): Promise<void> { if (session) { return send(session); } return Promise.all(this.model.getSessions().map(s => send(s))).then(() => undefined); } private onFileChanges(fileChangesEvent: FileChangesEvent): void { const toRemove = this.model.getBreakpoints().filter(bp => fileChangesEvent.contains(bp.uri, FileChangeType.DELETED)); if (toRemove.length) { this.model.removeBreakpoints(toRemove); } fileChangesEvent.getUpdated().forEach(event => { if (this.breakpointsToSendOnResourceSaved.delete(event.resource.toString())) { this.sendBreakpoints(event.resource, true); } }); } private loadBreakpoints(): Breakpoint[] { let result: Breakpoint[] | undefined; try { result = JSON.parse(this.storageService.get(DEBUG_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((breakpoint: any) => { return new Breakpoint(uri.parse(breakpoint.uri.external || breakpoint.source.uri.external), breakpoint.lineNumber, breakpoint.column, breakpoint.enabled, breakpoint.condition, breakpoint.hitCondition, breakpoint.logMessage, breakpoint.adapterData, this.textFileService); }); } catch (e) { } return result || []; } private loadFunctionBreakpoints(): FunctionBreakpoint[] { let result: FunctionBreakpoint[] | undefined; try { result = JSON.parse(this.storageService.get(DEBUG_FUNCTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((fb: any) => { return new FunctionBreakpoint(fb.name, fb.enabled, fb.hitCondition, fb.condition, fb.logMessage); }); } catch (e) { } return result || []; } private loadExceptionBreakpoints(): ExceptionBreakpoint[] { let result: ExceptionBreakpoint[] | undefined; try { result = JSON.parse(this.storageService.get(DEBUG_EXCEPTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((exBreakpoint: any) => { return new ExceptionBreakpoint(exBreakpoint.filter, exBreakpoint.label, exBreakpoint.enabled); }); } catch (e) { } return result || []; } private loadDataBreakpoints(): DataBreakpoint[] { let result: DataBreakpoint[] | undefined; try { result = JSON.parse(this.storageService.get(DEBUG_DATA_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((dbp: any) => { return new DataBreakpoint(dbp.label, dbp.dataId, true, dbp.enabled, dbp.hitCondition, dbp.condition, dbp.logMessage); }); } catch (e) { } return result || []; } private loadWatchExpressions(): Expression[] { let result: Expression[] | undefined; try { result = JSON.parse(this.storageService.get(DEBUG_WATCH_EXPRESSIONS_KEY, StorageScope.WORKSPACE, '[]')).map((watchStoredData: { name: string, id: string }) => { return new Expression(watchStoredData.name, watchStoredData.id); }); } catch (e) { } return result || []; } private storeWatchExpressions(): void { const watchExpressions = this.model.getWatchExpressions(); if (watchExpressions.length) { this.storageService.store(DEBUG_WATCH_EXPRESSIONS_KEY, JSON.stringify(watchExpressions.map(we => ({ name: we.name, id: we.getId() }))), StorageScope.WORKSPACE); } else { this.storageService.remove(DEBUG_WATCH_EXPRESSIONS_KEY, StorageScope.WORKSPACE); } } private storeBreakpoints(): void { const breakpoints = this.model.getBreakpoints(); if (breakpoints.length) { this.storageService.store(DEBUG_BREAKPOINTS_KEY, JSON.stringify(breakpoints), StorageScope.WORKSPACE); } else { this.storageService.remove(DEBUG_BREAKPOINTS_KEY, StorageScope.WORKSPACE); } const functionBreakpoints = this.model.getFunctionBreakpoints(); if (functionBreakpoints.length) { this.storageService.store(DEBUG_FUNCTION_BREAKPOINTS_KEY, JSON.stringify(functionBreakpoints), StorageScope.WORKSPACE); } else { this.storageService.remove(DEBUG_FUNCTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE); } const dataBreakpoints = this.model.getDataBreakpoints().filter(dbp => dbp.canPersist); if (dataBreakpoints.length) { this.storageService.store(DEBUG_DATA_BREAKPOINTS_KEY, JSON.stringify(dataBreakpoints), StorageScope.WORKSPACE); } else { this.storageService.remove(DEBUG_DATA_BREAKPOINTS_KEY, StorageScope.WORKSPACE); } const exceptionBreakpoints = this.model.getExceptionBreakpoints(); if (exceptionBreakpoints.length) { this.storageService.store(DEBUG_EXCEPTION_BREAKPOINTS_KEY, JSON.stringify(exceptionBreakpoints), StorageScope.WORKSPACE); } else { this.storageService.remove(DEBUG_EXCEPTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE); } } //---- telemetry private telemetryDebugSessionStart(root: IWorkspaceFolder | undefined, type: string): Promise<void> { const dbgr = this.configurationManager.getDebugger(type); if (!dbgr) { return Promise.resolve(); } const extension = dbgr.getMainExtensionDescriptor(); /* __GDPR__ "debugSessionStart" : { "type": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "breakpointCount": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "exceptionBreakpoints": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "watchExpressionsCount": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "extensionName": { "classification": "PublicNonPersonalData", "purpose": "FeatureInsight" }, "isBuiltin": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true}, "launchJsonExists": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true } } */ return this.telemetryService.publicLog('debugSessionStart', { type: type, breakpointCount: this.model.getBreakpoints().length, exceptionBreakpoints: this.model.getExceptionBreakpoints(), watchExpressionsCount: this.model.getWatchExpressions().length, extensionName: extension.identifier.value, isBuiltin: extension.isBuiltin, launchJsonExists: root && !!this.configurationService.getValue<IGlobalConfig>('launch', { resource: root.uri }) }); } private telemetryDebugSessionStop(session: IDebugSession, adapterExitEvent: AdapterEndEvent): Promise<any> { const breakpoints = this.model.getBreakpoints(); /* __GDPR__ "debugSessionStop" : { "type" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "success": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "sessionLengthInSeconds": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "breakpointCount": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "watchExpressionsCount": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true } } */ return this.telemetryService.publicLog('debugSessionStop', { type: session && session.configuration.type, success: adapterExitEvent.emittedStopped || breakpoints.length === 0, sessionLengthInSeconds: adapterExitEvent.sessionLengthInSeconds, breakpointCount: breakpoints.length, watchExpressionsCount: this.model.getWatchExpressions().length }); } private telemetryDebugMisconfiguration(debugType: string | undefined, message: string): Promise<any> { /* __GDPR__ "debugMisconfiguration" : { "type" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "error": { "classification": "CallstackOrException", "purpose": "FeatureInsight" } } */ return this.telemetryService.publicLog('debugMisconfiguration', { type: debugType, error: message }); } private telemetryDebugAddBreakpoint(breakpoint: IBreakpoint, context: string): Promise<any> { /* __GDPR__ "debugAddBreakpoint" : { "context": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "hasCondition": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "hasHitCondition": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "hasLogMessage": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true } } */ return this.telemetryService.publicLog('debugAddBreakpoint', { context: context, hasCondition: !!breakpoint.condition, hasHitCondition: !!breakpoint.hitCondition, hasLogMessage: !!breakpoint.logMessage }); } }
src/vs/workbench/contrib/debug/browser/debugService.ts
1
https://github.com/microsoft/vscode/commit/20e24e879acc220cbb9b365001b5d1427824edaf
[ 0.05547647178173065, 0.0009347012382932007, 0.0001640727714402601, 0.00017358799232169986, 0.00519543094560504 ]
{ "id": 5, "code_window": [ "\tlet model: DebugModel;\n", "\tlet rawSession: MockRawSession;\n", "\n", "\tsetup(() => {\n", "\t\tmodel = new DebugModel([], true, [], [], [], [], <any>{ isDirty: (e: any) => false });\n", "\t\trawSession = new MockRawSession();\n", "\t});\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tmodel = new DebugModel([], [], [], [], [], <any>{ isDirty: (e: any) => false });\n" ], "file_path": "src/vs/workbench/contrib/debug/test/browser/debugModel.test.ts", "type": "replace", "edit_start_line_idx": 26 }
{ "version": "0.2.0", "configurations": [ { "name": "Launch Extension", "type": "extensionHost", "request": "launch", "runtimeExecutable": "${execPath}", "args": [ "--extensionDevelopmentPath=${workspaceFolder}" ], "stopOnEntry": false, "sourceMaps": true, "outDir": "${workspaceFolder}/out", "preLaunchTask": "npm" } ] }
extensions/php/.vscode/launch.json
0
https://github.com/microsoft/vscode/commit/20e24e879acc220cbb9b365001b5d1427824edaf
[ 0.00017300799663644284, 0.00017248319636564702, 0.0001719583960948512, 0.00017248319636564702, 5.248002707958221e-7 ]
{ "id": 5, "code_window": [ "\tlet model: DebugModel;\n", "\tlet rawSession: MockRawSession;\n", "\n", "\tsetup(() => {\n", "\t\tmodel = new DebugModel([], true, [], [], [], [], <any>{ isDirty: (e: any) => false });\n", "\t\trawSession = new MockRawSession();\n", "\t});\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tmodel = new DebugModel([], [], [], [], [], <any>{ isDirty: (e: any) => false });\n" ], "file_path": "src/vs/workbench/contrib/debug/test/browser/debugModel.test.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 { QuickPickManyToggle, BackAction } from 'vs/workbench/browser/parts/quickinput/quickInput'; import { KeybindingsRegistry, KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry'; import { Registry } from 'vs/platform/registry/common/platform'; import { IWorkbenchActionRegistry, Extensions as ActionExtensions } from 'vs/workbench/common/actions'; import { SyncActionDescriptor } from 'vs/platform/actions/common/actions'; import { KeyMod, KeyCode } from 'vs/base/common/keyCodes'; import { inQuickOpenContext } from 'vs/workbench/browser/parts/quickopen/quickopen'; KeybindingsRegistry.registerCommandAndKeybindingRule(QuickPickManyToggle); const registry = Registry.as<IWorkbenchActionRegistry>(ActionExtensions.WorkbenchActions); registry.registerWorkbenchAction(new SyncActionDescriptor(BackAction, BackAction.ID, BackAction.LABEL, { primary: 0, win: { primary: KeyMod.Alt | KeyCode.LeftArrow }, mac: { primary: KeyMod.WinCtrl | KeyCode.US_MINUS }, linux: { primary: KeyMod.CtrlCmd | KeyMod.Alt | KeyCode.US_MINUS } }, inQuickOpenContext, KeybindingWeight.WorkbenchContrib + 50), 'Back');
src/vs/workbench/browser/parts/quickinput/quickInputActions.ts
0
https://github.com/microsoft/vscode/commit/20e24e879acc220cbb9b365001b5d1427824edaf
[ 0.00017663395556155592, 0.00017558556282892823, 0.00017453717009630054, 0.00017558556282892823, 0.0000010483927326276898 ]
{ "id": 5, "code_window": [ "\tlet model: DebugModel;\n", "\tlet rawSession: MockRawSession;\n", "\n", "\tsetup(() => {\n", "\t\tmodel = new DebugModel([], true, [], [], [], [], <any>{ isDirty: (e: any) => false });\n", "\t\trawSession = new MockRawSession();\n", "\t});\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tmodel = new DebugModel([], [], [], [], [], <any>{ isDirty: (e: any) => false });\n" ], "file_path": "src/vs/workbench/contrib/debug/test/browser/debugModel.test.ts", "type": "replace", "edit_start_line_idx": 26 }
{ "registrations": [ { "component": { "type": "git", "git": { "name": "Microsoft/vscode-JSON.tmLanguage", "repositoryUrl": "https://github.com/Microsoft/vscode-JSON.tmLanguage", "commitHash": "9bd83f1c252b375e957203f21793316203f61f70" } }, "license": "MIT", "version": "0.0.0" } ], "version": 1 }
extensions/json/cgmanifest.json
0
https://github.com/microsoft/vscode/commit/20e24e879acc220cbb9b365001b5d1427824edaf
[ 0.00017435071640647948, 0.00017375890456605703, 0.00017316709272563457, 0.00017375890456605703, 5.918118404224515e-7 ]
{ "id": 0, "code_window": [ "import { Schemas } from 'vs/base/common/network';\n", "import { URI } from 'vs/base/common/uri';\n", "import { IConfigurationService } from 'vs/platform/configuration/common/configuration';\n", "import { ILogService } from 'vs/platform/log/common/log';\n", "import { INotificationService } from 'vs/platform/notification/common/notification';\n", "import { IShellLaunchConfig, TerminalLocation, TerminalSettingId, WaitOnExitValue } from 'vs/platform/terminal/common/terminal';\n", "import { formatMessageForTerminal } from 'vs/platform/terminal/common/terminalStrings';\n", "import { ThemeIcon } from 'vs/platform/theme/common/themeService';\n", "import { IViewDescriptorService, IViewsService, ViewContainerLocation } from 'vs/workbench/common/views';\n", "import { TaskTerminalStatus } from 'vs/workbench/contrib/tasks/browser/taskTerminalStatus';\n", "import { ProblemCollectorEventKind, ProblemHandlingStrategy, StartStopProblemCollector, WatchingProblemCollector } from 'vs/workbench/contrib/tasks/common/problemCollectors';\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { IShellLaunchConfig, TerminalSettingId, WaitOnExitValue } from 'vs/platform/terminal/common/terminal';\n" ], "file_path": "src/vs/workbench/contrib/tasks/browser/terminalTaskSystem.ts", "type": "replace", "edit_start_line_idx": 33 }
/*--------------------------------------------------------------------------------------------- * 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 Severity from 'vs/base/common/severity'; import { dispose, toDisposable } from 'vs/base/common/lifecycle'; import { URI } from 'vs/base/common/uri'; import { EditorInputCapabilities, IEditorIdentifier, IUntypedEditorInput } from 'vs/workbench/common/editor'; import { IThemeService, ThemeIcon } from 'vs/platform/theme/common/themeService'; import { EditorInput, IEditorCloseHandler } from 'vs/workbench/common/editor/editorInput'; import { ITerminalInstance, ITerminalInstanceService, terminalEditorId } from 'vs/workbench/contrib/terminal/browser/terminal'; import { getColorClass, getUriClasses } from 'vs/workbench/contrib/terminal/browser/terminalIcon'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IShellLaunchConfig, TerminalExitReason, TerminalLocation, TerminalSettingId } from 'vs/platform/terminal/common/terminal'; import { IEditorGroup } from 'vs/workbench/services/editor/common/editorGroupsService'; import { ILifecycleService } from 'vs/workbench/services/lifecycle/common/lifecycle'; import { ConfirmOnKill } from 'vs/workbench/contrib/terminal/common/terminal'; import { IContextKey, IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { TerminalContextKeys } from 'vs/workbench/contrib/terminal/common/terminalContextKey'; import { ConfirmResult, IDialogService } from 'vs/platform/dialogs/common/dialogs'; import { Emitter } from 'vs/base/common/event'; export class TerminalEditorInput extends EditorInput implements IEditorCloseHandler { static readonly ID = 'workbench.editors.terminal'; override readonly closeHandler = this; private _isDetached = false; private _isShuttingDown = false; private _isReverted = false; private _copyLaunchConfig?: IShellLaunchConfig; private _terminalEditorFocusContextKey: IContextKey<boolean>; private _group: IEditorGroup | undefined; protected readonly _onDidRequestAttach = this._register(new Emitter<ITerminalInstance>()); readonly onDidRequestAttach = this._onDidRequestAttach.event; setGroup(group: IEditorGroup | undefined) { this._group = group; } get group(): IEditorGroup | undefined { return this._group; } override get typeId(): string { return TerminalEditorInput.ID; } override get editorId(): string | undefined { return terminalEditorId; } override get capabilities(): EditorInputCapabilities { return EditorInputCapabilities.Readonly | EditorInputCapabilities.Singleton | EditorInputCapabilities.CanDropIntoEditor; } setTerminalInstance(instance: ITerminalInstance): void { if (this._terminalInstance) { throw new Error('cannot set instance that has already been set'); } this._terminalInstance = instance; this._setupInstanceListeners(); } override copy(): EditorInput { const instance = this._terminalInstanceService.createInstance(this._copyLaunchConfig || {}, TerminalLocation.Editor); instance.focusWhenReady(); this._copyLaunchConfig = undefined; return this._instantiationService.createInstance(TerminalEditorInput, instance.resource, instance); } /** * Sets the launch config to use for the next call to EditorInput.copy, which will be used when * the editor's split command is run. */ setCopyLaunchConfig(launchConfig: IShellLaunchConfig) { this._copyLaunchConfig = launchConfig; } /** * Returns the terminal instance for this input if it has not yet been detached from the input. */ get terminalInstance(): ITerminalInstance | undefined { return this._isDetached ? undefined : this._terminalInstance; } showConfirm(): boolean { if (this._isReverted) { return false; } const confirmOnKill = this._configurationService.getValue<ConfirmOnKill>(TerminalSettingId.ConfirmOnKill); if (confirmOnKill === 'editor' || confirmOnKill === 'always') { return this._terminalInstance?.hasChildProcesses || false; } return false; } async confirm(terminals: ReadonlyArray<IEditorIdentifier>): Promise<ConfirmResult> { const { choice } = await this._dialogService.show( Severity.Warning, localize('confirmDirtyTerminal.message', "Do you want to terminate running processes?"), [ localize({ key: 'confirmDirtyTerminal.button', comment: ['&& denotes a mnemonic'] }, "&&Terminate"), localize('cancel', "Cancel") ], { cancelId: 1, detail: terminals.length > 1 ? terminals.map(terminal => terminal.editor.getName()).join('\n') + '\n\n' + localize('confirmDirtyTerminals.detail', "Closing will terminate the running processes in the terminals.") : localize('confirmDirtyTerminal.detail', "Closing will terminate the running processes in this terminal.") } ); switch (choice) { case 0: return ConfirmResult.DONT_SAVE; default: return ConfirmResult.CANCEL; } } override async revert(): Promise<void> { // On revert just treat the terminal as permanently non-dirty this._isReverted = true; } constructor( public readonly resource: URI, private _terminalInstance: ITerminalInstance | undefined, @IThemeService private readonly _themeService: IThemeService, @ITerminalInstanceService private readonly _terminalInstanceService: ITerminalInstanceService, @IInstantiationService private readonly _instantiationService: IInstantiationService, @IConfigurationService private readonly _configurationService: IConfigurationService, @ILifecycleService private readonly _lifecycleService: ILifecycleService, @IContextKeyService _contextKeyService: IContextKeyService, @IDialogService private readonly _dialogService: IDialogService ) { super(); this._terminalEditorFocusContextKey = TerminalContextKeys.editorFocus.bindTo(_contextKeyService); if (_terminalInstance) { this._setupInstanceListeners(); } } private _setupInstanceListeners(): void { const instance = this._terminalInstance; if (!instance) { return; } this._register(toDisposable(() => { if (!this._isDetached && !this._isShuttingDown) { // Will be ignored if triggered by onExit or onDisposed terminal events // as disposed was already called instance.dispose(TerminalExitReason.User); } })); const disposeListeners = [ instance.onExit(() => this.dispose()), instance.onDisposed(() => this.dispose()), instance.onTitleChanged(() => this._onDidChangeLabel.fire()), instance.onIconChanged(() => this._onDidChangeLabel.fire()), instance.onDidFocus(() => this._terminalEditorFocusContextKey.set(true)), instance.onDidBlur(() => this._terminalEditorFocusContextKey.reset()), instance.statusList.onDidChangePrimaryStatus(() => this._onDidChangeLabel.fire()) ]; // Don't dispose editor when instance is torn down on shutdown to avoid extra work and so // the editor/tabs don't disappear this._lifecycleService.onWillShutdown(() => { this._isShuttingDown = true; dispose(disposeListeners); }); } override getName() { return this._terminalInstance?.title || this.resource.fragment; } override getLabelExtraClasses(): string[] { if (!this._terminalInstance) { return []; } const extraClasses: string[] = ['terminal-tab']; const colorClass = getColorClass(this._terminalInstance); if (colorClass) { extraClasses.push(colorClass); } const uriClasses = getUriClasses(this._terminalInstance, this._themeService.getColorTheme().type); if (uriClasses) { extraClasses.push(...uriClasses); } if (ThemeIcon.isThemeIcon(this._terminalInstance.icon)) { extraClasses.push(`codicon-${this._terminalInstance.icon.id}`); } return extraClasses; } /** * Detach the instance from the input such that when the input is disposed it will not dispose * of the terminal instance/process. */ detachInstance() { if (!this._isShuttingDown) { this._terminalInstance?.detachFromElement(); this._isDetached = true; } } public override getDescription(): string | undefined { return this._terminalInstance?.description; } public override toUntyped(): IUntypedEditorInput { return { resource: this.resource, options: { override: terminalEditorId, pinned: true, forceReload: true } }; } }
src/vs/workbench/contrib/terminal/browser/terminalEditorInput.ts
1
https://github.com/microsoft/vscode/commit/82a00605474987a1b6f5208018d523fa3b2d356a
[ 0.002553988480940461, 0.00032983836717903614, 0.00016224199498537928, 0.00016951948055066168, 0.0004893105360679328 ]
{ "id": 0, "code_window": [ "import { Schemas } from 'vs/base/common/network';\n", "import { URI } from 'vs/base/common/uri';\n", "import { IConfigurationService } from 'vs/platform/configuration/common/configuration';\n", "import { ILogService } from 'vs/platform/log/common/log';\n", "import { INotificationService } from 'vs/platform/notification/common/notification';\n", "import { IShellLaunchConfig, TerminalLocation, TerminalSettingId, WaitOnExitValue } from 'vs/platform/terminal/common/terminal';\n", "import { formatMessageForTerminal } from 'vs/platform/terminal/common/terminalStrings';\n", "import { ThemeIcon } from 'vs/platform/theme/common/themeService';\n", "import { IViewDescriptorService, IViewsService, ViewContainerLocation } from 'vs/workbench/common/views';\n", "import { TaskTerminalStatus } from 'vs/workbench/contrib/tasks/browser/taskTerminalStatus';\n", "import { ProblemCollectorEventKind, ProblemHandlingStrategy, StartStopProblemCollector, WatchingProblemCollector } from 'vs/workbench/contrib/tasks/common/problemCollectors';\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { IShellLaunchConfig, TerminalSettingId, WaitOnExitValue } from 'vs/platform/terminal/common/terminal';\n" ], "file_path": "src/vs/workbench/contrib/tasks/browser/terminalTaskSystem.ts", "type": "replace", "edit_start_line_idx": 33 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as vscode from 'vscode'; import { Command, CommandManager } from '../commands/commandManager'; import type * as Proto from '../protocol'; import * as PConst from '../protocol.const'; import { ClientCapability, ITypeScriptServiceClient, ServerResponse } from '../typescriptService'; import API from '../utils/api'; import { nulToken } from '../utils/cancellation'; import { applyCodeAction } from '../utils/codeAction'; import { conditionalRegistration, requireSomeCapability } from '../utils/dependentRegistration'; import { DocumentSelector } from '../utils/documentSelector'; import { LanguageDescription } from '../utils/languageDescription'; import { parseKindModifier } from '../utils/modifiers'; import * as Previewer from '../utils/previewer'; import { snippetForFunctionCall } from '../utils/snippetForFunctionCall'; import { TelemetryReporter } from '../utils/telemetry'; import * as typeConverters from '../utils/typeConverters'; import TypingsStatus from '../utils/typingsStatus'; import FileConfigurationManager from './fileConfigurationManager'; interface DotAccessorContext { readonly range: vscode.Range; readonly text: string; } interface CompletionContext { readonly isNewIdentifierLocation: boolean; readonly isMemberCompletion: boolean; readonly isInValidCommitCharacterContext: boolean; readonly dotAccessorContext?: DotAccessorContext; readonly enableCallCompletions: boolean; readonly useCodeSnippetsOnMethodSuggest: boolean; readonly wordRange: vscode.Range | undefined; readonly line: string; readonly useFuzzyWordRangeLogic: boolean; } type ResolvedCompletionItem = { readonly edits?: readonly vscode.TextEdit[]; readonly commands: readonly vscode.Command[]; }; class MyCompletionItem extends vscode.CompletionItem { public readonly useCodeSnippet: boolean; constructor( public readonly position: vscode.Position, public readonly document: vscode.TextDocument, public readonly tsEntry: Proto.CompletionEntry, private readonly completionContext: CompletionContext, public readonly metadata: any | undefined, client: ITypeScriptServiceClient, ) { super(tsEntry.name, MyCompletionItem.convertKind(tsEntry.kind)); if (tsEntry.source && tsEntry.hasAction) { // De-prioritze auto-imports // https://github.com/microsoft/vscode/issues/40311 this.sortText = '\uffff' + tsEntry.sortText; // Render "fancy" when source is a workspace path const qualifierCandidate = vscode.workspace.asRelativePath(tsEntry.source); if (qualifierCandidate !== tsEntry.source) { this.label = { label: tsEntry.name, description: qualifierCandidate }; } } else { this.sortText = tsEntry.sortText; } const { sourceDisplay, isSnippet } = tsEntry; if (sourceDisplay) { this.label = { label: tsEntry.name, description: Previewer.plainWithLinks(sourceDisplay, client) }; } if (tsEntry.labelDetails) { this.label = { label: tsEntry.name, ...tsEntry.labelDetails }; } this.preselect = tsEntry.isRecommended; this.position = position; this.useCodeSnippet = completionContext.useCodeSnippetsOnMethodSuggest && (this.kind === vscode.CompletionItemKind.Function || this.kind === vscode.CompletionItemKind.Method); this.range = this.getRangeFromReplacementSpan(tsEntry, completionContext); this.commitCharacters = MyCompletionItem.getCommitCharacters(completionContext, tsEntry); this.insertText = isSnippet && tsEntry.insertText ? new vscode.SnippetString(tsEntry.insertText) : tsEntry.insertText; this.filterText = this.getFilterText(completionContext.line, tsEntry.insertText); if (completionContext.isMemberCompletion && completionContext.dotAccessorContext && !(this.insertText instanceof vscode.SnippetString)) { this.filterText = completionContext.dotAccessorContext.text + (this.insertText || this.label); if (!this.range) { const replacementRange = this.getFuzzyWordRange(); if (replacementRange) { this.range = { inserting: completionContext.dotAccessorContext.range, replacing: completionContext.dotAccessorContext.range.union(replacementRange), }; } else { this.range = completionContext.dotAccessorContext.range; } this.insertText = this.filterText; } } if (tsEntry.kindModifiers) { const kindModifiers = parseKindModifier(tsEntry.kindModifiers); if (kindModifiers.has(PConst.KindModifiers.optional)) { this.insertText ??= this.textLabel; this.filterText ??= this.textLabel; if (typeof this.label === 'string') { this.label += '?'; } else { this.label.label += '?'; } } if (kindModifiers.has(PConst.KindModifiers.deprecated)) { this.tags = [vscode.CompletionItemTag.Deprecated]; } if (kindModifiers.has(PConst.KindModifiers.color)) { this.kind = vscode.CompletionItemKind.Color; } this.detail = getScriptKindDetails(tsEntry); } this.resolveRange(); } private get textLabel() { return typeof this.label === 'string' ? this.label : this.label.label; } private _resolvedPromise?: { readonly requestToken: vscode.CancellationTokenSource; readonly promise: Promise<ResolvedCompletionItem | undefined>; waiting: number; }; public async resolveCompletionItem( client: ITypeScriptServiceClient, token: vscode.CancellationToken, ): Promise<ResolvedCompletionItem | undefined> { token.onCancellationRequested(() => { if (this._resolvedPromise && --this._resolvedPromise.waiting <= 0) { // Give a little extra time for another caller to come in setTimeout(() => { if (this._resolvedPromise && this._resolvedPromise.waiting <= 0) { this._resolvedPromise.requestToken.cancel(); } }, 300); } }); if (this._resolvedPromise) { ++this._resolvedPromise.waiting; return this._resolvedPromise.promise; } const requestToken = new vscode.CancellationTokenSource(); const promise = (async (): Promise<ResolvedCompletionItem | undefined> => { const filepath = client.toOpenedFilePath(this.document); if (!filepath) { return undefined; } const args: Proto.CompletionDetailsRequestArgs = { ...typeConverters.Position.toFileLocationRequestArgs(filepath, this.position), entryNames: [ this.tsEntry.source || this.tsEntry.data ? { name: this.tsEntry.name, source: this.tsEntry.source, data: this.tsEntry.data, } : this.tsEntry.name ] }; const response = await client.interruptGetErr(() => client.execute('completionEntryDetails', args, requestToken.token)); if (response.type !== 'response' || !response.body || !response.body.length) { return undefined; } const detail = response.body[0]; const newItemDetails = this.getDetails(client, detail); if (newItemDetails) { this.detail = newItemDetails; } this.documentation = this.getDocumentation(client, detail, this.document.uri); const codeAction = this.getCodeActions(detail, filepath); const commands: vscode.Command[] = [{ command: CompletionAcceptedCommand.ID, title: '', arguments: [this] }]; if (codeAction.command) { commands.push(codeAction.command); } const additionalTextEdits = codeAction.additionalTextEdits; if (this.useCodeSnippet) { const shouldCompleteFunction = await this.isValidFunctionCompletionContext(client, filepath, this.position, this.document, token); if (shouldCompleteFunction) { const { snippet, parameterCount } = snippetForFunctionCall({ ...this, label: this.textLabel }, detail.displayParts); this.insertText = snippet; if (parameterCount > 0) { //Fix for https://github.com/microsoft/vscode/issues/104059 //Don't show parameter hints if "editor.parameterHints.enabled": false if (vscode.workspace.getConfiguration('editor.parameterHints').get('enabled')) { commands.push({ title: 'triggerParameterHints', command: 'editor.action.triggerParameterHints' }); } } } } return { commands, edits: additionalTextEdits }; })(); this._resolvedPromise = { promise, requestToken, waiting: 1, }; return this._resolvedPromise.promise; } private getDetails( client: ITypeScriptServiceClient, detail: Proto.CompletionEntryDetails, ): string | undefined { const parts: string[] = []; if (detail.kind === PConst.Kind.script) { // details were already added return undefined; } for (const action of detail.codeActions ?? []) { parts.push(action.description); } parts.push(Previewer.plainWithLinks(detail.displayParts, client)); return parts.join('\n\n'); } private getDocumentation( client: ITypeScriptServiceClient, detail: Proto.CompletionEntryDetails, baseUri: vscode.Uri, ): vscode.MarkdownString | undefined { const documentation = new vscode.MarkdownString(); Previewer.addMarkdownDocumentation(documentation, detail.documentation, detail.tags, client); documentation.baseUri = baseUri; return documentation.value.length ? documentation : undefined; } private async isValidFunctionCompletionContext( client: ITypeScriptServiceClient, filepath: string, position: vscode.Position, document: vscode.TextDocument, token: vscode.CancellationToken ): Promise<boolean> { // Workaround for https://github.com/microsoft/TypeScript/issues/12677 // Don't complete function calls inside of destructive assignments or imports try { const args: Proto.FileLocationRequestArgs = typeConverters.Position.toFileLocationRequestArgs(filepath, position); const response = await client.execute('quickinfo', args, token); if (response.type === 'response' && response.body) { switch (response.body.kind) { case 'var': case 'let': case 'const': case 'alias': return false; } } } catch { // Noop } // Don't complete function call if there is already something that looks like a function call // https://github.com/microsoft/vscode/issues/18131 const after = document.lineAt(position.line).text.slice(position.character); return after.match(/^[a-z_$0-9]*\s*\(/gi) === null; } private getCodeActions( detail: Proto.CompletionEntryDetails, filepath: string ): { command?: vscode.Command; additionalTextEdits?: vscode.TextEdit[] } { if (!detail.codeActions || !detail.codeActions.length) { return {}; } // Try to extract out the additionalTextEdits for the current file. // Also check if we still have to apply other workspace edits and commands // using a vscode command const additionalTextEdits: vscode.TextEdit[] = []; let hasRemainingCommandsOrEdits = false; for (const tsAction of detail.codeActions) { if (tsAction.commands) { hasRemainingCommandsOrEdits = true; } // Apply all edits in the current file using `additionalTextEdits` if (tsAction.changes) { for (const change of tsAction.changes) { if (change.fileName === filepath) { additionalTextEdits.push(...change.textChanges.map(typeConverters.TextEdit.fromCodeEdit)); } else { hasRemainingCommandsOrEdits = true; } } } } let command: vscode.Command | undefined = undefined; if (hasRemainingCommandsOrEdits) { // Create command that applies all edits not in the current file. command = { title: '', command: ApplyCompletionCodeActionCommand.ID, arguments: [filepath, detail.codeActions.map((x): Proto.CodeAction => ({ commands: x.commands, description: x.description, changes: x.changes.filter(x => x.fileName !== filepath) }))] }; } return { command, additionalTextEdits: additionalTextEdits.length ? additionalTextEdits : undefined }; } private getRangeFromReplacementSpan(tsEntry: Proto.CompletionEntry, completionContext: CompletionContext) { if (!tsEntry.replacementSpan) { return; } let replaceRange = typeConverters.Range.fromTextSpan(tsEntry.replacementSpan); // Make sure we only replace a single line at most if (!replaceRange.isSingleLine) { replaceRange = new vscode.Range(replaceRange.start.line, replaceRange.start.character, replaceRange.start.line, completionContext.line.length); } // If TS returns an explicit replacement range, we should use it for both types of completion return { inserting: replaceRange, replacing: replaceRange, }; } private getFilterText(line: string, insertText: string | undefined): string | undefined { // Handle private field completions if (this.tsEntry.name.startsWith('#')) { const wordRange = this.completionContext.wordRange; const wordStart = wordRange ? line.charAt(wordRange.start.character) : undefined; if (insertText) { if (insertText.startsWith('this.#')) { return wordStart === '#' ? insertText : insertText.replace(/^this\.#/, ''); } else { return insertText; } } else { return wordStart === '#' ? undefined : this.tsEntry.name.replace(/^#/, ''); } } // For `this.` completions, generally don't set the filter text since we don't want them to be overly prioritized. #74164 if (insertText?.startsWith('this.')) { return undefined; } // Handle the case: // ``` // const xyz = { 'ab c': 1 }; // xyz.ab| // ``` // In which case we want to insert a bracket accessor but should use `.abc` as the filter text instead of // the bracketed insert text. else if (insertText?.startsWith('[')) { return insertText.replace(/^\[['"](.+)[['"]\]$/, '.$1'); } // In all other cases, fallback to using the insertText return insertText; } private resolveRange(): void { if (this.range) { return; } const replaceRange = this.getFuzzyWordRange(); if (replaceRange) { this.range = { inserting: new vscode.Range(replaceRange.start, this.position), replacing: replaceRange }; } } private getFuzzyWordRange() { if (this.completionContext.useFuzzyWordRangeLogic) { // Try getting longer, prefix based range for completions that span words const text = this.completionContext.line.slice(Math.max(0, this.position.character - this.textLabel.length), this.position.character).toLowerCase(); const entryName = this.textLabel.toLowerCase(); for (let i = entryName.length; i >= 0; --i) { if (text.endsWith(entryName.substr(0, i)) && (!this.completionContext.wordRange || this.completionContext.wordRange.start.character > this.position.character - i)) { return new vscode.Range( new vscode.Position(this.position.line, Math.max(0, this.position.character - i)), this.position); } } } return this.completionContext.wordRange; } private static convertKind(kind: string): vscode.CompletionItemKind { switch (kind) { case PConst.Kind.primitiveType: case PConst.Kind.keyword: return vscode.CompletionItemKind.Keyword; case PConst.Kind.const: case PConst.Kind.let: case PConst.Kind.variable: case PConst.Kind.localVariable: case PConst.Kind.alias: case PConst.Kind.parameter: return vscode.CompletionItemKind.Variable; case PConst.Kind.memberVariable: case PConst.Kind.memberGetAccessor: case PConst.Kind.memberSetAccessor: return vscode.CompletionItemKind.Field; case PConst.Kind.function: case PConst.Kind.localFunction: return vscode.CompletionItemKind.Function; case PConst.Kind.method: case PConst.Kind.constructSignature: case PConst.Kind.callSignature: case PConst.Kind.indexSignature: return vscode.CompletionItemKind.Method; case PConst.Kind.enum: return vscode.CompletionItemKind.Enum; case PConst.Kind.enumMember: return vscode.CompletionItemKind.EnumMember; case PConst.Kind.module: case PConst.Kind.externalModuleName: return vscode.CompletionItemKind.Module; case PConst.Kind.class: case PConst.Kind.type: return vscode.CompletionItemKind.Class; case PConst.Kind.interface: return vscode.CompletionItemKind.Interface; case PConst.Kind.warning: return vscode.CompletionItemKind.Text; case PConst.Kind.script: return vscode.CompletionItemKind.File; case PConst.Kind.directory: return vscode.CompletionItemKind.Folder; case PConst.Kind.string: return vscode.CompletionItemKind.Constant; default: return vscode.CompletionItemKind.Property; } } private static getCommitCharacters(context: CompletionContext, entry: Proto.CompletionEntry): string[] | undefined { if (entry.kind === PConst.Kind.warning || entry.kind === PConst.Kind.string) { // Ambient JS word based suggestion, strings return undefined; } if (context.isNewIdentifierLocation || !context.isInValidCommitCharacterContext) { return undefined; } const commitCharacters: string[] = ['.', ',', ';']; if (context.enableCallCompletions) { commitCharacters.push('('); } return commitCharacters; } } function getScriptKindDetails(tsEntry: Proto.CompletionEntry,): string | undefined { if (!tsEntry.kindModifiers || tsEntry.kind !== PConst.Kind.script) { return; } const kindModifiers = parseKindModifier(tsEntry.kindModifiers); for (const extModifier of PConst.KindModifiers.fileExtensionKindModifiers) { if (kindModifiers.has(extModifier)) { if (tsEntry.name.toLowerCase().endsWith(extModifier)) { return tsEntry.name; } else { return tsEntry.name + extModifier; } } } return undefined; } class CompletionAcceptedCommand implements Command { public static readonly ID = '_typescript.onCompletionAccepted'; public readonly id = CompletionAcceptedCommand.ID; public constructor( private readonly onCompletionAccepted: (item: vscode.CompletionItem) => void, private readonly telemetryReporter: TelemetryReporter, ) { } public execute(item: vscode.CompletionItem) { this.onCompletionAccepted(item); if (item instanceof MyCompletionItem) { /* __GDPR__ "completions.accept" : { "owner": "mjbvz", "isPackageJsonImport" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "isImportStatementCompletion" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "${include}": [ "${TypeScriptCommonProperties}" ] } */ this.telemetryReporter.logTelemetry('completions.accept', { isPackageJsonImport: item.tsEntry.isPackageJsonImport ? 'true' : undefined, isImportStatementCompletion: item.tsEntry.isImportStatementCompletion ? 'true' : undefined, }); } } } /** * Command fired when an completion item needs to be applied */ class ApplyCompletionCommand implements Command { public static readonly ID = '_typescript.applyCompletionCommand'; public readonly id = ApplyCompletionCommand.ID; public constructor( private readonly client: ITypeScriptServiceClient, ) { } public async execute(item: MyCompletionItem) { const resolved = await item.resolveCompletionItem(this.client, nulToken); if (!resolved) { return; } const { edits, commands } = resolved; if (edits) { const workspaceEdit = new vscode.WorkspaceEdit(); for (const edit of edits) { workspaceEdit.replace(item.document.uri, edit.range, edit.newText); } await vscode.workspace.applyEdit(workspaceEdit); } for (const command of commands) { await vscode.commands.executeCommand(command.command, ...(command.arguments ?? [])); } } } class ApplyCompletionCodeActionCommand implements Command { public static readonly ID = '_typescript.applyCompletionCodeAction'; public readonly id = ApplyCompletionCodeActionCommand.ID; public constructor( private readonly client: ITypeScriptServiceClient ) { } public async execute(_file: string, codeActions: Proto.CodeAction[]): Promise<boolean> { if (codeActions.length === 0) { return true; } if (codeActions.length === 1) { return applyCodeAction(this.client, codeActions[0], nulToken); } const selection = await vscode.window.showQuickPick( codeActions.map(action => ({ label: action.description, description: '', action, })), { placeHolder: vscode.l10n.t("Select code action to apply") }); if (selection) { return applyCodeAction(this.client, selection.action, nulToken); } return false; } } interface CompletionConfiguration { readonly useCodeSnippetsOnMethodSuggest: boolean; readonly nameSuggestions: boolean; readonly pathSuggestions: boolean; readonly autoImportSuggestions: boolean; readonly importStatementSuggestions: boolean; } namespace CompletionConfiguration { export const useCodeSnippetsOnMethodSuggest = 'suggest.completeFunctionCalls'; export const nameSuggestions = 'suggest.names'; export const pathSuggestions = 'suggest.paths'; export const autoImportSuggestions = 'suggest.autoImports'; export const importStatementSuggestions = 'suggest.importStatements'; export function getConfigurationForResource( modeId: string, resource: vscode.Uri ): CompletionConfiguration { const config = vscode.workspace.getConfiguration(modeId, resource); return { useCodeSnippetsOnMethodSuggest: config.get<boolean>(CompletionConfiguration.useCodeSnippetsOnMethodSuggest, false), pathSuggestions: config.get<boolean>(CompletionConfiguration.pathSuggestions, true), autoImportSuggestions: config.get<boolean>(CompletionConfiguration.autoImportSuggestions, true), nameSuggestions: config.get<boolean>(CompletionConfiguration.nameSuggestions, true), importStatementSuggestions: config.get<boolean>(CompletionConfiguration.importStatementSuggestions, true), }; } } class TypeScriptCompletionItemProvider implements vscode.CompletionItemProvider<MyCompletionItem> { public static readonly triggerCharacters = ['.', '"', '\'', '`', '/', '@', '<', '#', ' ']; constructor( private readonly client: ITypeScriptServiceClient, private readonly language: LanguageDescription, private readonly typingsStatus: TypingsStatus, private readonly fileConfigurationManager: FileConfigurationManager, commandManager: CommandManager, private readonly telemetryReporter: TelemetryReporter, onCompletionAccepted: (item: vscode.CompletionItem) => void ) { commandManager.register(new ApplyCompletionCodeActionCommand(this.client)); commandManager.register(new CompletionAcceptedCommand(onCompletionAccepted, this.telemetryReporter)); commandManager.register(new ApplyCompletionCommand(this.client)); } public async provideCompletionItems( document: vscode.TextDocument, position: vscode.Position, token: vscode.CancellationToken, context: vscode.CompletionContext ): Promise<vscode.CompletionList<MyCompletionItem> | undefined> { if (!vscode.workspace.getConfiguration(this.language.id, document).get('suggest.enabled')) { return undefined; } if (this.typingsStatus.isAcquiringTypings) { return Promise.reject<vscode.CompletionList<MyCompletionItem>>({ label: vscode.l10n.t({ message: "Acquiring typings...", comment: ['Typings refers to the *.d.ts typings files that power our IntelliSense. It should not be localized'], }), detail: vscode.l10n.t({ message: "Acquiring typings definitions for IntelliSense.", comment: ['Typings refers to the *.d.ts typings files that power our IntelliSense. It should not be localized'], }) }); } const file = this.client.toOpenedFilePath(document); if (!file) { return undefined; } const line = document.lineAt(position.line); const completionConfiguration = CompletionConfiguration.getConfigurationForResource(this.language.id, document.uri); if (!this.shouldTrigger(context, line, position, completionConfiguration)) { return undefined; } let wordRange = document.getWordRangeAtPosition(position); if (wordRange && !wordRange.isEmpty) { const secondCharPosition = wordRange.start.translate(0, 1); const firstChar = document.getText(new vscode.Range(wordRange.start, secondCharPosition)); if (firstChar === '@') { wordRange = wordRange.with(secondCharPosition); } } await this.client.interruptGetErr(() => this.fileConfigurationManager.ensureConfigurationForDocument(document, token)); const args: Proto.CompletionsRequestArgs = { ...typeConverters.Position.toFileLocationRequestArgs(file, position), includeExternalModuleExports: completionConfiguration.autoImportSuggestions, includeInsertTextCompletions: true, triggerCharacter: this.getTsTriggerCharacter(context), triggerKind: typeConverters.CompletionTriggerKind.toProtocolCompletionTriggerKind(context.triggerKind), }; let isNewIdentifierLocation = true; let isIncomplete = false; let isMemberCompletion = false; let dotAccessorContext: DotAccessorContext | undefined; let entries: ReadonlyArray<Proto.CompletionEntry>; let metadata: any | undefined; let response: ServerResponse.Response<Proto.CompletionInfoResponse> | undefined; let duration: number | undefined; if (this.client.apiVersion.gte(API.v300)) { const startTime = Date.now(); try { response = await this.client.interruptGetErr(() => this.client.execute('completionInfo', args, token)); } finally { duration = Date.now() - startTime; } if (response.type !== 'response' || !response.body) { this.logCompletionsTelemetry(duration, response); return undefined; } isNewIdentifierLocation = response.body.isNewIdentifierLocation; isMemberCompletion = response.body.isMemberCompletion; if (isMemberCompletion) { const dotMatch = line.text.slice(0, position.character).match(/\??\.\s*$/) || undefined; if (dotMatch) { const range = new vscode.Range(position.translate({ characterDelta: -dotMatch[0].length }), position); const text = document.getText(range); dotAccessorContext = { range, text }; } } isIncomplete = !!response.body.isIncomplete || (response as any).metadata && (response as any).metadata.isIncomplete; entries = response.body.entries; metadata = response.metadata; } else { const response = await this.client.interruptGetErr(() => this.client.execute('completions', args, token)); if (response.type !== 'response' || !response.body) { return undefined; } entries = response.body; metadata = response.metadata; } const completionContext = { isNewIdentifierLocation, isMemberCompletion, dotAccessorContext, isInValidCommitCharacterContext: this.isInValidCommitCharacterContext(document, position), enableCallCompletions: !completionConfiguration.useCodeSnippetsOnMethodSuggest, wordRange, line: line.text, useCodeSnippetsOnMethodSuggest: completionConfiguration.useCodeSnippetsOnMethodSuggest, useFuzzyWordRangeLogic: this.client.apiVersion.lt(API.v390), }; let includesPackageJsonImport = false; let includesImportStatementCompletion = false; const items: MyCompletionItem[] = []; for (const entry of entries) { if (!shouldExcludeCompletionEntry(entry, completionConfiguration)) { const item = new MyCompletionItem(position, document, entry, completionContext, metadata, this.client); item.command = { command: ApplyCompletionCommand.ID, title: '', arguments: [item] }; items.push(item); includesPackageJsonImport = includesPackageJsonImport || !!entry.isPackageJsonImport; includesImportStatementCompletion = includesImportStatementCompletion || !!entry.isImportStatementCompletion; } } if (duration !== undefined) { this.logCompletionsTelemetry(duration, response, includesPackageJsonImport, includesImportStatementCompletion); } return new vscode.CompletionList(items, isIncomplete); } private logCompletionsTelemetry( duration: number, response: ServerResponse.Response<Proto.CompletionInfoResponse> | undefined, includesPackageJsonImport?: boolean, includesImportStatementCompletion?: boolean, ) { /* __GDPR__ "completions.execute" : { "owner": "mjbvz", "duration" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "type" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "count" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "flags": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "updateGraphDurationMs" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "createAutoImportProviderProgramDurationMs" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "includesPackageJsonImport" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "includesImportStatementCompletion" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "${include}": [ "${TypeScriptCommonProperties}" ] } */ this.telemetryReporter.logTelemetry('completions.execute', { duration: String(duration), type: response?.type ?? 'unknown', flags: response?.type === 'response' && typeof response.body?.flags === 'number' ? String(response.body.flags) : undefined, count: String(response?.type === 'response' && response.body ? response.body.entries.length : 0), updateGraphDurationMs: response?.type === 'response' && typeof response.performanceData?.updateGraphDurationMs === 'number' ? String(response.performanceData.updateGraphDurationMs) : undefined, createAutoImportProviderProgramDurationMs: response?.type === 'response' && typeof response.performanceData?.createAutoImportProviderProgramDurationMs === 'number' ? String(response.performanceData.createAutoImportProviderProgramDurationMs) : undefined, includesPackageJsonImport: includesPackageJsonImport ? 'true' : undefined, includesImportStatementCompletion: includesImportStatementCompletion ? 'true' : undefined, }); } private getTsTriggerCharacter(context: vscode.CompletionContext): Proto.CompletionsTriggerCharacter | undefined { switch (context.triggerCharacter) { case '@': // Workaround for https://github.com/microsoft/TypeScript/issues/27321 return this.client.apiVersion.gte(API.v310) && this.client.apiVersion.lt(API.v320) ? undefined : '@'; case '#': // Workaround for https://github.com/microsoft/TypeScript/issues/36367 return this.client.apiVersion.lt(API.v381) ? undefined : '#'; case ' ': { const space: Proto.CompletionsTriggerCharacter = ' '; return this.client.apiVersion.gte(API.v430) ? space : undefined; } case '.': case '"': case '\'': case '`': case '/': case '<': return context.triggerCharacter; } return undefined; } public async resolveCompletionItem( item: MyCompletionItem, token: vscode.CancellationToken ): Promise<MyCompletionItem | undefined> { await item.resolveCompletionItem(this.client, token); return item; } private isInValidCommitCharacterContext( document: vscode.TextDocument, position: vscode.Position ): boolean { if (this.client.apiVersion.lt(API.v320)) { // Workaround for https://github.com/microsoft/TypeScript/issues/27742 // Only enable dot completions when previous character not a dot preceded by whitespace. // Prevents incorrectly completing while typing spread operators. if (position.character > 1) { const preText = document.getText(new vscode.Range( position.line, 0, position.line, position.character)); return preText.match(/(\s|^)\.$/ig) === null; } } return true; } private shouldTrigger( context: vscode.CompletionContext, line: vscode.TextLine, position: vscode.Position, configuration: CompletionConfiguration, ): boolean { if (context.triggerCharacter === ' ') { if (!configuration.importStatementSuggestions || this.client.apiVersion.lt(API.v430)) { return false; } const pre = line.text.slice(0, position.character); return pre === 'import'; } return true; } } function shouldExcludeCompletionEntry( element: Proto.CompletionEntry, completionConfiguration: CompletionConfiguration ) { return ( (!completionConfiguration.nameSuggestions && element.kind === PConst.Kind.warning) || (!completionConfiguration.pathSuggestions && (element.kind === PConst.Kind.directory || element.kind === PConst.Kind.script || element.kind === PConst.Kind.externalModuleName)) || (!completionConfiguration.autoImportSuggestions && element.hasAction) ); } export function register( selector: DocumentSelector, language: LanguageDescription, client: ITypeScriptServiceClient, typingsStatus: TypingsStatus, fileConfigurationManager: FileConfigurationManager, commandManager: CommandManager, telemetryReporter: TelemetryReporter, onCompletionAccepted: (item: vscode.CompletionItem) => void ) { return conditionalRegistration([ requireSomeCapability(client, ClientCapability.EnhancedSyntax, ClientCapability.Semantic), ], () => { return vscode.languages.registerCompletionItemProvider(selector.syntax, new TypeScriptCompletionItemProvider(client, language, typingsStatus, fileConfigurationManager, commandManager, telemetryReporter, onCompletionAccepted), ...TypeScriptCompletionItemProvider.triggerCharacters); }); }
extensions/typescript-language-features/src/languageFeatures/completions.ts
0
https://github.com/microsoft/vscode/commit/82a00605474987a1b6f5208018d523fa3b2d356a
[ 0.00019301135034766048, 0.00017219199799001217, 0.00016472865536343306, 0.00017237717111129314, 0.000003200409537384985 ]
{ "id": 0, "code_window": [ "import { Schemas } from 'vs/base/common/network';\n", "import { URI } from 'vs/base/common/uri';\n", "import { IConfigurationService } from 'vs/platform/configuration/common/configuration';\n", "import { ILogService } from 'vs/platform/log/common/log';\n", "import { INotificationService } from 'vs/platform/notification/common/notification';\n", "import { IShellLaunchConfig, TerminalLocation, TerminalSettingId, WaitOnExitValue } from 'vs/platform/terminal/common/terminal';\n", "import { formatMessageForTerminal } from 'vs/platform/terminal/common/terminalStrings';\n", "import { ThemeIcon } from 'vs/platform/theme/common/themeService';\n", "import { IViewDescriptorService, IViewsService, ViewContainerLocation } from 'vs/workbench/common/views';\n", "import { TaskTerminalStatus } from 'vs/workbench/contrib/tasks/browser/taskTerminalStatus';\n", "import { ProblemCollectorEventKind, ProblemHandlingStrategy, StartStopProblemCollector, WatchingProblemCollector } from 'vs/workbench/contrib/tasks/common/problemCollectors';\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { IShellLaunchConfig, TerminalSettingId, WaitOnExitValue } from 'vs/platform/terminal/common/terminal';\n" ], "file_path": "src/vs/workbench/contrib/tasks/browser/terminalTaskSystem.ts", "type": "replace", "edit_start_line_idx": 33 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { IPickAndOpenOptions, ISaveDialogOptions, IOpenDialogOptions, IFileDialogService, FileFilter } from 'vs/platform/dialogs/common/dialogs'; import { URI } from 'vs/base/common/uri'; import { InstantiationType, registerSingleton } from 'vs/platform/instantiation/common/extensions'; import { AbstractFileDialogService } from 'vs/workbench/services/dialogs/browser/abstractFileDialogService'; import { Schemas } from 'vs/base/common/network'; import { memoize } from 'vs/base/common/decorators'; import { HTMLFileSystemProvider } from 'vs/platform/files/browser/htmlFileSystemProvider'; import { localize } from 'vs/nls'; import { getMediaOrTextMime } from 'vs/base/common/mime'; import { basename } from 'vs/base/common/resources'; import { triggerDownload, triggerUpload } from 'vs/base/browser/dom'; import Severity from 'vs/base/common/severity'; import { VSBuffer } from 'vs/base/common/buffer'; import { extractFileListData } from 'vs/platform/dnd/browser/dnd'; import { Iterable } from 'vs/base/common/iterator'; import { WebFileSystemAccess } from 'vs/platform/files/browser/webFileSystemAccess'; export class FileDialogService extends AbstractFileDialogService implements IFileDialogService { @memoize private get fileSystemProvider(): HTMLFileSystemProvider { return this.fileService.getProvider(Schemas.file) as HTMLFileSystemProvider; } async pickFileFolderAndOpen(options: IPickAndOpenOptions): Promise<void> { const schema = this.getFileSystemSchema(options); if (!options.defaultUri) { options.defaultUri = await this.defaultFilePath(schema); } if (this.shouldUseSimplified(schema)) { return super.pickFileFolderAndOpenSimplified(schema, options, false); } throw new Error(localize('pickFolderAndOpen', "Can't open folders, try adding a folder to the workspace instead.")); } protected override addFileSchemaIfNeeded(schema: string, isFolder: boolean): string[] { return (schema === Schemas.untitled) ? [Schemas.file] : (((schema !== Schemas.file) && (!isFolder || (schema !== Schemas.vscodeRemote))) ? [schema, Schemas.file] : [schema]); } async pickFileAndOpen(options: IPickAndOpenOptions): Promise<void> { const schema = this.getFileSystemSchema(options); if (!options.defaultUri) { options.defaultUri = await this.defaultFilePath(schema); } if (this.shouldUseSimplified(schema)) { return super.pickFileAndOpenSimplified(schema, options, false); } if (!WebFileSystemAccess.supported(window)) { return this.showUnsupportedBrowserWarning('open'); } let fileHandle: FileSystemHandle | undefined = undefined; try { ([fileHandle] = await window.showOpenFilePicker({ multiple: false })); } catch (error) { return; // `showOpenFilePicker` will throw an error when the user cancels } if (!WebFileSystemAccess.isFileSystemFileHandle(fileHandle)) { return; } const uri = await this.fileSystemProvider.registerFileHandle(fileHandle); this.addFileToRecentlyOpened(uri); await this.openerService.open(uri, { fromUserGesture: true, editorOptions: { pinned: true } }); } async pickFolderAndOpen(options: IPickAndOpenOptions): Promise<void> { const schema = this.getFileSystemSchema(options); if (!options.defaultUri) { options.defaultUri = await this.defaultFolderPath(schema); } if (this.shouldUseSimplified(schema)) { return super.pickFolderAndOpenSimplified(schema, options); } throw new Error(localize('pickFolderAndOpen', "Can't open folders, try adding a folder to the workspace instead.")); } async pickWorkspaceAndOpen(options: IPickAndOpenOptions): Promise<void> { options.availableFileSystems = this.getWorkspaceAvailableFileSystems(options); const schema = this.getFileSystemSchema(options); if (!options.defaultUri) { options.defaultUri = await this.defaultWorkspacePath(schema); } if (this.shouldUseSimplified(schema)) { return super.pickWorkspaceAndOpenSimplified(schema, options); } throw new Error(localize('pickWorkspaceAndOpen', "Can't open workspaces, try adding a folder to the workspace instead.")); } async pickFileToSave(defaultUri: URI, availableFileSystems?: string[]): Promise<URI | undefined> { const schema = this.getFileSystemSchema({ defaultUri, availableFileSystems }); const options = this.getPickFileToSaveDialogOptions(defaultUri, availableFileSystems); if (this.shouldUseSimplified(schema)) { return super.pickFileToSaveSimplified(schema, options); } if (!WebFileSystemAccess.supported(window)) { return this.showUnsupportedBrowserWarning('save'); } let fileHandle: FileSystemHandle | undefined = undefined; const startIn = Iterable.first(this.fileSystemProvider.directories); try { fileHandle = await window.showSaveFilePicker({ types: this.getFilePickerTypes(options.filters), ...{ suggestedName: basename(defaultUri), startIn } }); } catch (error) { return; // `showSaveFilePicker` will throw an error when the user cancels } if (!WebFileSystemAccess.isFileSystemFileHandle(fileHandle)) { return undefined; } return this.fileSystemProvider.registerFileHandle(fileHandle); } private getFilePickerTypes(filters?: FileFilter[]): FilePickerAcceptType[] | undefined { return filters?.filter(filter => { return !((filter.extensions.length === 1) && ((filter.extensions[0] === '*') || filter.extensions[0] === '')); }).map(filter => { const accept: Record<string, string[]> = {}; const extensions = filter.extensions.filter(ext => (ext.indexOf('-') < 0) && (ext.indexOf('*') < 0) && (ext.indexOf('_') < 0)); accept[getMediaOrTextMime(`fileName.${filter.extensions[0]}`) ?? 'text/plain'] = extensions.map(ext => ext.startsWith('.') ? ext : `.${ext}`); return { description: filter.name, accept }; }); } async showSaveDialog(options: ISaveDialogOptions): Promise<URI | undefined> { const schema = this.getFileSystemSchema(options); if (this.shouldUseSimplified(schema)) { return super.showSaveDialogSimplified(schema, options); } if (!WebFileSystemAccess.supported(window)) { return this.showUnsupportedBrowserWarning('save'); } let fileHandle: FileSystemHandle | undefined = undefined; const startIn = Iterable.first(this.fileSystemProvider.directories); try { fileHandle = await window.showSaveFilePicker({ types: this.getFilePickerTypes(options.filters), ...options.defaultUri ? { suggestedName: basename(options.defaultUri) } : undefined, ...{ startIn } }); } catch (error) { return undefined; // `showSaveFilePicker` will throw an error when the user cancels } if (!WebFileSystemAccess.isFileSystemFileHandle(fileHandle)) { return undefined; } return this.fileSystemProvider.registerFileHandle(fileHandle); } async showOpenDialog(options: IOpenDialogOptions): Promise<URI[] | undefined> { const schema = this.getFileSystemSchema(options); if (this.shouldUseSimplified(schema)) { return super.showOpenDialogSimplified(schema, options); } if (!WebFileSystemAccess.supported(window)) { return this.showUnsupportedBrowserWarning('open'); } let uri: URI | undefined; const startIn = Iterable.first(this.fileSystemProvider.directories) ?? 'documents'; try { if (options.canSelectFiles) { const handle = await window.showOpenFilePicker({ multiple: false, types: this.getFilePickerTypes(options.filters), ...{ startIn } }); if (handle.length === 1 && WebFileSystemAccess.isFileSystemFileHandle(handle[0])) { uri = await this.fileSystemProvider.registerFileHandle(handle[0]); } } else { const handle = await window.showDirectoryPicker({ ...{ startIn } }); uri = await this.fileSystemProvider.registerDirectoryHandle(handle); } } catch (error) { // ignore - `showOpenFilePicker` / `showDirectoryPicker` will throw an error when the user cancels } return uri ? [uri] : undefined; } private async showUnsupportedBrowserWarning(context: 'save' | 'open'): Promise<undefined> { // When saving, try to just download the contents // of the active text editor if any as a workaround if (context === 'save') { const activeTextModel = this.codeEditorService.getActiveCodeEditor()?.getModel(); if (activeTextModel) { triggerDownload(VSBuffer.fromString(activeTextModel.getValue()).buffer, basename(activeTextModel.uri)); return; } } // Otherwise inform the user about options const buttons = context === 'open' ? [localize('openRemote', "Open Remote..."), localize('learnMore', "Learn More"), localize('openFiles', "Open Files...")] : [localize('openRemote', "Open Remote..."), localize('learnMore', "Learn More")]; const res = await this.dialogService.show( Severity.Warning, localize('unsupportedBrowserMessage', "Opening Local Folders is Unsupported"), buttons, { detail: localize('unsupportedBrowserDetail', "Your browser doesn't support opening local folders.\nYou can either open single files or open a remote repository."), cancelId: -1 // no "Cancel" button offered } ); switch (res.choice) { case 0: this.commandService.executeCommand('workbench.action.remote.showMenu'); break; case 1: this.openerService.open('https://aka.ms/VSCodeWebLocalFileSystemAccess'); break; case 2: { const files = await triggerUpload(); if (files) { const filesData = (await this.instantiationService.invokeFunction(accessor => extractFileListData(accessor, files))).filter(fileData => !fileData.isDirectory); if (filesData.length > 0) { this.editorService.openEditors(filesData.map(fileData => { return { resource: fileData.resource, contents: fileData.contents?.toString(), options: { pinned: true } }; })); } } } break; } return undefined; } private shouldUseSimplified(scheme: string): boolean { return ![Schemas.file, Schemas.vscodeUserData, Schemas.tmp].includes(scheme); } } registerSingleton(IFileDialogService, FileDialogService, InstantiationType.Delayed);
src/vs/workbench/services/dialogs/browser/fileDialogService.ts
0
https://github.com/microsoft/vscode/commit/82a00605474987a1b6f5208018d523fa3b2d356a
[ 0.00018325365090277046, 0.00017126803868450224, 0.00015882342995610088, 0.0001724908361211419, 0.000004867644747719169 ]
{ "id": 0, "code_window": [ "import { Schemas } from 'vs/base/common/network';\n", "import { URI } from 'vs/base/common/uri';\n", "import { IConfigurationService } from 'vs/platform/configuration/common/configuration';\n", "import { ILogService } from 'vs/platform/log/common/log';\n", "import { INotificationService } from 'vs/platform/notification/common/notification';\n", "import { IShellLaunchConfig, TerminalLocation, TerminalSettingId, WaitOnExitValue } from 'vs/platform/terminal/common/terminal';\n", "import { formatMessageForTerminal } from 'vs/platform/terminal/common/terminalStrings';\n", "import { ThemeIcon } from 'vs/platform/theme/common/themeService';\n", "import { IViewDescriptorService, IViewsService, ViewContainerLocation } from 'vs/workbench/common/views';\n", "import { TaskTerminalStatus } from 'vs/workbench/contrib/tasks/browser/taskTerminalStatus';\n", "import { ProblemCollectorEventKind, ProblemHandlingStrategy, StartStopProblemCollector, WatchingProblemCollector } from 'vs/workbench/contrib/tasks/common/problemCollectors';\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { IShellLaunchConfig, TerminalSettingId, WaitOnExitValue } from 'vs/platform/terminal/common/terminal';\n" ], "file_path": "src/vs/workbench/contrib/tasks/browser/terminalTaskSystem.ts", "type": "replace", "edit_start_line_idx": 33 }
{ "name": "diff", "displayName": "%displayName%", "description": "%description%", "version": "1.0.0", "publisher": "vscode", "license": "MIT", "engines": { "vscode": "0.10.x" }, "scripts": { "update-grammar": "node ../node_modules/vscode-grammar-updater/bin textmate/diff.tmbundle Syntaxes/Diff.plist ./syntaxes/diff.tmLanguage.json" }, "contributes": { "languages": [ { "id": "diff", "aliases": [ "Diff", "diff" ], "extensions": [ ".diff", ".patch", ".rej" ], "configuration": "./language-configuration.json" } ], "grammars": [ { "language": "diff", "scopeName": "source.diff", "path": "./syntaxes/diff.tmLanguage.json" } ] } }
extensions/diff/package.json
0
https://github.com/microsoft/vscode/commit/82a00605474987a1b6f5208018d523fa3b2d356a
[ 0.00017591995128896087, 0.00017455713532399386, 0.0001722227461868897, 0.0001750429510138929, 0.0000014527051916957134 ]
{ "id": 1, "code_window": [ "\t\t\tthis._logService.trace(`No terminal found to split for group ${group}`);\n", "\t\t}\n", "\t\t// Either no group is used, no terminal with the group exists or splitting an existing terminal failed.\n", "\t\tconst createdTerminal = await this._terminalService.createTerminal({ location: TerminalLocation.Panel, config: launchConfigs });\n", "\t\tcreatedTerminal.onDisposed((terminal) => this._fireTaskEvent({ kind: TaskEventKind.Terminated, exitReason: terminal.exitReason, taskId: task.getRecentlyUsedKey() }));\n", "\t\treturn createdTerminal;\n", "\t}\n", "\n", "\tprivate _reconnectToTerminals(): void {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tconst createdTerminal = await this._terminalService.createTerminal({ config: launchConfigs });\n" ], "file_path": "src/vs/workbench/contrib/tasks/browser/terminalTaskSystem.ts", "type": "replace", "edit_start_line_idx": 1338 }
/*--------------------------------------------------------------------------------------------- * 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 Severity from 'vs/base/common/severity'; import { dispose, toDisposable } from 'vs/base/common/lifecycle'; import { URI } from 'vs/base/common/uri'; import { EditorInputCapabilities, IEditorIdentifier, IUntypedEditorInput } from 'vs/workbench/common/editor'; import { IThemeService, ThemeIcon } from 'vs/platform/theme/common/themeService'; import { EditorInput, IEditorCloseHandler } from 'vs/workbench/common/editor/editorInput'; import { ITerminalInstance, ITerminalInstanceService, terminalEditorId } from 'vs/workbench/contrib/terminal/browser/terminal'; import { getColorClass, getUriClasses } from 'vs/workbench/contrib/terminal/browser/terminalIcon'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IShellLaunchConfig, TerminalExitReason, TerminalLocation, TerminalSettingId } from 'vs/platform/terminal/common/terminal'; import { IEditorGroup } from 'vs/workbench/services/editor/common/editorGroupsService'; import { ILifecycleService } from 'vs/workbench/services/lifecycle/common/lifecycle'; import { ConfirmOnKill } from 'vs/workbench/contrib/terminal/common/terminal'; import { IContextKey, IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { TerminalContextKeys } from 'vs/workbench/contrib/terminal/common/terminalContextKey'; import { ConfirmResult, IDialogService } from 'vs/platform/dialogs/common/dialogs'; import { Emitter } from 'vs/base/common/event'; export class TerminalEditorInput extends EditorInput implements IEditorCloseHandler { static readonly ID = 'workbench.editors.terminal'; override readonly closeHandler = this; private _isDetached = false; private _isShuttingDown = false; private _isReverted = false; private _copyLaunchConfig?: IShellLaunchConfig; private _terminalEditorFocusContextKey: IContextKey<boolean>; private _group: IEditorGroup | undefined; protected readonly _onDidRequestAttach = this._register(new Emitter<ITerminalInstance>()); readonly onDidRequestAttach = this._onDidRequestAttach.event; setGroup(group: IEditorGroup | undefined) { this._group = group; } get group(): IEditorGroup | undefined { return this._group; } override get typeId(): string { return TerminalEditorInput.ID; } override get editorId(): string | undefined { return terminalEditorId; } override get capabilities(): EditorInputCapabilities { return EditorInputCapabilities.Readonly | EditorInputCapabilities.Singleton | EditorInputCapabilities.CanDropIntoEditor; } setTerminalInstance(instance: ITerminalInstance): void { if (this._terminalInstance) { throw new Error('cannot set instance that has already been set'); } this._terminalInstance = instance; this._setupInstanceListeners(); } override copy(): EditorInput { const instance = this._terminalInstanceService.createInstance(this._copyLaunchConfig || {}, TerminalLocation.Editor); instance.focusWhenReady(); this._copyLaunchConfig = undefined; return this._instantiationService.createInstance(TerminalEditorInput, instance.resource, instance); } /** * Sets the launch config to use for the next call to EditorInput.copy, which will be used when * the editor's split command is run. */ setCopyLaunchConfig(launchConfig: IShellLaunchConfig) { this._copyLaunchConfig = launchConfig; } /** * Returns the terminal instance for this input if it has not yet been detached from the input. */ get terminalInstance(): ITerminalInstance | undefined { return this._isDetached ? undefined : this._terminalInstance; } showConfirm(): boolean { if (this._isReverted) { return false; } const confirmOnKill = this._configurationService.getValue<ConfirmOnKill>(TerminalSettingId.ConfirmOnKill); if (confirmOnKill === 'editor' || confirmOnKill === 'always') { return this._terminalInstance?.hasChildProcesses || false; } return false; } async confirm(terminals: ReadonlyArray<IEditorIdentifier>): Promise<ConfirmResult> { const { choice } = await this._dialogService.show( Severity.Warning, localize('confirmDirtyTerminal.message', "Do you want to terminate running processes?"), [ localize({ key: 'confirmDirtyTerminal.button', comment: ['&& denotes a mnemonic'] }, "&&Terminate"), localize('cancel', "Cancel") ], { cancelId: 1, detail: terminals.length > 1 ? terminals.map(terminal => terminal.editor.getName()).join('\n') + '\n\n' + localize('confirmDirtyTerminals.detail', "Closing will terminate the running processes in the terminals.") : localize('confirmDirtyTerminal.detail', "Closing will terminate the running processes in this terminal.") } ); switch (choice) { case 0: return ConfirmResult.DONT_SAVE; default: return ConfirmResult.CANCEL; } } override async revert(): Promise<void> { // On revert just treat the terminal as permanently non-dirty this._isReverted = true; } constructor( public readonly resource: URI, private _terminalInstance: ITerminalInstance | undefined, @IThemeService private readonly _themeService: IThemeService, @ITerminalInstanceService private readonly _terminalInstanceService: ITerminalInstanceService, @IInstantiationService private readonly _instantiationService: IInstantiationService, @IConfigurationService private readonly _configurationService: IConfigurationService, @ILifecycleService private readonly _lifecycleService: ILifecycleService, @IContextKeyService _contextKeyService: IContextKeyService, @IDialogService private readonly _dialogService: IDialogService ) { super(); this._terminalEditorFocusContextKey = TerminalContextKeys.editorFocus.bindTo(_contextKeyService); if (_terminalInstance) { this._setupInstanceListeners(); } } private _setupInstanceListeners(): void { const instance = this._terminalInstance; if (!instance) { return; } this._register(toDisposable(() => { if (!this._isDetached && !this._isShuttingDown) { // Will be ignored if triggered by onExit or onDisposed terminal events // as disposed was already called instance.dispose(TerminalExitReason.User); } })); const disposeListeners = [ instance.onExit(() => this.dispose()), instance.onDisposed(() => this.dispose()), instance.onTitleChanged(() => this._onDidChangeLabel.fire()), instance.onIconChanged(() => this._onDidChangeLabel.fire()), instance.onDidFocus(() => this._terminalEditorFocusContextKey.set(true)), instance.onDidBlur(() => this._terminalEditorFocusContextKey.reset()), instance.statusList.onDidChangePrimaryStatus(() => this._onDidChangeLabel.fire()) ]; // Don't dispose editor when instance is torn down on shutdown to avoid extra work and so // the editor/tabs don't disappear this._lifecycleService.onWillShutdown(() => { this._isShuttingDown = true; dispose(disposeListeners); }); } override getName() { return this._terminalInstance?.title || this.resource.fragment; } override getLabelExtraClasses(): string[] { if (!this._terminalInstance) { return []; } const extraClasses: string[] = ['terminal-tab']; const colorClass = getColorClass(this._terminalInstance); if (colorClass) { extraClasses.push(colorClass); } const uriClasses = getUriClasses(this._terminalInstance, this._themeService.getColorTheme().type); if (uriClasses) { extraClasses.push(...uriClasses); } if (ThemeIcon.isThemeIcon(this._terminalInstance.icon)) { extraClasses.push(`codicon-${this._terminalInstance.icon.id}`); } return extraClasses; } /** * Detach the instance from the input such that when the input is disposed it will not dispose * of the terminal instance/process. */ detachInstance() { if (!this._isShuttingDown) { this._terminalInstance?.detachFromElement(); this._isDetached = true; } } public override getDescription(): string | undefined { return this._terminalInstance?.description; } public override toUntyped(): IUntypedEditorInput { return { resource: this.resource, options: { override: terminalEditorId, pinned: true, forceReload: true } }; } }
src/vs/workbench/contrib/terminal/browser/terminalEditorInput.ts
1
https://github.com/microsoft/vscode/commit/82a00605474987a1b6f5208018d523fa3b2d356a
[ 0.0003402667643968016, 0.0001922876836033538, 0.00016423320630565286, 0.00017219013534486294, 0.00004160272146691568 ]
{ "id": 1, "code_window": [ "\t\t\tthis._logService.trace(`No terminal found to split for group ${group}`);\n", "\t\t}\n", "\t\t// Either no group is used, no terminal with the group exists or splitting an existing terminal failed.\n", "\t\tconst createdTerminal = await this._terminalService.createTerminal({ location: TerminalLocation.Panel, config: launchConfigs });\n", "\t\tcreatedTerminal.onDisposed((terminal) => this._fireTaskEvent({ kind: TaskEventKind.Terminated, exitReason: terminal.exitReason, taskId: task.getRecentlyUsedKey() }));\n", "\t\treturn createdTerminal;\n", "\t}\n", "\n", "\tprivate _reconnectToTerminals(): void {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tconst createdTerminal = await this._terminalService.createTerminal({ config: launchConfigs });\n" ], "file_path": "src/vs/workbench/contrib/tasks/browser/terminalTaskSystem.ts", "type": "replace", "edit_start_line_idx": 1338 }
THIRD-PARTY SOFTWARE NOTICES AND INFORMATION Do Not Translate or Localize This project incorporates components from the projects listed below. The original copyright notices and the licenses under which Microsoft received such components are set forth below. Microsoft reserves all rights not expressly granted herein, whether by implication, estoppel or otherwise. %% nodejs path library (https://github.com/nodejs/node/tree/43dd49c9782848c25e5b03448c8a0f923f13c158) ========================================= Copyright Joyent, Inc. and other Node contributors. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ========================================= END OF nodejs path library NOTICES AND INFORMATION %% markedjs NOTICES AND INFORMATION BEGIN HERE ========================================= The MIT License (MIT) Copyright (c) 2018+, MarkedJS (https://github.com/markedjs/) Copyright (c) 2011-2018, Christopher Jeffrey (https://github.com/chjj/) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ========================================= END OF markedjs NOTICES AND INFORMATION
build/monaco/ThirdPartyNotices.txt
0
https://github.com/microsoft/vscode/commit/82a00605474987a1b6f5208018d523fa3b2d356a
[ 0.00017884506087284535, 0.00017485635180491954, 0.00016991046140901744, 0.00017440358351450413, 0.0000026455422812432516 ]
{ "id": 1, "code_window": [ "\t\t\tthis._logService.trace(`No terminal found to split for group ${group}`);\n", "\t\t}\n", "\t\t// Either no group is used, no terminal with the group exists or splitting an existing terminal failed.\n", "\t\tconst createdTerminal = await this._terminalService.createTerminal({ location: TerminalLocation.Panel, config: launchConfigs });\n", "\t\tcreatedTerminal.onDisposed((terminal) => this._fireTaskEvent({ kind: TaskEventKind.Terminated, exitReason: terminal.exitReason, taskId: task.getRecentlyUsedKey() }));\n", "\t\treturn createdTerminal;\n", "\t}\n", "\n", "\tprivate _reconnectToTerminals(): void {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tconst createdTerminal = await this._terminalService.createTerminal({ config: launchConfigs });\n" ], "file_path": "src/vs/workbench/contrib/tasks/browser/terminalTaskSystem.ts", "type": "replace", "edit_start_line_idx": 1338 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as assert from 'assert'; import { URI } from 'vs/base/common/uri'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { EditorPart } from 'vs/workbench/browser/parts/editor/editorPart'; import { IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService'; import { EditorService } from 'vs/workbench/services/editor/browser/editorService'; import { IUntitledTextResourceEditorInput } from 'vs/workbench/common/editor'; import { IWorkingCopyBackupService } from 'vs/workbench/services/workingCopy/common/workingCopyBackup'; import { toResource } from 'vs/base/test/common/utils'; import { IFilesConfigurationService } from 'vs/workbench/services/filesConfiguration/common/filesConfigurationService'; import { IWorkingCopyService } from 'vs/workbench/services/workingCopy/common/workingCopyService'; import { IWorkingCopyBackup } from 'vs/workbench/services/workingCopy/common/workingCopy'; import { ILogService } from 'vs/platform/log/common/log'; import { ILifecycleService, LifecyclePhase } from 'vs/workbench/services/lifecycle/common/lifecycle'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { UntitledTextEditorInput } from 'vs/workbench/services/untitled/common/untitledTextEditorInput'; import { createEditorPart, InMemoryTestWorkingCopyBackupService, registerTestResourceEditor, TestServiceAccessor, toTypedWorkingCopyId, toUntypedWorkingCopyId, workbenchInstantiationService } from 'vs/workbench/test/browser/workbenchTestServices'; import { TestWorkingCopy } from 'vs/workbench/test/common/workbenchTestServices'; import { CancellationToken } from 'vs/base/common/cancellation'; import { timeout } from 'vs/base/common/async'; import { BrowserWorkingCopyBackupTracker } from 'vs/workbench/services/workingCopy/browser/workingCopyBackupTracker'; import { DisposableStore, dispose, IDisposable } from 'vs/base/common/lifecycle'; import { IWorkingCopyEditorHandler, IWorkingCopyEditorService } from 'vs/workbench/services/workingCopy/common/workingCopyEditorService'; import { bufferToReadable, VSBuffer } from 'vs/base/common/buffer'; import { isWindows } from 'vs/base/common/platform'; import { Schemas } from 'vs/base/common/network'; import { IWorkspaceTrustRequestService } from 'vs/platform/workspace/common/workspaceTrust'; import { TestWorkspaceTrustRequestService } from 'vs/workbench/services/workspaces/test/common/testWorkspaceTrustService'; suite('WorkingCopyBackupTracker (browser)', function () { let accessor: TestServiceAccessor; const disposables = new DisposableStore(); setup(() => { disposables.add(registerTestResourceEditor()); }); teardown(() => { disposables.clear(); }); class TestWorkingCopyBackupTracker extends BrowserWorkingCopyBackupTracker { constructor( @IWorkingCopyBackupService workingCopyBackupService: IWorkingCopyBackupService, @IFilesConfigurationService filesConfigurationService: IFilesConfigurationService, @IWorkingCopyService workingCopyService: IWorkingCopyService, @ILifecycleService lifecycleService: ILifecycleService, @ILogService logService: ILogService, @IWorkingCopyEditorService workingCopyEditorService: IWorkingCopyEditorService, @IEditorService editorService: IEditorService, @IEditorGroupsService editorGroupService: IEditorGroupsService ) { super(workingCopyBackupService, filesConfigurationService, workingCopyService, lifecycleService, logService, workingCopyEditorService, editorService, editorGroupService); } protected override getBackupScheduleDelay(): number { return 10; // Reduce timeout for tests } get pendingBackupOperationCount(): number { return this.pendingBackupOperations.size; } getUnrestoredBackups() { return this.unrestoredBackups; } async testRestoreBackups(handler: IWorkingCopyEditorHandler): Promise<void> { return super.restoreBackups(handler); } } class TestUntitledTextEditorInput extends UntitledTextEditorInput { resolved = false; override resolve() { this.resolved = true; return super.resolve(); } } async function createTracker(): Promise<{ accessor: TestServiceAccessor; part: EditorPart; tracker: TestWorkingCopyBackupTracker; workingCopyBackupService: InMemoryTestWorkingCopyBackupService; instantiationService: IInstantiationService; cleanup: () => void }> { const disposables = new DisposableStore(); const workingCopyBackupService = new InMemoryTestWorkingCopyBackupService(); const instantiationService = workbenchInstantiationService(undefined, disposables); instantiationService.stub(IWorkingCopyBackupService, workingCopyBackupService); const part = await createEditorPart(instantiationService, disposables); instantiationService.stub(IEditorGroupsService, part); disposables.add(registerTestResourceEditor()); instantiationService.stub(IWorkspaceTrustRequestService, new TestWorkspaceTrustRequestService(false)); const editorService: EditorService = instantiationService.createInstance(EditorService); instantiationService.stub(IEditorService, editorService); accessor = instantiationService.createInstance(TestServiceAccessor); const tracker = disposables.add(instantiationService.createInstance(TestWorkingCopyBackupTracker)); return { accessor, part, tracker, workingCopyBackupService: workingCopyBackupService, instantiationService, cleanup: () => disposables.dispose() }; } async function untitledBackupTest(untitled: IUntitledTextResourceEditorInput = { resource: undefined }): Promise<void> { const { accessor, cleanup, workingCopyBackupService } = await createTracker(); const untitledTextEditor = (await accessor.editorService.openEditor(untitled))?.input as UntitledTextEditorInput; const untitledTextModel = await untitledTextEditor.resolve(); if (!untitled?.contents) { untitledTextModel.textEditorModel?.setValue('Super Good'); } await workingCopyBackupService.joinBackupResource(); assert.strictEqual(workingCopyBackupService.hasBackupSync(untitledTextModel), true); untitledTextModel.dispose(); await workingCopyBackupService.joinDiscardBackup(); assert.strictEqual(workingCopyBackupService.hasBackupSync(untitledTextModel), false); cleanup(); } test('Track backups (untitled)', function () { return untitledBackupTest(); }); test('Track backups (untitled with initial contents)', function () { return untitledBackupTest({ resource: undefined, contents: 'Foo Bar' }); }); test('Track backups (custom)', async function () { const { accessor, tracker, cleanup, workingCopyBackupService } = await createTracker(); class TestBackupWorkingCopy extends TestWorkingCopy { backupDelay = 0; constructor(resource: URI) { super(resource); accessor.workingCopyService.registerWorkingCopy(this); } override async backup(token: CancellationToken): Promise<IWorkingCopyBackup> { await timeout(this.backupDelay); return {}; } } const resource = toResource.call(this, '/path/custom.txt'); const customWorkingCopy = new TestBackupWorkingCopy(resource); // Normal customWorkingCopy.setDirty(true); assert.strictEqual(tracker.pendingBackupOperationCount, 1); await workingCopyBackupService.joinBackupResource(); assert.strictEqual(workingCopyBackupService.hasBackupSync(customWorkingCopy), true); customWorkingCopy.setDirty(false); customWorkingCopy.setDirty(true); assert.strictEqual(tracker.pendingBackupOperationCount, 1); await workingCopyBackupService.joinBackupResource(); assert.strictEqual(workingCopyBackupService.hasBackupSync(customWorkingCopy), true); customWorkingCopy.setDirty(false); assert.strictEqual(tracker.pendingBackupOperationCount, 1); await workingCopyBackupService.joinDiscardBackup(); assert.strictEqual(workingCopyBackupService.hasBackupSync(customWorkingCopy), false); // Cancellation customWorkingCopy.setDirty(true); await timeout(0); customWorkingCopy.setDirty(false); assert.strictEqual(tracker.pendingBackupOperationCount, 1); await workingCopyBackupService.joinDiscardBackup(); assert.strictEqual(workingCopyBackupService.hasBackupSync(customWorkingCopy), false); customWorkingCopy.dispose(); cleanup(); }); async function restoreBackupsInit(): Promise<[TestWorkingCopyBackupTracker, TestServiceAccessor, IDisposable]> { const fooFile = URI.file(isWindows ? 'c:\\Foo' : '/Foo'); const barFile = URI.file(isWindows ? 'c:\\Bar' : '/Bar'); const untitledFile1 = URI.from({ scheme: Schemas.untitled, path: 'Untitled-1' }); const untitledFile2 = URI.from({ scheme: Schemas.untitled, path: 'Untitled-2' }); const disposables = new DisposableStore(); const workingCopyBackupService = new InMemoryTestWorkingCopyBackupService(); const instantiationService = workbenchInstantiationService(undefined, disposables); instantiationService.stub(IWorkingCopyBackupService, workingCopyBackupService); const part = await createEditorPart(instantiationService, disposables); instantiationService.stub(IEditorGroupsService, part); instantiationService.stub(IWorkspaceTrustRequestService, new TestWorkspaceTrustRequestService(false)); const editorService: EditorService = instantiationService.createInstance(EditorService); instantiationService.stub(IEditorService, editorService); accessor = instantiationService.createInstance(TestServiceAccessor); // Backup 2 normal files and 2 untitled files const untitledFile1WorkingCopyId = toUntypedWorkingCopyId(untitledFile1); const untitledFile2WorkingCopyId = toTypedWorkingCopyId(untitledFile2); await workingCopyBackupService.backup(untitledFile1WorkingCopyId, bufferToReadable(VSBuffer.fromString('untitled-1'))); await workingCopyBackupService.backup(untitledFile2WorkingCopyId, bufferToReadable(VSBuffer.fromString('untitled-2'))); const fooFileWorkingCopyId = toUntypedWorkingCopyId(fooFile); const barFileWorkingCopyId = toTypedWorkingCopyId(barFile); await workingCopyBackupService.backup(fooFileWorkingCopyId, bufferToReadable(VSBuffer.fromString('fooFile'))); await workingCopyBackupService.backup(barFileWorkingCopyId, bufferToReadable(VSBuffer.fromString('barFile'))); const tracker = disposables.add(instantiationService.createInstance(TestWorkingCopyBackupTracker)); accessor.lifecycleService.phase = LifecyclePhase.Restored; return [tracker, accessor, disposables]; } test('Restore backups (basics, some handled)', async function () { const [tracker, accessor, disposables] = await restoreBackupsInit(); assert.strictEqual(tracker.getUnrestoredBackups().size, 0); let handlesCounter = 0; let isOpenCounter = 0; let createEditorCounter = 0; await tracker.testRestoreBackups({ handles: workingCopy => { handlesCounter++; return workingCopy.typeId === 'testBackupTypeId'; }, isOpen: (workingCopy, editor) => { isOpenCounter++; return false; }, createEditor: workingCopy => { createEditorCounter++; return accessor.instantiationService.createInstance(TestUntitledTextEditorInput, accessor.untitledTextEditorService.create({ initialValue: 'foo' })); } }); assert.strictEqual(handlesCounter, 4); assert.strictEqual(isOpenCounter, 0); assert.strictEqual(createEditorCounter, 2); assert.strictEqual(accessor.editorService.count, 2); assert.ok(accessor.editorService.editors.every(editor => editor.isDirty())); assert.strictEqual(tracker.getUnrestoredBackups().size, 2); for (const editor of accessor.editorService.editors) { assert.ok(editor instanceof TestUntitledTextEditorInput); assert.strictEqual(editor.resolved, true); } dispose(disposables); }); test('Restore backups (basics, none handled)', async function () { const [tracker, accessor, disposables] = await restoreBackupsInit(); await tracker.testRestoreBackups({ handles: workingCopy => false, isOpen: (workingCopy, editor) => { throw new Error('unexpected'); }, createEditor: workingCopy => { throw new Error('unexpected'); } }); assert.strictEqual(accessor.editorService.count, 0); assert.strictEqual(tracker.getUnrestoredBackups().size, 4); dispose(disposables); }); test('Restore backups (basics, error case)', async function () { const [tracker, , disposables] = await restoreBackupsInit(); try { await tracker.testRestoreBackups({ handles: workingCopy => true, isOpen: (workingCopy, editor) => { throw new Error('unexpected'); }, createEditor: workingCopy => { throw new Error('unexpected'); } }); } catch (error) { // ignore } assert.strictEqual(tracker.getUnrestoredBackups().size, 4); dispose(disposables); }); test('Restore backups (multiple handlers)', async function () { const [tracker, accessor, disposables] = await restoreBackupsInit(); const firstHandler = tracker.testRestoreBackups({ handles: workingCopy => { return workingCopy.typeId === 'testBackupTypeId'; }, isOpen: (workingCopy, editor) => { return false; }, createEditor: workingCopy => { return accessor.instantiationService.createInstance(TestUntitledTextEditorInput, accessor.untitledTextEditorService.create({ initialValue: 'foo' })); } }); const secondHandler = tracker.testRestoreBackups({ handles: workingCopy => { return workingCopy.typeId.length === 0; }, isOpen: (workingCopy, editor) => { return false; }, createEditor: workingCopy => { return accessor.instantiationService.createInstance(TestUntitledTextEditorInput, accessor.untitledTextEditorService.create({ initialValue: 'foo' })); } }); await Promise.all([firstHandler, secondHandler]); assert.strictEqual(accessor.editorService.count, 4); assert.ok(accessor.editorService.editors.every(editor => editor.isDirty())); assert.strictEqual(tracker.getUnrestoredBackups().size, 0); for (const editor of accessor.editorService.editors) { assert.ok(editor instanceof TestUntitledTextEditorInput); assert.strictEqual(editor.resolved, true); } dispose(disposables); }); test('Restore backups (editors already opened)', async function () { const [tracker, accessor, disposables] = await restoreBackupsInit(); assert.strictEqual(tracker.getUnrestoredBackups().size, 0); let handlesCounter = 0; let isOpenCounter = 0; const editor1 = accessor.instantiationService.createInstance(TestUntitledTextEditorInput, accessor.untitledTextEditorService.create({ initialValue: 'foo' })); const editor2 = accessor.instantiationService.createInstance(TestUntitledTextEditorInput, accessor.untitledTextEditorService.create({ initialValue: 'foo' })); await accessor.editorService.openEditors([{ editor: editor1 }, { editor: editor2 }]); editor1.resolved = false; editor2.resolved = false; await tracker.testRestoreBackups({ handles: workingCopy => { handlesCounter++; return workingCopy.typeId === 'testBackupTypeId'; }, isOpen: (workingCopy, editor) => { isOpenCounter++; return true; }, createEditor: workingCopy => { throw new Error('unexpected'); } }); assert.strictEqual(handlesCounter, 4); assert.strictEqual(isOpenCounter, 4); assert.strictEqual(accessor.editorService.count, 2); assert.strictEqual(tracker.getUnrestoredBackups().size, 2); for (const editor of accessor.editorService.editors) { assert.ok(editor instanceof TestUntitledTextEditorInput); // assert that we only call `resolve` on inactive editors if (accessor.editorService.isVisible(editor)) { assert.strictEqual(editor.resolved, false); } else { assert.strictEqual(editor.resolved, true); } } dispose(disposables); }); });
src/vs/workbench/services/workingCopy/test/browser/workingCopyBackupTracker.test.ts
0
https://github.com/microsoft/vscode/commit/82a00605474987a1b6f5208018d523fa3b2d356a
[ 0.0001766583591233939, 0.0001734858815325424, 0.00016693539510015398, 0.00017416427726857364, 0.0000020347695226519136 ]
{ "id": 1, "code_window": [ "\t\t\tthis._logService.trace(`No terminal found to split for group ${group}`);\n", "\t\t}\n", "\t\t// Either no group is used, no terminal with the group exists or splitting an existing terminal failed.\n", "\t\tconst createdTerminal = await this._terminalService.createTerminal({ location: TerminalLocation.Panel, config: launchConfigs });\n", "\t\tcreatedTerminal.onDisposed((terminal) => this._fireTaskEvent({ kind: TaskEventKind.Terminated, exitReason: terminal.exitReason, taskId: task.getRecentlyUsedKey() }));\n", "\t\treturn createdTerminal;\n", "\t}\n", "\n", "\tprivate _reconnectToTerminals(): void {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tconst createdTerminal = await this._terminalService.createTerminal({ config: launchConfigs });\n" ], "file_path": "src/vs/workbench/contrib/tasks/browser/terminalTaskSystem.ts", "type": "replace", "edit_start_line_idx": 1338 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { CharCode } from 'vs/base/common/charCode'; import * as strings from 'vs/base/common/strings'; import { Constants } from 'vs/base/common/uint'; import { EditOperation, ISingleEditOperation } from 'vs/editor/common/core/editOperation'; import { Position } from 'vs/editor/common/core/position'; import { Range } from 'vs/editor/common/core/range'; import { Selection } from 'vs/editor/common/core/selection'; import { ICommand, ICursorStateComputerData, IEditOperationBuilder } from 'vs/editor/common/editorCommon'; import { ITextModel } from 'vs/editor/common/model'; import { ILanguageConfigurationService } from 'vs/editor/common/languages/languageConfigurationRegistry'; import { BlockCommentCommand } from 'vs/editor/contrib/comment/browser/blockCommentCommand'; export interface IInsertionPoint { ignore: boolean; commentStrOffset: number; } export interface ILinePreflightData { ignore: boolean; commentStr: string; commentStrOffset: number; commentStrLength: number; } export interface IPreflightDataSupported { supported: true; shouldRemoveComments: boolean; lines: ILinePreflightData[]; } export interface IPreflightDataUnsupported { supported: false; } export type IPreflightData = IPreflightDataSupported | IPreflightDataUnsupported; export interface ISimpleModel { getLineContent(lineNumber: number): string; } export const enum Type { Toggle = 0, ForceAdd = 1, ForceRemove = 2 } export class LineCommentCommand implements ICommand { private readonly _selection: Selection; private readonly _tabSize: number; private readonly _type: Type; private readonly _insertSpace: boolean; private readonly _ignoreEmptyLines: boolean; private _selectionId: string | null; private _deltaColumn: number; private _moveEndPositionDown: boolean; private _ignoreFirstLine: boolean; constructor( private readonly languageConfigurationService: ILanguageConfigurationService, selection: Selection, tabSize: number, type: Type, insertSpace: boolean, ignoreEmptyLines: boolean, ignoreFirstLine?: boolean, ) { this._selection = selection; this._tabSize = tabSize; this._type = type; this._insertSpace = insertSpace; this._selectionId = null; this._deltaColumn = 0; this._moveEndPositionDown = false; this._ignoreEmptyLines = ignoreEmptyLines; this._ignoreFirstLine = ignoreFirstLine || false; } /** * Do an initial pass over the lines and gather info about the line comment string. * Returns null if any of the lines doesn't support a line comment string. */ private static _gatherPreflightCommentStrings(model: ITextModel, startLineNumber: number, endLineNumber: number, languageConfigurationService: ILanguageConfigurationService): ILinePreflightData[] | null { model.tokenization.tokenizeIfCheap(startLineNumber); const languageId = model.getLanguageIdAtPosition(startLineNumber, 1); const config = languageConfigurationService.getLanguageConfiguration(languageId).comments; const commentStr = (config ? config.lineCommentToken : null); if (!commentStr) { // Mode does not support line comments return null; } const lines: ILinePreflightData[] = []; for (let i = 0, lineCount = endLineNumber - startLineNumber + 1; i < lineCount; i++) { lines[i] = { ignore: false, commentStr: commentStr, commentStrOffset: 0, commentStrLength: commentStr.length }; } return lines; } /** * Analyze lines and decide which lines are relevant and what the toggle should do. * Also, build up several offsets and lengths useful in the generation of editor operations. */ public static _analyzeLines(type: Type, insertSpace: boolean, model: ISimpleModel, lines: ILinePreflightData[], startLineNumber: number, ignoreEmptyLines: boolean, ignoreFirstLine: boolean, languageConfigurationService: ILanguageConfigurationService): IPreflightData { let onlyWhitespaceLines = true; let shouldRemoveComments: boolean; if (type === Type.Toggle) { shouldRemoveComments = true; } else if (type === Type.ForceAdd) { shouldRemoveComments = false; } else { shouldRemoveComments = true; } for (let i = 0, lineCount = lines.length; i < lineCount; i++) { const lineData = lines[i]; const lineNumber = startLineNumber + i; if (lineNumber === startLineNumber && ignoreFirstLine) { // first line ignored lineData.ignore = true; continue; } const lineContent = model.getLineContent(lineNumber); const lineContentStartOffset = strings.firstNonWhitespaceIndex(lineContent); if (lineContentStartOffset === -1) { // Empty or whitespace only line lineData.ignore = ignoreEmptyLines; lineData.commentStrOffset = lineContent.length; continue; } onlyWhitespaceLines = false; lineData.ignore = false; lineData.commentStrOffset = lineContentStartOffset; if (shouldRemoveComments && !BlockCommentCommand._haystackHasNeedleAtOffset(lineContent, lineData.commentStr, lineContentStartOffset)) { if (type === Type.Toggle) { // Every line so far has been a line comment, but this one is not shouldRemoveComments = false; } else if (type === Type.ForceAdd) { // Will not happen } else { lineData.ignore = true; } } if (shouldRemoveComments && insertSpace) { // Remove a following space if present const commentStrEndOffset = lineContentStartOffset + lineData.commentStrLength; if (commentStrEndOffset < lineContent.length && lineContent.charCodeAt(commentStrEndOffset) === CharCode.Space) { lineData.commentStrLength += 1; } } } if (type === Type.Toggle && onlyWhitespaceLines) { // For only whitespace lines, we insert comments shouldRemoveComments = false; // Also, no longer ignore them for (let i = 0, lineCount = lines.length; i < lineCount; i++) { lines[i].ignore = false; } } return { supported: true, shouldRemoveComments: shouldRemoveComments, lines: lines }; } /** * Analyze all lines and decide exactly what to do => not supported | insert line comments | remove line comments */ public static _gatherPreflightData(type: Type, insertSpace: boolean, model: ITextModel, startLineNumber: number, endLineNumber: number, ignoreEmptyLines: boolean, ignoreFirstLine: boolean, languageConfigurationService: ILanguageConfigurationService): IPreflightData { const lines = LineCommentCommand._gatherPreflightCommentStrings(model, startLineNumber, endLineNumber, languageConfigurationService); if (lines === null) { return { supported: false }; } return LineCommentCommand._analyzeLines(type, insertSpace, model, lines, startLineNumber, ignoreEmptyLines, ignoreFirstLine, languageConfigurationService); } /** * Given a successful analysis, execute either insert line comments, either remove line comments */ private _executeLineComments(model: ISimpleModel, builder: IEditOperationBuilder, data: IPreflightDataSupported, s: Selection): void { let ops: ISingleEditOperation[]; if (data.shouldRemoveComments) { ops = LineCommentCommand._createRemoveLineCommentsOperations(data.lines, s.startLineNumber); } else { LineCommentCommand._normalizeInsertionPoint(model, data.lines, s.startLineNumber, this._tabSize); ops = this._createAddLineCommentsOperations(data.lines, s.startLineNumber); } const cursorPosition = new Position(s.positionLineNumber, s.positionColumn); for (let i = 0, len = ops.length; i < len; i++) { builder.addEditOperation(ops[i].range, ops[i].text); if (Range.isEmpty(ops[i].range) && Range.getStartPosition(ops[i].range).equals(cursorPosition)) { const lineContent = model.getLineContent(cursorPosition.lineNumber); if (lineContent.length + 1 === cursorPosition.column) { this._deltaColumn = (ops[i].text || '').length; } } } this._selectionId = builder.trackSelection(s); } private _attemptRemoveBlockComment(model: ITextModel, s: Selection, startToken: string, endToken: string): ISingleEditOperation[] | null { let startLineNumber = s.startLineNumber; let endLineNumber = s.endLineNumber; const startTokenAllowedBeforeColumn = endToken.length + Math.max( model.getLineFirstNonWhitespaceColumn(s.startLineNumber), s.startColumn ); let startTokenIndex = model.getLineContent(startLineNumber).lastIndexOf(startToken, startTokenAllowedBeforeColumn - 1); let endTokenIndex = model.getLineContent(endLineNumber).indexOf(endToken, s.endColumn - 1 - startToken.length); if (startTokenIndex !== -1 && endTokenIndex === -1) { endTokenIndex = model.getLineContent(startLineNumber).indexOf(endToken, startTokenIndex + startToken.length); endLineNumber = startLineNumber; } if (startTokenIndex === -1 && endTokenIndex !== -1) { startTokenIndex = model.getLineContent(endLineNumber).lastIndexOf(startToken, endTokenIndex); startLineNumber = endLineNumber; } if (s.isEmpty() && (startTokenIndex === -1 || endTokenIndex === -1)) { startTokenIndex = model.getLineContent(startLineNumber).indexOf(startToken); if (startTokenIndex !== -1) { endTokenIndex = model.getLineContent(startLineNumber).indexOf(endToken, startTokenIndex + startToken.length); } } // We have to adjust to possible inner white space. // For Space after startToken, add Space to startToken - range math will work out. if (startTokenIndex !== -1 && model.getLineContent(startLineNumber).charCodeAt(startTokenIndex + startToken.length) === CharCode.Space) { startToken += ' '; } // For Space before endToken, add Space before endToken and shift index one left. if (endTokenIndex !== -1 && model.getLineContent(endLineNumber).charCodeAt(endTokenIndex - 1) === CharCode.Space) { endToken = ' ' + endToken; endTokenIndex -= 1; } if (startTokenIndex !== -1 && endTokenIndex !== -1) { return BlockCommentCommand._createRemoveBlockCommentOperations( new Range(startLineNumber, startTokenIndex + startToken.length + 1, endLineNumber, endTokenIndex + 1), startToken, endToken ); } return null; } /** * Given an unsuccessful analysis, delegate to the block comment command */ private _executeBlockComment(model: ITextModel, builder: IEditOperationBuilder, s: Selection): void { model.tokenization.tokenizeIfCheap(s.startLineNumber); const languageId = model.getLanguageIdAtPosition(s.startLineNumber, 1); const config = this.languageConfigurationService.getLanguageConfiguration(languageId).comments; if (!config || !config.blockCommentStartToken || !config.blockCommentEndToken) { // Mode does not support block comments return; } const startToken = config.blockCommentStartToken; const endToken = config.blockCommentEndToken; let ops = this._attemptRemoveBlockComment(model, s, startToken, endToken); if (!ops) { if (s.isEmpty()) { const lineContent = model.getLineContent(s.startLineNumber); let firstNonWhitespaceIndex = strings.firstNonWhitespaceIndex(lineContent); if (firstNonWhitespaceIndex === -1) { // Line is empty or contains only whitespace firstNonWhitespaceIndex = lineContent.length; } ops = BlockCommentCommand._createAddBlockCommentOperations( new Range(s.startLineNumber, firstNonWhitespaceIndex + 1, s.startLineNumber, lineContent.length + 1), startToken, endToken, this._insertSpace ); } else { ops = BlockCommentCommand._createAddBlockCommentOperations( new Range(s.startLineNumber, model.getLineFirstNonWhitespaceColumn(s.startLineNumber), s.endLineNumber, model.getLineMaxColumn(s.endLineNumber)), startToken, endToken, this._insertSpace ); } if (ops.length === 1) { // Leave cursor after token and Space this._deltaColumn = startToken.length + 1; } } this._selectionId = builder.trackSelection(s); for (const op of ops) { builder.addEditOperation(op.range, op.text); } } public getEditOperations(model: ITextModel, builder: IEditOperationBuilder): void { let s = this._selection; this._moveEndPositionDown = false; if (s.startLineNumber === s.endLineNumber && this._ignoreFirstLine) { builder.addEditOperation(new Range(s.startLineNumber, model.getLineMaxColumn(s.startLineNumber), s.startLineNumber + 1, 1), s.startLineNumber === model.getLineCount() ? '' : '\n'); this._selectionId = builder.trackSelection(s); return; } if (s.startLineNumber < s.endLineNumber && s.endColumn === 1) { this._moveEndPositionDown = true; s = s.setEndPosition(s.endLineNumber - 1, model.getLineMaxColumn(s.endLineNumber - 1)); } const data = LineCommentCommand._gatherPreflightData( this._type, this._insertSpace, model, s.startLineNumber, s.endLineNumber, this._ignoreEmptyLines, this._ignoreFirstLine, this.languageConfigurationService ); if (data.supported) { return this._executeLineComments(model, builder, data, s); } return this._executeBlockComment(model, builder, s); } public computeCursorState(model: ITextModel, helper: ICursorStateComputerData): Selection { let result = helper.getTrackedSelection(this._selectionId!); if (this._moveEndPositionDown) { result = result.setEndPosition(result.endLineNumber + 1, 1); } return new Selection( result.selectionStartLineNumber, result.selectionStartColumn + this._deltaColumn, result.positionLineNumber, result.positionColumn + this._deltaColumn ); } /** * Generate edit operations in the remove line comment case */ public static _createRemoveLineCommentsOperations(lines: ILinePreflightData[], startLineNumber: number): ISingleEditOperation[] { const res: ISingleEditOperation[] = []; for (let i = 0, len = lines.length; i < len; i++) { const lineData = lines[i]; if (lineData.ignore) { continue; } res.push(EditOperation.delete(new Range( startLineNumber + i, lineData.commentStrOffset + 1, startLineNumber + i, lineData.commentStrOffset + lineData.commentStrLength + 1 ))); } return res; } /** * Generate edit operations in the add line comment case */ private _createAddLineCommentsOperations(lines: ILinePreflightData[], startLineNumber: number): ISingleEditOperation[] { const res: ISingleEditOperation[] = []; const afterCommentStr = this._insertSpace ? ' ' : ''; for (let i = 0, len = lines.length; i < len; i++) { const lineData = lines[i]; if (lineData.ignore) { continue; } res.push(EditOperation.insert(new Position(startLineNumber + i, lineData.commentStrOffset + 1), lineData.commentStr + afterCommentStr)); } return res; } private static nextVisibleColumn(currentVisibleColumn: number, tabSize: number, isTab: boolean, columnSize: number): number { if (isTab) { return currentVisibleColumn + (tabSize - (currentVisibleColumn % tabSize)); } return currentVisibleColumn + columnSize; } /** * Adjust insertion points to have them vertically aligned in the add line comment case */ public static _normalizeInsertionPoint(model: ISimpleModel, lines: IInsertionPoint[], startLineNumber: number, tabSize: number): void { let minVisibleColumn = Constants.MAX_SAFE_SMALL_INTEGER; let j: number; let lenJ: number; for (let i = 0, len = lines.length; i < len; i++) { if (lines[i].ignore) { continue; } const lineContent = model.getLineContent(startLineNumber + i); let currentVisibleColumn = 0; for (let j = 0, lenJ = lines[i].commentStrOffset; currentVisibleColumn < minVisibleColumn && j < lenJ; j++) { currentVisibleColumn = LineCommentCommand.nextVisibleColumn(currentVisibleColumn, tabSize, lineContent.charCodeAt(j) === CharCode.Tab, 1); } if (currentVisibleColumn < minVisibleColumn) { minVisibleColumn = currentVisibleColumn; } } minVisibleColumn = Math.floor(minVisibleColumn / tabSize) * tabSize; for (let i = 0, len = lines.length; i < len; i++) { if (lines[i].ignore) { continue; } const lineContent = model.getLineContent(startLineNumber + i); let currentVisibleColumn = 0; for (j = 0, lenJ = lines[i].commentStrOffset; currentVisibleColumn < minVisibleColumn && j < lenJ; j++) { currentVisibleColumn = LineCommentCommand.nextVisibleColumn(currentVisibleColumn, tabSize, lineContent.charCodeAt(j) === CharCode.Tab, 1); } if (currentVisibleColumn > minVisibleColumn) { lines[i].commentStrOffset = j - 1; } else { lines[i].commentStrOffset = j; } } } }
src/vs/editor/contrib/comment/browser/lineCommentCommand.ts
0
https://github.com/microsoft/vscode/commit/82a00605474987a1b6f5208018d523fa3b2d356a
[ 0.00017713099077809602, 0.00017393955204170197, 0.0001658371911616996, 0.00017427426064386964, 0.0000020315883375587873 ]
{ "id": 2, "code_window": [ "\t\t}));\n", "\n", "\t\tconst disposeListeners = [\n", "\t\t\tinstance.onExit(() => this.dispose()),\n", "\t\t\tinstance.onDisposed(() => this.dispose()),\n", "\t\t\tinstance.onTitleChanged(() => this._onDidChangeLabel.fire()),\n", "\t\t\tinstance.onIconChanged(() => this._onDidChangeLabel.fire()),\n", "\t\t\tinstance.onDidFocus(() => this._terminalEditorFocusContextKey.set(true)),\n", "\t\t\tinstance.onDidBlur(() => this._terminalEditorFocusContextKey.reset()),\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tinstance.onExit((e) => {\n", "\t\t\t\tif (!instance.waitOnExit) {\n", "\t\t\t\t\tthis.dispose();\n", "\t\t\t\t}\n", "\t\t\t}),\n" ], "file_path": "src/vs/workbench/contrib/terminal/browser/terminalEditorInput.ts", "type": "replace", "edit_start_line_idx": 164 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as Async from 'vs/base/common/async'; import { IStringDictionary } from 'vs/base/common/collections'; import { Emitter, Event } from 'vs/base/common/event'; import { isUNC } from 'vs/base/common/extpath'; import { Disposable, DisposableStore } from 'vs/base/common/lifecycle'; import { LinkedMap, Touch } from 'vs/base/common/map'; import * as Objects from 'vs/base/common/objects'; import * as path from 'vs/base/common/path'; import * as Platform from 'vs/base/common/platform'; import * as resources from 'vs/base/common/resources'; import Severity from 'vs/base/common/severity'; import * as Types from 'vs/base/common/types'; import * as nls from 'vs/nls'; import { asArray } from 'vs/base/common/arrays'; import { IModelService } from 'vs/editor/common/services/model'; import { IFileService } from 'vs/platform/files/common/files'; import { IMarkerService, MarkerSeverity } from 'vs/platform/markers/common/markers'; import { IWorkspaceContextService, IWorkspaceFolder, WorkbenchState } from 'vs/platform/workspace/common/workspace'; import { Markers } from 'vs/workbench/contrib/markers/common/markers'; import { ProblemMatcher, ProblemMatcherRegistry /*, ProblemPattern, getResource */ } from 'vs/workbench/contrib/tasks/common/problemMatcher'; import { Codicon } from 'vs/base/common/codicons'; import { Schemas } from 'vs/base/common/network'; import { URI } from 'vs/base/common/uri'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { ILogService } from 'vs/platform/log/common/log'; import { INotificationService } from 'vs/platform/notification/common/notification'; import { IShellLaunchConfig, TerminalLocation, TerminalSettingId, WaitOnExitValue } from 'vs/platform/terminal/common/terminal'; import { formatMessageForTerminal } from 'vs/platform/terminal/common/terminalStrings'; import { ThemeIcon } from 'vs/platform/theme/common/themeService'; import { IViewDescriptorService, IViewsService, ViewContainerLocation } from 'vs/workbench/common/views'; import { TaskTerminalStatus } from 'vs/workbench/contrib/tasks/browser/taskTerminalStatus'; import { ProblemCollectorEventKind, ProblemHandlingStrategy, StartStopProblemCollector, WatchingProblemCollector } from 'vs/workbench/contrib/tasks/common/problemCollectors'; import { GroupKind } from 'vs/workbench/contrib/tasks/common/taskConfiguration'; import { CommandOptions, CommandString, ContributedTask, CustomTask, DependsOrder, ICommandConfiguration, IConfigurationProperties, IExtensionTaskSource, InMemoryTask, IPresentationOptions, IShellConfiguration, IShellQuotingOptions, ITaskEvent, PanelKind, RevealKind, RevealProblemKind, RuntimeType, ShellQuoting, Task, TaskEvent, TaskEventKind, TaskScope, TaskSettingId, TaskSourceKind } from 'vs/workbench/contrib/tasks/common/tasks'; import { ITaskService } from 'vs/workbench/contrib/tasks/common/taskService'; import { IResolvedVariables, IResolveSet, ITaskExecuteResult, ITaskResolver, ITaskSummary, ITaskSystem, ITaskSystemInfo, ITaskSystemInfoResolver, ITaskTerminateResponse, TaskError, TaskErrors, TaskExecuteKind, Triggers } from 'vs/workbench/contrib/tasks/common/taskSystem'; import { ITerminalGroupService, ITerminalInstance, ITerminalService } from 'vs/workbench/contrib/terminal/browser/terminal'; import { VSCodeOscProperty, VSCodeOscPt, VSCodeSequence } from 'vs/workbench/contrib/terminal/browser/terminalEscapeSequences'; import { TerminalProcessExtHostProxy } from 'vs/workbench/contrib/terminal/browser/terminalProcessExtHostProxy'; import { ITerminalProfileResolverService, TERMINAL_VIEW_ID } from 'vs/workbench/contrib/terminal/common/terminal'; import { IConfigurationResolverService } from 'vs/workbench/services/configurationResolver/common/configurationResolver'; import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService'; import { IOutputService } from 'vs/workbench/services/output/common/output'; import { IPaneCompositePartService } from 'vs/workbench/services/panecomposite/browser/panecomposite'; import { IPathService } from 'vs/workbench/services/path/common/pathService'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; interface ITerminalData { terminal: ITerminalInstance; lastTask: string; group?: string; } interface IActiveTerminalData { terminal: ITerminalInstance; task: Task; promise: Promise<ITaskSummary>; state?: TaskEventKind; } interface IReconnectionTaskData { label: string; id: string; lastTask: string; group?: string; } const ReconnectionType = 'Task'; class InstanceManager { private _currentInstances: number = 0; private _counter: number = 0; addInstance() { this._currentInstances++; this._counter++; } removeInstance() { this._currentInstances--; } get instances() { return this._currentInstances; } get counter() { return this._counter; } } class VariableResolver { private static _regex = /\$\{(.*?)\}/g; constructor(public workspaceFolder: IWorkspaceFolder | undefined, public taskSystemInfo: ITaskSystemInfo | undefined, public readonly values: Map<string, string>, private _service: IConfigurationResolverService | undefined) { } async resolve(value: string): Promise<string> { const replacers: Promise<string>[] = []; value.replace(VariableResolver._regex, (match, ...args) => { replacers.push(this._replacer(match, args)); return match; }); const resolvedReplacers = await Promise.all(replacers); return value.replace(VariableResolver._regex, () => resolvedReplacers.shift()!); } private async _replacer(match: string, args: string[]): Promise<string> { // Strip out the ${} because the map contains them variables without those characters. const result = this.values.get(match.substring(2, match.length - 1)); if ((result !== undefined) && (result !== null)) { return result; } if (this._service) { return this._service.resolveAsync(this.workspaceFolder, match); } return match; } } class VerifiedTask { readonly task: Task; readonly resolver: ITaskResolver; readonly trigger: string; resolvedVariables?: IResolvedVariables; systemInfo?: ITaskSystemInfo; workspaceFolder?: IWorkspaceFolder; shellLaunchConfig?: IShellLaunchConfig; constructor(task: Task, resolver: ITaskResolver, trigger: string) { this.task = task; this.resolver = resolver; this.trigger = trigger; } public verify(): boolean { let verified = false; if (this.trigger && this.resolvedVariables && this.workspaceFolder && (this.shellLaunchConfig !== undefined)) { verified = true; } return verified; } public getVerifiedTask(): { task: Task; resolver: ITaskResolver; trigger: string; resolvedVariables: IResolvedVariables; systemInfo: ITaskSystemInfo; workspaceFolder: IWorkspaceFolder; shellLaunchConfig: IShellLaunchConfig } { if (this.verify()) { return { task: this.task, resolver: this.resolver, trigger: this.trigger, resolvedVariables: this.resolvedVariables!, systemInfo: this.systemInfo!, workspaceFolder: this.workspaceFolder!, shellLaunchConfig: this.shellLaunchConfig! }; } else { throw new Error('VerifiedTask was not checked. verify must be checked before getVerifiedTask.'); } } } export class TerminalTaskSystem extends Disposable implements ITaskSystem { public static TelemetryEventName: string = 'taskService'; private static readonly ProcessVarName = '__process__'; private static _shellQuotes: IStringDictionary<IShellQuotingOptions> = { 'cmd': { strong: '"' }, 'powershell': { escape: { escapeChar: '`', charsToEscape: ' "\'()' }, strong: '\'', weak: '"' }, 'bash': { escape: { escapeChar: '\\', charsToEscape: ' "\'' }, strong: '\'', weak: '"' }, 'zsh': { escape: { escapeChar: '\\', charsToEscape: ' "\'' }, strong: '\'', weak: '"' } }; private static _osShellQuotes: IStringDictionary<IShellQuotingOptions> = { 'Linux': TerminalTaskSystem._shellQuotes['bash'], 'Mac': TerminalTaskSystem._shellQuotes['bash'], 'Windows': TerminalTaskSystem._shellQuotes['powershell'] }; private _activeTasks: IStringDictionary<IActiveTerminalData>; private _instances: IStringDictionary<InstanceManager>; private _busyTasks: IStringDictionary<Task>; private _terminals: IStringDictionary<ITerminalData>; private _idleTaskTerminals: LinkedMap<string, string>; private _sameTaskTerminals: IStringDictionary<string>; private _taskSystemInfoResolver: ITaskSystemInfoResolver; private _lastTask: VerifiedTask | undefined; // Should always be set in run private _currentTask!: VerifiedTask; private _isRerun: boolean = false; private _previousPanelId: string | undefined; private _previousTerminalInstance: ITerminalInstance | undefined; private _terminalStatusManager: TaskTerminalStatus; private _terminalCreationQueue: Promise<ITerminalInstance | void> = Promise.resolve(); private _hasReconnected: boolean = false; private readonly _onDidStateChange: Emitter<ITaskEvent>; private _reconnectedTerminals: ITerminalInstance[] | undefined; taskShellIntegrationStartSequence(cwd: string | URI | undefined): string { if (!this._configurationService.getValue(TaskSettingId.ShowDecorations)) { return ''; } return ( VSCodeSequence(VSCodeOscPt.PromptStart) + VSCodeSequence(VSCodeOscPt.Property, `${VSCodeOscProperty.Task}=True`) + (cwd ? VSCodeSequence(VSCodeOscPt.Property, `${VSCodeOscProperty.Cwd}=${typeof cwd === 'string' ? cwd : cwd.fsPath}`) : '' ) + VSCodeSequence(VSCodeOscPt.CommandStart) ); } get taskShellIntegrationOutputSequence(): string { if (!this._configurationService.getValue(TaskSettingId.ShowDecorations)) { return ''; } return VSCodeSequence(VSCodeOscPt.CommandExecuted); } constructor( private _terminalService: ITerminalService, private _terminalGroupService: ITerminalGroupService, private _outputService: IOutputService, private _paneCompositeService: IPaneCompositePartService, private _viewsService: IViewsService, private _markerService: IMarkerService, private _modelService: IModelService, private _configurationResolverService: IConfigurationResolverService, private _contextService: IWorkspaceContextService, private _environmentService: IWorkbenchEnvironmentService, private _outputChannelId: string, private _fileService: IFileService, private _terminalProfileResolverService: ITerminalProfileResolverService, private _pathService: IPathService, private _viewDescriptorService: IViewDescriptorService, private _logService: ILogService, private _configurationService: IConfigurationService, private _notificationService: INotificationService, taskService: ITaskService, instantiationService: IInstantiationService, taskSystemInfoResolver: ITaskSystemInfoResolver, ) { super(); this._activeTasks = Object.create(null); this._instances = Object.create(null); this._busyTasks = Object.create(null); this._terminals = Object.create(null); this._idleTaskTerminals = new LinkedMap<string, string>(); this._sameTaskTerminals = Object.create(null); this._onDidStateChange = new Emitter(); this._taskSystemInfoResolver = taskSystemInfoResolver; this._register(this._terminalStatusManager = instantiationService.createInstance(TaskTerminalStatus)); } public get onDidStateChange(): Event<ITaskEvent> { return this._onDidStateChange.event; } private _log(value: string): void { this._appendOutput(value + '\n'); } protected _showOutput(): void { this._outputService.showChannel(this._outputChannelId, true); } public reconnect(task: Task, resolver: ITaskResolver): ITaskExecuteResult { this._reconnectToTerminals(); return this.run(task, resolver, Triggers.reconnect); } public run(task: Task, resolver: ITaskResolver, trigger: string = Triggers.command): ITaskExecuteResult { task = task.clone(); // A small amount of task state is stored in the task (instance) and tasks passed in to run may have that set already. const recentTaskKey = task.getRecentlyUsedKey() ?? ''; const validInstance = task.runOptions && task.runOptions.instanceLimit && this._instances[recentTaskKey] && this._instances[recentTaskKey].instances < task.runOptions.instanceLimit; const instance = this._instances[recentTaskKey] ? this._instances[recentTaskKey].instances : 0; this._currentTask = new VerifiedTask(task, resolver, trigger); if (instance > 0) { task.instance = this._instances[recentTaskKey].counter; } const lastTaskInstance = this.getLastInstance(task); const terminalData = lastTaskInstance ? this._activeTasks[lastTaskInstance.getMapKey()] : undefined; if (terminalData && terminalData.promise && !validInstance) { this._lastTask = this._currentTask; return { kind: TaskExecuteKind.Active, task: terminalData.task, active: { same: true, background: task.configurationProperties.isBackground! }, promise: terminalData.promise }; } try { const executeResult = { kind: TaskExecuteKind.Started, task, started: {}, promise: this._executeTask(task, resolver, trigger, new Set(), undefined) }; executeResult.promise.then(summary => { this._lastTask = this._currentTask; }); if (InMemoryTask.is(task) || !this._isTaskEmpty(task)) { if (!this._instances[recentTaskKey]) { this._instances[recentTaskKey] = new InstanceManager(); } this._instances[recentTaskKey].addInstance(); } return executeResult; } catch (error) { if (error instanceof TaskError) { throw error; } else if (error instanceof Error) { this._log(error.message); throw new TaskError(Severity.Error, error.message, TaskErrors.UnknownError); } else { this._log(error.toString()); throw new TaskError(Severity.Error, nls.localize('TerminalTaskSystem.unknownError', 'A unknown error has occurred while executing a task. See task output log for details.'), TaskErrors.UnknownError); } } } public rerun(): ITaskExecuteResult | undefined { if (this._lastTask && this._lastTask.verify()) { if ((this._lastTask.task.runOptions.reevaluateOnRerun !== undefined) && !this._lastTask.task.runOptions.reevaluateOnRerun) { this._isRerun = true; } const result = this.run(this._lastTask.task, this._lastTask.resolver); result.promise.then(summary => { this._isRerun = false; }); return result; } else { return undefined; } } private _showTaskLoadErrors(task: Task) { if (task.taskLoadMessages && task.taskLoadMessages.length > 0) { task.taskLoadMessages.forEach(loadMessage => { this._log(loadMessage + '\n'); }); const openOutput = 'Show Output'; this._notificationService.prompt(Severity.Warning, nls.localize('TerminalTaskSystem.taskLoadReporting', "There are issues with task \"{0}\". See the output for more details.", task._label), [{ label: openOutput, run: () => this._showOutput() }]); } } public isTaskVisible(task: Task): boolean { const terminalData = this._activeTasks[task.getMapKey()]; if (!terminalData) { return false; } const activeTerminalInstance = this._terminalService.activeInstance; const isPanelShowingTerminal = !!this._viewsService.getActiveViewWithId(TERMINAL_VIEW_ID); return isPanelShowingTerminal && (activeTerminalInstance?.instanceId === terminalData.terminal.instanceId); } public revealTask(task: Task): boolean { const terminalData = this._activeTasks[task.getMapKey()]; if (!terminalData) { return false; } const isTerminalInPanel: boolean = this._viewDescriptorService.getViewLocationById(TERMINAL_VIEW_ID) === ViewContainerLocation.Panel; if (isTerminalInPanel && this.isTaskVisible(task)) { if (this._previousPanelId) { if (this._previousTerminalInstance) { this._terminalService.setActiveInstance(this._previousTerminalInstance); } this._paneCompositeService.openPaneComposite(this._previousPanelId, ViewContainerLocation.Panel); } else { this._paneCompositeService.hideActivePaneComposite(ViewContainerLocation.Panel); } this._previousPanelId = undefined; this._previousTerminalInstance = undefined; } else { if (isTerminalInPanel) { this._previousPanelId = this._paneCompositeService.getActivePaneComposite(ViewContainerLocation.Panel)?.getId(); if (this._previousPanelId === TERMINAL_VIEW_ID) { this._previousTerminalInstance = this._terminalService.activeInstance ?? undefined; } } this._terminalService.setActiveInstance(terminalData.terminal); if (CustomTask.is(task) || ContributedTask.is(task)) { this._terminalGroupService.showPanel(task.command.presentation!.focus); } } return true; } public isActive(): Promise<boolean> { return Promise.resolve(this.isActiveSync()); } public isActiveSync(): boolean { return Object.keys(this._activeTasks).length > 0; } public canAutoTerminate(): boolean { return Object.keys(this._activeTasks).every(key => !this._activeTasks[key].task.configurationProperties.promptOnClose); } public getActiveTasks(): Task[] { return Object.keys(this._activeTasks).map(key => this._activeTasks[key].task); } public getLastInstance(task: Task): Task | undefined { let lastInstance = undefined; const recentKey = task.getRecentlyUsedKey(); Object.keys(this._activeTasks).forEach((key) => { if (recentKey && recentKey === this._activeTasks[key].task.getRecentlyUsedKey()) { lastInstance = this._activeTasks[key].task; } }); return lastInstance; } public getBusyTasks(): Task[] { return Object.keys(this._busyTasks).map(key => this._busyTasks[key]); } public customExecutionComplete(task: Task, result: number): Promise<void> { const activeTerminal = this._activeTasks[task.getMapKey()]; if (!activeTerminal) { return Promise.reject(new Error('Expected to have a terminal for an custom execution task')); } return new Promise<void>((resolve) => { // activeTerminal.terminal.rendererExit(result); resolve(); }); } private _removeInstances(task: Task) { const recentTaskKey = task.getRecentlyUsedKey() ?? ''; if (this._instances[recentTaskKey]) { this._instances[recentTaskKey].removeInstance(); if (this._instances[recentTaskKey].instances === 0) { delete this._instances[recentTaskKey]; } } } private _removeFromActiveTasks(task: Task | string): void { const key = typeof task === 'string' ? task : task.getMapKey(); if (!this._activeTasks[key]) { return; } const taskToRemove = this._activeTasks[key]; delete this._activeTasks[key]; this._removeInstances(taskToRemove.task); } private _fireTaskEvent(event: ITaskEvent) { if (event.__task) { const activeTask = this._activeTasks[event.__task.getMapKey()]; if (activeTask) { activeTask.state = event.kind; } } this._onDidStateChange.fire(event); } public terminate(task: Task): Promise<ITaskTerminateResponse> { const activeTerminal = this._activeTasks[task.getMapKey()]; if (!activeTerminal) { return Promise.resolve<ITaskTerminateResponse>({ success: false, task: undefined }); } return new Promise<ITaskTerminateResponse>((resolve, reject) => { const terminal = activeTerminal.terminal; terminal.onDisposed(terminal => { this._fireTaskEvent(TaskEvent.create(TaskEventKind.Terminated, task, terminal.instanceId, terminal.exitReason)); }); const onExit = terminal.onExit(() => { const task = activeTerminal.task; try { onExit.dispose(); this._fireTaskEvent(TaskEvent.create(TaskEventKind.Terminated, task, terminal.instanceId, terminal.exitReason)); } catch (error) { // Do nothing. } resolve({ success: true, task: task }); }); terminal.dispose(); }); } public terminateAll(): Promise<ITaskTerminateResponse[]> { const promises: Promise<ITaskTerminateResponse>[] = []; Object.keys(this._activeTasks).forEach((key) => { const terminalData = this._activeTasks[key]; const terminal = terminalData.terminal; promises.push(new Promise<ITaskTerminateResponse>((resolve, reject) => { const onExit = terminal.onExit(() => { const task = terminalData.task; try { onExit.dispose(); this._fireTaskEvent(TaskEvent.create(TaskEventKind.Terminated, task, terminal.instanceId, terminal.exitReason)); } catch (error) { // Do nothing. } resolve({ success: true, task: terminalData.task }); }); })); terminal.dispose(); }); this._activeTasks = Object.create(null); return Promise.all<ITaskTerminateResponse>(promises); } private _showDependencyCycleMessage(task: Task) { this._log(nls.localize('dependencyCycle', 'There is a dependency cycle. See task "{0}".', task._label )); this._showOutput(); } private async _executeTask(task: Task, resolver: ITaskResolver, trigger: string, encounteredDependencies: Set<string>, alreadyResolved?: Map<string, string>): Promise<ITaskSummary> { if (encounteredDependencies.has(task.getCommonTaskId())) { this._showDependencyCycleMessage(task); return {}; } this._showTaskLoadErrors(task); alreadyResolved = alreadyResolved ?? new Map<string, string>(); const promises: Promise<ITaskSummary>[] = []; if (task.configurationProperties.dependsOn) { for (const dependency of task.configurationProperties.dependsOn) { const dependencyTask = await resolver.resolve(dependency.uri, dependency.task!); if (dependencyTask) { this._adoptConfigurationForDependencyTask(dependencyTask, task); const key = dependencyTask.getMapKey(); let promise = this._activeTasks[key] ? this._getDependencyPromise(this._activeTasks[key]) : undefined; if (!promise) { this._fireTaskEvent(TaskEvent.create(TaskEventKind.DependsOnStarted, task)); encounteredDependencies.add(task.getCommonTaskId()); promise = this._executeDependencyTask(dependencyTask, resolver, trigger, encounteredDependencies, alreadyResolved); } promises.push(promise); if (task.configurationProperties.dependsOrder === DependsOrder.sequence) { const promiseResult = await promise; if (promiseResult.exitCode === 0) { promise = Promise.resolve(promiseResult); } else { promise = Promise.reject(promiseResult); break; } } promises.push(promise); } else { this._log(nls.localize('dependencyFailed', 'Couldn\'t resolve dependent task \'{0}\' in workspace folder \'{1}\'', Types.isString(dependency.task) ? dependency.task : JSON.stringify(dependency.task, undefined, 0), dependency.uri.toString() )); this._showOutput(); } } } if ((ContributedTask.is(task) || CustomTask.is(task)) && (task.command)) { return Promise.all(promises).then((summaries): Promise<ITaskSummary> | ITaskSummary => { encounteredDependencies.delete(task.getCommonTaskId()); for (const summary of summaries) { if (summary.exitCode !== 0) { this._removeInstances(task); return { exitCode: summary.exitCode }; } } if (this._isRerun) { return this._reexecuteCommand(task, trigger, alreadyResolved!); } else { return this._executeCommand(task, trigger, alreadyResolved!); } }); } else { return Promise.all(promises).then((summaries): ITaskSummary => { encounteredDependencies.delete(task.getCommonTaskId()); for (const summary of summaries) { if (summary.exitCode !== 0) { return { exitCode: summary.exitCode }; } } return { exitCode: 0 }; }); } } private _createInactiveDependencyPromise(task: Task): Promise<ITaskSummary> { return new Promise<ITaskSummary>(resolve => { const taskInactiveDisposable = this.onDidStateChange(taskEvent => { if ((taskEvent.kind === TaskEventKind.Inactive) && (taskEvent.__task === task)) { taskInactiveDisposable.dispose(); resolve({ exitCode: 0 }); } }); }); } private _adoptConfigurationForDependencyTask(dependencyTask: Task, task: Task): void { if (dependencyTask.configurationProperties.icon) { dependencyTask.configurationProperties.icon.id ||= task.configurationProperties.icon?.id; dependencyTask.configurationProperties.icon.color ||= task.configurationProperties.icon?.color; } else { dependencyTask.configurationProperties.icon = task.configurationProperties.icon; } if (dependencyTask.configurationProperties.hide) { dependencyTask.configurationProperties.hide ||= task.configurationProperties.hide; } else { dependencyTask.configurationProperties.hide = task.configurationProperties.hide; } } private async _getDependencyPromise(task: IActiveTerminalData): Promise<ITaskSummary> { if (!task.task.configurationProperties.isBackground) { return task.promise; } if (!task.task.configurationProperties.problemMatchers || task.task.configurationProperties.problemMatchers.length === 0) { return task.promise; } if (task.state === TaskEventKind.Inactive) { return { exitCode: 0 }; } return this._createInactiveDependencyPromise(task.task); } private async _executeDependencyTask(task: Task, resolver: ITaskResolver, trigger: string, encounteredDependencies: Set<string>, alreadyResolved?: Map<string, string>): Promise<ITaskSummary> { // If the task is a background task with a watching problem matcher, we don't wait for the whole task to finish, // just for the problem matcher to go inactive. if (!task.configurationProperties.isBackground) { return this._executeTask(task, resolver, trigger, encounteredDependencies, alreadyResolved); } const inactivePromise = this._createInactiveDependencyPromise(task); return Promise.race([inactivePromise, this._executeTask(task, resolver, trigger, encounteredDependencies, alreadyResolved)]); } private async _resolveAndFindExecutable(systemInfo: ITaskSystemInfo | undefined, workspaceFolder: IWorkspaceFolder | undefined, task: CustomTask | ContributedTask, cwd: string | undefined, envPath: string | undefined): Promise<string> { const command = await this._configurationResolverService.resolveAsync(workspaceFolder, CommandString.value(task.command.name!)); cwd = cwd ? await this._configurationResolverService.resolveAsync(workspaceFolder, cwd) : undefined; const paths = envPath ? await Promise.all(envPath.split(path.delimiter).map(p => this._configurationResolverService.resolveAsync(workspaceFolder, p))) : undefined; let foundExecutable = await systemInfo?.findExecutable(command, cwd, paths); if (!foundExecutable) { foundExecutable = path.join(cwd ?? '', command); } return foundExecutable; } private _findUnresolvedVariables(variables: Set<string>, alreadyResolved: Map<string, string>): Set<string> { if (alreadyResolved.size === 0) { return variables; } const unresolved = new Set<string>(); for (const variable of variables) { if (!alreadyResolved.has(variable.substring(2, variable.length - 1))) { unresolved.add(variable); } } return unresolved; } private _mergeMaps(mergeInto: Map<string, string>, mergeFrom: Map<string, string>) { for (const entry of mergeFrom) { if (!mergeInto.has(entry[0])) { mergeInto.set(entry[0], entry[1]); } } } private async _acquireInput(taskSystemInfo: ITaskSystemInfo | undefined, workspaceFolder: IWorkspaceFolder | undefined, task: CustomTask | ContributedTask, variables: Set<string>, alreadyResolved: Map<string, string>): Promise<IResolvedVariables | undefined> { const resolved = await this._resolveVariablesFromSet(taskSystemInfo, workspaceFolder, task, variables, alreadyResolved); this._fireTaskEvent(TaskEvent.create(TaskEventKind.AcquiredInput, task)); return resolved; } private _resolveVariablesFromSet(taskSystemInfo: ITaskSystemInfo | undefined, workspaceFolder: IWorkspaceFolder | undefined, task: CustomTask | ContributedTask, variables: Set<string>, alreadyResolved: Map<string, string>): Promise<IResolvedVariables | undefined> { const isProcess = task.command && task.command.runtime === RuntimeType.Process; const options = task.command && task.command.options ? task.command.options : undefined; const cwd = options ? options.cwd : undefined; let envPath: string | undefined = undefined; if (options && options.env) { for (const key of Object.keys(options.env)) { if (key.toLowerCase() === 'path') { if (Types.isString(options.env[key])) { envPath = options.env[key]; } break; } } } const unresolved = this._findUnresolvedVariables(variables, alreadyResolved); let resolvedVariables: Promise<IResolvedVariables | undefined>; if (taskSystemInfo && workspaceFolder) { const resolveSet: IResolveSet = { variables: unresolved }; if (taskSystemInfo.platform === Platform.Platform.Windows && isProcess) { resolveSet.process = { name: CommandString.value(task.command.name!) }; if (cwd) { resolveSet.process.cwd = cwd; } if (envPath) { resolveSet.process.path = envPath; } } resolvedVariables = taskSystemInfo.resolveVariables(workspaceFolder, resolveSet, TaskSourceKind.toConfigurationTarget(task._source.kind)).then(async (resolved) => { if (!resolved) { return undefined; } this._mergeMaps(alreadyResolved, resolved.variables); resolved.variables = new Map(alreadyResolved); if (isProcess) { let process = CommandString.value(task.command.name!); if (taskSystemInfo.platform === Platform.Platform.Windows) { process = await this._resolveAndFindExecutable(taskSystemInfo, workspaceFolder, task, cwd, envPath); } resolved.variables.set(TerminalTaskSystem.ProcessVarName, process); } return resolved; }); return resolvedVariables; } else { const variablesArray = new Array<string>(); unresolved.forEach(variable => variablesArray.push(variable)); return new Promise<IResolvedVariables | undefined>((resolve, reject) => { this._configurationResolverService.resolveWithInteraction(workspaceFolder, variablesArray, 'tasks', undefined, TaskSourceKind.toConfigurationTarget(task._source.kind)).then(async (resolvedVariablesMap: Map<string, string> | undefined) => { if (resolvedVariablesMap) { this._mergeMaps(alreadyResolved, resolvedVariablesMap); resolvedVariablesMap = new Map(alreadyResolved); if (isProcess) { let processVarValue: string; if (Platform.isWindows) { processVarValue = await this._resolveAndFindExecutable(taskSystemInfo, workspaceFolder, task, cwd, envPath); } else { processVarValue = await this._configurationResolverService.resolveAsync(workspaceFolder, CommandString.value(task.command.name!)); } resolvedVariablesMap.set(TerminalTaskSystem.ProcessVarName, processVarValue); } const resolvedVariablesResult: IResolvedVariables = { variables: resolvedVariablesMap, }; resolve(resolvedVariablesResult); } else { resolve(undefined); } }, reason => { reject(reason); }); }); } } private _executeCommand(task: CustomTask | ContributedTask, trigger: string, alreadyResolved: Map<string, string>): Promise<ITaskSummary> { const taskWorkspaceFolder = task.getWorkspaceFolder(); let workspaceFolder: IWorkspaceFolder | undefined; if (taskWorkspaceFolder) { workspaceFolder = this._currentTask.workspaceFolder = taskWorkspaceFolder; } else { const folders = this._contextService.getWorkspace().folders; workspaceFolder = folders.length > 0 ? folders[0] : undefined; } const systemInfo: ITaskSystemInfo | undefined = this._currentTask.systemInfo = this._taskSystemInfoResolver(workspaceFolder); const variables = new Set<string>(); this._collectTaskVariables(variables, task); const resolvedVariables = this._acquireInput(systemInfo, workspaceFolder, task, variables, alreadyResolved); return resolvedVariables.then((resolvedVariables) => { if (resolvedVariables && !this._isTaskEmpty(task)) { this._currentTask.resolvedVariables = resolvedVariables; return this._executeInTerminal(task, trigger, new VariableResolver(workspaceFolder, systemInfo, resolvedVariables.variables, this._configurationResolverService), workspaceFolder); } else { // Allows the taskExecutions array to be updated in the extension host this._fireTaskEvent(TaskEvent.create(TaskEventKind.End, task)); return Promise.resolve({ exitCode: 0 }); } }, reason => { return Promise.reject(reason); }); } private _isTaskEmpty(task: CustomTask | ContributedTask): boolean { const isCustomExecution = (task.command.runtime === RuntimeType.CustomExecution); return !((task.command !== undefined) && task.command.runtime && (isCustomExecution || (task.command.name !== undefined))); } private _reexecuteCommand(task: CustomTask | ContributedTask, trigger: string, alreadyResolved: Map<string, string>): Promise<ITaskSummary> { const lastTask = this._lastTask; if (!lastTask) { return Promise.reject(new Error('No task previously run')); } const workspaceFolder = this._currentTask.workspaceFolder = lastTask.workspaceFolder; const variables = new Set<string>(); this._collectTaskVariables(variables, task); // Check that the task hasn't changed to include new variables let hasAllVariables = true; variables.forEach(value => { if (value.substring(2, value.length - 1) in lastTask.getVerifiedTask().resolvedVariables) { hasAllVariables = false; } }); if (!hasAllVariables) { return this._acquireInput(lastTask.getVerifiedTask().systemInfo, lastTask.getVerifiedTask().workspaceFolder, task, variables, alreadyResolved).then((resolvedVariables) => { if (!resolvedVariables) { // Allows the taskExecutions array to be updated in the extension host this._fireTaskEvent(TaskEvent.create(TaskEventKind.End, task)); return { exitCode: 0 }; } this._currentTask.resolvedVariables = resolvedVariables; return this._executeInTerminal(task, trigger, new VariableResolver(lastTask.getVerifiedTask().workspaceFolder, lastTask.getVerifiedTask().systemInfo, resolvedVariables.variables, this._configurationResolverService), workspaceFolder!); }, reason => { return Promise.reject(reason); }); } else { this._currentTask.resolvedVariables = lastTask.getVerifiedTask().resolvedVariables; return this._executeInTerminal(task, trigger, new VariableResolver(lastTask.getVerifiedTask().workspaceFolder, lastTask.getVerifiedTask().systemInfo, lastTask.getVerifiedTask().resolvedVariables.variables, this._configurationResolverService), workspaceFolder!); } } private async _executeInTerminal(task: CustomTask | ContributedTask, trigger: string, resolver: VariableResolver, workspaceFolder: IWorkspaceFolder | undefined): Promise<ITaskSummary> { let terminal: ITerminalInstance | undefined = undefined; let error: TaskError | undefined = undefined; let promise: Promise<ITaskSummary> | undefined = undefined; if (task.configurationProperties.isBackground) { const problemMatchers = await this._resolveMatchers(resolver, task.configurationProperties.problemMatchers); const watchingProblemMatcher = new WatchingProblemCollector(problemMatchers, this._markerService, this._modelService, this._fileService); if ((problemMatchers.length > 0) && !watchingProblemMatcher.isWatching()) { this._appendOutput(nls.localize('TerminalTaskSystem.nonWatchingMatcher', 'Task {0} is a background task but uses a problem matcher without a background pattern', task._label)); this._showOutput(); } const toDispose = new DisposableStore(); let eventCounter: number = 0; const mapKey = task.getMapKey(); toDispose.add(watchingProblemMatcher.onDidStateChange((event) => { if (event.kind === ProblemCollectorEventKind.BackgroundProcessingBegins) { eventCounter++; this._busyTasks[mapKey] = task; this._fireTaskEvent(TaskEvent.create(TaskEventKind.Active, task, terminal?.instanceId)); } else if (event.kind === ProblemCollectorEventKind.BackgroundProcessingEnds) { eventCounter--; if (this._busyTasks[mapKey]) { delete this._busyTasks[mapKey]; } this._fireTaskEvent(TaskEvent.create(TaskEventKind.Inactive, task, terminal?.instanceId)); if (eventCounter === 0) { if ((watchingProblemMatcher.numberOfMatches > 0) && watchingProblemMatcher.maxMarkerSeverity && (watchingProblemMatcher.maxMarkerSeverity >= MarkerSeverity.Error)) { const reveal = task.command.presentation!.reveal; const revealProblems = task.command.presentation!.revealProblems; if (revealProblems === RevealProblemKind.OnProblem) { this._viewsService.openView(Markers.MARKERS_VIEW_ID, true); } else if (reveal === RevealKind.Silent) { this._terminalService.setActiveInstance(terminal!); this._terminalGroupService.showPanel(false); } } } } })); watchingProblemMatcher.aboutToStart(); let delayer: Async.Delayer<any> | undefined = undefined; [terminal, error] = await this._createTerminal(task, resolver, workspaceFolder); if (error) { return Promise.reject(new Error((<TaskError>error).message)); } if (!terminal) { return Promise.reject(new Error(`Failed to create terminal for task ${task._label}`)); } this._terminalStatusManager.addTerminal(task, terminal, watchingProblemMatcher); let processStartedSignaled = false; terminal.processReady.then(() => { if (!processStartedSignaled) { this._fireTaskEvent(TaskEvent.create(TaskEventKind.ProcessStarted, task, terminal!.instanceId, terminal!.processId!)); processStartedSignaled = true; } }, (_error) => { this._logService.error('Task terminal process never got ready'); }); this._fireTaskEvent(TaskEvent.create(TaskEventKind.Start, task, terminal.instanceId, resolver.values)); const onData = terminal.onLineData((line) => { watchingProblemMatcher.processLine(line); if (!delayer) { delayer = new Async.Delayer(3000); } delayer.trigger(() => { watchingProblemMatcher.forceDelivery(); delayer = undefined; }); }); promise = new Promise<ITaskSummary>((resolve, reject) => { const onExit = terminal!.onExit((terminalLaunchResult) => { const exitCode = typeof terminalLaunchResult === 'number' ? terminalLaunchResult : terminalLaunchResult?.code; onData.dispose(); onExit.dispose(); const key = task.getMapKey(); if (this._busyTasks[mapKey]) { delete this._busyTasks[mapKey]; } this._removeFromActiveTasks(task); this._fireTaskEvent(TaskEvent.create(TaskEventKind.Changed)); if (terminalLaunchResult !== undefined) { // Only keep a reference to the terminal if it is not being disposed. switch (task.command.presentation!.panel) { case PanelKind.Dedicated: this._sameTaskTerminals[key] = terminal!.instanceId.toString(); break; case PanelKind.Shared: this._idleTaskTerminals.set(key, terminal!.instanceId.toString(), Touch.AsOld); break; } } const reveal = task.command.presentation!.reveal; if ((reveal === RevealKind.Silent) && ((exitCode !== 0) || (watchingProblemMatcher.numberOfMatches > 0) && watchingProblemMatcher.maxMarkerSeverity && (watchingProblemMatcher.maxMarkerSeverity >= MarkerSeverity.Error))) { try { this._terminalService.setActiveInstance(terminal!); this._terminalGroupService.showPanel(false); } catch (e) { // If the terminal has already been disposed, then setting the active instance will fail. #99828 // There is nothing else to do here. } } watchingProblemMatcher.done(); watchingProblemMatcher.dispose(); if (!processStartedSignaled) { this._fireTaskEvent(TaskEvent.create(TaskEventKind.ProcessStarted, task, terminal!.instanceId, terminal!.processId!)); processStartedSignaled = true; } this._fireTaskEvent(TaskEvent.create(TaskEventKind.ProcessEnded, task, terminal!.instanceId, exitCode)); for (let i = 0; i < eventCounter; i++) { this._fireTaskEvent(TaskEvent.create(TaskEventKind.Inactive, task, terminal!.instanceId)); } eventCounter = 0; this._fireTaskEvent(TaskEvent.create(TaskEventKind.End, task)); toDispose.dispose(); resolve({ exitCode: exitCode ?? undefined }); }); }); if (trigger === Triggers.reconnect && !!terminal.xterm) { const bufferLines = []; const bufferReverseIterator = terminal.xterm.getBufferReverseIterator(); const startRegex = new RegExp(watchingProblemMatcher.beginPatterns.map(pattern => pattern.source).join('|')); for (const nextLine of bufferReverseIterator) { bufferLines.push(nextLine); if (startRegex.test(nextLine)) { break; } } for (let i = bufferLines.length - 1; i >= 0; i--) { watchingProblemMatcher.processLine(bufferLines[i]); } } } else { [terminal, error] = await this._createTerminal(task, resolver, workspaceFolder); if (error) { return Promise.reject(new Error((<TaskError>error).message)); } if (!terminal) { return Promise.reject(new Error(`Failed to create terminal for task ${task._label}`)); } let processStartedSignaled = false; terminal.processReady.then(() => { if (!processStartedSignaled) { this._fireTaskEvent(TaskEvent.create(TaskEventKind.ProcessStarted, task, terminal!.instanceId, terminal!.processId!)); processStartedSignaled = true; } }, (_error) => { // The process never got ready. Need to think how to handle this. }); this._fireTaskEvent(TaskEvent.create(TaskEventKind.Start, task, terminal.instanceId, resolver.values)); const mapKey = task.getMapKey(); this._busyTasks[mapKey] = task; this._fireTaskEvent(TaskEvent.create(TaskEventKind.Active, task, terminal.instanceId)); const problemMatchers = await this._resolveMatchers(resolver, task.configurationProperties.problemMatchers); const startStopProblemMatcher = new StartStopProblemCollector(problemMatchers, this._markerService, this._modelService, ProblemHandlingStrategy.Clean, this._fileService); this._terminalStatusManager.addTerminal(task, terminal, startStopProblemMatcher); const onData = terminal.onLineData((line) => { startStopProblemMatcher.processLine(line); }); promise = new Promise<ITaskSummary>((resolve, reject) => { const onExit = terminal!.onExit((terminalLaunchResult) => { const exitCode = typeof terminalLaunchResult === 'number' ? terminalLaunchResult : terminalLaunchResult?.code; onExit.dispose(); const key = task.getMapKey(); this._removeFromActiveTasks(task); this._fireTaskEvent(TaskEvent.create(TaskEventKind.Changed)); if (terminalLaunchResult !== undefined) { // Only keep a reference to the terminal if it is not being disposed. switch (task.command.presentation!.panel) { case PanelKind.Dedicated: this._sameTaskTerminals[key] = terminal!.instanceId.toString(); break; case PanelKind.Shared: this._idleTaskTerminals.set(key, terminal!.instanceId.toString(), Touch.AsOld); break; } } const reveal = task.command.presentation!.reveal; const revealProblems = task.command.presentation!.revealProblems; const revealProblemPanel = terminal && (revealProblems === RevealProblemKind.OnProblem) && (startStopProblemMatcher.numberOfMatches > 0); if (revealProblemPanel) { this._viewsService.openView(Markers.MARKERS_VIEW_ID); } else if (terminal && (reveal === RevealKind.Silent) && ((exitCode !== 0) || (startStopProblemMatcher.numberOfMatches > 0) && startStopProblemMatcher.maxMarkerSeverity && (startStopProblemMatcher.maxMarkerSeverity >= MarkerSeverity.Error))) { try { this._terminalService.setActiveInstance(terminal); this._terminalGroupService.showPanel(false); } catch (e) { // If the terminal has already been disposed, then setting the active instance will fail. #99828 // There is nothing else to do here. } } // Hack to work around #92868 until terminal is fixed. setTimeout(() => { onData.dispose(); startStopProblemMatcher.done(); startStopProblemMatcher.dispose(); }, 100); if (!processStartedSignaled && terminal) { this._fireTaskEvent(TaskEvent.create(TaskEventKind.ProcessStarted, task, terminal.instanceId, terminal.processId!)); processStartedSignaled = true; } this._fireTaskEvent(TaskEvent.create(TaskEventKind.ProcessEnded, task, terminal?.instanceId, exitCode ?? undefined)); if (this._busyTasks[mapKey]) { delete this._busyTasks[mapKey]; } this._fireTaskEvent(TaskEvent.create(TaskEventKind.Inactive, task, terminal?.instanceId)); this._fireTaskEvent(TaskEvent.create(TaskEventKind.End, task, terminal?.instanceId)); resolve({ exitCode: exitCode ?? undefined }); }); }); } const showProblemPanel = task.command.presentation && (task.command.presentation.revealProblems === RevealProblemKind.Always); if (showProblemPanel) { this._viewsService.openView(Markers.MARKERS_VIEW_ID); } else if (task.command.presentation && (task.command.presentation.reveal === RevealKind.Always)) { this._terminalService.setActiveInstance(terminal); this._terminalGroupService.showPanel(task.command.presentation.focus); } this._activeTasks[task.getMapKey()] = { terminal, task, promise }; this._fireTaskEvent(TaskEvent.create(TaskEventKind.Changed)); return promise; } private _createTerminalName(task: CustomTask | ContributedTask): string { const needsFolderQualification = this._contextService.getWorkbenchState() === WorkbenchState.WORKSPACE; return needsFolderQualification ? task.getQualifiedLabel() : (task.configurationProperties.name || ''); } private async _createShellLaunchConfig(task: CustomTask | ContributedTask, workspaceFolder: IWorkspaceFolder | undefined, variableResolver: VariableResolver, platform: Platform.Platform, options: CommandOptions, command: CommandString, args: CommandString[], waitOnExit: WaitOnExitValue): Promise<IShellLaunchConfig | undefined> { let shellLaunchConfig: IShellLaunchConfig; const isShellCommand = task.command.runtime === RuntimeType.Shell; const needsFolderQualification = this._contextService.getWorkbenchState() === WorkbenchState.WORKSPACE; const terminalName = this._createTerminalName(task); const type = ReconnectionType; const originalCommand = task.command.name; let cwd: string | URI | undefined; if (options.cwd) { cwd = options.cwd; if (!path.isAbsolute(cwd)) { if (workspaceFolder && (workspaceFolder.uri.scheme === Schemas.file)) { cwd = path.join(workspaceFolder.uri.fsPath, cwd); } } // This must be normalized to the OS cwd = isUNC(cwd) ? cwd : resources.toLocalResource(URI.from({ scheme: Schemas.file, path: cwd }), this._environmentService.remoteAuthority, this._pathService.defaultUriScheme); } if (isShellCommand) { let os: Platform.OperatingSystem; switch (platform) { case Platform.Platform.Windows: os = Platform.OperatingSystem.Windows; break; case Platform.Platform.Mac: os = Platform.OperatingSystem.Macintosh; break; case Platform.Platform.Linux: default: os = Platform.OperatingSystem.Linux; break; } const defaultProfile = await this._terminalProfileResolverService.getDefaultProfile({ allowAutomationShell: true, os, remoteAuthority: this._environmentService.remoteAuthority }); let icon: URI | ThemeIcon | { light: URI; dark: URI } | undefined; if (task.configurationProperties.icon?.id) { icon = ThemeIcon.fromId(task.configurationProperties.icon.id); } else { const taskGroupKind = task.configurationProperties.group ? GroupKind.to(task.configurationProperties.group) : undefined; const kindId = typeof taskGroupKind === 'string' ? taskGroupKind : taskGroupKind?.kind; icon = kindId === 'test' ? ThemeIcon.fromId(Codicon.beaker.id) : defaultProfile.icon; } shellLaunchConfig = { name: terminalName, type, executable: defaultProfile.path, args: defaultProfile.args, env: { ...defaultProfile.env }, icon, color: task.configurationProperties.icon?.color || undefined, waitOnExit }; let shellSpecified: boolean = false; const shellOptions: IShellConfiguration | undefined = task.command.options && task.command.options.shell; if (shellOptions) { if (shellOptions.executable) { // Clear out the args so that we don't end up with mismatched args. if (shellOptions.executable !== shellLaunchConfig.executable) { shellLaunchConfig.args = undefined; } shellLaunchConfig.executable = await this._resolveVariable(variableResolver, shellOptions.executable); shellSpecified = true; } if (shellOptions.args) { shellLaunchConfig.args = await this._resolveVariables(variableResolver, shellOptions.args.slice()); } } if (shellLaunchConfig.args === undefined) { shellLaunchConfig.args = []; } const shellArgs = Array.isArray(shellLaunchConfig.args!) ? <string[]>shellLaunchConfig.args!.slice(0) : [shellLaunchConfig.args!]; const toAdd: string[] = []; const basename = path.posix.basename((await this._pathService.fileURI(shellLaunchConfig.executable!)).path).toLowerCase(); const commandLine = this._buildShellCommandLine(platform, basename, shellOptions, command, originalCommand, args); let windowsShellArgs: boolean = false; if (platform === Platform.Platform.Windows) { windowsShellArgs = true; // If we don't have a cwd, then the terminal uses the home dir. const userHome = await this._pathService.userHome(); if (basename === 'cmd.exe' && ((options.cwd && isUNC(options.cwd)) || (!options.cwd && isUNC(userHome.fsPath)))) { return undefined; } if ((basename === 'powershell.exe') || (basename === 'pwsh.exe')) { if (!shellSpecified) { toAdd.push('-Command'); } } else if ((basename === 'bash.exe') || (basename === 'zsh.exe')) { windowsShellArgs = false; if (!shellSpecified) { toAdd.push('-c'); } } else if (basename === 'wsl.exe') { if (!shellSpecified) { toAdd.push('-e'); } } else { if (!shellSpecified) { toAdd.push('/d', '/c'); } } } else { if (!shellSpecified) { // Under Mac remove -l to not start it as a login shell. if (platform === Platform.Platform.Mac) { // Background on -l on osx https://github.com/microsoft/vscode/issues/107563 const osxShellArgs = this._configurationService.inspect(TerminalSettingId.ShellArgsMacOs); if ((osxShellArgs.user === undefined) && (osxShellArgs.userLocal === undefined) && (osxShellArgs.userLocalValue === undefined) && (osxShellArgs.userRemote === undefined) && (osxShellArgs.userRemoteValue === undefined) && (osxShellArgs.userValue === undefined) && (osxShellArgs.workspace === undefined) && (osxShellArgs.workspaceFolder === undefined) && (osxShellArgs.workspaceFolderValue === undefined) && (osxShellArgs.workspaceValue === undefined)) { const index = shellArgs.indexOf('-l'); if (index !== -1) { shellArgs.splice(index, 1); } } } toAdd.push('-c'); } } const combinedShellArgs = this._addAllArgument(toAdd, shellArgs); combinedShellArgs.push(commandLine); shellLaunchConfig.args = windowsShellArgs ? combinedShellArgs.join(' ') : combinedShellArgs; if (task.command.presentation && task.command.presentation.echo) { if (needsFolderQualification && workspaceFolder) { shellLaunchConfig.initialText = this.taskShellIntegrationStartSequence(cwd) + formatMessageForTerminal(nls.localize({ key: 'task.executingInFolder', comment: ['The workspace folder the task is running in', 'The task command line or label'] }, 'Executing task in folder {0}: {1}', workspaceFolder.name, commandLine), { excludeLeadingNewLine: true }) + this.taskShellIntegrationOutputSequence; } else { shellLaunchConfig.initialText = this.taskShellIntegrationStartSequence(cwd) + formatMessageForTerminal(nls.localize({ key: 'task.executing.shellIntegration', comment: ['The task command line or label'] }, 'Executing task: {0}', commandLine), { excludeLeadingNewLine: true }) + this.taskShellIntegrationOutputSequence; } } else { shellLaunchConfig.initialText = { text: this.taskShellIntegrationStartSequence(cwd) + this.taskShellIntegrationOutputSequence, trailingNewLine: false }; } } else { const commandExecutable = (task.command.runtime !== RuntimeType.CustomExecution) ? CommandString.value(command) : undefined; const executable = !isShellCommand ? await this._resolveVariable(variableResolver, await this._resolveVariable(variableResolver, '${' + TerminalTaskSystem.ProcessVarName + '}')) : commandExecutable; // When we have a process task there is no need to quote arguments. So we go ahead and take the string value. shellLaunchConfig = { name: terminalName, type, icon: task.configurationProperties.icon?.id ? ThemeIcon.fromId(task.configurationProperties.icon.id) : undefined, color: task.configurationProperties.icon?.color || undefined, executable: executable, args: args.map(a => Types.isString(a) ? a : a.value), waitOnExit }; if (task.command.presentation && task.command.presentation.echo) { const getArgsToEcho = (args: string | string[] | undefined): string => { if (!args || args.length === 0) { return ''; } if (Types.isString(args)) { return args; } return args.join(' '); }; if (needsFolderQualification && workspaceFolder) { shellLaunchConfig.initialText = this.taskShellIntegrationStartSequence(cwd) + formatMessageForTerminal(nls.localize({ key: 'task.executingInFolder', comment: ['The workspace folder the task is running in', 'The task command line or label'] }, 'Executing task in folder {0}: {1}', workspaceFolder.name, `${shellLaunchConfig.executable} ${getArgsToEcho(shellLaunchConfig.args)}`), { excludeLeadingNewLine: true }) + this.taskShellIntegrationOutputSequence; } else { shellLaunchConfig.initialText = this.taskShellIntegrationStartSequence(cwd) + formatMessageForTerminal(nls.localize({ key: 'task.executing.shell-integration', comment: ['The task command line or label'] }, 'Executing task: {0}', `${shellLaunchConfig.executable} ${getArgsToEcho(shellLaunchConfig.args)}`), { excludeLeadingNewLine: true }) + this.taskShellIntegrationOutputSequence; } } else { shellLaunchConfig.initialText = { text: this.taskShellIntegrationStartSequence(cwd) + this.taskShellIntegrationOutputSequence, trailingNewLine: false }; } } if (cwd) { shellLaunchConfig.cwd = cwd; } if (options.env) { if (shellLaunchConfig.env) { shellLaunchConfig.env = { ...shellLaunchConfig.env, ...options.env }; } else { shellLaunchConfig.env = options.env; } } shellLaunchConfig.isFeatureTerminal = true; shellLaunchConfig.useShellEnvironment = true; return shellLaunchConfig; } private _addAllArgument(shellCommandArgs: string[], configuredShellArgs: string[]): string[] { const combinedShellArgs: string[] = Objects.deepClone(configuredShellArgs); shellCommandArgs.forEach(element => { const shouldAddShellCommandArg = configuredShellArgs.every((arg, index) => { if ((arg.toLowerCase() === element) && (configuredShellArgs.length > index + 1)) { // We can still add the argument, but only if not all of the following arguments begin with "-". return !configuredShellArgs.slice(index + 1).every(testArg => testArg.startsWith('-')); } else { return arg.toLowerCase() !== element; } }); if (shouldAddShellCommandArg) { combinedShellArgs.push(element); } }); return combinedShellArgs; } private async _reconnectToTerminal(task: Task): Promise<ITerminalInstance | undefined> { if (!this._reconnectedTerminals) { return; } for (let i = 0; i < this._reconnectedTerminals.length; i++) { const terminal = this._reconnectedTerminals[i]; const taskForTerminal = terminal.shellLaunchConfig.attachPersistentProcess?.reconnectionProperties?.data as IReconnectionTaskData; if (taskForTerminal.lastTask === task.getCommonTaskId()) { this._reconnectedTerminals.splice(i, 1); return terminal; } } return undefined; } private async _doCreateTerminal(task: Task, group: string | undefined, launchConfigs: IShellLaunchConfig): Promise<ITerminalInstance> { const reconnectedTerminal = await this._reconnectToTerminal(task); if (reconnectedTerminal) { if ('command' in task && task.command.presentation) { reconnectedTerminal.waitOnExit = getWaitOnExitValue(task.command.presentation, task.configurationProperties); } reconnectedTerminal.onDisposed((terminal) => this._fireTaskEvent({ kind: TaskEventKind.Terminated, exitReason: terminal.exitReason, taskId: task.getRecentlyUsedKey() })); this._logService.trace('reconnected to task and terminal', task._id); return reconnectedTerminal; } if (group) { // Try to find an existing terminal to split. // Even if an existing terminal is found, the split can fail if the terminal width is too small. for (const terminal of Object.values(this._terminals)) { if (terminal.group === group) { this._logService.trace(`Found terminal to split for group ${group}`); const originalInstance = terminal.terminal; const result = await this._terminalService.createTerminal({ location: { parentTerminal: originalInstance }, config: launchConfigs }); result.onDisposed((terminal) => this._fireTaskEvent({ kind: TaskEventKind.Terminated, exitReason: terminal.exitReason, taskId: task.getRecentlyUsedKey() })); if (result) { return result; } } } this._logService.trace(`No terminal found to split for group ${group}`); } // Either no group is used, no terminal with the group exists or splitting an existing terminal failed. const createdTerminal = await this._terminalService.createTerminal({ location: TerminalLocation.Panel, config: launchConfigs }); createdTerminal.onDisposed((terminal) => this._fireTaskEvent({ kind: TaskEventKind.Terminated, exitReason: terminal.exitReason, taskId: task.getRecentlyUsedKey() })); return createdTerminal; } private _reconnectToTerminals(): void { if (this._hasReconnected) { this._logService.trace(`Already reconnected, to ${this._reconnectedTerminals?.length} terminals so returning`); return; } this._reconnectedTerminals = this._terminalService.getReconnectedTerminals(ReconnectionType)?.filter(t => !t.isDisposed); this._logService.trace(`Attempting reconnection of ${this._reconnectedTerminals?.length} terminals`); if (!this._reconnectedTerminals?.length) { this._logService.trace(`No terminals to reconnect to so returning`); } else { for (const terminal of this._reconnectedTerminals) { const task = terminal.shellLaunchConfig.attachPersistentProcess?.reconnectionProperties?.data as IReconnectionTaskData; this._logService.trace(`Reconnecting to task: ${JSON.stringify(task)}`); if (!task) { continue; } const terminalData = { lastTask: task.lastTask, group: task.group, terminal }; this._terminals[terminal.instanceId] = terminalData; } } this._hasReconnected = true; } private _deleteTaskAndTerminal(terminal: ITerminalInstance, terminalData: ITerminalData): void { delete this._terminals[terminal.instanceId]; delete this._sameTaskTerminals[terminalData.lastTask]; this._idleTaskTerminals.delete(terminalData.lastTask); // Delete the task now as a work around for cases when the onExit isn't fired. // This can happen if the terminal wasn't shutdown with an "immediate" flag and is expected. // For correct terminal re-use, the task needs to be deleted immediately. // Note that this shouldn't be a problem anymore since user initiated terminal kills are now immediate. const mapKey = terminalData.lastTask; this._removeFromActiveTasks(mapKey); if (this._busyTasks[mapKey]) { delete this._busyTasks[mapKey]; } } private async _createTerminal(task: CustomTask | ContributedTask, resolver: VariableResolver, workspaceFolder: IWorkspaceFolder | undefined): Promise<[ITerminalInstance | undefined, TaskError | undefined]> { const platform = resolver.taskSystemInfo ? resolver.taskSystemInfo.platform : Platform.platform; const options = await this._resolveOptions(resolver, task.command.options); const presentationOptions = task.command.presentation; if (!presentationOptions) { throw new Error('Task presentation options should not be undefined here.'); } const waitOnExit = getWaitOnExitValue(presentationOptions, task.configurationProperties); let command: CommandString | undefined; let args: CommandString[] | undefined; let launchConfigs: IShellLaunchConfig | undefined; if (task.command.runtime === RuntimeType.CustomExecution) { this._currentTask.shellLaunchConfig = launchConfigs = { customPtyImplementation: (id, cols, rows) => new TerminalProcessExtHostProxy(id, cols, rows, this._terminalService), waitOnExit, name: this._createTerminalName(task), initialText: task.command.presentation && task.command.presentation.echo ? formatMessageForTerminal(nls.localize({ key: 'task.executing', comment: ['The task command line or label'] }, 'Executing task: {0}', task._label), { excludeLeadingNewLine: true }) : undefined, isFeatureTerminal: true, icon: task.configurationProperties.icon?.id ? ThemeIcon.fromId(task.configurationProperties.icon.id) : undefined, color: task.configurationProperties.icon?.color || undefined }; } else { const resolvedResult: { command: CommandString; args: CommandString[] } = await this._resolveCommandAndArgs(resolver, task.command); command = resolvedResult.command; args = resolvedResult.args; this._currentTask.shellLaunchConfig = launchConfigs = await this._createShellLaunchConfig(task, workspaceFolder, resolver, platform, options, command, args, waitOnExit); if (launchConfigs === undefined) { return [undefined, new TaskError(Severity.Error, nls.localize('TerminalTaskSystem', 'Can\'t execute a shell command on an UNC drive using cmd.exe.'), TaskErrors.UnknownError)]; } } const prefersSameTerminal = presentationOptions.panel === PanelKind.Dedicated; const allowsSharedTerminal = presentationOptions.panel === PanelKind.Shared; const group = presentationOptions.group; const taskKey = task.getMapKey(); let terminalToReuse: ITerminalData | undefined; if (prefersSameTerminal) { const terminalId = this._sameTaskTerminals[taskKey]; if (terminalId) { terminalToReuse = this._terminals[terminalId]; delete this._sameTaskTerminals[taskKey]; } } else if (allowsSharedTerminal) { // Always allow to reuse the terminal previously used by the same task. let terminalId = this._idleTaskTerminals.remove(taskKey); if (!terminalId) { // There is no idle terminal which was used by the same task. // Search for any idle terminal used previously by a task of the same group // (or, if the task has no group, a terminal used by a task without group). for (const taskId of this._idleTaskTerminals.keys()) { const idleTerminalId = this._idleTaskTerminals.get(taskId)!; if (idleTerminalId && this._terminals[idleTerminalId] && this._terminals[idleTerminalId].group === group) { terminalId = this._idleTaskTerminals.remove(taskId); break; } } } if (terminalId) { terminalToReuse = this._terminals[terminalId]; } } if (terminalToReuse) { if (!launchConfigs) { throw new Error('Task shell launch configuration should not be undefined here.'); } terminalToReuse.terminal.scrollToBottom(); await terminalToReuse.terminal.reuseTerminal(launchConfigs); if (task.command.presentation && task.command.presentation.clear) { terminalToReuse.terminal.clearBuffer(); } this._terminals[terminalToReuse.terminal.instanceId.toString()].lastTask = taskKey; return [terminalToReuse.terminal, undefined]; } this._terminalCreationQueue = this._terminalCreationQueue.then(() => this._doCreateTerminal(task, group, launchConfigs!)); const terminal: ITerminalInstance = (await this._terminalCreationQueue)!; terminal.shellLaunchConfig.reconnectionProperties = { ownerId: ReconnectionType, data: { lastTask: task.getCommonTaskId(), group, label: task._label, id: task._id } }; const terminalKey = terminal.instanceId.toString(); const terminalData = { terminal: terminal, lastTask: taskKey, group }; terminal.onDisposed(() => this._deleteTaskAndTerminal(terminal, terminalData)); this._terminals[terminalKey] = terminalData; return [terminal, undefined]; } private _buildShellCommandLine(platform: Platform.Platform, shellExecutable: string, shellOptions: IShellConfiguration | undefined, command: CommandString, originalCommand: CommandString | undefined, args: CommandString[]): string { const basename = path.parse(shellExecutable).name.toLowerCase(); const shellQuoteOptions = this._getQuotingOptions(basename, shellOptions, platform); function needsQuotes(value: string): boolean { if (value.length >= 2) { const first = value[0] === shellQuoteOptions.strong ? shellQuoteOptions.strong : value[0] === shellQuoteOptions.weak ? shellQuoteOptions.weak : undefined; if (first === value[value.length - 1]) { return false; } } let quote: string | undefined; for (let i = 0; i < value.length; i++) { // We found the end quote. const ch = value[i]; if (ch === quote) { quote = undefined; } else if (quote !== undefined) { // skip the character. We are quoted. continue; } else if (ch === shellQuoteOptions.escape) { // Skip the next character i++; } else if (ch === shellQuoteOptions.strong || ch === shellQuoteOptions.weak) { quote = ch; } else if (ch === ' ') { return true; } } return false; } function quote(value: string, kind: ShellQuoting): [string, boolean] { if (kind === ShellQuoting.Strong && shellQuoteOptions.strong) { return [shellQuoteOptions.strong + value + shellQuoteOptions.strong, true]; } else if (kind === ShellQuoting.Weak && shellQuoteOptions.weak) { return [shellQuoteOptions.weak + value + shellQuoteOptions.weak, true]; } else if (kind === ShellQuoting.Escape && shellQuoteOptions.escape) { if (Types.isString(shellQuoteOptions.escape)) { return [value.replace(/ /g, shellQuoteOptions.escape + ' '), true]; } else { const buffer: string[] = []; for (const ch of shellQuoteOptions.escape.charsToEscape) { buffer.push(`\\${ch}`); } const regexp: RegExp = new RegExp('[' + buffer.join(',') + ']', 'g'); const escapeChar = shellQuoteOptions.escape.escapeChar; return [value.replace(regexp, (match) => escapeChar + match), true]; } } return [value, false]; } function quoteIfNecessary(value: CommandString): [string, boolean] { if (Types.isString(value)) { if (needsQuotes(value)) { return quote(value, ShellQuoting.Strong); } else { return [value, false]; } } else { return quote(value.value, value.quoting); } } // If we have no args and the command is a string then use the command to stay backwards compatible with the old command line // model. To allow variable resolving with spaces we do continue if the resolved value is different than the original one // and the resolved one needs quoting. if ((!args || args.length === 0) && Types.isString(command) && (command === originalCommand as string || needsQuotes(originalCommand as string))) { return command; } const result: string[] = []; let commandQuoted = false; let argQuoted = false; let value: string; let quoted: boolean; [value, quoted] = quoteIfNecessary(command); result.push(value); commandQuoted = quoted; for (const arg of args) { [value, quoted] = quoteIfNecessary(arg); result.push(value); argQuoted = argQuoted || quoted; } let commandLine = result.join(' '); // There are special rules quoted command line in cmd.exe if (platform === Platform.Platform.Windows) { if (basename === 'cmd' && commandQuoted && argQuoted) { commandLine = '"' + commandLine + '"'; } else if ((basename === 'powershell' || basename === 'pwsh') && commandQuoted) { commandLine = '& ' + commandLine; } } return commandLine; } private _getQuotingOptions(shellBasename: string, shellOptions: IShellConfiguration | undefined, platform: Platform.Platform): IShellQuotingOptions { if (shellOptions && shellOptions.quoting) { return shellOptions.quoting; } return TerminalTaskSystem._shellQuotes[shellBasename] || TerminalTaskSystem._osShellQuotes[Platform.PlatformToString(platform)]; } private _collectTaskVariables(variables: Set<string>, task: CustomTask | ContributedTask): void { if (task.command && task.command.name) { this._collectCommandVariables(variables, task.command, task); } this._collectMatcherVariables(variables, task.configurationProperties.problemMatchers); if (task.command.runtime === RuntimeType.CustomExecution && (CustomTask.is(task) || ContributedTask.is(task))) { let definition: any; if (CustomTask.is(task)) { definition = task._source.config.element; } else { definition = Objects.deepClone(task.defines); delete definition._key; delete definition.type; } this._collectDefinitionVariables(variables, definition); } } private _collectDefinitionVariables(variables: Set<string>, definition: any): void { if (Types.isString(definition)) { this._collectVariables(variables, definition); } else if (Array.isArray(definition)) { definition.forEach((element: any) => this._collectDefinitionVariables(variables, element)); } else if (Types.isObject(definition)) { for (const key in definition) { this._collectDefinitionVariables(variables, definition[key]); } } } private _collectCommandVariables(variables: Set<string>, command: ICommandConfiguration, task: CustomTask | ContributedTask): void { // The custom execution should have everything it needs already as it provided // the callback. if (command.runtime === RuntimeType.CustomExecution) { return; } if (command.name === undefined) { throw new Error('Command name should never be undefined here.'); } this._collectVariables(variables, command.name); command.args?.forEach(arg => this._collectVariables(variables, arg)); // Try to get a scope. const scope = (<IExtensionTaskSource>task._source).scope; if (scope !== TaskScope.Global) { variables.add('${workspaceFolder}'); } if (command.options) { const options = command.options; if (options.cwd) { this._collectVariables(variables, options.cwd); } const optionsEnv = options.env; if (optionsEnv) { Object.keys(optionsEnv).forEach((key) => { const value: any = optionsEnv[key]; if (Types.isString(value)) { this._collectVariables(variables, value); } }); } if (options.shell) { if (options.shell.executable) { this._collectVariables(variables, options.shell.executable); } options.shell.args?.forEach(arg => this._collectVariables(variables, arg)); } } } private _collectMatcherVariables(variables: Set<string>, values: Array<string | ProblemMatcher> | undefined): void { if (values === undefined || values === null || values.length === 0) { return; } values.forEach((value) => { let matcher: ProblemMatcher; if (Types.isString(value)) { if (value[0] === '$') { matcher = ProblemMatcherRegistry.get(value.substring(1)); } else { matcher = ProblemMatcherRegistry.get(value); } } else { matcher = value; } if (matcher && matcher.filePrefix) { if (Types.isString(matcher.filePrefix)) { this._collectVariables(variables, matcher.filePrefix); } else { for (const fp of [...asArray(matcher.filePrefix.include || []), ...asArray(matcher.filePrefix.exclude || [])]) { this._collectVariables(variables, fp); } } } }); } private _collectVariables(variables: Set<string>, value: string | CommandString): void { const string: string = Types.isString(value) ? value : value.value; const r = /\$\{(.*?)\}/g; let matches: RegExpExecArray | null; do { matches = r.exec(string); if (matches) { variables.add(matches[0]); } } while (matches); } private async _resolveCommandAndArgs(resolver: VariableResolver, commandConfig: ICommandConfiguration): Promise<{ command: CommandString; args: CommandString[] }> { // First we need to use the command args: let args: CommandString[] = commandConfig.args ? commandConfig.args.slice() : []; args = await this._resolveVariables(resolver, args); const command: CommandString = await this._resolveVariable(resolver, commandConfig.name); return { command, args }; } private async _resolveVariables(resolver: VariableResolver, value: string[]): Promise<string[]>; private async _resolveVariables(resolver: VariableResolver, value: CommandString[]): Promise<CommandString[]>; private async _resolveVariables(resolver: VariableResolver, value: CommandString[]): Promise<CommandString[]> { return Promise.all(value.map(s => this._resolveVariable(resolver, s))); } private async _resolveMatchers(resolver: VariableResolver, values: Array<string | ProblemMatcher> | undefined): Promise<ProblemMatcher[]> { if (values === undefined || values === null || values.length === 0) { return []; } const result: ProblemMatcher[] = []; for (const value of values) { let matcher: ProblemMatcher; if (Types.isString(value)) { if (value[0] === '$') { matcher = ProblemMatcherRegistry.get(value.substring(1)); } else { matcher = ProblemMatcherRegistry.get(value); } } else { matcher = value; } if (!matcher) { this._appendOutput(nls.localize('unknownProblemMatcher', 'Problem matcher {0} can\'t be resolved. The matcher will be ignored')); continue; } const taskSystemInfo: ITaskSystemInfo | undefined = resolver.taskSystemInfo; const hasFilePrefix = matcher.filePrefix !== undefined; const hasUriProvider = taskSystemInfo !== undefined && taskSystemInfo.uriProvider !== undefined; if (!hasFilePrefix && !hasUriProvider) { result.push(matcher); } else { const copy = Objects.deepClone(matcher); if (hasUriProvider && (taskSystemInfo !== undefined)) { copy.uriProvider = taskSystemInfo.uriProvider; } if (hasFilePrefix) { const filePrefix = copy.filePrefix; if (Types.isString(filePrefix)) { copy.filePrefix = await this._resolveVariable(resolver, filePrefix); } else if (filePrefix !== undefined) { if (filePrefix.include) { filePrefix.include = Array.isArray(filePrefix.include) ? await Promise.all(filePrefix.include.map(x => this._resolveVariable(resolver, x))) : await this._resolveVariable(resolver, filePrefix.include); } if (filePrefix.exclude) { filePrefix.exclude = Array.isArray(filePrefix.exclude) ? await Promise.all(filePrefix.exclude.map(x => this._resolveVariable(resolver, x))) : await this._resolveVariable(resolver, filePrefix.exclude); } } } result.push(copy); } } return result; } private async _resolveVariable(resolver: VariableResolver, value: string | undefined): Promise<string>; private async _resolveVariable(resolver: VariableResolver, value: CommandString | undefined): Promise<CommandString>; private async _resolveVariable(resolver: VariableResolver, value: CommandString | undefined): Promise<CommandString> { // TODO@Dirk Task.getWorkspaceFolder should return a WorkspaceFolder that is defined in workspace.ts if (Types.isString(value)) { return resolver.resolve(value); } else if (value !== undefined) { return { value: await resolver.resolve(value.value), quoting: value.quoting }; } else { // This should never happen throw new Error('Should never try to resolve undefined.'); } } private async _resolveOptions(resolver: VariableResolver, options: CommandOptions | undefined): Promise<CommandOptions> { if (options === undefined || options === null) { let cwd: string | undefined; try { cwd = await this._resolveVariable(resolver, '${workspaceFolder}'); } catch (e) { // No workspace } return { cwd }; } const result: CommandOptions = Types.isString(options.cwd) ? { cwd: await this._resolveVariable(resolver, options.cwd) } : { cwd: await this._resolveVariable(resolver, '${workspaceFolder}') }; if (options.env) { result.env = Object.create(null); for (const key of Object.keys(options.env)) { const value: any = options.env![key]; if (Types.isString(value)) { result.env![key] = await this._resolveVariable(resolver, value); } else { result.env![key] = value.toString(); } } } return result; } static WellKnownCommands: IStringDictionary<boolean> = { 'ant': true, 'cmake': true, 'eslint': true, 'gradle': true, 'grunt': true, 'gulp': true, 'jake': true, 'jenkins': true, 'jshint': true, 'make': true, 'maven': true, 'msbuild': true, 'msc': true, 'nmake': true, 'npm': true, 'rake': true, 'tsc': true, 'xbuild': true }; public getSanitizedCommand(cmd: string): string { let result = cmd.toLowerCase(); const index = result.lastIndexOf(path.sep); if (index !== -1) { result = result.substring(index + 1); } if (TerminalTaskSystem.WellKnownCommands[result]) { return result; } return 'other'; } private _appendOutput(output: string): void { const outputChannel = this._outputService.getChannel(this._outputChannelId); outputChannel?.append(output); } } function getWaitOnExitValue(presentationOptions: IPresentationOptions, configurationProperties: IConfigurationProperties) { if ((presentationOptions.close === undefined) || (presentationOptions.close === false)) { if ((presentationOptions.reveal !== RevealKind.Never) || !configurationProperties.isBackground || (presentationOptions.close === false)) { if (presentationOptions.panel === PanelKind.New) { return taskShellIntegrationWaitOnExitSequence(nls.localize('closeTerminal', 'Press any key to close the terminal.')); } else if (presentationOptions.showReuseMessage) { return taskShellIntegrationWaitOnExitSequence(nls.localize('reuseTerminal', 'Terminal will be reused by tasks, press any key to close it.')); } else { return true; } } } return !presentationOptions.close; } function taskShellIntegrationWaitOnExitSequence(message: string): (exitCode: number) => string { return (exitCode) => { return `${VSCodeSequence(VSCodeOscPt.CommandFinished, exitCode.toString())}${message}`; }; }
src/vs/workbench/contrib/tasks/browser/terminalTaskSystem.ts
1
https://github.com/microsoft/vscode/commit/82a00605474987a1b6f5208018d523fa3b2d356a
[ 0.0022328724153339863, 0.00022594639449380338, 0.00016206063446588814, 0.00017121298878919333, 0.0002766632824204862 ]
{ "id": 2, "code_window": [ "\t\t}));\n", "\n", "\t\tconst disposeListeners = [\n", "\t\t\tinstance.onExit(() => this.dispose()),\n", "\t\t\tinstance.onDisposed(() => this.dispose()),\n", "\t\t\tinstance.onTitleChanged(() => this._onDidChangeLabel.fire()),\n", "\t\t\tinstance.onIconChanged(() => this._onDidChangeLabel.fire()),\n", "\t\t\tinstance.onDidFocus(() => this._terminalEditorFocusContextKey.set(true)),\n", "\t\t\tinstance.onDidBlur(() => this._terminalEditorFocusContextKey.reset()),\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tinstance.onExit((e) => {\n", "\t\t\t\tif (!instance.waitOnExit) {\n", "\t\t\t\t\tthis.dispose();\n", "\t\t\t\t}\n", "\t\t\t}),\n" ], "file_path": "src/vs/workbench/contrib/terminal/browser/terminalEditorInput.ts", "type": "replace", "edit_start_line_idx": 164 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import 'mocha'; import * as assert from 'assert'; import { closeAllEditors, withRandomFileEditor } from './testUtils'; import * as vscode from 'vscode'; import { parsePartialStylesheet, getFlatNode } from '../util'; import { isValidLocationForEmmetAbbreviation } from '../abbreviationActions'; suite('Tests for partial parse of Stylesheets', () => { teardown(closeAllEditors); function isValid(doc: vscode.TextDocument, range: vscode.Range, syntax: string): boolean { const rootNode = parsePartialStylesheet(doc, range.end); const endOffset = doc.offsetAt(range.end); const currentNode = getFlatNode(rootNode, endOffset, true); return isValidLocationForEmmetAbbreviation(doc, rootNode, currentNode, syntax, endOffset, range); } test('Ignore block comment inside rule', function (): any { const cssContents = ` p { margin: p ; /*dn: none; p */ p p p. } p `; return withRandomFileEditor(cssContents, '.css', (_, doc) => { const rangesForEmmet = [ new vscode.Range(3, 18, 3, 19), // Same line after block comment new vscode.Range(4, 1, 4, 2), // p after block comment new vscode.Range(5, 1, 5, 3) // p. after block comment ]; const rangesNotEmmet = [ new vscode.Range(1, 0, 1, 1), // Selector new vscode.Range(2, 9, 2, 10), // Property value new vscode.Range(3, 3, 3, 5), // dn inside block comment new vscode.Range(3, 13, 3, 14), // p just before ending of block comment new vscode.Range(6, 2, 6, 3) // p after ending of block ]; rangesForEmmet.forEach(range => { assert.strictEqual(isValid(doc, range, 'css'), true); }); rangesNotEmmet.forEach(range => { assert.strictEqual(isValid(doc, range, 'css'), false); }); return Promise.resolve(); }); }); test('Ignore commented braces', function (): any { const sassContents = ` .foo // .foo { brs /* .foo { op.3 dn { */ bgc } bg `; return withRandomFileEditor(sassContents, '.scss', (_, doc) => { const rangesNotEmmet = [ new vscode.Range(1, 0, 1, 4), // Selector new vscode.Range(2, 3, 2, 7), // Line commented selector new vscode.Range(3, 3, 3, 7), // Block commented selector new vscode.Range(4, 0, 4, 2), // dn inside block comment new vscode.Range(6, 1, 6, 2), // bgc inside a rule whose opening brace is commented new vscode.Range(7, 2, 7, 4) // bg after ending of badly constructed block ]; rangesNotEmmet.forEach(range => { assert.strictEqual(isValid(doc, range, 'scss'), false); }); return Promise.resolve(); }); }); test('Block comment between selector and open brace', function (): any { const cssContents = ` p /* First line of a multiline comment */ { margin: p ; /*dn: none; p */ p p p. } p `; return withRandomFileEditor(cssContents, '.css', (_, doc) => { const rangesForEmmet = [ new vscode.Range(7, 18, 7, 19), // Same line after block comment new vscode.Range(8, 1, 8, 2), // p after block comment new vscode.Range(9, 1, 9, 3) // p. after block comment ]; const rangesNotEmmet = [ new vscode.Range(1, 2, 1, 3), // Selector new vscode.Range(3, 3, 3, 4), // Inside multiline comment new vscode.Range(5, 0, 5, 1), // Opening Brace new vscode.Range(6, 9, 6, 10), // Property value new vscode.Range(7, 3, 7, 5), // dn inside block comment new vscode.Range(7, 13, 7, 14), // p just before ending of block comment new vscode.Range(10, 2, 10, 3) // p after ending of block ]; rangesForEmmet.forEach(range => { assert.strictEqual(isValid(doc, range, 'css'), true); }); rangesNotEmmet.forEach(range => { assert.strictEqual(isValid(doc, range, 'css'), false); }); return Promise.resolve(); }); }); test('Nested and consecutive rulesets with errors', function (): any { const sassContents = ` .foo{ a a }}{ p } .bar{ @ .rudi { @ } }}} `; return withRandomFileEditor(sassContents, '.scss', (_, doc) => { const rangesForEmmet = [ new vscode.Range(2, 1, 2, 2), // Inside a ruleset before errors new vscode.Range(3, 1, 3, 2), // Inside a ruleset after no serious error new vscode.Range(7, 1, 7, 2), // @ inside a so far well structured ruleset new vscode.Range(9, 2, 9, 3), // @ inside a so far well structured nested ruleset ]; const rangesNotEmmet = [ new vscode.Range(4, 4, 4, 5), // p inside ruleset without proper selector new vscode.Range(6, 3, 6, 4) // In selector ]; rangesForEmmet.forEach(range => { assert.strictEqual(isValid(doc, range, 'scss'), true); }); rangesNotEmmet.forEach(range => { assert.strictEqual(isValid(doc, range, 'scss'), false); }); return Promise.resolve(); }); }); test('One liner sass', function (): any { const sassContents = ` .foo{dn}.bar{.boo{dn}dn}.comd{/*{dn*/p{div{dn}} }.foo{.other{dn}} dn `; return withRandomFileEditor(sassContents, '.scss', (_, doc) => { const rangesForEmmet = [ new vscode.Range(1, 5, 1, 7), // Inside a ruleset new vscode.Range(1, 18, 1, 20), // Inside a nested ruleset new vscode.Range(1, 21, 1, 23), // Inside ruleset after nested one. new vscode.Range(1, 43, 1, 45), // Inside nested ruleset after comment new vscode.Range(1, 61, 1, 63) // Inside nested ruleset ]; const rangesNotEmmet = [ new vscode.Range(1, 3, 1, 4), // In foo selector new vscode.Range(1, 10, 1, 11), // In bar selector new vscode.Range(1, 15, 1, 16), // In boo selector new vscode.Range(1, 28, 1, 29), // In comd selector new vscode.Range(1, 33, 1, 34), // In commented dn new vscode.Range(1, 37, 1, 38), // In p selector new vscode.Range(1, 39, 1, 42), // In div selector new vscode.Range(1, 66, 1, 68) // Outside any ruleset ]; rangesForEmmet.forEach(range => { assert.strictEqual(isValid(doc, range, 'scss'), true); }); rangesNotEmmet.forEach(range => { assert.strictEqual(isValid(doc, range, 'scss'), false); }); return Promise.resolve(); }); }); test('Variables and interpolation', function (): any { const sassContents = ` p.#{dn} { p.3 #{$attr}-color: blue; dn } op .foo{nes{ted}} { dn } `; return withRandomFileEditor(sassContents, '.scss', (_, doc) => { const rangesForEmmet = [ new vscode.Range(2, 1, 2, 4), // p.3 inside a ruleset whose selector uses interpolation new vscode.Range(4, 1, 4, 3) // dn inside ruleset after property with variable ]; const rangesNotEmmet = [ new vscode.Range(1, 0, 1, 1), // In p in selector new vscode.Range(1, 2, 1, 3), // In # in selector new vscode.Range(1, 4, 1, 6), // In dn inside variable in selector new vscode.Range(3, 7, 3, 8), // r of attr inside variable new vscode.Range(5, 2, 5, 4), // op after ruleset new vscode.Range(7, 1, 7, 3), // dn inside ruleset whose selector uses nested interpolation new vscode.Range(3, 1, 3, 2), // # inside ruleset ]; rangesForEmmet.forEach(range => { assert.strictEqual(isValid(doc, range, 'scss'), true); }); rangesNotEmmet.forEach(range => { assert.strictEqual(isValid(doc, range, 'scss'), false); }); return Promise.resolve(); }); }); test('Comments in sass', function (): any { const sassContents = ` .foo{ /* p // p */ brs6-2p dn } p /* c om ment */{ m10 } .boo{ op.3 } `; return withRandomFileEditor(sassContents, '.scss', (_, doc) => { const rangesForEmmet = [ new vscode.Range(2, 14, 2, 21), // brs6-2p with a block commented line comment ('/* */' overrides '//') new vscode.Range(3, 1, 3, 3), // dn after a line with combined comments inside a ruleset new vscode.Range(9, 1, 9, 4), // m10 inside ruleset whose selector is before a comment new vscode.Range(12, 1, 12, 5) // op3 inside a ruleset with commented extra braces ]; const rangesNotEmmet = [ new vscode.Range(2, 4, 2, 5), // In p inside block comment new vscode.Range(2, 9, 2, 10), // In p inside block comment and after line comment new vscode.Range(6, 3, 6, 4) // In c inside block comment ]; rangesForEmmet.forEach(range => { assert.strictEqual(isValid(doc, range, 'scss'), true); }); rangesNotEmmet.forEach(range => { assert.strictEqual(isValid(doc, range, 'scss'), false); }); return Promise.resolve(); }); }); });
extensions/emmet/src/test/partialParsingStylesheet.test.ts
0
https://github.com/microsoft/vscode/commit/82a00605474987a1b6f5208018d523fa3b2d356a
[ 0.00017636449774727225, 0.00017307016241829842, 0.00016924639930948615, 0.0001729802752379328, 0.0000018284172256244346 ]
{ "id": 2, "code_window": [ "\t\t}));\n", "\n", "\t\tconst disposeListeners = [\n", "\t\t\tinstance.onExit(() => this.dispose()),\n", "\t\t\tinstance.onDisposed(() => this.dispose()),\n", "\t\t\tinstance.onTitleChanged(() => this._onDidChangeLabel.fire()),\n", "\t\t\tinstance.onIconChanged(() => this._onDidChangeLabel.fire()),\n", "\t\t\tinstance.onDidFocus(() => this._terminalEditorFocusContextKey.set(true)),\n", "\t\t\tinstance.onDidBlur(() => this._terminalEditorFocusContextKey.reset()),\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tinstance.onExit((e) => {\n", "\t\t\t\tif (!instance.waitOnExit) {\n", "\t\t\t\t\tthis.dispose();\n", "\t\t\t\t}\n", "\t\t\t}),\n" ], "file_path": "src/vs/workbench/contrib/terminal/browser/terminalEditorInput.ts", "type": "replace", "edit_start_line_idx": 164 }
parameters: - name: VSCODE_CLI_TARGET type: string - name: VSCODE_CLI_ARTIFACT type: string - name: VSCODE_CLI_ENV type: object default: {} steps: - script: cargo build --release --target ${{ parameters.VSCODE_CLI_TARGET }} --bin=code displayName: Compile ${{ parameters.VSCODE_CLI_TARGET }} workingDirectory: $(Build.SourcesDirectory)/cli env: CARGO_NET_GIT_FETCH_WITH_CLI: true ${{ each pair in parameters.VSCODE_CLI_ENV }}: ${{ pair.key }}: ${{ pair.value }} - ${{ if or(contains(parameters.VSCODE_CLI_TARGET, '-windows-'), contains(parameters.VSCODE_CLI_TARGET, '-darwin')) }}: - task: ArchiveFiles@2 inputs: ${{ if contains(parameters.VSCODE_CLI_TARGET, '-windows-') }}: rootFolderOrFile: $(Build.SourcesDirectory)/cli/target/${{ parameters.VSCODE_CLI_TARGET }}/release/code.exe ${{ if contains(parameters.VSCODE_CLI_TARGET, '-darwin') }}: rootFolderOrFile: $(Build.SourcesDirectory)/cli/target/${{ parameters.VSCODE_CLI_TARGET }}/release/code includeRootFolder: false archiveType: zip archiveFile: $(Build.ArtifactStagingDirectory)/${{ parameters.VSCODE_CLI_ARTIFACT }}.zip - publish: $(Build.ArtifactStagingDirectory)/${{ parameters.VSCODE_CLI_ARTIFACT }}.zip artifact: ${{ parameters.VSCODE_CLI_ARTIFACT }} displayName: Publish ${{ parameters.VSCODE_CLI_ARTIFACT }} artifact - ${{ else }}: - task: ArchiveFiles@2 inputs: rootFolderOrFile: $(Build.SourcesDirectory)/cli/target/${{ parameters.VSCODE_CLI_TARGET }}/release/code includeRootFolder: false archiveType: tar tarCompression: gz archiveFile: $(Build.ArtifactStagingDirectory)/${{ parameters.VSCODE_CLI_ARTIFACT }}.tar.gz - publish: $(Build.ArtifactStagingDirectory)/${{ parameters.VSCODE_CLI_ARTIFACT }}.tar.gz artifact: ${{ parameters.VSCODE_CLI_ARTIFACT }} displayName: Publish ${{ parameters.VSCODE_CLI_ARTIFACT }} artifact
build/azure-pipelines/cli/cli-compile-and-publish.yml
0
https://github.com/microsoft/vscode/commit/82a00605474987a1b6f5208018d523fa3b2d356a
[ 0.0001782757171895355, 0.00017464064876548946, 0.00016972844605334103, 0.00017494356143288314, 0.0000027609689823293593 ]
{ "id": 2, "code_window": [ "\t\t}));\n", "\n", "\t\tconst disposeListeners = [\n", "\t\t\tinstance.onExit(() => this.dispose()),\n", "\t\t\tinstance.onDisposed(() => this.dispose()),\n", "\t\t\tinstance.onTitleChanged(() => this._onDidChangeLabel.fire()),\n", "\t\t\tinstance.onIconChanged(() => this._onDidChangeLabel.fire()),\n", "\t\t\tinstance.onDidFocus(() => this._terminalEditorFocusContextKey.set(true)),\n", "\t\t\tinstance.onDidBlur(() => this._terminalEditorFocusContextKey.reset()),\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tinstance.onExit((e) => {\n", "\t\t\t\tif (!instance.waitOnExit) {\n", "\t\t\t\t\tthis.dispose();\n", "\t\t\t\t}\n", "\t\t\t}),\n" ], "file_path": "src/vs/workbench/contrib/terminal/browser/terminalEditorInput.ts", "type": "replace", "edit_start_line_idx": 164 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Lazy } from 'vs/base/common/lazy'; /** * A regex that extracts the link suffix which contains line and column information. */ const linkSuffixRegex = new Lazy<RegExp>(() => { let ri = 0; let ci = 0; function l(): string { return `(?<row${ri++}>\\d+)`; } function c(): string { return `(?<col${ci++}>\\d+)`; } // The comments in the regex below use real strings/numbers for better readability, here's // the legend: // - Path = foo // - Row = 339 // - Col = 12 // // These all support single quote ' in the place of " and [] in the place of () const lineAndColumnRegexClauses = [ // foo:339 // foo:339:12 // foo 339 // foo 339:12 [#140780] // "foo",339 // "foo",339:12 `(?::| |['"],)${l()}(:${c()})?$`, // "foo", line 339 [#40468] // "foo", line 339, col 12 // "foo", line 339, column 12 // "foo":line 339 // "foo":line 339, col 12 // "foo":line 339, column 12 // "foo": line 339 // "foo": line 339, col 12 // "foo": line 339, column 12 // "foo" on line 339 // "foo" on line 339, col 12 // "foo" on line 339, column 12 `['"](?:, |: ?| on )line ${l()}(, col(?:umn)? ${c()})?$`, // foo(339) // foo(339,12) // foo(339, 12) // foo (339) // foo (339,12) // foo (339, 12) ` ?[\\[\\(]${l()}(?:, ?${c()})?[\\]\\)]`, ]; const suffixClause = lineAndColumnRegexClauses // Join all clauses together .join('|') // Convert spaces to allow the non-breaking space char (ascii 160) .replace(/ /g, `[${'\u00A0'} ]`); return new RegExp(`(${suffixClause})`); }); /** * Removes the optional link suffix which contains line and column information. * @param link The link to parse. */ export function removeLinkSuffix(link: string): string { const suffix = getLinkSuffix(link)?.suffix; if (!suffix) { return link; } return link.substring(0, suffix.index); } /** * Returns the optional link suffix which contains line and column information. * @param link The link to parse. */ export function getLinkSuffix(link: string): { row: number | undefined; col: number | undefined; suffix: { index: number; text: string } } | null { const matches = linkSuffixRegex.getValue().exec(link); const groups = matches?.groups; if (!groups || matches.length < 1) { return null; } const rowString = groups.row0 || groups.row1 || groups.row2; const colString = groups.col0 || groups.col1 || groups.col2; return { row: rowString !== undefined ? parseInt(rowString) : undefined, col: colString !== undefined ? parseInt(colString) : undefined, suffix: { index: matches.index, text: matches[0] } }; }
src/vs/workbench/contrib/terminal/browser/links/terminalLinkParsing.ts
0
https://github.com/microsoft/vscode/commit/82a00605474987a1b6f5208018d523fa3b2d356a
[ 0.0001761524035828188, 0.00017173805099446326, 0.0001621389965293929, 0.0001729433424770832, 0.000004026706392323831 ]
{ "id": 0, "code_window": [ "export * from './middleware';\n", "export * from './nest-application';\n", "export * from './nest-application-context';\n", "export { NestFactory } from './nest-factory';\n", "export * from './router';\n", "export * from './services';" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "export * from './application-config';\n" ], "file_path": "packages/core/index.ts", "type": "add", "edit_start_line_idx": 16 }
import { Scope } from '@nestjs/common'; import { SCOPE_OPTIONS_METADATA } from '@nestjs/common/constants'; import { Abstract, ClassProvider, Controller, DynamicModule, ExistingProvider, FactoryProvider, Injectable, NestModule, Provider, ValueProvider, } from '@nestjs/common/interfaces'; import { Type } from '@nestjs/common/interfaces/type.interface'; import { randomStringGenerator } from '@nestjs/common/utils/random-string-generator.util'; import { isFunction, isNil, isString, isSymbol, isUndefined, } from '@nestjs/common/utils/shared.utils'; import { InvalidClassException } from '../errors/exceptions/invalid-class.exception'; import { RuntimeException } from '../errors/exceptions/runtime.exception'; import { UnknownExportException } from '../errors/exceptions/unknown-export.exception'; import { NestContainer } from './container'; import { InstanceWrapper } from './instance-wrapper'; import { ModuleRef } from './module-ref'; interface ProviderName { name?: string | symbol; } export class Module { private readonly _id: string; private readonly _imports = new Set<Module>(); private readonly _providers = new Map<any, InstanceWrapper<Injectable>>(); private readonly _injectables = new Map<any, InstanceWrapper<Injectable>>(); private readonly _controllers = new Map< string, InstanceWrapper<Controller> >(); private readonly _exports = new Set<string | symbol>(); constructor( private readonly _metatype: Type<any>, private readonly _scope: Type<any>[], private readonly container: NestContainer, ) { this.addCoreProviders(container); this._id = randomStringGenerator(); } get id(): string { return this._id; } get scope(): Type<any>[] { return this._scope; } get providers(): Map<any, InstanceWrapper<Injectable>> { return this._providers; } get imports(): Set<Module> { return this._imports; } /** * Left for backward-compatibility reasons */ get relatedModules(): Set<Module> { return this._imports; } /** * Left for backward-compatibility reasons */ get components(): Map<string, InstanceWrapper<Injectable>> { return this._providers; } /** * Left for backward-compatibility reasons */ get routes(): Map<string, InstanceWrapper<Controller>> { return this._controllers; } get injectables(): Map<string, InstanceWrapper<Injectable>> { return this._injectables; } get controllers(): Map<string, InstanceWrapper<Controller>> { return this._controllers; } get exports(): Set<string | symbol> { return this._exports; } get instance(): NestModule { if (!this._providers.has(this._metatype.name)) { throw new RuntimeException(); } const module = this._providers.get(this._metatype.name); return module.instance as NestModule; } get metatype(): Type<any> { return this._metatype; } public addCoreProviders(container: NestContainer) { this.addModuleAsProvider(); this.addModuleRef(); } public addModuleRef() { const moduleRef = this.createModuleReferenceType(); this._providers.set( ModuleRef.name, new InstanceWrapper({ name: ModuleRef.name, metatype: ModuleRef as any, isResolved: true, instance: new moduleRef(), host: this, }), ); } public addModuleAsProvider() { this._providers.set( this._metatype.name, new InstanceWrapper({ name: this._metatype.name, metatype: this._metatype, isResolved: false, instance: null, host: this, }), ); } public addInjectable<T extends Injectable>( injectable: Type<T>, host?: Type<T>, ) { if (this.isCustomProvider(injectable)) { return this.addCustomProvider(injectable, this._injectables); } const instanceWrapper = new InstanceWrapper({ name: injectable.name, metatype: injectable, instance: null, isResolved: false, scope: this.getClassScope(injectable), host: this, }); this._injectables.set(injectable.name, instanceWrapper); if (host) { const hostWrapper = this._controllers.get(host && host.name); hostWrapper && hostWrapper.addEnhancerMetadata(instanceWrapper); } } public addProvider(provider: Provider): string { if (this.isCustomProvider(provider)) { return this.addCustomProvider(provider, this._providers); } this._providers.set( (provider as Type<Injectable>).name, new InstanceWrapper({ name: (provider as Type<Injectable>).name, metatype: provider as Type<Injectable>, instance: null, isResolved: false, scope: this.getClassScope(provider), host: this, }), ); return (provider as Type<Injectable>).name; } public isCustomProvider( provider: Provider, ): provider is | ClassProvider | FactoryProvider | ValueProvider | ExistingProvider { return !isNil( (provider as | ClassProvider | FactoryProvider | ValueProvider | ExistingProvider).provide, ); } public addCustomProvider( provider: ( | ClassProvider | FactoryProvider | ValueProvider | ExistingProvider) & ProviderName, collection: Map<string, any>, ): string { const name = this.getProviderStaticToken(provider.provide) as string; provider = { ...provider, name, }; if (this.isCustomClass(provider)) { this.addCustomClass(provider, collection); } else if (this.isCustomValue(provider)) { this.addCustomValue(provider, collection); } else if (this.isCustomFactory(provider)) { this.addCustomFactory(provider, collection); } else if (this.isCustomUseExisting(provider)) { this.addCustomUseExisting(provider, collection); } return name; } public isCustomClass(provider: any): provider is ClassProvider { return !isUndefined((provider as ClassProvider).useClass); } public isCustomValue(provider: any): provider is ValueProvider { return !isUndefined((provider as ValueProvider).useValue); } public isCustomFactory(provider: any): provider is FactoryProvider { return !isUndefined((provider as FactoryProvider).useFactory); } public isCustomUseExisting(provider: any): provider is ExistingProvider { return !isUndefined((provider as ExistingProvider).useExisting); } public isDynamicModule(exported: any): exported is DynamicModule { return exported && exported.module; } public addCustomClass( provider: ClassProvider & ProviderName, collection: Map<string, InstanceWrapper>, ) { const { name, useClass, scope } = provider; collection.set( name as string, new InstanceWrapper({ name, metatype: useClass, instance: null, isResolved: false, scope, host: this, }), ); } public addCustomValue( provider: ValueProvider & ProviderName, collection: Map<string, InstanceWrapper>, ) { const { name, useValue: value } = provider; collection.set( name as string, new InstanceWrapper({ name, metatype: null, instance: value, isResolved: true, async: value instanceof Promise, host: this, }), ); } public addCustomFactory( provider: FactoryProvider & ProviderName, collection: Map<string, InstanceWrapper>, ) { const { name, useFactory: factory, inject, scope } = provider; collection.set( name as string, new InstanceWrapper({ name, metatype: factory as any, instance: null, isResolved: false, inject: inject || [], scope, host: this, }), ); } public addCustomUseExisting( provider: ExistingProvider & ProviderName, collection: Map<string, InstanceWrapper>, ) { const { name, useExisting } = provider; collection.set( name as string, new InstanceWrapper({ name, metatype: (instance => instance) as any, instance: null, isResolved: false, inject: [useExisting], host: this, }), ); } public addExportedProvider( provider: Provider & ProviderName | string | symbol | DynamicModule, ) { const addExportedUnit = (token: string | symbol) => this._exports.add(this.validateExportedProvider(token)); if (this.isCustomProvider(provider as any)) { return this.addCustomExportedProvider(provider as any); } else if (isString(provider) || isSymbol(provider)) { return addExportedUnit(provider); } else if (this.isDynamicModule(provider)) { const { module } = provider; return addExportedUnit(module.name); } addExportedUnit(provider.name); } public addCustomExportedProvider( provider: | FactoryProvider | ValueProvider | ClassProvider | ExistingProvider, ) { const provide = provider.provide; if (isString(provide) || isSymbol(provide)) { return this._exports.add(this.validateExportedProvider(provide)); } this._exports.add(this.validateExportedProvider(provide.name)); } public validateExportedProvider(token: string | symbol) { if (this._providers.has(token)) { return token; } const importsArray = [...this._imports.values()]; const importsNames = importsArray .filter(item => item) .map(({ metatype }) => metatype) .filter(metatype => metatype) .map(({ name }) => name); if (!importsNames.includes(token as any)) { const { name } = this.metatype; throw new UnknownExportException(name); } return token; } public addController(controller: Type<Controller>) { this._controllers.set( controller.name, new InstanceWrapper({ name: controller.name, metatype: controller, instance: null, isResolved: false, scope: this.getClassScope(controller), host: this, }), ); } public addRelatedModule(module: any) { this._imports.add(module); } public replace(toReplace: string | symbol | Type<any>, options: any) { if (options.isProvider && this.hasProvider(toReplace)) { const name = this.getProviderStaticToken(toReplace); const originalProvider = this._providers.get(name); return originalProvider.mergeWith({ provide: toReplace, ...options }); } else if (!options.isProvider && this.hasInjectable(toReplace)) { const name = this.getProviderStaticToken(toReplace); const originalInjectable = this._injectables.get(name); return originalInjectable.mergeWith({ provide: toReplace, ...options, }); } } public hasProvider(token: string | symbol | Type<any>): boolean { const name = this.getProviderStaticToken(token); return this._providers.has(name); } public hasInjectable(token: string | symbol | Type<any>): boolean { const name = this.getProviderStaticToken(token); return this._injectables.has(name); } public getProviderStaticToken( provider: string | symbol | Type<any> | Abstract<any>, ): string | symbol { return isFunction(provider) ? (provider as Function).name : (provider as string | symbol); } public getProviderByKey<T = any>(name: string | symbol): InstanceWrapper<T> { return this._providers.get(name) as InstanceWrapper<T>; } public createModuleReferenceType(): any { const self = this; return class extends ModuleRef { constructor() { super(self.container); } public get<TInput = any, TResult = TInput>( typeOrToken: Type<TInput> | string | symbol, options: { strict: boolean } = { strict: true }, ): TResult { if (!(options && options.strict)) { return this.find<TInput, TResult>(typeOrToken); } return this.findInstanceByPrototypeOrToken<TInput, TResult>( typeOrToken, self, ); } public async create<T = any>(type: Type<T>): Promise<T> { if (!(type && isFunction(type) && type.prototype)) { throw new InvalidClassException(type); } return this.instantiateClass<T>(type, self); } }; } private getClassScope(provider: Provider): Scope { const metadata = Reflect.getMetadata(SCOPE_OPTIONS_METADATA, provider); return metadata && metadata.scope; } }
packages/core/injector/module.ts
1
https://github.com/nestjs/nest/commit/94949fee6e498e8f791e8c398bfc837a8223db3e
[ 0.0016964530805125833, 0.0002502547577023506, 0.00016590647283010185, 0.00017042059334926307, 0.00025602380628697574 ]
{ "id": 0, "code_window": [ "export * from './middleware';\n", "export * from './nest-application';\n", "export * from './nest-application-context';\n", "export { NestFactory } from './nest-factory';\n", "export * from './router';\n", "export * from './services';" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "export * from './application-config';\n" ], "file_path": "packages/core/index.ts", "type": "add", "edit_start_line_idx": 16 }
/* * Nest @testing * Copyright(c) 2017 - 2019 Kamil Mysliwiec * https://nestjs.com * MIT Licensed */ export * from './interfaces'; export * from './test'; export * from './testing-module'; export * from './testing-module.builder';
packages/testing/index.ts
0
https://github.com/nestjs/nest/commit/94949fee6e498e8f791e8c398bfc837a8223db3e
[ 0.0004296964325476438, 0.00033393659396097064, 0.00023817672627046704, 0.00033393659396097064, 0.00009575985313858837 ]
{ "id": 0, "code_window": [ "export * from './middleware';\n", "export * from './nest-application';\n", "export * from './nest-application-context';\n", "export { NestFactory } from './nest-factory';\n", "export * from './router';\n", "export * from './services';" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "export * from './application-config';\n" ], "file_path": "packages/core/index.ts", "type": "add", "edit_start_line_idx": 16 }
import { INestApplication } from '@nestjs/common'; import { Transport } from '@nestjs/microservices'; import { Test } from '@nestjs/testing'; import { expect } from 'chai'; import * as request from 'supertest'; import { RedisController } from '../src/redis/redis.controller'; describe('REDIS transport', () => { let server; let app: INestApplication; beforeEach(async () => { const module = await Test.createTestingModule({ controllers: [RedisController], }).compile(); app = module.createNestApplication(); server = app.getHttpAdapter().getInstance(); app.connectMicroservice({ transport: Transport.REDIS, }); await app.startAllMicroservicesAsync(); await app.init(); }); it(`/POST`, () => { return request(server) .post('/?command=sum') .send([1, 2, 3, 4, 5]) .expect(200, '15'); }); it(`/POST (Promise/async)`, () => { return request(server) .post('/?command=asyncSum') .send([1, 2, 3, 4, 5]) .expect(200) .expect(200, '15'); }); it(`/POST (Observable stream)`, () => { return request(server) .post('/?command=streamSum') .send([1, 2, 3, 4, 5]) .expect(200, '15'); }); it(`/POST (concurrent)`, () => { return request(server) .post('/concurrent') .send([ Array.from({ length: 10 }, (v, k) => k + 1), Array.from({ length: 10 }, (v, k) => k + 11), Array.from({ length: 10 }, (v, k) => k + 21), Array.from({ length: 10 }, (v, k) => k + 31), Array.from({ length: 10 }, (v, k) => k + 41), Array.from({ length: 10 }, (v, k) => k + 51), Array.from({ length: 10 }, (v, k) => k + 61), Array.from({ length: 10 }, (v, k) => k + 71), Array.from({ length: 10 }, (v, k) => k + 81), Array.from({ length: 10 }, (v, k) => k + 91), ]) .expect(200, 'true'); }); it(`/POST (streaming)`, () => { return request(server) .post('/stream') .send([1, 2, 3, 4, 5]) .expect(200, '15'); }); it(`/POST (event notification)`, done => { request(server) .post('/notify') .send([1, 2, 3, 4, 5]) .end(() => { setTimeout(() => { expect(RedisController.IS_NOTIFIED).to.be.true; done(); }, 1000); }); }); afterEach(async () => { await app.close(); }); });
integration/microservices/e2e/sum-redis.spec.ts
0
https://github.com/nestjs/nest/commit/94949fee6e498e8f791e8c398bfc837a8223db3e
[ 0.00017343132640235126, 0.00016930245328694582, 0.00016537957708351314, 0.00016973575111478567, 0.0000022626954887527972 ]
{ "id": 0, "code_window": [ "export * from './middleware';\n", "export * from './nest-application';\n", "export * from './nest-application-context';\n", "export { NestFactory } from './nest-factory';\n", "export * from './router';\n", "export * from './services';" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "export * from './application-config';\n" ], "file_path": "packages/core/index.ts", "type": "add", "edit_start_line_idx": 16 }
import { INestApplication } from '@nestjs/common'; import { Test } from '@nestjs/testing'; import * as request from 'supertest'; import { AsyncOptionsExistingModule } from '../src/async-existing-options.module'; describe('Mongoose', () => { let server; let app: INestApplication; beforeEach(async () => { const module = await Test.createTestingModule({ imports: [AsyncOptionsExistingModule], }).compile(); app = module.createNestApplication(); server = app.getHttpServer(); await app.init(); }); it(`should return created entity`, () => { const cat = { name: 'Nest', age: 20, breed: 'Awesome', }; return request(server) .post('/cats') .send(cat) .expect(201) .expect(({ body }) => body.name === cat.name); }); afterEach(async () => { await app.close(); }); });
integration/mongoose/e2e/async-existing-options.spec.ts
0
https://github.com/nestjs/nest/commit/94949fee6e498e8f791e8c398bfc837a8223db3e
[ 0.00016914072330109775, 0.00016830017557367682, 0.00016751514340285212, 0.00016827243962325156, 6.08358845965995e-7 ]
{ "id": 1, "code_window": [ "import { RuntimeException } from '../errors/exceptions/runtime.exception';\n", "import { UnknownExportException } from '../errors/exceptions/unknown-export.exception';\n", "import { NestContainer } from './container';\n", "import { InstanceWrapper } from './instance-wrapper';\n", "import { ModuleRef } from './module-ref';\n", "\n", "interface ProviderName {\n", " name?: string | symbol;\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "import { ApplicationConfig } from '../application-config';\n" ], "file_path": "packages/core/injector/module.ts", "type": "add", "edit_start_line_idx": 29 }
/* * Nest @core * Copyright(c) 2017 - 2019 Kamil Mysliwiec * https://nestjs.com * MIT Licensed */ import 'reflect-metadata'; export * from './adapters'; export { APP_FILTER, APP_GUARD, APP_INTERCEPTOR, APP_PIPE } from './constants'; export * from './exceptions'; export * from './helpers'; export * from './injector'; export * from './middleware'; export * from './nest-application'; export * from './nest-application-context'; export { NestFactory } from './nest-factory'; export * from './router'; export * from './services';
packages/core/index.ts
1
https://github.com/nestjs/nest/commit/94949fee6e498e8f791e8c398bfc837a8223db3e
[ 0.00018024527525994927, 0.0001744704059092328, 0.00016869553655851632, 0.0001744704059092328, 0.000005774869350716472 ]
{ "id": 1, "code_window": [ "import { RuntimeException } from '../errors/exceptions/runtime.exception';\n", "import { UnknownExportException } from '../errors/exceptions/unknown-export.exception';\n", "import { NestContainer } from './container';\n", "import { InstanceWrapper } from './instance-wrapper';\n", "import { ModuleRef } from './module-ref';\n", "\n", "interface ProviderName {\n", " name?: string | symbol;\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "import { ApplicationConfig } from '../application-config';\n" ], "file_path": "packages/core/injector/module.ts", "type": "add", "edit_start_line_idx": 29 }
{ "name": "nest-typescript-starter", "version": "1.0.0", "lockfileVersion": 1, "requires": true, "dependencies": { "@babel/code-frame": { "version": "7.0.0", "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.0.0.tgz", "integrity": "sha512-OfC2uemaknXr87bdLUkWog7nYuliM9Ij5HUcajsVcMCpQrcLmtxRbVFTIqmcSkSeYRBFBRxs2FiUqFJDLdiebA==", "dev": true, "requires": { "@babel/highlight": "^7.0.0" } }, "@babel/highlight": { "version": "7.0.0", "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.0.0.tgz", "integrity": "sha512-UFMC4ZeFC48Tpvj7C8UgLvtkaUuovQX+5xNWrsIoMG8o2z+XFKjKaN9iVmS84dPwVN00W4wPmqvYoZF3EGAsfw==", "dev": true, "requires": { "chalk": "^2.0.0", "esutils": "^2.0.2", "js-tokens": "^4.0.0" } }, "@nestjs/common": { "version": "6.3.1", "resolved": "https://registry.npmjs.org/@nestjs/common/-/common-6.3.1.tgz", "integrity": "sha512-uuI/CCe6MFISMX+fSpkRvvQ6CBlXW89+5wfiveQ22AzAxgqGLAyWvNVHUE8F+zev7QDbxbY9vfPtm8CE5kiJVQ==", "requires": { "axios": "0.19.0", "cli-color": "1.4.0", "uuid": "3.3.2" } }, "@nestjs/core": { "version": "6.3.1", "resolved": "https://registry.npmjs.org/@nestjs/core/-/core-6.3.1.tgz", "integrity": "sha512-GiH64nX5Z/HrHESo0huiSFH894/hzs0qRuSVNSq4MWIgHgTjdFlqu/VcXlPz21pJXhoimegpk1x1wsm2hu+WUw==", "requires": { "@nuxtjs/opencollective": "0.2.2", "fast-safe-stringify": "2.0.6", "iterare": "1.1.2", "object-hash": "1.3.1", "optional": "0.1.4", "uuid": "3.3.2" } }, "@nestjs/platform-express": { "version": "6.3.1", "resolved": "https://registry.npmjs.org/@nestjs/platform-express/-/platform-express-6.3.1.tgz", "integrity": "sha512-vPOkcqhYS+qw5ZJNOp19YnT2uKXB6Phgu5P11AiylE+Cc0eoTSdouVDK4e3I8Lja91VuNN5WSYsODYlJzpMVpA==", "requires": { "body-parser": "1.19.0", "cors": "2.8.5", "express": "4.17.1", "multer": "1.4.1" } }, "@nestjs/typeorm": { "version": "6.1.2", "resolved": "https://registry.npmjs.org/@nestjs/typeorm/-/typeorm-6.1.2.tgz", "integrity": "sha512-uNLvNTW72h4mypvscBgYgE2q8LHgvrhNzV6YqJgvf0VaGv5fi72hl0Zlfwmvh7h50ysW221mJCraX56yn+Uzxw==", "requires": { "uuid": "3.3.2" } }, "@nuxtjs/opencollective": { "version": "0.2.2", "resolved": "https://registry.npmjs.org/@nuxtjs/opencollective/-/opencollective-0.2.2.tgz", "integrity": "sha512-69gFVDs7mJfNjv9Zs5DFVD+pvBW+k1TaHSOqUWqAyTTfLcKI/EMYQgvEvziRd+zAFtUOoye6MfWh0qvinGISPw==", "requires": { "chalk": "^2.4.1", "consola": "^2.3.0", "node-fetch": "^2.3.0" }, "dependencies": { "chalk": { "version": "2.4.2", "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", "requires": { "ansi-styles": "^3.2.1", "escape-string-regexp": "^1.0.5", "supports-color": "^5.3.0" } } } }, "@types/node": { "version": "7.10.6", "resolved": "https://registry.npmjs.org/@types/node/-/node-7.10.6.tgz", "integrity": "sha512-d0BOAicT0tEdbdVQlLGOVul1kvg6YvbaADRCThGCz5NJ0e9r00SofcR1x69hmlCyrHuB6jd4cKzL9bMLjPnpAA==", "dev": true }, "accepts": { "version": "1.3.7", "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.7.tgz", "integrity": "sha512-Il80Qs2WjYlJIBNzNkK6KYqlVMTbZLXgHx2oT0pU/fjRHyEp+PEfEPY0R3WCwAGVOtauxh1hOxNgIf5bv7dQpA==", "requires": { "mime-types": "~2.1.24", "negotiator": "0.6.2" } }, "ansi-regex": { "version": "4.1.0", "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.0.tgz", "integrity": "sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg==" }, "ansi-styles": { "version": "3.2.1", "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", "requires": { "color-convert": "^1.9.0" } }, "any-promise": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/any-promise/-/any-promise-1.3.0.tgz", "integrity": "sha1-q8av7tzqUugJzcA3au0845Y10X8=" }, "app-root-path": { "version": "2.2.1", "resolved": "https://registry.npmjs.org/app-root-path/-/app-root-path-2.2.1.tgz", "integrity": "sha512-91IFKeKk7FjfmezPKkwtaRvSpnUc4gDwPAjA1YZ9Gn0q0PPeW+vbeUsZuyDwjI7+QTHhcLen2v25fi/AmhvbJA==" }, "append-field": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/append-field/-/append-field-1.0.0.tgz", "integrity": "sha1-HjRA6RXwsSA9I3SOeO3XubW0PlY=" }, "arg": { "version": "4.1.0", "resolved": "https://registry.npmjs.org/arg/-/arg-4.1.0.tgz", "integrity": "sha512-ZWc51jO3qegGkVh8Hwpv636EkbesNV5ZNQPCtRa+0qytRYPEs9IYT9qITY9buezqUH5uqyzlWLcufrzU2rffdg==", "dev": true }, "argparse": { "version": "1.0.10", "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", "requires": { "sprintf-js": "~1.0.2" } }, "array-flatten": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz", "integrity": "sha1-ml9pkFGx5wczKPKgCJaLZOopVdI=" }, "axios": { "version": "0.19.0", "resolved": "https://registry.npmjs.org/axios/-/axios-0.19.0.tgz", "integrity": "sha512-1uvKqKQta3KBxIz14F2v06AEHZ/dIoeKfbTRkK1E5oqjDnuEerLmYTgJB5AiQZHJcljpg1TuRzdjDR06qNk0DQ==", "requires": { "follow-redirects": "1.5.10", "is-buffer": "^2.0.2" } }, "balanced-match": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz", "integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c=" }, "base64-js": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.3.0.tgz", "integrity": "sha512-ccav/yGvoa80BQDljCxsmmQ3Xvx60/UpBIij5QN21W3wBi/hhIC9OoO+KLpu9IJTS9j4DRVJ3aDDF9cMSoa2lw==" }, "bignumber.js": { "version": "7.2.1", "resolved": "https://registry.npmjs.org/bignumber.js/-/bignumber.js-7.2.1.tgz", "integrity": "sha512-S4XzBk5sMB+Rcb/LNcpzXr57VRTxgAvaAEDAl1AwRx27j00hT84O6OkteE7u8UB3NuaaygCRrEpqox4uDOrbdQ==" }, "body-parser": { "version": "1.19.0", "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.19.0.tgz", "integrity": "sha512-dhEPs72UPbDnAQJ9ZKMNTP6ptJaionhP5cBb541nXPlW60Jepo9RV/a4fX4XWW9CuFNK22krhrj1+rgzifNCsw==", "requires": { "bytes": "3.1.0", "content-type": "~1.0.4", "debug": "2.6.9", "depd": "~1.1.2", "http-errors": "1.7.2", "iconv-lite": "0.4.24", "on-finished": "~2.3.0", "qs": "6.7.0", "raw-body": "2.4.0", "type-is": "~1.6.17" }, "dependencies": { "debug": { "version": "2.6.9", "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", "requires": { "ms": "2.0.0" } }, "ms": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=" } } }, "brace-expansion": { "version": "1.1.11", "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", "requires": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" } }, "buffer": { "version": "5.2.1", "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.2.1.tgz", "integrity": "sha512-c+Ko0loDaFfuPWiL02ls9Xd3GO3cPVmUobQ6t3rXNUk304u6hGq+8N/kFi+QEIKhzK3uwolVhLzszmfLmMLnqg==", "requires": { "base64-js": "^1.0.2", "ieee754": "^1.1.4" } }, "buffer-from": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.0.tgz", "integrity": "sha512-c5mRlguI/Pe2dSZmpER62rSCu0ryKmWddzRYsuXc50U2/g8jMOulc31VZMa4mYx31U5xsmSOpDCgH88Vl9cDGQ==" }, "builtin-modules": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/builtin-modules/-/builtin-modules-1.1.1.tgz", "integrity": "sha1-Jw8HbFpywC9bZaR9+Uxf46J4iS8=", "dev": true }, "busboy": { "version": "0.2.14", "resolved": "https://registry.npmjs.org/busboy/-/busboy-0.2.14.tgz", "integrity": "sha1-bCpiLvz0fFe7vh4qnDetNseSVFM=", "requires": { "dicer": "0.2.5", "readable-stream": "1.1.x" } }, "bytes": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.0.tgz", "integrity": "sha512-zauLjrfCG+xvoyaqLoV8bLVXXNGC4JqlxFCutSDWA6fJrTo2ZuvLYTqZ7aHBLZSMOopbzwv8f+wZcVzfVTI2Dg==" }, "camelcase": { "version": "5.3.1", "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz", "integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==" }, "chalk": { "version": "2.3.2", "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.3.2.tgz", "integrity": "sha512-ZM4j2/ld/YZDc3Ma8PgN7gyAk+kHMMMyzLNryCPGhWrsfAuDVeuid5bpRFTDgMH9JBK2lA4dyyAkkZYF/WcqDQ==", "requires": { "ansi-styles": "^3.2.1", "escape-string-regexp": "^1.0.5", "supports-color": "^5.3.0" } }, "cli-color": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/cli-color/-/cli-color-1.4.0.tgz", "integrity": "sha512-xu6RvQqqrWEo6MPR1eixqGPywhYBHRs653F9jfXB2Hx4jdM/3WxiNE1vppRmxtMIfl16SFYTpYlrnqH/HsK/2w==", "requires": { "ansi-regex": "^2.1.1", "d": "1", "es5-ext": "^0.10.46", "es6-iterator": "^2.0.3", "memoizee": "^0.4.14", "timers-ext": "^0.1.5" }, "dependencies": { "ansi-regex": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=" } } }, "cli-highlight": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/cli-highlight/-/cli-highlight-2.1.1.tgz", "integrity": "sha512-0y0VlNmdD99GXZHYnvrQcmHxP8Bi6T00qucGgBgGv4kJ0RyDthNnnFPupHV7PYv/OXSVk+azFbOeaW6+vGmx9A==", "requires": { "chalk": "^2.3.0", "highlight.js": "^9.6.0", "mz": "^2.4.0", "parse5": "^4.0.0", "yargs": "^13.0.0" } }, "cliui": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/cliui/-/cliui-5.0.0.tgz", "integrity": "sha512-PYeGSEmmHM6zvoef2w8TPzlrnNpXIjTipYK780YswmIP9vjxmd6Y2a3CB2Ks6/AU8NHjZugXvo8w3oWM2qnwXA==", "requires": { "string-width": "^3.1.0", "strip-ansi": "^5.2.0", "wrap-ansi": "^5.1.0" } }, "color-convert": { "version": "1.9.1", "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.1.tgz", "integrity": "sha512-mjGanIiwQJskCC18rPR6OmrZ6fm2Lc7PeGFYwCmy5J34wC6F1PzdGL6xeMfmgicfYcNLGuVFA3WzXtIDCQSZxQ==", "requires": { "color-name": "^1.1.1" } }, "color-name": { "version": "1.1.3", "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", "integrity": "sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=" }, "commander": { "version": "2.20.0", "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.0.tgz", "integrity": "sha512-7j2y+40w61zy6YC2iRNpUe/NwhNyoXrYpHMrSunaMG64nRnaf96zO/KMQR4OyN/UnE5KLyEBnKHd4aG3rskjpQ==", "dev": true }, "concat-map": { "version": "0.0.1", "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=" }, "concat-stream": { "version": "1.6.2", "resolved": "https://registry.npmjs.org/concat-stream/-/concat-stream-1.6.2.tgz", "integrity": "sha512-27HBghJxjiZtIk3Ycvn/4kbJk/1uZuJFfuPEns6LaEvpvG1f0hTea8lilrouyo9mVc2GWdcEZ8OLoGmSADlrCw==", "requires": { "buffer-from": "^1.0.0", "inherits": "^2.0.3", "readable-stream": "^2.2.2", "typedarray": "^0.0.6" }, "dependencies": { "readable-stream": { "version": "2.3.6", "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.6.tgz", "integrity": "sha512-tQtKA9WIAhBF3+VLAseyMqZeBjW0AHJoxOtYqSUZNJxauErmLbVm2FW1y+J/YA9dUrAC39ITejlZWhVIwawkKw==", "requires": { "core-util-is": "~1.0.0", "inherits": "~2.0.3", "isarray": "~1.0.0", "process-nextick-args": "~2.0.0", "safe-buffer": "~5.1.1", "string_decoder": "~1.1.1", "util-deprecate": "~1.0.1" } }, "string_decoder": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", "requires": { "safe-buffer": "~5.1.0" } } } }, "consola": { "version": "2.7.1", "resolved": "https://registry.npmjs.org/consola/-/consola-2.7.1.tgz", "integrity": "sha512-u7JYs+HnMbZPD2cEuS1XHsLeqtazA0kd5lAk8r8DnnGdgNhOdb7DSubJ+QLdQkbtpmmxgp7gs8Ug44sCyY4FCQ==" }, "content-disposition": { "version": "0.5.3", "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.3.tgz", "integrity": "sha512-ExO0774ikEObIAEV9kDo50o+79VCUdEB6n6lzKgGwupcVeRlhrj3qGAfwq8G6uBJjkqLrhT0qEYFcWng8z1z0g==", "requires": { "safe-buffer": "5.1.2" } }, "content-type": { "version": "1.0.4", "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.4.tgz", "integrity": "sha512-hIP3EEPs8tB9AT1L+NUqtwOAps4mk2Zob89MWXMHjHWg9milF/j4osnnQLXBCBFBk/tvIG/tUc9mOUJiPBhPXA==" }, "cookie": { "version": "0.4.0", "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.4.0.tgz", "integrity": "sha512-+Hp8fLp57wnUSt0tY0tHEXh4voZRDnoIrZPqlo3DPiI4y9lwg/jqx+1Om94/W6ZaPDOUbnjOt/99w66zk+l1Xg==" }, "cookie-signature": { "version": "1.0.6", "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz", "integrity": "sha1-4wOogrNCzD7oylE6eZmXNNqzriw=" }, "core-util-is": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz", "integrity": "sha1-tf1UIgqivFq1eqtxQMlAdUUDwac=" }, "cors": { "version": "2.8.5", "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.5.tgz", "integrity": "sha512-KIHbLJqu73RGr/hnbrO9uBeixNGuvSQjul/jdFvS/KFSIH1hWVd1ng7zOHx+YrEfInLG7q4n6GHQ9cDtxv/P6g==", "requires": { "object-assign": "^4", "vary": "^1" } }, "cross-spawn": { "version": "6.0.5", "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-6.0.5.tgz", "integrity": "sha512-eTVLrBSt7fjbDygz805pMnstIs2VTBNkRm0qxZd+M7A5XDdxVRWO5MxGBXZhjY4cqLYLdtrGqRf8mBPmzwSpWQ==", "requires": { "nice-try": "^1.0.4", "path-key": "^2.0.1", "semver": "^5.5.0", "shebang-command": "^1.2.0", "which": "^1.2.9" } }, "d": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/d/-/d-1.0.0.tgz", "integrity": "sha1-dUu1v+VUUdpppYuU1F9MWwRi1Y8=", "requires": { "es5-ext": "^0.10.9" } }, "debug": { "version": "4.1.1", "resolved": "https://registry.npmjs.org/debug/-/debug-4.1.1.tgz", "integrity": "sha512-pYAIzeRo8J6KPEaJ0VWOh5Pzkbw/RetuzehGM7QRRX5he4fPHx2rdKMB256ehJCkX+XRQm16eZLqLNS8RSZXZw==", "requires": { "ms": "^2.1.1" } }, "decamelize": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/decamelize/-/decamelize-1.2.0.tgz", "integrity": "sha1-9lNNFRSCabIDUue+4m9QH5oZEpA=" }, "depd": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/depd/-/depd-1.1.2.tgz", "integrity": "sha1-m81S4UwJd2PnSbJ0xDRu0uVgtak=" }, "destroy": { "version": "1.0.4", "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.0.4.tgz", "integrity": "sha1-l4hXRCxEdJ5CBmE+N5RiBYJqvYA=" }, "dicer": { "version": "0.2.5", "resolved": "https://registry.npmjs.org/dicer/-/dicer-0.2.5.tgz", "integrity": "sha1-WZbAhrszIYyBLAkL3cCc0S+stw8=", "requires": { "readable-stream": "1.1.x", "streamsearch": "0.1.2" } }, "diff": { "version": "3.5.0", "resolved": "https://registry.npmjs.org/diff/-/diff-3.5.0.tgz", "integrity": "sha512-A46qtFgd+g7pDZinpnwiRJtxbC1hpgf0uzP3iG89scHk0AUC7A1TGxf5OiiOUv/JMZR8GOt8hL900hV0bOy5xA==", "dev": true }, "dotenv": { "version": "6.2.0", "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-6.2.0.tgz", "integrity": "sha512-HygQCKUBSFl8wKQZBSemMywRWcEDNidvNbjGVyZu3nbZ8qq9ubiPoGLMdRDpfSrpkkm9BXYFkpKxxFX38o/76w==" }, "ee-first": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", "integrity": "sha1-WQxhFWsK4vTwJVcyoViyZrxWsh0=" }, "emoji-regex": { "version": "7.0.3", "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-7.0.3.tgz", "integrity": "sha512-CwBLREIQ7LvYFB0WyRvwhq5N5qPhc6PMjD6bYggFlI5YyDgl+0vxq5VHbMOFqLg7hfWzmu8T5Z1QofhmTIhItA==" }, "encodeurl": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz", "integrity": "sha1-rT/0yG7C0CkyL1oCw6mmBslbP1k=" }, "end-of-stream": { "version": "1.4.1", "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.1.tgz", "integrity": "sha512-1MkrZNvWTKCaigbn+W15elq2BB/L22nqrSY5DKlo3X6+vclJm8Bb5djXJBmEX6fS3+zCh/F4VBK5Z2KxJt4s2Q==", "requires": { "once": "^1.4.0" } }, "es5-ext": { "version": "0.10.50", "resolved": "https://registry.npmjs.org/es5-ext/-/es5-ext-0.10.50.tgz", "integrity": "sha512-KMzZTPBkeQV/JcSQhI5/z6d9VWJ3EnQ194USTUwIYZ2ZbpN8+SGXQKt1h68EX44+qt+Fzr8DO17vnxrw7c3agw==", "requires": { "es6-iterator": "~2.0.3", "es6-symbol": "~3.1.1", "next-tick": "^1.0.0" } }, "es6-iterator": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/es6-iterator/-/es6-iterator-2.0.3.tgz", "integrity": "sha1-p96IkUGgWpSwhUQDstCg+/qY87c=", "requires": { "d": "1", "es5-ext": "^0.10.35", "es6-symbol": "^3.1.1" } }, "es6-symbol": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/es6-symbol/-/es6-symbol-3.1.1.tgz", "integrity": "sha1-vwDvT9q2uhtG7Le2KbTH7VcVzHc=", "requires": { "d": "1", "es5-ext": "~0.10.14" } }, "es6-weak-map": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/es6-weak-map/-/es6-weak-map-2.0.2.tgz", "integrity": "sha1-XjqzIlH/0VOKH45f+hNXdy+S2W8=", "requires": { "d": "1", "es5-ext": "^0.10.14", "es6-iterator": "^2.0.1", "es6-symbol": "^3.1.1" } }, "escape-html": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", "integrity": "sha1-Aljq5NPQwJdN4cFpGI7wBR0dGYg=" }, "escape-string-regexp": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=" }, "esprima": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.0.tgz", "integrity": "sha512-oftTcaMu/EGrEIu904mWteKIv8vMuOgGYo7EhVJJN00R/EED9DCua/xxHRdYnKtcECzVg7xOWhflvJMnqcFZjw==" }, "esutils": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.2.tgz", "integrity": "sha1-Cr9PHKpbyx96nYrMbepPqqBLrJs=", "dev": true }, "etag": { "version": "1.8.1", "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", "integrity": "sha1-Qa4u62XvpiJorr/qg6x9eSmbCIc=" }, "event-emitter": { "version": "0.3.5", "resolved": "https://registry.npmjs.org/event-emitter/-/event-emitter-0.3.5.tgz", "integrity": "sha1-34xp7vFkeSPHFXuc6DhAYQsCzDk=", "requires": { "d": "1", "es5-ext": "~0.10.14" } }, "execa": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/execa/-/execa-1.0.0.tgz", "integrity": "sha512-adbxcyWV46qiHyvSp50TKt05tB4tK3HcmF7/nxfAdhnox83seTDbwnaqKO4sXRy7roHAIFqJP/Rw/AuEbX61LA==", "requires": { "cross-spawn": "^6.0.0", "get-stream": "^4.0.0", "is-stream": "^1.1.0", "npm-run-path": "^2.0.0", "p-finally": "^1.0.0", "signal-exit": "^3.0.0", "strip-eof": "^1.0.0" } }, "express": { "version": "4.17.1", "resolved": "https://registry.npmjs.org/express/-/express-4.17.1.tgz", "integrity": "sha512-mHJ9O79RqluphRrcw2X/GTh3k9tVv8YcoyY4Kkh4WDMUYKRZUq0h1o0w2rrrxBqM7VoeUVqgb27xlEMXTnYt4g==", "requires": { "accepts": "~1.3.7", "array-flatten": "1.1.1", "body-parser": "1.19.0", "content-disposition": "0.5.3", "content-type": "~1.0.4", "cookie": "0.4.0", "cookie-signature": "1.0.6", "debug": "2.6.9", "depd": "~1.1.2", "encodeurl": "~1.0.2", "escape-html": "~1.0.3", "etag": "~1.8.1", "finalhandler": "~1.1.2", "fresh": "0.5.2", "merge-descriptors": "1.0.1", "methods": "~1.1.2", "on-finished": "~2.3.0", "parseurl": "~1.3.3", "path-to-regexp": "0.1.7", "proxy-addr": "~2.0.5", "qs": "6.7.0", "range-parser": "~1.2.1", "safe-buffer": "5.1.2", "send": "0.17.1", "serve-static": "1.14.1", "setprototypeof": "1.1.1", "statuses": "~1.5.0", "type-is": "~1.6.18", "utils-merge": "1.0.1", "vary": "~1.1.2" }, "dependencies": { "debug": { "version": "2.6.9", "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", "requires": { "ms": "2.0.0" } }, "ms": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=" } } }, "fast-safe-stringify": { "version": "2.0.6", "resolved": "https://registry.npmjs.org/fast-safe-stringify/-/fast-safe-stringify-2.0.6.tgz", "integrity": "sha512-q8BZ89jjc+mz08rSxROs8VsrBBcn1SIw1kq9NjolL509tkABRk9io01RAjSaEv1Xb2uFLt8VtRiZbGp5H8iDtg==" }, "figlet": { "version": "1.2.3", "resolved": "https://registry.npmjs.org/figlet/-/figlet-1.2.3.tgz", "integrity": "sha512-+F5zdvZ66j77b8x2KCPvWUHC0UCKUMWrewxmewgPlagp3wmDpcrHMbyv/ygq/6xoxBPGQA+UJU3SMoBzKoROQQ==" }, "finalhandler": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.1.2.tgz", "integrity": "sha512-aAWcW57uxVNrQZqFXjITpW3sIUQmHGG3qSb9mUah9MgMC4NeWhNOlNjXEYq3HjRAvL6arUviZGGJsBg6z0zsWA==", "requires": { "debug": "2.6.9", "encodeurl": "~1.0.2", "escape-html": "~1.0.3", "on-finished": "~2.3.0", "parseurl": "~1.3.3", "statuses": "~1.5.0", "unpipe": "~1.0.0" }, "dependencies": { "debug": { "version": "2.6.9", "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", "requires": { "ms": "2.0.0" } }, "ms": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=" } } }, "find-up": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/find-up/-/find-up-3.0.0.tgz", "integrity": "sha512-1yD6RmLI1XBfxugvORwlck6f75tYL+iR0jqwsOrOxMZyGYqUuDhJ0l4AXdO1iX/FTs9cBAMEk1gWSEx1kSbylg==", "requires": { "locate-path": "^3.0.0" } }, "follow-redirects": { "version": "1.5.10", "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.5.10.tgz", "integrity": "sha512-0V5l4Cizzvqt5D44aTXbFZz+FtyXV1vrDN6qrelxtfYQKW0KO0W2T/hkE8xvGa/540LkZlkaUjO4ailYTFtHVQ==", "requires": { "debug": "=3.1.0" }, "dependencies": { "debug": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/debug/-/debug-3.1.0.tgz", "integrity": "sha512-OX8XqP7/1a9cqkxYw2yXss15f26NKWBpDXQd0/uK/KPqdQhxbPa994hnzjcE2VqQpDslf55723cKPUOGSmMY3g==", "requires": { "ms": "2.0.0" } }, "ms": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=" } } }, "forwarded": { "version": "0.1.2", "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.1.2.tgz", "integrity": "sha1-mMI9qxF1ZXuMBXPozszZGw/xjIQ=" }, "fresh": { "version": "0.5.2", "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz", "integrity": "sha1-PYyt2Q2XZWn6g1qx+OSyOhBWBac=" }, "fs.realpath": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", "integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=" }, "get-caller-file": { "version": "2.0.5", "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==" }, "get-stream": { "version": "4.1.0", "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-4.1.0.tgz", "integrity": "sha512-GMat4EJ5161kIy2HevLlr4luNjBgvmj413KaQA7jt4V8B4RDsfpHk7WQ9GVqfYyyx8OS/L66Kox+rJRNklLK7w==", "requires": { "pump": "^3.0.0" } }, "glob": { "version": "7.1.2", "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.2.tgz", "integrity": "sha512-MJTUg1kjuLeQCJ+ccE4Vpa6kKVXkPYJ2mOCQyUuKLcLQsdrMCpBPUi8qVE6+YuaJkozeA9NusTAw3hLr8Xe5EQ==", "requires": { "fs.realpath": "^1.0.0", "inflight": "^1.0.4", "inherits": "2", "minimatch": "^3.0.4", "once": "^1.3.0", "path-is-absolute": "^1.0.0" } }, "has-ansi": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/has-ansi/-/has-ansi-2.0.0.tgz", "integrity": "sha1-NPUEnOHs3ysGSa8+8k5F7TVBbZE=", "requires": { "ansi-regex": "^2.0.0" }, "dependencies": { "ansi-regex": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=" } } }, "has-flag": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=" }, "highlight.js": { "version": "9.15.8", "resolved": "https://registry.npmjs.org/highlight.js/-/highlight.js-9.15.8.tgz", "integrity": "sha512-RrapkKQWwE+wKdF73VsOa2RQdIoO3mxwJ4P8mhbI6KYJUraUHRKM5w5zQQKXNk0xNL4UVRdulV9SBJcmzJNzVA==" }, "http-errors": { "version": "1.7.2", "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-1.7.2.tgz", "integrity": "sha512-uUQBt3H/cSIVfch6i1EuPNy/YsRSOUBXTVfZ+yR7Zjez3qjBz6i9+i4zjNaoqcoFVI4lQJ5plg63TvGfRSDCRg==", "requires": { "depd": "~1.1.2", "inherits": "2.0.3", "setprototypeof": "1.1.1", "statuses": ">= 1.5.0 < 2", "toidentifier": "1.0.0" } }, "iconv-lite": { "version": "0.4.24", "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", "requires": { "safer-buffer": ">= 2.1.2 < 3" } }, "ieee754": { "version": "1.1.13", "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.1.13.tgz", "integrity": "sha512-4vf7I2LYV/HaWerSo3XmlMkp5eZ83i+/CDluXi/IGTs/O1sejBNhTtnxzmRZfvOUqj7lZjqHkeTvpgSFDlWZTg==" }, "inflight": { "version": "1.0.6", "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", "integrity": "sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=", "requires": { "once": "^1.3.0", "wrappy": "1" } }, "inherits": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz", "integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=" }, "invert-kv": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/invert-kv/-/invert-kv-2.0.0.tgz", "integrity": "sha512-wPVv/y/QQ/Uiirj/vh3oP+1Ww+AWehmi1g5fFWGPF6IpCBCDVrhgHRMvrLfdYcwDh3QJbGXDW4JAuzxElLSqKA==" }, "ipaddr.js": { "version": "1.9.0", "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.0.tgz", "integrity": "sha512-M4Sjn6N/+O6/IXSJseKqHoFc+5FdGJ22sXqnjTpdZweHK64MzEPAyQZyEU3R/KRv2GLoa7nNtg/C2Ev6m7z+eA==" }, "is-buffer": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/is-buffer/-/is-buffer-2.0.3.tgz", "integrity": "sha512-U15Q7MXTuZlrbymiz95PJpZxu8IlipAp4dtS3wOdgPXx3mqBnslrWU14kxfHB+Py/+2PVKSr37dMAgM2A4uArw==" }, "is-fullwidth-code-point": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz", "integrity": "sha1-o7MKXE8ZkYMWeqq5O+764937ZU8=" }, "is-promise": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-2.1.0.tgz", "integrity": "sha1-eaKp7OfwlugPNtKy87wWwf9L8/o=" }, "is-stream": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-1.1.0.tgz", "integrity": "sha1-EtSj3U5o4Lec6428hBc66A2RykQ=" }, "isarray": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", "integrity": "sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE=" }, "isexe": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", "integrity": "sha1-6PvzdNxVb/iUehDcsFctYz8s+hA=" }, "iterare": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/iterare/-/iterare-1.1.2.tgz", "integrity": "sha512-25rVYmj/dDvTR6zOa9jY1Ihd6USLa0J508Ub2iy7Aga+xu9JMbjDds2Uh03ReDGbva/YN3s3Ybi+Do0nOX6wAg==" }, "js-tokens": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", "dev": true }, "js-yaml": { "version": "3.13.1", "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.13.1.tgz", "integrity": "sha512-YfbcO7jXDdyj0DGxYVSlSeQNHbD7XPWvrVWeVUujrQEoZzWJIRrCPoyk6kL6IAjAG2IolMK4T0hNUe0HOUs5Jw==", "requires": { "argparse": "^1.0.7", "esprima": "^4.0.0" } }, "lcid": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/lcid/-/lcid-2.0.0.tgz", "integrity": "sha512-avPEb8P8EGnwXKClwsNUgryVjllcRqtMYa49NTsbQagYuT1DcXnl1915oxWjoyGrXR6zH/Y0Zc96xWsPcoDKeA==", "requires": { "invert-kv": "^2.0.0" } }, "locate-path": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-3.0.0.tgz", "integrity": "sha512-7AO748wWnIhNqAuaty2ZWHkQHRSNfPVIsPIfwEOWO22AmaoVrWavlOcMR5nzTLNYvp36X220/maaRsrec1G65A==", "requires": { "p-locate": "^3.0.0", "path-exists": "^3.0.0" } }, "lru-queue": { "version": "0.1.0", "resolved": "https://registry.npmjs.org/lru-queue/-/lru-queue-0.1.0.tgz", "integrity": "sha1-Jzi9nw089PhEkMVzbEhpmsYyzaM=", "requires": { "es5-ext": "~0.10.2" } }, "make-error": { "version": "1.3.5", "resolved": "https://registry.npmjs.org/make-error/-/make-error-1.3.5.tgz", "integrity": "sha512-c3sIjNUow0+8swNwVpqoH4YCShKNFkMaw6oH1mNS2haDZQqkeZFlHS3dhoeEbKKmJB4vXpJucU6oH75aDYeE9g==", "dev": true }, "map-age-cleaner": { "version": "0.1.3", "resolved": "https://registry.npmjs.org/map-age-cleaner/-/map-age-cleaner-0.1.3.tgz", "integrity": "sha512-bJzx6nMoP6PDLPBFmg7+xRKeFZvFboMrGlxmNj9ClvX53KrmvM5bXFXEWjbz4cz1AFn+jWJ9z/DJSz7hrs0w3w==", "requires": { "p-defer": "^1.0.0" } }, "media-typer": { "version": "0.3.0", "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", "integrity": "sha1-hxDXrwqmJvj/+hzgAWhUUmMlV0g=" }, "mem": { "version": "4.3.0", "resolved": "https://registry.npmjs.org/mem/-/mem-4.3.0.tgz", "integrity": "sha512-qX2bG48pTqYRVmDB37rn/6PT7LcR8T7oAX3bf99u1Tt1nzxYfxkgqDwUwolPlXweM0XzBOBFzSx4kfp7KP1s/w==", "requires": { "map-age-cleaner": "^0.1.1", "mimic-fn": "^2.0.0", "p-is-promise": "^2.0.0" } }, "memoizee": { "version": "0.4.14", "resolved": "https://registry.npmjs.org/memoizee/-/memoizee-0.4.14.tgz", "integrity": "sha512-/SWFvWegAIYAO4NQMpcX+gcra0yEZu4OntmUdrBaWrJncxOqAziGFlHxc7yjKVK2uu3lpPW27P27wkR82wA8mg==", "requires": { "d": "1", "es5-ext": "^0.10.45", "es6-weak-map": "^2.0.2", "event-emitter": "^0.3.5", "is-promise": "^2.1", "lru-queue": "0.1", "next-tick": "1", "timers-ext": "^0.1.5" } }, "merge-descriptors": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.1.tgz", "integrity": "sha1-sAqqVW3YtEVoFQ7J0blT8/kMu2E=" }, "methods": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz", "integrity": "sha1-VSmk1nZUE07cxSZmVoNbD4Ua/O4=" }, "mime": { "version": "1.6.0", "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz", "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==" }, "mime-db": { "version": "1.40.0", "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.40.0.tgz", "integrity": "sha512-jYdeOMPy9vnxEqFRRo6ZvTZ8d9oPb+k18PKoYNYUe2stVEBPPwsln/qWzdbmaIvnhZ9v2P+CuecK+fpUfsV2mA==" }, "mime-types": { "version": "2.1.24", "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.24.tgz", "integrity": "sha512-WaFHS3MCl5fapm3oLxU4eYDw77IQM2ACcxQ9RIxfaC3ooc6PFuBMGZZsYpvoXS5D5QTWPieo1jjLdAm3TBP3cQ==", "requires": { "mime-db": "1.40.0" } }, "mimic-fn": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz", "integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==" }, "minimatch": { "version": "3.0.4", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz", "integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==", "requires": { "brace-expansion": "^1.1.7" } }, "minimist": { "version": "0.0.8", "resolved": "https://registry.npmjs.org/minimist/-/minimist-0.0.8.tgz", "integrity": "sha1-hX/Kv8M5fSYluCKCYuhqp6ARsF0=" }, "mkdirp": { "version": "0.5.1", "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.1.tgz", "integrity": "sha1-MAV0OOrGz3+MR2fzhkjWaX11yQM=", "requires": { "minimist": "0.0.8" } }, "ms": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.1.tgz", "integrity": "sha512-tgp+dl5cGk28utYktBsrFqA7HKgrhgPsg6Z/EfhWI4gl1Hwq8B/GmY/0oXZ6nF8hDVesS/FpnYaD/kOWhYQvyg==" }, "multer": { "version": "1.4.1", "resolved": "https://registry.npmjs.org/multer/-/multer-1.4.1.tgz", "integrity": "sha512-zzOLNRxzszwd+61JFuAo0fxdQfvku12aNJgnla0AQ+hHxFmfc/B7jBVuPr5Rmvu46Jze/iJrFpSOsD7afO8SDw==", "requires": { "append-field": "^1.0.0", "busboy": "^0.2.11", "concat-stream": "^1.5.2", "mkdirp": "^0.5.1", "object-assign": "^4.1.1", "on-finished": "^2.3.0", "type-is": "^1.6.4", "xtend": "^4.0.0" } }, "mysql": { "version": "2.17.1", "resolved": "https://registry.npmjs.org/mysql/-/mysql-2.17.1.tgz", "integrity": "sha512-7vMqHQ673SAk5C8fOzTG2LpPcf3bNt0oL3sFpxPEEFp1mdlDcrLK0On7z8ZYKaaHrHwNcQ/MTUz7/oobZ2OyyA==", "requires": { "bignumber.js": "7.2.1", "readable-stream": "2.3.6", "safe-buffer": "5.1.2", "sqlstring": "2.3.1" }, "dependencies": { "readable-stream": { "version": "2.3.6", "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.6.tgz", "integrity": "sha512-tQtKA9WIAhBF3+VLAseyMqZeBjW0AHJoxOtYqSUZNJxauErmLbVm2FW1y+J/YA9dUrAC39ITejlZWhVIwawkKw==", "requires": { "core-util-is": "~1.0.0", "inherits": "~2.0.3", "isarray": "~1.0.0", "process-nextick-args": "~2.0.0", "safe-buffer": "~5.1.1", "string_decoder": "~1.1.1", "util-deprecate": "~1.0.1" } }, "string_decoder": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", "requires": { "safe-buffer": "~5.1.0" } } } }, "mz": { "version": "2.7.0", "resolved": "https://registry.npmjs.org/mz/-/mz-2.7.0.tgz", "integrity": "sha512-z81GNO7nnYMEhrGh9LeymoE4+Yr0Wn5McHIZMK5cfQCl+NDX08sCZgUc9/6MHni9IWuFLm1Z3HTCXu2z9fN62Q==", "requires": { "any-promise": "^1.0.0", "object-assign": "^4.0.1", "thenify-all": "^1.0.0" } }, "negotiator": { "version": "0.6.2", "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.2.tgz", "integrity": "sha512-hZXc7K2e+PgeI1eDBe/10Ard4ekbfrrqG8Ep+8Jmf4JID2bNg7NvCPOZN+kfF574pFQI7mum2AUqDidoKqcTOw==" }, "next-tick": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/next-tick/-/next-tick-1.0.0.tgz", "integrity": "sha1-yobR/ogoFpsBICCOPchCS524NCw=" }, "nice-try": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/nice-try/-/nice-try-1.0.5.tgz", "integrity": "sha512-1nh45deeb5olNY7eX82BkPO7SSxR5SSYJiPTrTdFUVYwAl8CKMA5N9PjTYkHiRjisVcxcQ1HXdLhx2qxxJzLNQ==" }, "node-fetch": { "version": "2.6.0", "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.0.tgz", "integrity": "sha512-8dG4H5ujfvFiqDmVu9fQ5bOHUC15JMjMY/Zumv26oOvvVJjM67KF8koCWIabKQ1GJIa9r2mMZscBq/TbdOcmNA==" }, "npm-run-path": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-2.0.2.tgz", "integrity": "sha1-NakjLfo11wZ7TLLd8jV7GHFTbF8=", "requires": { "path-key": "^2.0.0" } }, "object-assign": { "version": "4.1.1", "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", "integrity": "sha1-IQmtx5ZYh8/AXLvUQsrIv7s2CGM=" }, "object-hash": { "version": "1.3.1", "resolved": "https://registry.npmjs.org/object-hash/-/object-hash-1.3.1.tgz", "integrity": "sha512-OSuu/pU4ENM9kmREg0BdNrUDIl1heYa4mBZacJc+vVWz4GtAwu7jO8s4AIt2aGRUTqxykpWzI3Oqnsm13tTMDA==" }, "on-finished": { "version": "2.3.0", "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.3.0.tgz", "integrity": "sha1-IPEzZIGwg811M3mSoWlxqi2QaUc=", "requires": { "ee-first": "1.1.1" } }, "once": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", "integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=", "requires": { "wrappy": "1" } }, "optional": { "version": "0.1.4", "resolved": "https://registry.npmjs.org/optional/-/optional-0.1.4.tgz", "integrity": "sha512-gtvrrCfkE08wKcgXaVwQVgwEQ8vel2dc5DDBn9RLQZ3YtmtkBss6A2HY6BnJH4N/4Ku97Ri/SF8sNWE2225WJw==" }, "os-locale": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/os-locale/-/os-locale-3.1.0.tgz", "integrity": "sha512-Z8l3R4wYWM40/52Z+S265okfFj8Kt2cC2MKY+xNi3kFs+XGI7WXu/I309QQQYbRW4ijiZ+yxs9pqEhJh0DqW3Q==", "requires": { "execa": "^1.0.0", "lcid": "^2.0.0", "mem": "^4.0.0" } }, "p-defer": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/p-defer/-/p-defer-1.0.0.tgz", "integrity": "sha1-n26xgvbJqozXQwBKfU+WsZaw+ww=" }, "p-finally": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/p-finally/-/p-finally-1.0.0.tgz", "integrity": "sha1-P7z7FbiZpEEjs0ttzBi3JDNqLK4=" }, "p-is-promise": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/p-is-promise/-/p-is-promise-2.1.0.tgz", "integrity": "sha512-Y3W0wlRPK8ZMRbNq97l4M5otioeA5lm1z7bkNkxCka8HSPjR0xRWmpCmc9utiaLP9Jb1eD8BgeIxTW4AIF45Pg==" }, "p-limit": { "version": "2.2.0", "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.2.0.tgz", "integrity": "sha512-pZbTJpoUsCzV48Mc9Nh51VbwO0X9cuPFE8gYwx9BTCt9SF8/b7Zljd2fVgOxhIF/HDTKgpVzs+GPhyKfjLLFRQ==", "requires": { "p-try": "^2.0.0" } }, "p-locate": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-3.0.0.tgz", "integrity": "sha512-x+12w/To+4GFfgJhBEpiDcLozRJGegY+Ei7/z0tSLkMmxGZNybVMSfWj9aJn8Z5Fc7dBUNJOOVgPv2H7IwulSQ==", "requires": { "p-limit": "^2.0.0" } }, "p-try": { "version": "2.2.0", "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz", "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==" }, "parent-require": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/parent-require/-/parent-require-1.0.0.tgz", "integrity": "sha1-dGoWdjgIOoYLDu9nMssn7UbDKXc=" }, "parse5": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/parse5/-/parse5-4.0.0.tgz", "integrity": "sha512-VrZ7eOd3T1Fk4XWNXMgiGBK/z0MG48BWG2uQNU4I72fkQuKUTZpl+u9k+CxEG0twMVzSmXEEz12z5Fnw1jIQFA==" }, "parseurl": { "version": "1.3.3", "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==" }, "path-exists": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-3.0.0.tgz", "integrity": "sha1-zg6+ql94yxiSXqfYENe1mwEP1RU=" }, "path-is-absolute": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", "integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=" }, "path-key": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/path-key/-/path-key-2.0.1.tgz", "integrity": "sha1-QRyttXTFoUDTpLGRDUDYDMn0C0A=" }, "path-parse": { "version": "1.0.6", "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.6.tgz", "integrity": "sha512-GSmOT2EbHrINBf9SR7CDELwlJ8AENk3Qn7OikK4nFYAu3Ote2+JYNVvkpAEQm3/TLNEJFD/xZJjzyxg3KBWOzw==", "dev": true }, "path-to-regexp": { "version": "0.1.7", "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.7.tgz", "integrity": "sha1-32BBeABfUi8V60SQ5yR6G/qmf4w=" }, "process-nextick-args": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.0.tgz", "integrity": "sha512-MtEC1TqN0EU5nephaJ4rAtThHtC86dNN9qCuEhtshvpVBkAW5ZO7BASN9REnF9eoXGcRub+pFuKEpOHE+HbEMw==" }, "proxy-addr": { "version": "2.0.5", "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.5.tgz", "integrity": "sha512-t/7RxHXPH6cJtP0pRG6smSr9QJidhB+3kXu0KgXnbGYMgzEnUxRQ4/LDdfOwZEMyIh3/xHb8PX3t+lfL9z+YVQ==", "requires": { "forwarded": "~0.1.2", "ipaddr.js": "1.9.0" } }, "pump": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.0.tgz", "integrity": "sha512-LwZy+p3SFs1Pytd/jYct4wpv49HiYCqd9Rlc5ZVdk0V+8Yzv6jR5Blk3TRmPL1ft69TxP0IMZGJ+WPFU2BFhww==", "requires": { "end-of-stream": "^1.1.0", "once": "^1.3.1" } }, "qs": { "version": "6.7.0", "resolved": "https://registry.npmjs.org/qs/-/qs-6.7.0.tgz", "integrity": "sha512-VCdBRNFTX1fyE7Nb6FYoURo/SPe62QCaAyzJvUjwRaIsc+NePBEniHlvxFmmX56+HZphIGtV0XeCirBtpDrTyQ==" }, "range-parser": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==" }, "raw-body": { "version": "2.4.0", "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.4.0.tgz", "integrity": "sha512-4Oz8DUIwdvoa5qMJelxipzi/iJIi40O5cGV1wNYp5hvZP8ZN0T+jiNkL0QepXs+EsQ9XJ8ipEDoiH70ySUJP3Q==", "requires": { "bytes": "3.1.0", "http-errors": "1.7.2", "iconv-lite": "0.4.24", "unpipe": "1.0.0" } }, "readable-stream": { "version": "1.1.14", "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-1.1.14.tgz", "integrity": "sha1-fPTFTvZI44EwhMY23SB54WbAgdk=", "requires": { "core-util-is": "~1.0.0", "inherits": "~2.0.1", "isarray": "0.0.1", "string_decoder": "~0.10.x" }, "dependencies": { "isarray": { "version": "0.0.1", "resolved": "https://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz", "integrity": "sha1-ihis/Kmo9Bd+Cav8YDiTmwXR7t8=" } } }, "reflect-metadata": { "version": "0.1.13", "resolved": "https://registry.npmjs.org/reflect-metadata/-/reflect-metadata-0.1.13.tgz", "integrity": "sha512-Ts1Y/anZELhSsjMcU605fU9RE4Oi3p5ORujwbIKXfWa+0Zxs510Qrmrce5/Jowq3cHSZSJqBjypxmHarc+vEWg==" }, "require-directory": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", "integrity": "sha1-jGStX9MNqxyXbiNE/+f3kqam30I=" }, "require-main-filename": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/require-main-filename/-/require-main-filename-2.0.0.tgz", "integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==" }, "resolve": { "version": "1.11.0", "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.11.0.tgz", "integrity": "sha512-WL2pBDjqT6pGUNSUzMw00o4T7If+z4H2x3Gz893WoUQ5KW8Vr9txp00ykiP16VBaZF5+j/OcXJHZ9+PCvdiDKw==", "dev": true, "requires": { "path-parse": "^1.0.6" } }, "rxjs": { "version": "6.5.2", "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-6.5.2.tgz", "integrity": "sha512-HUb7j3kvb7p7eCUHE3FqjoDsC1xfZQ4AHFWfTKSpZ+sAhhz5X1WX0ZuUqWbzB2QhSLp3DoLUG+hMdEDKqWo2Zg==", "requires": { "tslib": "^1.9.0" } }, "safe-buffer": { "version": "5.1.2", "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==" }, "safer-buffer": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==" }, "sax": { "version": "1.2.4", "resolved": "https://registry.npmjs.org/sax/-/sax-1.2.4.tgz", "integrity": "sha512-NqVDv9TpANUjFm0N8uM5GxL36UgKi9/atZw+x7YFnQ8ckwFGKrl4xX4yWtrey3UJm5nP1kUbnYgLopqWNSRhWw==" }, "semver": { "version": "5.5.0", "resolved": "https://registry.npmjs.org/semver/-/semver-5.5.0.tgz", "integrity": "sha512-4SJ3dm0WAwWy/NVeioZh5AntkdJoWKxHxcmyP622fOkgHa4z3R0TdBJICINyaSDE6uNwVc8gZr+ZinwZAH4xIA==" }, "send": { "version": "0.17.1", "resolved": "https://registry.npmjs.org/send/-/send-0.17.1.tgz", "integrity": "sha512-BsVKsiGcQMFwT8UxypobUKyv7irCNRHk1T0G680vk88yf6LBByGcZJOTJCrTP2xVN6yI+XjPJcNuE3V4fT9sAg==", "requires": { "debug": "2.6.9", "depd": "~1.1.2", "destroy": "~1.0.4", "encodeurl": "~1.0.2", "escape-html": "~1.0.3", "etag": "~1.8.1", "fresh": "0.5.2", "http-errors": "~1.7.2", "mime": "1.6.0", "ms": "2.1.1", "on-finished": "~2.3.0", "range-parser": "~1.2.1", "statuses": "~1.5.0" }, "dependencies": { "debug": { "version": "2.6.9", "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", "requires": { "ms": "2.0.0" }, "dependencies": { "ms": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=" } } } } }, "serve-static": { "version": "1.14.1", "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.14.1.tgz", "integrity": "sha512-JMrvUwE54emCYWlTI+hGrGv5I8dEwmco/00EvkzIIsR7MqrHonbD9pO2MOfFnpFntl7ecpZs+3mW+XbQZu9QCg==", "requires": { "encodeurl": "~1.0.2", "escape-html": "~1.0.3", "parseurl": "~1.3.3", "send": "0.17.1" } }, "set-blocking": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz", "integrity": "sha1-BF+XgtARrppoA93TgrJDkrPYkPc=" }, "setprototypeof": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.1.1.tgz", "integrity": "sha512-JvdAWfbXeIGaZ9cILp38HntZSFSo3mWg6xGcJJsd+d4aRMOqauag1C63dJfDw7OaMYwEbHMOxEZ1lqVRYP2OAw==" }, "shebang-command": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-1.2.0.tgz", "integrity": "sha1-RKrGW2lbAzmJaMOfNj/uXer98eo=", "requires": { "shebang-regex": "^1.0.0" } }, "shebang-regex": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-1.0.0.tgz", "integrity": "sha1-2kL0l0DAtC2yypcoVxyxkMmO/qM=" }, "signal-exit": { "version": "3.0.2", "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.2.tgz", "integrity": "sha1-tf3AjxKH6hF4Yo5BXiUTK3NkbG0=" }, "source-map": { "version": "0.6.1", "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", "dev": true }, "source-map-support": { "version": "0.5.12", "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.12.tgz", "integrity": "sha512-4h2Pbvyy15EE02G+JOZpUCmqWJuqrs+sEkzewTm++BPi7Hvn/HwcqLAcNxYAyI0x13CpPPn+kMjl+hplXMHITQ==", "dev": true, "requires": { "buffer-from": "^1.0.0", "source-map": "^0.6.0" } }, "sprintf-js": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", "integrity": "sha1-BOaSb2YolTVPPdAVIDYzuFcpfiw=" }, "sqlstring": { "version": "2.3.1", "resolved": "https://registry.npmjs.org/sqlstring/-/sqlstring-2.3.1.tgz", "integrity": "sha1-R1OT/56RR5rqYtyvDKPRSYOn+0A=" }, "statuses": { "version": "1.5.0", "resolved": "https://registry.npmjs.org/statuses/-/statuses-1.5.0.tgz", "integrity": "sha1-Fhx9rBd2Wf2YEfQ3cfqZOBR4Yow=" }, "streamsearch": { "version": "0.1.2", "resolved": "https://registry.npmjs.org/streamsearch/-/streamsearch-0.1.2.tgz", "integrity": "sha1-gIudDlb8Jz2Am6VzOOkpkZoanxo=" }, "string-width": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/string-width/-/string-width-3.1.0.tgz", "integrity": "sha512-vafcv6KjVZKSgz06oM/H6GDBrAtz8vdhQakGjFIvNrHA6y3HCF1CInLy+QLq8dTJPQ1b+KDUqDFctkdRW44e1w==", "requires": { "emoji-regex": "^7.0.1", "is-fullwidth-code-point": "^2.0.0", "strip-ansi": "^5.1.0" } }, "string_decoder": { "version": "0.10.31", "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-0.10.31.tgz", "integrity": "sha1-YuIDvEF2bGwoyfyEMB2rHFMQ+pQ=" }, "strip-ansi": { "version": "5.2.0", "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.2.0.tgz", "integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==", "requires": { "ansi-regex": "^4.1.0" } }, "strip-eof": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/strip-eof/-/strip-eof-1.0.0.tgz", "integrity": "sha1-u0P/VZim6wXYm1n80SnJgzE2Br8=" }, "supports-color": { "version": "5.3.0", "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.3.0.tgz", "integrity": "sha512-0aP01LLIskjKs3lq52EC0aGBAJhLq7B2Rd8HC/DR/PtNNpcLilNmHC12O+hu0usQpo7wtHNRqtrhBwtDb0+dNg==", "requires": { "has-flag": "^3.0.0" } }, "thenify": { "version": "3.3.0", "resolved": "https://registry.npmjs.org/thenify/-/thenify-3.3.0.tgz", "integrity": "sha1-5p44obq+lpsBCCB5eLn2K4hgSDk=", "requires": { "any-promise": "^1.0.0" } }, "thenify-all": { "version": "1.6.0", "resolved": "https://registry.npmjs.org/thenify-all/-/thenify-all-1.6.0.tgz", "integrity": "sha1-GhkY1ALY/D+Y+/I02wvMjMEOlyY=", "requires": { "thenify": ">= 3.1.0 < 4" } }, "timers-ext": { "version": "0.1.7", "resolved": "https://registry.npmjs.org/timers-ext/-/timers-ext-0.1.7.tgz", "integrity": "sha512-b85NUNzTSdodShTIbky6ZF02e8STtVVfD+fu4aXXShEELpozH+bCpJLYMPZbsABN2wDH7fJpqIoXxJpzbf0NqQ==", "requires": { "es5-ext": "~0.10.46", "next-tick": "1" } }, "toidentifier": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.0.tgz", "integrity": "sha512-yaOH/Pk/VEhBWWTlhI+qXxDFXlejDGcQipMlyxda9nthulaxLZUNcUqFxokp0vcYnvteJln5FNQDRrxj3YcbVw==" }, "ts-node": { "version": "8.2.0", "resolved": "https://registry.npmjs.org/ts-node/-/ts-node-8.2.0.tgz", "integrity": "sha512-m8XQwUurkbYqXrKqr3WHCW310utRNvV5OnRVeISeea7LoCWVcdfeB/Ntl8JYWFh+WRoUAdBgESrzKochQt7sMw==", "dev": true, "requires": { "arg": "^4.1.0", "diff": "^4.0.1", "make-error": "^1.1.1", "source-map-support": "^0.5.6", "yn": "^3.0.0" }, "dependencies": { "diff": { "version": "4.0.1", "resolved": "https://registry.npmjs.org/diff/-/diff-4.0.1.tgz", "integrity": "sha512-s2+XdvhPCOF01LRQBC8hf4vhbVmI2CGS5aZnxLJlT5FtdhPCDFq80q++zK2KlrVorVDdL5BOGZ/VfLrVtYNF+Q==", "dev": true } } }, "tslib": { "version": "1.9.3", "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.9.3.tgz", "integrity": "sha512-4krF8scpejhaOgqzBEcGM7yDIEfi0/8+8zDRZhNZZ2kjmHJ4hv3zCbQWxoJGz1iw5U0Jl0nma13xzHXcncMavQ==" }, "tslint": { "version": "5.17.0", "resolved": "https://registry.npmjs.org/tslint/-/tslint-5.17.0.tgz", "integrity": "sha512-pflx87WfVoYepTet3xLfDOLDm9Jqi61UXIKePOuca0qoAZyrGWonDG9VTbji58Fy+8gciUn8Bt7y69+KEVjc/w==", "dev": true, "requires": { "@babel/code-frame": "^7.0.0", "builtin-modules": "^1.1.1", "chalk": "^2.3.0", "commander": "^2.12.1", "diff": "^3.2.0", "glob": "^7.1.1", "js-yaml": "^3.13.1", "minimatch": "^3.0.4", "mkdirp": "^0.5.1", "resolve": "^1.3.2", "semver": "^5.3.0", "tslib": "^1.8.0", "tsutils": "^2.29.0" } }, "tsutils": { "version": "2.29.0", "resolved": "https://registry.npmjs.org/tsutils/-/tsutils-2.29.0.tgz", "integrity": "sha512-g5JVHCIJwzfISaXpXE1qvNalca5Jwob6FjI4AoPlqMusJ6ftFE7IkkFoMhVLRgK+4Kx3gkzb8UZK5t5yTTvEmA==", "dev": true, "requires": { "tslib": "^1.8.1" } }, "type-is": { "version": "1.6.18", "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz", "integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==", "requires": { "media-typer": "0.3.0", "mime-types": "~2.1.24" } }, "typedarray": { "version": "0.0.6", "resolved": "https://registry.npmjs.org/typedarray/-/typedarray-0.0.6.tgz", "integrity": "sha1-hnrHTjhkGHsdPUfZlqeOxciDB3c=" }, "typeorm": { "version": "0.2.18", "resolved": "https://registry.npmjs.org/typeorm/-/typeorm-0.2.18.tgz", "integrity": "sha512-S553GwtG5ab268+VmaLCN7gKDqFPIzUw0eGMTobJ9yr0Np62Ojfx8j1Oa9bIeh5p7Pz1/kmGabAHoP1MYK05pA==", "requires": { "app-root-path": "^2.0.1", "buffer": "^5.1.0", "chalk": "^2.4.2", "cli-highlight": "^2.0.0", "debug": "^4.1.1", "dotenv": "^6.2.0", "glob": "^7.1.2", "js-yaml": "^3.13.1", "mkdirp": "^0.5.1", "reflect-metadata": "^0.1.13", "tslib": "^1.9.0", "xml2js": "^0.4.17", "yargonaut": "^1.1.2", "yargs": "^13.2.1" }, "dependencies": { "chalk": { "version": "2.4.2", "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", "requires": { "ansi-styles": "^3.2.1", "escape-string-regexp": "^1.0.5", "supports-color": "^5.3.0" } } } }, "typescript": { "version": "3.5.1", "resolved": "https://registry.npmjs.org/typescript/-/typescript-3.5.1.tgz", "integrity": "sha512-64HkdiRv1yYZsSe4xC1WVgamNigVYjlssIoaH2HcZF0+ijsk5YK2g0G34w9wJkze8+5ow4STd22AynfO6ZYYLw==" }, "unpipe": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", "integrity": "sha1-sr9O6FFKrmFltIF4KdIbLvSZBOw=" }, "util-deprecate": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", "integrity": "sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8=" }, "utils-merge": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz", "integrity": "sha1-n5VxD1CiZ5R7LMwSR0HBAoQn5xM=" }, "uuid": { "version": "3.3.2", "resolved": "https://registry.npmjs.org/uuid/-/uuid-3.3.2.tgz", "integrity": "sha512-yXJmeNaw3DnnKAOKJE51sL/ZaYfWJRl1pK9dr19YFCu0ObS231AB1/LbqTKRAQ5kw8A90rA6fr4riOUpTZvQZA==" }, "vary": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", "integrity": "sha1-IpnwLG3tMNSllhsLn3RSShj2NPw=" }, "which": { "version": "1.3.1", "resolved": "https://registry.npmjs.org/which/-/which-1.3.1.tgz", "integrity": "sha512-HxJdYWq1MTIQbJ3nw0cqssHoTNU267KlrDuGZ1WYlxDStUtKUhOaJmh112/TZmHxxUfuJqPXSOm7tDyas0OSIQ==", "requires": { "isexe": "^2.0.0" } }, "which-module": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/which-module/-/which-module-2.0.0.tgz", "integrity": "sha1-2e8H3Od7mQK4o6j6SzHD4/fm6Ho=" }, "wrap-ansi": { "version": "5.1.0", "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-5.1.0.tgz", "integrity": "sha512-QC1/iN/2/RPVJ5jYK8BGttj5z83LmSKmvbvrXPNCLZSEb32KKVDJDl/MOt2N01qU2H/FkzEa9PKto1BqDjtd7Q==", "requires": { "ansi-styles": "^3.2.0", "string-width": "^3.0.0", "strip-ansi": "^5.0.0" } }, "wrappy": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=" }, "xml2js": { "version": "0.4.19", "resolved": "https://registry.npmjs.org/xml2js/-/xml2js-0.4.19.tgz", "integrity": "sha512-esZnJZJOiJR9wWKMyuvSE1y6Dq5LCuJanqhxslH2bxM6duahNZ+HMpCLhBQGZkbX6xRf8x1Y2eJlgt2q3qo49Q==", "requires": { "sax": ">=0.6.0", "xmlbuilder": "~9.0.1" } }, "xmlbuilder": { "version": "9.0.7", "resolved": "https://registry.npmjs.org/xmlbuilder/-/xmlbuilder-9.0.7.tgz", "integrity": "sha1-Ey7mPS7FVlxVfiD0wi35rKaGsQ0=" }, "xtend": { "version": "4.0.1", "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.1.tgz", "integrity": "sha1-pcbVMr5lbiPbgg77lDofBJmNY68=" }, "y18n": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/y18n/-/y18n-4.0.0.tgz", "integrity": "sha512-r9S/ZyXu/Xu9q1tYlpsLIsa3EeLXXk0VwlxqTcFRfg9EhMW+17kbt9G0NrgCmhGb5vT2hyhJZLfDGx+7+5Uj/w==" }, "yargonaut": { "version": "1.1.4", "resolved": "https://registry.npmjs.org/yargonaut/-/yargonaut-1.1.4.tgz", "integrity": "sha512-rHgFmbgXAAzl+1nngqOcwEljqHGG9uUZoPjsdZEs1w5JW9RXYzrSvH/u70C1JE5qFi0qjsdhnUX/dJRpWqitSA==", "requires": { "chalk": "^1.1.1", "figlet": "^1.1.1", "parent-require": "^1.0.0" }, "dependencies": { "ansi-regex": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=" }, "ansi-styles": { "version": "2.2.1", "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz", "integrity": "sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4=" }, "chalk": { "version": "1.1.3", "resolved": "https://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz", "integrity": "sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=", "requires": { "ansi-styles": "^2.2.1", "escape-string-regexp": "^1.0.2", "has-ansi": "^2.0.0", "strip-ansi": "^3.0.0", "supports-color": "^2.0.0" } }, "strip-ansi": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", "requires": { "ansi-regex": "^2.0.0" } }, "supports-color": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-2.0.0.tgz", "integrity": "sha1-U10EXOa2Nj+kARcIRimZXp3zJMc=" } } }, "yargs": { "version": "13.2.4", "resolved": "https://registry.npmjs.org/yargs/-/yargs-13.2.4.tgz", "integrity": "sha512-HG/DWAJa1PAnHT9JAhNa8AbAv3FPaiLzioSjCcmuXXhP8MlpHO5vwls4g4j6n30Z74GVQj8Xa62dWVx1QCGklg==", "requires": { "cliui": "^5.0.0", "find-up": "^3.0.0", "get-caller-file": "^2.0.1", "os-locale": "^3.1.0", "require-directory": "^2.1.1", "require-main-filename": "^2.0.0", "set-blocking": "^2.0.0", "string-width": "^3.0.0", "which-module": "^2.0.0", "y18n": "^4.0.0", "yargs-parser": "^13.1.0" } }, "yargs-parser": { "version": "13.1.0", "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-13.1.0.tgz", "integrity": "sha512-Yq+32PrijHRri0vVKQEm+ys8mbqWjLiwQkMFNXEENutzLPP0bE4Lcd4iA3OQY5HF+GD3xXxf0MEHb8E4/SA3AA==", "requires": { "camelcase": "^5.0.0", "decamelize": "^1.2.0" } }, "yn": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/yn/-/yn-3.1.0.tgz", "integrity": "sha512-kKfnnYkbTfrAdd0xICNFw7Atm8nKpLcLv9AZGEt+kczL/WQVai4e2V6ZN8U/O+iI6WrNuJjNNOyu4zfhl9D3Hg==", "dev": true } } }
sample/05-sql-typeorm/package-lock.json
0
https://github.com/nestjs/nest/commit/94949fee6e498e8f791e8c398bfc837a8223db3e
[ 0.00017715546709951013, 0.00017332723655272275, 0.00016735885583329946, 0.000173501786775887, 0.0000019489543774398044 ]
{ "id": 1, "code_window": [ "import { RuntimeException } from '../errors/exceptions/runtime.exception';\n", "import { UnknownExportException } from '../errors/exceptions/unknown-export.exception';\n", "import { NestContainer } from './container';\n", "import { InstanceWrapper } from './instance-wrapper';\n", "import { ModuleRef } from './module-ref';\n", "\n", "interface ProviderName {\n", " name?: string | symbol;\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "import { ApplicationConfig } from '../application-config';\n" ], "file_path": "packages/core/injector/module.ts", "type": "add", "edit_start_line_idx": 29 }
import { CallHandler, ExecutionContext, Injectable, NestInterceptor, Scope, } from '@nestjs/common'; import { Observable } from 'rxjs'; @Injectable({ scope: Scope.REQUEST }) export class Interceptor implements NestInterceptor { static COUNTER = 0; constructor() { Interceptor.COUNTER++; } intercept(context: ExecutionContext, call: CallHandler): Observable<any> { return call.handle(); } }
integration/scopes/src/hello/interceptors/logging.interceptor.ts
0
https://github.com/nestjs/nest/commit/94949fee6e498e8f791e8c398bfc837a8223db3e
[ 0.00020322692580521107, 0.00019907660316675901, 0.0001949262950802222, 0.00019907660316675901, 0.000004150315362494439 ]
{ "id": 1, "code_window": [ "import { RuntimeException } from '../errors/exceptions/runtime.exception';\n", "import { UnknownExportException } from '../errors/exceptions/unknown-export.exception';\n", "import { NestContainer } from './container';\n", "import { InstanceWrapper } from './instance-wrapper';\n", "import { ModuleRef } from './module-ref';\n", "\n", "interface ProviderName {\n", " name?: string | symbol;\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "import { ApplicationConfig } from '../application-config';\n" ], "file_path": "packages/core/injector/module.ts", "type": "add", "edit_start_line_idx": 29 }
{ "compilerOptions": { "module": "commonjs", "declaration": true, "noImplicitAny": false, "skipLibCheck": true, "suppressImplicitAnyIndexErrors": true, "noUnusedLocals": false, "removeComments": false, "noLib": false, "emitDecoratorMetadata": true, "experimentalDecorators": true, "target": "es2017", "sourceMap": false, "allowJs": false, "strict": true, "strictNullChecks": false }, "exclude": ["../node_modules", "./**/*.spec.ts"] }
packages/tsconfig.base.json
0
https://github.com/nestjs/nest/commit/94949fee6e498e8f791e8c398bfc837a8223db3e
[ 0.0001759196020429954, 0.0001752848766045645, 0.00017483983538113534, 0.00017509525059722364, 4.6075882664808887e-7 ]
{ "id": 2, "code_window": [ "\n", " public addCoreProviders(container: NestContainer) {\n", " this.addModuleAsProvider();\n", " this.addModuleRef();\n", " }\n", "\n", " public addModuleRef() {\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " this.addApplicationConfig();\n" ], "file_path": "packages/core/injector/module.ts", "type": "add", "edit_start_line_idx": 118 }
import { Scope } from '@nestjs/common'; import { SCOPE_OPTIONS_METADATA } from '@nestjs/common/constants'; import { Abstract, ClassProvider, Controller, DynamicModule, ExistingProvider, FactoryProvider, Injectable, NestModule, Provider, ValueProvider, } from '@nestjs/common/interfaces'; import { Type } from '@nestjs/common/interfaces/type.interface'; import { randomStringGenerator } from '@nestjs/common/utils/random-string-generator.util'; import { isFunction, isNil, isString, isSymbol, isUndefined, } from '@nestjs/common/utils/shared.utils'; import { InvalidClassException } from '../errors/exceptions/invalid-class.exception'; import { RuntimeException } from '../errors/exceptions/runtime.exception'; import { UnknownExportException } from '../errors/exceptions/unknown-export.exception'; import { NestContainer } from './container'; import { InstanceWrapper } from './instance-wrapper'; import { ModuleRef } from './module-ref'; interface ProviderName { name?: string | symbol; } export class Module { private readonly _id: string; private readonly _imports = new Set<Module>(); private readonly _providers = new Map<any, InstanceWrapper<Injectable>>(); private readonly _injectables = new Map<any, InstanceWrapper<Injectable>>(); private readonly _controllers = new Map< string, InstanceWrapper<Controller> >(); private readonly _exports = new Set<string | symbol>(); constructor( private readonly _metatype: Type<any>, private readonly _scope: Type<any>[], private readonly container: NestContainer, ) { this.addCoreProviders(container); this._id = randomStringGenerator(); } get id(): string { return this._id; } get scope(): Type<any>[] { return this._scope; } get providers(): Map<any, InstanceWrapper<Injectable>> { return this._providers; } get imports(): Set<Module> { return this._imports; } /** * Left for backward-compatibility reasons */ get relatedModules(): Set<Module> { return this._imports; } /** * Left for backward-compatibility reasons */ get components(): Map<string, InstanceWrapper<Injectable>> { return this._providers; } /** * Left for backward-compatibility reasons */ get routes(): Map<string, InstanceWrapper<Controller>> { return this._controllers; } get injectables(): Map<string, InstanceWrapper<Injectable>> { return this._injectables; } get controllers(): Map<string, InstanceWrapper<Controller>> { return this._controllers; } get exports(): Set<string | symbol> { return this._exports; } get instance(): NestModule { if (!this._providers.has(this._metatype.name)) { throw new RuntimeException(); } const module = this._providers.get(this._metatype.name); return module.instance as NestModule; } get metatype(): Type<any> { return this._metatype; } public addCoreProviders(container: NestContainer) { this.addModuleAsProvider(); this.addModuleRef(); } public addModuleRef() { const moduleRef = this.createModuleReferenceType(); this._providers.set( ModuleRef.name, new InstanceWrapper({ name: ModuleRef.name, metatype: ModuleRef as any, isResolved: true, instance: new moduleRef(), host: this, }), ); } public addModuleAsProvider() { this._providers.set( this._metatype.name, new InstanceWrapper({ name: this._metatype.name, metatype: this._metatype, isResolved: false, instance: null, host: this, }), ); } public addInjectable<T extends Injectable>( injectable: Type<T>, host?: Type<T>, ) { if (this.isCustomProvider(injectable)) { return this.addCustomProvider(injectable, this._injectables); } const instanceWrapper = new InstanceWrapper({ name: injectable.name, metatype: injectable, instance: null, isResolved: false, scope: this.getClassScope(injectable), host: this, }); this._injectables.set(injectable.name, instanceWrapper); if (host) { const hostWrapper = this._controllers.get(host && host.name); hostWrapper && hostWrapper.addEnhancerMetadata(instanceWrapper); } } public addProvider(provider: Provider): string { if (this.isCustomProvider(provider)) { return this.addCustomProvider(provider, this._providers); } this._providers.set( (provider as Type<Injectable>).name, new InstanceWrapper({ name: (provider as Type<Injectable>).name, metatype: provider as Type<Injectable>, instance: null, isResolved: false, scope: this.getClassScope(provider), host: this, }), ); return (provider as Type<Injectable>).name; } public isCustomProvider( provider: Provider, ): provider is | ClassProvider | FactoryProvider | ValueProvider | ExistingProvider { return !isNil( (provider as | ClassProvider | FactoryProvider | ValueProvider | ExistingProvider).provide, ); } public addCustomProvider( provider: ( | ClassProvider | FactoryProvider | ValueProvider | ExistingProvider) & ProviderName, collection: Map<string, any>, ): string { const name = this.getProviderStaticToken(provider.provide) as string; provider = { ...provider, name, }; if (this.isCustomClass(provider)) { this.addCustomClass(provider, collection); } else if (this.isCustomValue(provider)) { this.addCustomValue(provider, collection); } else if (this.isCustomFactory(provider)) { this.addCustomFactory(provider, collection); } else if (this.isCustomUseExisting(provider)) { this.addCustomUseExisting(provider, collection); } return name; } public isCustomClass(provider: any): provider is ClassProvider { return !isUndefined((provider as ClassProvider).useClass); } public isCustomValue(provider: any): provider is ValueProvider { return !isUndefined((provider as ValueProvider).useValue); } public isCustomFactory(provider: any): provider is FactoryProvider { return !isUndefined((provider as FactoryProvider).useFactory); } public isCustomUseExisting(provider: any): provider is ExistingProvider { return !isUndefined((provider as ExistingProvider).useExisting); } public isDynamicModule(exported: any): exported is DynamicModule { return exported && exported.module; } public addCustomClass( provider: ClassProvider & ProviderName, collection: Map<string, InstanceWrapper>, ) { const { name, useClass, scope } = provider; collection.set( name as string, new InstanceWrapper({ name, metatype: useClass, instance: null, isResolved: false, scope, host: this, }), ); } public addCustomValue( provider: ValueProvider & ProviderName, collection: Map<string, InstanceWrapper>, ) { const { name, useValue: value } = provider; collection.set( name as string, new InstanceWrapper({ name, metatype: null, instance: value, isResolved: true, async: value instanceof Promise, host: this, }), ); } public addCustomFactory( provider: FactoryProvider & ProviderName, collection: Map<string, InstanceWrapper>, ) { const { name, useFactory: factory, inject, scope } = provider; collection.set( name as string, new InstanceWrapper({ name, metatype: factory as any, instance: null, isResolved: false, inject: inject || [], scope, host: this, }), ); } public addCustomUseExisting( provider: ExistingProvider & ProviderName, collection: Map<string, InstanceWrapper>, ) { const { name, useExisting } = provider; collection.set( name as string, new InstanceWrapper({ name, metatype: (instance => instance) as any, instance: null, isResolved: false, inject: [useExisting], host: this, }), ); } public addExportedProvider( provider: Provider & ProviderName | string | symbol | DynamicModule, ) { const addExportedUnit = (token: string | symbol) => this._exports.add(this.validateExportedProvider(token)); if (this.isCustomProvider(provider as any)) { return this.addCustomExportedProvider(provider as any); } else if (isString(provider) || isSymbol(provider)) { return addExportedUnit(provider); } else if (this.isDynamicModule(provider)) { const { module } = provider; return addExportedUnit(module.name); } addExportedUnit(provider.name); } public addCustomExportedProvider( provider: | FactoryProvider | ValueProvider | ClassProvider | ExistingProvider, ) { const provide = provider.provide; if (isString(provide) || isSymbol(provide)) { return this._exports.add(this.validateExportedProvider(provide)); } this._exports.add(this.validateExportedProvider(provide.name)); } public validateExportedProvider(token: string | symbol) { if (this._providers.has(token)) { return token; } const importsArray = [...this._imports.values()]; const importsNames = importsArray .filter(item => item) .map(({ metatype }) => metatype) .filter(metatype => metatype) .map(({ name }) => name); if (!importsNames.includes(token as any)) { const { name } = this.metatype; throw new UnknownExportException(name); } return token; } public addController(controller: Type<Controller>) { this._controllers.set( controller.name, new InstanceWrapper({ name: controller.name, metatype: controller, instance: null, isResolved: false, scope: this.getClassScope(controller), host: this, }), ); } public addRelatedModule(module: any) { this._imports.add(module); } public replace(toReplace: string | symbol | Type<any>, options: any) { if (options.isProvider && this.hasProvider(toReplace)) { const name = this.getProviderStaticToken(toReplace); const originalProvider = this._providers.get(name); return originalProvider.mergeWith({ provide: toReplace, ...options }); } else if (!options.isProvider && this.hasInjectable(toReplace)) { const name = this.getProviderStaticToken(toReplace); const originalInjectable = this._injectables.get(name); return originalInjectable.mergeWith({ provide: toReplace, ...options, }); } } public hasProvider(token: string | symbol | Type<any>): boolean { const name = this.getProviderStaticToken(token); return this._providers.has(name); } public hasInjectable(token: string | symbol | Type<any>): boolean { const name = this.getProviderStaticToken(token); return this._injectables.has(name); } public getProviderStaticToken( provider: string | symbol | Type<any> | Abstract<any>, ): string | symbol { return isFunction(provider) ? (provider as Function).name : (provider as string | symbol); } public getProviderByKey<T = any>(name: string | symbol): InstanceWrapper<T> { return this._providers.get(name) as InstanceWrapper<T>; } public createModuleReferenceType(): any { const self = this; return class extends ModuleRef { constructor() { super(self.container); } public get<TInput = any, TResult = TInput>( typeOrToken: Type<TInput> | string | symbol, options: { strict: boolean } = { strict: true }, ): TResult { if (!(options && options.strict)) { return this.find<TInput, TResult>(typeOrToken); } return this.findInstanceByPrototypeOrToken<TInput, TResult>( typeOrToken, self, ); } public async create<T = any>(type: Type<T>): Promise<T> { if (!(type && isFunction(type) && type.prototype)) { throw new InvalidClassException(type); } return this.instantiateClass<T>(type, self); } }; } private getClassScope(provider: Provider): Scope { const metadata = Reflect.getMetadata(SCOPE_OPTIONS_METADATA, provider); return metadata && metadata.scope; } }
packages/core/injector/module.ts
1
https://github.com/nestjs/nest/commit/94949fee6e498e8f791e8c398bfc837a8223db3e
[ 0.9987348914146423, 0.043111544102430344, 0.0001656608219491318, 0.00017499159730505198, 0.2012389600276947 ]
{ "id": 2, "code_window": [ "\n", " public addCoreProviders(container: NestContainer) {\n", " this.addModuleAsProvider();\n", " this.addModuleRef();\n", " }\n", "\n", " public addModuleRef() {\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " this.addApplicationConfig();\n" ], "file_path": "packages/core/injector/module.ts", "type": "add", "edit_start_line_idx": 118 }
export * from './request-constants';
packages/core/router/request/index.ts
0
https://github.com/nestjs/nest/commit/94949fee6e498e8f791e8c398bfc837a8223db3e
[ 0.00017280470638070256, 0.00017280470638070256, 0.00017280470638070256, 0.00017280470638070256, 0 ]
{ "id": 2, "code_window": [ "\n", " public addCoreProviders(container: NestContainer) {\n", " this.addModuleAsProvider();\n", " this.addModuleRef();\n", " }\n", "\n", " public addModuleRef() {\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " this.addApplicationConfig();\n" ], "file_path": "packages/core/injector/module.ts", "type": "add", "edit_start_line_idx": 118 }
import { BadRequestException, HttpException, PayloadTooLargeException, } from '@nestjs/common'; import { multerExceptions } from './multer.constants'; export function transformException(error: Error | undefined) { if (!error || error instanceof HttpException) { return error; } switch (error.message) { case multerExceptions.LIMIT_FILE_SIZE: return new PayloadTooLargeException(error.message); case multerExceptions.LIMIT_FILE_COUNT: case multerExceptions.LIMIT_FIELD_KEY: case multerExceptions.LIMIT_FIELD_VALUE: case multerExceptions.LIMIT_FIELD_COUNT: case multerExceptions.LIMIT_UNEXPECTED_FILE: case multerExceptions.LIMIT_PART_COUNT: return new BadRequestException(error.message); } return error; }
packages/platform-express/multer/multer/multer.utils.ts
0
https://github.com/nestjs/nest/commit/94949fee6e498e8f791e8c398bfc837a8223db3e
[ 0.00017271873366553336, 0.00017202259914483875, 0.00017089345783460885, 0.0001724555913824588, 8.056147748902731e-7 ]
{ "id": 2, "code_window": [ "\n", " public addCoreProviders(container: NestContainer) {\n", " this.addModuleAsProvider();\n", " this.addModuleRef();\n", " }\n", "\n", " public addModuleRef() {\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " this.addApplicationConfig();\n" ], "file_path": "packages/core/injector/module.ts", "type": "add", "edit_start_line_idx": 118 }
{ "name": "@nestjs/core", "version": "6.3.0", "description": "Modern, fast, powerful node.js web framework", "scripts": { "coverage": "nyc report --reporter=text-lcov | coveralls", "test": "nyc --require ts-node/register mocha packages/**/*.spec.ts --reporter spec --retries 3 --require 'node_modules/reflect-metadata/Reflect.js'", "integration-test": "mocha integration/**/*.spec.ts --reporter spec --require ts-node/register --require 'node_modules/reflect-metadata/Reflect.js'", "lint": "tslint -p tsconfig.json -c tslint.json \"packages/**/*.ts\" -e \"*.spec.ts\"", "format": "prettier **/**/*.ts --ignore-path ./.prettierignore --write && git status", "clean": "gulp clean:bundle", "build": "npm run clean && gulp build", "prebuild:dev": "rm -rf node_modules/@nestjs", "build:dev": "gulp build --dist node_modules/@nestjs && gulp move", "postinstall": "opencollective", "prerelease": "gulp copy-misc && gulp build --dist node_modules/@nestjs", "publish": "npm run prerelease && npm run build && ./node_modules/.bin/lerna publish --force-publish --access public --exact -m \"chore(@nestjs) publish %s release\"", "publish:rc": "npm run prerelease && npm run build && ./node_modules/.bin/lerna publish --npm-tag=rc --access public -m \"chore(@nestjs) publish %s release\"", "publish:next": "npm run prerelease && npm run build && ./node_modules/.bin/lerna publish --npm-tag=next --access public --skip-git -m \"chore(@nestjs) publish %s release\"", "publish:beta": "npm run prerelease && npm run build && ./node_modules/.bin/lerna publish --npm-tag=beta --access public -m \"chore(@nestjs) publish %s release\"", "publish:test": "npm run prerelease && npm run build && ./node_modules/.bin/lerna publish --force-publish --access public --npm-tag=test --skip-git -m \"chore(@nestjs) publish %s release\"" }, "engines": { "node": ">= 8.9.0" }, "repository": { "type": "git", "url": "https://github.com/nestjs/nest" }, "author": "Kamil Mysliwiec", "license": "MIT", "dependencies": { "@grpc/proto-loader": "0.3.0", "@nestjs/common": "6.1.1", "@nestjs/core": "6.1.1", "@nestjs/microservices": "6.1.1", "@nestjs/testing": "6.1.1", "@nestjs/websockets": "6.1.1", "@nuxtjs/opencollective": "0.2.2", "amqp-connection-manager": "2.3.2", "amqplib": "0.5.3", "apollo-server-express": "2.6.1", "axios": "0.19.0", "cache-manager": "2.9.1", "class-transformer": "0.2.3", "class-validator": "0.9.1", "cli-color": "1.4.0", "connect": "3.7.0", "cors": "2.8.5", "engine.io-client": "3.3.2", "express": "4.17.1", "fast-json-stringify": "1.15.3", "fast-safe-stringify": "2.0.6", "fastify": "2.4.1", "fastify-cors": "2.1.3", "fastify-formbody": "3.1.0", "fastify-multipart": "1.0.0", "graphql": "14.3.1", "grpc": "1.21.1", "http2": "3.3.7", "iterare": "1.1.2", "merge-graphql-schemas": "1.5.8", "mqtt": "3.0.0", "multer": "1.4.1", "nats": "1.2.10", "object-hash": "1.3.1", "optional": "0.1.4", "path-to-regexp": "3.0.0", "pump": "3.0.0", "redis": "2.8.0", "reflect-metadata": "0.1.13", "rxjs": "6.5.2", "rxjs-compat": "6.5.2", "socket.io": "2.2.0", "ts-morph": "2.3.0", "uuid": "3.3.2" }, "devDependencies": { "@types/amqplib": "0.5.12", "@types/cache-manager": "1.2.7", "@types/chai": "4.1.7", "@types/chai-as-promised": "7.1.0", "@types/cors": "2.8.5", "@types/express": "4.17.0", "@types/fastify-cors": "2.1.0", "@types/kafka-node": "2.0.8", "@types/mocha": "5.2.7", "@types/node": "10.14.8", "@types/redis": "2.8.13", "@types/reflect-metadata": "0.0.5", "@types/sinon": "7.0.12", "@types/socket.io": "2.1.2", "@types/ws": "6.0.1", "artillery": "1.6.0-28", "awesome-typescript-loader": "5.2.1", "body-parser": "1.19.0", "chai": "4.2.0", "chai-as-promised": "7.1.1", "clang-format": "1.2.4", "concurrently": "4.1.0", "conventional-changelog": "3.1.8", "core-js": "3.1.3", "coveralls": "3.0.4", "csv-write-stream": "2.0.0", "delete-empty": "2.0.0", "fastify-static": "2.4.0", "gulp": "4.0.1", "gulp-clang-format": "1.0.27", "gulp-clean": "0.4.0", "gulp-sourcemaps": "2.6.5", "gulp-typescript": "5.0.1", "gulp-watch": "5.0.1", "husky": "1.3.1", "imports-loader": "0.8.0", "json-loader": "0.5.7", "lerna": "3.14.1", "lint-staged": "8.2.0", "memory-usage": "1.2.1", "mocha": "3.5.3", "nodemon": "1.19.1", "nyc": "14.1.1", "prettier": "1.17.1", "sinon": "7.3.2", "sinon-chai": "3.3.0", "socket.io-client": "2.2.0", "supertest": "4.0.2", "ts-node": "8.2.0", "tslint": "5.17.0", "typescript": "3.5.1" }, "collective": { "type": "opencollective", "url": "https://opencollective.com/nest", "donation": { "text": "Become a partner:" } }, "nyc": { "include": [ "packages/**/*.ts" ], "exclude": [ "node_modules/", "packages/**/test/**", "packages/**/*.spec.ts", "packages/**/adapters/*.ts", "packages/**/nest-*.ts", "packages/**/test/**/*.ts", "packages/core/errors/**/*", "packages/common/exceptions/*.ts", "packages/common/http/*.ts", "packages/common/utils/load-package.util.ts", "packages/microservices/exceptions/", "packages/microservices/microservices-module.ts", "packages/core/middleware/middleware-module.ts", "packages/core/injector/module-ref.ts", "packages/core/injector/container-scanner.ts", "packages/common/cache/**/*", "packages/common/serializer/**/*", "packages/common/services/logger.service.ts" ], "extension": [ ".ts" ], "require": [ "ts-node/register" ], "reporter": [ "text-summary", "html" ], "sourceMap": true, "instrument": true }, "lint-staged": { "packages/**/*.{ts,json}": [ "npm run format", "git add" ] }, "husky": { "hooks": { "pre-commit": "lint-staged" } } }
package.json
0
https://github.com/nestjs/nest/commit/94949fee6e498e8f791e8c398bfc837a8223db3e
[ 0.00017655076226219535, 0.00017017379286698997, 0.00016584225522819906, 0.0001698016276350245, 0.0000024452758680126863 ]
{ "id": 3, "code_window": [ " );\n", " }\n", "\n", " public addInjectable<T extends Injectable>(\n", " injectable: Type<T>,\n", " host?: Type<T>,\n", " ) {\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " public addApplicationConfig() {\n", " this._providers.set(\n", " ApplicationConfig.name,\n", " new InstanceWrapper({\n", " name: ApplicationConfig.name,\n", " metatype: null,\n", " isResolved: true,\n", " instance: this.container.applicationConfig,\n", " host: this,\n", " }),\n", " );\n", " }\n", "\n" ], "file_path": "packages/core/injector/module.ts", "type": "add", "edit_start_line_idx": 147 }
import { Scope } from '@nestjs/common'; import { SCOPE_OPTIONS_METADATA } from '@nestjs/common/constants'; import { Abstract, ClassProvider, Controller, DynamicModule, ExistingProvider, FactoryProvider, Injectable, NestModule, Provider, ValueProvider, } from '@nestjs/common/interfaces'; import { Type } from '@nestjs/common/interfaces/type.interface'; import { randomStringGenerator } from '@nestjs/common/utils/random-string-generator.util'; import { isFunction, isNil, isString, isSymbol, isUndefined, } from '@nestjs/common/utils/shared.utils'; import { InvalidClassException } from '../errors/exceptions/invalid-class.exception'; import { RuntimeException } from '../errors/exceptions/runtime.exception'; import { UnknownExportException } from '../errors/exceptions/unknown-export.exception'; import { NestContainer } from './container'; import { InstanceWrapper } from './instance-wrapper'; import { ModuleRef } from './module-ref'; interface ProviderName { name?: string | symbol; } export class Module { private readonly _id: string; private readonly _imports = new Set<Module>(); private readonly _providers = new Map<any, InstanceWrapper<Injectable>>(); private readonly _injectables = new Map<any, InstanceWrapper<Injectable>>(); private readonly _controllers = new Map< string, InstanceWrapper<Controller> >(); private readonly _exports = new Set<string | symbol>(); constructor( private readonly _metatype: Type<any>, private readonly _scope: Type<any>[], private readonly container: NestContainer, ) { this.addCoreProviders(container); this._id = randomStringGenerator(); } get id(): string { return this._id; } get scope(): Type<any>[] { return this._scope; } get providers(): Map<any, InstanceWrapper<Injectable>> { return this._providers; } get imports(): Set<Module> { return this._imports; } /** * Left for backward-compatibility reasons */ get relatedModules(): Set<Module> { return this._imports; } /** * Left for backward-compatibility reasons */ get components(): Map<string, InstanceWrapper<Injectable>> { return this._providers; } /** * Left for backward-compatibility reasons */ get routes(): Map<string, InstanceWrapper<Controller>> { return this._controllers; } get injectables(): Map<string, InstanceWrapper<Injectable>> { return this._injectables; } get controllers(): Map<string, InstanceWrapper<Controller>> { return this._controllers; } get exports(): Set<string | symbol> { return this._exports; } get instance(): NestModule { if (!this._providers.has(this._metatype.name)) { throw new RuntimeException(); } const module = this._providers.get(this._metatype.name); return module.instance as NestModule; } get metatype(): Type<any> { return this._metatype; } public addCoreProviders(container: NestContainer) { this.addModuleAsProvider(); this.addModuleRef(); } public addModuleRef() { const moduleRef = this.createModuleReferenceType(); this._providers.set( ModuleRef.name, new InstanceWrapper({ name: ModuleRef.name, metatype: ModuleRef as any, isResolved: true, instance: new moduleRef(), host: this, }), ); } public addModuleAsProvider() { this._providers.set( this._metatype.name, new InstanceWrapper({ name: this._metatype.name, metatype: this._metatype, isResolved: false, instance: null, host: this, }), ); } public addInjectable<T extends Injectable>( injectable: Type<T>, host?: Type<T>, ) { if (this.isCustomProvider(injectable)) { return this.addCustomProvider(injectable, this._injectables); } const instanceWrapper = new InstanceWrapper({ name: injectable.name, metatype: injectable, instance: null, isResolved: false, scope: this.getClassScope(injectable), host: this, }); this._injectables.set(injectable.name, instanceWrapper); if (host) { const hostWrapper = this._controllers.get(host && host.name); hostWrapper && hostWrapper.addEnhancerMetadata(instanceWrapper); } } public addProvider(provider: Provider): string { if (this.isCustomProvider(provider)) { return this.addCustomProvider(provider, this._providers); } this._providers.set( (provider as Type<Injectable>).name, new InstanceWrapper({ name: (provider as Type<Injectable>).name, metatype: provider as Type<Injectable>, instance: null, isResolved: false, scope: this.getClassScope(provider), host: this, }), ); return (provider as Type<Injectable>).name; } public isCustomProvider( provider: Provider, ): provider is | ClassProvider | FactoryProvider | ValueProvider | ExistingProvider { return !isNil( (provider as | ClassProvider | FactoryProvider | ValueProvider | ExistingProvider).provide, ); } public addCustomProvider( provider: ( | ClassProvider | FactoryProvider | ValueProvider | ExistingProvider) & ProviderName, collection: Map<string, any>, ): string { const name = this.getProviderStaticToken(provider.provide) as string; provider = { ...provider, name, }; if (this.isCustomClass(provider)) { this.addCustomClass(provider, collection); } else if (this.isCustomValue(provider)) { this.addCustomValue(provider, collection); } else if (this.isCustomFactory(provider)) { this.addCustomFactory(provider, collection); } else if (this.isCustomUseExisting(provider)) { this.addCustomUseExisting(provider, collection); } return name; } public isCustomClass(provider: any): provider is ClassProvider { return !isUndefined((provider as ClassProvider).useClass); } public isCustomValue(provider: any): provider is ValueProvider { return !isUndefined((provider as ValueProvider).useValue); } public isCustomFactory(provider: any): provider is FactoryProvider { return !isUndefined((provider as FactoryProvider).useFactory); } public isCustomUseExisting(provider: any): provider is ExistingProvider { return !isUndefined((provider as ExistingProvider).useExisting); } public isDynamicModule(exported: any): exported is DynamicModule { return exported && exported.module; } public addCustomClass( provider: ClassProvider & ProviderName, collection: Map<string, InstanceWrapper>, ) { const { name, useClass, scope } = provider; collection.set( name as string, new InstanceWrapper({ name, metatype: useClass, instance: null, isResolved: false, scope, host: this, }), ); } public addCustomValue( provider: ValueProvider & ProviderName, collection: Map<string, InstanceWrapper>, ) { const { name, useValue: value } = provider; collection.set( name as string, new InstanceWrapper({ name, metatype: null, instance: value, isResolved: true, async: value instanceof Promise, host: this, }), ); } public addCustomFactory( provider: FactoryProvider & ProviderName, collection: Map<string, InstanceWrapper>, ) { const { name, useFactory: factory, inject, scope } = provider; collection.set( name as string, new InstanceWrapper({ name, metatype: factory as any, instance: null, isResolved: false, inject: inject || [], scope, host: this, }), ); } public addCustomUseExisting( provider: ExistingProvider & ProviderName, collection: Map<string, InstanceWrapper>, ) { const { name, useExisting } = provider; collection.set( name as string, new InstanceWrapper({ name, metatype: (instance => instance) as any, instance: null, isResolved: false, inject: [useExisting], host: this, }), ); } public addExportedProvider( provider: Provider & ProviderName | string | symbol | DynamicModule, ) { const addExportedUnit = (token: string | symbol) => this._exports.add(this.validateExportedProvider(token)); if (this.isCustomProvider(provider as any)) { return this.addCustomExportedProvider(provider as any); } else if (isString(provider) || isSymbol(provider)) { return addExportedUnit(provider); } else if (this.isDynamicModule(provider)) { const { module } = provider; return addExportedUnit(module.name); } addExportedUnit(provider.name); } public addCustomExportedProvider( provider: | FactoryProvider | ValueProvider | ClassProvider | ExistingProvider, ) { const provide = provider.provide; if (isString(provide) || isSymbol(provide)) { return this._exports.add(this.validateExportedProvider(provide)); } this._exports.add(this.validateExportedProvider(provide.name)); } public validateExportedProvider(token: string | symbol) { if (this._providers.has(token)) { return token; } const importsArray = [...this._imports.values()]; const importsNames = importsArray .filter(item => item) .map(({ metatype }) => metatype) .filter(metatype => metatype) .map(({ name }) => name); if (!importsNames.includes(token as any)) { const { name } = this.metatype; throw new UnknownExportException(name); } return token; } public addController(controller: Type<Controller>) { this._controllers.set( controller.name, new InstanceWrapper({ name: controller.name, metatype: controller, instance: null, isResolved: false, scope: this.getClassScope(controller), host: this, }), ); } public addRelatedModule(module: any) { this._imports.add(module); } public replace(toReplace: string | symbol | Type<any>, options: any) { if (options.isProvider && this.hasProvider(toReplace)) { const name = this.getProviderStaticToken(toReplace); const originalProvider = this._providers.get(name); return originalProvider.mergeWith({ provide: toReplace, ...options }); } else if (!options.isProvider && this.hasInjectable(toReplace)) { const name = this.getProviderStaticToken(toReplace); const originalInjectable = this._injectables.get(name); return originalInjectable.mergeWith({ provide: toReplace, ...options, }); } } public hasProvider(token: string | symbol | Type<any>): boolean { const name = this.getProviderStaticToken(token); return this._providers.has(name); } public hasInjectable(token: string | symbol | Type<any>): boolean { const name = this.getProviderStaticToken(token); return this._injectables.has(name); } public getProviderStaticToken( provider: string | symbol | Type<any> | Abstract<any>, ): string | symbol { return isFunction(provider) ? (provider as Function).name : (provider as string | symbol); } public getProviderByKey<T = any>(name: string | symbol): InstanceWrapper<T> { return this._providers.get(name) as InstanceWrapper<T>; } public createModuleReferenceType(): any { const self = this; return class extends ModuleRef { constructor() { super(self.container); } public get<TInput = any, TResult = TInput>( typeOrToken: Type<TInput> | string | symbol, options: { strict: boolean } = { strict: true }, ): TResult { if (!(options && options.strict)) { return this.find<TInput, TResult>(typeOrToken); } return this.findInstanceByPrototypeOrToken<TInput, TResult>( typeOrToken, self, ); } public async create<T = any>(type: Type<T>): Promise<T> { if (!(type && isFunction(type) && type.prototype)) { throw new InvalidClassException(type); } return this.instantiateClass<T>(type, self); } }; } private getClassScope(provider: Provider): Scope { const metadata = Reflect.getMetadata(SCOPE_OPTIONS_METADATA, provider); return metadata && metadata.scope; } }
packages/core/injector/module.ts
1
https://github.com/nestjs/nest/commit/94949fee6e498e8f791e8c398bfc837a8223db3e
[ 0.9983548521995544, 0.06941918283700943, 0.00016621460963506252, 0.00017693212430458516, 0.2288513481616974 ]
{ "id": 3, "code_window": [ " );\n", " }\n", "\n", " public addInjectable<T extends Injectable>(\n", " injectable: Type<T>,\n", " host?: Type<T>,\n", " ) {\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " public addApplicationConfig() {\n", " this._providers.set(\n", " ApplicationConfig.name,\n", " new InstanceWrapper({\n", " name: ApplicationConfig.name,\n", " metatype: null,\n", " isResolved: true,\n", " instance: this.container.applicationConfig,\n", " host: this,\n", " }),\n", " );\n", " }\n", "\n" ], "file_path": "packages/core/injector/module.ts", "type": "add", "edit_start_line_idx": 147 }
import { HttpServer, INestApplication, INestApplicationContext, INestMicroservice, } from '@nestjs/common'; import { MicroserviceOptions } from '@nestjs/common/interfaces/microservices/microservice-configuration.interface'; import { NestMicroserviceOptions } from '@nestjs/common/interfaces/microservices/nest-microservice-options.interface'; import { NestApplicationContextOptions } from '@nestjs/common/interfaces/nest-application-context-options.interface'; import { NestApplicationOptions } from '@nestjs/common/interfaces/nest-application-options.interface'; import { Logger } from '@nestjs/common/services/logger.service'; import { loadPackage } from '@nestjs/common/utils/load-package.util'; import { isFunction, isNil } from '@nestjs/common/utils/shared.utils'; import { AbstractHttpAdapter } from './adapters/http-adapter'; import { ApplicationConfig } from './application-config'; import { MESSAGES } from './constants'; import { ExceptionsZone } from './errors/exceptions-zone'; import { loadAdapter } from './helpers/load-adapter'; import { NestContainer } from './injector/container'; import { InstanceLoader } from './injector/instance-loader'; import { MetadataScanner } from './metadata-scanner'; import { NestApplication } from './nest-application'; import { NestApplicationContext } from './nest-application-context'; import { DependenciesScanner } from './scanner'; export class NestFactoryStatic { private readonly logger = new Logger('NestFactory', true); /** * Creates an instance of the NestApplication * @returns {Promise} */ public async create<T extends INestApplication = INestApplication>( module: any, options?: NestApplicationOptions, ): Promise<T>; public async create<T extends INestApplication = INestApplication>( module: any, httpAdapter: AbstractHttpAdapter, options?: NestApplicationOptions, ): Promise<T>; public async create<T extends INestApplication = INestApplication>( module: any, serverOrOptions?: AbstractHttpAdapter | NestApplicationOptions, options?: NestApplicationOptions, ): Promise<T> { // tslint:disable-next-line:prefer-const let [httpServer, appOptions] = this.isHttpServer(serverOrOptions) ? [serverOrOptions, options] : [this.createHttpAdapter(), serverOrOptions]; const applicationConfig = new ApplicationConfig(); const container = new NestContainer(applicationConfig); this.applyLogger(appOptions); await this.initialize(module, container, applicationConfig, httpServer); const instance = new NestApplication( container, httpServer, applicationConfig, appOptions, ); const target = this.createNestInstance(instance); return this.createAdapterProxy<T>(target, httpServer); } /** * Creates an instance of the NestMicroservice * * @param {} module Entry (root) application module class * @param {NestMicroserviceOptions & MicroserviceOptions} options Optional microservice configuration * @returns {Promise} */ public async createMicroservice( module: any, options?: NestMicroserviceOptions & MicroserviceOptions, ): Promise<INestMicroservice> { const { NestMicroservice } = loadPackage( '@nestjs/microservices', 'NestFactory', () => require('@nestjs/microservices'), ); const applicationConfig = new ApplicationConfig(); const container = new NestContainer(applicationConfig); this.applyLogger(options); await this.initialize(module, container, applicationConfig); return this.createNestInstance<INestMicroservice>( new NestMicroservice(container, options, applicationConfig), ); } /** * Creates an instance of the NestApplicationContext * * @param {} module Entry (root) application module class * @param {NestApplicationContextOptions} options Optional Nest application configuration * @returns {Promise} */ public async createApplicationContext( module: any, options?: NestApplicationContextOptions, ): Promise<INestApplicationContext> { const container = new NestContainer(); this.applyLogger(options); await this.initialize(module, container); const modules = container.getModules().values(); const root = modules.next().value; const context = this.createNestInstance<NestApplicationContext>( new NestApplicationContext(container, [], root), ); return context.init(); } private createNestInstance<T>(instance: T): T { return this.createProxy(instance); } private async initialize( module: any, container: NestContainer, config = new ApplicationConfig(), httpServer: HttpServer = null, ) { const instanceLoader = new InstanceLoader(container); const dependenciesScanner = new DependenciesScanner( container, new MetadataScanner(), config, ); container.setHttpAdapter(httpServer); try { this.logger.log(MESSAGES.APPLICATION_START); await ExceptionsZone.asyncRun(async () => { await dependenciesScanner.scan(module); await instanceLoader.createInstancesOfDependencies(); dependenciesScanner.applyApplicationProviders(); }); } catch (e) { process.abort(); } } private createProxy(target: any) { const proxy = this.createExceptionProxy(); return new Proxy(target, { get: proxy, set: proxy, }); } private createExceptionProxy() { return (receiver: Record<string, any>, prop: string) => { if (!(prop in receiver)) { return; } if (isFunction(receiver[prop])) { return this.createExceptionZone(receiver, prop); } return receiver[prop]; }; } private createExceptionZone( receiver: Record<string, any>, prop: string, ): Function { return (...args: unknown[]) => { let result; ExceptionsZone.run(() => { result = receiver[prop](...args); }); return result; }; } private applyLogger(options: NestApplicationContextOptions | undefined) { if (!options) { return; } !isNil(options.logger) && Logger.overrideLogger(options.logger); } private createHttpAdapter<T = any>(httpServer?: T): AbstractHttpAdapter { const { ExpressAdapter } = loadAdapter( '@nestjs/platform-express', 'HTTP', () => require('@nestjs/platform-express'), ); return new ExpressAdapter(httpServer); } private isHttpServer( serverOrOptions: AbstractHttpAdapter | NestApplicationOptions, ): serverOrOptions is AbstractHttpAdapter { return !!( serverOrOptions && (serverOrOptions as AbstractHttpAdapter).patch ); } private createAdapterProxy<T>(app: NestApplication, adapter: HttpServer): T { return (new Proxy(app, { get: (receiver: Record<string, any>, prop: string) => { if (!(prop in receiver) && prop in adapter) { return this.createExceptionZone(adapter, prop); } return receiver[prop]; }, }) as unknown) as T; } } export const NestFactory = new NestFactoryStatic();
packages/core/nest-factory.ts
0
https://github.com/nestjs/nest/commit/94949fee6e498e8f791e8c398bfc837a8223db3e
[ 0.002135484479367733, 0.0002814377658069134, 0.00016493046132382005, 0.00017233889957424253, 0.0004088031710125506 ]
{ "id": 3, "code_window": [ " );\n", " }\n", "\n", " public addInjectable<T extends Injectable>(\n", " injectable: Type<T>,\n", " host?: Type<T>,\n", " ) {\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " public addApplicationConfig() {\n", " this._providers.set(\n", " ApplicationConfig.name,\n", " new InstanceWrapper({\n", " name: ApplicationConfig.name,\n", " metatype: null,\n", " isResolved: true,\n", " instance: this.container.applicationConfig,\n", " host: this,\n", " }),\n", " );\n", " }\n", "\n" ], "file_path": "packages/core/injector/module.ts", "type": "add", "edit_start_line_idx": 147 }
import * as ProtoLoader from '@grpc/proto-loader'; import { INestApplication } from '@nestjs/common'; import { Transport } from '@nestjs/microservices'; import { Test } from '@nestjs/testing'; import { fail } from 'assert'; import { expect } from 'chai'; import * as GRPC from 'grpc'; import { join } from 'path'; import * as request from 'supertest'; import { GrpcController } from '../src/grpc/grpc.controller'; describe('GRPC transport', () => { let server; let app: INestApplication; let client: any; before(async () => { const module = await Test.createTestingModule({ controllers: [GrpcController], }).compile(); app = module.createNestApplication(); server = app.getHttpAdapter().getInstance(); app.connectMicroservice({ transport: Transport.GRPC, options: { package: 'math', protoPath: join(__dirname, '../src/grpc/math.proto'), }, }); // Start gRPC microservice await app.startAllMicroservicesAsync(); await app.init(); // Load proto-buffers for test gRPC dispatch const proto = ProtoLoader.loadSync( join(__dirname, '../src/grpc/math.proto'), ) as any; // Create Raw gRPC client object const protoGRPC = GRPC.loadPackageDefinition(proto) as any; // Create client connected to started services at standard 5000 port client = new protoGRPC.math.Math( 'localhost:5000', GRPC.credentials.createInsecure(), ); }); it(`GRPC Sending and Receiving HTTP POST`, () => { return request(server) .post('/') .send([1, 2, 3, 4, 5]) .expect(200, { result: 15 }); }); it('GRPC Sending and receiving Stream from RX handler', async () => { const callHandler = client.SumStream(); callHandler.on('data', (msg: number) => { expect(msg).to.eql({ result: 15 }); callHandler.cancel(); }); callHandler.on('error', (err: any) => { // We want to fail only on real errors while Cancellation error // is expected if ( String(err) .toLowerCase() .indexOf('cancelled') === -1 ) { fail('gRPC Stream error happened, error: ' + err); } }); return new Promise((resolve, reject) => { callHandler.write({ data: [1, 2, 3, 4, 5] }); setTimeout(() => resolve(), 1000); }); }); it('GRPC Sending and receiving Stream from Call Passthrough handler', async () => { const callHandler = client.SumStreamPass(); callHandler.on('data', (msg: number) => { expect(msg).to.eql({ result: 15 }); callHandler.cancel(); }); callHandler.on('error', (err: any) => { // We want to fail only on real errors while Cancellation error // is expected if ( String(err) .toLowerCase() .indexOf('cancelled') === -1 ) { fail('gRPC Stream error happened, error: ' + err); } }); return new Promise((resolve, reject) => { callHandler.write({ data: [1, 2, 3, 4, 5] }); setTimeout(() => resolve(), 1000); }); }); after(async () => { await app.close(); client.close(); }); });
integration/microservices/e2e/sum-grpc.spec.ts
0
https://github.com/nestjs/nest/commit/94949fee6e498e8f791e8c398bfc837a8223db3e
[ 0.0001800140889827162, 0.0001698442647466436, 0.00016569446597713977, 0.0001686992181930691, 0.000003732346385731944 ]
{ "id": 3, "code_window": [ " );\n", " }\n", "\n", " public addInjectable<T extends Injectable>(\n", " injectable: Type<T>,\n", " host?: Type<T>,\n", " ) {\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " public addApplicationConfig() {\n", " this._providers.set(\n", " ApplicationConfig.name,\n", " new InstanceWrapper({\n", " name: ApplicationConfig.name,\n", " metatype: null,\n", " isResolved: true,\n", " instance: this.container.applicationConfig,\n", " host: this,\n", " }),\n", " );\n", " }\n", "\n" ], "file_path": "packages/core/injector/module.ts", "type": "add", "edit_start_line_idx": 147 }
{ "compilerOptions": { "module": "commonjs", "declaration": false, "noImplicitAny": false, "removeComments": true, "noLib": false, "emitDecoratorMetadata": true, "experimentalDecorators": true, "target": "es6", "sourceMap": true, "allowJs": true, "outDir": "./dist" }, "include": [ "src/**/*", "e2e/**/*" ], "exclude": [ "node_modules", ] }
integration/microservices/tsconfig.json
0
https://github.com/nestjs/nest/commit/94949fee6e498e8f791e8c398bfc837a8223db3e
[ 0.00018130931130144745, 0.00017561431741341949, 0.000172230284078978, 0.00017330337141174823, 0.0000040507247831556015 ]
{ "id": 0, "code_window": [ " toolbarItems: [],\n", " };\n", "\n", " constructor(props: Props) {\n", " super(props);\n", "\n", " this.state = {\n", " openView: null,\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " constructor(props) {\n" ], "file_path": "public/app/features/dashboard/panel_editor/EditorTabBody.tsx", "type": "replace", "edit_start_line_idx": 38 }
// Libraries import React, { PureComponent, ChangeEvent } from 'react'; // Utils & Services import { AngularComponent, getAngularLoader } from 'app/core/services/AngularLoader'; import { connectWithStore } from 'app/core/utils/connectWithReduxStore'; import { StoreState } from 'app/types'; import { updateLocation } from 'app/core/actions'; // Components import { EditorTabBody, EditorToolbarView } from './EditorTabBody'; import { VizTypePicker } from './VizTypePicker'; import { PluginHelp } from 'app/core/components/PluginHelp/PluginHelp'; import { FadeIn } from 'app/core/components/Animations/FadeIn'; // Types import { PanelModel } from '../state/PanelModel'; import { DashboardModel } from '../state/DashboardModel'; import { PanelPlugin } from 'app/types/plugins'; interface Props { panel: PanelModel; dashboard: DashboardModel; plugin: PanelPlugin; angularPanel?: AngularComponent; onTypeChanged: (newType: PanelPlugin) => void; updateLocation: typeof updateLocation; urlOpenVizPicker: boolean; } interface State { isVizPickerOpen: boolean; searchQuery: string; searchResults: PanelPlugin[]; scrollTop: number; } export class VisualizationTab extends PureComponent<Props, State> { element: HTMLElement; angularOptions: AngularComponent; searchInput: HTMLElement; constructor(props: Props) { super(props); this.state = { isVizPickerOpen: this.props.urlOpenVizPicker, searchQuery: '', searchResults: [], scrollTop: 0, }; } getPanelDefaultOptions = () => { const { panel, plugin } = this.props; if (plugin.exports.PanelDefaults) { return panel.getOptions(plugin.exports.PanelDefaults.options); } return panel.getOptions(plugin.exports.PanelDefaults); }; renderPanelOptions() { const { plugin, angularPanel } = this.props; const { PanelOptions } = plugin.exports; if (angularPanel) { return <div ref={element => (this.element = element)} />; } return ( <> {PanelOptions ? ( <PanelOptions options={this.getPanelDefaultOptions()} onChange={this.onPanelOptionsChanged} /> ) : ( <p>Visualization has no options</p> )} </> ); } componentDidMount() { if (this.shouldLoadAngularOptions()) { this.loadAngularOptions(); } } componentDidUpdate(prevProps: Props) { if (this.props.plugin !== prevProps.plugin) { this.cleanUpAngularOptions(); } if (this.shouldLoadAngularOptions()) { this.loadAngularOptions(); } } shouldLoadAngularOptions() { return this.props.angularPanel && this.element && !this.angularOptions; } loadAngularOptions() { const { angularPanel } = this.props; const scope = angularPanel.getScope(); // When full page reloading in edit mode the angular panel has on fully compiled & instantiated yet if (!scope.$$childHead) { setTimeout(() => { this.forceUpdate(); }); return; } const panelCtrl = scope.$$childHead.ctrl; panelCtrl.initEditMode(); let template = ''; for (let i = 0; i < panelCtrl.editorTabs.length; i++) { template += ` <div class="panel-options-group" ng-cloak>` + (i > 0 ? `<div class="panel-options-group__header"> <span class="panel-options-group__title">{{ctrl.editorTabs[${i}].title}} </span> </div>` : '') + `<div class="panel-options-group__body"> <panel-editor-tab editor-tab="ctrl.editorTabs[${i}]" ctrl="ctrl"></panel-editor-tab> </div> </div> `; } const loader = getAngularLoader(); const scopeProps = { ctrl: panelCtrl }; this.angularOptions = loader.load(this.element, scopeProps, template); } componentWillUnmount() { this.cleanUpAngularOptions(); } cleanUpAngularOptions() { if (this.angularOptions) { this.angularOptions.destroy(); this.angularOptions = null; } } clearQuery = () => { this.setState({ searchQuery: '' }); }; onPanelOptionsChanged = (options: any) => { this.props.panel.updateOptions(options); this.forceUpdate(); }; onOpenVizPicker = () => { this.setState({ isVizPickerOpen: true, scrollTop: 0 }); }; onCloseVizPicker = () => { if (this.props.urlOpenVizPicker) { this.props.updateLocation({ query: { openVizPicker: null }, partial: true }); } this.setState({ isVizPickerOpen: false }); }; onSearchQueryChange = (evt: ChangeEvent<HTMLInputElement>) => { const value = evt.target.value; this.setState({ searchQuery: value, }); }; renderToolbar = (): JSX.Element => { const { plugin } = this.props; const { searchQuery } = this.state; if (this.state.isVizPickerOpen) { return ( <> <label className="gf-form--has-input-icon"> <input type="text" className={`gf-form-input width-13 ${!this.hasSearchResults ? 'gf-form-input--invalid' : ''}`} placeholder="" onChange={this.onSearchQueryChange} value={searchQuery} ref={elem => elem && elem.focus()} /> <i className="gf-form-input-icon fa fa-search" /> </label> <button className="btn btn-link toolbar__close" onClick={this.onCloseVizPicker}> <i className="fa fa-chevron-up" /> </button> </> ); } else { return ( <div className="toolbar__main" onClick={this.onOpenVizPicker}> <img className="toolbar__main-image" src={plugin.info.logos.small} /> <div className="toolbar__main-name">{plugin.name}</div> <i className="fa fa-caret-down" /> </div> ); } }; onTypeChanged = (plugin: PanelPlugin) => { if (plugin.id === this.props.plugin.id) { this.setState({ isVizPickerOpen: false }); } else { this.props.onTypeChanged(plugin); } }; setSearchResults = (searchResults: PanelPlugin[]) => { this.setState({ searchResults: searchResults }); }; get hasSearchResults () { return this.state.searchResults && this.state.searchResults.length > 0; } renderHelp = () => <PluginHelp plugin={this.props.plugin} type="help" />; setScrollTop = (event: React.MouseEvent<HTMLElement>) => { const target = event.target as HTMLElement; this.setState({ scrollTop: target.scrollTop }); }; render() { const { plugin } = this.props; const { isVizPickerOpen, searchQuery, scrollTop } = this.state; const pluginHelp: EditorToolbarView = { heading: 'Help', icon: 'fa fa-question', render: this.renderHelp, }; return ( <EditorTabBody heading="Visualization" renderToolbar={this.renderToolbar} toolbarItems={[pluginHelp]} scrollTop={scrollTop} setScrollTop={this.setScrollTop} > <> <FadeIn in={isVizPickerOpen} duration={200} unmountOnExit={true} onExited={this.clearQuery}> <VizTypePicker current={plugin} onTypeChanged={this.onTypeChanged} searchQuery={searchQuery} onClose={this.onCloseVizPicker} onPluginListChange={this.setSearchResults} /> </FadeIn> {this.renderPanelOptions()} </> </EditorTabBody> ); } } const mapStateToProps = (state: StoreState) => ({ urlOpenVizPicker: !!state.location.query.openVizPicker, }); const mapDispatchToProps = { updateLocation, }; export default connectWithStore(VisualizationTab, mapStateToProps, mapDispatchToProps);
public/app/features/dashboard/panel_editor/VisualizationTab.tsx
1
https://github.com/grafana/grafana/commit/44eaa3eaa886e0f193e9b6ae364e0526c858cb00
[ 0.972741425037384, 0.04589514061808586, 0.00016940315254032612, 0.0012467881897464395, 0.178273007273674 ]
{ "id": 0, "code_window": [ " toolbarItems: [],\n", " };\n", "\n", " constructor(props: Props) {\n", " super(props);\n", "\n", " this.state = {\n", " openView: null,\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " constructor(props) {\n" ], "file_path": "public/app/features/dashboard/panel_editor/EditorTabBody.tsx", "type": "replace", "edit_start_line_idx": 38 }
// package lcs provides functions to calculate Longest Common Subsequence (LCS) // values from two arbitrary arrays. package lcs import ( "context" "reflect" ) // Lcs is the interface to calculate the LCS of two arrays. type Lcs interface { // Values calculates the LCS value of the two arrays. Values() (values []interface{}) // ValueContext is a context aware version of Values() ValuesContext(ctx context.Context) (values []interface{}, err error) // IndexPairs calculates paris of indices which have the same value in LCS. IndexPairs() (pairs []IndexPair) // IndexPairsContext is a context aware version of IndexPairs() IndexPairsContext(ctx context.Context) (pairs []IndexPair, err error) // Length calculates the length of the LCS. Length() (length int) // LengthContext is a context aware version of Length() LengthContext(ctx context.Context) (length int, err error) // Left returns one of the two arrays to be compared. Left() (leftValues []interface{}) // Right returns the other of the two arrays to be compared. Right() (righttValues []interface{}) } // IndexPair represents an pair of indeices in the Left and Right arrays found in the LCS value. type IndexPair struct { Left int Right int } type lcs struct { left []interface{} right []interface{} /* for caching */ table [][]int indexPairs []IndexPair values []interface{} } // New creates a new LCS calculator from two arrays. func New(left, right []interface{}) Lcs { return &lcs{ left: left, right: right, table: nil, indexPairs: nil, values: nil, } } // Table implements Lcs.Table() func (lcs *lcs) Table() (table [][]int) { table, _ = lcs.TableContext(context.Background()) return table } // Table implements Lcs.TableContext() func (lcs *lcs) TableContext(ctx context.Context) (table [][]int, err error) { if lcs.table != nil { return lcs.table, nil } sizeX := len(lcs.left) + 1 sizeY := len(lcs.right) + 1 table = make([][]int, sizeX) for x := 0; x < sizeX; x++ { table[x] = make([]int, sizeY) } for y := 1; y < sizeY; y++ { select { // check in each y to save some time case <-ctx.Done(): return nil, ctx.Err() default: // nop } for x := 1; x < sizeX; x++ { increment := 0 if reflect.DeepEqual(lcs.left[x-1], lcs.right[y-1]) { increment = 1 } table[x][y] = max(table[x-1][y-1]+increment, table[x-1][y], table[x][y-1]) } } lcs.table = table return table, nil } // Table implements Lcs.Length() func (lcs *lcs) Length() (length int) { length, _ = lcs.LengthContext(context.Background()) return length } // Table implements Lcs.LengthContext() func (lcs *lcs) LengthContext(ctx context.Context) (length int, err error) { table, err := lcs.TableContext(ctx) if err != nil { return 0, err } return table[len(lcs.left)][len(lcs.right)], nil } // Table implements Lcs.IndexPairs() func (lcs *lcs) IndexPairs() (pairs []IndexPair) { pairs, _ = lcs.IndexPairsContext(context.Background()) return pairs } // Table implements Lcs.IndexPairsContext() func (lcs *lcs) IndexPairsContext(ctx context.Context) (pairs []IndexPair, err error) { if lcs.indexPairs != nil { return lcs.indexPairs, nil } table, err := lcs.TableContext(ctx) if err != nil { return nil, err } pairs = make([]IndexPair, table[len(table)-1][len(table[0])-1]) for x, y := len(lcs.left), len(lcs.right); x > 0 && y > 0; { if reflect.DeepEqual(lcs.left[x-1], lcs.right[y-1]) { pairs[table[x][y]-1] = IndexPair{Left: x - 1, Right: y - 1} x-- y-- } else { if table[x-1][y] >= table[x][y-1] { x-- } else { y-- } } } lcs.indexPairs = pairs return pairs, nil } // Table implements Lcs.Values() func (lcs *lcs) Values() (values []interface{}) { values, _ = lcs.ValuesContext(context.Background()) return values } // Table implements Lcs.ValuesContext() func (lcs *lcs) ValuesContext(ctx context.Context) (values []interface{}, err error) { if lcs.values != nil { return lcs.values, nil } pairs, err := lcs.IndexPairsContext(ctx) if err != nil { return nil, err } values = make([]interface{}, len(pairs)) for i, pair := range pairs { values[i] = lcs.left[pair.Left] } lcs.values = values return values, nil } // Table implements Lcs.Left() func (lcs *lcs) Left() (leftValues []interface{}) { leftValues = lcs.left return } // Table implements Lcs.Right() func (lcs *lcs) Right() (rightValues []interface{}) { rightValues = lcs.right return } func max(first int, rest ...int) (max int) { max = first for _, value := range rest { if value > max { max = value } } return }
vendor/github.com/yudai/golcs/golcs.go
0
https://github.com/grafana/grafana/commit/44eaa3eaa886e0f193e9b6ae364e0526c858cb00
[ 0.0005992507794871926, 0.00019834842532873154, 0.0001664123556111008, 0.00016977536142803729, 0.00009599469194654375 ]
{ "id": 0, "code_window": [ " toolbarItems: [],\n", " };\n", "\n", " constructor(props: Props) {\n", " super(props);\n", "\n", " this.state = {\n", " openView: null,\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " constructor(props) {\n" ], "file_path": "public/app/features/dashboard/panel_editor/EditorTabBody.tsx", "type": "replace", "edit_start_line_idx": 38 }
import angular from 'angular'; import _ from 'lodash'; import kbn from 'app/core/utils/kbn'; export class LinkSrv { /** @ngInject */ constructor(private templateSrv, private timeSrv) {} getLinkUrl(link) { const url = this.templateSrv.replace(link.url || ''); const params = {}; if (link.keepTime) { const range = this.timeSrv.timeRangeForUrl(); params['from'] = range.from; params['to'] = range.to; } if (link.includeVars) { this.templateSrv.fillVariableValuesForUrl(params); } return this.addParamsToUrl(url, params); } addParamsToUrl(url, params) { const paramsArray = []; _.each(params, (value, key) => { if (value === null) { return; } if (value === true) { paramsArray.push(key); } else if (_.isArray(value)) { _.each(value, instance => { paramsArray.push(key + '=' + encodeURIComponent(instance)); }); } else { paramsArray.push(key + '=' + encodeURIComponent(value)); } }); if (paramsArray.length === 0) { return url; } return this.appendToQueryString(url, paramsArray.join('&')); } appendToQueryString(url, stringToAppend) { if (!_.isUndefined(stringToAppend) && stringToAppend !== null && stringToAppend !== '') { const pos = url.indexOf('?'); if (pos !== -1) { if (url.length - pos > 1) { url += '&'; } } else { url += '?'; } url += stringToAppend; } return url; } getAnchorInfo(link) { const info: any = {}; info.href = this.getLinkUrl(link); info.title = this.templateSrv.replace(link.title || ''); return info; } getPanelLinkAnchorInfo(link, scopedVars) { const info: any = {}; info.target = link.targetBlank ? '_blank' : ''; if (link.type === 'absolute') { info.target = link.targetBlank ? '_blank' : '_self'; info.href = this.templateSrv.replace(link.url || '', scopedVars); info.title = this.templateSrv.replace(link.title || '', scopedVars); } else if (link.url) { info.href = link.url; info.title = this.templateSrv.replace(link.title || '', scopedVars); } else if (link.dashUri) { info.href = 'dashboard/' + link.dashUri + '?'; info.title = this.templateSrv.replace(link.title || '', scopedVars); } else { info.title = this.templateSrv.replace(link.title || '', scopedVars); const slug = kbn.slugifyForUrl(link.dashboard || ''); info.href = 'dashboard/db/' + slug + '?'; } const params = {}; if (link.keepTime) { const range = this.timeSrv.timeRangeForUrl(); params['from'] = range.from; params['to'] = range.to; } if (link.includeVars) { this.templateSrv.fillVariableValuesForUrl(params, scopedVars); } info.href = this.addParamsToUrl(info.href, params); if (link.params) { info.href = this.appendToQueryString(info.href, this.templateSrv.replace(link.params, scopedVars)); } return info; } } angular.module('grafana.services').service('linkSrv', LinkSrv);
public/app/features/panel/panellinks/link_srv.ts
0
https://github.com/grafana/grafana/commit/44eaa3eaa886e0f193e9b6ae364e0526c858cb00
[ 0.9597802758216858, 0.08014865219593048, 0.00016844557831063867, 0.00017169110651593655, 0.26521891355514526 ]
{ "id": 0, "code_window": [ " toolbarItems: [],\n", " };\n", "\n", " constructor(props: Props) {\n", " super(props);\n", "\n", " this.state = {\n", " openView: null,\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " constructor(props) {\n" ], "file_path": "public/app/features/dashboard/panel_editor/EditorTabBody.tsx", "type": "replace", "edit_start_line_idx": 38 }
<div class="gf-form-inline"> <div class="gf-form"> <label class="gf-form-label query-keyword width-7"> <span ng-show="isFirst">Group by</span> <span ng-hide="isFirst">Then by</span> </label> <gf-form-dropdown model="agg.type" lookup-text="true" get-options="getBucketAggTypes()" on-change="onTypeChanged()" allow-custom="false" label-mode="true" css-class="width-10"> </gf-form-dropdown> <gf-form-dropdown ng-if="agg.field" model="agg.field" get-options="getFieldsInternal()" on-change="onChange()" allow-custom="false" label-mode="true" css-class="width-12"> </gf-form-dropdown> </div> <div class="gf-form gf-form--grow"> <label class="gf-form-label gf-form-label--grow"> <a ng-click="toggleOptions()"> <i class="fa fa-caret-down" ng-show="showOptions"></i> <i class="fa fa-caret-right" ng-hide="showOptions"></i> {{settingsLinkText}} </a> </label> </div> <div class="gf-form"> <label class="gf-form-label" ng-if="isFirst"> <a class="pointer" ng-click="addBucketAgg()"><i class="fa fa-plus"></i></a> </label> <label class="gf-form-label" ng-if="bucketAggCount > 1"> <a class="pointer" ng-click="removeBucketAgg()"><i class="fa fa-minus"></i></a> </label> </div> </div> <div class="gf-form-group" ng-if="showOptions"> <div ng-if="agg.type === 'date_histogram'"> <div class="gf-form offset-width-7"> <label class="gf-form-label width-10">Interval</label> <gf-form-dropdown model="agg.settings.interval" get-options="getIntervalOptions()" on-change="onChangeInternal()" allow-custom="true" label-mode="true" css-class="width-12"> </gf-form-dropdown> </div> <div class="gf-form offset-width-7"> <label class="gf-form-label width-10">Min Doc Count</label> <input type="number" class="gf-form-input max-width-12" ng-model="agg.settings.min_doc_count" ng-blur="onChangeInternal()"> </div> <div class="gf-form offset-width-7"> <label class="gf-form-label width-10"> Trim edges <info-popover mode="right-normal"> Trim the edges on the timeseries datapoints </info-popover> </label> <input class="gf-form-input max-width-12" type="number" ng-model="agg.settings.trimEdges" ng-change="onChangeInternal()"> </div> <div class="gf-form offset-width-7"> <label class="gf-form-label width-10"> Offset <info-popover mode="right-normal"> Change the start value of each bucket by the specified positive (+) or negative offset (-) duration, such as 1h for an hour, or 1d for a day </info-popover> </label> <input class="gf-form-input max-width-12" type="text" ng-model="agg.settings.offset" ng-change="onChangeInternal()"> </div> </div> <div ng-if="agg.type === 'histogram'"> <div class="gf-form offset-width-7"> <label class="gf-form-label width-10">Interval</label> <input type="number" class="gf-form-input max-width-12" ng-model="agg.settings.interval" ng-blur="onChangeInternal()"> </div> <div class="gf-form offset-width-7"> <label class="gf-form-label width-10">Min Doc Count</label> <input type="number" class="gf-form-input max-width-12" ng-model="agg.settings.min_doc_count" ng-blur="onChangeInternal()"> </div> </div> <div ng-if="agg.type === 'terms'"> <div class="gf-form offset-width-7"> <label class="gf-form-label width-10">Order</label> <gf-form-dropdown model="agg.settings.order" lookup-text="true" get-options="getOrderOptions()" on-change="onChangeInternal()" label-mode="true" css-class="width-12"> </gf-form-dropdown> </div> <div class="gf-form offset-width-7"> <label class="gf-form-label width-10">Size</label> <gf-form-dropdown model="agg.settings.size" lookup-text="true" get-options="getSizeOptions()" on-change="onChangeInternal()" label-mode="true" allow-custom="true" css-class="width-12"> </gf-form-dropdown> </div> <div class="gf-form offset-width-7"> <label class="gf-form-label width-10">Min Doc Count</label> <input type="number" class="gf-form-input max-width-12" ng-model="agg.settings.min_doc_count" ng-blur="onChangeInternal()"> </div> <div class="gf-form offset-width-7"> <label class="gf-form-label width-10">Order By</label> <gf-form-dropdown model="agg.settings.orderBy" lookup-text="true" get-options="getOrderByOptions()" on-change="onChangeInternal()" label-mode="true" css-class="width-12"> </gf-form-dropdown> </div> <div class="gf-form offset-width-7"> <label class="gf-form-label width-10"> Missing <info-popover mode="right-normal"> The missing parameter defines how documents that are missing a value should be treated. By default they will be ignored but it is also possible to treat them as if they had a value </info-popover> </label> <input type="text" class="gf-form-input max-width-12" empty-to-null ng-model="agg.settings.missing" ng-blur="onChangeInternal()" spellcheck='false'> </div> </div> <div ng-if="agg.type === 'filters'"> <div class="gf-form-inline offset-width-7" ng-repeat="filter in agg.settings.filters"> <div class="gf-form"> <label class="gf-form-label width-10">Query {{$index + 1}}</label> <input type="text" class="gf-form-input max-width-12" ng-model="filter.query" spellcheck='false' placeholder="Lucene query" ng-blur="onChangeInternal()"> <label class="gf-form-label width-10">Label {{$index + 1}}</label> <input type="text" class="gf-form-input max-width-12" ng-model="filter.label" spellcheck='false' placeholder="Label" ng-blur="onChangeInternal()"> </div> <div class="gf-form"> <label class="gf-form-label" ng-if="$first"> <a class="pointer" ng-click="addFiltersQuery()"><i class="fa fa-plus"></i></a> </label> <label class="gf-form-label" ng-if="!$first"> <a class="pointer" ng-click="removeFiltersQuery(filter)"><i class="fa fa-minus"></i></a> </label> </div> </div> </div> <div ng-if="agg.type === 'geohash_grid'"> <div class="gf-form offset-width-7"> <label class="gf-form-label width-10">Precision</label> <input type="number" class="gf-form-input max-width-12" ng-model="agg.settings.precision" spellcheck='false' placeholder="3" ng-blur="onChangeInternal()"> </div> </div> </div>
public/app/plugins/datasource/elasticsearch/partials/bucket_agg.html
0
https://github.com/grafana/grafana/commit/44eaa3eaa886e0f193e9b6ae364e0526c858cb00
[ 0.0001701934088487178, 0.00016804969345685095, 0.0001658637629589066, 0.00016801842139102519, 0.0000011110674904557527 ]
{ "id": 1, "code_window": [ "// Libraries\n", "import React, { PureComponent, ChangeEvent } from 'react';\n", "\n", "// Utils & Services\n", "import { AngularComponent, getAngularLoader } from 'app/core/services/AngularLoader';\n", "import { connectWithStore } from 'app/core/utils/connectWithReduxStore';\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import React, { PureComponent } from 'react';\n" ], "file_path": "public/app/features/dashboard/panel_editor/VisualizationTab.tsx", "type": "replace", "edit_start_line_idx": 1 }
// Libraries import React, { PureComponent } from 'react'; // Components import { CustomScrollbar, PanelOptionsGroup } from '@grafana/ui'; import { FadeIn } from 'app/core/components/Animations/FadeIn'; interface Props { children: JSX.Element; heading: string; renderToolbar?: () => JSX.Element; toolbarItems?: EditorToolbarView[]; scrollTop?: number; setScrollTop?: (value: React.MouseEvent<HTMLElement>) => void; } export interface EditorToolbarView { title?: string; heading?: string; icon?: string; disabled?: boolean; onClick?: () => void; render?: () => JSX.Element; action?: () => void; btnType?: 'danger'; } interface State { openView?: EditorToolbarView; isOpen: boolean; fadeIn: boolean; } export class EditorTabBody extends PureComponent<Props, State> { static defaultProps = { toolbarItems: [], }; constructor(props: Props) { super(props); this.state = { openView: null, fadeIn: false, isOpen: false, }; } componentDidMount() { this.setState({ fadeIn: true }); } onToggleToolBarView = (item: EditorToolbarView) => { this.setState({ openView: item, isOpen: this.state.openView !== item || !this.state.isOpen, }); }; onCloseOpenView = () => { this.setState({ isOpen: false }); }; static getDerivedStateFromProps(props, state) { if (state.openView) { const activeToolbarItem = props.toolbarItems.find( item => item.title === state.openView.title && item.icon === state.openView.icon ); if (activeToolbarItem) { return { ...state, openView: activeToolbarItem, }; } } return state; } renderButton(view: EditorToolbarView) { const onClick = () => { if (view.onClick) { view.onClick(); } if (view.render) { this.onToggleToolBarView(view); } }; return ( <div className="nav-buttons" key={view.title + view.icon}> <button className="btn navbar-button" onClick={onClick} disabled={view.disabled}> {view.icon && <i className={view.icon} />} {view.title} </button> </div> ); } renderOpenView(view: EditorToolbarView) { return ( <PanelOptionsGroup title={view.title || view.heading} onClose={this.onCloseOpenView}> {view.render()} </PanelOptionsGroup> ); } render() { const { children, renderToolbar, heading, toolbarItems, scrollTop, setScrollTop } = this.props; const { openView, fadeIn, isOpen } = this.state; return ( <> <div className="toolbar"> <div className="toolbar__left"> <div className="toolbar__heading">{heading}</div> {renderToolbar && renderToolbar()} </div> {toolbarItems.map(item => this.renderButton(item))} </div> <div className="panel-editor__scroll"> <CustomScrollbar autoHide={false} scrollTop={scrollTop} setScrollTop={setScrollTop}> <div className="panel-editor__content"> <FadeIn in={isOpen} duration={200} unmountOnExit={true}> {openView && this.renderOpenView(openView)} </FadeIn> <FadeIn in={fadeIn} duration={50}> {children} </FadeIn> </div> </CustomScrollbar> </div> </> ); } }
public/app/features/dashboard/panel_editor/EditorTabBody.tsx
1
https://github.com/grafana/grafana/commit/44eaa3eaa886e0f193e9b6ae364e0526c858cb00
[ 0.0004468762199394405, 0.00019063230138272047, 0.00016636206419207156, 0.00017121504060924053, 0.00007112315506674349 ]
{ "id": 1, "code_window": [ "// Libraries\n", "import React, { PureComponent, ChangeEvent } from 'react';\n", "\n", "// Utils & Services\n", "import { AngularComponent, getAngularLoader } from 'app/core/services/AngularLoader';\n", "import { connectWithStore } from 'app/core/utils/connectWithReduxStore';\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import React, { PureComponent } from 'react';\n" ], "file_path": "public/app/features/dashboard/panel_editor/VisualizationTab.tsx", "type": "replace", "edit_start_line_idx": 1 }
.gf-code-editor { min-height: 2.6rem; min-width: 20rem; flex-grow: 1; margin-right: 0.25rem; &.ace_editor { @include font-family-monospace(); font-size: 1rem; min-height: 3.6rem; // Include space for horizontal scrollbar @include border-radius($input-border-radius-sm); border: $input-btn-border-width solid $input-border-color; } .ace_content { z-index: 0; } } .ace_editor.ace_autocomplete { @include font-family-monospace(); font-size: 1rem; // Ace editor adds <style> tag at the end of <head>, after grafana.css, so !important // is used for overriding styles with the same CSS specificity. background-color: $dropdownBackground !important; color: $dropdownLinkColor !important; border: 1px solid $dropdownBorder !important; width: 550px !important; .ace_scroller { .ace_selected, .ace_active-line, .ace_line-hover { color: $dropdownLinkColorHover; background-color: $dropdownLinkBackgroundHover !important; } .ace_line-hover { border-color: transparent; } .ace_completion-highlight { color: $yellow; } .ace_rightAlignedText { color: $text-muted; z-index: 0; } } } $doc-font-size: $font-size-sm; .ace_tooltip.ace_doc-tooltip { @include font-family-monospace(); font-size: $doc-font-size; background-color: $popover-help-bg; color: $popover-help-color; background-image: none; border: 1px solid $dropdownBorder; padding: 0.5rem 1rem; hr { background-color: $popover-help-color; margin: 0.5rem 0rem; } code { padding: 0px 1px; margin: 0px; } } .ace_tooltip { border-radius: 3px; } .ace_hidden-cursors .ace_cursor { opacity: 0 !important; }
public/sass/components/_code_editor.scss
0
https://github.com/grafana/grafana/commit/44eaa3eaa886e0f193e9b6ae364e0526c858cb00
[ 0.00017640503938309848, 0.00017321176710538566, 0.00016769624198786914, 0.0001737320562824607, 0.000002443604898871854 ]
{ "id": 1, "code_window": [ "// Libraries\n", "import React, { PureComponent, ChangeEvent } from 'react';\n", "\n", "// Utils & Services\n", "import { AngularComponent, getAngularLoader } from 'app/core/services/AngularLoader';\n", "import { connectWithStore } from 'app/core/utils/connectWithReduxStore';\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import React, { PureComponent } from 'react';\n" ], "file_path": "public/app/features/dashboard/panel_editor/VisualizationTab.tsx", "type": "replace", "edit_start_line_idx": 1 }
// Go MySQL Driver - A MySQL-Driver for Go's database/sql package // // Copyright 2013 The Go-MySQL-Driver Authors. All rights reserved. // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this file, // You can obtain one at http://mozilla.org/MPL/2.0/. package mysql import ( "errors" "fmt" "log" "os" ) // Various errors the driver might return. Can change between driver versions. var ( ErrInvalidConn = errors.New("invalid connection") ErrMalformPkt = errors.New("malformed packet") ErrNoTLS = errors.New("TLS requested but server does not support TLS") ErrCleartextPassword = errors.New("this user requires clear text authentication. If you still want to use it, please add 'allowCleartextPasswords=1' to your DSN") ErrNativePassword = errors.New("this user requires mysql native password authentication.") ErrOldPassword = errors.New("this user requires old password authentication. If you still want to use it, please add 'allowOldPasswords=1' to your DSN. See also https://github.com/go-sql-driver/mysql/wiki/old_passwords") ErrUnknownPlugin = errors.New("this authentication plugin is not supported") ErrOldProtocol = errors.New("MySQL server does not support required protocol 41+") ErrPktSync = errors.New("commands out of sync. You can't run this command now") ErrPktSyncMul = errors.New("commands out of sync. Did you run multiple statements at once?") ErrPktTooLarge = errors.New("packet for query is too large. Try adjusting the 'max_allowed_packet' variable on the server") ErrBusyBuffer = errors.New("busy buffer") // errBadConnNoWrite is used for connection errors where nothing was sent to the database yet. // If this happens first in a function starting a database interaction, it should be replaced by driver.ErrBadConn // to trigger a resend. // See https://github.com/go-sql-driver/mysql/pull/302 errBadConnNoWrite = errors.New("bad connection") ) var errLog = Logger(log.New(os.Stderr, "[mysql] ", log.Ldate|log.Ltime|log.Lshortfile)) // Logger is used to log critical error messages. type Logger interface { Print(v ...interface{}) } // SetLogger is used to set the logger for critical errors. // The initial logger is os.Stderr. func SetLogger(logger Logger) error { if logger == nil { return errors.New("logger is nil") } errLog = logger return nil } // MySQLError is an error type which represents a single MySQL error type MySQLError struct { Number uint16 Message string } func (me *MySQLError) Error() string { return fmt.Sprintf("Error %d: %s", me.Number, me.Message) }
vendor/github.com/go-sql-driver/mysql/errors.go
0
https://github.com/grafana/grafana/commit/44eaa3eaa886e0f193e9b6ae364e0526c858cb00
[ 0.00025856465799733996, 0.00018040742725133896, 0.00016452679119538516, 0.0001678205153439194, 0.00003196618126821704 ]
{ "id": 1, "code_window": [ "// Libraries\n", "import React, { PureComponent, ChangeEvent } from 'react';\n", "\n", "// Utils & Services\n", "import { AngularComponent, getAngularLoader } from 'app/core/services/AngularLoader';\n", "import { connectWithStore } from 'app/core/utils/connectWithReduxStore';\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import React, { PureComponent } from 'react';\n" ], "file_path": "public/app/features/dashboard/panel_editor/VisualizationTab.tsx", "type": "replace", "edit_start_line_idx": 1 }
package login import ( "crypto/subtle" "github.com/grafana/grafana/pkg/bus" m "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/util" ) var validatePassword = func(providedPassword string, userPassword string, userSalt string) error { passwordHashed := util.EncodePassword(providedPassword, userSalt) if subtle.ConstantTimeCompare([]byte(passwordHashed), []byte(userPassword)) != 1 { return ErrInvalidCredentials } return nil } var loginUsingGrafanaDB = func(query *m.LoginUserQuery) error { userQuery := m.GetUserByLoginQuery{LoginOrEmail: query.Username} if err := bus.Dispatch(&userQuery); err != nil { return err } user := userQuery.Result if err := validatePassword(query.Password, user.Password, user.Salt); err != nil { return err } query.User = user return nil }
pkg/login/grafana_login.go
0
https://github.com/grafana/grafana/commit/44eaa3eaa886e0f193e9b6ae364e0526c858cb00
[ 0.00017241958994418383, 0.00017025005945470184, 0.00016699334082659334, 0.00017079364624805748, 0.000002188611460951506 ]
{ "id": 2, "code_window": [ "}\n", "\n", "interface State {\n", " isVizPickerOpen: boolean;\n", " searchQuery: string;\n", " searchResults: PanelPlugin[];\n", " scrollTop: number;\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "public/app/features/dashboard/panel_editor/VisualizationTab.tsx", "type": "replace", "edit_start_line_idx": 33 }
import React, { PureComponent } from 'react'; import _ from 'lodash'; import config from 'app/core/config'; import { PanelPlugin } from 'app/types/plugins'; import VizTypePickerPlugin from './VizTypePickerPlugin'; export interface Props { current: PanelPlugin; onTypeChanged: (newType: PanelPlugin) => void; searchQuery: string; onClose: () => void; onPluginListChange: (searchResults: PanelPlugin[]) => void; } export class VizTypePicker extends PureComponent<Props> { searchInput: HTMLElement; pluginList = this.getPanelPlugins(''); constructor(props: Props) { super(props); } get maxSelectedIndex() { const filteredPluginList = this.getFilteredPluginList(); return filteredPluginList.length - 1; } getPanelPlugins(filter): PanelPlugin[] { const panels = _.chain(config.panels) .filter({ hideFromList: false }) .map(item => item) .value(); // add sort by sort property return _.sortBy(panels, 'sort'); } renderVizPlugin = (plugin: PanelPlugin, index: number) => { const { onTypeChanged } = this.props; const isCurrent = plugin.id === this.props.current.id; return ( <VizTypePickerPlugin key={plugin.id} isCurrent={isCurrent} plugin={plugin} onClick={() => onTypeChanged(plugin)} /> ); }; getFilteredPluginList = (): PanelPlugin[] => { const { searchQuery, onPluginListChange } = this.props; const regex = new RegExp(searchQuery, 'i'); const pluginList = this.pluginList; const filtered = pluginList.filter(item => { return regex.test(item.name); }); onPluginListChange(filtered); return filtered; }; render() { const filteredPluginList = this.getFilteredPluginList(); return ( <div className="viz-picker"> <div className="viz-picker-list"> {filteredPluginList.map((plugin, index) => this.renderVizPlugin(plugin, index))} </div> </div> ); } }
public/app/features/dashboard/panel_editor/VizTypePicker.tsx
1
https://github.com/grafana/grafana/commit/44eaa3eaa886e0f193e9b6ae364e0526c858cb00
[ 0.06942865252494812, 0.013451753184199333, 0.0002567881892900914, 0.003042711643502116, 0.022040989249944687 ]
{ "id": 2, "code_window": [ "}\n", "\n", "interface State {\n", " isVizPickerOpen: boolean;\n", " searchQuery: string;\n", " searchResults: PanelPlugin[];\n", " scrollTop: number;\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "public/app/features/dashboard/panel_editor/VisualizationTab.tsx", "type": "replace", "edit_start_line_idx": 33 }
package pretty import ( "fmt" "io" "reflect" "strconv" "text/tabwriter" "github.com/kr/text" ) type formatter struct { v reflect.Value force bool quote bool } // Formatter makes a wrapper, f, that will format x as go source with line // breaks and tabs. Object f responds to the "%v" formatting verb when both the // "#" and " " (space) flags are set, for example: // // fmt.Sprintf("%# v", Formatter(x)) // // If one of these two flags is not set, or any other verb is used, f will // format x according to the usual rules of package fmt. // In particular, if x satisfies fmt.Formatter, then x.Format will be called. func Formatter(x interface{}) (f fmt.Formatter) { return formatter{v: reflect.ValueOf(x), quote: true} } func (fo formatter) String() string { return fmt.Sprint(fo.v.Interface()) // unwrap it } func (fo formatter) passThrough(f fmt.State, c rune) { s := "%" for i := 0; i < 128; i++ { if f.Flag(i) { s += string(i) } } if w, ok := f.Width(); ok { s += fmt.Sprintf("%d", w) } if p, ok := f.Precision(); ok { s += fmt.Sprintf(".%d", p) } s += string(c) fmt.Fprintf(f, s, fo.v.Interface()) } func (fo formatter) Format(f fmt.State, c rune) { if fo.force || c == 'v' && f.Flag('#') && f.Flag(' ') { w := tabwriter.NewWriter(f, 4, 4, 1, ' ', 0) p := &printer{tw: w, Writer: w, visited: make(map[visit]int)} p.printValue(fo.v, true, fo.quote) w.Flush() return } fo.passThrough(f, c) } type printer struct { io.Writer tw *tabwriter.Writer visited map[visit]int depth int } func (p *printer) indent() *printer { q := *p q.tw = tabwriter.NewWriter(p.Writer, 4, 4, 1, ' ', 0) q.Writer = text.NewIndentWriter(q.tw, []byte{'\t'}) return &q } func (p *printer) printInline(v reflect.Value, x interface{}, showType bool) { if showType { io.WriteString(p, v.Type().String()) fmt.Fprintf(p, "(%#v)", x) } else { fmt.Fprintf(p, "%#v", x) } } // printValue must keep track of already-printed pointer values to avoid // infinite recursion. type visit struct { v uintptr typ reflect.Type } func (p *printer) printValue(v reflect.Value, showType, quote bool) { if p.depth > 10 { io.WriteString(p, "!%v(DEPTH EXCEEDED)") return } switch v.Kind() { case reflect.Bool: p.printInline(v, v.Bool(), showType) case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: p.printInline(v, v.Int(), showType) case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: p.printInline(v, v.Uint(), showType) case reflect.Float32, reflect.Float64: p.printInline(v, v.Float(), showType) case reflect.Complex64, reflect.Complex128: fmt.Fprintf(p, "%#v", v.Complex()) case reflect.String: p.fmtString(v.String(), quote) case reflect.Map: t := v.Type() if showType { io.WriteString(p, t.String()) } writeByte(p, '{') if nonzero(v) { expand := !canInline(v.Type()) pp := p if expand { writeByte(p, '\n') pp = p.indent() } keys := v.MapKeys() for i := 0; i < v.Len(); i++ { showTypeInStruct := true k := keys[i] mv := v.MapIndex(k) pp.printValue(k, false, true) writeByte(pp, ':') if expand { writeByte(pp, '\t') } showTypeInStruct = t.Elem().Kind() == reflect.Interface pp.printValue(mv, showTypeInStruct, true) if expand { io.WriteString(pp, ",\n") } else if i < v.Len()-1 { io.WriteString(pp, ", ") } } if expand { pp.tw.Flush() } } writeByte(p, '}') case reflect.Struct: t := v.Type() if v.CanAddr() { addr := v.UnsafeAddr() vis := visit{addr, t} if vd, ok := p.visited[vis]; ok && vd < p.depth { p.fmtString(t.String()+"{(CYCLIC REFERENCE)}", false) break // don't print v again } p.visited[vis] = p.depth } if showType { io.WriteString(p, t.String()) } writeByte(p, '{') if nonzero(v) { expand := !canInline(v.Type()) pp := p if expand { writeByte(p, '\n') pp = p.indent() } for i := 0; i < v.NumField(); i++ { showTypeInStruct := true if f := t.Field(i); f.Name != "" { io.WriteString(pp, f.Name) writeByte(pp, ':') if expand { writeByte(pp, '\t') } showTypeInStruct = labelType(f.Type) } pp.printValue(getField(v, i), showTypeInStruct, true) if expand { io.WriteString(pp, ",\n") } else if i < v.NumField()-1 { io.WriteString(pp, ", ") } } if expand { pp.tw.Flush() } } writeByte(p, '}') case reflect.Interface: switch e := v.Elem(); { case e.Kind() == reflect.Invalid: io.WriteString(p, "nil") case e.IsValid(): pp := *p pp.depth++ pp.printValue(e, showType, true) default: io.WriteString(p, v.Type().String()) io.WriteString(p, "(nil)") } case reflect.Array, reflect.Slice: t := v.Type() if showType { io.WriteString(p, t.String()) } if v.Kind() == reflect.Slice && v.IsNil() && showType { io.WriteString(p, "(nil)") break } if v.Kind() == reflect.Slice && v.IsNil() { io.WriteString(p, "nil") break } writeByte(p, '{') expand := !canInline(v.Type()) pp := p if expand { writeByte(p, '\n') pp = p.indent() } for i := 0; i < v.Len(); i++ { showTypeInSlice := t.Elem().Kind() == reflect.Interface pp.printValue(v.Index(i), showTypeInSlice, true) if expand { io.WriteString(pp, ",\n") } else if i < v.Len()-1 { io.WriteString(pp, ", ") } } if expand { pp.tw.Flush() } writeByte(p, '}') case reflect.Ptr: e := v.Elem() if !e.IsValid() { writeByte(p, '(') io.WriteString(p, v.Type().String()) io.WriteString(p, ")(nil)") } else { pp := *p pp.depth++ writeByte(pp, '&') pp.printValue(e, true, true) } case reflect.Chan: x := v.Pointer() if showType { writeByte(p, '(') io.WriteString(p, v.Type().String()) fmt.Fprintf(p, ")(%#v)", x) } else { fmt.Fprintf(p, "%#v", x) } case reflect.Func: io.WriteString(p, v.Type().String()) io.WriteString(p, " {...}") case reflect.UnsafePointer: p.printInline(v, v.Pointer(), showType) case reflect.Invalid: io.WriteString(p, "nil") } } func canInline(t reflect.Type) bool { switch t.Kind() { case reflect.Map: return !canExpand(t.Elem()) case reflect.Struct: for i := 0; i < t.NumField(); i++ { if canExpand(t.Field(i).Type) { return false } } return true case reflect.Interface: return false case reflect.Array, reflect.Slice: return !canExpand(t.Elem()) case reflect.Ptr: return false case reflect.Chan, reflect.Func, reflect.UnsafePointer: return false } return true } func canExpand(t reflect.Type) bool { switch t.Kind() { case reflect.Map, reflect.Struct, reflect.Interface, reflect.Array, reflect.Slice, reflect.Ptr: return true } return false } func labelType(t reflect.Type) bool { switch t.Kind() { case reflect.Interface, reflect.Struct: return true } return false } func (p *printer) fmtString(s string, quote bool) { if quote { s = strconv.Quote(s) } io.WriteString(p, s) } func writeByte(w io.Writer, b byte) { w.Write([]byte{b}) } func getField(v reflect.Value, i int) reflect.Value { val := v.Field(i) if val.Kind() == reflect.Interface && !val.IsNil() { val = val.Elem() } return val }
vendor/github.com/kr/pretty/formatter.go
0
https://github.com/grafana/grafana/commit/44eaa3eaa886e0f193e9b6ae364e0526c858cb00
[ 0.9853157997131348, 0.05905763804912567, 0.00016522323130629957, 0.00017458411457482725, 0.23185069859027863 ]
{ "id": 2, "code_window": [ "}\n", "\n", "interface State {\n", " isVizPickerOpen: boolean;\n", " searchQuery: string;\n", " searchResults: PanelPlugin[];\n", " scrollTop: number;\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "public/app/features/dashboard/panel_editor/VisualizationTab.tsx", "type": "replace", "edit_start_line_idx": 33 }
<?xml version="1.0" encoding="utf-8"?> <!-- Generator: Adobe Illustrator 19.0.1, SVG Export Plug-In . SVG Version: 6.00 Build 0) --> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> <svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="121px" height="100px" viewBox="0 0 121 100" style="enable-background:new 0 0 100 100;" xml:space="preserve"> <style type="text/css"> .st0{fill:#FFFFFF;} .st1{fill:#52545c;} </style> <g> <path class="st0" d="M94.3,50C94.3,25.6,74.4,5.7,50,5.7S5.7,25.6,5.7,50S25.6,94.3,50,94.3S94.3,74.4,94.3,50z M49.1,73.7 c-13.9,0-25.7-5.6-25.7-12.3c0-0.7,0.1-1.3,0.4-2c4.4,5,14,8.3,25.3,8.3s20.9-3.4,25.3-8.3c0.2,0.6,0.4,1.3,0.4,2 C74.8,68,63.1,73.7,49.1,73.7z M49.1,62.5c-13.9,0-25.7-5.6-25.7-12.3c0-0.7,0.1-1.3,0.4-2c4.4,5,14,8.3,25.3,8.3 s20.9-3.4,25.3-8.3c0.2,0.6,0.4,1.3,0.4,2C74.8,56.9,63.1,62.5,49.1,62.5z M49.1,51.3c-13.9,0-25.7-5.6-25.7-12.3 c0-6.7,11.8-12.3,25.7-12.3S74.8,32.4,74.8,39C74.8,45.7,63.1,51.3,49.1,51.3z"/> <path class="st1" d="M49.1,67.7c-11.4,0-20.9-3.4-25.3-8.3c-0.2,0.6-0.4,1.3-0.4,2c0,6.7,11.8,12.3,25.7,12.3S74.8,68,74.8,61.4 c0-0.7-0.1-1.3-0.4-2C70.1,64.4,60.5,67.7,49.1,67.7z"/> <path class="st1" d="M49.1,56.5c-11.4,0-20.9-3.4-25.3-8.3c-0.2,0.6-0.4,1.3-0.4,2c0,6.7,11.8,12.3,25.7,12.3s25.7-5.6,25.7-12.3 c0-0.7-0.1-1.3-0.4-2C70.1,53.2,60.5,56.5,49.1,56.5z"/> <path class="st1" d="M49.1,26.7c-13.9,0-25.7,5.6-25.7,12.3c0,6.7,11.8,12.3,25.7,12.3S74.8,45.7,74.8,39 C74.8,32.4,63.1,26.7,49.1,26.7z"/> <path class="st1" d="M50,0C22.4,0,0,22.4,0,50s22.4,50,50,50c27.6,0,50-22.4,50-50S77.6,0,50,0z M5.7,50C5.7,25.6,25.6,5.7,50,5.7 S94.3,25.6,94.3,50S74.4,94.3,50,94.3S5.7,74.4,5.7,50z"/> </g> </svg>
public/img/icons_light_theme/icon_query.svg
0
https://github.com/grafana/grafana/commit/44eaa3eaa886e0f193e9b6ae364e0526c858cb00
[ 0.00042029464384540915, 0.00025323309819214046, 0.00016920556663535535, 0.00017019908409565687, 0.00011813105084002018 ]
{ "id": 2, "code_window": [ "}\n", "\n", "interface State {\n", " isVizPickerOpen: boolean;\n", " searchQuery: string;\n", " searchResults: PanelPlugin[];\n", " scrollTop: number;\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "public/app/features/dashboard/panel_editor/VisualizationTab.tsx", "type": "replace", "edit_start_line_idx": 33 }
// cgo -godefs types_dragonfly.go | go run mkpost.go // Code generated by the command above; see README.md. DO NOT EDIT. // +build amd64,dragonfly package unix const ( sizeofPtr = 0x8 sizeofShort = 0x2 sizeofInt = 0x4 sizeofLong = 0x8 sizeofLongLong = 0x8 ) type ( _C_short int16 _C_int int32 _C_long int64 _C_long_long int64 ) type Timespec struct { Sec int64 Nsec int64 } type Timeval struct { Sec int64 Usec int64 } type Rusage struct { Utime Timeval Stime Timeval Maxrss int64 Ixrss int64 Idrss int64 Isrss int64 Minflt int64 Majflt int64 Nswap int64 Inblock int64 Oublock int64 Msgsnd int64 Msgrcv int64 Nsignals int64 Nvcsw int64 Nivcsw int64 } type Rlimit struct { Cur int64 Max int64 } type _Gid_t uint32 const ( S_IFMT = 0xf000 S_IFIFO = 0x1000 S_IFCHR = 0x2000 S_IFDIR = 0x4000 S_IFBLK = 0x6000 S_IFREG = 0x8000 S_IFLNK = 0xa000 S_IFSOCK = 0xc000 S_ISUID = 0x800 S_ISGID = 0x400 S_ISVTX = 0x200 S_IRUSR = 0x100 S_IWUSR = 0x80 S_IXUSR = 0x40 ) type Stat_t struct { Ino uint64 Nlink uint32 Dev uint32 Mode uint16 Padding1 uint16 Uid uint32 Gid uint32 Rdev uint32 Atim Timespec Mtim Timespec Ctim Timespec Size int64 Blocks int64 Blksize uint32 Flags uint32 Gen uint32 Lspare int32 Qspare1 int64 Qspare2 int64 } type Statfs_t struct { Spare2 int64 Bsize int64 Iosize int64 Blocks int64 Bfree int64 Bavail int64 Files int64 Ffree int64 Fsid Fsid Owner uint32 Type int32 Flags int32 _ [4]byte Syncwrites int64 Asyncwrites int64 Fstypename [16]int8 Mntonname [80]int8 Syncreads int64 Asyncreads int64 Spares1 int16 Mntfromname [80]int8 Spares2 int16 _ [4]byte Spare [2]int64 } type Flock_t struct { Start int64 Len int64 Pid int32 Type int16 Whence int16 } type Dirent struct { Fileno uint64 Namlen uint16 Type uint8 Unused1 uint8 Unused2 uint32 Name [256]int8 } type Fsid struct { Val [2]int32 } const ( PathMax = 0x400 ) type RawSockaddrInet4 struct { Len uint8 Family uint8 Port uint16 Addr [4]byte /* in_addr */ Zero [8]int8 } type RawSockaddrInet6 struct { Len uint8 Family uint8 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } type RawSockaddrUnix struct { Len uint8 Family uint8 Path [104]int8 } type RawSockaddrDatalink struct { Len uint8 Family uint8 Index uint16 Type uint8 Nlen uint8 Alen uint8 Slen uint8 Data [12]int8 Rcf uint16 Route [16]uint16 } type RawSockaddr struct { Len uint8 Family uint8 Data [14]int8 } type RawSockaddrAny struct { Addr RawSockaddr Pad [92]int8 } type _Socklen uint32 type Linger struct { Onoff int32 Linger int32 } type Iovec struct { Base *byte Len uint64 } type IPMreq struct { Multiaddr [4]byte /* in_addr */ Interface [4]byte /* in_addr */ } type IPv6Mreq struct { Multiaddr [16]byte /* in6_addr */ Interface uint32 } type Msghdr struct { Name *byte Namelen uint32 _ [4]byte Iov *Iovec Iovlen int32 _ [4]byte Control *byte Controllen uint32 Flags int32 } type Cmsghdr struct { Len uint32 Level int32 Type int32 } type Inet6Pktinfo struct { Addr [16]byte /* in6_addr */ Ifindex uint32 } type IPv6MTUInfo struct { Addr RawSockaddrInet6 Mtu uint32 } type ICMPv6Filter struct { Filt [8]uint32 } const ( SizeofSockaddrInet4 = 0x10 SizeofSockaddrInet6 = 0x1c SizeofSockaddrAny = 0x6c SizeofSockaddrUnix = 0x6a SizeofSockaddrDatalink = 0x36 SizeofLinger = 0x8 SizeofIPMreq = 0x8 SizeofIPv6Mreq = 0x14 SizeofMsghdr = 0x30 SizeofCmsghdr = 0xc SizeofInet6Pktinfo = 0x14 SizeofIPv6MTUInfo = 0x20 SizeofICMPv6Filter = 0x20 ) const ( PTRACE_TRACEME = 0x0 PTRACE_CONT = 0x7 PTRACE_KILL = 0x8 ) type Kevent_t struct { Ident uint64 Filter int16 Flags uint16 Fflags uint32 Data int64 Udata *byte } type FdSet struct { Bits [16]uint64 } const ( SizeofIfMsghdr = 0xb0 SizeofIfData = 0xa0 SizeofIfaMsghdr = 0x14 SizeofIfmaMsghdr = 0x10 SizeofIfAnnounceMsghdr = 0x18 SizeofRtMsghdr = 0x98 SizeofRtMetrics = 0x70 ) type IfMsghdr struct { Msglen uint16 Version uint8 Type uint8 Addrs int32 Flags int32 Index uint16 _ [2]byte Data IfData } type IfData struct { Type uint8 Physical uint8 Addrlen uint8 Hdrlen uint8 Recvquota uint8 Xmitquota uint8 _ [2]byte Mtu uint64 Metric uint64 Link_state uint64 Baudrate uint64 Ipackets uint64 Ierrors uint64 Opackets uint64 Oerrors uint64 Collisions uint64 Ibytes uint64 Obytes uint64 Imcasts uint64 Omcasts uint64 Iqdrops uint64 Noproto uint64 Hwassist uint64 Oqdrops uint64 Lastchange Timeval } type IfaMsghdr struct { Msglen uint16 Version uint8 Type uint8 Addrs int32 Flags int32 Index uint16 _ [2]byte Metric int32 } type IfmaMsghdr struct { Msglen uint16 Version uint8 Type uint8 Addrs int32 Flags int32 Index uint16 _ [2]byte } type IfAnnounceMsghdr struct { Msglen uint16 Version uint8 Type uint8 Index uint16 Name [16]int8 What uint16 } type RtMsghdr struct { Msglen uint16 Version uint8 Type uint8 Index uint16 _ [2]byte Flags int32 Addrs int32 Pid int32 Seq int32 Errno int32 Use int32 Inits uint64 Rmx RtMetrics } type RtMetrics struct { Locks uint64 Mtu uint64 Pksent uint64 Expire uint64 Sendpipe uint64 Ssthresh uint64 Rtt uint64 Rttvar uint64 Recvpipe uint64 Hopcount uint64 Mssopt uint16 Pad uint16 _ [4]byte Msl uint64 Iwmaxsegs uint64 Iwcapsegs uint64 } const ( SizeofBpfVersion = 0x4 SizeofBpfStat = 0x8 SizeofBpfProgram = 0x10 SizeofBpfInsn = 0x8 SizeofBpfHdr = 0x20 ) type BpfVersion struct { Major uint16 Minor uint16 } type BpfStat struct { Recv uint32 Drop uint32 } type BpfProgram struct { Len uint32 _ [4]byte Insns *BpfInsn } type BpfInsn struct { Code uint16 Jt uint8 Jf uint8 K uint32 } type BpfHdr struct { Tstamp Timeval Caplen uint32 Datalen uint32 Hdrlen uint16 _ [6]byte } type Termios struct { Iflag uint32 Oflag uint32 Cflag uint32 Lflag uint32 Cc [20]uint8 Ispeed uint32 Ospeed uint32 } type Winsize struct { Row uint16 Col uint16 Xpixel uint16 Ypixel uint16 } const ( AT_FDCWD = 0xfffafdcd AT_SYMLINK_NOFOLLOW = 0x1 ) type PollFd struct { Fd int32 Events int16 Revents int16 } const ( POLLERR = 0x8 POLLHUP = 0x10 POLLIN = 0x1 POLLNVAL = 0x20 POLLOUT = 0x4 POLLPRI = 0x2 POLLRDBAND = 0x80 POLLRDNORM = 0x40 POLLWRBAND = 0x100 POLLWRNORM = 0x4 ) type Utsname struct { Sysname [32]byte Nodename [32]byte Release [32]byte Version [32]byte Machine [32]byte }
vendor/golang.org/x/sys/unix/ztypes_dragonfly_amd64.go
0
https://github.com/grafana/grafana/commit/44eaa3eaa886e0f193e9b6ae364e0526c858cb00
[ 0.00020926045544911176, 0.0001720701256999746, 0.0001649844052735716, 0.00017042628314811736, 0.0000079768424257054 ]
{ "id": 3, "code_window": [ " angularOptions: AngularComponent;\n", " searchInput: HTMLElement;\n", "\n", " constructor(props: Props) {\n", " super(props);\n", "\n", " this.state = {\n", " isVizPickerOpen: this.props.urlOpenVizPicker,\n", " searchQuery: '',\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " constructor(props) {\n" ], "file_path": "public/app/features/dashboard/panel_editor/VisualizationTab.tsx", "type": "replace", "edit_start_line_idx": 42 }
import React, { PureComponent } from 'react'; import _ from 'lodash'; import config from 'app/core/config'; import { PanelPlugin } from 'app/types/plugins'; import VizTypePickerPlugin from './VizTypePickerPlugin'; export interface Props { current: PanelPlugin; onTypeChanged: (newType: PanelPlugin) => void; searchQuery: string; onClose: () => void; onPluginListChange: (searchResults: PanelPlugin[]) => void; } export class VizTypePicker extends PureComponent<Props> { searchInput: HTMLElement; pluginList = this.getPanelPlugins(''); constructor(props: Props) { super(props); } get maxSelectedIndex() { const filteredPluginList = this.getFilteredPluginList(); return filteredPluginList.length - 1; } getPanelPlugins(filter): PanelPlugin[] { const panels = _.chain(config.panels) .filter({ hideFromList: false }) .map(item => item) .value(); // add sort by sort property return _.sortBy(panels, 'sort'); } renderVizPlugin = (plugin: PanelPlugin, index: number) => { const { onTypeChanged } = this.props; const isCurrent = plugin.id === this.props.current.id; return ( <VizTypePickerPlugin key={plugin.id} isCurrent={isCurrent} plugin={plugin} onClick={() => onTypeChanged(plugin)} /> ); }; getFilteredPluginList = (): PanelPlugin[] => { const { searchQuery, onPluginListChange } = this.props; const regex = new RegExp(searchQuery, 'i'); const pluginList = this.pluginList; const filtered = pluginList.filter(item => { return regex.test(item.name); }); onPluginListChange(filtered); return filtered; }; render() { const filteredPluginList = this.getFilteredPluginList(); return ( <div className="viz-picker"> <div className="viz-picker-list"> {filteredPluginList.map((plugin, index) => this.renderVizPlugin(plugin, index))} </div> </div> ); } }
public/app/features/dashboard/panel_editor/VizTypePicker.tsx
1
https://github.com/grafana/grafana/commit/44eaa3eaa886e0f193e9b6ae364e0526c858cb00
[ 0.013818061910569668, 0.0049214838072657585, 0.0001685016613919288, 0.002357069868594408, 0.005145430099219084 ]
{ "id": 3, "code_window": [ " angularOptions: AngularComponent;\n", " searchInput: HTMLElement;\n", "\n", " constructor(props: Props) {\n", " super(props);\n", "\n", " this.state = {\n", " isVizPickerOpen: this.props.urlOpenVizPicker,\n", " searchQuery: '',\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " constructor(props) {\n" ], "file_path": "public/app/features/dashboard/panel_editor/VisualizationTab.tsx", "type": "replace", "edit_start_line_idx": 42 }
// Copyright 2014 The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package model import ( "sort" ) // SeparatorByte is a byte that cannot occur in valid UTF-8 sequences and is // used to separate label names, label values, and other strings from each other // when calculating their combined hash value (aka signature aka fingerprint). const SeparatorByte byte = 255 var ( // cache the signature of an empty label set. emptyLabelSignature = hashNew() ) // LabelsToSignature returns a quasi-unique signature (i.e., fingerprint) for a // given label set. (Collisions are possible but unlikely if the number of label // sets the function is applied to is small.) func LabelsToSignature(labels map[string]string) uint64 { if len(labels) == 0 { return emptyLabelSignature } labelNames := make([]string, 0, len(labels)) for labelName := range labels { labelNames = append(labelNames, labelName) } sort.Strings(labelNames) sum := hashNew() for _, labelName := range labelNames { sum = hashAdd(sum, labelName) sum = hashAddByte(sum, SeparatorByte) sum = hashAdd(sum, labels[labelName]) sum = hashAddByte(sum, SeparatorByte) } return sum } // labelSetToFingerprint works exactly as LabelsToSignature but takes a LabelSet as // parameter (rather than a label map) and returns a Fingerprint. func labelSetToFingerprint(ls LabelSet) Fingerprint { if len(ls) == 0 { return Fingerprint(emptyLabelSignature) } labelNames := make(LabelNames, 0, len(ls)) for labelName := range ls { labelNames = append(labelNames, labelName) } sort.Sort(labelNames) sum := hashNew() for _, labelName := range labelNames { sum = hashAdd(sum, string(labelName)) sum = hashAddByte(sum, SeparatorByte) sum = hashAdd(sum, string(ls[labelName])) sum = hashAddByte(sum, SeparatorByte) } return Fingerprint(sum) } // labelSetToFastFingerprint works similar to labelSetToFingerprint but uses a // faster and less allocation-heavy hash function, which is more susceptible to // create hash collisions. Therefore, collision detection should be applied. func labelSetToFastFingerprint(ls LabelSet) Fingerprint { if len(ls) == 0 { return Fingerprint(emptyLabelSignature) } var result uint64 for labelName, labelValue := range ls { sum := hashNew() sum = hashAdd(sum, string(labelName)) sum = hashAddByte(sum, SeparatorByte) sum = hashAdd(sum, string(labelValue)) result ^= sum } return Fingerprint(result) } // SignatureForLabels works like LabelsToSignature but takes a Metric as // parameter (rather than a label map) and only includes the labels with the // specified LabelNames into the signature calculation. The labels passed in // will be sorted by this function. func SignatureForLabels(m Metric, labels ...LabelName) uint64 { if len(labels) == 0 { return emptyLabelSignature } sort.Sort(LabelNames(labels)) sum := hashNew() for _, label := range labels { sum = hashAdd(sum, string(label)) sum = hashAddByte(sum, SeparatorByte) sum = hashAdd(sum, string(m[label])) sum = hashAddByte(sum, SeparatorByte) } return sum } // SignatureWithoutLabels works like LabelsToSignature but takes a Metric as // parameter (rather than a label map) and excludes the labels with any of the // specified LabelNames from the signature calculation. func SignatureWithoutLabels(m Metric, labels map[LabelName]struct{}) uint64 { if len(m) == 0 { return emptyLabelSignature } labelNames := make(LabelNames, 0, len(m)) for labelName := range m { if _, exclude := labels[labelName]; !exclude { labelNames = append(labelNames, labelName) } } if len(labelNames) == 0 { return emptyLabelSignature } sort.Sort(labelNames) sum := hashNew() for _, labelName := range labelNames { sum = hashAdd(sum, string(labelName)) sum = hashAddByte(sum, SeparatorByte) sum = hashAdd(sum, string(m[labelName])) sum = hashAddByte(sum, SeparatorByte) } return sum }
vendor/github.com/prometheus/common/model/signature.go
0
https://github.com/grafana/grafana/commit/44eaa3eaa886e0f193e9b6ae364e0526c858cb00
[ 0.0001784182240953669, 0.00017190199287142605, 0.00016647028678562492, 0.00017146082245744765, 0.000003519242682159529 ]
{ "id": 3, "code_window": [ " angularOptions: AngularComponent;\n", " searchInput: HTMLElement;\n", "\n", " constructor(props: Props) {\n", " super(props);\n", "\n", " this.state = {\n", " isVizPickerOpen: this.props.urlOpenVizPicker,\n", " searchQuery: '',\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " constructor(props) {\n" ], "file_path": "public/app/features/dashboard/panel_editor/VisualizationTab.tsx", "type": "replace", "edit_start_line_idx": 42 }
package imguploader import ( "context" "testing" "github.com/grafana/grafana/pkg/setting" . "github.com/smartystreets/goconvey/convey" ) func TestUploadToS3(t *testing.T) { SkipConvey("[Integration test] for external_image_store.s3", t, func() { cfg := setting.NewCfg() cfg.Load(&setting.CommandLineArgs{ HomePath: "../../../", }) s3Uploader, _ := NewImageUploader() path, err := s3Uploader.Upload(context.Background(), "../../../public/img/logo_transparent_400x.png") So(err, ShouldBeNil) So(path, ShouldNotEqual, "") }) }
pkg/components/imguploader/s3uploader_test.go
0
https://github.com/grafana/grafana/commit/44eaa3eaa886e0f193e9b6ae364e0526c858cb00
[ 0.00017715479771140963, 0.0001737395068630576, 0.00017052852490451187, 0.00017353519797325134, 0.0000027090195544587914 ]
{ "id": 3, "code_window": [ " angularOptions: AngularComponent;\n", " searchInput: HTMLElement;\n", "\n", " constructor(props: Props) {\n", " super(props);\n", "\n", " this.state = {\n", " isVizPickerOpen: this.props.urlOpenVizPicker,\n", " searchQuery: '',\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " constructor(props) {\n" ], "file_path": "public/app/features/dashboard/panel_editor/VisualizationTab.tsx", "type": "replace", "edit_start_line_idx": 42 }
package graphite import "github.com/grafana/grafana/pkg/tsdb" type TargetResponseDTO struct { Target string `json:"target"` DataPoints tsdb.TimeSeriesPoints `json:"datapoints"` }
pkg/tsdb/graphite/types.go
0
https://github.com/grafana/grafana/commit/44eaa3eaa886e0f193e9b6ae364e0526c858cb00
[ 0.00017312266572844237, 0.00017312266572844237, 0.00017312266572844237, 0.00017312266572844237, 0 ]
{ "id": 4, "code_window": [ " this.state = {\n", " isVizPickerOpen: this.props.urlOpenVizPicker,\n", " searchQuery: '',\n", " searchResults: [],\n", " scrollTop: 0,\n", " };\n", " }\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "public/app/features/dashboard/panel_editor/VisualizationTab.tsx", "type": "replace", "edit_start_line_idx": 48 }
// Libraries import React, { PureComponent, ChangeEvent } from 'react'; // Utils & Services import { AngularComponent, getAngularLoader } from 'app/core/services/AngularLoader'; import { connectWithStore } from 'app/core/utils/connectWithReduxStore'; import { StoreState } from 'app/types'; import { updateLocation } from 'app/core/actions'; // Components import { EditorTabBody, EditorToolbarView } from './EditorTabBody'; import { VizTypePicker } from './VizTypePicker'; import { PluginHelp } from 'app/core/components/PluginHelp/PluginHelp'; import { FadeIn } from 'app/core/components/Animations/FadeIn'; // Types import { PanelModel } from '../state/PanelModel'; import { DashboardModel } from '../state/DashboardModel'; import { PanelPlugin } from 'app/types/plugins'; interface Props { panel: PanelModel; dashboard: DashboardModel; plugin: PanelPlugin; angularPanel?: AngularComponent; onTypeChanged: (newType: PanelPlugin) => void; updateLocation: typeof updateLocation; urlOpenVizPicker: boolean; } interface State { isVizPickerOpen: boolean; searchQuery: string; searchResults: PanelPlugin[]; scrollTop: number; } export class VisualizationTab extends PureComponent<Props, State> { element: HTMLElement; angularOptions: AngularComponent; searchInput: HTMLElement; constructor(props: Props) { super(props); this.state = { isVizPickerOpen: this.props.urlOpenVizPicker, searchQuery: '', searchResults: [], scrollTop: 0, }; } getPanelDefaultOptions = () => { const { panel, plugin } = this.props; if (plugin.exports.PanelDefaults) { return panel.getOptions(plugin.exports.PanelDefaults.options); } return panel.getOptions(plugin.exports.PanelDefaults); }; renderPanelOptions() { const { plugin, angularPanel } = this.props; const { PanelOptions } = plugin.exports; if (angularPanel) { return <div ref={element => (this.element = element)} />; } return ( <> {PanelOptions ? ( <PanelOptions options={this.getPanelDefaultOptions()} onChange={this.onPanelOptionsChanged} /> ) : ( <p>Visualization has no options</p> )} </> ); } componentDidMount() { if (this.shouldLoadAngularOptions()) { this.loadAngularOptions(); } } componentDidUpdate(prevProps: Props) { if (this.props.plugin !== prevProps.plugin) { this.cleanUpAngularOptions(); } if (this.shouldLoadAngularOptions()) { this.loadAngularOptions(); } } shouldLoadAngularOptions() { return this.props.angularPanel && this.element && !this.angularOptions; } loadAngularOptions() { const { angularPanel } = this.props; const scope = angularPanel.getScope(); // When full page reloading in edit mode the angular panel has on fully compiled & instantiated yet if (!scope.$$childHead) { setTimeout(() => { this.forceUpdate(); }); return; } const panelCtrl = scope.$$childHead.ctrl; panelCtrl.initEditMode(); let template = ''; for (let i = 0; i < panelCtrl.editorTabs.length; i++) { template += ` <div class="panel-options-group" ng-cloak>` + (i > 0 ? `<div class="panel-options-group__header"> <span class="panel-options-group__title">{{ctrl.editorTabs[${i}].title}} </span> </div>` : '') + `<div class="panel-options-group__body"> <panel-editor-tab editor-tab="ctrl.editorTabs[${i}]" ctrl="ctrl"></panel-editor-tab> </div> </div> `; } const loader = getAngularLoader(); const scopeProps = { ctrl: panelCtrl }; this.angularOptions = loader.load(this.element, scopeProps, template); } componentWillUnmount() { this.cleanUpAngularOptions(); } cleanUpAngularOptions() { if (this.angularOptions) { this.angularOptions.destroy(); this.angularOptions = null; } } clearQuery = () => { this.setState({ searchQuery: '' }); }; onPanelOptionsChanged = (options: any) => { this.props.panel.updateOptions(options); this.forceUpdate(); }; onOpenVizPicker = () => { this.setState({ isVizPickerOpen: true, scrollTop: 0 }); }; onCloseVizPicker = () => { if (this.props.urlOpenVizPicker) { this.props.updateLocation({ query: { openVizPicker: null }, partial: true }); } this.setState({ isVizPickerOpen: false }); }; onSearchQueryChange = (evt: ChangeEvent<HTMLInputElement>) => { const value = evt.target.value; this.setState({ searchQuery: value, }); }; renderToolbar = (): JSX.Element => { const { plugin } = this.props; const { searchQuery } = this.state; if (this.state.isVizPickerOpen) { return ( <> <label className="gf-form--has-input-icon"> <input type="text" className={`gf-form-input width-13 ${!this.hasSearchResults ? 'gf-form-input--invalid' : ''}`} placeholder="" onChange={this.onSearchQueryChange} value={searchQuery} ref={elem => elem && elem.focus()} /> <i className="gf-form-input-icon fa fa-search" /> </label> <button className="btn btn-link toolbar__close" onClick={this.onCloseVizPicker}> <i className="fa fa-chevron-up" /> </button> </> ); } else { return ( <div className="toolbar__main" onClick={this.onOpenVizPicker}> <img className="toolbar__main-image" src={plugin.info.logos.small} /> <div className="toolbar__main-name">{plugin.name}</div> <i className="fa fa-caret-down" /> </div> ); } }; onTypeChanged = (plugin: PanelPlugin) => { if (plugin.id === this.props.plugin.id) { this.setState({ isVizPickerOpen: false }); } else { this.props.onTypeChanged(plugin); } }; setSearchResults = (searchResults: PanelPlugin[]) => { this.setState({ searchResults: searchResults }); }; get hasSearchResults () { return this.state.searchResults && this.state.searchResults.length > 0; } renderHelp = () => <PluginHelp plugin={this.props.plugin} type="help" />; setScrollTop = (event: React.MouseEvent<HTMLElement>) => { const target = event.target as HTMLElement; this.setState({ scrollTop: target.scrollTop }); }; render() { const { plugin } = this.props; const { isVizPickerOpen, searchQuery, scrollTop } = this.state; const pluginHelp: EditorToolbarView = { heading: 'Help', icon: 'fa fa-question', render: this.renderHelp, }; return ( <EditorTabBody heading="Visualization" renderToolbar={this.renderToolbar} toolbarItems={[pluginHelp]} scrollTop={scrollTop} setScrollTop={this.setScrollTop} > <> <FadeIn in={isVizPickerOpen} duration={200} unmountOnExit={true} onExited={this.clearQuery}> <VizTypePicker current={plugin} onTypeChanged={this.onTypeChanged} searchQuery={searchQuery} onClose={this.onCloseVizPicker} onPluginListChange={this.setSearchResults} /> </FadeIn> {this.renderPanelOptions()} </> </EditorTabBody> ); } } const mapStateToProps = (state: StoreState) => ({ urlOpenVizPicker: !!state.location.query.openVizPicker, }); const mapDispatchToProps = { updateLocation, }; export default connectWithStore(VisualizationTab, mapStateToProps, mapDispatchToProps);
public/app/features/dashboard/panel_editor/VisualizationTab.tsx
1
https://github.com/grafana/grafana/commit/44eaa3eaa886e0f193e9b6ae364e0526c858cb00
[ 0.9961450099945068, 0.06412921100854874, 0.00016514290473423898, 0.00040678965160623193, 0.21757976710796356 ]
{ "id": 4, "code_window": [ " this.state = {\n", " isVizPickerOpen: this.props.urlOpenVizPicker,\n", " searchQuery: '',\n", " searchResults: [],\n", " scrollTop: 0,\n", " };\n", " }\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "public/app/features/dashboard/panel_editor/VisualizationTab.tsx", "type": "replace", "edit_start_line_idx": 48 }
/*- * Copyright 2014 Square Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jose import ( "encoding/base64" "errors" "fmt" "strings" "gopkg.in/square/go-jose.v2/json" ) // rawJSONWebSignature represents a raw JWS JSON object. Used for parsing/serializing. type rawJSONWebSignature struct { Payload *byteBuffer `json:"payload,omitempty"` Signatures []rawSignatureInfo `json:"signatures,omitempty"` Protected *byteBuffer `json:"protected,omitempty"` Header *rawHeader `json:"header,omitempty"` Signature *byteBuffer `json:"signature,omitempty"` } // rawSignatureInfo represents a single JWS signature over the JWS payload and protected header. type rawSignatureInfo struct { Protected *byteBuffer `json:"protected,omitempty"` Header *rawHeader `json:"header,omitempty"` Signature *byteBuffer `json:"signature,omitempty"` } // JSONWebSignature represents a signed JWS object after parsing. type JSONWebSignature struct { payload []byte // Signatures attached to this object (may be more than one for multi-sig). // Be careful about accessing these directly, prefer to use Verify() or // VerifyMulti() to ensure that the data you're getting is verified. Signatures []Signature } // Signature represents a single signature over the JWS payload and protected header. type Signature struct { // Merged header fields. Contains both protected and unprotected header // values. Prefer using Protected and Unprotected fields instead of this. // Values in this header may or may not have been signed and in general // should not be trusted. Header Header // Protected header. Values in this header were signed and // will be verified as part of the signature verification process. Protected Header // Unprotected header. Values in this header were not signed // and in general should not be trusted. Unprotected Header // The actual signature value Signature []byte protected *rawHeader header *rawHeader original *rawSignatureInfo } // ParseSigned parses a signed message in compact or full serialization format. func ParseSigned(input string) (*JSONWebSignature, error) { input = stripWhitespace(input) if strings.HasPrefix(input, "{") { return parseSignedFull(input) } return parseSignedCompact(input) } // Get a header value func (sig Signature) mergedHeaders() rawHeader { out := rawHeader{} out.merge(sig.protected) out.merge(sig.header) return out } // Compute data to be signed func (obj JSONWebSignature) computeAuthData(payload []byte, signature *Signature) []byte { var serializedProtected string if signature.original != nil && signature.original.Protected != nil { serializedProtected = signature.original.Protected.base64() } else if signature.protected != nil { serializedProtected = base64.RawURLEncoding.EncodeToString(mustSerializeJSON(signature.protected)) } else { serializedProtected = "" } return []byte(fmt.Sprintf("%s.%s", serializedProtected, base64.RawURLEncoding.EncodeToString(payload))) } // parseSignedFull parses a message in full format. func parseSignedFull(input string) (*JSONWebSignature, error) { var parsed rawJSONWebSignature err := json.Unmarshal([]byte(input), &parsed) if err != nil { return nil, err } return parsed.sanitized() } // sanitized produces a cleaned-up JWS object from the raw JSON. func (parsed *rawJSONWebSignature) sanitized() (*JSONWebSignature, error) { if parsed.Payload == nil { return nil, fmt.Errorf("square/go-jose: missing payload in JWS message") } obj := &JSONWebSignature{ payload: parsed.Payload.bytes(), Signatures: make([]Signature, len(parsed.Signatures)), } if len(parsed.Signatures) == 0 { // No signatures array, must be flattened serialization signature := Signature{} if parsed.Protected != nil && len(parsed.Protected.bytes()) > 0 { signature.protected = &rawHeader{} err := json.Unmarshal(parsed.Protected.bytes(), signature.protected) if err != nil { return nil, err } } // Check that there is not a nonce in the unprotected header if parsed.Header != nil && parsed.Header.getNonce() != "" { return nil, ErrUnprotectedNonce } signature.header = parsed.Header signature.Signature = parsed.Signature.bytes() // Make a fake "original" rawSignatureInfo to store the unprocessed // Protected header. This is necessary because the Protected header can // contain arbitrary fields not registered as part of the spec. See // https://tools.ietf.org/html/draft-ietf-jose-json-web-signature-41#section-4 // If we unmarshal Protected into a rawHeader with its explicit list of fields, // we cannot marshal losslessly. So we have to keep around the original bytes. // This is used in computeAuthData, which will first attempt to use // the original bytes of a protected header, and fall back on marshaling the // header struct only if those bytes are not available. signature.original = &rawSignatureInfo{ Protected: parsed.Protected, Header: parsed.Header, Signature: parsed.Signature, } var err error signature.Header, err = signature.mergedHeaders().sanitized() if err != nil { return nil, err } if signature.header != nil { signature.Unprotected, err = signature.header.sanitized() if err != nil { return nil, err } } if signature.protected != nil { signature.Protected, err = signature.protected.sanitized() if err != nil { return nil, err } } // As per RFC 7515 Section 4.1.3, only public keys are allowed to be embedded. jwk := signature.Header.JSONWebKey if jwk != nil && (!jwk.Valid() || !jwk.IsPublic()) { return nil, errors.New("square/go-jose: invalid embedded jwk, must be public key") } obj.Signatures = append(obj.Signatures, signature) } for i, sig := range parsed.Signatures { if sig.Protected != nil && len(sig.Protected.bytes()) > 0 { obj.Signatures[i].protected = &rawHeader{} err := json.Unmarshal(sig.Protected.bytes(), obj.Signatures[i].protected) if err != nil { return nil, err } } // Check that there is not a nonce in the unprotected header if sig.Header != nil && sig.Header.getNonce() != "" { return nil, ErrUnprotectedNonce } var err error obj.Signatures[i].Header, err = obj.Signatures[i].mergedHeaders().sanitized() if err != nil { return nil, err } if obj.Signatures[i].header != nil { obj.Signatures[i].Unprotected, err = obj.Signatures[i].header.sanitized() if err != nil { return nil, err } } if obj.Signatures[i].protected != nil { obj.Signatures[i].Protected, err = obj.Signatures[i].protected.sanitized() if err != nil { return nil, err } } obj.Signatures[i].Signature = sig.Signature.bytes() // As per RFC 7515 Section 4.1.3, only public keys are allowed to be embedded. jwk := obj.Signatures[i].Header.JSONWebKey if jwk != nil && (!jwk.Valid() || !jwk.IsPublic()) { return nil, errors.New("square/go-jose: invalid embedded jwk, must be public key") } // Copy value of sig original := sig obj.Signatures[i].header = sig.Header obj.Signatures[i].original = &original } return obj, nil } // parseSignedCompact parses a message in compact format. func parseSignedCompact(input string) (*JSONWebSignature, error) { parts := strings.Split(input, ".") if len(parts) != 3 { return nil, fmt.Errorf("square/go-jose: compact JWS format must have three parts") } rawProtected, err := base64.RawURLEncoding.DecodeString(parts[0]) if err != nil { return nil, err } payload, err := base64.RawURLEncoding.DecodeString(parts[1]) if err != nil { return nil, err } signature, err := base64.RawURLEncoding.DecodeString(parts[2]) if err != nil { return nil, err } raw := &rawJSONWebSignature{ Payload: newBuffer(payload), Protected: newBuffer(rawProtected), Signature: newBuffer(signature), } return raw.sanitized() } // CompactSerialize serializes an object using the compact serialization format. func (obj JSONWebSignature) CompactSerialize() (string, error) { if len(obj.Signatures) != 1 || obj.Signatures[0].header != nil || obj.Signatures[0].protected == nil { return "", ErrNotSupported } serializedProtected := mustSerializeJSON(obj.Signatures[0].protected) return fmt.Sprintf( "%s.%s.%s", base64.RawURLEncoding.EncodeToString(serializedProtected), base64.RawURLEncoding.EncodeToString(obj.payload), base64.RawURLEncoding.EncodeToString(obj.Signatures[0].Signature)), nil } // FullSerialize serializes an object using the full JSON serialization format. func (obj JSONWebSignature) FullSerialize() string { raw := rawJSONWebSignature{ Payload: newBuffer(obj.payload), } if len(obj.Signatures) == 1 { if obj.Signatures[0].protected != nil { serializedProtected := mustSerializeJSON(obj.Signatures[0].protected) raw.Protected = newBuffer(serializedProtected) } raw.Header = obj.Signatures[0].header raw.Signature = newBuffer(obj.Signatures[0].Signature) } else { raw.Signatures = make([]rawSignatureInfo, len(obj.Signatures)) for i, signature := range obj.Signatures { raw.Signatures[i] = rawSignatureInfo{ Header: signature.header, Signature: newBuffer(signature.Signature), } if signature.protected != nil { raw.Signatures[i].Protected = newBuffer(mustSerializeJSON(signature.protected)) } } } return string(mustSerializeJSON(raw)) }
vendor/gopkg.in/square/go-jose.v2/jws.go
0
https://github.com/grafana/grafana/commit/44eaa3eaa886e0f193e9b6ae364e0526c858cb00
[ 0.0004739182477351278, 0.00018136059225071222, 0.00016304005112033337, 0.00017367159307468683, 0.00005191802483750507 ]
{ "id": 4, "code_window": [ " this.state = {\n", " isVizPickerOpen: this.props.urlOpenVizPicker,\n", " searchQuery: '',\n", " searchResults: [],\n", " scrollTop: 0,\n", " };\n", " }\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "public/app/features/dashboard/panel_editor/VisualizationTab.tsx", "type": "replace", "edit_start_line_idx": 48 }
import '../all'; import { VariableSrv } from '../variable_srv'; import { DashboardModel } from '../../dashboard/state/DashboardModel'; import moment from 'moment'; import $q from 'q'; describe('VariableSrv', function(this: any) { const ctx = { datasourceSrv: {}, timeSrv: { timeRange: () => { return { from: '2018-01-29', to: '2019-01-29' }; }, }, $rootScope: { $on: () => {}, }, $injector: { instantiate: (ctr, obj) => new ctr(obj.model), }, templateSrv: { setGrafanaVariable: jest.fn(), init: vars => { this.variables = vars; }, updateIndex: () => {}, replace: str => str.replace(this.regex, match => { return match; }), }, $location: { search: () => {}, }, } as any; function describeUpdateVariable(desc, fn) { describe(desc, () => { const scenario: any = {}; scenario.setup = setupFn => { scenario.setupFn = setupFn; }; beforeEach(async () => { scenario.setupFn(); const ds: any = {}; ds.metricFindQuery = () => Promise.resolve(scenario.queryResult); ctx.variableSrv = new VariableSrv( $q, ctx.$location, ctx.$injector, ctx.templateSrv, ctx.timeSrv ); ctx.variableSrv.timeSrv = ctx.timeSrv; ctx.datasourceSrv = { get: () => Promise.resolve(ds), getMetricSources: () => scenario.metricSources, }; ctx.$injector.instantiate = (ctr, model) => { return getVarMockConstructor(ctr, model, ctx); }; ctx.variableSrv.init( new DashboardModel({ templating: { list: [] }, updateSubmenuVisibility: () => {}, }) ); scenario.variable = ctx.variableSrv.createVariableFromModel(scenario.variableModel); ctx.variableSrv.addVariable(scenario.variable); await ctx.variableSrv.updateOptions(scenario.variable); }); fn(scenario); }); } describeUpdateVariable('interval variable without auto', scenario => { scenario.setup(() => { scenario.variableModel = { type: 'interval', query: '1s,2h,5h,1d', name: 'test', }; }); it('should update options array', () => { expect(scenario.variable.options.length).toBe(4); expect(scenario.variable.options[0].text).toBe('1s'); expect(scenario.variable.options[0].value).toBe('1s'); }); }); // // Interval variable update // describeUpdateVariable('interval variable with auto', scenario => { scenario.setup(() => { scenario.variableModel = { type: 'interval', query: '1s,2h,5h,1d', name: 'test', auto: true, auto_count: 10, }; const range = { from: moment(new Date()) .subtract(7, 'days') .toDate(), to: new Date(), }; ctx.timeSrv.timeRange = () => range; // ctx.templateSrv.setGrafanaVariable = jest.fn(); }); it('should update options array', () => { expect(scenario.variable.options.length).toBe(5); expect(scenario.variable.options[0].text).toBe('auto'); expect(scenario.variable.options[0].value).toBe('$__auto_interval_test'); }); it('should set $__auto_interval_test', () => { const call = ctx.templateSrv.setGrafanaVariable.mock.calls[0]; expect(call[0]).toBe('$__auto_interval_test'); expect(call[1]).toBe('12h'); }); // updateAutoValue() gets called twice: once directly once via VariableSrv.validateVariableSelectionState() // So use lastCall instead of a specific call number it('should set $__auto_interval', () => { const call = ctx.templateSrv.setGrafanaVariable.mock.calls.pop(); expect(call[0]).toBe('$__auto_interval'); expect(call[1]).toBe('12h'); }); }); // // Query variable update // describeUpdateVariable('query variable with empty current object and refresh', scenario => { scenario.setup(() => { scenario.variableModel = { type: 'query', query: '', name: 'test', current: {}, }; scenario.queryResult = [{ text: 'backend1' }, { text: 'backend2' }]; }); it('should set current value to first option', () => { expect(scenario.variable.options.length).toBe(2); expect(scenario.variable.current.value).toBe('backend1'); }); }); describeUpdateVariable( 'query variable with multi select and new options does not contain some selected values', scenario => { scenario.setup(() => { scenario.variableModel = { type: 'query', query: '', name: 'test', current: { value: ['val1', 'val2', 'val3'], text: 'val1 + val2 + val3', }, }; scenario.queryResult = [{ text: 'val2' }, { text: 'val3' }]; }); it('should update current value', () => { expect(scenario.variable.current.value).toEqual(['val2', 'val3']); expect(scenario.variable.current.text).toEqual('val2 + val3'); }); } ); describeUpdateVariable( 'query variable with multi select and new options does not contain any selected values', scenario => { scenario.setup(() => { scenario.variableModel = { type: 'query', query: '', name: 'test', current: { value: ['val1', 'val2', 'val3'], text: 'val1 + val2 + val3', }, }; scenario.queryResult = [{ text: 'val5' }, { text: 'val6' }]; }); it('should update current value with first one', () => { expect(scenario.variable.current.value).toEqual('val5'); expect(scenario.variable.current.text).toEqual('val5'); }); } ); describeUpdateVariable('query variable with multi select and $__all selected', scenario => { scenario.setup(() => { scenario.variableModel = { type: 'query', query: '', name: 'test', includeAll: true, current: { value: ['$__all'], text: 'All', }, }; scenario.queryResult = [{ text: 'val5' }, { text: 'val6' }]; }); it('should keep current All value', () => { expect(scenario.variable.current.value).toEqual(['$__all']); expect(scenario.variable.current.text).toEqual('All'); }); }); describeUpdateVariable('query variable with numeric results', scenario => { scenario.setup(() => { scenario.variableModel = { type: 'query', query: '', name: 'test', current: {}, }; scenario.queryResult = [{ text: 12, value: 12 }]; }); it('should set current value to first option', () => { expect(scenario.variable.current.value).toBe('12'); expect(scenario.variable.options[0].value).toBe('12'); expect(scenario.variable.options[0].text).toBe('12'); }); }); describeUpdateVariable('basic query variable', scenario => { scenario.setup(() => { scenario.variableModel = { type: 'query', query: 'apps.*', name: 'test' }; scenario.queryResult = [{ text: 'backend1' }, { text: 'backend2' }]; }); it('should update options array', () => { expect(scenario.variable.options.length).toBe(2); expect(scenario.variable.options[0].text).toBe('backend1'); expect(scenario.variable.options[0].value).toBe('backend1'); expect(scenario.variable.options[1].value).toBe('backend2'); }); it('should select first option as value', () => { expect(scenario.variable.current.value).toBe('backend1'); }); }); describeUpdateVariable('and existing value still exists in options', scenario => { scenario.setup(() => { scenario.variableModel = { type: 'query', query: 'apps.*', name: 'test' }; scenario.variableModel.current = { value: 'backend2', text: 'backend2' }; scenario.queryResult = [{ text: 'backend1' }, { text: 'backend2' }]; }); it('should keep variable value', () => { expect(scenario.variable.current.text).toBe('backend2'); }); }); describeUpdateVariable('and regex pattern exists', scenario => { scenario.setup(() => { scenario.variableModel = { type: 'query', query: 'apps.*', name: 'test' }; scenario.variableModel.regex = '/apps.*(backend_[0-9]+)/'; scenario.queryResult = [ { text: 'apps.backend.backend_01.counters.req' }, { text: 'apps.backend.backend_02.counters.req' }, ]; }); it('should extract and use match group', () => { expect(scenario.variable.options[0].value).toBe('backend_01'); }); }); describeUpdateVariable('and regex pattern exists and no match', scenario => { scenario.setup(() => { scenario.variableModel = { type: 'query', query: 'apps.*', name: 'test' }; scenario.variableModel.regex = '/apps.*(backendasd[0-9]+)/'; scenario.queryResult = [ { text: 'apps.backend.backend_01.counters.req' }, { text: 'apps.backend.backend_02.counters.req' }, ]; }); it('should not add non matching items, None option should be added instead', () => { expect(scenario.variable.options.length).toBe(1); expect(scenario.variable.options[0].isNone).toBe(true); }); }); describeUpdateVariable('regex pattern without slashes', scenario => { scenario.setup(() => { scenario.variableModel = { type: 'query', query: 'apps.*', name: 'test' }; scenario.variableModel.regex = 'backend_01'; scenario.queryResult = [ { text: 'apps.backend.backend_01.counters.req' }, { text: 'apps.backend.backend_02.counters.req' }, ]; }); it('should return matches options', () => { expect(scenario.variable.options.length).toBe(1); }); }); describeUpdateVariable('regex pattern remove duplicates', scenario => { scenario.setup(() => { scenario.variableModel = { type: 'query', query: 'apps.*', name: 'test' }; scenario.variableModel.regex = '/backend_01/'; scenario.queryResult = [ { text: 'apps.backend.backend_01.counters.req' }, { text: 'apps.backend.backend_01.counters.req' }, ]; }); it('should return matches options', () => { expect(scenario.variable.options.length).toBe(1); }); }); describeUpdateVariable('with include All', scenario => { scenario.setup(() => { scenario.variableModel = { type: 'query', query: 'apps.*', name: 'test', includeAll: true, }; scenario.queryResult = [{ text: 'backend1' }, { text: 'backend2' }, { text: 'backend3' }]; }); it('should add All option', () => { expect(scenario.variable.options[0].text).toBe('All'); expect(scenario.variable.options[0].value).toBe('$__all'); }); }); describeUpdateVariable('with include all and custom value', scenario => { scenario.setup(() => { scenario.variableModel = { type: 'query', query: 'apps.*', name: 'test', includeAll: true, allValue: '*', }; scenario.queryResult = [{ text: 'backend1' }, { text: 'backend2' }, { text: 'backend3' }]; }); it('should add All option with custom value', () => { expect(scenario.variable.options[0].value).toBe('$__all'); }); }); describeUpdateVariable('without sort', scenario => { scenario.setup(() => { scenario.variableModel = { type: 'query', query: 'apps.*', name: 'test', sort: 0, }; scenario.queryResult = [{ text: 'bbb2' }, { text: 'aaa10' }, { text: 'ccc3' }]; }); it('should return options without sort', () => { expect(scenario.variable.options[0].text).toBe('bbb2'); expect(scenario.variable.options[1].text).toBe('aaa10'); expect(scenario.variable.options[2].text).toBe('ccc3'); }); }); describeUpdateVariable('with alphabetical sort (asc)', scenario => { scenario.setup(() => { scenario.variableModel = { type: 'query', query: 'apps.*', name: 'test', sort: 1, }; scenario.queryResult = [{ text: 'bbb2' }, { text: 'aaa10' }, { text: 'ccc3' }]; }); it('should return options with alphabetical sort', () => { expect(scenario.variable.options[0].text).toBe('aaa10'); expect(scenario.variable.options[1].text).toBe('bbb2'); expect(scenario.variable.options[2].text).toBe('ccc3'); }); }); describeUpdateVariable('with alphabetical sort (desc)', scenario => { scenario.setup(() => { scenario.variableModel = { type: 'query', query: 'apps.*', name: 'test', sort: 2, }; scenario.queryResult = [{ text: 'bbb2' }, { text: 'aaa10' }, { text: 'ccc3' }]; }); it('should return options with alphabetical sort', () => { expect(scenario.variable.options[0].text).toBe('ccc3'); expect(scenario.variable.options[1].text).toBe('bbb2'); expect(scenario.variable.options[2].text).toBe('aaa10'); }); }); describeUpdateVariable('with numerical sort (asc)', scenario => { scenario.setup(() => { scenario.variableModel = { type: 'query', query: 'apps.*', name: 'test', sort: 3, }; scenario.queryResult = [{ text: 'bbb2' }, { text: 'aaa10' }, { text: 'ccc3' }]; }); it('should return options with numerical sort', () => { expect(scenario.variable.options[0].text).toBe('bbb2'); expect(scenario.variable.options[1].text).toBe('ccc3'); expect(scenario.variable.options[2].text).toBe('aaa10'); }); }); describeUpdateVariable('with numerical sort (desc)', scenario => { scenario.setup(() => { scenario.variableModel = { type: 'query', query: 'apps.*', name: 'test', sort: 4, }; scenario.queryResult = [{ text: 'bbb2' }, { text: 'aaa10' }, { text: 'ccc3' }]; }); it('should return options with numerical sort', () => { expect(scenario.variable.options[0].text).toBe('aaa10'); expect(scenario.variable.options[1].text).toBe('ccc3'); expect(scenario.variable.options[2].text).toBe('bbb2'); }); }); // // datasource variable update // describeUpdateVariable('datasource variable with regex filter', scenario => { scenario.setup(() => { scenario.variableModel = { type: 'datasource', query: 'graphite', name: 'test', current: { value: 'backend4_pee', text: 'backend4_pee' }, regex: '/pee$/', }; scenario.metricSources = [ { name: 'backend1', meta: { id: 'influx' } }, { name: 'backend2_pee', meta: { id: 'graphite' } }, { name: 'backend3', meta: { id: 'graphite' } }, { name: 'backend4_pee', meta: { id: 'graphite' } }, ]; }); it('should set only contain graphite ds and filtered using regex', () => { expect(scenario.variable.options.length).toBe(2); expect(scenario.variable.options[0].value).toBe('backend2_pee'); expect(scenario.variable.options[1].value).toBe('backend4_pee'); }); it('should keep current value if available', () => { expect(scenario.variable.current.value).toBe('backend4_pee'); }); }); // // Custom variable update // describeUpdateVariable('update custom variable', scenario => { scenario.setup(() => { scenario.variableModel = { type: 'custom', query: 'hej, hop, asd, escaped\\,var', name: 'test', }; }); it('should update options array', () => { expect(scenario.variable.options.length).toBe(4); expect(scenario.variable.options[0].text).toBe('hej'); expect(scenario.variable.options[1].value).toBe('hop'); expect(scenario.variable.options[2].value).toBe('asd'); expect(scenario.variable.options[3].value).toBe('escaped,var'); }); }); describe('multiple interval variables with auto', () => { let variable1, variable2; beforeEach(() => { const range = { from: moment(new Date()) .subtract(7, 'days') .toDate(), to: new Date(), }; ctx.timeSrv.timeRange = () => range; ctx.templateSrv.setGrafanaVariable = jest.fn(); const variableModel1 = { type: 'interval', query: '1s,2h,5h,1d', name: 'variable1', auto: true, auto_count: 10, }; variable1 = ctx.variableSrv.createVariableFromModel(variableModel1); ctx.variableSrv.addVariable(variable1); const variableModel2 = { type: 'interval', query: '1s,2h,5h', name: 'variable2', auto: true, auto_count: 1000, }; variable2 = ctx.variableSrv.createVariableFromModel(variableModel2); ctx.variableSrv.addVariable(variable2); ctx.variableSrv.updateOptions(variable1); ctx.variableSrv.updateOptions(variable2); // ctx.$rootScope.$digest(); }); it('should update options array', () => { expect(variable1.options.length).toBe(5); expect(variable1.options[0].text).toBe('auto'); expect(variable1.options[0].value).toBe('$__auto_interval_variable1'); expect(variable2.options.length).toBe(4); expect(variable2.options[0].text).toBe('auto'); expect(variable2.options[0].value).toBe('$__auto_interval_variable2'); }); it('should correctly set $__auto_interval_variableX', () => { let variable1Set, variable2Set, legacySet, unknownSet = false; // updateAutoValue() gets called repeatedly: once directly once via VariableSrv.validateVariableSelectionState() // So check that all calls are valid rather than expect a specific number and/or ordering of calls for (let i = 0; i < ctx.templateSrv.setGrafanaVariable.mock.calls.length; i++) { const call = ctx.templateSrv.setGrafanaVariable.mock.calls[i]; switch (call[0]) { case '$__auto_interval_variable1': expect(call[1]).toBe('12h'); variable1Set = true; break; case '$__auto_interval_variable2': expect(call[1]).toBe('10m'); variable2Set = true; break; case '$__auto_interval': expect(call[1]).toEqual(expect.stringMatching(/^(12h|10m)$/)); legacySet = true; break; default: unknownSet = true; break; } } expect(variable1Set).toEqual(true); expect(variable2Set).toEqual(true); expect(legacySet).toEqual(true); expect(unknownSet).toEqual(false); }); }); }); function getVarMockConstructor(variable, model, ctx) { switch (model.model.type) { case 'datasource': return new variable(model.model, ctx.datasourceSrv, ctx.variableSrv, ctx.templateSrv); case 'query': return new variable(model.model, ctx.datasourceSrv, ctx.templateSrv, ctx.variableSrv); case 'interval': return new variable(model.model, ctx.timeSrv, ctx.templateSrv, ctx.variableSrv); case 'custom': return new variable(model.model, ctx.variableSrv); default: return new variable(model.model); } }
public/app/features/templating/specs/variable_srv.test.ts
0
https://github.com/grafana/grafana/commit/44eaa3eaa886e0f193e9b6ae364e0526c858cb00
[ 0.00017839745851233602, 0.00017242328613065183, 0.00016452364798169583, 0.0001724574831314385, 0.00000248541164182825 ]
{ "id": 4, "code_window": [ " this.state = {\n", " isVizPickerOpen: this.props.urlOpenVizPicker,\n", " searchQuery: '',\n", " searchResults: [],\n", " scrollTop: 0,\n", " };\n", " }\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "public/app/features/dashboard/panel_editor/VisualizationTab.tsx", "type": "replace", "edit_start_line_idx": 48 }
/* * * Copyright 2017 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ // Package passthrough implements a pass-through resolver. It sends the target // name without scheme back to gRPC as resolved address. package passthrough import "google.golang.org/grpc/resolver" const scheme = "passthrough" type passthroughBuilder struct{} func (*passthroughBuilder) Build(target resolver.Target, cc resolver.ClientConn, opts resolver.BuildOption) (resolver.Resolver, error) { r := &passthroughResolver{ target: target, cc: cc, } r.start() return r, nil } func (*passthroughBuilder) Scheme() string { return scheme } type passthroughResolver struct { target resolver.Target cc resolver.ClientConn } func (r *passthroughResolver) start() { r.cc.NewAddress([]resolver.Address{{Addr: r.target.Endpoint}}) } func (*passthroughResolver) ResolveNow(o resolver.ResolveNowOption) {} func (*passthroughResolver) Close() {} func init() { resolver.Register(&passthroughBuilder{}) }
vendor/google.golang.org/grpc/resolver/passthrough/passthrough.go
0
https://github.com/grafana/grafana/commit/44eaa3eaa886e0f193e9b6ae364e0526c858cb00
[ 0.00018397094390820712, 0.00017338362522423267, 0.00016786373453214765, 0.00017240425222553313, 0.000005430704277387122 ]
{ "id": 5, "code_window": [ " }\n", "\n", " this.setState({ isVizPickerOpen: false });\n", " };\n", "\n", " onSearchQueryChange = (evt: ChangeEvent<HTMLInputElement>) => {\n", " const value = evt.target.value;\n", " this.setState({\n", " searchQuery: value,\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " onSearchQueryChange = evt => {\n" ], "file_path": "public/app/features/dashboard/panel_editor/VisualizationTab.tsx", "type": "replace", "edit_start_line_idx": 174 }
// Libraries import React, { PureComponent, ChangeEvent } from 'react'; // Utils & Services import { AngularComponent, getAngularLoader } from 'app/core/services/AngularLoader'; import { connectWithStore } from 'app/core/utils/connectWithReduxStore'; import { StoreState } from 'app/types'; import { updateLocation } from 'app/core/actions'; // Components import { EditorTabBody, EditorToolbarView } from './EditorTabBody'; import { VizTypePicker } from './VizTypePicker'; import { PluginHelp } from 'app/core/components/PluginHelp/PluginHelp'; import { FadeIn } from 'app/core/components/Animations/FadeIn'; // Types import { PanelModel } from '../state/PanelModel'; import { DashboardModel } from '../state/DashboardModel'; import { PanelPlugin } from 'app/types/plugins'; interface Props { panel: PanelModel; dashboard: DashboardModel; plugin: PanelPlugin; angularPanel?: AngularComponent; onTypeChanged: (newType: PanelPlugin) => void; updateLocation: typeof updateLocation; urlOpenVizPicker: boolean; } interface State { isVizPickerOpen: boolean; searchQuery: string; searchResults: PanelPlugin[]; scrollTop: number; } export class VisualizationTab extends PureComponent<Props, State> { element: HTMLElement; angularOptions: AngularComponent; searchInput: HTMLElement; constructor(props: Props) { super(props); this.state = { isVizPickerOpen: this.props.urlOpenVizPicker, searchQuery: '', searchResults: [], scrollTop: 0, }; } getPanelDefaultOptions = () => { const { panel, plugin } = this.props; if (plugin.exports.PanelDefaults) { return panel.getOptions(plugin.exports.PanelDefaults.options); } return panel.getOptions(plugin.exports.PanelDefaults); }; renderPanelOptions() { const { plugin, angularPanel } = this.props; const { PanelOptions } = plugin.exports; if (angularPanel) { return <div ref={element => (this.element = element)} />; } return ( <> {PanelOptions ? ( <PanelOptions options={this.getPanelDefaultOptions()} onChange={this.onPanelOptionsChanged} /> ) : ( <p>Visualization has no options</p> )} </> ); } componentDidMount() { if (this.shouldLoadAngularOptions()) { this.loadAngularOptions(); } } componentDidUpdate(prevProps: Props) { if (this.props.plugin !== prevProps.plugin) { this.cleanUpAngularOptions(); } if (this.shouldLoadAngularOptions()) { this.loadAngularOptions(); } } shouldLoadAngularOptions() { return this.props.angularPanel && this.element && !this.angularOptions; } loadAngularOptions() { const { angularPanel } = this.props; const scope = angularPanel.getScope(); // When full page reloading in edit mode the angular panel has on fully compiled & instantiated yet if (!scope.$$childHead) { setTimeout(() => { this.forceUpdate(); }); return; } const panelCtrl = scope.$$childHead.ctrl; panelCtrl.initEditMode(); let template = ''; for (let i = 0; i < panelCtrl.editorTabs.length; i++) { template += ` <div class="panel-options-group" ng-cloak>` + (i > 0 ? `<div class="panel-options-group__header"> <span class="panel-options-group__title">{{ctrl.editorTabs[${i}].title}} </span> </div>` : '') + `<div class="panel-options-group__body"> <panel-editor-tab editor-tab="ctrl.editorTabs[${i}]" ctrl="ctrl"></panel-editor-tab> </div> </div> `; } const loader = getAngularLoader(); const scopeProps = { ctrl: panelCtrl }; this.angularOptions = loader.load(this.element, scopeProps, template); } componentWillUnmount() { this.cleanUpAngularOptions(); } cleanUpAngularOptions() { if (this.angularOptions) { this.angularOptions.destroy(); this.angularOptions = null; } } clearQuery = () => { this.setState({ searchQuery: '' }); }; onPanelOptionsChanged = (options: any) => { this.props.panel.updateOptions(options); this.forceUpdate(); }; onOpenVizPicker = () => { this.setState({ isVizPickerOpen: true, scrollTop: 0 }); }; onCloseVizPicker = () => { if (this.props.urlOpenVizPicker) { this.props.updateLocation({ query: { openVizPicker: null }, partial: true }); } this.setState({ isVizPickerOpen: false }); }; onSearchQueryChange = (evt: ChangeEvent<HTMLInputElement>) => { const value = evt.target.value; this.setState({ searchQuery: value, }); }; renderToolbar = (): JSX.Element => { const { plugin } = this.props; const { searchQuery } = this.state; if (this.state.isVizPickerOpen) { return ( <> <label className="gf-form--has-input-icon"> <input type="text" className={`gf-form-input width-13 ${!this.hasSearchResults ? 'gf-form-input--invalid' : ''}`} placeholder="" onChange={this.onSearchQueryChange} value={searchQuery} ref={elem => elem && elem.focus()} /> <i className="gf-form-input-icon fa fa-search" /> </label> <button className="btn btn-link toolbar__close" onClick={this.onCloseVizPicker}> <i className="fa fa-chevron-up" /> </button> </> ); } else { return ( <div className="toolbar__main" onClick={this.onOpenVizPicker}> <img className="toolbar__main-image" src={plugin.info.logos.small} /> <div className="toolbar__main-name">{plugin.name}</div> <i className="fa fa-caret-down" /> </div> ); } }; onTypeChanged = (plugin: PanelPlugin) => { if (plugin.id === this.props.plugin.id) { this.setState({ isVizPickerOpen: false }); } else { this.props.onTypeChanged(plugin); } }; setSearchResults = (searchResults: PanelPlugin[]) => { this.setState({ searchResults: searchResults }); }; get hasSearchResults () { return this.state.searchResults && this.state.searchResults.length > 0; } renderHelp = () => <PluginHelp plugin={this.props.plugin} type="help" />; setScrollTop = (event: React.MouseEvent<HTMLElement>) => { const target = event.target as HTMLElement; this.setState({ scrollTop: target.scrollTop }); }; render() { const { plugin } = this.props; const { isVizPickerOpen, searchQuery, scrollTop } = this.state; const pluginHelp: EditorToolbarView = { heading: 'Help', icon: 'fa fa-question', render: this.renderHelp, }; return ( <EditorTabBody heading="Visualization" renderToolbar={this.renderToolbar} toolbarItems={[pluginHelp]} scrollTop={scrollTop} setScrollTop={this.setScrollTop} > <> <FadeIn in={isVizPickerOpen} duration={200} unmountOnExit={true} onExited={this.clearQuery}> <VizTypePicker current={plugin} onTypeChanged={this.onTypeChanged} searchQuery={searchQuery} onClose={this.onCloseVizPicker} onPluginListChange={this.setSearchResults} /> </FadeIn> {this.renderPanelOptions()} </> </EditorTabBody> ); } } const mapStateToProps = (state: StoreState) => ({ urlOpenVizPicker: !!state.location.query.openVizPicker, }); const mapDispatchToProps = { updateLocation, }; export default connectWithStore(VisualizationTab, mapStateToProps, mapDispatchToProps);
public/app/features/dashboard/panel_editor/VisualizationTab.tsx
1
https://github.com/grafana/grafana/commit/44eaa3eaa886e0f193e9b6ae364e0526c858cb00
[ 0.9982942938804626, 0.10378655046224594, 0.00016633923223707825, 0.0002662201295606792, 0.2993982136249542 ]
{ "id": 5, "code_window": [ " }\n", "\n", " this.setState({ isVizPickerOpen: false });\n", " };\n", "\n", " onSearchQueryChange = (evt: ChangeEvent<HTMLInputElement>) => {\n", " const value = evt.target.value;\n", " this.setState({\n", " searchQuery: value,\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " onSearchQueryChange = evt => {\n" ], "file_path": "public/app/features/dashboard/panel_editor/VisualizationTab.tsx", "type": "replace", "edit_start_line_idx": 174 }
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`Render should render component 1`] = ` <div className="form-field" > <Component width={11} > Test </Component> <input className="gf-form-input width-12" onChange={[MockFunction]} type="text" value={10} /> </div> `;
packages/grafana-ui/src/components/FormField/__snapshots__/FormField.test.tsx.snap
0
https://github.com/grafana/grafana/commit/44eaa3eaa886e0f193e9b6ae364e0526c858cb00
[ 0.00017594594100955874, 0.00017086406296584755, 0.00016578218492213637, 0.00017086406296584755, 0.0000050818780437111855 ]
{ "id": 5, "code_window": [ " }\n", "\n", " this.setState({ isVizPickerOpen: false });\n", " };\n", "\n", " onSearchQueryChange = (evt: ChangeEvent<HTMLInputElement>) => {\n", " const value = evt.target.value;\n", " this.setState({\n", " searchQuery: value,\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " onSearchQueryChange = evt => {\n" ], "file_path": "public/app/features/dashboard/panel_editor/VisualizationTab.tsx", "type": "replace", "edit_start_line_idx": 174 }
// Copyright (C) 2014 Yasuhiro Matsumoto <[email protected]>. // // Use of this source code is governed by an MIT-style // license that can be found in the LICENSE file. // +build libsqlite3 package sqlite3 /* #cgo CFLAGS: -DUSE_LIBSQLITE3 #cgo linux LDFLAGS: -lsqlite3 #cgo darwin LDFLAGS: -L/usr/local/opt/sqlite/lib -lsqlite3 #cgo solaris LDFLAGS: -lsqlite3 */ import "C"
vendor/github.com/mattn/go-sqlite3/sqlite3_libsqlite3.go
0
https://github.com/grafana/grafana/commit/44eaa3eaa886e0f193e9b6ae364e0526c858cb00
[ 0.000176376779563725, 0.00017225657938979566, 0.00016813637921586633, 0.00017225657938979566, 0.000004120200173929334 ]
{ "id": 5, "code_window": [ " }\n", "\n", " this.setState({ isVizPickerOpen: false });\n", " };\n", "\n", " onSearchQueryChange = (evt: ChangeEvent<HTMLInputElement>) => {\n", " const value = evt.target.value;\n", " this.setState({\n", " searchQuery: value,\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " onSearchQueryChange = evt => {\n" ], "file_path": "public/app/features/dashboard/panel_editor/VisualizationTab.tsx", "type": "replace", "edit_start_line_idx": 174 }
package notifications import ( m "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/setting" ) type Message struct { To []string From string Subject string Body string Info string EmbededFiles []string } func setDefaultTemplateData(data map[string]interface{}, u *m.User) { data["AppUrl"] = setting.AppUrl data["BuildVersion"] = setting.BuildVersion data["BuildStamp"] = setting.BuildStamp data["EmailCodeValidHours"] = setting.EmailCodeValidMinutes / 60 data["Subject"] = map[string]interface{}{} if u != nil { data["Name"] = u.NameOrFallback() } }
pkg/services/notifications/email.go
0
https://github.com/grafana/grafana/commit/44eaa3eaa886e0f193e9b6ae364e0526c858cb00
[ 0.00017470434249844402, 0.00017281727923545986, 0.0001698916603345424, 0.0001738558494253084, 0.000002097528977174079 ]
{ "id": 6, "code_window": [ " <label className=\"gf-form--has-input-icon\">\n", " <input\n", " type=\"text\"\n", " className={`gf-form-input width-13 ${!this.hasSearchResults ? 'gf-form-input--invalid' : ''}`}\n", " placeholder=\"\"\n", " onChange={this.onSearchQueryChange}\n", " value={searchQuery}\n", " ref={elem => elem && elem.focus()}\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " className=\"gf-form-input width-13\"\n" ], "file_path": "public/app/features/dashboard/panel_editor/VisualizationTab.tsx", "type": "replace", "edit_start_line_idx": 191 }
// Libraries import React, { PureComponent, ChangeEvent } from 'react'; // Utils & Services import { AngularComponent, getAngularLoader } from 'app/core/services/AngularLoader'; import { connectWithStore } from 'app/core/utils/connectWithReduxStore'; import { StoreState } from 'app/types'; import { updateLocation } from 'app/core/actions'; // Components import { EditorTabBody, EditorToolbarView } from './EditorTabBody'; import { VizTypePicker } from './VizTypePicker'; import { PluginHelp } from 'app/core/components/PluginHelp/PluginHelp'; import { FadeIn } from 'app/core/components/Animations/FadeIn'; // Types import { PanelModel } from '../state/PanelModel'; import { DashboardModel } from '../state/DashboardModel'; import { PanelPlugin } from 'app/types/plugins'; interface Props { panel: PanelModel; dashboard: DashboardModel; plugin: PanelPlugin; angularPanel?: AngularComponent; onTypeChanged: (newType: PanelPlugin) => void; updateLocation: typeof updateLocation; urlOpenVizPicker: boolean; } interface State { isVizPickerOpen: boolean; searchQuery: string; searchResults: PanelPlugin[]; scrollTop: number; } export class VisualizationTab extends PureComponent<Props, State> { element: HTMLElement; angularOptions: AngularComponent; searchInput: HTMLElement; constructor(props: Props) { super(props); this.state = { isVizPickerOpen: this.props.urlOpenVizPicker, searchQuery: '', searchResults: [], scrollTop: 0, }; } getPanelDefaultOptions = () => { const { panel, plugin } = this.props; if (plugin.exports.PanelDefaults) { return panel.getOptions(plugin.exports.PanelDefaults.options); } return panel.getOptions(plugin.exports.PanelDefaults); }; renderPanelOptions() { const { plugin, angularPanel } = this.props; const { PanelOptions } = plugin.exports; if (angularPanel) { return <div ref={element => (this.element = element)} />; } return ( <> {PanelOptions ? ( <PanelOptions options={this.getPanelDefaultOptions()} onChange={this.onPanelOptionsChanged} /> ) : ( <p>Visualization has no options</p> )} </> ); } componentDidMount() { if (this.shouldLoadAngularOptions()) { this.loadAngularOptions(); } } componentDidUpdate(prevProps: Props) { if (this.props.plugin !== prevProps.plugin) { this.cleanUpAngularOptions(); } if (this.shouldLoadAngularOptions()) { this.loadAngularOptions(); } } shouldLoadAngularOptions() { return this.props.angularPanel && this.element && !this.angularOptions; } loadAngularOptions() { const { angularPanel } = this.props; const scope = angularPanel.getScope(); // When full page reloading in edit mode the angular panel has on fully compiled & instantiated yet if (!scope.$$childHead) { setTimeout(() => { this.forceUpdate(); }); return; } const panelCtrl = scope.$$childHead.ctrl; panelCtrl.initEditMode(); let template = ''; for (let i = 0; i < panelCtrl.editorTabs.length; i++) { template += ` <div class="panel-options-group" ng-cloak>` + (i > 0 ? `<div class="panel-options-group__header"> <span class="panel-options-group__title">{{ctrl.editorTabs[${i}].title}} </span> </div>` : '') + `<div class="panel-options-group__body"> <panel-editor-tab editor-tab="ctrl.editorTabs[${i}]" ctrl="ctrl"></panel-editor-tab> </div> </div> `; } const loader = getAngularLoader(); const scopeProps = { ctrl: panelCtrl }; this.angularOptions = loader.load(this.element, scopeProps, template); } componentWillUnmount() { this.cleanUpAngularOptions(); } cleanUpAngularOptions() { if (this.angularOptions) { this.angularOptions.destroy(); this.angularOptions = null; } } clearQuery = () => { this.setState({ searchQuery: '' }); }; onPanelOptionsChanged = (options: any) => { this.props.panel.updateOptions(options); this.forceUpdate(); }; onOpenVizPicker = () => { this.setState({ isVizPickerOpen: true, scrollTop: 0 }); }; onCloseVizPicker = () => { if (this.props.urlOpenVizPicker) { this.props.updateLocation({ query: { openVizPicker: null }, partial: true }); } this.setState({ isVizPickerOpen: false }); }; onSearchQueryChange = (evt: ChangeEvent<HTMLInputElement>) => { const value = evt.target.value; this.setState({ searchQuery: value, }); }; renderToolbar = (): JSX.Element => { const { plugin } = this.props; const { searchQuery } = this.state; if (this.state.isVizPickerOpen) { return ( <> <label className="gf-form--has-input-icon"> <input type="text" className={`gf-form-input width-13 ${!this.hasSearchResults ? 'gf-form-input--invalid' : ''}`} placeholder="" onChange={this.onSearchQueryChange} value={searchQuery} ref={elem => elem && elem.focus()} /> <i className="gf-form-input-icon fa fa-search" /> </label> <button className="btn btn-link toolbar__close" onClick={this.onCloseVizPicker}> <i className="fa fa-chevron-up" /> </button> </> ); } else { return ( <div className="toolbar__main" onClick={this.onOpenVizPicker}> <img className="toolbar__main-image" src={plugin.info.logos.small} /> <div className="toolbar__main-name">{plugin.name}</div> <i className="fa fa-caret-down" /> </div> ); } }; onTypeChanged = (plugin: PanelPlugin) => { if (plugin.id === this.props.plugin.id) { this.setState({ isVizPickerOpen: false }); } else { this.props.onTypeChanged(plugin); } }; setSearchResults = (searchResults: PanelPlugin[]) => { this.setState({ searchResults: searchResults }); }; get hasSearchResults () { return this.state.searchResults && this.state.searchResults.length > 0; } renderHelp = () => <PluginHelp plugin={this.props.plugin} type="help" />; setScrollTop = (event: React.MouseEvent<HTMLElement>) => { const target = event.target as HTMLElement; this.setState({ scrollTop: target.scrollTop }); }; render() { const { plugin } = this.props; const { isVizPickerOpen, searchQuery, scrollTop } = this.state; const pluginHelp: EditorToolbarView = { heading: 'Help', icon: 'fa fa-question', render: this.renderHelp, }; return ( <EditorTabBody heading="Visualization" renderToolbar={this.renderToolbar} toolbarItems={[pluginHelp]} scrollTop={scrollTop} setScrollTop={this.setScrollTop} > <> <FadeIn in={isVizPickerOpen} duration={200} unmountOnExit={true} onExited={this.clearQuery}> <VizTypePicker current={plugin} onTypeChanged={this.onTypeChanged} searchQuery={searchQuery} onClose={this.onCloseVizPicker} onPluginListChange={this.setSearchResults} /> </FadeIn> {this.renderPanelOptions()} </> </EditorTabBody> ); } } const mapStateToProps = (state: StoreState) => ({ urlOpenVizPicker: !!state.location.query.openVizPicker, }); const mapDispatchToProps = { updateLocation, }; export default connectWithStore(VisualizationTab, mapStateToProps, mapDispatchToProps);
public/app/features/dashboard/panel_editor/VisualizationTab.tsx
1
https://github.com/grafana/grafana/commit/44eaa3eaa886e0f193e9b6ae364e0526c858cb00
[ 0.9965083003044128, 0.03490626811981201, 0.00016439944738522172, 0.00017111620400100946, 0.18172751367092133 ]
{ "id": 6, "code_window": [ " <label className=\"gf-form--has-input-icon\">\n", " <input\n", " type=\"text\"\n", " className={`gf-form-input width-13 ${!this.hasSearchResults ? 'gf-form-input--invalid' : ''}`}\n", " placeholder=\"\"\n", " onChange={this.onSearchQueryChange}\n", " value={searchQuery}\n", " ref={elem => elem && elem.focus()}\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " className=\"gf-form-input width-13\"\n" ], "file_path": "public/app/features/dashboard/panel_editor/VisualizationTab.tsx", "type": "replace", "edit_start_line_idx": 191 }
/*- * Copyright 2014 Square Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jose import ( "crypto/ecdsa" "crypto/rsa" "encoding/base64" "errors" "fmt" "golang.org/x/crypto/ed25519" "gopkg.in/square/go-jose.v2/json" ) // NonceSource represents a source of random nonces to go into JWS objects type NonceSource interface { Nonce() (string, error) } // Signer represents a signer which takes a payload and produces a signed JWS object. type Signer interface { Sign(payload []byte) (*JSONWebSignature, error) Options() SignerOptions } // SigningKey represents an algorithm/key used to sign a message. type SigningKey struct { Algorithm SignatureAlgorithm Key interface{} } // SignerOptions represents options that can be set when creating signers. type SignerOptions struct { NonceSource NonceSource EmbedJWK bool // Optional map of additional keys to be inserted into the protected header // of a JWS object. Some specifications which make use of JWS like to insert // additional values here. All values must be JSON-serializable. ExtraHeaders map[HeaderKey]interface{} } // WithHeader adds an arbitrary value to the ExtraHeaders map, initializing it // if necessary. It returns itself and so can be used in a fluent style. func (so *SignerOptions) WithHeader(k HeaderKey, v interface{}) *SignerOptions { if so.ExtraHeaders == nil { so.ExtraHeaders = map[HeaderKey]interface{}{} } so.ExtraHeaders[k] = v return so } // WithContentType adds a content type ("cty") header and returns the updated // SignerOptions. func (so *SignerOptions) WithContentType(contentType ContentType) *SignerOptions { return so.WithHeader(HeaderContentType, contentType) } // WithType adds a type ("typ") header and returns the updated SignerOptions. func (so *SignerOptions) WithType(typ ContentType) *SignerOptions { return so.WithHeader(HeaderType, typ) } type payloadSigner interface { signPayload(payload []byte, alg SignatureAlgorithm) (Signature, error) } type payloadVerifier interface { verifyPayload(payload []byte, signature []byte, alg SignatureAlgorithm) error } type genericSigner struct { recipients []recipientSigInfo nonceSource NonceSource embedJWK bool extraHeaders map[HeaderKey]interface{} } type recipientSigInfo struct { sigAlg SignatureAlgorithm publicKey func() *JSONWebKey signer payloadSigner } func staticPublicKey(jwk *JSONWebKey) func() *JSONWebKey { return func() *JSONWebKey { return jwk } } // NewSigner creates an appropriate signer based on the key type func NewSigner(sig SigningKey, opts *SignerOptions) (Signer, error) { return NewMultiSigner([]SigningKey{sig}, opts) } // NewMultiSigner creates a signer for multiple recipients func NewMultiSigner(sigs []SigningKey, opts *SignerOptions) (Signer, error) { signer := &genericSigner{recipients: []recipientSigInfo{}} if opts != nil { signer.nonceSource = opts.NonceSource signer.embedJWK = opts.EmbedJWK signer.extraHeaders = opts.ExtraHeaders } for _, sig := range sigs { err := signer.addRecipient(sig.Algorithm, sig.Key) if err != nil { return nil, err } } return signer, nil } // newVerifier creates a verifier based on the key type func newVerifier(verificationKey interface{}) (payloadVerifier, error) { switch verificationKey := verificationKey.(type) { case ed25519.PublicKey: return &edEncrypterVerifier{ publicKey: verificationKey, }, nil case *rsa.PublicKey: return &rsaEncrypterVerifier{ publicKey: verificationKey, }, nil case *ecdsa.PublicKey: return &ecEncrypterVerifier{ publicKey: verificationKey, }, nil case []byte: return &symmetricMac{ key: verificationKey, }, nil case JSONWebKey: return newVerifier(verificationKey.Key) case *JSONWebKey: return newVerifier(verificationKey.Key) } if ov, ok := verificationKey.(OpaqueVerifier); ok { return &opaqueVerifier{verifier: ov}, nil } return nil, ErrUnsupportedKeyType } func (ctx *genericSigner) addRecipient(alg SignatureAlgorithm, signingKey interface{}) error { recipient, err := makeJWSRecipient(alg, signingKey) if err != nil { return err } ctx.recipients = append(ctx.recipients, recipient) return nil } func makeJWSRecipient(alg SignatureAlgorithm, signingKey interface{}) (recipientSigInfo, error) { switch signingKey := signingKey.(type) { case ed25519.PrivateKey: return newEd25519Signer(alg, signingKey) case *rsa.PrivateKey: return newRSASigner(alg, signingKey) case *ecdsa.PrivateKey: return newECDSASigner(alg, signingKey) case []byte: return newSymmetricSigner(alg, signingKey) case JSONWebKey: return newJWKSigner(alg, signingKey) case *JSONWebKey: return newJWKSigner(alg, *signingKey) } if signer, ok := signingKey.(OpaqueSigner); ok { return newOpaqueSigner(alg, signer) } return recipientSigInfo{}, ErrUnsupportedKeyType } func newJWKSigner(alg SignatureAlgorithm, signingKey JSONWebKey) (recipientSigInfo, error) { recipient, err := makeJWSRecipient(alg, signingKey.Key) if err != nil { return recipientSigInfo{}, err } if recipient.publicKey != nil && recipient.publicKey() != nil { // recipient.publicKey is a JWK synthesized for embedding when recipientSigInfo // was created for the inner key (such as a RSA or ECDSA public key). It contains // the pub key for embedding, but doesn't have extra params like key id. publicKey := signingKey publicKey.Key = recipient.publicKey().Key recipient.publicKey = staticPublicKey(&publicKey) // This should be impossible, but let's check anyway. if !recipient.publicKey().IsPublic() { return recipientSigInfo{}, errors.New("square/go-jose: public key was unexpectedly not public") } } return recipient, nil } func (ctx *genericSigner) Sign(payload []byte) (*JSONWebSignature, error) { obj := &JSONWebSignature{} obj.payload = payload obj.Signatures = make([]Signature, len(ctx.recipients)) for i, recipient := range ctx.recipients { protected := map[HeaderKey]interface{}{ headerAlgorithm: string(recipient.sigAlg), } if recipient.publicKey != nil && recipient.publicKey() != nil { // We want to embed the JWK or set the kid header, but not both. Having a protected // header that contains an embedded JWK while also simultaneously containing the kid // header is confusing, and at least in ACME the two are considered to be mutually // exclusive. The fact that both can exist at the same time is a somewhat unfortunate // result of the JOSE spec. We've decided that this library will only include one or // the other to avoid this confusion. // // See https://github.com/square/go-jose/issues/157 for more context. if ctx.embedJWK { protected[headerJWK] = recipient.publicKey() } else { protected[headerKeyID] = recipient.publicKey().KeyID } } if ctx.nonceSource != nil { nonce, err := ctx.nonceSource.Nonce() if err != nil { return nil, fmt.Errorf("square/go-jose: Error generating nonce: %v", err) } protected[headerNonce] = nonce } for k, v := range ctx.extraHeaders { protected[k] = v } serializedProtected := mustSerializeJSON(protected) input := []byte(fmt.Sprintf("%s.%s", base64.RawURLEncoding.EncodeToString(serializedProtected), base64.RawURLEncoding.EncodeToString(payload))) signatureInfo, err := recipient.signer.signPayload(input, recipient.sigAlg) if err != nil { return nil, err } signatureInfo.protected = &rawHeader{} for k, v := range protected { b, err := json.Marshal(v) if err != nil { return nil, fmt.Errorf("square/go-jose: Error marshalling item %#v: %v", k, err) } (*signatureInfo.protected)[k] = makeRawMessage(b) } obj.Signatures[i] = signatureInfo } return obj, nil } func (ctx *genericSigner) Options() SignerOptions { return SignerOptions{ NonceSource: ctx.nonceSource, EmbedJWK: ctx.embedJWK, ExtraHeaders: ctx.extraHeaders, } } // Verify validates the signature on the object and returns the payload. // This function does not support multi-signature, if you desire multi-sig // verification use VerifyMulti instead. // // Be careful when verifying signatures based on embedded JWKs inside the // payload header. You cannot assume that the key received in a payload is // trusted. func (obj JSONWebSignature) Verify(verificationKey interface{}) ([]byte, error) { err := obj.DetachedVerify(obj.payload, verificationKey) if err != nil { return nil, err } return obj.payload, nil } // UnsafePayloadWithoutVerification returns the payload without // verifying it. The content returned from this function cannot be // trusted. func (obj JSONWebSignature) UnsafePayloadWithoutVerification() []byte { return obj.payload } // DetachedVerify validates a detached signature on the given payload. In // most cases, you will probably want to use Verify instead. DetachedVerify // is only useful if you have a payload and signature that are separated from // each other. func (obj JSONWebSignature) DetachedVerify(payload []byte, verificationKey interface{}) error { verifier, err := newVerifier(verificationKey) if err != nil { return err } if len(obj.Signatures) > 1 { return errors.New("square/go-jose: too many signatures in payload; expecting only one") } signature := obj.Signatures[0] headers := signature.mergedHeaders() critical, err := headers.getCritical() if err != nil { return err } if len(critical) > 0 { // Unsupported crit header return ErrCryptoFailure } input := obj.computeAuthData(payload, &signature) alg := headers.getSignatureAlgorithm() err = verifier.verifyPayload(input, signature.Signature, alg) if err == nil { return nil } return ErrCryptoFailure } // VerifyMulti validates (one of the multiple) signatures on the object and // returns the index of the signature that was verified, along with the signature // object and the payload. We return the signature and index to guarantee that // callers are getting the verified value. func (obj JSONWebSignature) VerifyMulti(verificationKey interface{}) (int, Signature, []byte, error) { idx, sig, err := obj.DetachedVerifyMulti(obj.payload, verificationKey) if err != nil { return -1, Signature{}, nil, err } return idx, sig, obj.payload, nil } // DetachedVerifyMulti validates a detached signature on the given payload with // a signature/object that has potentially multiple signers. This returns the index // of the signature that was verified, along with the signature object. We return // the signature and index to guarantee that callers are getting the verified value. // // In most cases, you will probably want to use Verify or VerifyMulti instead. // DetachedVerifyMulti is only useful if you have a payload and signature that are // separated from each other, and the signature can have multiple signers at the // same time. func (obj JSONWebSignature) DetachedVerifyMulti(payload []byte, verificationKey interface{}) (int, Signature, error) { verifier, err := newVerifier(verificationKey) if err != nil { return -1, Signature{}, err } for i, signature := range obj.Signatures { headers := signature.mergedHeaders() critical, err := headers.getCritical() if err != nil { continue } if len(critical) > 0 { // Unsupported crit header continue } input := obj.computeAuthData(payload, &signature) alg := headers.getSignatureAlgorithm() err = verifier.verifyPayload(input, signature.Signature, alg) if err == nil { return i, signature, nil } } return -1, Signature{}, ErrCryptoFailure }
vendor/gopkg.in/square/go-jose.v2/signing.go
0
https://github.com/grafana/grafana/commit/44eaa3eaa886e0f193e9b6ae364e0526c858cb00
[ 0.0034739968832582235, 0.0002690938126761466, 0.00016263201541732997, 0.00017038029909599572, 0.0005227273213677108 ]