hunk
dict
file
stringlengths
0
11.8M
file_path
stringlengths
2
234
label
int64
0
1
commit_url
stringlengths
74
103
dependency_score
sequencelengths
5
5
{ "id": 6, "code_window": [ "\t/* Very aggressive list styles try to apply focus colors to every codicon in a list row. */\n", "\tcolor: var(--vscode-foreground) !important;\n", "}\n" ], "labels": [ "keep", "keep", "add" ], "after_edit": [ "\n", ".interactive-session .interactive-item-container.filtered-response .value .rendered-markdown {\n", "\t-webkit-mask-image: linear-gradient(rgba(0, 0, 0, 0.85), rgba(0, 0, 0, 0.05));\n", "\tmask-image: linear-gradient(rgba(0, 0, 0, 0.85), rgba(0, 0, 0, 0.05));\n", "}" ], "file_path": "src/vs/workbench/contrib/interactiveSession/browser/media/interactiveSession.css", "type": "add", "edit_start_line_idx": 327 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as path from 'vs/base/common/path'; import { URI, UriComponents } from 'vs/base/common/uri'; import { win32 } from 'vs/base/node/processes'; import * as types from 'vs/workbench/api/common/extHostTypes'; import { IExtHostWorkspace } from 'vs/workbench/api/common/extHostWorkspace'; import type * as vscode from 'vscode'; import * as tasks from '../common/shared/tasks'; import { IExtHostDocumentsAndEditors } from 'vs/workbench/api/common/extHostDocumentsAndEditors'; import { IExtHostConfiguration } from 'vs/workbench/api/common/extHostConfiguration'; import { IWorkspaceFolder, WorkspaceFolder } from 'vs/platform/workspace/common/workspace'; import { IExtensionDescription } from 'vs/platform/extensions/common/extensions'; import { IExtHostTerminalService } from 'vs/workbench/api/common/extHostTerminalService'; import { IExtHostRpcService } from 'vs/workbench/api/common/extHostRpcService'; import { IExtHostInitDataService } from 'vs/workbench/api/common/extHostInitDataService'; import { ExtHostTaskBase, TaskHandleDTO, TaskDTO, CustomExecutionDTO, HandlerData } from 'vs/workbench/api/common/extHostTask'; import { Schemas } from 'vs/base/common/network'; import { ILogService } from 'vs/platform/log/common/log'; import { IExtHostApiDeprecationService } from 'vs/workbench/api/common/extHostApiDeprecationService'; import * as resources from 'vs/base/common/resources'; import { homedir } from 'os'; import { IExtHostVariableResolverProvider } from 'vs/workbench/api/common/extHostVariableResolverService'; export class ExtHostTask extends ExtHostTaskBase { constructor( @IExtHostRpcService extHostRpc: IExtHostRpcService, @IExtHostInitDataService initData: IExtHostInitDataService, @IExtHostWorkspace private readonly workspaceService: IExtHostWorkspace, @IExtHostDocumentsAndEditors editorService: IExtHostDocumentsAndEditors, @IExtHostConfiguration configurationService: IExtHostConfiguration, @IExtHostTerminalService extHostTerminalService: IExtHostTerminalService, @ILogService logService: ILogService, @IExtHostApiDeprecationService deprecationService: IExtHostApiDeprecationService, @IExtHostVariableResolverProvider private readonly variableResolver: IExtHostVariableResolverProvider, ) { super(extHostRpc, initData, workspaceService, editorService, configurationService, extHostTerminalService, logService, deprecationService); if (initData.remote.isRemote && initData.remote.authority) { this.registerTaskSystem(Schemas.vscodeRemote, { scheme: Schemas.vscodeRemote, authority: initData.remote.authority, platform: process.platform }); } else { this.registerTaskSystem(Schemas.file, { scheme: Schemas.file, authority: '', platform: process.platform }); } this._proxy.$registerSupportedExecutions(true, true, true); } public async executeTask(extension: IExtensionDescription, task: vscode.Task): Promise<vscode.TaskExecution> { const tTask = (task as types.Task); if (!task.execution && (tTask._id === undefined)) { throw new Error('Tasks to execute must include an execution'); } // We have a preserved ID. So the task didn't change. if (tTask._id !== undefined) { // Always get the task execution first to prevent timing issues when retrieving it later const handleDto = TaskHandleDTO.from(tTask, this.workspaceService); const executionDTO = await this._proxy.$getTaskExecution(handleDto); if (executionDTO.task === undefined) { throw new Error('Task from execution DTO is undefined'); } const execution = await this.getTaskExecution(executionDTO, task); this._proxy.$executeTask(handleDto).catch(() => { /* The error here isn't actionable. */ }); return execution; } else { const dto = TaskDTO.from(task, extension); if (dto === undefined) { return Promise.reject(new Error('Task is not valid')); } // If this task is a custom execution, then we need to save it away // in the provided custom execution map that is cleaned up after the // task is executed. if (CustomExecutionDTO.is(dto.execution)) { await this.addCustomExecution(dto, task, false); } // Always get the task execution first to prevent timing issues when retrieving it later const execution = await this.getTaskExecution(await this._proxy.$getTaskExecution(dto), task); this._proxy.$executeTask(dto).catch(() => { /* The error here isn't actionable. */ }); return execution; } } protected provideTasksInternal(validTypes: { [key: string]: boolean }, taskIdPromises: Promise<void>[], handler: HandlerData, value: vscode.Task[] | null | undefined): { tasks: tasks.ITaskDTO[]; extension: IExtensionDescription } { const taskDTOs: tasks.ITaskDTO[] = []; if (value) { for (const task of value) { this.checkDeprecation(task, handler); if (!task.definition || !validTypes[task.definition.type]) { this._logService.warn(`The task [${task.source}, ${task.name}] uses an undefined task type. The task will be ignored in the future.`); } const taskDTO: tasks.ITaskDTO | undefined = TaskDTO.from(task, handler.extension); if (taskDTO) { taskDTOs.push(taskDTO); if (CustomExecutionDTO.is(taskDTO.execution)) { // The ID is calculated on the main thread task side, so, let's call into it here. // We need the task id's pre-computed for custom task executions because when OnDidStartTask // is invoked, we have to be able to map it back to our data. taskIdPromises.push(this.addCustomExecution(taskDTO, task, true)); } } } } return { tasks: taskDTOs, extension: handler.extension }; } protected async resolveTaskInternal(resolvedTaskDTO: tasks.ITaskDTO): Promise<tasks.ITaskDTO | undefined> { return resolvedTaskDTO; } private async getAFolder(workspaceFolders: vscode.WorkspaceFolder[] | undefined): Promise<IWorkspaceFolder> { let folder = (workspaceFolders && workspaceFolders.length > 0) ? workspaceFolders[0] : undefined; if (!folder) { const userhome = URI.file(homedir()); folder = new WorkspaceFolder({ uri: userhome, name: resources.basename(userhome), index: 0 }); } return { uri: folder.uri, name: folder.name, index: folder.index, toResource: () => { throw new Error('Not implemented'); } }; } public async $resolveVariables(uriComponents: UriComponents, toResolve: { process?: { name: string; cwd?: string; path?: string }; variables: string[] }): Promise<{ process?: string; variables: { [key: string]: string } }> { const uri: URI = URI.revive(uriComponents); const result = { process: <unknown>undefined as string, variables: Object.create(null) }; const workspaceFolder = await this._workspaceProvider.resolveWorkspaceFolder(uri); const workspaceFolders = (await this._workspaceProvider.getWorkspaceFolders2()) ?? []; const resolver = await this.variableResolver.getResolver(); const ws: IWorkspaceFolder = workspaceFolder ? { uri: workspaceFolder.uri, name: workspaceFolder.name, index: workspaceFolder.index, toResource: () => { throw new Error('Not implemented'); } } : await this.getAFolder(workspaceFolders); for (const variable of toResolve.variables) { result.variables[variable] = await resolver.resolveAsync(ws, variable); } if (toResolve.process !== undefined) { let paths: string[] | undefined = undefined; if (toResolve.process.path !== undefined) { paths = toResolve.process.path.split(path.delimiter); for (let i = 0; i < paths.length; i++) { paths[i] = await resolver.resolveAsync(ws, paths[i]); } } result.process = await win32.findExecutable( await resolver.resolveAsync(ws, toResolve.process.name), toResolve.process.cwd !== undefined ? await resolver.resolveAsync(ws, toResolve.process.cwd) : undefined, paths ); } return result; } public async $jsonTasksSupported(): Promise<boolean> { return true; } public async $findExecutable(command: string, cwd?: string, paths?: string[]): Promise<string> { return win32.findExecutable(command, cwd, paths); } }
src/vs/workbench/api/node/extHostTask.ts
0
https://github.com/microsoft/vscode/commit/324d1a25760c6abeb4a0492c0c5a22795b695bf4
[ 0.00017670754459686577, 0.000170604616869241, 0.00016592767497058958, 0.00017041873070411384, 0.000003023024646608974 ]
{ "id": 6, "code_window": [ "\t/* Very aggressive list styles try to apply focus colors to every codicon in a list row. */\n", "\tcolor: var(--vscode-foreground) !important;\n", "}\n" ], "labels": [ "keep", "keep", "add" ], "after_edit": [ "\n", ".interactive-session .interactive-item-container.filtered-response .value .rendered-markdown {\n", "\t-webkit-mask-image: linear-gradient(rgba(0, 0, 0, 0.85), rgba(0, 0, 0, 0.05));\n", "\tmask-image: linear-gradient(rgba(0, 0, 0, 0.85), rgba(0, 0, 0, 0.05));\n", "}" ], "file_path": "src/vs/workbench/contrib/interactiveSession/browser/media/interactiveSession.css", "type": "add", "edit_start_line_idx": 327 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as https from 'https'; import * as fs from 'fs'; import * as path from 'path'; import * as cp from 'child_process'; import { parse as parseUrl } from 'url'; function ensureFolderExists(loc: string) { if (!fs.existsSync(loc)) { const parent = path.dirname(loc); if (parent) { ensureFolderExists(parent); } fs.mkdirSync(loc); } } function getDownloadUrl(updateUrl: string, commit: string, platform: string, quality: string): string { return `${updateUrl}/commit:${commit}/server-${platform}/${quality}`; } async function downloadVSCodeServerArchive(updateUrl: string, commit: string, quality: string, destDir: string, log: (messsage: string) => void): Promise<string> { ensureFolderExists(destDir); const platform = process.platform === 'win32' ? 'win32-x64' : process.platform === 'darwin' ? 'darwin' : 'linux-x64'; const downloadUrl = getDownloadUrl(updateUrl, commit, platform, quality); return new Promise((resolve, reject) => { log(`Downloading VS Code Server from: ${downloadUrl}`); const requestOptions: https.RequestOptions = parseUrl(downloadUrl); https.get(requestOptions, res => { if (res.statusCode !== 302) { reject('Failed to get VS Code server archive location'); } const archiveUrl = res.headers.location; if (!archiveUrl) { reject('Failed to get VS Code server archive location'); return; } const archiveRequestOptions: https.RequestOptions = parseUrl(archiveUrl); if (archiveUrl.endsWith('.zip')) { const archivePath = path.resolve(destDir, `vscode-server-${commit}.zip`); const outStream = fs.createWriteStream(archivePath); outStream.on('close', () => { resolve(archivePath); }); https.get(archiveRequestOptions, res => { res.pipe(outStream); }); } else { const zipPath = path.resolve(destDir, `vscode-server-${commit}.tgz`); const outStream = fs.createWriteStream(zipPath); https.get(archiveRequestOptions, res => { res.pipe(outStream); }); outStream.on('close', () => { resolve(zipPath); }); } }); }); } /** * Unzip a .zip or .tar.gz VS Code archive */ function unzipVSCodeServer(vscodeArchivePath: string, extractDir: string, destDir: string, log: (messsage: string) => void) { log(`Extracting ${vscodeArchivePath}`); if (vscodeArchivePath.endsWith('.zip')) { const tempDir = fs.mkdtempSync(path.join(destDir, 'vscode-server-extract')); if (process.platform === 'win32') { cp.spawnSync('powershell.exe', [ '-NoProfile', '-ExecutionPolicy', 'Bypass', '-NonInteractive', '-NoLogo', '-Command', `Microsoft.PowerShell.Archive\\Expand-Archive -Path "${vscodeArchivePath}" -DestinationPath "${tempDir}"` ]); } else { cp.spawnSync('unzip', [vscodeArchivePath, '-d', `${tempDir}`]); } fs.renameSync(path.join(tempDir, process.platform === 'win32' ? 'vscode-server-win32-x64' : 'vscode-server-darwin-x64'), extractDir); } else { // tar does not create extractDir by default if (!fs.existsSync(extractDir)) { fs.mkdirSync(extractDir); } cp.spawnSync('tar', ['-xzf', vscodeArchivePath, '-C', extractDir, '--strip-components', '1']); } } export async function downloadAndUnzipVSCodeServer(updateUrl: string, commit: string, quality: string = 'stable', destDir: string, log: (messsage: string) => void): Promise<string> { const extractDir = path.join(destDir, commit); if (fs.existsSync(extractDir)) { log(`Found ${extractDir}. Skipping download.`); } else { log(`Downloading VS Code Server ${quality} - ${commit} into ${extractDir}.`); try { const vscodeArchivePath = await downloadVSCodeServerArchive(updateUrl, commit, quality, destDir, log); if (fs.existsSync(vscodeArchivePath)) { unzipVSCodeServer(vscodeArchivePath, extractDir, destDir, log); // Remove archive fs.unlinkSync(vscodeArchivePath); } } catch (err) { throw Error(`Failed to download and unzip VS Code ${quality} - ${commit}`); } } return Promise.resolve(extractDir); }
extensions/vscode-test-resolver/src/download.ts
0
https://github.com/microsoft/vscode/commit/324d1a25760c6abeb4a0492c0c5a22795b695bf4
[ 0.0004521050723269582, 0.0001969647710211575, 0.00016537027840968221, 0.0001697359257377684, 0.00007747684139758348 ]
{ "id": 7, "code_window": [ "import { Emitter, Event } from 'vs/base/common/event';\n", "import { IMarkdownString, MarkdownString } from 'vs/base/common/htmlContent';\n", "import { Disposable } from 'vs/base/common/lifecycle';\n", "import { URI } from 'vs/base/common/uri';\n", "import { ILogService } from 'vs/platform/log/common/log';\n", "import { IInteractiveProgress, IInteractiveResponse, IInteractiveSession, IInteractiveSessionFollowup, IInteractiveSessionReplyFollowup, InteractiveSessionVoteDirection } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionService';\n", "\n", "export interface IInteractiveRequestModel {\n", "\treadonly id: string;\n", "\treadonly username: string;\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { IInteractiveProgress, IInteractiveResponse, IInteractiveResponseErrorDetails, IInteractiveSession, IInteractiveSessionFollowup, IInteractiveSessionReplyFollowup, InteractiveSessionVoteDirection } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionService';\n" ], "file_path": "src/vs/workbench/contrib/interactiveSession/common/interactiveSessionModel.ts", "type": "replace", "edit_start_line_idx": 10 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Emitter, Event } from 'vs/base/common/event'; import { IMarkdownString, MarkdownString } from 'vs/base/common/htmlContent'; import { Disposable } from 'vs/base/common/lifecycle'; import { URI } from 'vs/base/common/uri'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { ILogService } from 'vs/platform/log/common/log'; import { IInteractiveRequestModel, IInteractiveResponseErrorDetails, IInteractiveResponseModel, IInteractiveSessionModel, IInteractiveSessionWelcomeMessageModel, IInteractiveWelcomeMessageContent } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionModel'; import { IInteractiveSessionReplyFollowup, IInteractiveSessionResponseCommandFollowup, IInteractiveSessionService, InteractiveSessionVoteDirection } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionService'; import { countWords } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionWordCounter'; export function isRequestVM(item: unknown): item is IInteractiveRequestViewModel { return !!item && typeof item === 'object' && 'message' in item; } export function isResponseVM(item: unknown): item is IInteractiveResponseViewModel { return !!item && typeof (item as IInteractiveResponseViewModel).onDidChange !== 'undefined'; } export function isWelcomeVM(item: unknown): item is IInteractiveWelcomeMessageViewModel { return !!item && typeof item === 'object' && 'content' in item; } export interface IInteractiveSessionViewModel { readonly sessionId: number; readonly onDidDisposeModel: Event<void>; readonly onDidChange: Event<void>; readonly welcomeMessage: IInteractiveWelcomeMessageViewModel | undefined; readonly inputPlaceholder?: string; getItems(): (IInteractiveRequestViewModel | IInteractiveResponseViewModel)[]; } export interface IInteractiveRequestViewModel { readonly id: string; readonly username: string; readonly avatarIconUri?: URI; readonly message: string | IInteractiveSessionReplyFollowup; readonly messageText: string; currentRenderedHeight: number | undefined; } export interface IInteractiveResponseRenderData { renderedWordCount: number; lastRenderTime: number; isFullyRendered: boolean; } export interface IInteractiveSessionLiveUpdateData { wordCountAfterLastUpdate: number; loadingStartTime: number; lastUpdateTime: number; impliedWordLoadRate: number; } export interface IInteractiveResponseViewModel { readonly onDidChange: Event<void>; readonly id: string; readonly providerId: string; readonly providerResponseId: string | undefined; readonly username: string; readonly avatarIconUri?: URI; readonly response: IMarkdownString; readonly isComplete: boolean; readonly isCanceled: boolean; readonly isPlaceholder: boolean; readonly vote: InteractiveSessionVoteDirection | undefined; readonly replyFollowups?: IInteractiveSessionReplyFollowup[]; readonly commandFollowups?: IInteractiveSessionResponseCommandFollowup[]; readonly errorDetails?: IInteractiveResponseErrorDetails; readonly progressiveResponseRenderingEnabled: boolean; readonly contentUpdateTimings?: IInteractiveSessionLiveUpdateData; renderData?: IInteractiveResponseRenderData; currentRenderedHeight: number | undefined; setVote(vote: InteractiveSessionVoteDirection): void; } export class InteractiveSessionViewModel extends Disposable implements IInteractiveSessionViewModel { private readonly _onDidDisposeModel = this._register(new Emitter<void>()); readonly onDidDisposeModel = this._onDidDisposeModel.event; private readonly _onDidChange = this._register(new Emitter<void>()); readonly onDidChange = this._onDidChange.event; private readonly _items: (IInteractiveRequestViewModel | IInteractiveResponseViewModel)[] = []; get inputPlaceholder(): string | undefined { return this._model.inputPlaceholder; } get welcomeMessage() { return this._model.welcomeMessage; } get sessionId() { return this._model.sessionId; } private readonly _progressiveResponseRenderingEnabled: boolean; get progressiveResponseRenderingEnabled(): boolean { return this._progressiveResponseRenderingEnabled; } constructor( private readonly _model: IInteractiveSessionModel, @IInteractiveSessionService private readonly interactiveSessionService: IInteractiveSessionService, @IInstantiationService private readonly instantiationService: IInstantiationService, ) { super(); this._progressiveResponseRenderingEnabled = this.interactiveSessionService.progressiveRenderingEnabled(this._model.providerId); _model.getRequests().forEach((request, i) => { this._items.push(new InteractiveRequestViewModel(request)); if (request.response) { this.onAddResponse(request.response); } }); this._register(_model.onDidDispose(() => this._onDidDisposeModel.fire())); this._register(_model.onDidChange(e => { if (e.kind === 'clear') { this._items.length = 0; this._onDidChange.fire(); } else if (e.kind === 'addRequest') { this._items.push(new InteractiveRequestViewModel(e.request)); if (e.request.response) { this.onAddResponse(e.request.response); } } else if (e.kind === 'addResponse') { this.onAddResponse(e.response); } this._onDidChange.fire(); })); } private onAddResponse(responseModel: IInteractiveResponseModel) { const response = this.instantiationService.createInstance(InteractiveResponseViewModel, responseModel, this.progressiveResponseRenderingEnabled); this._register(response.onDidChange(() => this._onDidChange.fire())); this._items.push(response); } getItems() { return [...this._items]; } override dispose() { super.dispose(); this._items .filter((item): item is InteractiveResponseViewModel => item instanceof InteractiveResponseViewModel) .forEach((item: InteractiveResponseViewModel) => item.dispose()); } } export class InteractiveRequestViewModel implements IInteractiveRequestViewModel { get id() { return this._model.id; } get username() { return this._model.username; } get avatarIconUri() { return this._model.avatarIconUri; } get message() { return this._model.message; } get messageText() { return typeof this.message === 'string' ? this.message : this.message.message; } currentRenderedHeight: number | undefined; constructor(readonly _model: IInteractiveRequestModel) { } } export class InteractiveResponseViewModel extends Disposable implements IInteractiveResponseViewModel { private _changeCount = 0; private readonly _onDidChange = this._register(new Emitter<void>()); readonly onDidChange = this._onDidChange.event; private _isPlaceholder = false; get isPlaceholder() { return this._isPlaceholder; } get id() { return this._model.id + `_${this._changeCount}`; } get providerId() { return this._model.providerId; } get providerResponseId() { return this._model.providerResponseId; } get username() { return this._model.username; } get avatarIconUri() { return this._model.avatarIconUri; } get response(): IMarkdownString { if (this._isPlaceholder) { return new MarkdownString('Thinking...'); } return this._model.response; } get isComplete() { return this._model.isComplete; } get isCanceled() { return this._model.isCanceled; } get replyFollowups() { return this._model.followups?.filter((f): f is IInteractiveSessionReplyFollowup => f.kind === 'reply'); } get commandFollowups() { return this._model.followups?.filter((f): f is IInteractiveSessionResponseCommandFollowup => f.kind === 'command'); } get errorDetails() { return this._model.errorDetails; } get vote() { return this._model.vote; } renderData: IInteractiveResponseRenderData | undefined = undefined; currentRenderedHeight: number | undefined; private _contentUpdateTimings: IInteractiveSessionLiveUpdateData | undefined = undefined; get contentUpdateTimings(): IInteractiveSessionLiveUpdateData | undefined { return this._contentUpdateTimings; } constructor( private readonly _model: IInteractiveResponseModel, public readonly progressiveResponseRenderingEnabled: boolean, @ILogService private readonly logService: ILogService ) { super(); this._isPlaceholder = !_model.response.value && !_model.isComplete; if (!_model.isComplete) { this._contentUpdateTimings = { loadingStartTime: Date.now(), lastUpdateTime: Date.now(), wordCountAfterLastUpdate: this._isPlaceholder ? 0 : countWords(_model.response.value), // don't count placeholder text impliedWordLoadRate: 0 }; } this._register(_model.onDidChange(() => { if (this._isPlaceholder && (_model.response.value || this.isComplete)) { this._isPlaceholder = false; if (this.renderData) { this.renderData.renderedWordCount = 0; } } if (this._contentUpdateTimings) { // This should be true, if the model is changing const now = Date.now(); const wordCount = countWords(_model.response.value); const timeDiff = now - this._contentUpdateTimings!.loadingStartTime; const impliedWordLoadRate = wordCount / (timeDiff / 1000); if (!this.isComplete) { this.trace('onDidChange', `Update- got ${wordCount} words over ${timeDiff}ms = ${impliedWordLoadRate} words/s. ${this.renderData?.renderedWordCount} words are rendered.`); this._contentUpdateTimings = { loadingStartTime: this._contentUpdateTimings!.loadingStartTime, lastUpdateTime: now, wordCountAfterLastUpdate: wordCount, // lastUpdateNewWordCount: wordCount - this._contentUpdateTimings!.wordCountAfterLastUpdate, // lastUpdateDuration: now - this._contentUpdateTimings!.lastUpdateTime, // none impliedWordLoadRate }; } else { this.trace(`onDidChange`, `Done- got ${wordCount} words over ${timeDiff}ms = ${impliedWordLoadRate} words/s. ${this.renderData?.renderedWordCount} words are rendered.`); } } else { this.logService.warn('InteractiveResponseViewModel#onDidChange: got model update but contentUpdateTimings is not initialized'); } // new data -> new id, new content to render this._changeCount++; if (this.renderData) { this.renderData.isFullyRendered = false; this.renderData.lastRenderTime = Date.now(); } this._onDidChange.fire(); })); } private trace(tag: string, message: string) { this.logService.trace(`InteractiveResponseViewModel#${tag}: ${message}`); } setVote(vote: InteractiveSessionVoteDirection): void { this._changeCount++; this._model.setVote(vote); } } export interface IInteractiveWelcomeMessageViewModel { readonly id: string; readonly username: string; readonly avatarIconUri?: URI; readonly content: IInteractiveWelcomeMessageContent[]; } export class InteractiveWelcomeMessageViewModel implements IInteractiveWelcomeMessageViewModel { get id() { return this._model.id; } get username() { return this._model.username; } get avatarIconUri() { return this._model.avatarIconUri; } get content() { return this._model.content; } constructor(readonly _model: IInteractiveSessionWelcomeMessageModel) { } }
src/vs/workbench/contrib/interactiveSession/common/interactiveSessionViewModel.ts
1
https://github.com/microsoft/vscode/commit/324d1a25760c6abeb4a0492c0c5a22795b695bf4
[ 0.9989860653877258, 0.22327357530593872, 0.00016374581900890917, 0.0005767968250438571, 0.4091722071170807 ]
{ "id": 7, "code_window": [ "import { Emitter, Event } from 'vs/base/common/event';\n", "import { IMarkdownString, MarkdownString } from 'vs/base/common/htmlContent';\n", "import { Disposable } from 'vs/base/common/lifecycle';\n", "import { URI } from 'vs/base/common/uri';\n", "import { ILogService } from 'vs/platform/log/common/log';\n", "import { IInteractiveProgress, IInteractiveResponse, IInteractiveSession, IInteractiveSessionFollowup, IInteractiveSessionReplyFollowup, InteractiveSessionVoteDirection } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionService';\n", "\n", "export interface IInteractiveRequestModel {\n", "\treadonly id: string;\n", "\treadonly username: string;\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { IInteractiveProgress, IInteractiveResponse, IInteractiveResponseErrorDetails, IInteractiveSession, IInteractiveSessionFollowup, IInteractiveSessionReplyFollowup, InteractiveSessionVoteDirection } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionService';\n" ], "file_path": "src/vs/workbench/contrib/interactiveSession/common/interactiveSessionModel.ts", "type": "replace", "edit_start_line_idx": 10 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { streamToBuffer } from 'vs/base/common/buffer'; import { CancellationToken } from 'vs/base/common/cancellation'; import { getErrorMessage } from 'vs/base/common/errors'; import { Disposable } from 'vs/base/common/lifecycle'; import { IHeaders, IRequestContext, IRequestOptions } from 'vs/base/parts/request/common/request'; import { localize } from 'vs/nls'; import { ConfigurationScope, Extensions, IConfigurationNode, IConfigurationRegistry } from 'vs/platform/configuration/common/configurationRegistry'; import { createDecorator } from 'vs/platform/instantiation/common/instantiation'; import { CONTEXT_LOG_LEVEL, ILogger, ILoggerService, LogLevel, LogLevelToString } from 'vs/platform/log/common/log'; import { Registry } from 'vs/platform/registry/common/platform'; export const IRequestService = createDecorator<IRequestService>('requestService'); export interface IRequestService { readonly _serviceBrand: undefined; request(options: IRequestOptions, token: CancellationToken): Promise<IRequestContext>; resolveProxy(url: string): Promise<string | undefined>; } class LoggableHeaders { private headers: IHeaders | undefined; constructor(private readonly original: IHeaders) { } toJSON(): any { if (!this.headers) { const headers = Object.create(null); for (const key in this.original) { if (key.toLowerCase() === 'authorization' || key.toLowerCase() === 'proxy-authorization') { headers[key] = '*****'; } else { headers[key] = this.original[key]; } } this.headers = headers; } return this.headers; } } export abstract class AbstractRequestService extends Disposable implements IRequestService { declare readonly _serviceBrand: undefined; protected readonly logger: ILogger; private counter = 0; constructor( remote: boolean, loggerService: ILoggerService ) { super(); this.logger = loggerService.createLogger(remote ? 'remotenetwork' : 'network', { name: remote ? localize('remote request', "Network Requests (Remote)") : localize('request', "Network Requests"), when: CONTEXT_LOG_LEVEL.isEqualTo(LogLevelToString(LogLevel.Trace)).serialize() }); } protected async logAndRequest(stack: string, options: IRequestOptions, request: () => Promise<IRequestContext>): Promise<IRequestContext> { const prefix = `${stack} #${++this.counter}: ${options.url}`; this.logger.trace(`${prefix} - begin`, options.type, new LoggableHeaders(options.headers ?? {})); try { const result = await request(); this.logger.trace(`${prefix} - end`, options.type, result.res.statusCode, result.res.headers); return result; } catch (error) { this.logger.error(`${prefix} - error`, options.type, getErrorMessage(error)); throw error; } } abstract request(options: IRequestOptions, token: CancellationToken): Promise<IRequestContext>; abstract resolveProxy(url: string): Promise<string | undefined>; } export function isSuccess(context: IRequestContext): boolean { return (context.res.statusCode && context.res.statusCode >= 200 && context.res.statusCode < 300) || context.res.statusCode === 1223; } function hasNoContent(context: IRequestContext): boolean { return context.res.statusCode === 204; } export async function asText(context: IRequestContext): Promise<string | null> { if (hasNoContent(context)) { return null; } const buffer = await streamToBuffer(context.stream); return buffer.toString(); } export async function asTextOrError(context: IRequestContext): Promise<string | null> { if (!isSuccess(context)) { throw new Error('Server returned ' + context.res.statusCode); } return asText(context); } export async function asJson<T = {}>(context: IRequestContext): Promise<T | null> { if (!isSuccess(context)) { throw new Error('Server returned ' + context.res.statusCode); } if (hasNoContent(context)) { return null; } const buffer = await streamToBuffer(context.stream); const str = buffer.toString(); try { return JSON.parse(str); } catch (err) { err.message += ':\n' + str; throw err; } } export function updateProxyConfigurationsScope(scope: ConfigurationScope): void { registerProxyConfigurations(scope); } let proxyConfiguration: IConfigurationNode | undefined; function registerProxyConfigurations(scope: ConfigurationScope): void { const configurationRegistry = Registry.as<IConfigurationRegistry>(Extensions.Configuration); const oldProxyConfiguration = proxyConfiguration; proxyConfiguration = { id: 'http', order: 15, title: localize('httpConfigurationTitle', "HTTP"), type: 'object', scope, properties: { 'http.proxy': { type: 'string', pattern: '^(https?|socks5?)://([^:]*(:[^@]*)?@)?([^:]+|\\[[:0-9a-fA-F]+\\])(:\\d+)?/?$|^$', markdownDescription: localize('proxy', "The proxy setting to use. If not set, will be inherited from the `http_proxy` and `https_proxy` environment variables."), restricted: true }, 'http.proxyStrictSSL': { type: 'boolean', default: true, description: localize('strictSSL', "Controls whether the proxy server certificate should be verified against the list of supplied CAs."), restricted: true }, 'http.proxyAuthorization': { type: ['null', 'string'], default: null, markdownDescription: localize('proxyAuthorization', "The value to send as the `Proxy-Authorization` header for every network request."), restricted: true }, 'http.proxySupport': { type: 'string', enum: ['off', 'on', 'fallback', 'override'], enumDescriptions: [ localize('proxySupportOff', "Disable proxy support for extensions."), localize('proxySupportOn', "Enable proxy support for extensions."), localize('proxySupportFallback', "Enable proxy support for extensions, fall back to request options, when no proxy found."), localize('proxySupportOverride', "Enable proxy support for extensions, override request options."), ], default: 'override', description: localize('proxySupport', "Use the proxy support for extensions."), restricted: true }, 'http.systemCertificates': { type: 'boolean', default: true, description: localize('systemCertificates', "Controls whether CA certificates should be loaded from the OS. (On Windows and macOS, a reload of the window is required after turning this off.)"), restricted: true } } }; configurationRegistry.updateConfigurations({ add: [proxyConfiguration], remove: oldProxyConfiguration ? [oldProxyConfiguration] : [] }); } registerProxyConfigurations(ConfigurationScope.APPLICATION);
src/vs/platform/request/common/request.ts
0
https://github.com/microsoft/vscode/commit/324d1a25760c6abeb4a0492c0c5a22795b695bf4
[ 0.0026809165719896555, 0.0004405185754876584, 0.00016432249685749412, 0.00017375177412759513, 0.0006817911635152996 ]
{ "id": 7, "code_window": [ "import { Emitter, Event } from 'vs/base/common/event';\n", "import { IMarkdownString, MarkdownString } from 'vs/base/common/htmlContent';\n", "import { Disposable } from 'vs/base/common/lifecycle';\n", "import { URI } from 'vs/base/common/uri';\n", "import { ILogService } from 'vs/platform/log/common/log';\n", "import { IInteractiveProgress, IInteractiveResponse, IInteractiveSession, IInteractiveSessionFollowup, IInteractiveSessionReplyFollowup, InteractiveSessionVoteDirection } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionService';\n", "\n", "export interface IInteractiveRequestModel {\n", "\treadonly id: string;\n", "\treadonly username: string;\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { IInteractiveProgress, IInteractiveResponse, IInteractiveResponseErrorDetails, IInteractiveSession, IInteractiveSessionFollowup, IInteractiveSessionReplyFollowup, InteractiveSessionVoteDirection } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionService';\n" ], "file_path": "src/vs/workbench/contrib/interactiveSession/common/interactiveSessionModel.ts", "type": "replace", "edit_start_line_idx": 10 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; const gulp = require('gulp'); const util = require('./lib/util'); const task = require('./lib/task'); const compilation = require('./lib/compilation'); const optimize = require('./lib/optimize'); // Full compile, including nls and inline sources in sourcemaps, for build const compileBuildTask = task.define('compile-build', task.series( util.rimraf('out-build'), util.buildWebNodePaths('out-build'), compilation.compileApiProposalNamesTask, compilation.compileTask('src', 'out-build', true), optimize.optimizeLoaderTask('out-build', 'out-build', true) ) ); gulp.task(compileBuildTask); exports.compileBuildTask = compileBuildTask;
build/gulpfile.compile.js
0
https://github.com/microsoft/vscode/commit/324d1a25760c6abeb4a0492c0c5a22795b695bf4
[ 0.00017677513824310154, 0.00017592281801626086, 0.00017544084403198212, 0.00017555247177369893, 6.044019187356753e-7 ]
{ "id": 7, "code_window": [ "import { Emitter, Event } from 'vs/base/common/event';\n", "import { IMarkdownString, MarkdownString } from 'vs/base/common/htmlContent';\n", "import { Disposable } from 'vs/base/common/lifecycle';\n", "import { URI } from 'vs/base/common/uri';\n", "import { ILogService } from 'vs/platform/log/common/log';\n", "import { IInteractiveProgress, IInteractiveResponse, IInteractiveSession, IInteractiveSessionFollowup, IInteractiveSessionReplyFollowup, InteractiveSessionVoteDirection } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionService';\n", "\n", "export interface IInteractiveRequestModel {\n", "\treadonly id: string;\n", "\treadonly username: string;\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { IInteractiveProgress, IInteractiveResponse, IInteractiveResponseErrorDetails, IInteractiveSession, IInteractiveSessionFollowup, IInteractiveSessionReplyFollowup, InteractiveSessionVoteDirection } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionService';\n" ], "file_path": "src/vs/workbench/contrib/interactiveSession/common/interactiveSessionModel.ts", "type": "replace", "edit_start_line_idx": 10 }
test/** src/** tsconfig.json out/** extension.webpack.config.js yarn.lock
extensions/grunt/.vscodeignore
0
https://github.com/microsoft/vscode/commit/324d1a25760c6abeb4a0492c0c5a22795b695bf4
[ 0.00017377728363499045, 0.00017377728363499045, 0.00017377728363499045, 0.00017377728363499045, 0 ]
{ "id": 8, "code_window": [ "\treadonly message: string | IInteractiveSessionReplyFollowup;\n", "\treadonly response: IInteractiveResponseModel | undefined;\n", "}\n", "\n", "export interface IInteractiveResponseErrorDetails {\n", "\tmessage: string;\n", "\tresponseIsIncomplete?: boolean;\n", "}\n", "\n", "export interface IInteractiveResponseModel {\n", "\treadonly onDidChange: Event<void>;\n", "\treadonly id: string;\n", "\treadonly providerId: string;\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/interactiveSession/common/interactiveSessionModel.ts", "type": "replace", "edit_start_line_idx": 20 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { CancellationToken } from 'vs/base/common/cancellation'; import { Event } from 'vs/base/common/event'; import { IDisposable } from 'vs/base/common/lifecycle'; import { URI } from 'vs/base/common/uri'; import { CompletionItemKind, ProviderResult } from 'vs/editor/common/languages'; import { createDecorator } from 'vs/platform/instantiation/common/instantiation'; import { IInteractiveResponseErrorDetails, InteractiveSessionModel } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionModel'; export interface IInteractiveSession { id: number; requesterUsername: string; requesterAvatarIconUri?: URI; responderUsername: string; responderAvatarIconUri?: URI; inputPlaceholder?: string; dispose?(): void; } export interface IInteractiveRequest { session: IInteractiveSession; message: string | IInteractiveSessionReplyFollowup; } export interface IInteractiveResponse { session: IInteractiveSession; errorDetails?: IInteractiveResponseErrorDetails; timings?: { firstProgress: number; totalElapsed: number; }; } export type IInteractiveProgress = { content: string } | { responseId: string }; export interface IPersistedInteractiveState { } export interface IInteractiveProvider { readonly id: string; readonly progressiveRenderingEnabled?: boolean; readonly iconUrl?: string; prepareSession(initialState: IPersistedInteractiveState | undefined, token: CancellationToken): ProviderResult<IInteractiveSession | undefined>; resolveRequest?(session: IInteractiveSession, context: any, token: CancellationToken): ProviderResult<IInteractiveRequest>; provideWelcomeMessage?(token: CancellationToken): ProviderResult<(string | IInteractiveSessionReplyFollowup[])[] | undefined>; provideSuggestions?(token: CancellationToken): ProviderResult<string[] | undefined>; provideFollowups?(session: IInteractiveSession, token: CancellationToken): ProviderResult<IInteractiveSessionFollowup[] | undefined>; provideReply(request: IInteractiveRequest, progress: (progress: IInteractiveProgress) => void, token: CancellationToken): ProviderResult<IInteractiveResponse>; provideSlashCommands?(session: IInteractiveSession, token: CancellationToken): ProviderResult<IInteractiveSlashCommand[]>; } export interface IInteractiveSlashCommand { command: string; kind: CompletionItemKind; detail?: string; } export interface IInteractiveSessionReplyFollowup { kind: 'reply'; message: string; title?: string; tooltip?: string; metadata?: any; } export interface IInteractiveSessionResponseCommandFollowup { kind: 'command'; commandId: string; args?: any[]; title: string; // supports codicon strings } export type IInteractiveSessionFollowup = IInteractiveSessionReplyFollowup | IInteractiveSessionResponseCommandFollowup; export enum InteractiveSessionVoteDirection { Up = 1, Down = 2 } export interface IInteractiveSessionVoteAction { kind: 'vote'; responseId: string; direction: InteractiveSessionVoteDirection; } export enum InteractiveSessionCopyKind { // Keyboard shortcut or context menu Action = 1, Toolbar = 2 } export interface IInteractiveSessionCopyAction { kind: 'copy'; responseId: string; codeBlockIndex: number; copyType: InteractiveSessionCopyKind; copiedCharacters: number; totalCharacters: number; copiedText: string; } export interface IInteractiveSessionInsertAction { kind: 'insert'; responseId: string; codeBlockIndex: number; } export interface IInteractiveSessionCommandAction { kind: 'command'; command: IInteractiveSessionResponseCommandFollowup; } export type InteractiveSessionUserAction = IInteractiveSessionVoteAction | IInteractiveSessionCopyAction | IInteractiveSessionInsertAction | IInteractiveSessionCommandAction; export interface IInteractiveSessionUserActionEvent { action: InteractiveSessionUserAction; providerId: string; } export interface IInteractiveSessionDynamicRequest { /** * The message that will be displayed in the UI */ message: string; /** * Any extra metadata/context that will go to the provider. */ metadata?: any; } export interface IInteractiveSessionCompleteResponse { message: string; errorDetails?: IInteractiveResponseErrorDetails; } export const IInteractiveSessionService = createDecorator<IInteractiveSessionService>('IInteractiveSessionService'); export interface IInteractiveSessionService { _serviceBrand: undefined; registerProvider(provider: IInteractiveProvider): IDisposable; progressiveRenderingEnabled(providerId: string): boolean; startSession(providerId: string, allowRestoringSession: boolean, token: CancellationToken): Promise<InteractiveSessionModel | undefined>; /** * Returns whether the request was accepted. */ sendRequest(sessionId: number, message: string | IInteractiveSessionReplyFollowup): { completePromise: Promise<void> } | undefined; cancelCurrentRequestForSession(sessionId: number): void; getSlashCommands(sessionId: number, token: CancellationToken): Promise<IInteractiveSlashCommand[] | undefined>; clearSession(sessionId: number): void; acceptNewSessionState(sessionId: number, state: any): void; addInteractiveRequest(context: any): void; addCompleteRequest(message: string, response: IInteractiveSessionCompleteResponse): void; sendInteractiveRequestToProvider(providerId: string, message: IInteractiveSessionDynamicRequest): void; provideSuggestions(providerId: string, token: CancellationToken): Promise<string[] | undefined>; releaseSession(sessionId: number): void; onDidPerformUserAction: Event<IInteractiveSessionUserActionEvent>; notifyUserAction(event: IInteractiveSessionUserActionEvent): void; }
src/vs/workbench/contrib/interactiveSession/common/interactiveSessionService.ts
1
https://github.com/microsoft/vscode/commit/324d1a25760c6abeb4a0492c0c5a22795b695bf4
[ 0.9992660880088806, 0.21504226326942444, 0.00016643665730953217, 0.03610627353191376, 0.3674373924732208 ]
{ "id": 8, "code_window": [ "\treadonly message: string | IInteractiveSessionReplyFollowup;\n", "\treadonly response: IInteractiveResponseModel | undefined;\n", "}\n", "\n", "export interface IInteractiveResponseErrorDetails {\n", "\tmessage: string;\n", "\tresponseIsIncomplete?: boolean;\n", "}\n", "\n", "export interface IInteractiveResponseModel {\n", "\treadonly onDidChange: Event<void>;\n", "\treadonly id: string;\n", "\treadonly providerId: string;\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/interactiveSession/common/interactiveSessionModel.ts", "type": "replace", "edit_start_line_idx": 20 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Disposable, Event } from 'vscode'; import { RemoteSourcePublisher } from './api/git'; export interface IRemoteSourcePublisherRegistry { readonly onDidAddRemoteSourcePublisher: Event<RemoteSourcePublisher>; readonly onDidRemoveRemoteSourcePublisher: Event<RemoteSourcePublisher>; getRemoteSourcePublishers(): RemoteSourcePublisher[]; registerRemoteSourcePublisher(publisher: RemoteSourcePublisher): Disposable; }
extensions/git/src/remotePublisher.ts
0
https://github.com/microsoft/vscode/commit/324d1a25760c6abeb4a0492c0c5a22795b695bf4
[ 0.0006778889801353216, 0.00042141578160226345, 0.00016494256851729006, 0.00042141578160226345, 0.00025647319853305817 ]
{ "id": 8, "code_window": [ "\treadonly message: string | IInteractiveSessionReplyFollowup;\n", "\treadonly response: IInteractiveResponseModel | undefined;\n", "}\n", "\n", "export interface IInteractiveResponseErrorDetails {\n", "\tmessage: string;\n", "\tresponseIsIncomplete?: boolean;\n", "}\n", "\n", "export interface IInteractiveResponseModel {\n", "\treadonly onDidChange: Event<void>;\n", "\treadonly id: string;\n", "\treadonly providerId: string;\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/interactiveSession/common/interactiveSessionModel.ts", "type": "replace", "edit_start_line_idx": 20 }
/*--------------------------------------------------------------------------------------------- * 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 { SyncDescriptor } from 'vs/platform/instantiation/common/descriptors'; import { InstantiationType, registerSingleton } from 'vs/platform/instantiation/common/extensions'; import { Registry } from 'vs/platform/registry/common/platform'; import { IViewsRegistry, IViewDescriptor, Extensions as ViewExtensions } from 'vs/workbench/common/views'; import { VIEW_CONTAINER } from 'vs/workbench/contrib/files/browser/explorerViewlet'; import { ITimelineService, TimelinePaneId } from 'vs/workbench/contrib/timeline/common/timeline'; import { TimelineHasProviderContext, TimelineService } from 'vs/workbench/contrib/timeline/common/timelineService'; import { TimelinePane } from './timelinePane'; import { IConfigurationRegistry, Extensions as ConfigurationExtensions } from 'vs/platform/configuration/common/configurationRegistry'; import { ContextKeyExpr } from 'vs/platform/contextkey/common/contextkey'; import { ISubmenuItem, MenuId, MenuRegistry } from 'vs/platform/actions/common/actions'; import { ICommandHandler, CommandsRegistry } from 'vs/platform/commands/common/commands'; import { ExplorerFolderContext } from 'vs/workbench/contrib/files/common/files'; import { ResourceContextKey } from 'vs/workbench/common/contextkeys'; import { Codicon } from 'vs/base/common/codicons'; import { registerIcon } from 'vs/platform/theme/common/iconRegistry'; const timelineViewIcon = registerIcon('timeline-view-icon', Codicon.history, localize('timelineViewIcon', 'View icon of the timeline view.')); const timelineOpenIcon = registerIcon('timeline-open', Codicon.history, localize('timelineOpenIcon', 'Icon for the open timeline action.')); export class TimelinePaneDescriptor implements IViewDescriptor { readonly id = TimelinePaneId; readonly name = TimelinePane.TITLE; readonly containerIcon = timelineViewIcon; readonly ctorDescriptor = new SyncDescriptor(TimelinePane); readonly order = 2; readonly weight = 30; readonly collapsed = true; readonly canToggleVisibility = true; readonly hideByDefault = false; readonly canMoveView = true; readonly when = TimelineHasProviderContext; focusCommand = { id: 'timeline.focus' }; } // Configuration const configurationRegistry = Registry.as<IConfigurationRegistry>(ConfigurationExtensions.Configuration); configurationRegistry.registerConfiguration({ id: 'timeline', order: 1001, title: localize('timelineConfigurationTitle', "Timeline"), type: 'object', properties: { 'timeline.pageSize': { type: ['number', 'null'], default: null, markdownDescription: localize('timeline.pageSize', "The number of items to show in the Timeline view by default and when loading more items. Setting to `null` (the default) will automatically choose a page size based on the visible area of the Timeline view."), }, 'timeline.pageOnScroll': { type: 'boolean', default: false, description: localize('timeline.pageOnScroll', "Experimental. Controls whether the Timeline view will load the next page of items when you scroll to the end of the list."), }, } }); Registry.as<IViewsRegistry>(ViewExtensions.ViewsRegistry).registerViews([new TimelinePaneDescriptor()], VIEW_CONTAINER); namespace OpenTimelineAction { export const ID = 'files.openTimeline'; export const LABEL = localize('files.openTimeline', "Open Timeline"); export function handler(): ICommandHandler { return (accessor, arg) => { const service = accessor.get(ITimelineService); return service.setUri(arg); }; } } CommandsRegistry.registerCommand(OpenTimelineAction.ID, OpenTimelineAction.handler()); MenuRegistry.appendMenuItem(MenuId.ExplorerContext, ({ group: '4_timeline', order: 1, command: { id: OpenTimelineAction.ID, title: OpenTimelineAction.LABEL, icon: timelineOpenIcon }, when: ContextKeyExpr.and(ExplorerFolderContext.toNegated(), ResourceContextKey.HasResource, TimelineHasProviderContext) })); const timelineFilter = registerIcon('timeline-filter', Codicon.filter, localize('timelineFilter', 'Icon for the filter timeline action.')); MenuRegistry.appendMenuItem(MenuId.TimelineTitle, <ISubmenuItem>{ submenu: MenuId.TimelineFilterSubMenu, title: localize('filterTimeline', "Filter Timeline"), group: 'navigation', order: 100, icon: timelineFilter }); registerSingleton(ITimelineService, TimelineService, InstantiationType.Delayed);
src/vs/workbench/contrib/timeline/browser/timeline.contribution.ts
0
https://github.com/microsoft/vscode/commit/324d1a25760c6abeb4a0492c0c5a22795b695bf4
[ 0.00017527799354866147, 0.00017176015535369515, 0.000165197707246989, 0.00017264035705011338, 0.0000034041495382552966 ]
{ "id": 8, "code_window": [ "\treadonly message: string | IInteractiveSessionReplyFollowup;\n", "\treadonly response: IInteractiveResponseModel | undefined;\n", "}\n", "\n", "export interface IInteractiveResponseErrorDetails {\n", "\tmessage: string;\n", "\tresponseIsIncomplete?: boolean;\n", "}\n", "\n", "export interface IInteractiveResponseModel {\n", "\treadonly onDidChange: Event<void>;\n", "\treadonly id: string;\n", "\treadonly providerId: string;\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/workbench/contrib/interactiveSession/common/interactiveSessionModel.ts", "type": "replace", "edit_start_line_idx": 20 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Emitter } from 'vs/base/common/event'; import { Disposable } from 'vs/base/common/lifecycle'; import { ICellOutput, IOutputDto, IOutputItemDto } from 'vs/workbench/contrib/notebook/common/notebookCommon'; export class NotebookCellOutputTextModel extends Disposable implements ICellOutput { private _onDidChangeData = this._register(new Emitter<void>()); onDidChangeData = this._onDidChangeData.event; get outputs() { return this._rawOutput.outputs || []; } get metadata(): Record<string, any> | undefined { return this._rawOutput.metadata; } get outputId(): string { return this._rawOutput.outputId; } constructor( private _rawOutput: IOutputDto ) { super(); } replaceData(rawData: IOutputDto) { this._rawOutput = rawData; this._onDidChangeData.fire(); } appendData(items: IOutputItemDto[]) { this._rawOutput.outputs.push(...items); this._onDidChangeData.fire(); } toJSON(): IOutputDto { return { // data: this._data, metadata: this._rawOutput.metadata, outputs: this._rawOutput.outputs, outputId: this._rawOutput.outputId }; } }
src/vs/workbench/contrib/notebook/common/model/notebookCellOutputTextModel.ts
0
https://github.com/microsoft/vscode/commit/324d1a25760c6abeb4a0492c0c5a22795b695bf4
[ 0.0004422997881192714, 0.00022160587832331657, 0.000167112797498703, 0.00017376497271470726, 0.0000993865542113781 ]
{ "id": 9, "code_window": [ "import { Event } from 'vs/base/common/event';\n", "import { IDisposable } from 'vs/base/common/lifecycle';\n", "import { URI } from 'vs/base/common/uri';\n", "import { CompletionItemKind, ProviderResult } from 'vs/editor/common/languages';\n", "import { createDecorator } from 'vs/platform/instantiation/common/instantiation';\n", "import { IInteractiveResponseErrorDetails, InteractiveSessionModel } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionModel';\n", "\n", "export interface IInteractiveSession {\n", "\tid: number;\n", "\trequesterUsername: string;\n", "\trequesterAvatarIconUri?: URI;\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { InteractiveSessionModel } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionModel';\n" ], "file_path": "src/vs/workbench/contrib/interactiveSession/common/interactiveSessionService.ts", "type": "replace", "edit_start_line_idx": 11 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as dom from 'vs/base/browser/dom'; import { renderIcon } from 'vs/base/browser/ui/iconLabel/iconLabels'; import { IListVirtualDelegate } from 'vs/base/browser/ui/list/list'; import { IListAccessibilityProvider } from 'vs/base/browser/ui/list/listWidget'; import { ITreeNode, ITreeRenderer } from 'vs/base/browser/ui/tree/tree'; import { IntervalTimer } from 'vs/base/common/async'; import { Codicon } from 'vs/base/common/codicons'; import { Emitter, Event } from 'vs/base/common/event'; import { FuzzyScore } from 'vs/base/common/filters'; import { IMarkdownString, MarkdownString } from 'vs/base/common/htmlContent'; import { Disposable, DisposableStore, IDisposable } from 'vs/base/common/lifecycle'; import { ResourceMap } from 'vs/base/common/map'; import { FileAccess } from 'vs/base/common/network'; import { ThemeIcon } from 'vs/base/common/themables'; import { EditorExtensionsRegistry } from 'vs/editor/browser/editorExtensions'; import { CodeEditorWidget } from 'vs/editor/browser/widget/codeEditorWidget'; import { EDITOR_FONT_DEFAULTS, IEditorOptions } from 'vs/editor/common/config/editorOptions'; import { Range } from 'vs/editor/common/core/range'; import { ILanguageService } from 'vs/editor/common/languages/language'; import { ITextModel } from 'vs/editor/common/model'; import { IModelService } from 'vs/editor/common/services/model'; import { BracketMatchingController } from 'vs/editor/contrib/bracketMatching/browser/bracketMatching'; import { ContextMenuController } from 'vs/editor/contrib/contextmenu/browser/contextmenu'; import { IMarkdownRenderResult, MarkdownRenderer } from 'vs/editor/contrib/markdownRenderer/browser/markdownRenderer'; import { ViewportSemanticTokensContribution } from 'vs/editor/contrib/semanticTokens/browser/viewportSemanticTokens'; import { SmartSelectController } from 'vs/editor/contrib/smartSelect/browser/smartSelect'; import { WordHighlighterContribution } from 'vs/editor/contrib/wordHighlighter/browser/wordHighlighter'; import { localize } from 'vs/nls'; import { MenuWorkbenchToolBar } from 'vs/platform/actions/browser/toolbar'; import { MenuId } from 'vs/platform/actions/common/actions'; import { ICommandService } from 'vs/platform/commands/common/commands'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection'; import { ILogService } from 'vs/platform/log/common/log'; import { defaultButtonStyles } from 'vs/platform/theme/browser/defaultStyles'; import { MenuPreventer } from 'vs/workbench/contrib/codeEditor/browser/menuPreventer'; import { SelectionClipboardContributionID } from 'vs/workbench/contrib/codeEditor/browser/selectionClipboard'; import { getSimpleEditorOptions } from 'vs/workbench/contrib/codeEditor/browser/simpleEditorOptions'; import { IInteractiveSessionCodeBlockActionContext } from 'vs/workbench/contrib/interactiveSession/browser/actions/interactiveSessionCodeblockActions'; import { InteractiveSessionFollowups } from 'vs/workbench/contrib/interactiveSession/browser/interactiveSessionFollowups'; import { InteractiveSessionEditorOptions } from 'vs/workbench/contrib/interactiveSession/browser/interactiveSessionOptions'; import { CONTEXT_RESPONSE_HAS_PROVIDER_ID, CONTEXT_RESPONSE_VOTE } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionContextKeys'; import { IInteractiveSessionReplyFollowup, IInteractiveSessionService, IInteractiveSlashCommand, InteractiveSessionVoteDirection } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionService'; import { IInteractiveRequestViewModel, IInteractiveResponseViewModel, IInteractiveWelcomeMessageViewModel, isRequestVM, isResponseVM, isWelcomeVM } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionViewModel'; import { getNWords } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionWordCounter'; const $ = dom.$; export type InteractiveTreeItem = IInteractiveRequestViewModel | IInteractiveResponseViewModel | IInteractiveWelcomeMessageViewModel; interface IInteractiveListItemTemplate { rowContainer: HTMLElement; titleToolbar: MenuWorkbenchToolBar; avatar: HTMLElement; username: HTMLElement; value: HTMLElement; contextKeyService: IContextKeyService; templateDisposables: IDisposable; elementDisposables: DisposableStore; } interface IItemHeightChangeParams { element: InteractiveTreeItem; height: number; } const forceVerboseLayoutTracing = false; export interface IInteractiveSessionRendererDelegate { getListLength(): number; getSlashCommands(): IInteractiveSlashCommand[]; } export class InteractiveListItemRenderer extends Disposable implements ITreeRenderer<InteractiveTreeItem, FuzzyScore, IInteractiveListItemTemplate> { static readonly cursorCharacter = '\u258c'; static readonly ID = 'item'; private readonly renderer: MarkdownRenderer; protected readonly _onDidClickFollowup = this._register(new Emitter<IInteractiveSessionReplyFollowup>()); readonly onDidClickFollowup: Event<IInteractiveSessionReplyFollowup> = this._onDidClickFollowup.event; protected readonly _onDidChangeItemHeight = this._register(new Emitter<IItemHeightChangeParams>()); readonly onDidChangeItemHeight: Event<IItemHeightChangeParams> = this._onDidChangeItemHeight.event; private readonly _editorPool: EditorPool; private _currentLayoutWidth: number = 0; constructor( private readonly editorOptions: InteractiveSessionEditorOptions, private readonly delegate: IInteractiveSessionRendererDelegate, @IInstantiationService private readonly instantiationService: IInstantiationService, @IConfigurationService private readonly configService: IConfigurationService, @ILogService private readonly logService: ILogService, @ICommandService private readonly commandService: ICommandService, @IContextKeyService private readonly contextKeyService: IContextKeyService, @IInteractiveSessionService private readonly interactiveSessionService: IInteractiveSessionService, ) { super(); this.renderer = this.instantiationService.createInstance(MarkdownRenderer, {}); this._editorPool = this._register(this.instantiationService.createInstance(EditorPool, this.editorOptions)); } get templateId(): string { return InteractiveListItemRenderer.ID; } private traceLayout(method: string, message: string) { if (forceVerboseLayoutTracing) { this.logService.info(`InteractiveListItemRenderer#${method}: ${message}`); } else { this.logService.trace(`InteractiveListItemRenderer#${method}: ${message}`); } } private shouldRenderProgressively(element: IInteractiveResponseViewModel): boolean { return !this.configService.getValue('interactive.experimental.disableProgressiveRendering') && element.progressiveResponseRenderingEnabled; } private getProgressiveRenderRate(element: IInteractiveResponseViewModel): number { const configuredRate = this.configService.getValue('interactive.experimental.progressiveRenderingRate'); if (typeof configuredRate === 'number') { return configuredRate; } if (element.isComplete) { return 60; } if (element.contentUpdateTimings && element.contentUpdateTimings.impliedWordLoadRate) { // This doesn't account for dead time after the last update. When the previous update is the final one and the model is only waiting for followupQuestions, that's good. // When there was one quick update and then you are waiting longer for the next one, that's not good since the rate should be decreasing. // If it's an issue, we can change this to be based on the total time from now to the beginning. const rateBoost = 1.5; return element.contentUpdateTimings.impliedWordLoadRate * rateBoost; } return 8; } layout(width: number): void { this._currentLayoutWidth = width - 40; // TODO Padding this._editorPool.inUse.forEach(editor => { editor.layout(this._currentLayoutWidth); }); } renderTemplate(container: HTMLElement): IInteractiveListItemTemplate { const templateDisposables = new DisposableStore(); const rowContainer = dom.append(container, $('.interactive-item-container')); const header = dom.append(rowContainer, $('.header')); const user = dom.append(header, $('.user')); const avatar = dom.append(user, $('.avatar')); const username = dom.append(user, $('h3.username')); const value = dom.append(rowContainer, $('.value')); const elementDisposables = new DisposableStore(); const contextKeyService = templateDisposables.add(this.contextKeyService.createScoped(rowContainer)); const scopedInstantiationService = this.instantiationService.createChild(new ServiceCollection([IContextKeyService, contextKeyService])); const titleToolbar = templateDisposables.add(scopedInstantiationService.createInstance(MenuWorkbenchToolBar, header, MenuId.InteractiveSessionTitle, { menuOptions: { shouldForwardArgs: true } })); const template: IInteractiveListItemTemplate = { avatar, username, value, rowContainer, elementDisposables, titleToolbar, templateDisposables, contextKeyService }; return template; } renderElement(node: ITreeNode<InteractiveTreeItem, FuzzyScore>, index: number, templateData: IInteractiveListItemTemplate): void { const { element } = node; const kind = isRequestVM(element) ? 'request' : isResponseVM(element) ? 'response' : 'welcome'; this.traceLayout('renderElement', `${kind}, index=${index}`); CONTEXT_RESPONSE_HAS_PROVIDER_ID.bindTo(templateData.contextKeyService).set(isResponseVM(element) && !!element.providerResponseId && !element.isPlaceholder); if (isResponseVM(element)) { CONTEXT_RESPONSE_VOTE.bindTo(templateData.contextKeyService).set(element.vote === InteractiveSessionVoteDirection.Up ? 'up' : element.vote === InteractiveSessionVoteDirection.Down ? 'down' : ''); } else { CONTEXT_RESPONSE_VOTE.bindTo(templateData.contextKeyService).set(''); } templateData.titleToolbar.context = element; templateData.rowContainer.classList.toggle('interactive-request', isRequestVM(element)); templateData.rowContainer.classList.toggle('interactive-response', isResponseVM(element)); templateData.rowContainer.classList.toggle('interactive-welcome', isWelcomeVM(element)); templateData.username.textContent = element.username; if (element.avatarIconUri) { const avatarIcon = dom.$<HTMLImageElement>('img.icon'); avatarIcon.src = FileAccess.uriToBrowserUri(element.avatarIconUri).toString(true); templateData.avatar.replaceChildren(avatarIcon); } else { const defaultIcon = isRequestVM(element) ? Codicon.account : Codicon.hubot; const avatarIcon = dom.$(ThemeIcon.asCSSSelector(defaultIcon)); templateData.avatar.replaceChildren(avatarIcon); } // Do a progressive render if // - This the last response in the list // - And the response is not complete // - Or, we previously started a progressive rendering of this element (if the element is complete, we will finish progressive rendering with a very fast rate) // - And, the feature is not disabled in configuration if (isResponseVM(element) && index === this.delegate.getListLength() - 1 && (!element.isComplete || element.renderData) && this.shouldRenderProgressively(element)) { this.traceLayout('renderElement', `start progressive render ${kind}, index=${index}`); const progressiveRenderingDisposables = templateData.elementDisposables.add(new DisposableStore()); const timer = templateData.elementDisposables.add(new IntervalTimer()); const runProgressiveRender = (initial?: boolean) => { try { if (this.doNextProgressiveRender(element, index, templateData, !!initial, progressiveRenderingDisposables)) { timer.cancel(); } } catch (err) { // Kill the timer if anything went wrong, avoid getting stuck in a nasty rendering loop. timer.cancel(); throw err; } }; runProgressiveRender(true); timer.cancelAndSet(runProgressiveRender, 50); } else if (isResponseVM(element)) { this.basicRenderElement(element.response.value, element, index, templateData, element.isCanceled); } else if (isRequestVM(element)) { this.basicRenderElement(element.messageText, element, index, templateData); } else { this.renderWelcomeMessage(element, templateData); } } private basicRenderElement(markdownValue: string, element: InteractiveTreeItem, index: number, templateData: IInteractiveListItemTemplate, fillInIncompleteTokens = false) { const result = this.renderMarkdown(new MarkdownString(markdownValue), element, templateData.elementDisposables, templateData, fillInIncompleteTokens); dom.clearNode(templateData.value); templateData.value.appendChild(result.element); templateData.elementDisposables.add(result); if (isResponseVM(element) && element.errorDetails?.message) { const errorDetails = dom.append(templateData.value, $('.interactive-response-error-details', undefined, renderIcon(Codicon.error))); errorDetails.appendChild($('span', undefined, element.errorDetails.message)); } if (isResponseVM(element) && element.commandFollowups?.length) { const followupsContainer = dom.append(templateData.value, $('.interactive-response-followups')); templateData.elementDisposables.add(new InteractiveSessionFollowups( followupsContainer, element.commandFollowups, defaultButtonStyles, followup => { this.interactiveSessionService.notifyUserAction({ providerId: element.providerId, action: { kind: 'command', command: followup } }); return this.commandService.executeCommand(followup.commandId, ...(followup.args ?? [])); })); } } private renderWelcomeMessage(element: IInteractiveWelcomeMessageViewModel, templateData: IInteractiveListItemTemplate) { dom.clearNode(templateData.value); const slashCommands = this.delegate.getSlashCommands(); for (const item of element.content) { if (Array.isArray(item)) { templateData.elementDisposables.add(new InteractiveSessionFollowups( templateData.value, item, undefined, followup => this._onDidClickFollowup.fire(followup))); } else { const result = this.renderMarkdown(item as IMarkdownString, element, templateData.elementDisposables, templateData); for (const codeElement of result.element.querySelectorAll('code')) { if (codeElement.textContent && slashCommands.find(command => codeElement.textContent === `/${command.command}`)) { codeElement.classList.add('interactive-slash-command'); } } templateData.value.appendChild(result.element); templateData.elementDisposables.add(result); } } } private doNextProgressiveRender(element: IInteractiveResponseViewModel, index: number, templateData: IInteractiveListItemTemplate, isInRenderElement: boolean, disposables: DisposableStore): boolean { disposables.clear(); let isFullyRendered = false; if (element.isCanceled) { this.traceLayout('runProgressiveRender', `canceled, index=${index}`); element.renderData = undefined; this.basicRenderElement(element.response.value, element, index, templateData, true); isFullyRendered = true; } else { // TODO- this method has the side effect of updating element.renderData const toRender = this.getProgressiveMarkdownToRender(element); isFullyRendered = !!element.renderData?.isFullyRendered; if (isFullyRendered) { // We've reached the end of the available content, so do a normal render this.traceLayout('runProgressiveRender', `end progressive render, index=${index}`); if (element.isComplete) { this.traceLayout('runProgressiveRender', `and disposing renderData, response is complete, index=${index}`); element.renderData = undefined; } else { this.traceLayout('runProgressiveRender', `Rendered all available words, but model is not complete.`); } disposables.clear(); this.basicRenderElement(element.response.value, element, index, templateData, !element.isComplete); } else if (toRender) { // Doing the progressive render const plusCursor = toRender.match(/```.*$/) ? toRender + `\n${InteractiveListItemRenderer.cursorCharacter}` : toRender + ` ${InteractiveListItemRenderer.cursorCharacter}`; const result = this.renderMarkdown(new MarkdownString(plusCursor), element, disposables, templateData, true); dom.clearNode(templateData.value); templateData.value.appendChild(result.element); disposables.add(result); } else { // Nothing new to render, not done, keep waiting return false; } } // Some render happened - update the height const height = templateData.rowContainer.offsetHeight; element.currentRenderedHeight = height; if (!isInRenderElement) { this._onDidChangeItemHeight.fire({ element, height: templateData.rowContainer.offsetHeight }); } return !!isFullyRendered; } private renderMarkdown(markdown: IMarkdownString, element: InteractiveTreeItem, disposables: DisposableStore, templateData: IInteractiveListItemTemplate, fillInIncompleteTokens = false): IMarkdownRenderResult { const disposablesList: IDisposable[] = []; let codeBlockIndex = 0; // TODO if the slash commands stay completely dynamic, this isn't quite right const slashCommands = this.delegate.getSlashCommands(); const usedSlashCommand = slashCommands.find(s => markdown.value.startsWith(`/${s.command} `)); const toRender = usedSlashCommand ? markdown.value.slice(usedSlashCommand.command.length + 2) : markdown.value; markdown = new MarkdownString(toRender); const result = this.renderer.render(markdown, { fillInIncompleteTokens, codeBlockRendererSync: (languageId, text) => { const ref = this.renderCodeBlock({ languageId, text, codeBlockIndex: codeBlockIndex++, element, parentContextKeyService: templateData.contextKeyService }, disposables); // Attach this after updating text/layout of the editor, so it should only be fired when the size updates later (horizontal scrollbar, wrapping) // not during a renderElement OR a progressive render (when we will be firing this event anyway at the end of the render) disposables.add(ref.object.onDidChangeContentHeight(() => { ref.object.layout(this._currentLayoutWidth); this._onDidChangeItemHeight.fire({ element, height: templateData.rowContainer.offsetHeight }); })); disposablesList.push(ref); return ref.object.element; } }); if (usedSlashCommand) { const slashCommandElement = $('span.interactive-slash-command', { title: usedSlashCommand.detail }, `/${usedSlashCommand.command} `); if (result.element.firstChild?.nodeName.toLowerCase() === 'p') { result.element.firstChild.insertBefore(slashCommandElement, result.element.firstChild.firstChild); } else { result.element.insertBefore($('p', undefined, slashCommandElement), result.element.firstChild); } } disposablesList.reverse().forEach(d => disposables.add(d)); return result; } private renderCodeBlock(data: IInteractiveResultCodeBlockData, disposables: DisposableStore): IDisposableReference<IInteractiveResultCodeBlockPart> { const ref = this._editorPool.get(); const editorInfo = ref.object; editorInfo.render(data, this._currentLayoutWidth); return ref; } private getProgressiveMarkdownToRender(element: IInteractiveResponseViewModel): string | undefined { const renderData = element.renderData ?? { renderedWordCount: 0, lastRenderTime: 0 }; const rate = this.getProgressiveRenderRate(element); const numWordsToRender = renderData.lastRenderTime === 0 ? 1 : renderData.renderedWordCount + // Additional words to render beyond what's already rendered Math.floor((Date.now() - renderData.lastRenderTime) / 1000 * rate); if (numWordsToRender === renderData.renderedWordCount) { return undefined; } const result = getNWords(element.response.value, numWordsToRender); element.renderData = { renderedWordCount: result.actualWordCount, lastRenderTime: Date.now(), isFullyRendered: result.isFullString }; return result.value; } disposeElement(node: ITreeNode<InteractiveTreeItem, FuzzyScore>, index: number, templateData: IInteractiveListItemTemplate): void { templateData.elementDisposables.clear(); } disposeTemplate(templateData: IInteractiveListItemTemplate): void { templateData.templateDisposables.dispose(); } } export class InteractiveSessionListDelegate implements IListVirtualDelegate<InteractiveTreeItem> { constructor( @ILogService private readonly logService: ILogService ) { } private _traceLayout(method: string, message: string) { if (forceVerboseLayoutTracing) { this.logService.info(`InteractiveSessionListDelegate#${method}: ${message}`); } else { this.logService.trace(`InteractiveSessionListDelegate#${method}: ${message}`); } } getHeight(element: InteractiveTreeItem): number { const kind = isRequestVM(element) ? 'request' : 'response'; const height = ('currentRenderedHeight' in element ? element.currentRenderedHeight : undefined) ?? 200; this._traceLayout('getHeight', `${kind}, height=${height}`); return height; } getTemplateId(element: InteractiveTreeItem): string { return InteractiveListItemRenderer.ID; } hasDynamicHeight(element: InteractiveTreeItem): boolean { return true; } } export class InteractiveSessionAccessibilityProvider implements IListAccessibilityProvider<InteractiveTreeItem> { getWidgetAriaLabel(): string { return localize('interactiveSession', "Interactive Session"); } getAriaLabel(element: InteractiveTreeItem): string { if (isRequestVM(element)) { return localize('interactiveRequest', "Request: {0}", element.messageText); } if (isResponseVM(element)) { return localize('interactiveResponse', "Response: {0}", element.response.value); } return ''; } } interface IInteractiveResultCodeBlockData { text: string; languageId: string; codeBlockIndex: number; element: InteractiveTreeItem; parentContextKeyService: IContextKeyService; } interface IInteractiveResultCodeBlockPart { readonly onDidChangeContentHeight: Event<number>; readonly element: HTMLElement; readonly textModel: ITextModel; layout(width: number): void; render(data: IInteractiveResultCodeBlockData, width: number): void; dispose(): void; } export interface IInteractiveResultCodeBlockInfo { providerId: string; responseId: string; codeBlockIndex: number; } export const codeBlockInfosByModelUri = new ResourceMap<IInteractiveResultCodeBlockInfo>(); class CodeBlockPart extends Disposable implements IInteractiveResultCodeBlockPart { private readonly _onDidChangeContentHeight = this._register(new Emitter<number>()); public readonly onDidChangeContentHeight = this._onDidChangeContentHeight.event; private readonly editor: CodeEditorWidget; private readonly toolbar: MenuWorkbenchToolBar; private readonly contextKeyService: IContextKeyService; public readonly textModel: ITextModel; public readonly element: HTMLElement; constructor( private readonly options: InteractiveSessionEditorOptions, @IInstantiationService instantiationService: IInstantiationService, @IContextKeyService contextKeyService: IContextKeyService, @ILanguageService private readonly languageService: ILanguageService, @IModelService private readonly modelService: IModelService, ) { super(); this.element = $('.interactive-result-editor-wrapper'); this.contextKeyService = this._register(contextKeyService.createScoped(this.element)); const scopedInstantiationService = instantiationService.createChild(new ServiceCollection([IContextKeyService, this.contextKeyService])); this.toolbar = this._register(scopedInstantiationService.createInstance(MenuWorkbenchToolBar, this.element, MenuId.InteractiveSessionCodeBlock, { menuOptions: { shouldForwardArgs: true } })); const editorElement = dom.append(this.element, $('.interactive-result-editor')); this.editor = this._register(scopedInstantiationService.createInstance(CodeEditorWidget, editorElement, { ...getSimpleEditorOptions(), readOnly: true, lineNumbers: 'off', selectOnLineNumbers: true, scrollBeyondLastLine: false, lineDecorationsWidth: 8, dragAndDrop: false, padding: { top: 2, bottom: 2 }, mouseWheelZoom: false, scrollbar: { alwaysConsumeMouseWheel: false }, ...this.getEditorOptionsFromConfig() }, { isSimpleWidget: true, contributions: EditorExtensionsRegistry.getSomeEditorContributions([ MenuPreventer.ID, SelectionClipboardContributionID, ContextMenuController.ID, WordHighlighterContribution.ID, ViewportSemanticTokensContribution.ID, BracketMatchingController.ID, SmartSelectController.ID, ]) })); this._register(this.options.onDidChange(() => { this.editor.updateOptions(this.getEditorOptionsFromConfig()); })); this._register(this.editor.onDidContentSizeChange(e => { if (e.contentHeightChanged) { this._onDidChangeContentHeight.fire(e.contentHeight); } })); this._register(this.editor.onDidBlurEditorWidget(() => { WordHighlighterContribution.get(this.editor)?.stopHighlighting(); })); this._register(this.editor.onDidFocusEditorWidget(() => { WordHighlighterContribution.get(this.editor)?.restoreViewState(true); })); const vscodeLanguageId = this.languageService.getLanguageIdByLanguageName('javascript'); this.textModel = this._register(this.modelService.createModel('', this.languageService.createById(vscodeLanguageId), undefined)); this.editor.setModel(this.textModel); } private getEditorOptionsFromConfig(): IEditorOptions { return { wordWrap: this.options.configuration.resultEditor.wordWrap, bracketPairColorization: this.options.configuration.resultEditor.bracketPairColorization, fontFamily: this.options.configuration.resultEditor.fontFamily === 'default' ? EDITOR_FONT_DEFAULTS.fontFamily : this.options.configuration.resultEditor.fontFamily, fontSize: this.options.configuration.resultEditor.fontSize, fontWeight: this.options.configuration.resultEditor.fontWeight, lineHeight: this.options.configuration.resultEditor.lineHeight, }; } layout(width: number): void { const realContentHeight = this.editor.getContentHeight(); const editorBorder = 2; this.editor.layout({ width: width - editorBorder, height: realContentHeight }); } render(data: IInteractiveResultCodeBlockData, width: number): void { this.contextKeyService.updateParent(data.parentContextKeyService); if (this.options.configuration.resultEditor.wordWrap === 'on') { // Intialize the editor with the new proper width so that getContentHeight // will be computed correctly in the next call to layout() this.layout(width); } this.setText(data.text); this.setLanguage(data.languageId); this.layout(width); if (isResponseVM(data.element) && data.element.providerResponseId) { // For telemetry reporting codeBlockInfosByModelUri.set(this.textModel.uri, { providerId: data.element.providerId, responseId: data.element.providerResponseId, codeBlockIndex: data.codeBlockIndex }); } else { codeBlockInfosByModelUri.delete(this.textModel.uri); } this.toolbar.context = <IInteractiveSessionCodeBlockActionContext>{ code: data.text, codeBlockIndex: data.codeBlockIndex, element: data.element }; } private setText(newText: string): void { let currentText = this.textModel.getLinesContent().join('\n'); if (newText === currentText) { return; } let removedChars = 0; if (currentText.endsWith(` ${InteractiveListItemRenderer.cursorCharacter}`)) { removedChars = 2; } else if (currentText.endsWith(InteractiveListItemRenderer.cursorCharacter)) { removedChars = 1; } if (removedChars > 0) { currentText = currentText.slice(0, currentText.length - removedChars); } if (newText.startsWith(currentText)) { const text = newText.slice(currentText.length); const lastLine = this.textModel.getLineCount(); const lastCol = this.textModel.getLineMaxColumn(lastLine); const insertAtCol = lastCol - removedChars; this.textModel.applyEdits([{ range: new Range(lastLine, insertAtCol, lastLine, lastCol), text }]); } else { // console.log(`Failed to optimize setText`); this.textModel.setValue(newText); } } private setLanguage(languageId: string): void { const vscodeLanguageId = this.languageService.getLanguageIdByLanguageName(languageId); if (vscodeLanguageId) { this.textModel.setLanguage(vscodeLanguageId); } } } interface IDisposableReference<T> extends IDisposable { object: T; } class EditorPool extends Disposable { private _pool: ResourcePool<IInteractiveResultCodeBlockPart>; public get inUse(): ReadonlySet<IInteractiveResultCodeBlockPart> { return this._pool.inUse; } constructor( private readonly options: InteractiveSessionEditorOptions, @IInstantiationService private readonly instantiationService: IInstantiationService, ) { super(); this._pool = this._register(new ResourcePool(() => this.editorFactory())); // TODO listen to changes on options } private editorFactory(): IInteractiveResultCodeBlockPart { return this.instantiationService.createInstance(CodeBlockPart, this.options); } get(): IDisposableReference<IInteractiveResultCodeBlockPart> { const object = this._pool.get(); return { object, dispose: () => this._pool.release(object) }; } } // TODO does something in lifecycle.ts cover this? class ResourcePool<T extends IDisposable> extends Disposable { private readonly pool: T[] = []; private _inUse = new Set<T>; public get inUse(): ReadonlySet<T> { return this._inUse; } constructor( private readonly _itemFactory: () => T, ) { super(); } get(): T { if (this.pool.length > 0) { const item = this.pool.pop()!; this._inUse.add(item); return item; } const item = this._register(this._itemFactory()); this._inUse.add(item); return item; } release(item: T): void { this._inUse.delete(item); this.pool.push(item); } }
src/vs/workbench/contrib/interactiveSession/browser/interactiveSessionListRenderer.ts
1
https://github.com/microsoft/vscode/commit/324d1a25760c6abeb4a0492c0c5a22795b695bf4
[ 0.9972844123840332, 0.043095093220472336, 0.0001638010871829465, 0.00017381938232574612, 0.1926702857017517 ]
{ "id": 9, "code_window": [ "import { Event } from 'vs/base/common/event';\n", "import { IDisposable } from 'vs/base/common/lifecycle';\n", "import { URI } from 'vs/base/common/uri';\n", "import { CompletionItemKind, ProviderResult } from 'vs/editor/common/languages';\n", "import { createDecorator } from 'vs/platform/instantiation/common/instantiation';\n", "import { IInteractiveResponseErrorDetails, InteractiveSessionModel } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionModel';\n", "\n", "export interface IInteractiveSession {\n", "\tid: number;\n", "\trequesterUsername: string;\n", "\trequesterAvatarIconUri?: URI;\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { InteractiveSessionModel } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionModel';\n" ], "file_path": "src/vs/workbench/contrib/interactiveSession/common/interactiveSessionService.ts", "type": "replace", "edit_start_line_idx": 11 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { DisposableStore, IDisposable, toDisposable } from 'vs/base/common/lifecycle'; import { autorun } from 'vs/base/common/observableImpl/autorun'; import { IObservable, BaseObservable, transaction, IReader, ITransaction, ConvenientObservable, IObserver, observableValue, getFunctionName } from 'vs/base/common/observableImpl/base'; import { derived } from 'vs/base/common/observableImpl/derived'; import { Event } from 'vs/base/common/event'; import { getLogger } from 'vs/base/common/observableImpl/logging'; export function constObservable<T>(value: T): IObservable<T> { return new ConstObservable(value); } class ConstObservable<T> extends ConvenientObservable<T, void> { constructor(private readonly value: T) { super(); } public override get debugName(): string { return this.toString(); } public get(): T { return this.value; } public addObserver(observer: IObserver): void { // NO OP } public removeObserver(observer: IObserver): void { // NO OP } override toString(): string { return `Const: ${this.value}`; } } export function observableFromPromise<T>(promise: Promise<T>): IObservable<{ value?: T }> { const observable = observableValue<{ value?: T }>('promiseValue', {}); promise.then((value) => { observable.set({ value }, undefined); }); return observable; } export function waitForState<T, TState extends T>(observable: IObservable<T>, predicate: (state: T) => state is TState): Promise<TState>; export function waitForState<T>(observable: IObservable<T>, predicate: (state: T) => boolean): Promise<T>; export function waitForState<T>(observable: IObservable<T>, predicate: (state: T) => boolean): Promise<T> { return new Promise(resolve => { let didRun = false; let shouldDispose = false; const d = autorun('waitForState', reader => { const currentState = observable.read(reader); if (predicate(currentState)) { if (!didRun) { shouldDispose = true; } else { d.dispose(); } resolve(currentState); } }); didRun = true; if (shouldDispose) { d.dispose(); } }); } export function observableFromEvent<T, TArgs = unknown>( event: Event<TArgs>, getValue: (args: TArgs | undefined) => T ): IObservable<T> { return new FromEventObservable(event, getValue); } export class FromEventObservable<TArgs, T> extends BaseObservable<T> { private value: T | undefined; private hasValue = false; private subscription: IDisposable | undefined; constructor( private readonly event: Event<TArgs>, private readonly getValue: (args: TArgs | undefined) => T ) { super(); } private getDebugName(): string | undefined { return getFunctionName(this.getValue); } public get debugName(): string { const name = this.getDebugName(); return 'From Event' + (name ? `: ${name}` : ''); } protected override onFirstObserverAdded(): void { this.subscription = this.event(this.handleEvent); } private readonly handleEvent = (args: TArgs | undefined) => { const newValue = this.getValue(args); const didChange = !this.hasValue || this.value !== newValue; getLogger()?.handleFromEventObservableTriggered(this, { oldValue: this.value, newValue, change: undefined, didChange }); if (didChange) { this.value = newValue; if (this.hasValue) { transaction( (tx) => { for (const o of this.observers) { tx.updateObserver(o, this); o.handleChange(this, undefined); } }, () => { const name = this.getDebugName(); return 'Event fired' + (name ? `: ${name}` : ''); } ); } this.hasValue = true; } }; protected override onLastObserverRemoved(): void { this.subscription!.dispose(); this.subscription = undefined; this.hasValue = false; this.value = undefined; } public get(): T { if (this.subscription) { if (!this.hasValue) { this.handleEvent(undefined); } return this.value!; } else { // no cache, as there are no subscribers to keep it updated return this.getValue(undefined); } } } export namespace observableFromEvent { export const Observer = FromEventObservable; } export function observableSignalFromEvent( debugName: string, event: Event<any> ): IObservable<void> { return new FromEventObservableSignal(debugName, event); } class FromEventObservableSignal extends BaseObservable<void> { private subscription: IDisposable | undefined; constructor( public readonly debugName: string, private readonly event: Event<any>, ) { super(); } protected override onFirstObserverAdded(): void { this.subscription = this.event(this.handleEvent); } private readonly handleEvent = () => { transaction( (tx) => { for (const o of this.observers) { tx.updateObserver(o, this); o.handleChange(this, undefined); } }, () => this.debugName ); }; protected override onLastObserverRemoved(): void { this.subscription!.dispose(); this.subscription = undefined; } public override get(): void { // NO OP } } export function observableSignal( debugName: string ): IObservableSignal { return new ObservableSignal(debugName); } export interface IObservableSignal extends IObservable<void> { trigger(tx: ITransaction | undefined): void; } class ObservableSignal extends BaseObservable<void> implements IObservableSignal { constructor( public readonly debugName: string ) { super(); } public trigger(tx: ITransaction | undefined): void { if (!tx) { transaction(tx => { this.trigger(tx); }, () => `Trigger signal ${this.debugName}`); return; } for (const o of this.observers) { tx.updateObserver(o, this); o.handleChange(this, undefined); } } public override get(): void { // NO OP } } export function debouncedObservable<T>(observable: IObservable<T>, debounceMs: number, disposableStore: DisposableStore): IObservable<T | undefined> { const debouncedObservable = observableValue<T | undefined>('debounced', undefined); let timeout: any = undefined; disposableStore.add(autorun('debounce', reader => { const value = observable.read(reader); if (timeout) { clearTimeout(timeout); } timeout = setTimeout(() => { transaction(tx => { debouncedObservable.set(value, tx); }); }, debounceMs); })); return debouncedObservable; } export function wasEventTriggeredRecently(event: Event<any>, timeoutMs: number, disposableStore: DisposableStore): IObservable<boolean> { const observable = observableValue('triggeredRecently', false); let timeout: any = undefined; disposableStore.add(event(() => { observable.set(true, undefined); if (timeout) { clearTimeout(timeout); } timeout = setTimeout(() => { observable.set(false, undefined); }, timeoutMs); })); return observable; } /** * This ensures the observable cache is kept up-to-date, even if there are no subscribers. * This is useful when the observables `get` method is used, but not its `read` method. * * (Usually, when no one is actually observing the observable, getting its value will * compute it from scratch, as the cache cannot be trusted: * Because no one is actually observing its value, keeping the cache up-to-date would be too expensive) */ export function keepAlive(observable: IObservable<any>): IDisposable { const o = new KeepAliveObserver(); observable.addObserver(o); return toDisposable(() => { observable.removeObserver(o); }); } class KeepAliveObserver implements IObserver { beginUpdate<T>(observable: IObservable<T, void>): void { // NO OP } handleChange<T, TChange>(observable: IObservable<T, TChange>, change: TChange): void { // NO OP } endUpdate<T>(observable: IObservable<T, void>): void { // NO OP } } export function derivedObservableWithCache<T>(name: string, computeFn: (reader: IReader, lastValue: T | undefined) => T): IObservable<T> { let lastValue: T | undefined = undefined; const observable = derived(name, reader => { lastValue = computeFn(reader, lastValue); return lastValue; }); return observable; } export function derivedObservableWithWritableCache<T>(name: string, computeFn: (reader: IReader, lastValue: T | undefined) => T): IObservable<T> & { clearCache(transaction: ITransaction): void } { let lastValue: T | undefined = undefined; const counter = observableValue('derivedObservableWithWritableCache.counter', 0); const observable = derived(name, reader => { counter.read(reader); lastValue = computeFn(reader, lastValue); return lastValue; }); return Object.assign(observable, { clearCache: (transaction: ITransaction) => { lastValue = undefined; counter.set(counter.get() + 1, transaction); }, }); }
src/vs/base/common/observableImpl/utils.ts
0
https://github.com/microsoft/vscode/commit/324d1a25760c6abeb4a0492c0c5a22795b695bf4
[ 0.0010751549853011966, 0.00020020821830257773, 0.0001628276804694906, 0.00017030455637723207, 0.000154339853907004 ]
{ "id": 9, "code_window": [ "import { Event } from 'vs/base/common/event';\n", "import { IDisposable } from 'vs/base/common/lifecycle';\n", "import { URI } from 'vs/base/common/uri';\n", "import { CompletionItemKind, ProviderResult } from 'vs/editor/common/languages';\n", "import { createDecorator } from 'vs/platform/instantiation/common/instantiation';\n", "import { IInteractiveResponseErrorDetails, InteractiveSessionModel } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionModel';\n", "\n", "export interface IInteractiveSession {\n", "\tid: number;\n", "\trequesterUsername: string;\n", "\trequesterAvatarIconUri?: URI;\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { InteractiveSessionModel } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionModel';\n" ], "file_path": "src/vs/workbench/contrib/interactiveSession/common/interactiveSessionService.ts", "type": "replace", "edit_start_line_idx": 11 }
{ "extends": "../tsconfig.base.json", "compilerOptions": { "outDir": "./out", "types": [ "node" ] }, "include": [ "src/**/*", "../../src/vscode-dts/vscode.d.ts", "../../src/vscode-dts/vscode.proposed.tunnels.d.ts", "../../src/vscode-dts/vscode.proposed.resolvers.d.ts" ] }
extensions/vscode-test-resolver/tsconfig.json
0
https://github.com/microsoft/vscode/commit/324d1a25760c6abeb4a0492c0c5a22795b695bf4
[ 0.00017278922314289957, 0.00017087205196730793, 0.00016895486623980105, 0.00017087205196730793, 0.000001917178451549262 ]
{ "id": 9, "code_window": [ "import { Event } from 'vs/base/common/event';\n", "import { IDisposable } from 'vs/base/common/lifecycle';\n", "import { URI } from 'vs/base/common/uri';\n", "import { CompletionItemKind, ProviderResult } from 'vs/editor/common/languages';\n", "import { createDecorator } from 'vs/platform/instantiation/common/instantiation';\n", "import { IInteractiveResponseErrorDetails, InteractiveSessionModel } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionModel';\n", "\n", "export interface IInteractiveSession {\n", "\tid: number;\n", "\trequesterUsername: string;\n", "\trequesterAvatarIconUri?: URI;\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { InteractiveSessionModel } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionModel';\n" ], "file_path": "src/vs/workbench/contrib/interactiveSession/common/interactiveSessionService.ts", "type": "replace", "edit_start_line_idx": 11 }
# Visual Studio Code - Open Source ("Code - OSS") [![Feature Requests](https://img.shields.io/github/issues/microsoft/vscode/feature-request.svg)](https://github.com/microsoft/vscode/issues?q=is%3Aopen+is%3Aissue+label%3Afeature-request+sort%3Areactions-%2B1-desc) [![Bugs](https://img.shields.io/github/issues/microsoft/vscode/bug.svg)](https://github.com/microsoft/vscode/issues?utf8=✓&q=is%3Aissue+is%3Aopen+label%3Abug) [![Gitter](https://img.shields.io/badge/chat-on%20gitter-yellow.svg)](https://gitter.im/Microsoft/vscode) ## The Repository This repository ("`Code - OSS`") is where we (Microsoft) develop the [Visual Studio Code](https://code.visualstudio.com) product together with the community. Not only do we work on code and issues here, we also publish our [roadmap](https://github.com/microsoft/vscode/wiki/Roadmap), [monthly iteration plans](https://github.com/microsoft/vscode/wiki/Iteration-Plans), and our [endgame plans](https://github.com/microsoft/vscode/wiki/Running-the-Endgame). This source code is available to everyone under the standard [MIT license](https://github.com/microsoft/vscode/blob/main/LICENSE.txt). ## Visual Studio Code <p align="center"> <img alt="VS Code in action" src="https://user-images.githubusercontent.com/35271042/118224532-3842c400-b438-11eb-923d-a5f66fa6785a.png"> </p> [Visual Studio Code](https://code.visualstudio.com) is a distribution of the `Code - OSS` repository with Microsoft-specific customizations released under a traditional [Microsoft product license](https://code.visualstudio.com/License/). [Visual Studio Code](https://code.visualstudio.com) combines the simplicity of a code editor with what developers need for their core edit-build-debug cycle. It provides comprehensive code editing, navigation, and understanding support along with lightweight debugging, a rich extensibility model, and lightweight integration with existing tools. Visual Studio Code is updated monthly with new features and bug fixes. You can download it for Windows, macOS, and Linux on [Visual Studio Code's website](https://code.visualstudio.com/Download). To get the latest releases every day, install the [Insiders build](https://code.visualstudio.com/insiders). ## Contributing There are many ways in which you can participate in this project, for example: * [Submit bugs and feature requests](https://github.com/microsoft/vscode/issues), and help us verify as they are checked in * Review [source code changes](https://github.com/microsoft/vscode/pulls) * Review the [documentation](https://github.com/microsoft/vscode-docs) and make pull requests for anything from typos to additional and new content If you are interested in fixing issues and contributing directly to the code base, please see the document [How to Contribute](https://github.com/microsoft/vscode/wiki/How-to-Contribute), which covers the following: * [How to build and run from source](https://github.com/microsoft/vscode/wiki/How-to-Contribute) * [The development workflow, including debugging and running tests](https://github.com/microsoft/vscode/wiki/How-to-Contribute#debugging) * [Coding guidelines](https://github.com/microsoft/vscode/wiki/Coding-Guidelines) * [Submitting pull requests](https://github.com/microsoft/vscode/wiki/How-to-Contribute#pull-requests) * [Finding an issue to work on](https://github.com/microsoft/vscode/wiki/How-to-Contribute#where-to-contribute) * [Contributing to translations](https://aka.ms/vscodeloc) ## Feedback * Ask a question on [Stack Overflow](https://stackoverflow.com/questions/tagged/vscode) * [Request a new feature](CONTRIBUTING.md) * Upvote [popular feature requests](https://github.com/microsoft/vscode/issues?q=is%3Aopen+is%3Aissue+label%3Afeature-request+sort%3Areactions-%2B1-desc) * [File an issue](https://github.com/microsoft/vscode/issues) * Connect with the extension author community on [GitHub Discussions](https://github.com/microsoft/vscode-discussions/discussions) or [Slack](https://aka.ms/vscode-dev-community) * Follow [@code](https://twitter.com/code) and let us know what you think! See our [wiki](https://github.com/microsoft/vscode/wiki/Feedback-Channels) for a description of each of these channels and information on some other available community-driven channels. ## Related Projects Many of the core components and extensions to VS Code live in their own repositories on GitHub. For example, the [node debug adapter](https://github.com/microsoft/vscode-node-debug) and the [mono debug adapter](https://github.com/microsoft/vscode-mono-debug) repositories are separate from each other. For a complete list, please visit the [Related Projects](https://github.com/microsoft/vscode/wiki/Related-Projects) page on our [wiki](https://github.com/microsoft/vscode/wiki). ## Bundled Extensions VS Code includes a set of built-in extensions located in the [extensions](extensions) folder, including grammars and snippets for many languages. Extensions that provide rich language support (code completion, Go to Definition) for a language have the suffix `language-features`. For example, the `json` extension provides coloring for `JSON` and the `json-language-features` extension provides rich language support for `JSON`. ## Development Container This repository includes a Visual Studio Code Dev Containers / GitHub Codespaces development container. - For [Dev Containers](https://aka.ms/vscode-remote/download/containers), use the **Dev Containers: Clone Repository in Container Volume...** command which creates a Docker volume for better disk I/O on macOS and Windows. - If you already have VS Code and Docker installed, you can also click [here](https://vscode.dev/redirect?url=vscode://ms-vscode-remote.remote-containers/cloneInVolume?url=https://github.com/microsoft/vscode) to get started. This will cause VS Code to automatically install the Dev Containers extension if needed, clone the source code into a container volume, and spin up a dev container for use. - For Codespaces, install the [GitHub Codespaces](https://marketplace.visualstudio.com/items?itemName=GitHub.codespaces) extension in VS Code, and use the **Codespaces: Create New Codespace** command. Docker / the Codespace should have at least **4 Cores and 6 GB of RAM (8 GB recommended)** to run full build. See the [development container README](.devcontainer/README.md) for more information. ## Code of Conduct This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [[email protected]](mailto:[email protected]) with any additional questions or comments. ## License Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the [MIT](LICENSE.txt) license.
README.md
0
https://github.com/microsoft/vscode/commit/324d1a25760c6abeb4a0492c0c5a22795b695bf4
[ 0.0001764846092555672, 0.0001677617256063968, 0.00016091349243652076, 0.00016693743236828595, 0.000004316523700254038 ]
{ "id": 10, "code_window": [ "\tmessage: string | IInteractiveSessionReplyFollowup;\n", "}\n", "\n", "export interface IInteractiveResponse {\n", "\tsession: IInteractiveSession;\n", "\terrorDetails?: IInteractiveResponseErrorDetails;\n", "\ttimings?: {\n", "\t\tfirstProgress: number;\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "export interface IInteractiveResponseErrorDetails {\n", "\tmessage: string;\n", "\tresponseIsIncomplete?: boolean;\n", "\tresponseIsFiltered?: boolean;\n", "}\n", "\n" ], "file_path": "src/vs/workbench/contrib/interactiveSession/common/interactiveSessionService.ts", "type": "add", "edit_start_line_idx": 28 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { CancellationToken } from 'vs/base/common/cancellation'; import { Event } from 'vs/base/common/event'; import { IDisposable } from 'vs/base/common/lifecycle'; import { URI } from 'vs/base/common/uri'; import { CompletionItemKind, ProviderResult } from 'vs/editor/common/languages'; import { createDecorator } from 'vs/platform/instantiation/common/instantiation'; import { IInteractiveResponseErrorDetails, InteractiveSessionModel } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionModel'; export interface IInteractiveSession { id: number; requesterUsername: string; requesterAvatarIconUri?: URI; responderUsername: string; responderAvatarIconUri?: URI; inputPlaceholder?: string; dispose?(): void; } export interface IInteractiveRequest { session: IInteractiveSession; message: string | IInteractiveSessionReplyFollowup; } export interface IInteractiveResponse { session: IInteractiveSession; errorDetails?: IInteractiveResponseErrorDetails; timings?: { firstProgress: number; totalElapsed: number; }; } export type IInteractiveProgress = { content: string } | { responseId: string }; export interface IPersistedInteractiveState { } export interface IInteractiveProvider { readonly id: string; readonly progressiveRenderingEnabled?: boolean; readonly iconUrl?: string; prepareSession(initialState: IPersistedInteractiveState | undefined, token: CancellationToken): ProviderResult<IInteractiveSession | undefined>; resolveRequest?(session: IInteractiveSession, context: any, token: CancellationToken): ProviderResult<IInteractiveRequest>; provideWelcomeMessage?(token: CancellationToken): ProviderResult<(string | IInteractiveSessionReplyFollowup[])[] | undefined>; provideSuggestions?(token: CancellationToken): ProviderResult<string[] | undefined>; provideFollowups?(session: IInteractiveSession, token: CancellationToken): ProviderResult<IInteractiveSessionFollowup[] | undefined>; provideReply(request: IInteractiveRequest, progress: (progress: IInteractiveProgress) => void, token: CancellationToken): ProviderResult<IInteractiveResponse>; provideSlashCommands?(session: IInteractiveSession, token: CancellationToken): ProviderResult<IInteractiveSlashCommand[]>; } export interface IInteractiveSlashCommand { command: string; kind: CompletionItemKind; detail?: string; } export interface IInteractiveSessionReplyFollowup { kind: 'reply'; message: string; title?: string; tooltip?: string; metadata?: any; } export interface IInteractiveSessionResponseCommandFollowup { kind: 'command'; commandId: string; args?: any[]; title: string; // supports codicon strings } export type IInteractiveSessionFollowup = IInteractiveSessionReplyFollowup | IInteractiveSessionResponseCommandFollowup; export enum InteractiveSessionVoteDirection { Up = 1, Down = 2 } export interface IInteractiveSessionVoteAction { kind: 'vote'; responseId: string; direction: InteractiveSessionVoteDirection; } export enum InteractiveSessionCopyKind { // Keyboard shortcut or context menu Action = 1, Toolbar = 2 } export interface IInteractiveSessionCopyAction { kind: 'copy'; responseId: string; codeBlockIndex: number; copyType: InteractiveSessionCopyKind; copiedCharacters: number; totalCharacters: number; copiedText: string; } export interface IInteractiveSessionInsertAction { kind: 'insert'; responseId: string; codeBlockIndex: number; } export interface IInteractiveSessionCommandAction { kind: 'command'; command: IInteractiveSessionResponseCommandFollowup; } export type InteractiveSessionUserAction = IInteractiveSessionVoteAction | IInteractiveSessionCopyAction | IInteractiveSessionInsertAction | IInteractiveSessionCommandAction; export interface IInteractiveSessionUserActionEvent { action: InteractiveSessionUserAction; providerId: string; } export interface IInteractiveSessionDynamicRequest { /** * The message that will be displayed in the UI */ message: string; /** * Any extra metadata/context that will go to the provider. */ metadata?: any; } export interface IInteractiveSessionCompleteResponse { message: string; errorDetails?: IInteractiveResponseErrorDetails; } export const IInteractiveSessionService = createDecorator<IInteractiveSessionService>('IInteractiveSessionService'); export interface IInteractiveSessionService { _serviceBrand: undefined; registerProvider(provider: IInteractiveProvider): IDisposable; progressiveRenderingEnabled(providerId: string): boolean; startSession(providerId: string, allowRestoringSession: boolean, token: CancellationToken): Promise<InteractiveSessionModel | undefined>; /** * Returns whether the request was accepted. */ sendRequest(sessionId: number, message: string | IInteractiveSessionReplyFollowup): { completePromise: Promise<void> } | undefined; cancelCurrentRequestForSession(sessionId: number): void; getSlashCommands(sessionId: number, token: CancellationToken): Promise<IInteractiveSlashCommand[] | undefined>; clearSession(sessionId: number): void; acceptNewSessionState(sessionId: number, state: any): void; addInteractiveRequest(context: any): void; addCompleteRequest(message: string, response: IInteractiveSessionCompleteResponse): void; sendInteractiveRequestToProvider(providerId: string, message: IInteractiveSessionDynamicRequest): void; provideSuggestions(providerId: string, token: CancellationToken): Promise<string[] | undefined>; releaseSession(sessionId: number): void; onDidPerformUserAction: Event<IInteractiveSessionUserActionEvent>; notifyUserAction(event: IInteractiveSessionUserActionEvent): void; }
src/vs/workbench/contrib/interactiveSession/common/interactiveSessionService.ts
1
https://github.com/microsoft/vscode/commit/324d1a25760c6abeb4a0492c0c5a22795b695bf4
[ 0.9990293979644775, 0.3232467472553253, 0.00017567134636919945, 0.016462059691548347, 0.4405781924724579 ]
{ "id": 10, "code_window": [ "\tmessage: string | IInteractiveSessionReplyFollowup;\n", "}\n", "\n", "export interface IInteractiveResponse {\n", "\tsession: IInteractiveSession;\n", "\terrorDetails?: IInteractiveResponseErrorDetails;\n", "\ttimings?: {\n", "\t\tfirstProgress: number;\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "export interface IInteractiveResponseErrorDetails {\n", "\tmessage: string;\n", "\tresponseIsIncomplete?: boolean;\n", "\tresponseIsFiltered?: boolean;\n", "}\n", "\n" ], "file_path": "src/vs/workbench/contrib/interactiveSession/common/interactiveSessionService.ts", "type": "add", "edit_start_line_idx": 28 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ declare module 'vscode' { export interface TerminalQuickFixProvider { /** * Provides terminal quick fixes * @param commandMatchResult The command match result for which to provide quick fixes * @param token A cancellation token indicating the result is no longer needed * @return Terminal quick fix(es) if any */ provideTerminalQuickFixes(commandMatchResult: TerminalCommandMatchResult, token: CancellationToken): ProviderResult<(TerminalQuickFixCommand | TerminalQuickFixOpener)[] | TerminalQuickFixCommand | TerminalQuickFixOpener>; } export interface TerminalCommandMatchResult { commandLine: string; commandLineMatch: RegExpMatchArray; outputMatch?: { regexMatch: RegExpMatchArray; outputLines: string[]; }; } export namespace window { /** * @param provider A terminal quick fix provider * @return A {@link Disposable} that unregisters the provider when being disposed */ export function registerTerminalQuickFixProvider(id: string, provider: TerminalQuickFixProvider): Disposable; } export class TerminalQuickFixCommand { /** * The terminal command to run */ terminalCommand: string; constructor(terminalCommand: string); } export class TerminalQuickFixOpener { /** * The uri to open */ uri: Uri; constructor(uri: Uri); } /** * A matcher that runs on a sub-section of a terminal command's output */ interface TerminalOutputMatcher { /** * A string or regex to match against the unwrapped line. If this is a regex with the multiline * flag, it will scan an amount of lines equal to `\n` instances in the regex + 1. */ lineMatcher: string | RegExp; /** * Which side of the output to anchor the {@link offset} and {@link length} against. */ anchor: TerminalOutputAnchor; /** * The number of rows above or below the {@link anchor} to start matching against. */ offset: number; /** * The number of wrapped lines to match against, this should be as small as possible for performance * reasons. This is capped at 40. */ length: number; } enum TerminalOutputAnchor { Top = 0, Bottom = 1 } enum TerminalQuickFixType { Command = 0, Opener = 1 } }
src/vscode-dts/vscode.proposed.terminalQuickFixProvider.d.ts
0
https://github.com/microsoft/vscode/commit/324d1a25760c6abeb4a0492c0c5a22795b695bf4
[ 0.00149701745249331, 0.0003355465014465153, 0.0001673563092481345, 0.00017214706167578697, 0.00041214353404939175 ]
{ "id": 10, "code_window": [ "\tmessage: string | IInteractiveSessionReplyFollowup;\n", "}\n", "\n", "export interface IInteractiveResponse {\n", "\tsession: IInteractiveSession;\n", "\terrorDetails?: IInteractiveResponseErrorDetails;\n", "\ttimings?: {\n", "\t\tfirstProgress: number;\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "export interface IInteractiveResponseErrorDetails {\n", "\tmessage: string;\n", "\tresponseIsIncomplete?: boolean;\n", "\tresponseIsFiltered?: boolean;\n", "}\n", "\n" ], "file_path": "src/vs/workbench/contrib/interactiveSession/common/interactiveSessionService.ts", "type": "add", "edit_start_line_idx": 28 }
@{ var total = 0; var totalMessage = ""; @* a multiline razor comment embedded in csharp *@ if (IsPost) { // Retrieve the numbers that the user entered. var num1 = Request["text1"]; var num2 = Request["text2"]; // Convert the entered strings into integers numbers and add. total = num1.AsInt() + num2.AsInt(); <italic><bold>totalMessage = "Total = " + total;</bold></italic> } } <!DOCTYPE html> <html lang="en"> <head> <title>Add Numbers</title> <meta charset="utf-8" /> </head> <body> <p>Enter two whole numbers and then click <strong>Add</strong>.</p> <form action="" method="post"> <p><label for="text1">First Number:</label> <input type="text" name="text1" /> </p> <p><label for="text2">Second Number:</label> <input type="text" name="text2" /> </p> <p><input type="submit" value="Add" /></p> </form> @* now we call the totalMessage method (a multi line razor comment outside code) *@ <p>@totalMessage</p> <p>@(totalMessage+"!")</p> An email address (with escaped at character): name@@domain.com </body> </html>
extensions/vscode-colorize-tests/test/colorize-fixtures/test.cshtml
0
https://github.com/microsoft/vscode/commit/324d1a25760c6abeb4a0492c0c5a22795b695bf4
[ 0.0001736957929097116, 0.0001714184181764722, 0.00017034033953677863, 0.00017122228746302426, 0.0000012003890788037097 ]
{ "id": 10, "code_window": [ "\tmessage: string | IInteractiveSessionReplyFollowup;\n", "}\n", "\n", "export interface IInteractiveResponse {\n", "\tsession: IInteractiveSession;\n", "\terrorDetails?: IInteractiveResponseErrorDetails;\n", "\ttimings?: {\n", "\t\tfirstProgress: number;\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "export interface IInteractiveResponseErrorDetails {\n", "\tmessage: string;\n", "\tresponseIsIncomplete?: boolean;\n", "\tresponseIsFiltered?: boolean;\n", "}\n", "\n" ], "file_path": "src/vs/workbench/contrib/interactiveSession/common/interactiveSessionService.ts", "type": "add", "edit_start_line_idx": 28 }
/*--------------------------------------------------------------------------------------------- * 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 { IConfigurationNode } from 'vs/platform/configuration/common/configurationRegistry'; import { Registry } from 'vs/platform/registry/common/platform'; import { IWorkbenchContribution } from 'vs/workbench/common/contributions'; import { IWorkspaceContextService, IWorkspaceFolder } from 'vs/platform/workspace/common/workspace'; import { ConfigurationTarget, IConfigurationOverrides, IConfigurationService, IConfigurationValue } from 'vs/platform/configuration/common/configuration'; import { Disposable } from 'vs/base/common/lifecycle'; import { Emitter } from 'vs/base/common/event'; export const applicationConfigurationNodeBase = Object.freeze<IConfigurationNode>({ 'id': 'application', 'order': 100, 'title': localize('applicationConfigurationTitle', "Application"), 'type': 'object' }); export const workbenchConfigurationNodeBase = Object.freeze<IConfigurationNode>({ 'id': 'workbench', 'order': 7, 'title': localize('workbenchConfigurationTitle', "Workbench"), 'type': 'object', }); export const Extensions = { ConfigurationMigration: 'base.contributions.configuration.migration' }; export type ConfigurationValue = { value: any | undefined /* Remove */ }; export type ConfigurationKeyValuePairs = [string, ConfigurationValue][]; export type ConfigurationMigrationFn = (value: any, valueAccessor: (key: string) => any) => ConfigurationValue | ConfigurationKeyValuePairs | Promise<ConfigurationValue | ConfigurationKeyValuePairs>; export type ConfigurationMigration = { key: string; migrateFn: ConfigurationMigrationFn }; export interface IConfigurationMigrationRegistry { registerConfigurationMigrations(configurationMigrations: ConfigurationMigration[]): void; } class ConfigurationMigrationRegistry implements IConfigurationMigrationRegistry { readonly migrations: ConfigurationMigration[] = []; private readonly _onDidRegisterConfigurationMigrations = new Emitter<ConfigurationMigration[]>(); readonly onDidRegisterConfigurationMigration = this._onDidRegisterConfigurationMigrations.event; registerConfigurationMigrations(configurationMigrations: ConfigurationMigration[]): void { this.migrations.push(...configurationMigrations); } } const configurationMigrationRegistry = new ConfigurationMigrationRegistry(); Registry.add(Extensions.ConfigurationMigration, configurationMigrationRegistry); export class ConfigurationMigrationWorkbenchContribution extends Disposable implements IWorkbenchContribution { constructor( @IConfigurationService private readonly configurationService: IConfigurationService, @IWorkspaceContextService private readonly workspaceService: IWorkspaceContextService, ) { super(); this._register(this.workspaceService.onDidChangeWorkspaceFolders(async (e) => { for (const folder of e.added) { await this.migrateConfigurationsForFolder(folder, configurationMigrationRegistry.migrations); } })); this.migrateConfigurations(configurationMigrationRegistry.migrations); this._register(configurationMigrationRegistry.onDidRegisterConfigurationMigration(migration => this.migrateConfigurations(migration))); } private async migrateConfigurations(migrations: ConfigurationMigration[]): Promise<void> { await this.migrateConfigurationsForFolder(undefined, migrations); for (const folder of this.workspaceService.getWorkspace().folders) { await this.migrateConfigurationsForFolder(folder, migrations); } } private async migrateConfigurationsForFolder(folder: IWorkspaceFolder | undefined, migrations: ConfigurationMigration[]): Promise<void> { await Promise.all(migrations.map(migration => this.migrateConfigurationsForFolderAndOverride(migration, { resource: folder?.uri }))); } private async migrateConfigurationsForFolderAndOverride(migration: ConfigurationMigration, overrides: IConfigurationOverrides): Promise<void> { const data = this.configurationService.inspect(migration.key, overrides); await this.migrateConfigurationForFolderOverrideAndTarget(migration, overrides, data, 'userValue', ConfigurationTarget.USER); await this.migrateConfigurationForFolderOverrideAndTarget(migration, overrides, data, 'userLocalValue', ConfigurationTarget.USER_LOCAL); await this.migrateConfigurationForFolderOverrideAndTarget(migration, overrides, data, 'userRemoteValue', ConfigurationTarget.USER_REMOTE); await this.migrateConfigurationForFolderOverrideAndTarget(migration, overrides, data, 'workspaceFolderValue', ConfigurationTarget.WORKSPACE_FOLDER); await this.migrateConfigurationForFolderOverrideAndTarget(migration, overrides, data, 'workspaceValue', ConfigurationTarget.WORKSPACE); if (typeof overrides.overrideIdentifier === 'undefined' && typeof data.overrideIdentifiers !== 'undefined') { for (const overrideIdentifier of data.overrideIdentifiers) { await this.migrateConfigurationsForFolderAndOverride(migration, { resource: overrides.resource, overrideIdentifier }); } } } private async migrateConfigurationForFolderOverrideAndTarget(migration: ConfigurationMigration, overrides: IConfigurationOverrides, data: IConfigurationValue<any>, dataKey: keyof IConfigurationValue<any>, target: ConfigurationTarget): Promise<void> { const value = data[dataKey]; if (typeof value === 'undefined') { return; } const valueAccessor = (key: string) => this.configurationService.inspect(key, overrides)[dataKey]; const result = await migration.migrateFn(value, valueAccessor); const keyValuePairs: ConfigurationKeyValuePairs = Array.isArray(result) ? result : [[migration.key, result]]; await Promise.allSettled(keyValuePairs.map(async ([key, value]) => this.configurationService.updateValue(key, value.value, overrides, target))); } }
src/vs/workbench/common/configuration.ts
0
https://github.com/microsoft/vscode/commit/324d1a25760c6abeb4a0492c0c5a22795b695bf4
[ 0.00017660699086263776, 0.0001711892691673711, 0.00016699508705642074, 0.0001707871851976961, 0.000003058652964682551 ]
{ "id": 11, "code_window": [ "import { IMarkdownString, MarkdownString } from 'vs/base/common/htmlContent';\n", "import { Disposable } from 'vs/base/common/lifecycle';\n", "import { URI } from 'vs/base/common/uri';\n", "import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';\n", "import { ILogService } from 'vs/platform/log/common/log';\n", "import { IInteractiveRequestModel, IInteractiveResponseErrorDetails, IInteractiveResponseModel, IInteractiveSessionModel, IInteractiveSessionWelcomeMessageModel, IInteractiveWelcomeMessageContent } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionModel';\n", "import { IInteractiveSessionReplyFollowup, IInteractiveSessionResponseCommandFollowup, IInteractiveSessionService, InteractiveSessionVoteDirection } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionService';\n", "import { countWords } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionWordCounter';\n", "\n", "export function isRequestVM(item: unknown): item is IInteractiveRequestViewModel {\n", "\treturn !!item && typeof item === 'object' && 'message' in item;\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { IInteractiveRequestModel, IInteractiveResponseModel, IInteractiveSessionModel, IInteractiveSessionWelcomeMessageModel, IInteractiveWelcomeMessageContent } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionModel';\n", "import { IInteractiveResponseErrorDetails, IInteractiveSessionReplyFollowup, IInteractiveSessionResponseCommandFollowup, IInteractiveSessionService, InteractiveSessionVoteDirection } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionService';\n" ], "file_path": "src/vs/workbench/contrib/interactiveSession/common/interactiveSessionViewModel.ts", "type": "replace", "edit_start_line_idx": 11 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as dom from 'vs/base/browser/dom'; import { renderIcon } from 'vs/base/browser/ui/iconLabel/iconLabels'; import { IListVirtualDelegate } from 'vs/base/browser/ui/list/list'; import { IListAccessibilityProvider } from 'vs/base/browser/ui/list/listWidget'; import { ITreeNode, ITreeRenderer } from 'vs/base/browser/ui/tree/tree'; import { IntervalTimer } from 'vs/base/common/async'; import { Codicon } from 'vs/base/common/codicons'; import { Emitter, Event } from 'vs/base/common/event'; import { FuzzyScore } from 'vs/base/common/filters'; import { IMarkdownString, MarkdownString } from 'vs/base/common/htmlContent'; import { Disposable, DisposableStore, IDisposable } from 'vs/base/common/lifecycle'; import { ResourceMap } from 'vs/base/common/map'; import { FileAccess } from 'vs/base/common/network'; import { ThemeIcon } from 'vs/base/common/themables'; import { EditorExtensionsRegistry } from 'vs/editor/browser/editorExtensions'; import { CodeEditorWidget } from 'vs/editor/browser/widget/codeEditorWidget'; import { EDITOR_FONT_DEFAULTS, IEditorOptions } from 'vs/editor/common/config/editorOptions'; import { Range } from 'vs/editor/common/core/range'; import { ILanguageService } from 'vs/editor/common/languages/language'; import { ITextModel } from 'vs/editor/common/model'; import { IModelService } from 'vs/editor/common/services/model'; import { BracketMatchingController } from 'vs/editor/contrib/bracketMatching/browser/bracketMatching'; import { ContextMenuController } from 'vs/editor/contrib/contextmenu/browser/contextmenu'; import { IMarkdownRenderResult, MarkdownRenderer } from 'vs/editor/contrib/markdownRenderer/browser/markdownRenderer'; import { ViewportSemanticTokensContribution } from 'vs/editor/contrib/semanticTokens/browser/viewportSemanticTokens'; import { SmartSelectController } from 'vs/editor/contrib/smartSelect/browser/smartSelect'; import { WordHighlighterContribution } from 'vs/editor/contrib/wordHighlighter/browser/wordHighlighter'; import { localize } from 'vs/nls'; import { MenuWorkbenchToolBar } from 'vs/platform/actions/browser/toolbar'; import { MenuId } from 'vs/platform/actions/common/actions'; import { ICommandService } from 'vs/platform/commands/common/commands'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection'; import { ILogService } from 'vs/platform/log/common/log'; import { defaultButtonStyles } from 'vs/platform/theme/browser/defaultStyles'; import { MenuPreventer } from 'vs/workbench/contrib/codeEditor/browser/menuPreventer'; import { SelectionClipboardContributionID } from 'vs/workbench/contrib/codeEditor/browser/selectionClipboard'; import { getSimpleEditorOptions } from 'vs/workbench/contrib/codeEditor/browser/simpleEditorOptions'; import { IInteractiveSessionCodeBlockActionContext } from 'vs/workbench/contrib/interactiveSession/browser/actions/interactiveSessionCodeblockActions'; import { InteractiveSessionFollowups } from 'vs/workbench/contrib/interactiveSession/browser/interactiveSessionFollowups'; import { InteractiveSessionEditorOptions } from 'vs/workbench/contrib/interactiveSession/browser/interactiveSessionOptions'; import { CONTEXT_RESPONSE_HAS_PROVIDER_ID, CONTEXT_RESPONSE_VOTE } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionContextKeys'; import { IInteractiveSessionReplyFollowup, IInteractiveSessionService, IInteractiveSlashCommand, InteractiveSessionVoteDirection } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionService'; import { IInteractiveRequestViewModel, IInteractiveResponseViewModel, IInteractiveWelcomeMessageViewModel, isRequestVM, isResponseVM, isWelcomeVM } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionViewModel'; import { getNWords } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionWordCounter'; const $ = dom.$; export type InteractiveTreeItem = IInteractiveRequestViewModel | IInteractiveResponseViewModel | IInteractiveWelcomeMessageViewModel; interface IInteractiveListItemTemplate { rowContainer: HTMLElement; titleToolbar: MenuWorkbenchToolBar; avatar: HTMLElement; username: HTMLElement; value: HTMLElement; contextKeyService: IContextKeyService; templateDisposables: IDisposable; elementDisposables: DisposableStore; } interface IItemHeightChangeParams { element: InteractiveTreeItem; height: number; } const forceVerboseLayoutTracing = false; export interface IInteractiveSessionRendererDelegate { getListLength(): number; getSlashCommands(): IInteractiveSlashCommand[]; } export class InteractiveListItemRenderer extends Disposable implements ITreeRenderer<InteractiveTreeItem, FuzzyScore, IInteractiveListItemTemplate> { static readonly cursorCharacter = '\u258c'; static readonly ID = 'item'; private readonly renderer: MarkdownRenderer; protected readonly _onDidClickFollowup = this._register(new Emitter<IInteractiveSessionReplyFollowup>()); readonly onDidClickFollowup: Event<IInteractiveSessionReplyFollowup> = this._onDidClickFollowup.event; protected readonly _onDidChangeItemHeight = this._register(new Emitter<IItemHeightChangeParams>()); readonly onDidChangeItemHeight: Event<IItemHeightChangeParams> = this._onDidChangeItemHeight.event; private readonly _editorPool: EditorPool; private _currentLayoutWidth: number = 0; constructor( private readonly editorOptions: InteractiveSessionEditorOptions, private readonly delegate: IInteractiveSessionRendererDelegate, @IInstantiationService private readonly instantiationService: IInstantiationService, @IConfigurationService private readonly configService: IConfigurationService, @ILogService private readonly logService: ILogService, @ICommandService private readonly commandService: ICommandService, @IContextKeyService private readonly contextKeyService: IContextKeyService, @IInteractiveSessionService private readonly interactiveSessionService: IInteractiveSessionService, ) { super(); this.renderer = this.instantiationService.createInstance(MarkdownRenderer, {}); this._editorPool = this._register(this.instantiationService.createInstance(EditorPool, this.editorOptions)); } get templateId(): string { return InteractiveListItemRenderer.ID; } private traceLayout(method: string, message: string) { if (forceVerboseLayoutTracing) { this.logService.info(`InteractiveListItemRenderer#${method}: ${message}`); } else { this.logService.trace(`InteractiveListItemRenderer#${method}: ${message}`); } } private shouldRenderProgressively(element: IInteractiveResponseViewModel): boolean { return !this.configService.getValue('interactive.experimental.disableProgressiveRendering') && element.progressiveResponseRenderingEnabled; } private getProgressiveRenderRate(element: IInteractiveResponseViewModel): number { const configuredRate = this.configService.getValue('interactive.experimental.progressiveRenderingRate'); if (typeof configuredRate === 'number') { return configuredRate; } if (element.isComplete) { return 60; } if (element.contentUpdateTimings && element.contentUpdateTimings.impliedWordLoadRate) { // This doesn't account for dead time after the last update. When the previous update is the final one and the model is only waiting for followupQuestions, that's good. // When there was one quick update and then you are waiting longer for the next one, that's not good since the rate should be decreasing. // If it's an issue, we can change this to be based on the total time from now to the beginning. const rateBoost = 1.5; return element.contentUpdateTimings.impliedWordLoadRate * rateBoost; } return 8; } layout(width: number): void { this._currentLayoutWidth = width - 40; // TODO Padding this._editorPool.inUse.forEach(editor => { editor.layout(this._currentLayoutWidth); }); } renderTemplate(container: HTMLElement): IInteractiveListItemTemplate { const templateDisposables = new DisposableStore(); const rowContainer = dom.append(container, $('.interactive-item-container')); const header = dom.append(rowContainer, $('.header')); const user = dom.append(header, $('.user')); const avatar = dom.append(user, $('.avatar')); const username = dom.append(user, $('h3.username')); const value = dom.append(rowContainer, $('.value')); const elementDisposables = new DisposableStore(); const contextKeyService = templateDisposables.add(this.contextKeyService.createScoped(rowContainer)); const scopedInstantiationService = this.instantiationService.createChild(new ServiceCollection([IContextKeyService, contextKeyService])); const titleToolbar = templateDisposables.add(scopedInstantiationService.createInstance(MenuWorkbenchToolBar, header, MenuId.InteractiveSessionTitle, { menuOptions: { shouldForwardArgs: true } })); const template: IInteractiveListItemTemplate = { avatar, username, value, rowContainer, elementDisposables, titleToolbar, templateDisposables, contextKeyService }; return template; } renderElement(node: ITreeNode<InteractiveTreeItem, FuzzyScore>, index: number, templateData: IInteractiveListItemTemplate): void { const { element } = node; const kind = isRequestVM(element) ? 'request' : isResponseVM(element) ? 'response' : 'welcome'; this.traceLayout('renderElement', `${kind}, index=${index}`); CONTEXT_RESPONSE_HAS_PROVIDER_ID.bindTo(templateData.contextKeyService).set(isResponseVM(element) && !!element.providerResponseId && !element.isPlaceholder); if (isResponseVM(element)) { CONTEXT_RESPONSE_VOTE.bindTo(templateData.contextKeyService).set(element.vote === InteractiveSessionVoteDirection.Up ? 'up' : element.vote === InteractiveSessionVoteDirection.Down ? 'down' : ''); } else { CONTEXT_RESPONSE_VOTE.bindTo(templateData.contextKeyService).set(''); } templateData.titleToolbar.context = element; templateData.rowContainer.classList.toggle('interactive-request', isRequestVM(element)); templateData.rowContainer.classList.toggle('interactive-response', isResponseVM(element)); templateData.rowContainer.classList.toggle('interactive-welcome', isWelcomeVM(element)); templateData.username.textContent = element.username; if (element.avatarIconUri) { const avatarIcon = dom.$<HTMLImageElement>('img.icon'); avatarIcon.src = FileAccess.uriToBrowserUri(element.avatarIconUri).toString(true); templateData.avatar.replaceChildren(avatarIcon); } else { const defaultIcon = isRequestVM(element) ? Codicon.account : Codicon.hubot; const avatarIcon = dom.$(ThemeIcon.asCSSSelector(defaultIcon)); templateData.avatar.replaceChildren(avatarIcon); } // Do a progressive render if // - This the last response in the list // - And the response is not complete // - Or, we previously started a progressive rendering of this element (if the element is complete, we will finish progressive rendering with a very fast rate) // - And, the feature is not disabled in configuration if (isResponseVM(element) && index === this.delegate.getListLength() - 1 && (!element.isComplete || element.renderData) && this.shouldRenderProgressively(element)) { this.traceLayout('renderElement', `start progressive render ${kind}, index=${index}`); const progressiveRenderingDisposables = templateData.elementDisposables.add(new DisposableStore()); const timer = templateData.elementDisposables.add(new IntervalTimer()); const runProgressiveRender = (initial?: boolean) => { try { if (this.doNextProgressiveRender(element, index, templateData, !!initial, progressiveRenderingDisposables)) { timer.cancel(); } } catch (err) { // Kill the timer if anything went wrong, avoid getting stuck in a nasty rendering loop. timer.cancel(); throw err; } }; runProgressiveRender(true); timer.cancelAndSet(runProgressiveRender, 50); } else if (isResponseVM(element)) { this.basicRenderElement(element.response.value, element, index, templateData, element.isCanceled); } else if (isRequestVM(element)) { this.basicRenderElement(element.messageText, element, index, templateData); } else { this.renderWelcomeMessage(element, templateData); } } private basicRenderElement(markdownValue: string, element: InteractiveTreeItem, index: number, templateData: IInteractiveListItemTemplate, fillInIncompleteTokens = false) { const result = this.renderMarkdown(new MarkdownString(markdownValue), element, templateData.elementDisposables, templateData, fillInIncompleteTokens); dom.clearNode(templateData.value); templateData.value.appendChild(result.element); templateData.elementDisposables.add(result); if (isResponseVM(element) && element.errorDetails?.message) { const errorDetails = dom.append(templateData.value, $('.interactive-response-error-details', undefined, renderIcon(Codicon.error))); errorDetails.appendChild($('span', undefined, element.errorDetails.message)); } if (isResponseVM(element) && element.commandFollowups?.length) { const followupsContainer = dom.append(templateData.value, $('.interactive-response-followups')); templateData.elementDisposables.add(new InteractiveSessionFollowups( followupsContainer, element.commandFollowups, defaultButtonStyles, followup => { this.interactiveSessionService.notifyUserAction({ providerId: element.providerId, action: { kind: 'command', command: followup } }); return this.commandService.executeCommand(followup.commandId, ...(followup.args ?? [])); })); } } private renderWelcomeMessage(element: IInteractiveWelcomeMessageViewModel, templateData: IInteractiveListItemTemplate) { dom.clearNode(templateData.value); const slashCommands = this.delegate.getSlashCommands(); for (const item of element.content) { if (Array.isArray(item)) { templateData.elementDisposables.add(new InteractiveSessionFollowups( templateData.value, item, undefined, followup => this._onDidClickFollowup.fire(followup))); } else { const result = this.renderMarkdown(item as IMarkdownString, element, templateData.elementDisposables, templateData); for (const codeElement of result.element.querySelectorAll('code')) { if (codeElement.textContent && slashCommands.find(command => codeElement.textContent === `/${command.command}`)) { codeElement.classList.add('interactive-slash-command'); } } templateData.value.appendChild(result.element); templateData.elementDisposables.add(result); } } } private doNextProgressiveRender(element: IInteractiveResponseViewModel, index: number, templateData: IInteractiveListItemTemplate, isInRenderElement: boolean, disposables: DisposableStore): boolean { disposables.clear(); let isFullyRendered = false; if (element.isCanceled) { this.traceLayout('runProgressiveRender', `canceled, index=${index}`); element.renderData = undefined; this.basicRenderElement(element.response.value, element, index, templateData, true); isFullyRendered = true; } else { // TODO- this method has the side effect of updating element.renderData const toRender = this.getProgressiveMarkdownToRender(element); isFullyRendered = !!element.renderData?.isFullyRendered; if (isFullyRendered) { // We've reached the end of the available content, so do a normal render this.traceLayout('runProgressiveRender', `end progressive render, index=${index}`); if (element.isComplete) { this.traceLayout('runProgressiveRender', `and disposing renderData, response is complete, index=${index}`); element.renderData = undefined; } else { this.traceLayout('runProgressiveRender', `Rendered all available words, but model is not complete.`); } disposables.clear(); this.basicRenderElement(element.response.value, element, index, templateData, !element.isComplete); } else if (toRender) { // Doing the progressive render const plusCursor = toRender.match(/```.*$/) ? toRender + `\n${InteractiveListItemRenderer.cursorCharacter}` : toRender + ` ${InteractiveListItemRenderer.cursorCharacter}`; const result = this.renderMarkdown(new MarkdownString(plusCursor), element, disposables, templateData, true); dom.clearNode(templateData.value); templateData.value.appendChild(result.element); disposables.add(result); } else { // Nothing new to render, not done, keep waiting return false; } } // Some render happened - update the height const height = templateData.rowContainer.offsetHeight; element.currentRenderedHeight = height; if (!isInRenderElement) { this._onDidChangeItemHeight.fire({ element, height: templateData.rowContainer.offsetHeight }); } return !!isFullyRendered; } private renderMarkdown(markdown: IMarkdownString, element: InteractiveTreeItem, disposables: DisposableStore, templateData: IInteractiveListItemTemplate, fillInIncompleteTokens = false): IMarkdownRenderResult { const disposablesList: IDisposable[] = []; let codeBlockIndex = 0; // TODO if the slash commands stay completely dynamic, this isn't quite right const slashCommands = this.delegate.getSlashCommands(); const usedSlashCommand = slashCommands.find(s => markdown.value.startsWith(`/${s.command} `)); const toRender = usedSlashCommand ? markdown.value.slice(usedSlashCommand.command.length + 2) : markdown.value; markdown = new MarkdownString(toRender); const result = this.renderer.render(markdown, { fillInIncompleteTokens, codeBlockRendererSync: (languageId, text) => { const ref = this.renderCodeBlock({ languageId, text, codeBlockIndex: codeBlockIndex++, element, parentContextKeyService: templateData.contextKeyService }, disposables); // Attach this after updating text/layout of the editor, so it should only be fired when the size updates later (horizontal scrollbar, wrapping) // not during a renderElement OR a progressive render (when we will be firing this event anyway at the end of the render) disposables.add(ref.object.onDidChangeContentHeight(() => { ref.object.layout(this._currentLayoutWidth); this._onDidChangeItemHeight.fire({ element, height: templateData.rowContainer.offsetHeight }); })); disposablesList.push(ref); return ref.object.element; } }); if (usedSlashCommand) { const slashCommandElement = $('span.interactive-slash-command', { title: usedSlashCommand.detail }, `/${usedSlashCommand.command} `); if (result.element.firstChild?.nodeName.toLowerCase() === 'p') { result.element.firstChild.insertBefore(slashCommandElement, result.element.firstChild.firstChild); } else { result.element.insertBefore($('p', undefined, slashCommandElement), result.element.firstChild); } } disposablesList.reverse().forEach(d => disposables.add(d)); return result; } private renderCodeBlock(data: IInteractiveResultCodeBlockData, disposables: DisposableStore): IDisposableReference<IInteractiveResultCodeBlockPart> { const ref = this._editorPool.get(); const editorInfo = ref.object; editorInfo.render(data, this._currentLayoutWidth); return ref; } private getProgressiveMarkdownToRender(element: IInteractiveResponseViewModel): string | undefined { const renderData = element.renderData ?? { renderedWordCount: 0, lastRenderTime: 0 }; const rate = this.getProgressiveRenderRate(element); const numWordsToRender = renderData.lastRenderTime === 0 ? 1 : renderData.renderedWordCount + // Additional words to render beyond what's already rendered Math.floor((Date.now() - renderData.lastRenderTime) / 1000 * rate); if (numWordsToRender === renderData.renderedWordCount) { return undefined; } const result = getNWords(element.response.value, numWordsToRender); element.renderData = { renderedWordCount: result.actualWordCount, lastRenderTime: Date.now(), isFullyRendered: result.isFullString }; return result.value; } disposeElement(node: ITreeNode<InteractiveTreeItem, FuzzyScore>, index: number, templateData: IInteractiveListItemTemplate): void { templateData.elementDisposables.clear(); } disposeTemplate(templateData: IInteractiveListItemTemplate): void { templateData.templateDisposables.dispose(); } } export class InteractiveSessionListDelegate implements IListVirtualDelegate<InteractiveTreeItem> { constructor( @ILogService private readonly logService: ILogService ) { } private _traceLayout(method: string, message: string) { if (forceVerboseLayoutTracing) { this.logService.info(`InteractiveSessionListDelegate#${method}: ${message}`); } else { this.logService.trace(`InteractiveSessionListDelegate#${method}: ${message}`); } } getHeight(element: InteractiveTreeItem): number { const kind = isRequestVM(element) ? 'request' : 'response'; const height = ('currentRenderedHeight' in element ? element.currentRenderedHeight : undefined) ?? 200; this._traceLayout('getHeight', `${kind}, height=${height}`); return height; } getTemplateId(element: InteractiveTreeItem): string { return InteractiveListItemRenderer.ID; } hasDynamicHeight(element: InteractiveTreeItem): boolean { return true; } } export class InteractiveSessionAccessibilityProvider implements IListAccessibilityProvider<InteractiveTreeItem> { getWidgetAriaLabel(): string { return localize('interactiveSession', "Interactive Session"); } getAriaLabel(element: InteractiveTreeItem): string { if (isRequestVM(element)) { return localize('interactiveRequest', "Request: {0}", element.messageText); } if (isResponseVM(element)) { return localize('interactiveResponse', "Response: {0}", element.response.value); } return ''; } } interface IInteractiveResultCodeBlockData { text: string; languageId: string; codeBlockIndex: number; element: InteractiveTreeItem; parentContextKeyService: IContextKeyService; } interface IInteractiveResultCodeBlockPart { readonly onDidChangeContentHeight: Event<number>; readonly element: HTMLElement; readonly textModel: ITextModel; layout(width: number): void; render(data: IInteractiveResultCodeBlockData, width: number): void; dispose(): void; } export interface IInteractiveResultCodeBlockInfo { providerId: string; responseId: string; codeBlockIndex: number; } export const codeBlockInfosByModelUri = new ResourceMap<IInteractiveResultCodeBlockInfo>(); class CodeBlockPart extends Disposable implements IInteractiveResultCodeBlockPart { private readonly _onDidChangeContentHeight = this._register(new Emitter<number>()); public readonly onDidChangeContentHeight = this._onDidChangeContentHeight.event; private readonly editor: CodeEditorWidget; private readonly toolbar: MenuWorkbenchToolBar; private readonly contextKeyService: IContextKeyService; public readonly textModel: ITextModel; public readonly element: HTMLElement; constructor( private readonly options: InteractiveSessionEditorOptions, @IInstantiationService instantiationService: IInstantiationService, @IContextKeyService contextKeyService: IContextKeyService, @ILanguageService private readonly languageService: ILanguageService, @IModelService private readonly modelService: IModelService, ) { super(); this.element = $('.interactive-result-editor-wrapper'); this.contextKeyService = this._register(contextKeyService.createScoped(this.element)); const scopedInstantiationService = instantiationService.createChild(new ServiceCollection([IContextKeyService, this.contextKeyService])); this.toolbar = this._register(scopedInstantiationService.createInstance(MenuWorkbenchToolBar, this.element, MenuId.InteractiveSessionCodeBlock, { menuOptions: { shouldForwardArgs: true } })); const editorElement = dom.append(this.element, $('.interactive-result-editor')); this.editor = this._register(scopedInstantiationService.createInstance(CodeEditorWidget, editorElement, { ...getSimpleEditorOptions(), readOnly: true, lineNumbers: 'off', selectOnLineNumbers: true, scrollBeyondLastLine: false, lineDecorationsWidth: 8, dragAndDrop: false, padding: { top: 2, bottom: 2 }, mouseWheelZoom: false, scrollbar: { alwaysConsumeMouseWheel: false }, ...this.getEditorOptionsFromConfig() }, { isSimpleWidget: true, contributions: EditorExtensionsRegistry.getSomeEditorContributions([ MenuPreventer.ID, SelectionClipboardContributionID, ContextMenuController.ID, WordHighlighterContribution.ID, ViewportSemanticTokensContribution.ID, BracketMatchingController.ID, SmartSelectController.ID, ]) })); this._register(this.options.onDidChange(() => { this.editor.updateOptions(this.getEditorOptionsFromConfig()); })); this._register(this.editor.onDidContentSizeChange(e => { if (e.contentHeightChanged) { this._onDidChangeContentHeight.fire(e.contentHeight); } })); this._register(this.editor.onDidBlurEditorWidget(() => { WordHighlighterContribution.get(this.editor)?.stopHighlighting(); })); this._register(this.editor.onDidFocusEditorWidget(() => { WordHighlighterContribution.get(this.editor)?.restoreViewState(true); })); const vscodeLanguageId = this.languageService.getLanguageIdByLanguageName('javascript'); this.textModel = this._register(this.modelService.createModel('', this.languageService.createById(vscodeLanguageId), undefined)); this.editor.setModel(this.textModel); } private getEditorOptionsFromConfig(): IEditorOptions { return { wordWrap: this.options.configuration.resultEditor.wordWrap, bracketPairColorization: this.options.configuration.resultEditor.bracketPairColorization, fontFamily: this.options.configuration.resultEditor.fontFamily === 'default' ? EDITOR_FONT_DEFAULTS.fontFamily : this.options.configuration.resultEditor.fontFamily, fontSize: this.options.configuration.resultEditor.fontSize, fontWeight: this.options.configuration.resultEditor.fontWeight, lineHeight: this.options.configuration.resultEditor.lineHeight, }; } layout(width: number): void { const realContentHeight = this.editor.getContentHeight(); const editorBorder = 2; this.editor.layout({ width: width - editorBorder, height: realContentHeight }); } render(data: IInteractiveResultCodeBlockData, width: number): void { this.contextKeyService.updateParent(data.parentContextKeyService); if (this.options.configuration.resultEditor.wordWrap === 'on') { // Intialize the editor with the new proper width so that getContentHeight // will be computed correctly in the next call to layout() this.layout(width); } this.setText(data.text); this.setLanguage(data.languageId); this.layout(width); if (isResponseVM(data.element) && data.element.providerResponseId) { // For telemetry reporting codeBlockInfosByModelUri.set(this.textModel.uri, { providerId: data.element.providerId, responseId: data.element.providerResponseId, codeBlockIndex: data.codeBlockIndex }); } else { codeBlockInfosByModelUri.delete(this.textModel.uri); } this.toolbar.context = <IInteractiveSessionCodeBlockActionContext>{ code: data.text, codeBlockIndex: data.codeBlockIndex, element: data.element }; } private setText(newText: string): void { let currentText = this.textModel.getLinesContent().join('\n'); if (newText === currentText) { return; } let removedChars = 0; if (currentText.endsWith(` ${InteractiveListItemRenderer.cursorCharacter}`)) { removedChars = 2; } else if (currentText.endsWith(InteractiveListItemRenderer.cursorCharacter)) { removedChars = 1; } if (removedChars > 0) { currentText = currentText.slice(0, currentText.length - removedChars); } if (newText.startsWith(currentText)) { const text = newText.slice(currentText.length); const lastLine = this.textModel.getLineCount(); const lastCol = this.textModel.getLineMaxColumn(lastLine); const insertAtCol = lastCol - removedChars; this.textModel.applyEdits([{ range: new Range(lastLine, insertAtCol, lastLine, lastCol), text }]); } else { // console.log(`Failed to optimize setText`); this.textModel.setValue(newText); } } private setLanguage(languageId: string): void { const vscodeLanguageId = this.languageService.getLanguageIdByLanguageName(languageId); if (vscodeLanguageId) { this.textModel.setLanguage(vscodeLanguageId); } } } interface IDisposableReference<T> extends IDisposable { object: T; } class EditorPool extends Disposable { private _pool: ResourcePool<IInteractiveResultCodeBlockPart>; public get inUse(): ReadonlySet<IInteractiveResultCodeBlockPart> { return this._pool.inUse; } constructor( private readonly options: InteractiveSessionEditorOptions, @IInstantiationService private readonly instantiationService: IInstantiationService, ) { super(); this._pool = this._register(new ResourcePool(() => this.editorFactory())); // TODO listen to changes on options } private editorFactory(): IInteractiveResultCodeBlockPart { return this.instantiationService.createInstance(CodeBlockPart, this.options); } get(): IDisposableReference<IInteractiveResultCodeBlockPart> { const object = this._pool.get(); return { object, dispose: () => this._pool.release(object) }; } } // TODO does something in lifecycle.ts cover this? class ResourcePool<T extends IDisposable> extends Disposable { private readonly pool: T[] = []; private _inUse = new Set<T>; public get inUse(): ReadonlySet<T> { return this._inUse; } constructor( private readonly _itemFactory: () => T, ) { super(); } get(): T { if (this.pool.length > 0) { const item = this.pool.pop()!; this._inUse.add(item); return item; } const item = this._register(this._itemFactory()); this._inUse.add(item); return item; } release(item: T): void { this._inUse.delete(item); this.pool.push(item); } }
src/vs/workbench/contrib/interactiveSession/browser/interactiveSessionListRenderer.ts
1
https://github.com/microsoft/vscode/commit/324d1a25760c6abeb4a0492c0c5a22795b695bf4
[ 0.9986333250999451, 0.08530440926551819, 0.00016360660083591938, 0.00017835495236795396, 0.2707592248916626 ]
{ "id": 11, "code_window": [ "import { IMarkdownString, MarkdownString } from 'vs/base/common/htmlContent';\n", "import { Disposable } from 'vs/base/common/lifecycle';\n", "import { URI } from 'vs/base/common/uri';\n", "import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';\n", "import { ILogService } from 'vs/platform/log/common/log';\n", "import { IInteractiveRequestModel, IInteractiveResponseErrorDetails, IInteractiveResponseModel, IInteractiveSessionModel, IInteractiveSessionWelcomeMessageModel, IInteractiveWelcomeMessageContent } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionModel';\n", "import { IInteractiveSessionReplyFollowup, IInteractiveSessionResponseCommandFollowup, IInteractiveSessionService, InteractiveSessionVoteDirection } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionService';\n", "import { countWords } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionWordCounter';\n", "\n", "export function isRequestVM(item: unknown): item is IInteractiveRequestViewModel {\n", "\treturn !!item && typeof item === 'object' && 'message' in item;\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { IInteractiveRequestModel, IInteractiveResponseModel, IInteractiveSessionModel, IInteractiveSessionWelcomeMessageModel, IInteractiveWelcomeMessageContent } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionModel';\n", "import { IInteractiveResponseErrorDetails, IInteractiveSessionReplyFollowup, IInteractiveSessionResponseCommandFollowup, IInteractiveSessionService, InteractiveSessionVoteDirection } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionService';\n" ], "file_path": "src/vs/workbench/contrib/interactiveSession/common/interactiveSessionViewModel.ts", "type": "replace", "edit_start_line_idx": 11 }
'use strict'; var M; (function (M) { var C = (function () { function C() { } return C; })(); (function (x, property, number) { if (property === undefined) { property = w; } var local = 1; // unresolved symbol because x is local //self.x++; self.w--; // ok because w is a property property; f = function (y) { return y + x + local + w + self.w; }; function sum(z) { return z + f(z) + w + self.w; } }); })(M || (M = {})); var c = new M.C(12, 5);
src/vs/platform/files/test/node/fixtures/resolver/examples/small.js
0
https://github.com/microsoft/vscode/commit/324d1a25760c6abeb4a0492c0c5a22795b695bf4
[ 0.00017247104551643133, 0.0001713295205263421, 0.00017014278273563832, 0.00017137468967121094, 9.510461040918017e-7 ]
{ "id": 11, "code_window": [ "import { IMarkdownString, MarkdownString } from 'vs/base/common/htmlContent';\n", "import { Disposable } from 'vs/base/common/lifecycle';\n", "import { URI } from 'vs/base/common/uri';\n", "import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';\n", "import { ILogService } from 'vs/platform/log/common/log';\n", "import { IInteractiveRequestModel, IInteractiveResponseErrorDetails, IInteractiveResponseModel, IInteractiveSessionModel, IInteractiveSessionWelcomeMessageModel, IInteractiveWelcomeMessageContent } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionModel';\n", "import { IInteractiveSessionReplyFollowup, IInteractiveSessionResponseCommandFollowup, IInteractiveSessionService, InteractiveSessionVoteDirection } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionService';\n", "import { countWords } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionWordCounter';\n", "\n", "export function isRequestVM(item: unknown): item is IInteractiveRequestViewModel {\n", "\treturn !!item && typeof item === 'object' && 'message' in item;\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { IInteractiveRequestModel, IInteractiveResponseModel, IInteractiveSessionModel, IInteractiveSessionWelcomeMessageModel, IInteractiveWelcomeMessageContent } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionModel';\n", "import { IInteractiveResponseErrorDetails, IInteractiveSessionReplyFollowup, IInteractiveSessionResponseCommandFollowup, IInteractiveSessionService, InteractiveSessionVoteDirection } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionService';\n" ], "file_path": "src/vs/workbench/contrib/interactiveSession/common/interactiveSessionViewModel.ts", "type": "replace", "edit_start_line_idx": 11 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // // PLEASE DO NOT MODIFY / DELETE UNLESS YOU KNOW WHAT YOU ARE DOING // // This file is providing the test runner to use when running extension tests. // By default the test runner in use is Mocha based. // // You can provide your own test runner if you want to override it by exporting // a function run(testRoot: string, clb: (error:Error) => void) that the extension // host can call to run the tests. The test runner is expected to use console.log // to report the results back to the caller. When the tests are finished, return // a possible error to the callback or null if none. const testRunner = require('../../../../../test/integration/electron/testrunner'); // You can directly control Mocha options by uncommenting the following lines // See https://github.com/mochajs/mocha/wiki/Using-mocha-programmatically#set-options for more info testRunner.configure({ ui: 'tdd', // the TDD UI is being used in extension.test.ts (suite, test, etc.) color: true, timeout: 60000, }); export = testRunner;
extensions/typescript-language-features/src/test/unit/index.ts
0
https://github.com/microsoft/vscode/commit/324d1a25760c6abeb4a0492c0c5a22795b695bf4
[ 0.00017129005573224276, 0.00016951216093730181, 0.00016774404502939433, 0.0001695023529464379, 0.0000014476693195319967 ]
{ "id": 11, "code_window": [ "import { IMarkdownString, MarkdownString } from 'vs/base/common/htmlContent';\n", "import { Disposable } from 'vs/base/common/lifecycle';\n", "import { URI } from 'vs/base/common/uri';\n", "import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';\n", "import { ILogService } from 'vs/platform/log/common/log';\n", "import { IInteractiveRequestModel, IInteractiveResponseErrorDetails, IInteractiveResponseModel, IInteractiveSessionModel, IInteractiveSessionWelcomeMessageModel, IInteractiveWelcomeMessageContent } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionModel';\n", "import { IInteractiveSessionReplyFollowup, IInteractiveSessionResponseCommandFollowup, IInteractiveSessionService, InteractiveSessionVoteDirection } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionService';\n", "import { countWords } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionWordCounter';\n", "\n", "export function isRequestVM(item: unknown): item is IInteractiveRequestViewModel {\n", "\treturn !!item && typeof item === 'object' && 'message' in item;\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { IInteractiveRequestModel, IInteractiveResponseModel, IInteractiveSessionModel, IInteractiveSessionWelcomeMessageModel, IInteractiveWelcomeMessageContent } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionModel';\n", "import { IInteractiveResponseErrorDetails, IInteractiveSessionReplyFollowup, IInteractiveSessionResponseCommandFollowup, IInteractiveSessionService, InteractiveSessionVoteDirection } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionService';\n" ], "file_path": "src/vs/workbench/contrib/interactiveSession/common/interactiveSessionViewModel.ts", "type": "replace", "edit_start_line_idx": 11 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { deepStrictEqual, strictEqual } from 'assert'; import { IStringDictionary } from 'vs/base/common/collections'; import { isWindows, OperatingSystem, Platform } from 'vs/base/common/platform'; import { URI as Uri } from 'vs/base/common/uri'; import { addTerminalEnvironmentKeys, createTerminalEnvironment, getCwd, getDefaultShell, getLangEnvVariable, mergeEnvironments, preparePathForShell, shouldSetLangEnvVariable } from 'vs/workbench/contrib/terminal/common/terminalEnvironment'; import { PosixShellType, WindowsShellType } from 'vs/platform/terminal/common/terminal'; suite('Workbench - TerminalEnvironment', () => { suite('addTerminalEnvironmentKeys', () => { test('should set expected variables', () => { const env: { [key: string]: any } = {}; addTerminalEnvironmentKeys(env, '1.2.3', 'en', 'on'); strictEqual(env['TERM_PROGRAM'], 'vscode'); strictEqual(env['TERM_PROGRAM_VERSION'], '1.2.3'); strictEqual(env['COLORTERM'], 'truecolor'); strictEqual(env['LANG'], 'en_US.UTF-8'); }); test('should use language variant for LANG that is provided in locale', () => { const env: { [key: string]: any } = {}; addTerminalEnvironmentKeys(env, '1.2.3', 'en-au', 'on'); strictEqual(env['LANG'], 'en_AU.UTF-8', 'LANG is equal to the requested locale with UTF-8'); }); test('should fallback to en_US when no locale is provided', () => { const env2: { [key: string]: any } = { FOO: 'bar' }; addTerminalEnvironmentKeys(env2, '1.2.3', undefined, 'on'); strictEqual(env2['LANG'], 'en_US.UTF-8', 'LANG is equal to en_US.UTF-8 as fallback.'); // More info on issue #14586 }); test('should fallback to en_US when an invalid locale is provided', () => { const env3 = { LANG: 'replace' }; addTerminalEnvironmentKeys(env3, '1.2.3', undefined, 'on'); strictEqual(env3['LANG'], 'en_US.UTF-8', 'LANG is set to the fallback LANG'); }); test('should override existing LANG', () => { const env4 = { LANG: 'en_AU.UTF-8' }; addTerminalEnvironmentKeys(env4, '1.2.3', undefined, 'on'); strictEqual(env4['LANG'], 'en_US.UTF-8', 'LANG is equal to the parent environment\'s LANG'); }); }); suite('shouldSetLangEnvVariable', () => { test('auto', () => { strictEqual(shouldSetLangEnvVariable({}, 'auto'), true); strictEqual(shouldSetLangEnvVariable({ LANG: 'en-US' }, 'auto'), true); strictEqual(shouldSetLangEnvVariable({ LANG: 'en-US.utf' }, 'auto'), true); strictEqual(shouldSetLangEnvVariable({ LANG: 'en-US.utf8' }, 'auto'), false); strictEqual(shouldSetLangEnvVariable({ LANG: 'en-US.UTF-8' }, 'auto'), false); }); test('off', () => { strictEqual(shouldSetLangEnvVariable({}, 'off'), false); strictEqual(shouldSetLangEnvVariable({ LANG: 'en-US' }, 'off'), false); strictEqual(shouldSetLangEnvVariable({ LANG: 'en-US.utf' }, 'off'), false); strictEqual(shouldSetLangEnvVariable({ LANG: 'en-US.utf8' }, 'off'), false); strictEqual(shouldSetLangEnvVariable({ LANG: 'en-US.UTF-8' }, 'off'), false); }); test('on', () => { strictEqual(shouldSetLangEnvVariable({}, 'on'), true); strictEqual(shouldSetLangEnvVariable({ LANG: 'en-US' }, 'on'), true); strictEqual(shouldSetLangEnvVariable({ LANG: 'en-US.utf' }, 'on'), true); strictEqual(shouldSetLangEnvVariable({ LANG: 'en-US.utf8' }, 'on'), true); strictEqual(shouldSetLangEnvVariable({ LANG: 'en-US.UTF-8' }, 'on'), true); }); }); suite('getLangEnvVariable', () => { test('should fallback to en_US when no locale is provided', () => { strictEqual(getLangEnvVariable(undefined), 'en_US.UTF-8'); strictEqual(getLangEnvVariable(''), 'en_US.UTF-8'); }); test('should fallback to default language variants when variant isn\'t provided', () => { strictEqual(getLangEnvVariable('af'), 'af_ZA.UTF-8'); strictEqual(getLangEnvVariable('am'), 'am_ET.UTF-8'); strictEqual(getLangEnvVariable('be'), 'be_BY.UTF-8'); strictEqual(getLangEnvVariable('bg'), 'bg_BG.UTF-8'); strictEqual(getLangEnvVariable('ca'), 'ca_ES.UTF-8'); strictEqual(getLangEnvVariable('cs'), 'cs_CZ.UTF-8'); strictEqual(getLangEnvVariable('da'), 'da_DK.UTF-8'); strictEqual(getLangEnvVariable('de'), 'de_DE.UTF-8'); strictEqual(getLangEnvVariable('el'), 'el_GR.UTF-8'); strictEqual(getLangEnvVariable('en'), 'en_US.UTF-8'); strictEqual(getLangEnvVariable('es'), 'es_ES.UTF-8'); strictEqual(getLangEnvVariable('et'), 'et_EE.UTF-8'); strictEqual(getLangEnvVariable('eu'), 'eu_ES.UTF-8'); strictEqual(getLangEnvVariable('fi'), 'fi_FI.UTF-8'); strictEqual(getLangEnvVariable('fr'), 'fr_FR.UTF-8'); strictEqual(getLangEnvVariable('he'), 'he_IL.UTF-8'); strictEqual(getLangEnvVariable('hr'), 'hr_HR.UTF-8'); strictEqual(getLangEnvVariable('hu'), 'hu_HU.UTF-8'); strictEqual(getLangEnvVariable('hy'), 'hy_AM.UTF-8'); strictEqual(getLangEnvVariable('is'), 'is_IS.UTF-8'); strictEqual(getLangEnvVariable('it'), 'it_IT.UTF-8'); strictEqual(getLangEnvVariable('ja'), 'ja_JP.UTF-8'); strictEqual(getLangEnvVariable('kk'), 'kk_KZ.UTF-8'); strictEqual(getLangEnvVariable('ko'), 'ko_KR.UTF-8'); strictEqual(getLangEnvVariable('lt'), 'lt_LT.UTF-8'); strictEqual(getLangEnvVariable('nl'), 'nl_NL.UTF-8'); strictEqual(getLangEnvVariable('no'), 'no_NO.UTF-8'); strictEqual(getLangEnvVariable('pl'), 'pl_PL.UTF-8'); strictEqual(getLangEnvVariable('pt'), 'pt_BR.UTF-8'); strictEqual(getLangEnvVariable('ro'), 'ro_RO.UTF-8'); strictEqual(getLangEnvVariable('ru'), 'ru_RU.UTF-8'); strictEqual(getLangEnvVariable('sk'), 'sk_SK.UTF-8'); strictEqual(getLangEnvVariable('sl'), 'sl_SI.UTF-8'); strictEqual(getLangEnvVariable('sr'), 'sr_YU.UTF-8'); strictEqual(getLangEnvVariable('sv'), 'sv_SE.UTF-8'); strictEqual(getLangEnvVariable('tr'), 'tr_TR.UTF-8'); strictEqual(getLangEnvVariable('uk'), 'uk_UA.UTF-8'); strictEqual(getLangEnvVariable('zh'), 'zh_CN.UTF-8'); }); test('should set language variant based on full locale', () => { strictEqual(getLangEnvVariable('en-AU'), 'en_AU.UTF-8'); strictEqual(getLangEnvVariable('en-au'), 'en_AU.UTF-8'); strictEqual(getLangEnvVariable('fa-ke'), 'fa_KE.UTF-8'); }); }); suite('mergeEnvironments', () => { test('should add keys', () => { const parent = { a: 'b' }; const other = { c: 'd' }; mergeEnvironments(parent, other); deepStrictEqual(parent, { a: 'b', c: 'd' }); }); (!isWindows ? test.skip : test)('should add keys ignoring case on Windows', () => { const parent = { a: 'b' }; const other = { A: 'c' }; mergeEnvironments(parent, other); deepStrictEqual(parent, { a: 'c' }); }); test('null values should delete keys from the parent env', () => { const parent = { a: 'b', c: 'd' }; const other: IStringDictionary<string | null> = { a: null }; mergeEnvironments(parent, other); deepStrictEqual(parent, { c: 'd' }); }); (!isWindows ? test.skip : test)('null values should delete keys from the parent env ignoring case on Windows', () => { const parent = { a: 'b', c: 'd' }; const other: IStringDictionary<string | null> = { A: null }; mergeEnvironments(parent, other); deepStrictEqual(parent, { c: 'd' }); }); }); suite('getCwd', () => { // This helper checks the paths in a cross-platform friendly manner function assertPathsMatch(a: string, b: string): void { strictEqual(Uri.file(a).fsPath, Uri.file(b).fsPath); } test('should default to userHome for an empty workspace', async () => { assertPathsMatch(await getCwd({ executable: undefined, args: [] }, '/userHome/', undefined, undefined, undefined), '/userHome/'); }); test('should use to the workspace if it exists', async () => { assertPathsMatch(await getCwd({ executable: undefined, args: [] }, '/userHome/', undefined, Uri.file('/foo'), undefined), '/foo'); }); test('should use an absolute custom cwd as is', async () => { assertPathsMatch(await getCwd({ executable: undefined, args: [] }, '/userHome/', undefined, undefined, '/foo'), '/foo'); }); test('should normalize a relative custom cwd against the workspace path', async () => { assertPathsMatch(await getCwd({ executable: undefined, args: [] }, '/userHome/', undefined, Uri.file('/bar'), 'foo'), '/bar/foo'); assertPathsMatch(await getCwd({ executable: undefined, args: [] }, '/userHome/', undefined, Uri.file('/bar'), './foo'), '/bar/foo'); assertPathsMatch(await getCwd({ executable: undefined, args: [] }, '/userHome/', undefined, Uri.file('/bar'), '../foo'), '/foo'); }); test('should fall back for relative a custom cwd that doesn\'t have a workspace', async () => { assertPathsMatch(await getCwd({ executable: undefined, args: [] }, '/userHome/', undefined, undefined, 'foo'), '/userHome/'); assertPathsMatch(await getCwd({ executable: undefined, args: [] }, '/userHome/', undefined, undefined, './foo'), '/userHome/'); assertPathsMatch(await getCwd({ executable: undefined, args: [] }, '/userHome/', undefined, undefined, '../foo'), '/userHome/'); }); test('should ignore custom cwd when told to ignore', async () => { assertPathsMatch(await getCwd({ executable: undefined, args: [], ignoreConfigurationCwd: true }, '/userHome/', undefined, Uri.file('/bar'), '/foo'), '/bar'); }); }); suite('getDefaultShell', () => { test('should change Sysnative to System32 in non-WoW64 systems', async () => { const shell = await getDefaultShell(key => { return ({ 'terminal.integrated.shell.windows': 'C:\\Windows\\Sysnative\\cmd.exe' } as any)[key]; }, 'DEFAULT', false, 'C:\\Windows', undefined, {} as any, false, Platform.Windows); strictEqual(shell, 'C:\\Windows\\System32\\cmd.exe'); }); test('should not change Sysnative to System32 in WoW64 systems', async () => { const shell = await getDefaultShell(key => { return ({ 'terminal.integrated.shell.windows': 'C:\\Windows\\Sysnative\\cmd.exe' } as any)[key]; }, 'DEFAULT', true, 'C:\\Windows', undefined, {} as any, false, Platform.Windows); strictEqual(shell, 'C:\\Windows\\Sysnative\\cmd.exe'); }); test('should use automationShell when specified', async () => { const shell1 = await getDefaultShell(key => { return ({ 'terminal.integrated.shell.windows': 'shell', 'terminal.integrated.automationShell.windows': undefined } as any)[key]; }, 'DEFAULT', false, 'C:\\Windows', undefined, {} as any, false, Platform.Windows); strictEqual(shell1, 'shell', 'automationShell was false'); const shell2 = await getDefaultShell(key => { return ({ 'terminal.integrated.shell.windows': 'shell', 'terminal.integrated.automationShell.windows': undefined } as any)[key]; }, 'DEFAULT', false, 'C:\\Windows', undefined, {} as any, true, Platform.Windows); strictEqual(shell2, 'shell', 'automationShell was true'); const shell3 = await getDefaultShell(key => { return ({ 'terminal.integrated.shell.windows': 'shell', 'terminal.integrated.automationShell.windows': 'automationShell' } as any)[key]; }, 'DEFAULT', false, 'C:\\Windows', undefined, {} as any, true, Platform.Windows); strictEqual(shell3, 'automationShell', 'automationShell was true and specified in settings'); }); }); suite('preparePathForShell', () => { const wslPathBackend = { getWslPath: async (original: string, direction: 'unix-to-win' | 'win-to-unix') => { if (direction === 'unix-to-win') { const match = original.match(/^\/mnt\/(?<drive>[a-zA-Z])\/(?<path>.+)$/); const groups = match?.groups; if (!groups) { return original; } return `${groups.drive}:\\${groups.path.replace(/\//g, '\\')}`; } const match = original.match(/(?<drive>[a-zA-Z]):\\(?<path>.+)/); const groups = match?.groups; if (!groups) { return original; } return `/mnt/${groups.drive.toLowerCase()}/${groups.path.replace(/\\/g, '/')}`; } }; suite('Windows frontend, Windows backend', () => { test('Command Prompt', async () => { strictEqual(await preparePathForShell('c:\\foo\\bar', 'cmd', 'cmd', WindowsShellType.CommandPrompt, wslPathBackend, OperatingSystem.Windows, true), `c:\\foo\\bar`); strictEqual(await preparePathForShell('c:\\foo\\bar\'baz', 'cmd', 'cmd', WindowsShellType.CommandPrompt, wslPathBackend, OperatingSystem.Windows, true), `c:\\foo\\bar'baz`); strictEqual(await preparePathForShell('c:\\foo\\bar$(echo evil)baz', 'cmd', 'cmd', WindowsShellType.CommandPrompt, wslPathBackend, OperatingSystem.Windows, true), `"c:\\foo\\bar$(echo evil)baz"`); }); test('PowerShell', async () => { strictEqual(await preparePathForShell('c:\\foo\\bar', 'pwsh', 'pwsh', WindowsShellType.PowerShell, wslPathBackend, OperatingSystem.Windows, true), `c:\\foo\\bar`); strictEqual(await preparePathForShell('c:\\foo\\bar\'baz', 'pwsh', 'pwsh', WindowsShellType.PowerShell, wslPathBackend, OperatingSystem.Windows, true), `& 'c:\\foo\\bar''baz'`); strictEqual(await preparePathForShell('c:\\foo\\bar$(echo evil)baz', 'pwsh', 'pwsh', WindowsShellType.PowerShell, wslPathBackend, OperatingSystem.Windows, true), `& 'c:\\foo\\bar$(echo evil)baz'`); }); test('Git Bash', async () => { strictEqual(await preparePathForShell('c:\\foo\\bar', 'bash', 'bash', WindowsShellType.GitBash, wslPathBackend, OperatingSystem.Windows, true), `'c:/foo/bar'`); strictEqual(await preparePathForShell('c:\\foo\\bar$(echo evil)baz', 'bash', 'bash', WindowsShellType.GitBash, wslPathBackend, OperatingSystem.Windows, true), `'c:/foo/bar(echo evil)baz'`); }); test('WSL', async () => { strictEqual(await preparePathForShell('c:\\foo\\bar', 'bash', 'bash', WindowsShellType.Wsl, wslPathBackend, OperatingSystem.Windows, true), '/mnt/c/foo/bar'); }); }); suite('Windows frontend, Linux backend', () => { test('Bash', async () => { strictEqual(await preparePathForShell('/foo/bar', 'bash', 'bash', PosixShellType.Bash, wslPathBackend, OperatingSystem.Linux, true), `'/foo/bar'`); strictEqual(await preparePathForShell('/foo/bar\'baz', 'bash', 'bash', PosixShellType.Bash, wslPathBackend, OperatingSystem.Linux, true), `'/foo/barbaz'`); strictEqual(await preparePathForShell('/foo/bar$(echo evil)baz', 'bash', 'bash', PosixShellType.Bash, wslPathBackend, OperatingSystem.Linux, true), `'/foo/bar(echo evil)baz'`); }); }); suite('Linux frontend, Windows backend', () => { test('Command Prompt', async () => { strictEqual(await preparePathForShell('c:\\foo\\bar', 'cmd', 'cmd', WindowsShellType.CommandPrompt, wslPathBackend, OperatingSystem.Windows, false), `c:\\foo\\bar`); strictEqual(await preparePathForShell('c:\\foo\\bar\'baz', 'cmd', 'cmd', WindowsShellType.CommandPrompt, wslPathBackend, OperatingSystem.Windows, false), `c:\\foo\\bar'baz`); strictEqual(await preparePathForShell('c:\\foo\\bar$(echo evil)baz', 'cmd', 'cmd', WindowsShellType.CommandPrompt, wslPathBackend, OperatingSystem.Windows, false), `"c:\\foo\\bar$(echo evil)baz"`); }); test('PowerShell', async () => { strictEqual(await preparePathForShell('c:\\foo\\bar', 'pwsh', 'pwsh', WindowsShellType.PowerShell, wslPathBackend, OperatingSystem.Windows, false), `c:\\foo\\bar`); strictEqual(await preparePathForShell('c:\\foo\\bar\'baz', 'pwsh', 'pwsh', WindowsShellType.PowerShell, wslPathBackend, OperatingSystem.Windows, false), `& 'c:\\foo\\bar''baz'`); strictEqual(await preparePathForShell('c:\\foo\\bar$(echo evil)baz', 'pwsh', 'pwsh', WindowsShellType.PowerShell, wslPathBackend, OperatingSystem.Windows, false), `& 'c:\\foo\\bar$(echo evil)baz'`); }); test('Git Bash', async () => { strictEqual(await preparePathForShell('c:\\foo\\bar', 'bash', 'bash', WindowsShellType.GitBash, wslPathBackend, OperatingSystem.Windows, false), `'c:/foo/bar'`); strictEqual(await preparePathForShell('c:\\foo\\bar$(echo evil)baz', 'bash', 'bash', WindowsShellType.GitBash, wslPathBackend, OperatingSystem.Windows, false), `'c:/foo/bar(echo evil)baz'`); }); test('WSL', async () => { strictEqual(await preparePathForShell('c:\\foo\\bar', 'bash', 'bash', WindowsShellType.Wsl, wslPathBackend, OperatingSystem.Windows, false), '/mnt/c/foo/bar'); }); }); suite('Linux frontend, Linux backend', () => { test('Bash', async () => { strictEqual(await preparePathForShell('/foo/bar', 'bash', 'bash', PosixShellType.Bash, wslPathBackend, OperatingSystem.Linux, false), `'/foo/bar'`); strictEqual(await preparePathForShell('/foo/bar\'baz', 'bash', 'bash', PosixShellType.Bash, wslPathBackend, OperatingSystem.Linux, false), `'/foo/barbaz'`); strictEqual(await preparePathForShell('/foo/bar$(echo evil)baz', 'bash', 'bash', PosixShellType.Bash, wslPathBackend, OperatingSystem.Linux, false), `'/foo/bar(echo evil)baz'`); }); }); }); suite('createTerminalEnvironment', () => { const commonVariables = { COLORTERM: 'truecolor', TERM_PROGRAM: 'vscode' }; test('should retain variables equal to the empty string', async () => { deepStrictEqual( await createTerminalEnvironment({}, undefined, undefined, undefined, 'off', { foo: 'bar', empty: '' }), { foo: 'bar', empty: '', ...commonVariables } ); }); }); });
src/vs/workbench/contrib/terminal/test/common/terminalEnvironment.test.ts
0
https://github.com/microsoft/vscode/commit/324d1a25760c6abeb4a0492c0c5a22795b695bf4
[ 0.0001743997709127143, 0.0001714882964733988, 0.0001658670953474939, 0.0001717801787890494, 0.0000021307180304575013 ]
{ "id": 12, "code_window": [ "\t}\n", "\n", "\texport interface InteractiveResponseErrorDetails {\n", "\t\tmessage: string;\n", "\t\tresponseIsIncomplete?: boolean;\n", "\t}\n", "\n", "\texport interface InteractiveResponseForProgress {\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\tresponseIsFiltered?: boolean;\n" ], "file_path": "src/vscode-dts/vscode.proposed.interactive.d.ts", "type": "add", "edit_start_line_idx": 103 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as dom from 'vs/base/browser/dom'; import { renderIcon } from 'vs/base/browser/ui/iconLabel/iconLabels'; import { IListVirtualDelegate } from 'vs/base/browser/ui/list/list'; import { IListAccessibilityProvider } from 'vs/base/browser/ui/list/listWidget'; import { ITreeNode, ITreeRenderer } from 'vs/base/browser/ui/tree/tree'; import { IntervalTimer } from 'vs/base/common/async'; import { Codicon } from 'vs/base/common/codicons'; import { Emitter, Event } from 'vs/base/common/event'; import { FuzzyScore } from 'vs/base/common/filters'; import { IMarkdownString, MarkdownString } from 'vs/base/common/htmlContent'; import { Disposable, DisposableStore, IDisposable } from 'vs/base/common/lifecycle'; import { ResourceMap } from 'vs/base/common/map'; import { FileAccess } from 'vs/base/common/network'; import { ThemeIcon } from 'vs/base/common/themables'; import { EditorExtensionsRegistry } from 'vs/editor/browser/editorExtensions'; import { CodeEditorWidget } from 'vs/editor/browser/widget/codeEditorWidget'; import { EDITOR_FONT_DEFAULTS, IEditorOptions } from 'vs/editor/common/config/editorOptions'; import { Range } from 'vs/editor/common/core/range'; import { ILanguageService } from 'vs/editor/common/languages/language'; import { ITextModel } from 'vs/editor/common/model'; import { IModelService } from 'vs/editor/common/services/model'; import { BracketMatchingController } from 'vs/editor/contrib/bracketMatching/browser/bracketMatching'; import { ContextMenuController } from 'vs/editor/contrib/contextmenu/browser/contextmenu'; import { IMarkdownRenderResult, MarkdownRenderer } from 'vs/editor/contrib/markdownRenderer/browser/markdownRenderer'; import { ViewportSemanticTokensContribution } from 'vs/editor/contrib/semanticTokens/browser/viewportSemanticTokens'; import { SmartSelectController } from 'vs/editor/contrib/smartSelect/browser/smartSelect'; import { WordHighlighterContribution } from 'vs/editor/contrib/wordHighlighter/browser/wordHighlighter'; import { localize } from 'vs/nls'; import { MenuWorkbenchToolBar } from 'vs/platform/actions/browser/toolbar'; import { MenuId } from 'vs/platform/actions/common/actions'; import { ICommandService } from 'vs/platform/commands/common/commands'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection'; import { ILogService } from 'vs/platform/log/common/log'; import { defaultButtonStyles } from 'vs/platform/theme/browser/defaultStyles'; import { MenuPreventer } from 'vs/workbench/contrib/codeEditor/browser/menuPreventer'; import { SelectionClipboardContributionID } from 'vs/workbench/contrib/codeEditor/browser/selectionClipboard'; import { getSimpleEditorOptions } from 'vs/workbench/contrib/codeEditor/browser/simpleEditorOptions'; import { IInteractiveSessionCodeBlockActionContext } from 'vs/workbench/contrib/interactiveSession/browser/actions/interactiveSessionCodeblockActions'; import { InteractiveSessionFollowups } from 'vs/workbench/contrib/interactiveSession/browser/interactiveSessionFollowups'; import { InteractiveSessionEditorOptions } from 'vs/workbench/contrib/interactiveSession/browser/interactiveSessionOptions'; import { CONTEXT_RESPONSE_HAS_PROVIDER_ID, CONTEXT_RESPONSE_VOTE } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionContextKeys'; import { IInteractiveSessionReplyFollowup, IInteractiveSessionService, IInteractiveSlashCommand, InteractiveSessionVoteDirection } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionService'; import { IInteractiveRequestViewModel, IInteractiveResponseViewModel, IInteractiveWelcomeMessageViewModel, isRequestVM, isResponseVM, isWelcomeVM } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionViewModel'; import { getNWords } from 'vs/workbench/contrib/interactiveSession/common/interactiveSessionWordCounter'; const $ = dom.$; export type InteractiveTreeItem = IInteractiveRequestViewModel | IInteractiveResponseViewModel | IInteractiveWelcomeMessageViewModel; interface IInteractiveListItemTemplate { rowContainer: HTMLElement; titleToolbar: MenuWorkbenchToolBar; avatar: HTMLElement; username: HTMLElement; value: HTMLElement; contextKeyService: IContextKeyService; templateDisposables: IDisposable; elementDisposables: DisposableStore; } interface IItemHeightChangeParams { element: InteractiveTreeItem; height: number; } const forceVerboseLayoutTracing = false; export interface IInteractiveSessionRendererDelegate { getListLength(): number; getSlashCommands(): IInteractiveSlashCommand[]; } export class InteractiveListItemRenderer extends Disposable implements ITreeRenderer<InteractiveTreeItem, FuzzyScore, IInteractiveListItemTemplate> { static readonly cursorCharacter = '\u258c'; static readonly ID = 'item'; private readonly renderer: MarkdownRenderer; protected readonly _onDidClickFollowup = this._register(new Emitter<IInteractiveSessionReplyFollowup>()); readonly onDidClickFollowup: Event<IInteractiveSessionReplyFollowup> = this._onDidClickFollowup.event; protected readonly _onDidChangeItemHeight = this._register(new Emitter<IItemHeightChangeParams>()); readonly onDidChangeItemHeight: Event<IItemHeightChangeParams> = this._onDidChangeItemHeight.event; private readonly _editorPool: EditorPool; private _currentLayoutWidth: number = 0; constructor( private readonly editorOptions: InteractiveSessionEditorOptions, private readonly delegate: IInteractiveSessionRendererDelegate, @IInstantiationService private readonly instantiationService: IInstantiationService, @IConfigurationService private readonly configService: IConfigurationService, @ILogService private readonly logService: ILogService, @ICommandService private readonly commandService: ICommandService, @IContextKeyService private readonly contextKeyService: IContextKeyService, @IInteractiveSessionService private readonly interactiveSessionService: IInteractiveSessionService, ) { super(); this.renderer = this.instantiationService.createInstance(MarkdownRenderer, {}); this._editorPool = this._register(this.instantiationService.createInstance(EditorPool, this.editorOptions)); } get templateId(): string { return InteractiveListItemRenderer.ID; } private traceLayout(method: string, message: string) { if (forceVerboseLayoutTracing) { this.logService.info(`InteractiveListItemRenderer#${method}: ${message}`); } else { this.logService.trace(`InteractiveListItemRenderer#${method}: ${message}`); } } private shouldRenderProgressively(element: IInteractiveResponseViewModel): boolean { return !this.configService.getValue('interactive.experimental.disableProgressiveRendering') && element.progressiveResponseRenderingEnabled; } private getProgressiveRenderRate(element: IInteractiveResponseViewModel): number { const configuredRate = this.configService.getValue('interactive.experimental.progressiveRenderingRate'); if (typeof configuredRate === 'number') { return configuredRate; } if (element.isComplete) { return 60; } if (element.contentUpdateTimings && element.contentUpdateTimings.impliedWordLoadRate) { // This doesn't account for dead time after the last update. When the previous update is the final one and the model is only waiting for followupQuestions, that's good. // When there was one quick update and then you are waiting longer for the next one, that's not good since the rate should be decreasing. // If it's an issue, we can change this to be based on the total time from now to the beginning. const rateBoost = 1.5; return element.contentUpdateTimings.impliedWordLoadRate * rateBoost; } return 8; } layout(width: number): void { this._currentLayoutWidth = width - 40; // TODO Padding this._editorPool.inUse.forEach(editor => { editor.layout(this._currentLayoutWidth); }); } renderTemplate(container: HTMLElement): IInteractiveListItemTemplate { const templateDisposables = new DisposableStore(); const rowContainer = dom.append(container, $('.interactive-item-container')); const header = dom.append(rowContainer, $('.header')); const user = dom.append(header, $('.user')); const avatar = dom.append(user, $('.avatar')); const username = dom.append(user, $('h3.username')); const value = dom.append(rowContainer, $('.value')); const elementDisposables = new DisposableStore(); const contextKeyService = templateDisposables.add(this.contextKeyService.createScoped(rowContainer)); const scopedInstantiationService = this.instantiationService.createChild(new ServiceCollection([IContextKeyService, contextKeyService])); const titleToolbar = templateDisposables.add(scopedInstantiationService.createInstance(MenuWorkbenchToolBar, header, MenuId.InteractiveSessionTitle, { menuOptions: { shouldForwardArgs: true } })); const template: IInteractiveListItemTemplate = { avatar, username, value, rowContainer, elementDisposables, titleToolbar, templateDisposables, contextKeyService }; return template; } renderElement(node: ITreeNode<InteractiveTreeItem, FuzzyScore>, index: number, templateData: IInteractiveListItemTemplate): void { const { element } = node; const kind = isRequestVM(element) ? 'request' : isResponseVM(element) ? 'response' : 'welcome'; this.traceLayout('renderElement', `${kind}, index=${index}`); CONTEXT_RESPONSE_HAS_PROVIDER_ID.bindTo(templateData.contextKeyService).set(isResponseVM(element) && !!element.providerResponseId && !element.isPlaceholder); if (isResponseVM(element)) { CONTEXT_RESPONSE_VOTE.bindTo(templateData.contextKeyService).set(element.vote === InteractiveSessionVoteDirection.Up ? 'up' : element.vote === InteractiveSessionVoteDirection.Down ? 'down' : ''); } else { CONTEXT_RESPONSE_VOTE.bindTo(templateData.contextKeyService).set(''); } templateData.titleToolbar.context = element; templateData.rowContainer.classList.toggle('interactive-request', isRequestVM(element)); templateData.rowContainer.classList.toggle('interactive-response', isResponseVM(element)); templateData.rowContainer.classList.toggle('interactive-welcome', isWelcomeVM(element)); templateData.username.textContent = element.username; if (element.avatarIconUri) { const avatarIcon = dom.$<HTMLImageElement>('img.icon'); avatarIcon.src = FileAccess.uriToBrowserUri(element.avatarIconUri).toString(true); templateData.avatar.replaceChildren(avatarIcon); } else { const defaultIcon = isRequestVM(element) ? Codicon.account : Codicon.hubot; const avatarIcon = dom.$(ThemeIcon.asCSSSelector(defaultIcon)); templateData.avatar.replaceChildren(avatarIcon); } // Do a progressive render if // - This the last response in the list // - And the response is not complete // - Or, we previously started a progressive rendering of this element (if the element is complete, we will finish progressive rendering with a very fast rate) // - And, the feature is not disabled in configuration if (isResponseVM(element) && index === this.delegate.getListLength() - 1 && (!element.isComplete || element.renderData) && this.shouldRenderProgressively(element)) { this.traceLayout('renderElement', `start progressive render ${kind}, index=${index}`); const progressiveRenderingDisposables = templateData.elementDisposables.add(new DisposableStore()); const timer = templateData.elementDisposables.add(new IntervalTimer()); const runProgressiveRender = (initial?: boolean) => { try { if (this.doNextProgressiveRender(element, index, templateData, !!initial, progressiveRenderingDisposables)) { timer.cancel(); } } catch (err) { // Kill the timer if anything went wrong, avoid getting stuck in a nasty rendering loop. timer.cancel(); throw err; } }; runProgressiveRender(true); timer.cancelAndSet(runProgressiveRender, 50); } else if (isResponseVM(element)) { this.basicRenderElement(element.response.value, element, index, templateData, element.isCanceled); } else if (isRequestVM(element)) { this.basicRenderElement(element.messageText, element, index, templateData); } else { this.renderWelcomeMessage(element, templateData); } } private basicRenderElement(markdownValue: string, element: InteractiveTreeItem, index: number, templateData: IInteractiveListItemTemplate, fillInIncompleteTokens = false) { const result = this.renderMarkdown(new MarkdownString(markdownValue), element, templateData.elementDisposables, templateData, fillInIncompleteTokens); dom.clearNode(templateData.value); templateData.value.appendChild(result.element); templateData.elementDisposables.add(result); if (isResponseVM(element) && element.errorDetails?.message) { const errorDetails = dom.append(templateData.value, $('.interactive-response-error-details', undefined, renderIcon(Codicon.error))); errorDetails.appendChild($('span', undefined, element.errorDetails.message)); } if (isResponseVM(element) && element.commandFollowups?.length) { const followupsContainer = dom.append(templateData.value, $('.interactive-response-followups')); templateData.elementDisposables.add(new InteractiveSessionFollowups( followupsContainer, element.commandFollowups, defaultButtonStyles, followup => { this.interactiveSessionService.notifyUserAction({ providerId: element.providerId, action: { kind: 'command', command: followup } }); return this.commandService.executeCommand(followup.commandId, ...(followup.args ?? [])); })); } } private renderWelcomeMessage(element: IInteractiveWelcomeMessageViewModel, templateData: IInteractiveListItemTemplate) { dom.clearNode(templateData.value); const slashCommands = this.delegate.getSlashCommands(); for (const item of element.content) { if (Array.isArray(item)) { templateData.elementDisposables.add(new InteractiveSessionFollowups( templateData.value, item, undefined, followup => this._onDidClickFollowup.fire(followup))); } else { const result = this.renderMarkdown(item as IMarkdownString, element, templateData.elementDisposables, templateData); for (const codeElement of result.element.querySelectorAll('code')) { if (codeElement.textContent && slashCommands.find(command => codeElement.textContent === `/${command.command}`)) { codeElement.classList.add('interactive-slash-command'); } } templateData.value.appendChild(result.element); templateData.elementDisposables.add(result); } } } private doNextProgressiveRender(element: IInteractiveResponseViewModel, index: number, templateData: IInteractiveListItemTemplate, isInRenderElement: boolean, disposables: DisposableStore): boolean { disposables.clear(); let isFullyRendered = false; if (element.isCanceled) { this.traceLayout('runProgressiveRender', `canceled, index=${index}`); element.renderData = undefined; this.basicRenderElement(element.response.value, element, index, templateData, true); isFullyRendered = true; } else { // TODO- this method has the side effect of updating element.renderData const toRender = this.getProgressiveMarkdownToRender(element); isFullyRendered = !!element.renderData?.isFullyRendered; if (isFullyRendered) { // We've reached the end of the available content, so do a normal render this.traceLayout('runProgressiveRender', `end progressive render, index=${index}`); if (element.isComplete) { this.traceLayout('runProgressiveRender', `and disposing renderData, response is complete, index=${index}`); element.renderData = undefined; } else { this.traceLayout('runProgressiveRender', `Rendered all available words, but model is not complete.`); } disposables.clear(); this.basicRenderElement(element.response.value, element, index, templateData, !element.isComplete); } else if (toRender) { // Doing the progressive render const plusCursor = toRender.match(/```.*$/) ? toRender + `\n${InteractiveListItemRenderer.cursorCharacter}` : toRender + ` ${InteractiveListItemRenderer.cursorCharacter}`; const result = this.renderMarkdown(new MarkdownString(plusCursor), element, disposables, templateData, true); dom.clearNode(templateData.value); templateData.value.appendChild(result.element); disposables.add(result); } else { // Nothing new to render, not done, keep waiting return false; } } // Some render happened - update the height const height = templateData.rowContainer.offsetHeight; element.currentRenderedHeight = height; if (!isInRenderElement) { this._onDidChangeItemHeight.fire({ element, height: templateData.rowContainer.offsetHeight }); } return !!isFullyRendered; } private renderMarkdown(markdown: IMarkdownString, element: InteractiveTreeItem, disposables: DisposableStore, templateData: IInteractiveListItemTemplate, fillInIncompleteTokens = false): IMarkdownRenderResult { const disposablesList: IDisposable[] = []; let codeBlockIndex = 0; // TODO if the slash commands stay completely dynamic, this isn't quite right const slashCommands = this.delegate.getSlashCommands(); const usedSlashCommand = slashCommands.find(s => markdown.value.startsWith(`/${s.command} `)); const toRender = usedSlashCommand ? markdown.value.slice(usedSlashCommand.command.length + 2) : markdown.value; markdown = new MarkdownString(toRender); const result = this.renderer.render(markdown, { fillInIncompleteTokens, codeBlockRendererSync: (languageId, text) => { const ref = this.renderCodeBlock({ languageId, text, codeBlockIndex: codeBlockIndex++, element, parentContextKeyService: templateData.contextKeyService }, disposables); // Attach this after updating text/layout of the editor, so it should only be fired when the size updates later (horizontal scrollbar, wrapping) // not during a renderElement OR a progressive render (when we will be firing this event anyway at the end of the render) disposables.add(ref.object.onDidChangeContentHeight(() => { ref.object.layout(this._currentLayoutWidth); this._onDidChangeItemHeight.fire({ element, height: templateData.rowContainer.offsetHeight }); })); disposablesList.push(ref); return ref.object.element; } }); if (usedSlashCommand) { const slashCommandElement = $('span.interactive-slash-command', { title: usedSlashCommand.detail }, `/${usedSlashCommand.command} `); if (result.element.firstChild?.nodeName.toLowerCase() === 'p') { result.element.firstChild.insertBefore(slashCommandElement, result.element.firstChild.firstChild); } else { result.element.insertBefore($('p', undefined, slashCommandElement), result.element.firstChild); } } disposablesList.reverse().forEach(d => disposables.add(d)); return result; } private renderCodeBlock(data: IInteractiveResultCodeBlockData, disposables: DisposableStore): IDisposableReference<IInteractiveResultCodeBlockPart> { const ref = this._editorPool.get(); const editorInfo = ref.object; editorInfo.render(data, this._currentLayoutWidth); return ref; } private getProgressiveMarkdownToRender(element: IInteractiveResponseViewModel): string | undefined { const renderData = element.renderData ?? { renderedWordCount: 0, lastRenderTime: 0 }; const rate = this.getProgressiveRenderRate(element); const numWordsToRender = renderData.lastRenderTime === 0 ? 1 : renderData.renderedWordCount + // Additional words to render beyond what's already rendered Math.floor((Date.now() - renderData.lastRenderTime) / 1000 * rate); if (numWordsToRender === renderData.renderedWordCount) { return undefined; } const result = getNWords(element.response.value, numWordsToRender); element.renderData = { renderedWordCount: result.actualWordCount, lastRenderTime: Date.now(), isFullyRendered: result.isFullString }; return result.value; } disposeElement(node: ITreeNode<InteractiveTreeItem, FuzzyScore>, index: number, templateData: IInteractiveListItemTemplate): void { templateData.elementDisposables.clear(); } disposeTemplate(templateData: IInteractiveListItemTemplate): void { templateData.templateDisposables.dispose(); } } export class InteractiveSessionListDelegate implements IListVirtualDelegate<InteractiveTreeItem> { constructor( @ILogService private readonly logService: ILogService ) { } private _traceLayout(method: string, message: string) { if (forceVerboseLayoutTracing) { this.logService.info(`InteractiveSessionListDelegate#${method}: ${message}`); } else { this.logService.trace(`InteractiveSessionListDelegate#${method}: ${message}`); } } getHeight(element: InteractiveTreeItem): number { const kind = isRequestVM(element) ? 'request' : 'response'; const height = ('currentRenderedHeight' in element ? element.currentRenderedHeight : undefined) ?? 200; this._traceLayout('getHeight', `${kind}, height=${height}`); return height; } getTemplateId(element: InteractiveTreeItem): string { return InteractiveListItemRenderer.ID; } hasDynamicHeight(element: InteractiveTreeItem): boolean { return true; } } export class InteractiveSessionAccessibilityProvider implements IListAccessibilityProvider<InteractiveTreeItem> { getWidgetAriaLabel(): string { return localize('interactiveSession', "Interactive Session"); } getAriaLabel(element: InteractiveTreeItem): string { if (isRequestVM(element)) { return localize('interactiveRequest', "Request: {0}", element.messageText); } if (isResponseVM(element)) { return localize('interactiveResponse', "Response: {0}", element.response.value); } return ''; } } interface IInteractiveResultCodeBlockData { text: string; languageId: string; codeBlockIndex: number; element: InteractiveTreeItem; parentContextKeyService: IContextKeyService; } interface IInteractiveResultCodeBlockPart { readonly onDidChangeContentHeight: Event<number>; readonly element: HTMLElement; readonly textModel: ITextModel; layout(width: number): void; render(data: IInteractiveResultCodeBlockData, width: number): void; dispose(): void; } export interface IInteractiveResultCodeBlockInfo { providerId: string; responseId: string; codeBlockIndex: number; } export const codeBlockInfosByModelUri = new ResourceMap<IInteractiveResultCodeBlockInfo>(); class CodeBlockPart extends Disposable implements IInteractiveResultCodeBlockPart { private readonly _onDidChangeContentHeight = this._register(new Emitter<number>()); public readonly onDidChangeContentHeight = this._onDidChangeContentHeight.event; private readonly editor: CodeEditorWidget; private readonly toolbar: MenuWorkbenchToolBar; private readonly contextKeyService: IContextKeyService; public readonly textModel: ITextModel; public readonly element: HTMLElement; constructor( private readonly options: InteractiveSessionEditorOptions, @IInstantiationService instantiationService: IInstantiationService, @IContextKeyService contextKeyService: IContextKeyService, @ILanguageService private readonly languageService: ILanguageService, @IModelService private readonly modelService: IModelService, ) { super(); this.element = $('.interactive-result-editor-wrapper'); this.contextKeyService = this._register(contextKeyService.createScoped(this.element)); const scopedInstantiationService = instantiationService.createChild(new ServiceCollection([IContextKeyService, this.contextKeyService])); this.toolbar = this._register(scopedInstantiationService.createInstance(MenuWorkbenchToolBar, this.element, MenuId.InteractiveSessionCodeBlock, { menuOptions: { shouldForwardArgs: true } })); const editorElement = dom.append(this.element, $('.interactive-result-editor')); this.editor = this._register(scopedInstantiationService.createInstance(CodeEditorWidget, editorElement, { ...getSimpleEditorOptions(), readOnly: true, lineNumbers: 'off', selectOnLineNumbers: true, scrollBeyondLastLine: false, lineDecorationsWidth: 8, dragAndDrop: false, padding: { top: 2, bottom: 2 }, mouseWheelZoom: false, scrollbar: { alwaysConsumeMouseWheel: false }, ...this.getEditorOptionsFromConfig() }, { isSimpleWidget: true, contributions: EditorExtensionsRegistry.getSomeEditorContributions([ MenuPreventer.ID, SelectionClipboardContributionID, ContextMenuController.ID, WordHighlighterContribution.ID, ViewportSemanticTokensContribution.ID, BracketMatchingController.ID, SmartSelectController.ID, ]) })); this._register(this.options.onDidChange(() => { this.editor.updateOptions(this.getEditorOptionsFromConfig()); })); this._register(this.editor.onDidContentSizeChange(e => { if (e.contentHeightChanged) { this._onDidChangeContentHeight.fire(e.contentHeight); } })); this._register(this.editor.onDidBlurEditorWidget(() => { WordHighlighterContribution.get(this.editor)?.stopHighlighting(); })); this._register(this.editor.onDidFocusEditorWidget(() => { WordHighlighterContribution.get(this.editor)?.restoreViewState(true); })); const vscodeLanguageId = this.languageService.getLanguageIdByLanguageName('javascript'); this.textModel = this._register(this.modelService.createModel('', this.languageService.createById(vscodeLanguageId), undefined)); this.editor.setModel(this.textModel); } private getEditorOptionsFromConfig(): IEditorOptions { return { wordWrap: this.options.configuration.resultEditor.wordWrap, bracketPairColorization: this.options.configuration.resultEditor.bracketPairColorization, fontFamily: this.options.configuration.resultEditor.fontFamily === 'default' ? EDITOR_FONT_DEFAULTS.fontFamily : this.options.configuration.resultEditor.fontFamily, fontSize: this.options.configuration.resultEditor.fontSize, fontWeight: this.options.configuration.resultEditor.fontWeight, lineHeight: this.options.configuration.resultEditor.lineHeight, }; } layout(width: number): void { const realContentHeight = this.editor.getContentHeight(); const editorBorder = 2; this.editor.layout({ width: width - editorBorder, height: realContentHeight }); } render(data: IInteractiveResultCodeBlockData, width: number): void { this.contextKeyService.updateParent(data.parentContextKeyService); if (this.options.configuration.resultEditor.wordWrap === 'on') { // Intialize the editor with the new proper width so that getContentHeight // will be computed correctly in the next call to layout() this.layout(width); } this.setText(data.text); this.setLanguage(data.languageId); this.layout(width); if (isResponseVM(data.element) && data.element.providerResponseId) { // For telemetry reporting codeBlockInfosByModelUri.set(this.textModel.uri, { providerId: data.element.providerId, responseId: data.element.providerResponseId, codeBlockIndex: data.codeBlockIndex }); } else { codeBlockInfosByModelUri.delete(this.textModel.uri); } this.toolbar.context = <IInteractiveSessionCodeBlockActionContext>{ code: data.text, codeBlockIndex: data.codeBlockIndex, element: data.element }; } private setText(newText: string): void { let currentText = this.textModel.getLinesContent().join('\n'); if (newText === currentText) { return; } let removedChars = 0; if (currentText.endsWith(` ${InteractiveListItemRenderer.cursorCharacter}`)) { removedChars = 2; } else if (currentText.endsWith(InteractiveListItemRenderer.cursorCharacter)) { removedChars = 1; } if (removedChars > 0) { currentText = currentText.slice(0, currentText.length - removedChars); } if (newText.startsWith(currentText)) { const text = newText.slice(currentText.length); const lastLine = this.textModel.getLineCount(); const lastCol = this.textModel.getLineMaxColumn(lastLine); const insertAtCol = lastCol - removedChars; this.textModel.applyEdits([{ range: new Range(lastLine, insertAtCol, lastLine, lastCol), text }]); } else { // console.log(`Failed to optimize setText`); this.textModel.setValue(newText); } } private setLanguage(languageId: string): void { const vscodeLanguageId = this.languageService.getLanguageIdByLanguageName(languageId); if (vscodeLanguageId) { this.textModel.setLanguage(vscodeLanguageId); } } } interface IDisposableReference<T> extends IDisposable { object: T; } class EditorPool extends Disposable { private _pool: ResourcePool<IInteractiveResultCodeBlockPart>; public get inUse(): ReadonlySet<IInteractiveResultCodeBlockPart> { return this._pool.inUse; } constructor( private readonly options: InteractiveSessionEditorOptions, @IInstantiationService private readonly instantiationService: IInstantiationService, ) { super(); this._pool = this._register(new ResourcePool(() => this.editorFactory())); // TODO listen to changes on options } private editorFactory(): IInteractiveResultCodeBlockPart { return this.instantiationService.createInstance(CodeBlockPart, this.options); } get(): IDisposableReference<IInteractiveResultCodeBlockPart> { const object = this._pool.get(); return { object, dispose: () => this._pool.release(object) }; } } // TODO does something in lifecycle.ts cover this? class ResourcePool<T extends IDisposable> extends Disposable { private readonly pool: T[] = []; private _inUse = new Set<T>; public get inUse(): ReadonlySet<T> { return this._inUse; } constructor( private readonly _itemFactory: () => T, ) { super(); } get(): T { if (this.pool.length > 0) { const item = this.pool.pop()!; this._inUse.add(item); return item; } const item = this._register(this._itemFactory()); this._inUse.add(item); return item; } release(item: T): void { this._inUse.delete(item); this.pool.push(item); } }
src/vs/workbench/contrib/interactiveSession/browser/interactiveSessionListRenderer.ts
1
https://github.com/microsoft/vscode/commit/324d1a25760c6abeb4a0492c0c5a22795b695bf4
[ 0.9864489436149597, 0.01472210232168436, 0.00016406243958044797, 0.00017488417506683618, 0.11456014215946198 ]
{ "id": 12, "code_window": [ "\t}\n", "\n", "\texport interface InteractiveResponseErrorDetails {\n", "\t\tmessage: string;\n", "\t\tresponseIsIncomplete?: boolean;\n", "\t}\n", "\n", "\texport interface InteractiveResponseForProgress {\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\tresponseIsFiltered?: boolean;\n" ], "file_path": "src/vscode-dts/vscode.proposed.interactive.d.ts", "type": "add", "edit_start_line_idx": 103 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; let i18n = require("../lib/i18n"); let fs = require("fs"); let path = require("path"); let gulp = require('gulp'); let vfs = require("vinyl-fs"); let rimraf = require('rimraf'); let minimist = require('minimist'); function update(options) { let idOrPath = options._; if (!idOrPath) { throw new Error('Argument must be the location of the localization extension.'); } let location = options.location; if (location !== undefined && !fs.existsSync(location)) { throw new Error(`${location} doesn't exist.`); } let externalExtensionsLocation = options.externalExtensionsLocation; if (externalExtensionsLocation !== undefined && !fs.existsSync(location)) { throw new Error(`${externalExtensionsLocation} doesn't exist.`); } let locExtFolder = idOrPath; if (/^\w{2,3}(-\w+)?$/.test(idOrPath)) { locExtFolder = path.join('..', 'vscode-loc', 'i18n', `vscode-language-pack-${idOrPath}`); } let locExtStat = fs.statSync(locExtFolder); if (!locExtStat || !locExtStat.isDirectory) { throw new Error('No directory found at ' + idOrPath); } let packageJSON = JSON.parse(fs.readFileSync(path.join(locExtFolder, 'package.json')).toString()); let contributes = packageJSON['contributes']; if (!contributes) { throw new Error('The extension must define a "localizations" contribution in the "package.json"'); } let localizations = contributes['localizations']; if (!localizations) { throw new Error('The extension must define a "localizations" contribution of type array in the "package.json"'); } localizations.forEach(function (localization) { if (!localization.languageId || !localization.languageName || !localization.localizedLanguageName) { throw new Error('Each localization contribution must define "languageId", "languageName" and "localizedLanguageName" properties.'); } let languageId = localization.languageId; let translationDataFolder = path.join(locExtFolder, 'translations'); switch (languageId) { case 'zh-cn': languageId = 'zh-Hans'; break; case 'zh-tw': languageId = 'zh-Hant'; break; case 'pt-br': languageId = 'pt-BR'; break; } if (fs.existsSync(translationDataFolder) && fs.existsSync(path.join(translationDataFolder, 'main.i18n.json'))) { console.log('Clearing \'' + translationDataFolder + '\'...'); rimraf.sync(translationDataFolder); } console.log(`Importing translations for ${languageId} form '${location}' to '${translationDataFolder}' ...`); let translationPaths = []; gulp.src([ path.join(location, '**', languageId, '*.xlf'), ...i18n.EXTERNAL_EXTENSIONS.map(extensionId => path.join(externalExtensionsLocation, extensionId, languageId, '*-new.xlf')) ], { silent: false }) .pipe(i18n.prepareI18nPackFiles(translationPaths)) .on('error', (error) => { console.log(`Error occurred while importing translations:`); translationPaths = undefined; if (Array.isArray(error)) { error.forEach(console.log); } else if (error) { console.log(error); } else { console.log('Unknown error'); } }) .pipe(vfs.dest(translationDataFolder)) .on('end', function () { if (translationPaths !== undefined) { localization.translations = []; for (let tp of translationPaths) { localization.translations.push({ id: tp.id, path: `./translations/${tp.resourceName}` }); } fs.writeFileSync(path.join(locExtFolder, 'package.json'), JSON.stringify(packageJSON, null, '\t') + '\n'); } }); }); } if (path.basename(process.argv[1]) === 'update-localization-extension.js') { var options = minimist(process.argv.slice(2), { string: ['location', 'externalExtensionsLocation'] }); update(options); }
build/npm/update-localization-extension.js
0
https://github.com/microsoft/vscode/commit/324d1a25760c6abeb4a0492c0c5a22795b695bf4
[ 0.00017774377192836255, 0.0001707943738438189, 0.00016837108705658466, 0.00017013937758747488, 0.000002446931148369913 ]
{ "id": 12, "code_window": [ "\t}\n", "\n", "\texport interface InteractiveResponseErrorDetails {\n", "\t\tmessage: string;\n", "\t\tresponseIsIncomplete?: boolean;\n", "\t}\n", "\n", "\texport interface InteractiveResponseForProgress {\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\tresponseIsFiltered?: boolean;\n" ], "file_path": "src/vscode-dts/vscode.proposed.interactive.d.ts", "type": "add", "edit_start_line_idx": 103 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { ExtensionContext, Uri, l10n } from 'vscode'; import { BaseLanguageClient, LanguageClientOptions } from 'vscode-languageclient'; import { startClient, LanguageClientConstructor } from '../cssClient'; import { LanguageClient } from 'vscode-languageclient/browser'; declare const Worker: { new(stringUrl: string): any; }; declare const TextDecoder: { new(encoding?: string): { decode(buffer: ArrayBuffer): string }; }; let client: BaseLanguageClient | undefined; // this method is called when vs code is activated export async function activate(context: ExtensionContext) { const serverMain = Uri.joinPath(context.extensionUri, 'server/dist/browser/cssServerMain.js'); try { const worker = new Worker(serverMain.toString()); worker.postMessage({ i10lLocation: l10n.uri?.toString(false) ?? '' }); const newLanguageClient: LanguageClientConstructor = (id: string, name: string, clientOptions: LanguageClientOptions) => { return new LanguageClient(id, name, clientOptions, worker); }; client = await startClient(context, newLanguageClient, { TextDecoder }); } catch (e) { console.log(e); } } export async function deactivate(): Promise<void> { if (client) { await client.stop(); client = undefined; } }
extensions/css-language-features/client/src/browser/cssClientMain.ts
0
https://github.com/microsoft/vscode/commit/324d1a25760c6abeb4a0492c0c5a22795b695bf4
[ 0.00017562511493451893, 0.00017000568914227188, 0.00016409232921432704, 0.00016944046365097165, 0.000003976421339757508 ]
{ "id": 12, "code_window": [ "\t}\n", "\n", "\texport interface InteractiveResponseErrorDetails {\n", "\t\tmessage: string;\n", "\t\tresponseIsIncomplete?: boolean;\n", "\t}\n", "\n", "\texport interface InteractiveResponseForProgress {\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\tresponseIsFiltered?: boolean;\n" ], "file_path": "src/vscode-dts/vscode.proposed.interactive.d.ts", "type": "add", "edit_start_line_idx": 103 }
/*--------------------------------------------------------------------------------------------- * 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 { stub } from 'sinon'; import { Emitter, Event } from 'vs/base/common/event'; import { Disposable, IDisposable } from 'vs/base/common/lifecycle'; import { Schemas } from 'vs/base/common/network'; import { IPath, normalize } from 'vs/base/common/path'; import * as platform from 'vs/base/common/platform'; import { isObject } from 'vs/base/common/types'; import { URI } from 'vs/base/common/uri'; import { Selection } from 'vs/editor/common/core/selection'; import { EditorType } from 'vs/editor/common/editorCommon'; import { ICommandService } from 'vs/platform/commands/common/commands'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { TestConfigurationService } from 'vs/platform/configuration/test/common/testConfigurationService'; import { IExtensionDescription } from 'vs/platform/extensions/common/extensions'; import { IFormatterChangeEvent, ILabelService, ResourceLabelFormatter, Verbosity } from 'vs/platform/label/common/label'; import { IWorkspace, IWorkspaceFolder, IWorkspaceIdentifier, Workspace } from 'vs/platform/workspace/common/workspace'; import { testWorkspace } from 'vs/platform/workspace/test/common/testWorkspace'; import { BaseConfigurationResolverService } from 'vs/workbench/services/configurationResolver/browser/baseConfigurationResolverService'; import { IConfigurationResolverService } from 'vs/workbench/services/configurationResolver/common/configurationResolver'; import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions'; import { IPathService } from 'vs/workbench/services/path/common/pathService'; import { TestEditorService, TestQuickInputService } from 'vs/workbench/test/browser/workbenchTestServices'; import { TestContextService, TestExtensionService } from 'vs/workbench/test/common/workbenchTestServices'; const mockLineNumber = 10; class TestEditorServiceWithActiveEditor extends TestEditorService { override get activeTextEditorControl(): any { return { getEditorType() { return EditorType.ICodeEditor; }, getSelection() { return new Selection(mockLineNumber, 1, mockLineNumber, 10); } }; } override get activeEditor(): any { return { get resource(): any { return URI.parse('file:///VSCode/workspaceLocation/file'); } }; } } class TestConfigurationResolverService extends BaseConfigurationResolverService { } const nullContext = { getAppRoot: () => undefined, getExecPath: () => undefined }; suite('Configuration Resolver Service', () => { let configurationResolverService: IConfigurationResolverService | null; const envVariables: { [key: string]: string } = { key1: 'Value for key1', key2: 'Value for key2' }; // let environmentService: MockWorkbenchEnvironmentService; let mockCommandService: MockCommandService; let editorService: TestEditorServiceWithActiveEditor; let containingWorkspace: Workspace; let workspace: IWorkspaceFolder; let quickInputService: TestQuickInputService; let labelService: MockLabelService; let pathService: MockPathService; let extensionService: IExtensionService; setup(() => { mockCommandService = new MockCommandService(); editorService = new TestEditorServiceWithActiveEditor(); quickInputService = new TestQuickInputService(); // environmentService = new MockWorkbenchEnvironmentService(envVariables); labelService = new MockLabelService(); pathService = new MockPathService(); extensionService = new TestExtensionService(); containingWorkspace = testWorkspace(URI.parse('file:///VSCode/workspaceLocation')); workspace = containingWorkspace.folders[0]; configurationResolverService = new TestConfigurationResolverService(nullContext, Promise.resolve(envVariables), editorService, new MockInputsConfigurationService(), mockCommandService, new TestContextService(containingWorkspace), quickInputService, labelService, pathService, extensionService); }); teardown(() => { configurationResolverService = null; }); test('substitute one', async () => { if (platform.isWindows) { assert.strictEqual(await configurationResolverService!.resolveAsync(workspace, 'abc ${workspaceFolder} xyz'), 'abc \\VSCode\\workspaceLocation xyz'); } else { assert.strictEqual(await configurationResolverService!.resolveAsync(workspace, 'abc ${workspaceFolder} xyz'), 'abc /VSCode/workspaceLocation xyz'); } }); test('workspace folder with argument', async () => { if (platform.isWindows) { assert.strictEqual(await configurationResolverService!.resolveAsync(workspace, 'abc ${workspaceFolder:workspaceLocation} xyz'), 'abc \\VSCode\\workspaceLocation xyz'); } else { assert.strictEqual(await configurationResolverService!.resolveAsync(workspace, 'abc ${workspaceFolder:workspaceLocation} xyz'), 'abc /VSCode/workspaceLocation xyz'); } }); test('workspace folder with invalid argument', () => { assert.rejects(async () => await configurationResolverService!.resolveAsync(workspace, 'abc ${workspaceFolder:invalidLocation} xyz')); }); test('workspace folder with undefined workspace folder', () => { assert.rejects(async () => await configurationResolverService!.resolveAsync(undefined, 'abc ${workspaceFolder} xyz')); }); test('workspace folder with argument and undefined workspace folder', async () => { if (platform.isWindows) { assert.strictEqual(await configurationResolverService!.resolveAsync(undefined, 'abc ${workspaceFolder:workspaceLocation} xyz'), 'abc \\VSCode\\workspaceLocation xyz'); } else { assert.strictEqual(await configurationResolverService!.resolveAsync(undefined, 'abc ${workspaceFolder:workspaceLocation} xyz'), 'abc /VSCode/workspaceLocation xyz'); } }); test('workspace folder with invalid argument and undefined workspace folder', () => { assert.rejects(async () => await configurationResolverService!.resolveAsync(undefined, 'abc ${workspaceFolder:invalidLocation} xyz')); }); test('workspace root folder name', async () => { assert.strictEqual(await configurationResolverService!.resolveAsync(workspace, 'abc ${workspaceRootFolderName} xyz'), 'abc workspaceLocation xyz'); }); test('current selected line number', async () => { assert.strictEqual(await configurationResolverService!.resolveAsync(workspace, 'abc ${lineNumber} xyz'), `abc ${mockLineNumber} xyz`); }); test('relative file', async () => { assert.strictEqual(await configurationResolverService!.resolveAsync(workspace, 'abc ${relativeFile} xyz'), 'abc file xyz'); }); test('relative file with argument', async () => { assert.strictEqual(await configurationResolverService!.resolveAsync(workspace, 'abc ${relativeFile:workspaceLocation} xyz'), 'abc file xyz'); }); test('relative file with invalid argument', () => { assert.rejects(async () => await configurationResolverService!.resolveAsync(workspace, 'abc ${relativeFile:invalidLocation} xyz')); }); test('relative file with undefined workspace folder', async () => { if (platform.isWindows) { assert.strictEqual(await configurationResolverService!.resolveAsync(undefined, 'abc ${relativeFile} xyz'), 'abc \\VSCode\\workspaceLocation\\file xyz'); } else { assert.strictEqual(await configurationResolverService!.resolveAsync(undefined, 'abc ${relativeFile} xyz'), 'abc /VSCode/workspaceLocation/file xyz'); } }); test('relative file with argument and undefined workspace folder', async () => { assert.strictEqual(await configurationResolverService!.resolveAsync(undefined, 'abc ${relativeFile:workspaceLocation} xyz'), 'abc file xyz'); }); test('relative file with invalid argument and undefined workspace folder', () => { assert.rejects(async () => await configurationResolverService!.resolveAsync(undefined, 'abc ${relativeFile:invalidLocation} xyz')); }); test('substitute many', async () => { if (platform.isWindows) { assert.strictEqual(await configurationResolverService!.resolveAsync(workspace, '${workspaceFolder} - ${workspaceFolder}'), '\\VSCode\\workspaceLocation - \\VSCode\\workspaceLocation'); } else { assert.strictEqual(await configurationResolverService!.resolveAsync(workspace, '${workspaceFolder} - ${workspaceFolder}'), '/VSCode/workspaceLocation - /VSCode/workspaceLocation'); } }); test('substitute one env variable', async () => { if (platform.isWindows) { assert.strictEqual(await configurationResolverService!.resolveAsync(workspace, 'abc ${workspaceFolder} ${env:key1} xyz'), 'abc \\VSCode\\workspaceLocation Value for key1 xyz'); } else { assert.strictEqual(await configurationResolverService!.resolveAsync(workspace, 'abc ${workspaceFolder} ${env:key1} xyz'), 'abc /VSCode/workspaceLocation Value for key1 xyz'); } }); test('substitute many env variable', async () => { if (platform.isWindows) { assert.strictEqual(await configurationResolverService!.resolveAsync(workspace, '${workspaceFolder} - ${workspaceFolder} ${env:key1} - ${env:key2}'), '\\VSCode\\workspaceLocation - \\VSCode\\workspaceLocation Value for key1 - Value for key2'); } else { assert.strictEqual(await configurationResolverService!.resolveAsync(workspace, '${workspaceFolder} - ${workspaceFolder} ${env:key1} - ${env:key2}'), '/VSCode/workspaceLocation - /VSCode/workspaceLocation Value for key1 - Value for key2'); } }); test('disallows nested keys (#77289)', async () => { assert.strictEqual(await configurationResolverService!.resolveAsync(workspace, '${env:key1} ${env:key1${env:key2}}'), 'Value for key1 ${env:key1${env:key2}}'); }); test('supports extensionDir', async () => { const getExtension = stub(extensionService, 'getExtension'); getExtension.withArgs('publisher.extId').returns(Promise.resolve({ extensionLocation: URI.file('/some/path') } as IExtensionDescription)); assert.strictEqual(await configurationResolverService!.resolveAsync(workspace, '${extensionInstallFolder:publisher.extId}'), URI.file('/some/path').fsPath); }); // test('substitute keys and values in object', () => { // const myObject = { // '${workspaceRootFolderName}': '${lineNumber}', // 'hey ${env:key1} ': '${workspaceRootFolderName}' // }; // assert.deepStrictEqual(configurationResolverService!.resolveAsync(workspace, myObject), { // 'workspaceLocation': `${editorService.mockLineNumber}`, // 'hey Value for key1 ': 'workspaceLocation' // }); // }); test('substitute one env variable using platform case sensitivity', async () => { if (platform.isWindows) { assert.strictEqual(await configurationResolverService!.resolveAsync(workspace, '${env:key1} - ${env:Key1}'), 'Value for key1 - Value for key1'); } else { assert.strictEqual(await configurationResolverService!.resolveAsync(workspace, '${env:key1} - ${env:Key1}'), 'Value for key1 - '); } }); test('substitute one configuration variable', async () => { const configurationService: IConfigurationService = new TestConfigurationService({ editor: { fontFamily: 'foo' }, terminal: { integrated: { fontFamily: 'bar' } } }); const service = new TestConfigurationResolverService(nullContext, Promise.resolve(envVariables), new TestEditorServiceWithActiveEditor(), configurationService, mockCommandService, new TestContextService(), quickInputService, labelService, pathService, extensionService); assert.strictEqual(await service.resolveAsync(workspace, 'abc ${config:editor.fontFamily} xyz'), 'abc foo xyz'); }); test('substitute configuration variable with undefined workspace folder', async () => { const configurationService: IConfigurationService = new TestConfigurationService({ editor: { fontFamily: 'foo' } }); const service = new TestConfigurationResolverService(nullContext, Promise.resolve(envVariables), new TestEditorServiceWithActiveEditor(), configurationService, mockCommandService, new TestContextService(), quickInputService, labelService, pathService, extensionService); assert.strictEqual(await service.resolveAsync(undefined, 'abc ${config:editor.fontFamily} xyz'), 'abc foo xyz'); }); test('substitute many configuration variables', async () => { const configurationService = new TestConfigurationService({ editor: { fontFamily: 'foo' }, terminal: { integrated: { fontFamily: 'bar' } } }); const service = new TestConfigurationResolverService(nullContext, Promise.resolve(envVariables), new TestEditorServiceWithActiveEditor(), configurationService, mockCommandService, new TestContextService(), quickInputService, labelService, pathService, extensionService); assert.strictEqual(await service.resolveAsync(workspace, 'abc ${config:editor.fontFamily} ${config:terminal.integrated.fontFamily} xyz'), 'abc foo bar xyz'); }); test('substitute one env variable and a configuration variable', async () => { const configurationService = new TestConfigurationService({ editor: { fontFamily: 'foo' }, terminal: { integrated: { fontFamily: 'bar' } } }); const service = new TestConfigurationResolverService(nullContext, Promise.resolve(envVariables), new TestEditorServiceWithActiveEditor(), configurationService, mockCommandService, new TestContextService(), quickInputService, labelService, pathService, extensionService); if (platform.isWindows) { assert.strictEqual(await service.resolveAsync(workspace, 'abc ${config:editor.fontFamily} ${workspaceFolder} ${env:key1} xyz'), 'abc foo \\VSCode\\workspaceLocation Value for key1 xyz'); } else { assert.strictEqual(await service.resolveAsync(workspace, 'abc ${config:editor.fontFamily} ${workspaceFolder} ${env:key1} xyz'), 'abc foo /VSCode/workspaceLocation Value for key1 xyz'); } }); test('substitute many env variable and a configuration variable', async () => { const configurationService = new TestConfigurationService({ editor: { fontFamily: 'foo' }, terminal: { integrated: { fontFamily: 'bar' } } }); const service = new TestConfigurationResolverService(nullContext, Promise.resolve(envVariables), new TestEditorServiceWithActiveEditor(), configurationService, mockCommandService, new TestContextService(), quickInputService, labelService, pathService, extensionService); if (platform.isWindows) { assert.strictEqual(await service.resolveAsync(workspace, '${config:editor.fontFamily} ${config:terminal.integrated.fontFamily} ${workspaceFolder} - ${workspaceFolder} ${env:key1} - ${env:key2}'), 'foo bar \\VSCode\\workspaceLocation - \\VSCode\\workspaceLocation Value for key1 - Value for key2'); } else { assert.strictEqual(await service.resolveAsync(workspace, '${config:editor.fontFamily} ${config:terminal.integrated.fontFamily} ${workspaceFolder} - ${workspaceFolder} ${env:key1} - ${env:key2}'), 'foo bar /VSCode/workspaceLocation - /VSCode/workspaceLocation Value for key1 - Value for key2'); } }); test('mixed types of configuration variables', async () => { const configurationService = new TestConfigurationService({ editor: { fontFamily: 'foo', lineNumbers: 123, insertSpaces: false }, terminal: { integrated: { fontFamily: 'bar' } }, json: { schemas: [ { fileMatch: [ '/myfile', '/myOtherfile' ], url: 'schemaURL' } ] } }); const service = new TestConfigurationResolverService(nullContext, Promise.resolve(envVariables), new TestEditorServiceWithActiveEditor(), configurationService, mockCommandService, new TestContextService(), quickInputService, labelService, pathService, extensionService); assert.strictEqual(await service.resolveAsync(workspace, 'abc ${config:editor.fontFamily} ${config:editor.lineNumbers} ${config:editor.insertSpaces} xyz'), 'abc foo 123 false xyz'); }); test('uses original variable as fallback', async () => { const configurationService = new TestConfigurationService({ editor: {} }); const service = new TestConfigurationResolverService(nullContext, Promise.resolve(envVariables), new TestEditorServiceWithActiveEditor(), configurationService, mockCommandService, new TestContextService(), quickInputService, labelService, pathService, extensionService); assert.strictEqual(await service.resolveAsync(workspace, 'abc ${unknownVariable} xyz'), 'abc ${unknownVariable} xyz'); assert.strictEqual(await service.resolveAsync(workspace, 'abc ${env:unknownVariable} xyz'), 'abc xyz'); }); test('configuration variables with invalid accessor', () => { const configurationService = new TestConfigurationService({ editor: { fontFamily: 'foo' } }); const service = new TestConfigurationResolverService(nullContext, Promise.resolve(envVariables), new TestEditorServiceWithActiveEditor(), configurationService, mockCommandService, new TestContextService(), quickInputService, labelService, pathService, extensionService); assert.rejects(async () => await service.resolveAsync(workspace, 'abc ${env} xyz')); assert.rejects(async () => await service.resolveAsync(workspace, 'abc ${env:} xyz')); assert.rejects(async () => await service.resolveAsync(workspace, 'abc ${config} xyz')); assert.rejects(async () => await service.resolveAsync(workspace, 'abc ${config:} xyz')); assert.rejects(async () => await service.resolveAsync(workspace, 'abc ${config:editor} xyz')); assert.rejects(async () => await service.resolveAsync(workspace, 'abc ${config:editor..fontFamily} xyz')); assert.rejects(async () => await service.resolveAsync(workspace, 'abc ${config:editor.none.none2} xyz')); }); test('a single command variable', () => { const configuration = { 'name': 'Attach to Process', 'type': 'node', 'request': 'attach', 'processId': '${command:command1}', 'port': 5858, 'sourceMaps': false, 'outDir': null }; return configurationResolverService!.resolveWithInteractionReplace(undefined, configuration).then(result => { assert.deepStrictEqual({ ...result }, { 'name': 'Attach to Process', 'type': 'node', 'request': 'attach', 'processId': 'command1-result', 'port': 5858, 'sourceMaps': false, 'outDir': null }); assert.strictEqual(1, mockCommandService.callCount); }); }); test('an old style command variable', () => { const configuration = { 'name': 'Attach to Process', 'type': 'node', 'request': 'attach', 'processId': '${command:commandVariable1}', 'port': 5858, 'sourceMaps': false, 'outDir': null }; const commandVariables = Object.create(null); commandVariables['commandVariable1'] = 'command1'; return configurationResolverService!.resolveWithInteractionReplace(undefined, configuration, undefined, commandVariables).then(result => { assert.deepStrictEqual({ ...result }, { 'name': 'Attach to Process', 'type': 'node', 'request': 'attach', 'processId': 'command1-result', 'port': 5858, 'sourceMaps': false, 'outDir': null }); assert.strictEqual(1, mockCommandService.callCount); }); }); test('multiple new and old-style command variables', () => { const configuration = { 'name': 'Attach to Process', 'type': 'node', 'request': 'attach', 'processId': '${command:commandVariable1}', 'pid': '${command:command2}', 'sourceMaps': false, 'outDir': 'src/${command:command2}', 'env': { 'processId': '__${command:command2}__', } }; const commandVariables = Object.create(null); commandVariables['commandVariable1'] = 'command1'; return configurationResolverService!.resolveWithInteractionReplace(undefined, configuration, undefined, commandVariables).then(result => { const expected = { 'name': 'Attach to Process', 'type': 'node', 'request': 'attach', 'processId': 'command1-result', 'pid': 'command2-result', 'sourceMaps': false, 'outDir': 'src/command2-result', 'env': { 'processId': '__command2-result__', } }; assert.deepStrictEqual(Object.keys(result), Object.keys(expected)); Object.keys(result).forEach(property => { const expectedProperty = (<any>expected)[property]; if (isObject(result[property])) { assert.deepStrictEqual({ ...result[property] }, expectedProperty); } else { assert.deepStrictEqual(result[property], expectedProperty); } }); assert.strictEqual(2, mockCommandService.callCount); }); }); test('a command variable that relies on resolved env vars', () => { const configuration = { 'name': 'Attach to Process', 'type': 'node', 'request': 'attach', 'processId': '${command:commandVariable1}', 'value': '${env:key1}' }; const commandVariables = Object.create(null); commandVariables['commandVariable1'] = 'command1'; return configurationResolverService!.resolveWithInteractionReplace(undefined, configuration, undefined, commandVariables).then(result => { assert.deepStrictEqual({ ...result }, { 'name': 'Attach to Process', 'type': 'node', 'request': 'attach', 'processId': 'Value for key1', 'value': 'Value for key1' }); assert.strictEqual(1, mockCommandService.callCount); }); }); test('a single prompt input variable', () => { const configuration = { 'name': 'Attach to Process', 'type': 'node', 'request': 'attach', 'processId': '${input:input1}', 'port': 5858, 'sourceMaps': false, 'outDir': null }; return configurationResolverService!.resolveWithInteractionReplace(workspace, configuration, 'tasks').then(result => { assert.deepStrictEqual({ ...result }, { 'name': 'Attach to Process', 'type': 'node', 'request': 'attach', 'processId': 'resolvedEnterinput1', 'port': 5858, 'sourceMaps': false, 'outDir': null }); assert.strictEqual(0, mockCommandService.callCount); }); }); test('a single pick input variable', () => { const configuration = { 'name': 'Attach to Process', 'type': 'node', 'request': 'attach', 'processId': '${input:input2}', 'port': 5858, 'sourceMaps': false, 'outDir': null }; return configurationResolverService!.resolveWithInteractionReplace(workspace, configuration, 'tasks').then(result => { assert.deepStrictEqual({ ...result }, { 'name': 'Attach to Process', 'type': 'node', 'request': 'attach', 'processId': 'selectedPick', 'port': 5858, 'sourceMaps': false, 'outDir': null }); assert.strictEqual(0, mockCommandService.callCount); }); }); test('a single command input variable', () => { const configuration = { 'name': 'Attach to Process', 'type': 'node', 'request': 'attach', 'processId': '${input:input4}', 'port': 5858, 'sourceMaps': false, 'outDir': null }; return configurationResolverService!.resolveWithInteractionReplace(workspace, configuration, 'tasks').then(result => { assert.deepStrictEqual({ ...result }, { 'name': 'Attach to Process', 'type': 'node', 'request': 'attach', 'processId': 'arg for command', 'port': 5858, 'sourceMaps': false, 'outDir': null }); assert.strictEqual(1, mockCommandService.callCount); }); }); test('several input variables and command', () => { const configuration = { 'name': '${input:input3}', 'type': '${command:command1}', 'request': '${input:input1}', 'processId': '${input:input2}', 'command': '${input:input4}', 'port': 5858, 'sourceMaps': false, 'outDir': null }; return configurationResolverService!.resolveWithInteractionReplace(workspace, configuration, 'tasks').then(result => { assert.deepStrictEqual({ ...result }, { 'name': 'resolvedEnterinput3', 'type': 'command1-result', 'request': 'resolvedEnterinput1', 'processId': 'selectedPick', 'command': 'arg for command', 'port': 5858, 'sourceMaps': false, 'outDir': null }); assert.strictEqual(2, mockCommandService.callCount); }); }); test('input variable with undefined workspace folder', () => { const configuration = { 'name': 'Attach to Process', 'type': 'node', 'request': 'attach', 'processId': '${input:input1}', 'port': 5858, 'sourceMaps': false, 'outDir': null }; return configurationResolverService!.resolveWithInteractionReplace(undefined, configuration, 'tasks').then(result => { assert.deepStrictEqual({ ...result }, { 'name': 'Attach to Process', 'type': 'node', 'request': 'attach', 'processId': 'resolvedEnterinput1', 'port': 5858, 'sourceMaps': false, 'outDir': null }); assert.strictEqual(0, mockCommandService.callCount); }); }); test('contributed variable', () => { const buildTask = 'npm: compile'; const variable = 'defaultBuildTask'; const configuration = { 'name': '${' + variable + '}', }; configurationResolverService!.contributeVariable(variable, async () => { return buildTask; }); return configurationResolverService!.resolveWithInteractionReplace(workspace, configuration).then(result => { assert.deepStrictEqual({ ...result }, { 'name': `${buildTask}` }); }); }); test('resolveWithEnvironment', async () => { const env = { 'VAR_1': 'VAL_1', 'VAR_2': 'VAL_2' }; const configuration = 'echo ${env:VAR_1}${env:VAR_2}'; const resolvedResult = await configurationResolverService!.resolveWithEnvironment({ ...env }, undefined, configuration); assert.deepStrictEqual(resolvedResult, 'echo VAL_1VAL_2'); }); }); class MockCommandService implements ICommandService { public _serviceBrand: undefined; public callCount = 0; onWillExecuteCommand = () => Disposable.None; onDidExecuteCommand = () => Disposable.None; public executeCommand(commandId: string, ...args: any[]): Promise<any> { this.callCount++; let result = `${commandId}-result`; if (args.length >= 1) { if (args[0] && args[0].value) { result = args[0].value; } } return Promise.resolve(result); } } class MockLabelService implements ILabelService { _serviceBrand: undefined; getUriLabel(resource: URI, options?: { relative?: boolean | undefined; noPrefix?: boolean | undefined }): string { return normalize(resource.fsPath); } getUriBasenameLabel(resource: URI): string { throw new Error('Method not implemented.'); } getWorkspaceLabel(workspace: URI | IWorkspaceIdentifier | IWorkspace, options?: { verbose: Verbosity }): string { throw new Error('Method not implemented.'); } getHostLabel(scheme: string, authority?: string): string { throw new Error('Method not implemented.'); } public getHostTooltip(): string | undefined { throw new Error('Method not implemented.'); } getSeparator(scheme: string, authority?: string): '/' | '\\' { throw new Error('Method not implemented.'); } registerFormatter(formatter: ResourceLabelFormatter): IDisposable { throw new Error('Method not implemented.'); } registerCachedFormatter(formatter: ResourceLabelFormatter): IDisposable { throw new Error('Method not implemented.'); } onDidChangeFormatters: Event<IFormatterChangeEvent> = new Emitter<IFormatterChangeEvent>().event; } class MockPathService implements IPathService { _serviceBrand: undefined; get path(): Promise<IPath> { throw new Error('Property not implemented'); } defaultUriScheme: string = Schemas.file; fileURI(path: string): Promise<URI> { throw new Error('Method not implemented.'); } userHome(options?: { preferLocal: boolean }): Promise<URI>; userHome(options: { preferLocal: true }): URI; userHome(options?: { preferLocal: boolean }): Promise<URI> | URI { const uri = URI.file('c:\\users\\username'); return options?.preferLocal ? uri : Promise.resolve(uri); } hasValidBasename(resource: URI, basename?: string): Promise<boolean>; hasValidBasename(resource: URI, os: platform.OperatingSystem, basename?: string): boolean; hasValidBasename(resource: URI, arg2?: string | platform.OperatingSystem, name?: string): boolean | Promise<boolean> { throw new Error('Method not implemented.'); } resolvedUserHome: URI | undefined; } class MockInputsConfigurationService extends TestConfigurationService { public override getValue(arg1?: any, arg2?: any): any { let configuration; if (arg1 === 'tasks') { configuration = { inputs: [ { id: 'input1', type: 'promptString', description: 'Enterinput1', default: 'default input1' }, { id: 'input2', type: 'pickString', description: 'Enterinput1', default: 'option2', options: ['option1', 'option2', 'option3'] }, { id: 'input3', type: 'promptString', description: 'Enterinput3', default: 'default input3', password: true }, { id: 'input4', type: 'command', command: 'command1', args: { value: 'arg for command' } } ] }; } return configuration; } }
src/vs/workbench/services/configurationResolver/test/electron-sandbox/configurationResolverService.test.ts
0
https://github.com/microsoft/vscode/commit/324d1a25760c6abeb4a0492c0c5a22795b695bf4
[ 0.0003043909091502428, 0.0001747019705362618, 0.00016572860477026552, 0.00017162782023660839, 0.000017905229469761252 ]
{ "id": 0, "code_window": [ " */\n", "\n", "import { EventEmitter } from 'events';\n", "\n", "export class Runner extends EventEmitter {\n" ], "labels": [ "keep", "keep", "add", "keep", "keep" ], "after_edit": [ "import { ChildProcess } from 'child_process';\n", "\n", "export interface Options {\n", " createProcess?(\n", " workspace: ProjectWorkspace, \n", " args: string[], \n", " debugPort?: number,\n", " ): ChildProcess;\n", " debugPort?: number;\n", " testNamePattern?: string;\n", " testFileNamePattern?: string;\n", "}\n" ], "file_path": "packages/jest-editor-support/index.d.ts", "type": "add", "edit_start_line_idx": 8 }
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ export type Location = { column: number, line: number, }; import type {ChildProcess} from 'child_process'; import type ProjectWorkspace from './project_workspace'; export type Options = { createProcess?: ( workspace: ProjectWorkspace, args: Array<string>, ) => ChildProcess, }; /** * Did the thing pass, fail or was it not run? */ export type TestReconciliationState = | 'Unknown' // The file has not changed, so the watcher didn't hit it | 'KnownFail' // Definitely failed | 'KnownSuccess' // Definitely passed | 'KnownSkip'; // Definitely skipped /** * The Jest Extension's version of a status for * whether the file passed or not * */ export type TestFileAssertionStatus = { file: string, message: string, status: TestReconciliationState, assertions: Array<TestAssertionStatus> | null, }; /** * The Jest Extension's version of a status for * individual assertion fails * */ export type TestAssertionStatus = { title: string, status: TestReconciliationState, message: string, shortMessage: ?string, terseMessage: ?string, line: ?number, };
packages/jest-editor-support/src/types.js
1
https://github.com/jestjs/jest/commit/a0220a62183d689f1a9155e9c9021028d5ffa6cf
[ 0.00017684171325527132, 0.00017148355254903436, 0.00016602943651378155, 0.00017238646978512406, 0.0000036717005968966987 ]
{ "id": 0, "code_window": [ " */\n", "\n", "import { EventEmitter } from 'events';\n", "\n", "export class Runner extends EventEmitter {\n" ], "labels": [ "keep", "keep", "add", "keep", "keep" ], "after_edit": [ "import { ChildProcess } from 'child_process';\n", "\n", "export interface Options {\n", " createProcess?(\n", " workspace: ProjectWorkspace, \n", " args: string[], \n", " debugPort?: number,\n", " ): ChildProcess;\n", " debugPort?: number;\n", " testNamePattern?: string;\n", " testFileNamePattern?: string;\n", "}\n" ], "file_path": "packages/jest-editor-support/index.d.ts", "type": "add", "edit_start_line_idx": 8 }
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @jest-environment jsdom */ 'use strict'; it('async test fails', done => { setTimeout(() => { expect(false).toBeTruthy(); done(); }, 1 * 1000); });
integration_tests/jasmine_async/__tests__/async_test_fails.test.js
0
https://github.com/jestjs/jest/commit/a0220a62183d689f1a9155e9c9021028d5ffa6cf
[ 0.00017824205860961229, 0.0001749131770338863, 0.00017158429545816034, 0.0001749131770338863, 0.0000033288815757259727 ]
{ "id": 0, "code_window": [ " */\n", "\n", "import { EventEmitter } from 'events';\n", "\n", "export class Runner extends EventEmitter {\n" ], "labels": [ "keep", "keep", "add", "keep", "keep" ], "after_edit": [ "import { ChildProcess } from 'child_process';\n", "\n", "export interface Options {\n", " createProcess?(\n", " workspace: ProjectWorkspace, \n", " args: string[], \n", " debugPort?: number,\n", " ): ChildProcess;\n", " debugPort?: number;\n", " testNamePattern?: string;\n", " testFileNamePattern?: string;\n", "}\n" ], "file_path": "packages/jest-editor-support/index.d.ts", "type": "add", "edit_start_line_idx": 8 }
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`prints the config object 1`] = ` "{ \\"configs\\": { \\"rootDir\\": \\"/path/to/dir\\", \\"roots\\": [ \\"path/to/dir/test\\" ], \\"testRunner\\": \\"myRunner\\" }, \\"globalConfig\\": { \\"automock\\": false, \\"watch\\": true }, \\"version\\": 123 } " `; exports[`prints the jest version 1`] = ` "{ \\"configs\\": { \\"testRunner\\": \\"myRunner\\" }, \\"globalConfig\\": { \\"watch\\": true }, \\"version\\": 123 } " `; exports[`prints the test framework name 1`] = ` "{ \\"configs\\": { \\"testRunner\\": \\"myRunner\\" }, \\"globalConfig\\": { \\"watch\\": true }, \\"version\\": 123 } " `;
packages/jest-cli/src/lib/__tests__/__snapshots__/log_debug_messages.test.js.snap
0
https://github.com/jestjs/jest/commit/a0220a62183d689f1a9155e9c9021028d5ffa6cf
[ 0.000978973344899714, 0.0003586048260331154, 0.0001687928888713941, 0.00023139279801398516, 0.0003114688443019986 ]
{ "id": 0, "code_window": [ " */\n", "\n", "import { EventEmitter } from 'events';\n", "\n", "export class Runner extends EventEmitter {\n" ], "labels": [ "keep", "keep", "add", "keep", "keep" ], "after_edit": [ "import { ChildProcess } from 'child_process';\n", "\n", "export interface Options {\n", " createProcess?(\n", " workspace: ProjectWorkspace, \n", " args: string[], \n", " debugPort?: number,\n", " ): ChildProcess;\n", " debugPort?: number;\n", " testNamePattern?: string;\n", " testFileNamePattern?: string;\n", "}\n" ], "file_path": "packages/jest-editor-support/index.d.ts", "type": "add", "edit_start_line_idx": 8 }
--- title: Jest 13.0: Flow & REPL author: Christoph Pojer authorURL: http://twitter.com/cpojer authorFBID: 100000023028168 --- Today we are happy to announce the next major release of Jest. We have made major changes to Jest which are going to benefit you and all of Facebook's JavaScript test infrastructure. Most importantly, we added static types to all of Jest's code during a recent Jest hackathon at Facebook. Fifteen people worked for a day and night to add [Flow](https://flowtype.org/) types to Jest and to add new features to Jest. The Flow types serve two purposes: First, we believe that code is written to be read. Most of the time, code is written only once but read by dozens of people over the course of years. Adding static types to the project helps document the code and helps explain some of the architecture in Jest. Second, adding static types makes maintenance easier and will allow us to more confidently refactor parts of Jest without fear of breakages. The Flow project has evolved a lot within Facebook and has been successfully adopted across many of our frameworks and almost all of our product code. Adoption can be parallelized incredibly well – it can be done file-by-file until enough of the codebase is well-typed. Then, Flow provides real value and helps guide through large changes. Through this, many small edge cases and bugs were found. <!--truncate--> With the help of [lerna](https://github.com/lerna/lerna), we continued to modularize the Jest project. With just a small [update to the configuration](https://github.com/lerna/lerna#lernajson), Flow and lerna now get along well with each other. Splitting up Jest into packages helped us rethink module boundaries and enabled us to ship useful [packages](https://github.com/facebook/jest/tree/master/packages) standalone: The `jest-runtime` and `jest-repl` cli tools now allow you to run scripts in a sandboxed Jest environment, enabling you to run and debug your app from the command line. This is especially helpful for projects that use Facebook's `@providesModule` module convention. To get started, just install `jest-repl` and run it in the same folder you normally run your tests in! We also published a `jest-changed-files` package that finds changed files in version control for either git or hg, a common thing in developer tools. ## New and improved features * Added a notification plugin that shows a test run notification when using `--notify`. * Added a `browser` config option to properly resolve npm packages with a browser field in `package.json` if you are writing tests for client side apps. * Improved “no tests found message” which will now report which tests were found and how they were filtered. * Added `jest.isMockFunction(jest.fn())` to test for mock functions. * Improved test reporter printing and added a test failure summary when running many tests. * Added support for mocking virtual modules through `jest.mock('Module', implementation, {virtual: true})`. * Removed the `.haste_cache` folder. Jest now uses the operating system's preferred temporary file location. * Added the duration of individual tests in verbose mode. * Added the ability to record snapshots in Jest. We'll be publishing a separate blog post about this feature soon. Finally, we have received a complete website redesign done by Matthew Johnston and added documentation for using [Jest with Webpack](http://facebook.github.io/jest/docs/tutorial-webpack.html#content). Happy Jesting!
website/blog/2016-06-22-jest-13.md
0
https://github.com/jestjs/jest/commit/a0220a62183d689f1a9155e9c9021028d5ffa6cf
[ 0.0001732357923174277, 0.00016796049021650106, 0.00016477861208841205, 0.0001658670953474939, 0.0000037565705497399904 ]
{ "id": 1, "code_window": [ "\n", "export class Runner extends EventEmitter {\n", " constructor(workspace: ProjectWorkspace);\n", " watchMode: boolean;\n", " start(watchMode?: boolean): void;\n", " closeProcess(): void;\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " constructor(workspace: ProjectWorkspace, options?: Options);\n" ], "file_path": "packages/jest-editor-support/index.d.ts", "type": "replace", "edit_start_line_idx": 10 }
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import type {Options} from './types'; import {ChildProcess, spawn} from 'child_process'; import {readFile} from 'fs'; import {tmpdir} from 'os'; import EventEmitter from 'events'; import ProjectWorkspace from './project_workspace'; import {createProcess} from './Process'; // This class represents the running process, and // passes out events when it understands what data is being // pass sent out of the process export default class Runner extends EventEmitter { debugprocess: ChildProcess; outputPath: string; workspace: ProjectWorkspace; _createProcess: ( workspace: ProjectWorkspace, args: Array<string>, ) => ChildProcess; watchMode: boolean; constructor(workspace: ProjectWorkspace, options?: Options) { super(); this._createProcess = (options && options.createProcess) || createProcess; this.workspace = workspace; this.outputPath = tmpdir() + '/jest_runner.json'; } start(watchMode: boolean = true) { if (this.debugprocess) { return; } this.watchMode = watchMode; // Handle the arg change on v18 const belowEighteen = this.workspace.localJestMajorVersion < 18; const outputArg = belowEighteen ? '--jsonOutputFile' : '--outputFile'; const args = ['--json', '--useStderr', outputArg, this.outputPath]; if (this.watchMode) args.push('--watch'); this.debugprocess = this._createProcess(this.workspace, args); this.debugprocess.stdout.on('data', (data: Buffer) => { // Make jest save to a file, otherwise we get chunked data // and it can be hard to put it back together. const stringValue = data .toString() .replace(/\n$/, '') .trim(); if (stringValue.startsWith('Test results written to')) { readFile(this.outputPath, 'utf8', (err, data) => { if (err) { const message = `JSON report not found at ${this.outputPath}`; this.emit('terminalError', message); } else { this.emit('executableJSON', JSON.parse(data)); } }); } else { this.emit('executableOutput', stringValue.replace('', '')); } }); this.debugprocess.stderr.on('data', (data: Buffer) => { this.emit('executableStdErr', data); }); this.debugprocess.on('exit', () => { this.emit('debuggerProcessExit'); }); this.debugprocess.on('error', (error: Error) => { this.emit('terminalError', 'Process failed: ' + error.message); }); this.debugprocess.on('close', () => { this.emit('debuggerProcessExit'); }); } runJestWithUpdateForSnapshots(completion: any) { const args = ['--updateSnapshot']; const updateProcess = this._createProcess(this.workspace, args); updateProcess.on('close', () => { completion(); }); } closeProcess() { if (process.platform === 'win32') { // Windows doesn't exit the process when it should. spawn('taskkill', ['/pid', '' + this.debugprocess.pid, '/T', '/F']); } else { this.debugprocess.kill(); } delete this.debugprocess; } }
packages/jest-editor-support/src/Runner.js
1
https://github.com/jestjs/jest/commit/a0220a62183d689f1a9155e9c9021028d5ffa6cf
[ 0.1633279174566269, 0.026434527710080147, 0.0001669451012276113, 0.0010644287103787065, 0.05283393710851669 ]
{ "id": 1, "code_window": [ "\n", "export class Runner extends EventEmitter {\n", " constructor(workspace: ProjectWorkspace);\n", " watchMode: boolean;\n", " start(watchMode?: boolean): void;\n", " closeProcess(): void;\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " constructor(workspace: ProjectWorkspace, options?: Options);\n" ], "file_path": "packages/jest-editor-support/index.d.ts", "type": "replace", "edit_start_line_idx": 10 }
// flow-typed signature: 9d7ebf432fe5436b8912d014b367d934 // flow-typed version: b059774d08/chalk_v1.x.x/flow_>=v0.21.x type $npm$chalk$StyleElement = { open: string; close: string; }; type $npm$chalk$Chain = $npm$chalk$Style & (...text: any[]) => string; type $npm$chalk$Style = { // General reset: $npm$chalk$Chain; bold: $npm$chalk$Chain; dim: $npm$chalk$Chain; italic: $npm$chalk$Chain; underline: $npm$chalk$Chain; inverse: $npm$chalk$Chain; strikethrough: $npm$chalk$Chain; // Text colors black: $npm$chalk$Chain; red: $npm$chalk$Chain; green: $npm$chalk$Chain; yellow: $npm$chalk$Chain; blue: $npm$chalk$Chain; magenta: $npm$chalk$Chain; cyan: $npm$chalk$Chain; white: $npm$chalk$Chain; gray: $npm$chalk$Chain; grey: $npm$chalk$Chain; // Background colors bgBlack: $npm$chalk$Chain; bgRed: $npm$chalk$Chain; bgGreen: $npm$chalk$Chain; bgYellow: $npm$chalk$Chain; bgBlue: $npm$chalk$Chain; bgMagenta: $npm$chalk$Chain; bgCyan: $npm$chalk$Chain; bgWhite: $npm$chalk$Chain; }; type $npm$chalk$StyleMap = { // General reset: $npm$chalk$StyleElement; bold: $npm$chalk$StyleElement; dim: $npm$chalk$StyleElement; italic: $npm$chalk$StyleElement; underline: $npm$chalk$StyleElement; inverse: $npm$chalk$StyleElement; strikethrough: $npm$chalk$StyleElement; // Text colors black: $npm$chalk$StyleElement; red: $npm$chalk$StyleElement; green: $npm$chalk$StyleElement; yellow: $npm$chalk$StyleElement; blue: $npm$chalk$StyleElement; magenta: $npm$chalk$StyleElement; cyan: $npm$chalk$StyleElement; white: $npm$chalk$StyleElement; gray: $npm$chalk$StyleElement; // Background colors bgBlack: $npm$chalk$StyleElement; bgRed: $npm$chalk$StyleElement; bgGreen: $npm$chalk$StyleElement; bgYellow: $npm$chalk$StyleElement; bgBlue: $npm$chalk$StyleElement; bgMagenta: $npm$chalk$StyleElement; bgCyan: $npm$chalk$StyleElement; bgWhite: $npm$chalk$StyleElement; }; declare module "chalk" { declare var enabled: boolean; declare var supportsColor: boolean; declare var styles: $npm$chalk$StyleMap; declare function stripColor(value: string): any; declare function hasColor(str: string): boolean; // General declare var reset: $npm$chalk$Chain; declare var bold: $npm$chalk$Chain; declare var dim: $npm$chalk$Chain; declare var italic: $npm$chalk$Chain; declare var underline: $npm$chalk$Chain; declare var inverse: $npm$chalk$Chain; declare var strikethrough: $npm$chalk$Chain; // Text colors declare var black: $npm$chalk$Chain; declare var red: $npm$chalk$Chain; declare var green: $npm$chalk$Chain; declare var yellow: $npm$chalk$Chain; declare var blue: $npm$chalk$Chain; declare var magenta: $npm$chalk$Chain; declare var cyan: $npm$chalk$Chain; declare var white: $npm$chalk$Chain; declare var gray: $npm$chalk$Chain; declare var grey: $npm$chalk$Chain; // Background colors declare var bgBlack: $npm$chalk$Chain; declare var bgRed: $npm$chalk$Chain; declare var bgGreen: $npm$chalk$Chain; declare var bgYellow: $npm$chalk$Chain; declare var bgBlue: $npm$chalk$Chain; declare var bgMagenta: $npm$chalk$Chain; declare var bgCyan: $npm$chalk$Chain; declare var bgWhite: $npm$chalk$Chain; }
flow-typed/npm/chalk_v1.x.x.js
0
https://github.com/jestjs/jest/commit/a0220a62183d689f1a9155e9c9021028d5ffa6cf
[ 0.0001778014120645821, 0.00017272180411964655, 0.00016879609029274434, 0.00017341808415949345, 0.0000024865619252523175 ]
{ "id": 1, "code_window": [ "\n", "export class Runner extends EventEmitter {\n", " constructor(workspace: ProjectWorkspace);\n", " watchMode: boolean;\n", " start(watchMode?: boolean): void;\n", " closeProcess(): void;\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " constructor(workspace: ProjectWorkspace, options?: Options);\n" ], "file_path": "packages/jest-editor-support/index.d.ts", "type": "replace", "edit_start_line_idx": 10 }
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import chalk from 'chalk'; export default (str: string, start: number, end: number) => chalk.dim(str.slice(0, start)) + chalk.reset(str.slice(start, end)) + chalk.dim(str.slice(end));
packages/jest-cli/src/lib/colorize.js
0
https://github.com/jestjs/jest/commit/a0220a62183d689f1a9155e9c9021028d5ffa6cf
[ 0.00017939774261321872, 0.00017234325059689581, 0.00016528877313248813, 0.00017234325059689581, 0.000007054484740365297 ]
{ "id": 1, "code_window": [ "\n", "export class Runner extends EventEmitter {\n", " constructor(workspace: ProjectWorkspace);\n", " watchMode: boolean;\n", " start(watchMode?: boolean): void;\n", " closeProcess(): void;\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " constructor(workspace: ProjectWorkspace, options?: Options);\n" ], "file_path": "packages/jest-editor-support/index.d.ts", "type": "replace", "edit_start_line_idx": 10 }
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 'use strict'; jest.mock('../'); const importedFn = require('../'); // empty mock name should result in default 'jest.fn()' output const mockFn = jest.fn(importedFn).mockName(''); test('first test', () => { mockFn(); expect(mockFn).toHaveBeenCalledTimes(1); });
integration_tests/mock-names/with-empty-mock-name/__tests__/index.js
0
https://github.com/jestjs/jest/commit/a0220a62183d689f1a9155e9c9021028d5ffa6cf
[ 0.00017984733858611435, 0.0001755371777107939, 0.00017122701683547348, 0.0001755371777107939, 0.0000043101608753204346 ]
{ "id": 2, "code_window": [ " localJestMajorVersin: number,\n", " );\n", " pathToJest: string;\n", " rootPath: string;\n", " localJestMajorVersion: number;\n", "}\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " pathToConfig: string;\n" ], "file_path": "packages/jest-editor-support/index.d.ts", "type": "add", "edit_start_line_idx": 34 }
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import { EventEmitter } from 'events'; export class Runner extends EventEmitter { constructor(workspace: ProjectWorkspace); watchMode: boolean; start(watchMode?: boolean): void; closeProcess(): void; runJestWithUpdateForSnapshots(completion: any): void; } export class Settings extends EventEmitter { constructor(workspace: ProjectWorkspace); getConfig(completed: Function): void; jestVersionMajor: number | null; settings: { testRegex: string; }; } export class ProjectWorkspace { constructor( rootPath: string, pathToJest: string, pathToConfig: string, localJestMajorVersin: number, ); pathToJest: string; rootPath: string; localJestMajorVersion: number; } export interface IParseResults { expects: Expect[]; itBlocks: ItBlock[]; } export function parse(file: string): IParseResults; export interface Location { column: number; line: number; } export class Node { start: Location; end: Location; file: string; } export class ItBlock extends Node { name: string; } export class Expect extends Node {} export class TestReconciler { stateForTestFile(file: string): TestReconcilationState; assertionsForTestFile(file: string): TestAssertionStatus[] | null; stateForTestAssertion( file: string, name: string, ): TestFileAssertionStatus | null; updateFileWithJestStatus(data: any): TestFileAssertionStatus[]; } export type TestReconcilationState = | 'Unknown' | 'KnownSuccess' | 'KnownFail' | 'KnownSkip'; export interface TestFileAssertionStatus { file: string; message: string; status: TestReconcilationState; assertions: Array<TestAssertionStatus>; } export interface TestAssertionStatus { title: string; status: TestReconcilationState; message: string; shortMessage?: string; terseMessage?: string; line?: number; } export interface JestFileResults { name: string; summary: string; message: string; status: 'failed' | 'passed'; startTime: number; endTime: number; assertionResults: Array<JestAssertionResults>; } export interface JestAssertionResults { name: string; title: string; status: 'failed' | 'passed'; failureMessages: string[]; } export interface JestTotalResults { success: boolean; startTime: number; numTotalTests: number; numTotalTestSuites: number; numRuntimeErrorTestSuites: number; numPassedTests: number; numFailedTests: number; numPendingTests: number; testResults: Array<JestFileResults>; }
packages/jest-editor-support/index.d.ts
1
https://github.com/jestjs/jest/commit/a0220a62183d689f1a9155e9c9021028d5ffa6cf
[ 0.9925562739372253, 0.07709872722625732, 0.00016857187438290566, 0.0002597779384814203, 0.26427382230758667 ]
{ "id": 2, "code_window": [ " localJestMajorVersin: number,\n", " );\n", " pathToJest: string;\n", " rootPath: string;\n", " localJestMajorVersion: number;\n", "}\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " pathToConfig: string;\n" ], "file_path": "packages/jest-editor-support/index.d.ts", "type": "add", "edit_start_line_idx": 34 }
# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. # yarn lockfile v1 ansi-regex@^2.0.0: version "2.1.1" resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-2.1.1.tgz#c3b33ab5ee360d86e0e628f0468ae7ef27d654df" ansi-styles@^2.2.1: version "2.2.1" resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-2.2.1.tgz#b432dd3358b634cf75e1e4664368240533c1ddbe" babel-code-frame@^6.22.0: version "6.22.0" resolved "https://registry.yarnpkg.com/babel-code-frame/-/babel-code-frame-6.22.0.tgz#027620bee567a88c32561574e7fd0801d33118e4" dependencies: chalk "^1.1.0" esutils "^2.0.2" js-tokens "^3.0.0" babel-helper-call-delegate@^6.24.1: version "6.24.1" resolved "https://registry.yarnpkg.com/babel-helper-call-delegate/-/babel-helper-call-delegate-6.24.1.tgz#ece6aacddc76e41c3461f88bfc575bd0daa2df8d" dependencies: babel-helper-hoist-variables "^6.24.1" babel-runtime "^6.22.0" babel-traverse "^6.24.1" babel-types "^6.24.1" babel-helper-define-map@^6.24.1: version "6.24.1" resolved "https://registry.yarnpkg.com/babel-helper-define-map/-/babel-helper-define-map-6.24.1.tgz#7a9747f258d8947d32d515f6aa1c7bd02204a080" dependencies: babel-helper-function-name "^6.24.1" babel-runtime "^6.22.0" babel-types "^6.24.1" lodash "^4.2.0" babel-helper-function-name@^6.24.1: version "6.24.1" resolved "https://registry.yarnpkg.com/babel-helper-function-name/-/babel-helper-function-name-6.24.1.tgz#d3475b8c03ed98242a25b48351ab18399d3580a9" dependencies: babel-helper-get-function-arity "^6.24.1" babel-runtime "^6.22.0" babel-template "^6.24.1" babel-traverse "^6.24.1" babel-types "^6.24.1" babel-helper-get-function-arity@^6.24.1: version "6.24.1" resolved "https://registry.yarnpkg.com/babel-helper-get-function-arity/-/babel-helper-get-function-arity-6.24.1.tgz#8f7782aa93407c41d3aa50908f89b031b1b6853d" dependencies: babel-runtime "^6.22.0" babel-types "^6.24.1" babel-helper-hoist-variables@^6.24.1: version "6.24.1" resolved "https://registry.yarnpkg.com/babel-helper-hoist-variables/-/babel-helper-hoist-variables-6.24.1.tgz#1ecb27689c9d25513eadbc9914a73f5408be7a76" dependencies: babel-runtime "^6.22.0" babel-types "^6.24.1" babel-helper-optimise-call-expression@^6.24.1: version "6.24.1" resolved "https://registry.yarnpkg.com/babel-helper-optimise-call-expression/-/babel-helper-optimise-call-expression-6.24.1.tgz#f7a13427ba9f73f8f4fa993c54a97882d1244257" dependencies: babel-runtime "^6.22.0" babel-types "^6.24.1" babel-helper-regex@^6.24.1: version "6.24.1" resolved "https://registry.yarnpkg.com/babel-helper-regex/-/babel-helper-regex-6.24.1.tgz#d36e22fab1008d79d88648e32116868128456ce8" dependencies: babel-runtime "^6.22.0" babel-types "^6.24.1" lodash "^4.2.0" babel-helper-remap-async-to-generator@^6.24.1: version "6.24.1" resolved "https://registry.yarnpkg.com/babel-helper-remap-async-to-generator/-/babel-helper-remap-async-to-generator-6.24.1.tgz#5ec581827ad723fecdd381f1c928390676e4551b" dependencies: babel-helper-function-name "^6.24.1" babel-runtime "^6.22.0" babel-template "^6.24.1" babel-traverse "^6.24.1" babel-types "^6.24.1" babel-helper-replace-supers@^6.24.1: version "6.24.1" resolved "https://registry.yarnpkg.com/babel-helper-replace-supers/-/babel-helper-replace-supers-6.24.1.tgz#bf6dbfe43938d17369a213ca8a8bf74b6a90ab1a" dependencies: babel-helper-optimise-call-expression "^6.24.1" babel-messages "^6.23.0" babel-runtime "^6.22.0" babel-template "^6.24.1" babel-traverse "^6.24.1" babel-types "^6.24.1" babel-messages@^6.23.0: version "6.23.0" resolved "https://registry.yarnpkg.com/babel-messages/-/babel-messages-6.23.0.tgz#f3cdf4703858035b2a2951c6ec5edf6c62f2630e" dependencies: babel-runtime "^6.22.0" babel-plugin-check-es2015-constants@^6.22.0: version "6.22.0" resolved "https://registry.yarnpkg.com/babel-plugin-check-es2015-constants/-/babel-plugin-check-es2015-constants-6.22.0.tgz#35157b101426fd2ffd3da3f75c7d1e91835bbf8a" dependencies: babel-runtime "^6.22.0" babel-plugin-syntax-async-functions@^6.8.0: version "6.13.0" resolved "https://registry.yarnpkg.com/babel-plugin-syntax-async-functions/-/babel-plugin-syntax-async-functions-6.13.0.tgz#cad9cad1191b5ad634bf30ae0872391e0647be95" babel-plugin-transform-async-to-generator@^6.22.0: version "6.24.1" resolved "https://registry.yarnpkg.com/babel-plugin-transform-async-to-generator/-/babel-plugin-transform-async-to-generator-6.24.1.tgz#6536e378aff6cb1d5517ac0e40eb3e9fc8d08761" dependencies: babel-helper-remap-async-to-generator "^6.24.1" babel-plugin-syntax-async-functions "^6.8.0" babel-runtime "^6.22.0" babel-plugin-transform-es2015-arrow-functions@^6.22.0: version "6.22.0" resolved "https://registry.yarnpkg.com/babel-plugin-transform-es2015-arrow-functions/-/babel-plugin-transform-es2015-arrow-functions-6.22.0.tgz#452692cb711d5f79dc7f85e440ce41b9f244d221" dependencies: babel-runtime "^6.22.0" babel-plugin-transform-es2015-block-scoped-functions@^6.22.0: version "6.22.0" resolved "https://registry.yarnpkg.com/babel-plugin-transform-es2015-block-scoped-functions/-/babel-plugin-transform-es2015-block-scoped-functions-6.22.0.tgz#bbc51b49f964d70cb8d8e0b94e820246ce3a6141" dependencies: babel-runtime "^6.22.0" babel-plugin-transform-es2015-block-scoping@^6.24.1: version "6.24.1" resolved "https://registry.yarnpkg.com/babel-plugin-transform-es2015-block-scoping/-/babel-plugin-transform-es2015-block-scoping-6.24.1.tgz#76c295dc3a4741b1665adfd3167215dcff32a576" dependencies: babel-runtime "^6.22.0" babel-template "^6.24.1" babel-traverse "^6.24.1" babel-types "^6.24.1" lodash "^4.2.0" babel-plugin-transform-es2015-classes@^6.24.1: version "6.24.1" resolved "https://registry.yarnpkg.com/babel-plugin-transform-es2015-classes/-/babel-plugin-transform-es2015-classes-6.24.1.tgz#5a4c58a50c9c9461e564b4b2a3bfabc97a2584db" dependencies: babel-helper-define-map "^6.24.1" babel-helper-function-name "^6.24.1" babel-helper-optimise-call-expression "^6.24.1" babel-helper-replace-supers "^6.24.1" babel-messages "^6.23.0" babel-runtime "^6.22.0" babel-template "^6.24.1" babel-traverse "^6.24.1" babel-types "^6.24.1" babel-plugin-transform-es2015-computed-properties@^6.24.1: version "6.24.1" resolved "https://registry.yarnpkg.com/babel-plugin-transform-es2015-computed-properties/-/babel-plugin-transform-es2015-computed-properties-6.24.1.tgz#6fe2a8d16895d5634f4cd999b6d3480a308159b3" dependencies: babel-runtime "^6.22.0" babel-template "^6.24.1" babel-plugin-transform-es2015-destructuring@^6.22.0: version "6.23.0" resolved "https://registry.yarnpkg.com/babel-plugin-transform-es2015-destructuring/-/babel-plugin-transform-es2015-destructuring-6.23.0.tgz#997bb1f1ab967f682d2b0876fe358d60e765c56d" dependencies: babel-runtime "^6.22.0" babel-plugin-transform-es2015-duplicate-keys@^6.24.1: version "6.24.1" resolved "https://registry.yarnpkg.com/babel-plugin-transform-es2015-duplicate-keys/-/babel-plugin-transform-es2015-duplicate-keys-6.24.1.tgz#73eb3d310ca969e3ef9ec91c53741a6f1576423e" dependencies: babel-runtime "^6.22.0" babel-types "^6.24.1" babel-plugin-transform-es2015-for-of@^6.22.0: version "6.23.0" resolved "https://registry.yarnpkg.com/babel-plugin-transform-es2015-for-of/-/babel-plugin-transform-es2015-for-of-6.23.0.tgz#f47c95b2b613df1d3ecc2fdb7573623c75248691" dependencies: babel-runtime "^6.22.0" babel-plugin-transform-es2015-function-name@^6.24.1: version "6.24.1" resolved "https://registry.yarnpkg.com/babel-plugin-transform-es2015-function-name/-/babel-plugin-transform-es2015-function-name-6.24.1.tgz#834c89853bc36b1af0f3a4c5dbaa94fd8eacaa8b" dependencies: babel-helper-function-name "^6.24.1" babel-runtime "^6.22.0" babel-types "^6.24.1" babel-plugin-transform-es2015-literals@^6.22.0: version "6.22.0" resolved "https://registry.yarnpkg.com/babel-plugin-transform-es2015-literals/-/babel-plugin-transform-es2015-literals-6.22.0.tgz#4f54a02d6cd66cf915280019a31d31925377ca2e" dependencies: babel-runtime "^6.22.0" babel-plugin-transform-es2015-modules-amd@^6.24.1: version "6.24.1" resolved "https://registry.yarnpkg.com/babel-plugin-transform-es2015-modules-amd/-/babel-plugin-transform-es2015-modules-amd-6.24.1.tgz#3b3e54017239842d6d19c3011c4bd2f00a00d154" dependencies: babel-plugin-transform-es2015-modules-commonjs "^6.24.1" babel-runtime "^6.22.0" babel-template "^6.24.1" babel-plugin-transform-es2015-modules-commonjs@^6.24.1: version "6.24.1" resolved "https://registry.yarnpkg.com/babel-plugin-transform-es2015-modules-commonjs/-/babel-plugin-transform-es2015-modules-commonjs-6.24.1.tgz#d3e310b40ef664a36622200097c6d440298f2bfe" dependencies: babel-plugin-transform-strict-mode "^6.24.1" babel-runtime "^6.22.0" babel-template "^6.24.1" babel-types "^6.24.1" babel-plugin-transform-es2015-modules-systemjs@^6.24.1: version "6.24.1" resolved "https://registry.yarnpkg.com/babel-plugin-transform-es2015-modules-systemjs/-/babel-plugin-transform-es2015-modules-systemjs-6.24.1.tgz#ff89a142b9119a906195f5f106ecf305d9407d23" dependencies: babel-helper-hoist-variables "^6.24.1" babel-runtime "^6.22.0" babel-template "^6.24.1" babel-plugin-transform-es2015-modules-umd@^6.24.1: version "6.24.1" resolved "https://registry.yarnpkg.com/babel-plugin-transform-es2015-modules-umd/-/babel-plugin-transform-es2015-modules-umd-6.24.1.tgz#ac997e6285cd18ed6176adb607d602344ad38468" dependencies: babel-plugin-transform-es2015-modules-amd "^6.24.1" babel-runtime "^6.22.0" babel-template "^6.24.1" babel-plugin-transform-es2015-object-super@^6.24.1: version "6.24.1" resolved "https://registry.yarnpkg.com/babel-plugin-transform-es2015-object-super/-/babel-plugin-transform-es2015-object-super-6.24.1.tgz#24cef69ae21cb83a7f8603dad021f572eb278f8d" dependencies: babel-helper-replace-supers "^6.24.1" babel-runtime "^6.22.0" babel-plugin-transform-es2015-parameters@^6.24.1: version "6.24.1" resolved "https://registry.yarnpkg.com/babel-plugin-transform-es2015-parameters/-/babel-plugin-transform-es2015-parameters-6.24.1.tgz#57ac351ab49caf14a97cd13b09f66fdf0a625f2b" dependencies: babel-helper-call-delegate "^6.24.1" babel-helper-get-function-arity "^6.24.1" babel-runtime "^6.22.0" babel-template "^6.24.1" babel-traverse "^6.24.1" babel-types "^6.24.1" babel-plugin-transform-es2015-shorthand-properties@^6.24.1: version "6.24.1" resolved "https://registry.yarnpkg.com/babel-plugin-transform-es2015-shorthand-properties/-/babel-plugin-transform-es2015-shorthand-properties-6.24.1.tgz#24f875d6721c87661bbd99a4622e51f14de38aa0" dependencies: babel-runtime "^6.22.0" babel-types "^6.24.1" babel-plugin-transform-es2015-spread@^6.22.0: version "6.22.0" resolved "https://registry.yarnpkg.com/babel-plugin-transform-es2015-spread/-/babel-plugin-transform-es2015-spread-6.22.0.tgz#d6d68a99f89aedc4536c81a542e8dd9f1746f8d1" dependencies: babel-runtime "^6.22.0" babel-plugin-transform-es2015-sticky-regex@^6.24.1: version "6.24.1" resolved "https://registry.yarnpkg.com/babel-plugin-transform-es2015-sticky-regex/-/babel-plugin-transform-es2015-sticky-regex-6.24.1.tgz#00c1cdb1aca71112cdf0cf6126c2ed6b457ccdbc" dependencies: babel-helper-regex "^6.24.1" babel-runtime "^6.22.0" babel-types "^6.24.1" babel-plugin-transform-es2015-template-literals@^6.22.0: version "6.22.0" resolved "https://registry.yarnpkg.com/babel-plugin-transform-es2015-template-literals/-/babel-plugin-transform-es2015-template-literals-6.22.0.tgz#a84b3450f7e9f8f1f6839d6d687da84bb1236d8d" dependencies: babel-runtime "^6.22.0" babel-plugin-transform-es2015-typeof-symbol@^6.22.0: version "6.23.0" resolved "https://registry.yarnpkg.com/babel-plugin-transform-es2015-typeof-symbol/-/babel-plugin-transform-es2015-typeof-symbol-6.23.0.tgz#dec09f1cddff94b52ac73d505c84df59dcceb372" dependencies: babel-runtime "^6.22.0" babel-plugin-transform-es2015-unicode-regex@^6.24.1: version "6.24.1" resolved "https://registry.yarnpkg.com/babel-plugin-transform-es2015-unicode-regex/-/babel-plugin-transform-es2015-unicode-regex-6.24.1.tgz#d38b12f42ea7323f729387f18a7c5ae1faeb35e9" dependencies: babel-helper-regex "^6.24.1" babel-runtime "^6.22.0" regexpu-core "^2.0.0" babel-plugin-transform-regenerator@^6.24.1: version "6.24.1" resolved "https://registry.yarnpkg.com/babel-plugin-transform-regenerator/-/babel-plugin-transform-regenerator-6.24.1.tgz#b8da305ad43c3c99b4848e4fe4037b770d23c418" dependencies: regenerator-transform "0.9.11" babel-plugin-transform-strict-mode@^6.24.1: version "6.24.1" resolved "https://registry.yarnpkg.com/babel-plugin-transform-strict-mode/-/babel-plugin-transform-strict-mode-6.24.1.tgz#d5faf7aa578a65bbe591cf5edae04a0c67020758" dependencies: babel-runtime "^6.22.0" babel-types "^6.24.1" babel-preset-es2015@^6.24.0: version "6.24.1" resolved "https://registry.yarnpkg.com/babel-preset-es2015/-/babel-preset-es2015-6.24.1.tgz#d44050d6bc2c9feea702aaf38d727a0210538939" dependencies: babel-plugin-check-es2015-constants "^6.22.0" babel-plugin-transform-es2015-arrow-functions "^6.22.0" babel-plugin-transform-es2015-block-scoped-functions "^6.22.0" babel-plugin-transform-es2015-block-scoping "^6.24.1" babel-plugin-transform-es2015-classes "^6.24.1" babel-plugin-transform-es2015-computed-properties "^6.24.1" babel-plugin-transform-es2015-destructuring "^6.22.0" babel-plugin-transform-es2015-duplicate-keys "^6.24.1" babel-plugin-transform-es2015-for-of "^6.22.0" babel-plugin-transform-es2015-function-name "^6.24.1" babel-plugin-transform-es2015-literals "^6.22.0" babel-plugin-transform-es2015-modules-amd "^6.24.1" babel-plugin-transform-es2015-modules-commonjs "^6.24.1" babel-plugin-transform-es2015-modules-systemjs "^6.24.1" babel-plugin-transform-es2015-modules-umd "^6.24.1" babel-plugin-transform-es2015-object-super "^6.24.1" babel-plugin-transform-es2015-parameters "^6.24.1" babel-plugin-transform-es2015-shorthand-properties "^6.24.1" babel-plugin-transform-es2015-spread "^6.22.0" babel-plugin-transform-es2015-sticky-regex "^6.24.1" babel-plugin-transform-es2015-template-literals "^6.22.0" babel-plugin-transform-es2015-typeof-symbol "^6.22.0" babel-plugin-transform-es2015-unicode-regex "^6.24.1" babel-plugin-transform-regenerator "^6.24.1" babel-runtime@^6.18.0, babel-runtime@^6.22.0: version "6.23.0" resolved "https://registry.yarnpkg.com/babel-runtime/-/babel-runtime-6.23.0.tgz#0a9489f144de70efb3ce4300accdb329e2fc543b" dependencies: core-js "^2.4.0" regenerator-runtime "^0.10.0" babel-template@^6.24.1: version "6.24.1" resolved "https://registry.yarnpkg.com/babel-template/-/babel-template-6.24.1.tgz#04ae514f1f93b3a2537f2a0f60a5a45fb8308333" dependencies: babel-runtime "^6.22.0" babel-traverse "^6.24.1" babel-types "^6.24.1" babylon "^6.11.0" lodash "^4.2.0" babel-traverse@^6.24.1: version "6.24.1" resolved "https://registry.yarnpkg.com/babel-traverse/-/babel-traverse-6.24.1.tgz#ab36673fd356f9a0948659e7b338d5feadb31695" dependencies: babel-code-frame "^6.22.0" babel-messages "^6.23.0" babel-runtime "^6.22.0" babel-types "^6.24.1" babylon "^6.15.0" debug "^2.2.0" globals "^9.0.0" invariant "^2.2.0" lodash "^4.2.0" babel-types@^6.19.0, babel-types@^6.24.1: version "6.24.1" resolved "https://registry.yarnpkg.com/babel-types/-/babel-types-6.24.1.tgz#a136879dc15b3606bda0d90c1fc74304c2ff0975" dependencies: babel-runtime "^6.22.0" esutils "^2.0.2" lodash "^4.2.0" to-fast-properties "^1.0.1" babylon@^6.11.0, babylon@^6.15.0: version "6.17.0" resolved "https://registry.yarnpkg.com/babylon/-/babylon-6.17.0.tgz#37da948878488b9c4e3c4038893fa3314b3fc932" chalk@^1.1.0: version "1.1.3" resolved "https://registry.yarnpkg.com/chalk/-/chalk-1.1.3.tgz#a8115c55e4a702fe4d150abd3872822a7e09fc98" dependencies: 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" core-js@^2.4.0: version "2.4.1" resolved "https://registry.yarnpkg.com/core-js/-/core-js-2.4.1.tgz#4de911e667b0eae9124e34254b53aea6fc618d3e" debug@^2.2.0: version "2.6.6" resolved "https://registry.yarnpkg.com/debug/-/debug-2.6.6.tgz#a9fa6fbe9ca43cf1e79f73b75c0189cbb7d6db5a" dependencies: ms "0.7.3" escape-string-regexp@^1.0.2: version "1.0.5" resolved "https://registry.yarnpkg.com/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz#1b61c0562190a8dff6ae3bb2cf0200ca130b86d4" esutils@^2.0.2: version "2.0.2" resolved "https://registry.yarnpkg.com/esutils/-/esutils-2.0.2.tgz#0abf4f1caa5bcb1f7a9d8acc6dea4faaa04bac9b" globals@^9.0.0: version "9.17.0" resolved "https://registry.yarnpkg.com/globals/-/globals-9.17.0.tgz#0c0ca696d9b9bb694d2e5470bd37777caad50286" has-ansi@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/has-ansi/-/has-ansi-2.0.0.tgz#34f5049ce1ecdf2b0649af3ef24e45ed35416d91" dependencies: ansi-regex "^2.0.0" invariant@^2.2.0: version "2.2.2" resolved "https://registry.yarnpkg.com/invariant/-/invariant-2.2.2.tgz#9e1f56ac0acdb6bf303306f338be3b204ae60360" dependencies: loose-envify "^1.0.0" js-tokens@^3.0.0: version "3.0.1" resolved "https://registry.yarnpkg.com/js-tokens/-/js-tokens-3.0.1.tgz#08e9f132484a2c45a30907e9dc4d5567b7f114d7" jsesc@~0.5.0: version "0.5.0" resolved "https://registry.yarnpkg.com/jsesc/-/jsesc-0.5.0.tgz#e7dee66e35d6fc16f710fe91d5cf69f70f08911d" lodash@^4.2.0: version "4.17.4" resolved "https://registry.yarnpkg.com/lodash/-/lodash-4.17.4.tgz#78203a4d1c328ae1d86dca6460e369b57f4055ae" loose-envify@^1.0.0: version "1.3.1" resolved "https://registry.yarnpkg.com/loose-envify/-/loose-envify-1.3.1.tgz#d1a8ad33fa9ce0e713d65fdd0ac8b748d478c848" dependencies: js-tokens "^3.0.0" [email protected]: version "0.7.3" resolved "https://registry.yarnpkg.com/ms/-/ms-0.7.3.tgz#708155a5e44e33f5fd0fc53e81d0d40a91be1fff" private@^0.1.6: version "0.1.7" resolved "https://registry.yarnpkg.com/private/-/private-0.1.7.tgz#68ce5e8a1ef0a23bb570cc28537b5332aba63ef1" regenerate@^1.2.1: version "1.3.2" resolved "https://registry.yarnpkg.com/regenerate/-/regenerate-1.3.2.tgz#d1941c67bad437e1be76433add5b385f95b19260" regenerator-runtime@^0.10.0: version "0.10.4" resolved "https://registry.yarnpkg.com/regenerator-runtime/-/regenerator-runtime-0.10.4.tgz#74cb6598d3ba2eb18694e968a40e2b3b4df9cf93" [email protected]: version "0.9.11" resolved "https://registry.yarnpkg.com/regenerator-transform/-/regenerator-transform-0.9.11.tgz#3a7d067520cb7b7176769eb5ff868691befe1283" dependencies: babel-runtime "^6.18.0" babel-types "^6.19.0" private "^0.1.6" regexpu-core@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/regexpu-core/-/regexpu-core-2.0.0.tgz#49d038837b8dcf8bfa5b9a42139938e6ea2ae240" dependencies: regenerate "^1.2.1" regjsgen "^0.2.0" regjsparser "^0.1.4" regjsgen@^0.2.0: version "0.2.0" resolved "https://registry.yarnpkg.com/regjsgen/-/regjsgen-0.2.0.tgz#6c016adeac554f75823fe37ac05b92d5a4edb1f7" regjsparser@^0.1.4: version "0.1.5" resolved "https://registry.yarnpkg.com/regjsparser/-/regjsparser-0.1.5.tgz#7ee8f84dc6fa792d3fd0ae228d24bd949ead205c" dependencies: jsesc "~0.5.0" strip-ansi@^3.0.0: version "3.0.1" resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-3.0.1.tgz#6a385fb8853d952d5ff05d0e8aaf94278dc63dcf" dependencies: ansi-regex "^2.0.0" supports-color@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-2.0.0.tgz#535d045ce6b6363fa40117084629995e9df324c7" to-fast-properties@^1.0.1: version "1.0.2" resolved "https://registry.yarnpkg.com/to-fast-properties/-/to-fast-properties-1.0.2.tgz#f3f5c0c3ba7299a7ef99427e44633257ade43320"
integration_tests/native-async-mock/yarn.lock
0
https://github.com/jestjs/jest/commit/a0220a62183d689f1a9155e9c9021028d5ffa6cf
[ 0.00017312880663666874, 0.00017031935567501932, 0.00016380265878979117, 0.00017066134023480117, 0.0000019560061446100008 ]
{ "id": 2, "code_window": [ " localJestMajorVersin: number,\n", " );\n", " pathToJest: string;\n", " rootPath: string;\n", " localJestMajorVersion: number;\n", "}\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " pathToConfig: string;\n" ], "file_path": "packages/jest-editor-support/index.d.ts", "type": "add", "edit_start_line_idx": 34 }
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 'use strict'; module.exports = require('./internal-module');
packages/jest-runtime/src/__tests__/test_root/internal-root.js
0
https://github.com/jestjs/jest/commit/a0220a62183d689f1a9155e9c9021028d5ffa6cf
[ 0.00018115932471118867, 0.0001797661534510553, 0.00017837296763900667, 0.0001797661534510553, 0.0000013931785360909998 ]
{ "id": 2, "code_window": [ " localJestMajorVersin: number,\n", " );\n", " pathToJest: string;\n", " rootPath: string;\n", " localJestMajorVersion: number;\n", "}\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " pathToConfig: string;\n" ], "file_path": "packages/jest-editor-support/index.d.ts", "type": "add", "edit_start_line_idx": 34 }
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 'use strict'; it.concurrent('one', () => Promise.resolve()); it.concurrent.skip('two', () => Promise.resolve()); it.concurrent('three', () => Promise.resolve()); it.concurrent('concurrent test fails', () => Promise.reject());
integration_tests/jasmine_async/__tests__/concurrent.test.js
0
https://github.com/jestjs/jest/commit/a0220a62183d689f1a9155e9c9021028d5ffa6cf
[ 0.00017885476700030267, 0.00017802935326471925, 0.00017720395408105105, 0.00017802935326471925, 8.254064596258104e-7 ]
{ "id": 3, "code_window": [ " title: string;\n", " status: 'failed' | 'passed';\n", " failureMessages: string[];\n", "}\n", "\n", "export interface JestTotalResults {\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " fullName: string;\n" ], "file_path": "packages/jest-editor-support/index.d.ts", "type": "add", "edit_start_line_idx": 109 }
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import type {Options} from './types'; import {ChildProcess, spawn} from 'child_process'; import {readFile} from 'fs'; import {tmpdir} from 'os'; import EventEmitter from 'events'; import ProjectWorkspace from './project_workspace'; import {createProcess} from './Process'; // This class represents the running process, and // passes out events when it understands what data is being // pass sent out of the process export default class Runner extends EventEmitter { debugprocess: ChildProcess; outputPath: string; workspace: ProjectWorkspace; _createProcess: ( workspace: ProjectWorkspace, args: Array<string>, ) => ChildProcess; watchMode: boolean; constructor(workspace: ProjectWorkspace, options?: Options) { super(); this._createProcess = (options && options.createProcess) || createProcess; this.workspace = workspace; this.outputPath = tmpdir() + '/jest_runner.json'; } start(watchMode: boolean = true) { if (this.debugprocess) { return; } this.watchMode = watchMode; // Handle the arg change on v18 const belowEighteen = this.workspace.localJestMajorVersion < 18; const outputArg = belowEighteen ? '--jsonOutputFile' : '--outputFile'; const args = ['--json', '--useStderr', outputArg, this.outputPath]; if (this.watchMode) args.push('--watch'); this.debugprocess = this._createProcess(this.workspace, args); this.debugprocess.stdout.on('data', (data: Buffer) => { // Make jest save to a file, otherwise we get chunked data // and it can be hard to put it back together. const stringValue = data .toString() .replace(/\n$/, '') .trim(); if (stringValue.startsWith('Test results written to')) { readFile(this.outputPath, 'utf8', (err, data) => { if (err) { const message = `JSON report not found at ${this.outputPath}`; this.emit('terminalError', message); } else { this.emit('executableJSON', JSON.parse(data)); } }); } else { this.emit('executableOutput', stringValue.replace('', '')); } }); this.debugprocess.stderr.on('data', (data: Buffer) => { this.emit('executableStdErr', data); }); this.debugprocess.on('exit', () => { this.emit('debuggerProcessExit'); }); this.debugprocess.on('error', (error: Error) => { this.emit('terminalError', 'Process failed: ' + error.message); }); this.debugprocess.on('close', () => { this.emit('debuggerProcessExit'); }); } runJestWithUpdateForSnapshots(completion: any) { const args = ['--updateSnapshot']; const updateProcess = this._createProcess(this.workspace, args); updateProcess.on('close', () => { completion(); }); } closeProcess() { if (process.platform === 'win32') { // Windows doesn't exit the process when it should. spawn('taskkill', ['/pid', '' + this.debugprocess.pid, '/T', '/F']); } else { this.debugprocess.kill(); } delete this.debugprocess; } }
packages/jest-editor-support/src/Runner.js
1
https://github.com/jestjs/jest/commit/a0220a62183d689f1a9155e9c9021028d5ffa6cf
[ 0.00017798901535570621, 0.00016956943727564067, 0.0001643709110794589, 0.00016794232942629606, 0.000004405774234328419 ]
{ "id": 3, "code_window": [ " title: string;\n", " status: 'failed' | 'passed';\n", " failureMessages: string[];\n", "}\n", "\n", "export interface JestTotalResults {\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " fullName: string;\n" ], "file_path": "packages/jest-editor-support/index.d.ts", "type": "add", "edit_start_line_idx": 109 }
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ 'use strict'; const path = require('path'); const runJest = require('../runJest'); const DIR = path.resolve(__dirname, '../pass_with_no_tests-test'); describe('jest --passWithNoTests', () => { test('fails the test suite if no files are found', () => { const result = runJest(DIR, ['--testPathPattern', '/non/existing/path/']); const status = result.status; const stdout = result.stdout.toString(); expect(stdout).toMatch('No tests found'); expect(status).toBe(1); }); test("doesn't fail the test suite if no files are found", () => { const result = runJest(DIR, [ '--testPathPattern', '/non/existing/path/', '--passWithNoTests', ]); const status = result.status; const stdout = result.stdout.toString(); expect(stdout).toMatch('No tests found'); expect(status).toBe(0); }); });
integration_tests/__tests__/pass_with_no_tests.test.js
0
https://github.com/jestjs/jest/commit/a0220a62183d689f1a9155e9c9021028d5ffa6cf
[ 0.00039967134944163263, 0.00023253390099853277, 0.00017074067727662623, 0.00017986175953410566, 0.00009656950714997947 ]
{ "id": 3, "code_window": [ " title: string;\n", " status: 'failed' | 'passed';\n", " failureMessages: string[];\n", "}\n", "\n", "export interface JestTotalResults {\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " fullName: string;\n" ], "file_path": "packages/jest-editor-support/index.d.ts", "type": "add", "edit_start_line_idx": 109 }
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ module.exports = () => {};
integration_tests/mock-names/with-empty-mock-name/index.js
0
https://github.com/jestjs/jest/commit/a0220a62183d689f1a9155e9c9021028d5ffa6cf
[ 0.000178567657712847, 0.00017724011559039354, 0.00017591255891602486, 0.00017724011559039354, 0.0000013275493984110653 ]
{ "id": 3, "code_window": [ " title: string;\n", " status: 'failed' | 'passed';\n", " failureMessages: string[];\n", "}\n", "\n", "export interface JestTotalResults {\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " fullName: string;\n" ], "file_path": "packages/jest-editor-support/index.d.ts", "type": "add", "edit_start_line_idx": 109 }
--- id: troubleshooting title: Troubleshooting --- Uh oh, something went wrong? Use this guide to resolve issues with Jest. ### Tests are Failing and You Don't Know Why Try using the debugging support built into Node. Place a `debugger;` statement in any of your tests, and then, in your project's directory, run: ``` node --inspect-brk node_modules/.bin/jest --runInBand [any other arguments here] or on Windows node --inspect-brk ./node_modules/jest/bin/jest.js --runInBand [any other arguments here] ``` This will run Jest in a Node process that an external debugger can connect to. Note that the process will pause until the debugger has connected to it. For example, to connect the [Node Inspector](https://github.com/node-inspector/node-inspector) debugger to the paused process, you would first install it (if you don't have it installed already): ``` npm install --global node-inspector ``` Then simply run it: ``` node-inspector ``` This will output a link that you can open in Chrome. After opening that link, the Chrome Developer Tools will be displayed, and a breakpoint will be set at the first line of the Jest CLI script (this is done simply to give you time to open the developer tools and to prevent Jest from executing before you have time to do so). Click the button that looks like a "play" button in the upper right hand side of the screen to continue execution. When Jest executes the test that contains the `debugger` statement, execution will pause and you can examine the current scope and call stack. > Note: the `--runInBand` cli option makes sure Jest runs test in the same process rather than spawning processes for individual tests. Normally Jest parallelizes test runs across processes but it is hard to debug many processes at the same time. ### Debugging in VS Code There are multiple ways to debug Jest tests with [Visual Studio Code's](https://code.visualstudio.com) built in [debugger](https://code.visualstudio.com/docs/nodejs/nodejs-debugging). To attach the built-in debugger, run your tests as aforementioned: ``` node --inspect-brk node_modules/.bin/jest --runInBand [any other arguments here] or on Windows node --inspect-brk ./node_modules/jest/bin/jest.js --runInBand [any other arguments here] ``` Then attach VS Code's debugger using the following `launch.json` config: ```json { "version": "0.2.0", "configurations": [ { "type": "node", "request": "attach", "name": "Attach", "port": 9229 }, ] } ``` To automatically launch and attach to a process running your tests, use the following configuration: ```json { "version": "0.2.0", "configurations": [ { "name": "Debug Jest Tests", "type": "node", "request": "launch", "runtimeArgs": [ "--inspect-brk", "${workspaceRoot}/node_modules/.bin/jest", "--runInBand" ], "console": "integratedTerminal", "internalConsoleOptions": "neverOpen" } ] } ``` If you are using Facebook's [`create-react-app`](https://github.com/facebookincubator/create-react-app), you can debug your Jest tests with the following configuration: ```json { "version": "0.2.0", "configurations": [ { "name": "Debug CRA Tests", "type": "node", "request": "launch", "runtimeExecutable": "${workspaceRoot}/node_modules/.bin/react-scripts", "runtimeArgs": [ "--inspect-brk", "test" ], "args": [ "--runInBand", "--no-cache", "--env=jsdom" ], "cwd": "${workspaceRoot}", "protocol": "inspector", "console": "integratedTerminal", "internalConsoleOptions": "neverOpen" } ] } ``` More information on Node debugging can be found [here](https://nodejs.org/api/debugger.html). ### Debugging in WebStorm The easiest way to debug Jest tests in [WebStorm](https://www.jetbrains.com/webstorm/) is using `Jest run/debug configuration`. It will launch tests and automatically attach debugger. In the WebStorm menu `Run` select `Edit Configurations...`. Then click `+` and select `Jest`. Optionally specify the Jest configuration file, additional options, and environment variables. Save the configuration, put the breakpoints in the code, then click the green debug icon to start debugging. If you are using Facebook's [`create-react-app`](https://github.com/facebookincubator/create-react-app), in the Jest run/debug configuration specify the path to the `react-scripts` package in the Jest package field and add `--env=jsdom` to the Jest options field. ### Caching Issues The transform script was changed or babel was updated and the changes aren't being recognized by Jest? Retry with [`--no-cache`](CLI.md#cache). Jest caches transformed module files to speed up test execution. If you are using your own custom transformer, consider adding a `getCacheKey` function to it: [getCacheKey in Relay](https://github.com/facebook/relay/blob/58cf36c73769690f0bbf90562707eadb062b029d/scripts/jest/preprocessor.js#L56-L61). ### Unresolved Promises If a promise doesn't resolve at all, this error might be thrown: ``` - Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.` ``` Most commonly this is being caused by conflicting Promise implementations. Consider replacing the global promise implementation with your own, for example `global.Promise = require.requireActual('promise');` and/or consolidate the used Promise libraries to a single one. If your test is long running, you may want to consider to increase the timeout by calling `jest.setTimeout` ``` jest.setTimeout(10000); // 10 second timeout ``` ### Watchman Issues Try running Jest with [`--no-watchman`](CLI.md#watchman) or set the `watchman` configuration option to `false`. Also see [watchman troubleshooting](https://facebook.github.io/watchman/docs/troubleshooting.html). ### Tests are Extremely Slow on Docker and/or Continuous Integration (CI) server. While Jest is most of the time extremely fast on modern multi-core computers with fast SSDs, it may be slow on certain setups as our users [have](https://github.com/facebook/jest/issues/1395) [discovered](https://github.com/facebook/jest/issues/1524#issuecomment-260246008). Based on the [findings](https://github.com/facebook/jest/issues/1524#issuecomment-262366820), one way to mitigate this issue and improve the speed by up to 50% is to run tests sequentially. In order to do this you can run tests in the same thread using [`--runInBand`](CLI.md#runinband): ```bash # Using Jest CLI jest --runInBand # Using npm test (e.g. with create-react-app) npm test -- --runInBand ``` Another alternative to expediting test execution time on Continuous Integration Servers such as Travis-CI is to set the max worker pool to ~_4_. Specifically on Travis-CI, this can reduce test execution time in half. Note: The Travis CI _free_ plan available for open source projects only includes 2 CPU cores. ```bash # Using Jest CLI jest --maxWorkers=4 # Using npm test (e.g. with create-react-app) npm test -- --maxWorkers=4 ``` ### Tests are slow when leveraging automocking Whether via [`automock: true`](configuration.html#automock-boolean) in config or lots of [`jest.mock('my-module')`](jest-object.html#jestmockmodulename-factory-options) calls in tests, automocking has a performance cost that can add up in large projects. The more dependencies a module has, the more work Jest has to do to mock it. Something that can offset this performance cost significantly is adding a code transformer that moves `import` or `require` calls from the top of a module, where they are always executed, down into the body of the module, where they are usually not executed. This can lower the number of modules Jest has to load when running your tests by a considerable amount. To transform `import` statements, there is [babel-plugin-transform-inline-imports-commonjs](https://github.com/zertosh/babel-plugin-transform-inline-imports-commonjs), and to transform `require` statements, there is [Facebook's `inline-requires` babel plugin](https://github.com/facebook/fbjs/blob/master/packages/babel-preset-fbjs/plugins/inline-requires.js), which is part of the `babel-preset-fbjs` package. ### I'm using npm3 and my node_modules aren't properly loading. Upgrade `jest-cli` to `0.9.0` or above. ### I'm using babel and my unmocked imports aren't working? Upgrade `jest-cli` to `0.9.0` or above. Explanation: ```js jest.dontMock('foo'); import foo from './foo'; ``` In ES6, import statements get hoisted before all other ```js const foo = require('foo'); jest.dontMock('foo'); // Oops! ``` In Jest 0.9.0, a new API `jest.unmock` was introduced. Together with a plugin for babel, this will now work properly when using `babel-jest`: ```js jest.unmock('./foo'); // Use unmock! import foo from './foo'; // foo is not mocked! ``` See the [Getting Started]GettingStarted.md#using-babel) guide on how to enable babel support. ### I upgraded to Jest 0.9.0 and my tests are now failing? Jest is now using Jasmine 2 by default. It should be easy to upgrade using the Jasmine [upgrade guide](http://jasmine.github.io/2.0/introduction.html). If you would like to continue using Jasmine 1, set the `testRunner` config option to `jasmine1` or pass `--testRunner=jasmine1` as a command line option. ### Compatibility issues Jest takes advantage of new features added to Node 4. We recommend that you upgrade to the latest stable release of Node. The minimum supported version is `v4.0.0`. Versions `0.x.x` are not supported. ### `coveragePathIgnorePatterns` seems to not have any effect. Make sure you are not using the `babel-plugin-istanbul` plugin. Jest wraps Istanbul, and therefore also tells Istanbul what files to instrument with coverage collection. When using `babel-plugin-istanbul`, every file that is processed by Babel will have coverage collection code, hence it is not being ignored by `coveragePathIgnorePatterns`. ### Still unresolved? See [Help](/jest/help.html).
docs/Troubleshooting.md
0
https://github.com/jestjs/jest/commit/a0220a62183d689f1a9155e9c9021028d5ffa6cf
[ 0.00017220697191078216, 0.0001669113407842815, 0.00016163656255230308, 0.00016680460248608142, 0.000002741659955063369 ]
{ "id": 4, "code_window": [ " _createProcess: (\n", " workspace: ProjectWorkspace,\n", " args: Array<string>,\n", " ) => ChildProcess;\n", " watchMode: boolean;\n", "\n", " constructor(workspace: ProjectWorkspace, options?: Options) {\n", " super();\n", " this._createProcess = (options && options.createProcess) || createProcess;\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " options: Options;\n" ], "file_path": "packages/jest-editor-support/src/Runner.js", "type": "add", "edit_start_line_idx": 30 }
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import type {Options} from './types'; import {ChildProcess, spawn} from 'child_process'; import {readFile} from 'fs'; import {tmpdir} from 'os'; import EventEmitter from 'events'; import ProjectWorkspace from './project_workspace'; import {createProcess} from './Process'; // This class represents the running process, and // passes out events when it understands what data is being // pass sent out of the process export default class Runner extends EventEmitter { debugprocess: ChildProcess; outputPath: string; workspace: ProjectWorkspace; _createProcess: ( workspace: ProjectWorkspace, args: Array<string>, ) => ChildProcess; watchMode: boolean; constructor(workspace: ProjectWorkspace, options?: Options) { super(); this._createProcess = (options && options.createProcess) || createProcess; this.workspace = workspace; this.outputPath = tmpdir() + '/jest_runner.json'; } start(watchMode: boolean = true) { if (this.debugprocess) { return; } this.watchMode = watchMode; // Handle the arg change on v18 const belowEighteen = this.workspace.localJestMajorVersion < 18; const outputArg = belowEighteen ? '--jsonOutputFile' : '--outputFile'; const args = ['--json', '--useStderr', outputArg, this.outputPath]; if (this.watchMode) args.push('--watch'); this.debugprocess = this._createProcess(this.workspace, args); this.debugprocess.stdout.on('data', (data: Buffer) => { // Make jest save to a file, otherwise we get chunked data // and it can be hard to put it back together. const stringValue = data .toString() .replace(/\n$/, '') .trim(); if (stringValue.startsWith('Test results written to')) { readFile(this.outputPath, 'utf8', (err, data) => { if (err) { const message = `JSON report not found at ${this.outputPath}`; this.emit('terminalError', message); } else { this.emit('executableJSON', JSON.parse(data)); } }); } else { this.emit('executableOutput', stringValue.replace('', '')); } }); this.debugprocess.stderr.on('data', (data: Buffer) => { this.emit('executableStdErr', data); }); this.debugprocess.on('exit', () => { this.emit('debuggerProcessExit'); }); this.debugprocess.on('error', (error: Error) => { this.emit('terminalError', 'Process failed: ' + error.message); }); this.debugprocess.on('close', () => { this.emit('debuggerProcessExit'); }); } runJestWithUpdateForSnapshots(completion: any) { const args = ['--updateSnapshot']; const updateProcess = this._createProcess(this.workspace, args); updateProcess.on('close', () => { completion(); }); } closeProcess() { if (process.platform === 'win32') { // Windows doesn't exit the process when it should. spawn('taskkill', ['/pid', '' + this.debugprocess.pid, '/T', '/F']); } else { this.debugprocess.kill(); } delete this.debugprocess; } }
packages/jest-editor-support/src/Runner.js
1
https://github.com/jestjs/jest/commit/a0220a62183d689f1a9155e9c9021028d5ffa6cf
[ 0.9959771037101746, 0.27691879868507385, 0.00016666261944919825, 0.002008007373660803, 0.42105892300605774 ]
{ "id": 4, "code_window": [ " _createProcess: (\n", " workspace: ProjectWorkspace,\n", " args: Array<string>,\n", " ) => ChildProcess;\n", " watchMode: boolean;\n", "\n", " constructor(workspace: ProjectWorkspace, options?: Options) {\n", " super();\n", " this._createProcess = (options && options.createProcess) || createProcess;\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " options: Options;\n" ], "file_path": "packages/jest-editor-support/src/Runner.js", "type": "add", "edit_start_line_idx": 30 }
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import type {Config, NewPlugin, Printer, Refs} from 'types/PrettyFormat'; import { printChildren, printComment, printElement, printElementAsLeaf, printProps, printText, } from './lib/markup'; type Attribute = { name: string, value: string, }; type Element = { attributes: Array<Attribute>, childNodes: Array<Element | Text | Comment>, nodeType: 1, tagName: string, }; type Text = { data: string, nodeType: 3, }; type Comment = { data: string, nodeType: 8, }; const ELEMENT_NODE = 1; const TEXT_NODE = 3; const COMMENT_NODE = 8; const ELEMENT_REGEXP = /^((HTML|SVG)\w*)?Element$/; const testNode = (nodeType: any, name: any) => (nodeType === ELEMENT_NODE && ELEMENT_REGEXP.test(name)) || (nodeType === TEXT_NODE && name === 'Text') || (nodeType === COMMENT_NODE && name === 'Comment'); export const test = (val: any) => val && val.constructor && val.constructor.name && testNode(val.nodeType, val.constructor.name); // Convert array of attribute objects to keys array and props object. const keysMapper = attribute => attribute.name; const propsReducer = (props, attribute) => { props[attribute.name] = attribute.value; return props; }; export const serialize = ( node: Element | Text | Comment, config: Config, indentation: string, depth: number, refs: Refs, printer: Printer, ): string => { if (node.nodeType === TEXT_NODE) { return printText(node.data, config); } if (node.nodeType === COMMENT_NODE) { return printComment(node.data, config); } const type = node.tagName.toLowerCase(); if (++depth > config.maxDepth) { return printElementAsLeaf(type, config); } return printElement( type, printProps( Array.prototype.map.call(node.attributes, keysMapper).sort(), Array.prototype.reduce.call(node.attributes, propsReducer, {}), config, indentation + config.indent, depth, refs, printer, ), printChildren( Array.prototype.slice.call(node.childNodes), config, indentation + config.indent, depth, refs, printer, ), config, indentation, ); }; export default ({serialize, test}: NewPlugin);
packages/pretty-format/src/plugins/dom_element.js
0
https://github.com/jestjs/jest/commit/a0220a62183d689f1a9155e9c9021028d5ffa6cf
[ 0.00018360854301135987, 0.00017597770784050226, 0.00017005877452902496, 0.0001772178802639246, 0.0000036145718240732094 ]
{ "id": 4, "code_window": [ " _createProcess: (\n", " workspace: ProjectWorkspace,\n", " args: Array<string>,\n", " ) => ChildProcess;\n", " watchMode: boolean;\n", "\n", " constructor(workspace: ProjectWorkspace, options?: Options) {\n", " super();\n", " this._createProcess = (options && options.createProcess) || createProcess;\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " options: Options;\n" ], "file_path": "packages/jest-editor-support/src/Runner.js", "type": "add", "edit_start_line_idx": 30 }
// test.jsx require('../module.jsx');
packages/jest-cli/src/__tests__/test_root/__testtests__/test.jsx
0
https://github.com/jestjs/jest/commit/a0220a62183d689f1a9155e9c9021028d5ffa6cf
[ 0.00017737688904162496, 0.00017737688904162496, 0.00017737688904162496, 0.00017737688904162496, 0 ]
{ "id": 4, "code_window": [ " _createProcess: (\n", " workspace: ProjectWorkspace,\n", " args: Array<string>,\n", " ) => ChildProcess;\n", " watchMode: boolean;\n", "\n", " constructor(workspace: ProjectWorkspace, options?: Options) {\n", " super();\n", " this._createProcess = (options && options.createProcess) || createProcess;\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " options: Options;\n" ], "file_path": "packages/jest-editor-support/src/Runner.js", "type": "add", "edit_start_line_idx": 30 }
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 'use strict'; require('../this-directory-is-covered/excluded-from-coverage'); it('strips flowtypes using babel-jest and .babelrc', () => { const a: string = 'a'; expect(a).toBe('a'); });
integration_tests/transform/babel-jest/__tests__/babel_jest.test.js
0
https://github.com/jestjs/jest/commit/a0220a62183d689f1a9155e9c9021028d5ffa6cf
[ 0.00017854466568678617, 0.00017405502148903906, 0.00016956539184320718, 0.00017405502148903906, 0.000004489636921789497 ]
{ "id": 5, "code_window": [ "\n", " constructor(workspace: ProjectWorkspace, options?: Options) {\n", " super();\n", " this._createProcess = (options && options.createProcess) || createProcess;\n", " this.workspace = workspace;\n", " this.outputPath = tmpdir() + '/jest_runner.json';\n", " }\n", "\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " this.options = options || {};\n" ], "file_path": "packages/jest-editor-support/src/Runner.js", "type": "add", "edit_start_line_idx": 34 }
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import type {Options} from './types'; import {ChildProcess, spawn} from 'child_process'; import {readFile} from 'fs'; import {tmpdir} from 'os'; import EventEmitter from 'events'; import ProjectWorkspace from './project_workspace'; import {createProcess} from './Process'; // This class represents the running process, and // passes out events when it understands what data is being // pass sent out of the process export default class Runner extends EventEmitter { debugprocess: ChildProcess; outputPath: string; workspace: ProjectWorkspace; _createProcess: ( workspace: ProjectWorkspace, args: Array<string>, ) => ChildProcess; watchMode: boolean; constructor(workspace: ProjectWorkspace, options?: Options) { super(); this._createProcess = (options && options.createProcess) || createProcess; this.workspace = workspace; this.outputPath = tmpdir() + '/jest_runner.json'; } start(watchMode: boolean = true) { if (this.debugprocess) { return; } this.watchMode = watchMode; // Handle the arg change on v18 const belowEighteen = this.workspace.localJestMajorVersion < 18; const outputArg = belowEighteen ? '--jsonOutputFile' : '--outputFile'; const args = ['--json', '--useStderr', outputArg, this.outputPath]; if (this.watchMode) args.push('--watch'); this.debugprocess = this._createProcess(this.workspace, args); this.debugprocess.stdout.on('data', (data: Buffer) => { // Make jest save to a file, otherwise we get chunked data // and it can be hard to put it back together. const stringValue = data .toString() .replace(/\n$/, '') .trim(); if (stringValue.startsWith('Test results written to')) { readFile(this.outputPath, 'utf8', (err, data) => { if (err) { const message = `JSON report not found at ${this.outputPath}`; this.emit('terminalError', message); } else { this.emit('executableJSON', JSON.parse(data)); } }); } else { this.emit('executableOutput', stringValue.replace('', '')); } }); this.debugprocess.stderr.on('data', (data: Buffer) => { this.emit('executableStdErr', data); }); this.debugprocess.on('exit', () => { this.emit('debuggerProcessExit'); }); this.debugprocess.on('error', (error: Error) => { this.emit('terminalError', 'Process failed: ' + error.message); }); this.debugprocess.on('close', () => { this.emit('debuggerProcessExit'); }); } runJestWithUpdateForSnapshots(completion: any) { const args = ['--updateSnapshot']; const updateProcess = this._createProcess(this.workspace, args); updateProcess.on('close', () => { completion(); }); } closeProcess() { if (process.platform === 'win32') { // Windows doesn't exit the process when it should. spawn('taskkill', ['/pid', '' + this.debugprocess.pid, '/T', '/F']); } else { this.debugprocess.kill(); } delete this.debugprocess; } }
packages/jest-editor-support/src/Runner.js
1
https://github.com/jestjs/jest/commit/a0220a62183d689f1a9155e9c9021028d5ffa6cf
[ 0.9980754852294922, 0.2725833058357239, 0.00016498929471708834, 0.0004702343721874058, 0.4311298429965973 ]
{ "id": 5, "code_window": [ "\n", " constructor(workspace: ProjectWorkspace, options?: Options) {\n", " super();\n", " this._createProcess = (options && options.createProcess) || createProcess;\n", " this.workspace = workspace;\n", " this.outputPath = tmpdir() + '/jest_runner.json';\n", " }\n", "\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " this.options = options || {};\n" ], "file_path": "packages/jest-editor-support/src/Runner.js", "type": "add", "edit_start_line_idx": 34 }
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ 'use strict'; const path = require('path'); const skipOnWindows = require('../../scripts/skip_on_windows'); const {extractSummary, cleanup, writeFiles} = require('../utils'); const runJest = require('../runJest'); const DIR = path.resolve(__dirname, '../jest.config.js'); skipOnWindows.suite(); beforeEach(() => cleanup(DIR)); afterAll(() => cleanup(DIR)); test('works with jest.conf.js', () => { writeFiles(DIR, { '__tests__/a-banana.js': `test('banana', () => expect(1).toBe(1));`, 'jest.config.js': `module.exports = {testRegex: '.*-banana.js'};`, 'package.json': '{}', }); const {stderr, status} = runJest(DIR, ['-w=1', '--ci=false']); const {rest, summary} = extractSummary(stderr); expect(status).toBe(0); expect(rest).toMatchSnapshot(); expect(summary).toMatchSnapshot(); }); test('traverses directory tree up until it finds jest.config', () => { writeFiles(DIR, { '__tests__/a-banana.js': ` test('banana', () => expect(1).toBe(1)); test('abc', () => console.log(process.cwd())); `, 'jest.config.js': `module.exports = {testRegex: '.*-banana.js'};`, 'package.json': '{}', 'some/nested/directory/file.js': '// nothing special', }); const {stderr, status, stdout} = runJest( path.join(DIR, 'some', 'nested', 'directory'), ['-w=1', '--ci=false'], {skipPkgJsonCheck: true}, ); // Snapshot the console.loged `process.cwd()` and make sure it stays the same expect( stdout.replace(/^\W+(.*)integration_tests/gm, '<<REPLACED>>'), ).toMatchSnapshot(); const {rest, summary} = extractSummary(stderr); expect(status).toBe(0); expect(rest).toMatchSnapshot(); expect(summary).toMatchSnapshot(); }); test('invalid JS in jest.config.js', () => { writeFiles(DIR, { '__tests__/a-banana.js': `test('banana', () => expect(1).toBe(1));`, 'jest.config.js': `module.exports = i'll break this file yo`, 'package.json': '{}', }); const {stderr, status} = runJest(DIR, ['-w=1', '--ci=false']); expect(stderr).toMatch('SyntaxError: '); expect(status).toBe(1); });
integration_tests/__tests__/jest.config.js.test.js
0
https://github.com/jestjs/jest/commit/a0220a62183d689f1a9155e9c9021028d5ffa6cf
[ 0.00017850908625405282, 0.00017267942894250154, 0.0001673162478255108, 0.00017326604574918747, 0.0000032970956453937106 ]
{ "id": 5, "code_window": [ "\n", " constructor(workspace: ProjectWorkspace, options?: Options) {\n", " super();\n", " this._createProcess = (options && options.createProcess) || createProcess;\n", " this.workspace = workspace;\n", " this.outputPath = tmpdir() + '/jest_runner.json';\n", " }\n", "\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " this.options = options || {};\n" ], "file_path": "packages/jest-editor-support/src/Runner.js", "type": "add", "edit_start_line_idx": 34 }
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import type {GlobalConfig} from 'types/Config'; import type { OnTestFailure, OnTestStart, OnTestSuccess, Test, TestRunnerOptions, TestWatcher, } from 'types/TestRunner'; import pify from 'pify'; import runTest from './run_test'; import throat from 'throat'; import workerFarm from 'worker-farm'; const TEST_WORKER_PATH = require.resolve('./test_worker'); class TestRunner { _globalConfig: GlobalConfig; constructor(globalConfig: GlobalConfig) { this._globalConfig = globalConfig; } async runTests( tests: Array<Test>, watcher: TestWatcher, onStart: OnTestStart, onResult: OnTestSuccess, onFailure: OnTestFailure, options: TestRunnerOptions, ): Promise<void> { return await (options.serial ? this._createInBandTestRun(tests, watcher, onStart, onResult, onFailure) : this._createParallelTestRun( tests, watcher, onStart, onResult, onFailure, )); } async _createInBandTestRun( tests: Array<Test>, watcher: TestWatcher, onStart: OnTestStart, onResult: OnTestSuccess, onFailure: OnTestFailure, ) { const mutex = throat(1); return tests.reduce( (promise, test) => mutex(() => promise .then(async () => { if (watcher.isInterrupted()) { throw new CancelRun(); } await onStart(test); return runTest( test.path, this._globalConfig, test.context.config, test.context.resolver, ); }) .then(result => onResult(test, result)) .catch(err => onFailure(test, err)), ), Promise.resolve(), ); } async _createParallelTestRun( tests: Array<Test>, watcher: TestWatcher, onStart: OnTestStart, onResult: OnTestSuccess, onFailure: OnTestFailure, ) { const farm = workerFarm( { autoStart: true, maxConcurrentCallsPerWorker: 1, maxConcurrentWorkers: this._globalConfig.maxWorkers, maxRetries: 2, // Allow for a couple of transient errors. }, TEST_WORKER_PATH, ); const mutex = throat(this._globalConfig.maxWorkers); const worker = pify(farm); // Send test suites to workers continuously instead of all at once to track // the start time of individual tests. const runTestInWorker = test => mutex(async () => { if (watcher.isInterrupted()) { return Promise.reject(); } await onStart(test); return worker({ config: test.context.config, globalConfig: this._globalConfig, path: test.path, rawModuleMap: watcher.isWatchMode() ? test.context.moduleMap.getRawModuleMap() : null, }); }); const onError = async (err, test) => { await onFailure(test, err); if (err.type === 'ProcessTerminatedError') { console.error( 'A worker process has quit unexpectedly! ' + 'Most likely this is an initialization error.', ); process.exit(1); } }; const onInterrupt = new Promise((_, reject) => { watcher.on('change', state => { if (state.interrupted) { reject(new CancelRun()); } }); }); const runAllTests = Promise.all( tests.map(test => runTestInWorker(test) .then(testResult => onResult(test, testResult)) .catch(error => onError(error, test)), ), ); const cleanup = () => workerFarm.end(farm); return Promise.race([runAllTests, onInterrupt]).then(cleanup, cleanup); } } class CancelRun extends Error { constructor(message: ?string) { super(message); this.name = 'CancelRun'; } } module.exports = TestRunner;
packages/jest-runner/src/index.js
0
https://github.com/jestjs/jest/commit/a0220a62183d689f1a9155e9c9021028d5ffa6cf
[ 0.003522752318531275, 0.0004437999741639942, 0.0001681620196904987, 0.00017508157179690897, 0.0008239787421189249 ]
{ "id": 5, "code_window": [ "\n", " constructor(workspace: ProjectWorkspace, options?: Options) {\n", " super();\n", " this._createProcess = (options && options.createProcess) || createProcess;\n", " this.workspace = workspace;\n", " this.outputPath = tmpdir() + '/jest_runner.json';\n", " }\n", "\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " this.options = options || {};\n" ], "file_path": "packages/jest-editor-support/src/Runner.js", "type": "add", "edit_start_line_idx": 34 }
// Copyright 2004-present Facebook. All Rights Reserved. it('adds 1 + 2 to equal 3 in Typescript', () => { const sum = require('../sum.ts'); expect(sum(1, 2)).toBe(3); }); it('adds 1 + 2 to equal 3 in JavaScript', () => { const sum = require('../sum.js'); expect(sum(1, 2)).toBe(3); });
examples/typescript/__tests__/sum.test.js
0
https://github.com/jestjs/jest/commit/a0220a62183d689f1a9155e9c9021028d5ffa6cf
[ 0.00018080641166307032, 0.00017962217680178583, 0.00017843795649241656, 0.00017962217680178583, 0.0000011842275853268802 ]
{ "id": 6, "code_window": [ "\n", " const args = ['--json', '--useStderr', outputArg, this.outputPath];\n", " if (this.watchMode) args.push('--watch');\n", "\n", " this.debugprocess = this._createProcess(this.workspace, args);\n", " this.debugprocess.stdout.on('data', (data: Buffer) => {\n", " // Make jest save to a file, otherwise we get chunked data\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " if (this.options.testNamePattern) {\n", " args.push('--testNamePattern', this.options.testNamePattern);\n", " }\n", " if (this.options.testFileNamePattern) {\n", " args.push(this.options.testFileNamePattern);\n", " }\n" ], "file_path": "packages/jest-editor-support/src/Runner.js", "type": "add", "edit_start_line_idx": 51 }
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import type {Options} from './types'; import {ChildProcess, spawn} from 'child_process'; import {readFile} from 'fs'; import {tmpdir} from 'os'; import EventEmitter from 'events'; import ProjectWorkspace from './project_workspace'; import {createProcess} from './Process'; // This class represents the running process, and // passes out events when it understands what data is being // pass sent out of the process export default class Runner extends EventEmitter { debugprocess: ChildProcess; outputPath: string; workspace: ProjectWorkspace; _createProcess: ( workspace: ProjectWorkspace, args: Array<string>, ) => ChildProcess; watchMode: boolean; constructor(workspace: ProjectWorkspace, options?: Options) { super(); this._createProcess = (options && options.createProcess) || createProcess; this.workspace = workspace; this.outputPath = tmpdir() + '/jest_runner.json'; } start(watchMode: boolean = true) { if (this.debugprocess) { return; } this.watchMode = watchMode; // Handle the arg change on v18 const belowEighteen = this.workspace.localJestMajorVersion < 18; const outputArg = belowEighteen ? '--jsonOutputFile' : '--outputFile'; const args = ['--json', '--useStderr', outputArg, this.outputPath]; if (this.watchMode) args.push('--watch'); this.debugprocess = this._createProcess(this.workspace, args); this.debugprocess.stdout.on('data', (data: Buffer) => { // Make jest save to a file, otherwise we get chunked data // and it can be hard to put it back together. const stringValue = data .toString() .replace(/\n$/, '') .trim(); if (stringValue.startsWith('Test results written to')) { readFile(this.outputPath, 'utf8', (err, data) => { if (err) { const message = `JSON report not found at ${this.outputPath}`; this.emit('terminalError', message); } else { this.emit('executableJSON', JSON.parse(data)); } }); } else { this.emit('executableOutput', stringValue.replace('', '')); } }); this.debugprocess.stderr.on('data', (data: Buffer) => { this.emit('executableStdErr', data); }); this.debugprocess.on('exit', () => { this.emit('debuggerProcessExit'); }); this.debugprocess.on('error', (error: Error) => { this.emit('terminalError', 'Process failed: ' + error.message); }); this.debugprocess.on('close', () => { this.emit('debuggerProcessExit'); }); } runJestWithUpdateForSnapshots(completion: any) { const args = ['--updateSnapshot']; const updateProcess = this._createProcess(this.workspace, args); updateProcess.on('close', () => { completion(); }); } closeProcess() { if (process.platform === 'win32') { // Windows doesn't exit the process when it should. spawn('taskkill', ['/pid', '' + this.debugprocess.pid, '/T', '/F']); } else { this.debugprocess.kill(); } delete this.debugprocess; } }
packages/jest-editor-support/src/Runner.js
1
https://github.com/jestjs/jest/commit/a0220a62183d689f1a9155e9c9021028d5ffa6cf
[ 0.9979032278060913, 0.3801681399345398, 0.00016356137348338962, 0.035698726773262024, 0.4622465968132019 ]
{ "id": 6, "code_window": [ "\n", " const args = ['--json', '--useStderr', outputArg, this.outputPath];\n", " if (this.watchMode) args.push('--watch');\n", "\n", " this.debugprocess = this._createProcess(this.workspace, args);\n", " this.debugprocess.stdout.on('data', (data: Buffer) => {\n", " // Make jest save to a file, otherwise we get chunked data\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " if (this.options.testNamePattern) {\n", " args.push('--testNamePattern', this.options.testNamePattern);\n", " }\n", " if (this.options.testFileNamePattern) {\n", " args.push(this.options.testFileNamePattern);\n", " }\n" ], "file_path": "packages/jest-editor-support/src/Runner.js", "type": "add", "edit_start_line_idx": 51 }
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ module.exports = () => {};
integration_tests/auto-clear-mocks/with-auto-clear/index.js
0
https://github.com/jestjs/jest/commit/a0220a62183d689f1a9155e9c9021028d5ffa6cf
[ 0.00017813112935982645, 0.00017333045252598822, 0.00016852977569215, 0.00017333045252598822, 0.000004800676833838224 ]
{ "id": 6, "code_window": [ "\n", " const args = ['--json', '--useStderr', outputArg, this.outputPath];\n", " if (this.watchMode) args.push('--watch');\n", "\n", " this.debugprocess = this._createProcess(this.workspace, args);\n", " this.debugprocess.stdout.on('data', (data: Buffer) => {\n", " // Make jest save to a file, otherwise we get chunked data\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " if (this.options.testNamePattern) {\n", " args.push('--testNamePattern', this.options.testNamePattern);\n", " }\n", " if (this.options.testFileNamePattern) {\n", " args.push(this.options.testFileNamePattern);\n", " }\n" ], "file_path": "packages/jest-editor-support/src/Runner.js", "type": "add", "edit_start_line_idx": 51 }
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ global.setup = true;
integration_tests/coverage_report/setup.js
0
https://github.com/jestjs/jest/commit/a0220a62183d689f1a9155e9c9021028d5ffa6cf
[ 0.00017897931684274226, 0.00017897931684274226, 0.00017897931684274226, 0.00017897931684274226, 0 ]
{ "id": 6, "code_window": [ "\n", " const args = ['--json', '--useStderr', outputArg, this.outputPath];\n", " if (this.watchMode) args.push('--watch');\n", "\n", " this.debugprocess = this._createProcess(this.workspace, args);\n", " this.debugprocess.stdout.on('data', (data: Buffer) => {\n", " // Make jest save to a file, otherwise we get chunked data\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " if (this.options.testNamePattern) {\n", " args.push('--testNamePattern', this.options.testNamePattern);\n", " }\n", " if (this.options.testFileNamePattern) {\n", " args.push(this.options.testFileNamePattern);\n", " }\n" ], "file_path": "packages/jest-editor-support/src/Runner.js", "type": "add", "edit_start_line_idx": 51 }
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ type Location = { column: number, line: number, }; type NodeLocation = { end: Location, start: Location, }; type ParentNode = CallExpression | MemberExpression; export type Node = CallExpression | MemberExpression | Identifier | Literal; export type Identifier = { type: 'Identifier', name: string, value: string, parent: ParentNode, loc: NodeLocation, }; export type MemberExpression = { type: 'MemberExpression', name: string, expression: CallExpression, property: Identifier, object: Identifier, parent: ParentNode, loc: NodeLocation, }; export type Literal = { type: 'Literal', value?: string, rawValue?: string, parent: ParentNode, loc: NodeLocation, }; export type CallExpression = { type: 'CallExpression', arguments: Array<Literal>, callee: Identifier | MemberExpression, parent: ParentNode, loc: NodeLocation, }; export type EslintContext = {| report: ({loc?: NodeLocation, message: string, node: any}) => void, |};
packages/eslint-plugin-jest/src/rules/types.js
0
https://github.com/jestjs/jest/commit/a0220a62183d689f1a9155e9c9021028d5ffa6cf
[ 0.00018057123816106468, 0.0001748892100295052, 0.00016852961562108248, 0.00017497176304459572, 0.000003300026037322823 ]
{ "id": 7, "code_window": [ " completion();\n", " });\n", " }\n", "\n", " closeProcess() {\n", " if (process.platform === 'win32') {\n", " // Windows doesn't exit the process when it should.\n", " spawn('taskkill', ['/pid', '' + this.debugprocess.pid, '/T', '/F']);\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " if (!this.debugprocess) {\n", " return;\n", " }\n" ], "file_path": "packages/jest-editor-support/src/Runner.js", "type": "add", "edit_start_line_idx": 100 }
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import type {Options} from './types'; import {ChildProcess, spawn} from 'child_process'; import {readFile} from 'fs'; import {tmpdir} from 'os'; import EventEmitter from 'events'; import ProjectWorkspace from './project_workspace'; import {createProcess} from './Process'; // This class represents the running process, and // passes out events when it understands what data is being // pass sent out of the process export default class Runner extends EventEmitter { debugprocess: ChildProcess; outputPath: string; workspace: ProjectWorkspace; _createProcess: ( workspace: ProjectWorkspace, args: Array<string>, ) => ChildProcess; watchMode: boolean; constructor(workspace: ProjectWorkspace, options?: Options) { super(); this._createProcess = (options && options.createProcess) || createProcess; this.workspace = workspace; this.outputPath = tmpdir() + '/jest_runner.json'; } start(watchMode: boolean = true) { if (this.debugprocess) { return; } this.watchMode = watchMode; // Handle the arg change on v18 const belowEighteen = this.workspace.localJestMajorVersion < 18; const outputArg = belowEighteen ? '--jsonOutputFile' : '--outputFile'; const args = ['--json', '--useStderr', outputArg, this.outputPath]; if (this.watchMode) args.push('--watch'); this.debugprocess = this._createProcess(this.workspace, args); this.debugprocess.stdout.on('data', (data: Buffer) => { // Make jest save to a file, otherwise we get chunked data // and it can be hard to put it back together. const stringValue = data .toString() .replace(/\n$/, '') .trim(); if (stringValue.startsWith('Test results written to')) { readFile(this.outputPath, 'utf8', (err, data) => { if (err) { const message = `JSON report not found at ${this.outputPath}`; this.emit('terminalError', message); } else { this.emit('executableJSON', JSON.parse(data)); } }); } else { this.emit('executableOutput', stringValue.replace('', '')); } }); this.debugprocess.stderr.on('data', (data: Buffer) => { this.emit('executableStdErr', data); }); this.debugprocess.on('exit', () => { this.emit('debuggerProcessExit'); }); this.debugprocess.on('error', (error: Error) => { this.emit('terminalError', 'Process failed: ' + error.message); }); this.debugprocess.on('close', () => { this.emit('debuggerProcessExit'); }); } runJestWithUpdateForSnapshots(completion: any) { const args = ['--updateSnapshot']; const updateProcess = this._createProcess(this.workspace, args); updateProcess.on('close', () => { completion(); }); } closeProcess() { if (process.platform === 'win32') { // Windows doesn't exit the process when it should. spawn('taskkill', ['/pid', '' + this.debugprocess.pid, '/T', '/F']); } else { this.debugprocess.kill(); } delete this.debugprocess; } }
packages/jest-editor-support/src/Runner.js
1
https://github.com/jestjs/jest/commit/a0220a62183d689f1a9155e9c9021028d5ffa6cf
[ 0.7880128622055054, 0.14442060887813568, 0.0001667853503022343, 0.0034650301095098257, 0.30009695887565613 ]
{ "id": 7, "code_window": [ " completion();\n", " });\n", " }\n", "\n", " closeProcess() {\n", " if (process.platform === 'win32') {\n", " // Windows doesn't exit the process when it should.\n", " spawn('taskkill', ['/pid', '' + this.debugprocess.pid, '/T', '/F']);\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " if (!this.debugprocess) {\n", " return;\n", " }\n" ], "file_path": "packages/jest-editor-support/src/Runner.js", "type": "add", "edit_start_line_idx": 100 }
// Copyright 2004-present Facebook. All Rights Reserved. 'use strict'; jest.useFakeTimers(); it('schedules a 10-second timer after 1 second', () => { const infiniteTimerGame = require('../infiniteTimerGame'); const callback = jest.fn(); infiniteTimerGame(callback); // At this point in time, there should have been a single call to // setTimeout to schedule the end of the game in 1 second. expect(setTimeout.mock.calls.length).toBe(1); expect(setTimeout.mock.calls[0][1]).toBe(1000); // Fast forward and exhaust only currently pending timers // (but not any new timers that get created during that process) jest.runOnlyPendingTimers(); // At this point, our 1-second timer should have fired it's callback expect(callback).toBeCalled(); // And it should have created a new timer to start the game over in // 10 seconds expect(setTimeout.mock.calls.length).toBe(2); expect(setTimeout.mock.calls[1][1]).toBe(10000); });
examples/timer/__tests__/infinite_timer_game.test.js
0
https://github.com/jestjs/jest/commit/a0220a62183d689f1a9155e9c9021028d5ffa6cf
[ 0.00017450755694881082, 0.0001729036885080859, 0.00017194381507579237, 0.00017225969349965453, 0.0000011414143727961346 ]
{ "id": 7, "code_window": [ " completion();\n", " });\n", " }\n", "\n", " closeProcess() {\n", " if (process.platform === 'win32') {\n", " // Windows doesn't exit the process when it should.\n", " spawn('taskkill', ['/pid', '' + this.debugprocess.pid, '/T', '/F']);\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " if (!this.debugprocess) {\n", " return;\n", " }\n" ], "file_path": "packages/jest-editor-support/src/Runner.js", "type": "add", "edit_start_line_idx": 100 }
# jest-docblock `jest-docblock` is a package that can extract and parse a specially-formatted comment called a "docblock" at the top of a file. A docblock looks like this: ```js /** * Stuff goes here! */ ``` Docblocks can contain pragmas, which are words prefixed by `@`: ```js /** * Pragma incoming! * * @flow */ ``` Pragmas can also take arguments: ```js /** * Check this out: * * @myPragma it is so cool */ ``` `jest-docblock` can: * extract the docblock from some code as a string * parse a docblock string's pragmas into an object * print an object and some comments back to a string ## Installation ```sh # with yarn $ yarn add jest-docblock # with npm $ npm install jest-docblock ``` ## Usage ```js const code = ` /** * Everything is awesome! * * @everything is:awesome * @flow */ export const everything = Object.create(null); export default function isAwesome(something) { return something === everything; } `; const { extract, strip, parse, parseWithComments, print } = require("jest-docblock"); const docblock = extract(code); console.log(docblock); // "/**\n * Everything is awesome!\n * \n * @everything is:awesome\n * @flow\n */" const stripped = strip(code); console.log(stripped); // "export const everything = Object.create(null);\n export default function isAwesome(something) {\n return something === everything;\n }" const pragmas = parse(docblock); console.log(pragmas); // { everything: "is:awesome", flow: "" } const parsed = parseWithComments(docblock); console.log(parsed); // { comments: "Everything is awesome!", pragmas: { everything: "is:awesome", flow: "" } } console.log(print({pragmas, comments: "hi!"})) // /**\n * hi!\n *\n * @everything is:awesome\n * @flow\n */; ``` ## API Documentation ### `extract(contents: string): string` Extracts a docblock from some file contents. Returns the docblock contained in `contents`. If `contents` did not contain a docblock, it will return the empty string (`""`). ### `strip(contents: string): string` Strips the top docblock from a file and return the result. If a file does not have a docblock at the top, then return the file unchanged. ### `parse(docblock: string): {[key: string]: string}` Parses the pragmas in a docblock string into an object whose keys are the pragma tags and whose values are the arguments to those pragmas. ### `parseWithComments(docblock: string): { comments: string, pragmas: {[key: string]: string} }` Similar to `parse` except this method also returns the comments from the docblock. Useful when used with `print()`. ### `print({ comments?: string, pragmas?: {[key: string]: string} }): string` Prints an object of key-value pairs back into a docblock. If `comments` are provided, they will be positioned on the top of the docblock.
packages/jest-docblock/README.md
0
https://github.com/jestjs/jest/commit/a0220a62183d689f1a9155e9c9021028d5ffa6cf
[ 0.0001980321540031582, 0.00017053776537068188, 0.00016454842989332974, 0.00016753148520365357, 0.000009469014003116172 ]
{ "id": 7, "code_window": [ " completion();\n", " });\n", " }\n", "\n", " closeProcess() {\n", " if (process.platform === 'win32') {\n", " // Windows doesn't exit the process when it should.\n", " spawn('taskkill', ['/pid', '' + this.debugprocess.pid, '/T', '/F']);\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " if (!this.debugprocess) {\n", " return;\n", " }\n" ], "file_path": "packages/jest-editor-support/src/Runner.js", "type": "add", "edit_start_line_idx": 100 }
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`Upgrade help logs a warning when \`scriptPreprocessor\` and/or \`preprocessorIgnorePatterns\` are used 1`] = ` "<yellow><bold><bold>●<bold> Deprecation Warning</>:</> <yellow></> <yellow> Option <bold>\\"preprocessorIgnorePatterns\\"</> was replaced by <bold>\\"transformIgnorePatterns\\"</>, which support multiple preprocessors.</> <yellow></> <yellow> Jest now treats your current configuration as:</> <yellow> {</> <yellow> <bold>\\"transformIgnorePatterns\\"</>: <bold>[\\"bar/baz\\", \\"qux/quux\\"]</></> <yellow> }</> <yellow></> <yellow> Please update your configuration.</> <yellow></> <yellow> <bold>Configuration Documentation:</></> <yellow> https://facebook.github.io/jest/docs/configuration.html</> <yellow></>" `; exports[`preset throws when preset not found 1`] = ` "<red><bold><bold>● <bold>Validation Error</>:</> <red></> <red> Preset <bold>doesnt-exist</> not found.</> <red></> <red> <bold>Configuration Documentation:</></> <red> https://facebook.github.io/jest/docs/configuration.html</> <red></>" `; exports[`rootDir throws if the options is missing a rootDir property 1`] = ` "<red><bold><bold>● <bold>Validation Error</>:</> <red></> <red> Configuration option <bold>rootDir</> must be specified.</> <red></> <red> <bold>Configuration Documentation:</></> <red> https://facebook.github.io/jest/docs/configuration.html</> <red></>" `; exports[`testEnvironment throws on invalid environment names 1`] = ` "<red><bold><bold>● <bold>Validation Error</>:</> <red></> <red> Test environment <bold>phantom</> cannot be found. Make sure the <bold>testEnvironment</> configuration option points to an existing node module.</> <red></> <red> <bold>Configuration Documentation:</></> <red> https://facebook.github.io/jest/docs/configuration.html</> <red></>" `; exports[`testMatch throws if testRegex and testMatch are both specified 1`] = ` "<red><bold><bold>● <bold>Validation Error</>:</> <red></> <red> Configuration options <bold>testMatch</> and <bold>testRegex</> cannot be used together.</> <red></> <red> <bold>Configuration Documentation:</></> <red> https://facebook.github.io/jest/docs/configuration.html</> <red></>" `;
packages/jest-config/src/__tests__/__snapshots__/normalize.test.js.snap
0
https://github.com/jestjs/jest/commit/a0220a62183d689f1a9155e9c9021028d5ffa6cf
[ 0.00017170181672554463, 0.00016906263772398233, 0.0001675857783993706, 0.00016879568283911794, 0.000001301319230151421 ]
{ "id": 8, "code_window": [ " createProcess?: (\n", " workspace: ProjectWorkspace,\n", " args: Array<string>,\n", " ) => ChildProcess,\n", "};\n", "\n", "/**\n", " * Did the thing pass, fail or was it not run?\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " testNamePattern?: string,\n", " testFileNamePattern?: string,\n" ], "file_path": "packages/jest-editor-support/src/types.js", "type": "add", "edit_start_line_idx": 22 }
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import { EventEmitter } from 'events'; export class Runner extends EventEmitter { constructor(workspace: ProjectWorkspace); watchMode: boolean; start(watchMode?: boolean): void; closeProcess(): void; runJestWithUpdateForSnapshots(completion: any): void; } export class Settings extends EventEmitter { constructor(workspace: ProjectWorkspace); getConfig(completed: Function): void; jestVersionMajor: number | null; settings: { testRegex: string; }; } export class ProjectWorkspace { constructor( rootPath: string, pathToJest: string, pathToConfig: string, localJestMajorVersin: number, ); pathToJest: string; rootPath: string; localJestMajorVersion: number; } export interface IParseResults { expects: Expect[]; itBlocks: ItBlock[]; } export function parse(file: string): IParseResults; export interface Location { column: number; line: number; } export class Node { start: Location; end: Location; file: string; } export class ItBlock extends Node { name: string; } export class Expect extends Node {} export class TestReconciler { stateForTestFile(file: string): TestReconcilationState; assertionsForTestFile(file: string): TestAssertionStatus[] | null; stateForTestAssertion( file: string, name: string, ): TestFileAssertionStatus | null; updateFileWithJestStatus(data: any): TestFileAssertionStatus[]; } export type TestReconcilationState = | 'Unknown' | 'KnownSuccess' | 'KnownFail' | 'KnownSkip'; export interface TestFileAssertionStatus { file: string; message: string; status: TestReconcilationState; assertions: Array<TestAssertionStatus>; } export interface TestAssertionStatus { title: string; status: TestReconcilationState; message: string; shortMessage?: string; terseMessage?: string; line?: number; } export interface JestFileResults { name: string; summary: string; message: string; status: 'failed' | 'passed'; startTime: number; endTime: number; assertionResults: Array<JestAssertionResults>; } export interface JestAssertionResults { name: string; title: string; status: 'failed' | 'passed'; failureMessages: string[]; } export interface JestTotalResults { success: boolean; startTime: number; numTotalTests: number; numTotalTestSuites: number; numRuntimeErrorTestSuites: number; numPassedTests: number; numFailedTests: number; numPendingTests: number; testResults: Array<JestFileResults>; }
packages/jest-editor-support/index.d.ts
1
https://github.com/jestjs/jest/commit/a0220a62183d689f1a9155e9c9021028d5ffa6cf
[ 0.001397408195771277, 0.0002718950854614377, 0.0001674207887845114, 0.00017066451255232096, 0.000325513887219131 ]
{ "id": 8, "code_window": [ " createProcess?: (\n", " workspace: ProjectWorkspace,\n", " args: Array<string>,\n", " ) => ChildProcess,\n", "};\n", "\n", "/**\n", " * Did the thing pass, fail or was it not run?\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " testNamePattern?: string,\n", " testFileNamePattern?: string,\n" ], "file_path": "packages/jest-editor-support/src/types.js", "type": "add", "edit_start_line_idx": 22 }
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ export type Jasmine = Object;
types/Jasmine.js
0
https://github.com/jestjs/jest/commit/a0220a62183d689f1a9155e9c9021028d5ffa6cf
[ 0.0001750350056681782, 0.00017461484821978956, 0.00017419469077140093, 0.00017461484821978956, 4.201574483886361e-7 ]
{ "id": 8, "code_window": [ " createProcess?: (\n", " workspace: ProjectWorkspace,\n", " args: Array<string>,\n", " ) => ChildProcess,\n", "};\n", "\n", "/**\n", " * Did the thing pass, fail or was it not run?\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " testNamePattern?: string,\n", " testFileNamePattern?: string,\n" ], "file_path": "packages/jest-editor-support/src/types.js", "type": "add", "edit_start_line_idx": 22 }
@if "%DEBUG%" == "" @echo off @rem ########################################################################## @rem @rem Gradle startup script for Windows @rem @rem ########################################################################## @rem Set local scope for the variables with windows NT shell if "%OS%"=="Windows_NT" setlocal @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. set DEFAULT_JVM_OPTS= set DIRNAME=%~dp0 if "%DIRNAME%" == "" set DIRNAME=. set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% @rem Find java.exe if defined JAVA_HOME goto findJavaFromJavaHome set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 if "%ERRORLEVEL%" == "0" goto init echo. echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. echo. echo Please set the JAVA_HOME variable in your environment to match the echo location of your Java installation. goto fail :findJavaFromJavaHome set JAVA_HOME=%JAVA_HOME:"=% set JAVA_EXE=%JAVA_HOME%/bin/java.exe if exist "%JAVA_EXE%" goto init echo. echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% echo. echo Please set the JAVA_HOME variable in your environment to match the echo location of your Java installation. goto fail :init @rem Get command-line arguments, handling Windowz variants if not "%OS%" == "Windows_NT" goto win9xME_args if "%@eval[2+2]" == "4" goto 4NT_args :win9xME_args @rem Slurp the command line arguments. set CMD_LINE_ARGS= set _SKIP=2 :win9xME_args_slurp if "x%~1" == "x" goto execute set CMD_LINE_ARGS=%* goto execute :4NT_args @rem Get arguments from the 4NT Shell from JP Software set CMD_LINE_ARGS=%$ :execute @rem Setup the command line set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar @rem Execute Gradle "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% :end @rem End local scope for the variables with windows NT shell if "%ERRORLEVEL%"=="0" goto mainEnd :fail rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of rem the _cmd.exe /c_ return code! if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 exit /b 1 :mainEnd if "%OS%"=="Windows_NT" endlocal :omega
examples/react-native/android/gradlew.bat
0
https://github.com/jestjs/jest/commit/a0220a62183d689f1a9155e9c9021028d5ffa6cf
[ 0.00017419469077140093, 0.0001687415351625532, 0.00016508511907886714, 0.0001680785499047488, 0.000002601287405923358 ]
{ "id": 8, "code_window": [ " createProcess?: (\n", " workspace: ProjectWorkspace,\n", " args: Array<string>,\n", " ) => ChildProcess,\n", "};\n", "\n", "/**\n", " * Did the thing pass, fail or was it not run?\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " testNamePattern?: string,\n", " testFileNamePattern?: string,\n" ], "file_path": "packages/jest-editor-support/src/types.js", "type": "add", "edit_start_line_idx": 22 }
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ module.exports = {extension: 'js'};
integration_tests/resolve/test2.js
0
https://github.com/jestjs/jest/commit/a0220a62183d689f1a9155e9c9021028d5ffa6cf
[ 0.00017166366160381585, 0.00017166366160381585, 0.00017166366160381585, 0.00017166366160381585, 0 ]
{ "id": 2, "code_window": [ " name: wait-for-remote-alertmanager\n", "- commands:\n", " - apk add --update build-base\n", " - go clean -testcache\n", " - go test -run TestIntegrationRemoteAlertmanager -covermode=atomic -timeout=2m ./pkg/services/ngalert/notifier/...\n", " depends_on:\n", " - wire-install\n", " - wait-for-remote-alertmanager\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " - go test -run TestIntegrationRemoteAlertmanager -covermode=atomic -timeout=2m ./pkg/services/ngalert/...\n" ], "file_path": ".drone.yml", "type": "replace", "edit_start_line_idx": 3991 }
## This is a self-documented Makefile. For usage information, run `make help`: ## ## For more information, refer to https://suva.sh/posts/well-documented-makefiles/ WIRE_TAGS = "oss" -include local/Makefile include .bingo/Variables.mk .PHONY: all deps-go deps-js deps build-go build-backend build-server build-cli build-js build build-docker-full build-docker-full-ubuntu lint-go golangci-lint test-go test-js gen-ts test run run-frontend clean devenv devenv-down protobuf drone help gen-go gen-cue fix-cue GO = go GO_FILES ?= ./pkg/... SH_FILES ?= $(shell find ./scripts -name *.sh) GO_BUILD_FLAGS += $(if $(GO_BUILD_DEV),-dev) GO_BUILD_FLAGS += $(if $(GO_BUILD_TAGS),-build-tags=$(GO_BUILD_TAGS)) targets := $(shell echo '$(sources)' | tr "," " ") GO_INTEGRATION_TESTS := $(shell find ./pkg -type f -name '*_test.go' -exec grep -l '^func TestIntegration' '{}' '+' | grep -o '\(.*\)/' | sort -u) all: deps build ##@ Dependencies deps-go: ## Install backend dependencies. $(GO) run build.go setup deps-js: node_modules ## Install frontend dependencies. deps: deps-js ## Install all dependencies. node_modules: package.json yarn.lock ## Install node modules. @echo "install frontend dependencies" YARN_ENABLE_PROGRESS_BARS=false yarn install --immutable ##@ Swagger SPEC_TARGET = public/api-spec.json ENTERPRISE_SPEC_TARGET = public/api-enterprise-spec.json MERGED_SPEC_TARGET = public/api-merged.json NGALERT_SPEC_TARGET = pkg/services/ngalert/api/tooling/api.json $(NGALERT_SPEC_TARGET): +$(MAKE) -C pkg/services/ngalert/api/tooling api.json $(MERGED_SPEC_TARGET): swagger-oss-gen swagger-enterprise-gen $(NGALERT_SPEC_TARGET) $(SWAGGER) ## Merge generated and ngalert API specs # known conflicts DsPermissionType, AddApiKeyCommand, Json, Duration (identical models referenced by both specs) $(SWAGGER) mixin $(SPEC_TARGET) $(ENTERPRISE_SPEC_TARGET) $(NGALERT_SPEC_TARGET) --ignore-conflicts -o $(MERGED_SPEC_TARGET) swagger-oss-gen: $(SWAGGER) ## Generate API Swagger specification @echo "re-generating swagger for OSS" rm -f $(SPEC_TARGET) SWAGGER_GENERATE_EXTENSION=false $(SWAGGER) generate spec -m -w pkg/server -o $(SPEC_TARGET) \ -x "github.com/grafana/grafana/pkg/services/ngalert/api/tooling/definitions" \ -x "github.com/prometheus/alertmanager" \ -i pkg/api/swagger_tags.json \ --exclude-tag=alpha \ --exclude-tag=enterprise # this file only exists if enterprise is enabled ENTERPRISE_EXT_FILE = pkg/extensions/ext.go ifeq ("$(wildcard $(ENTERPRISE_EXT_FILE))","") ## if enterprise is not enabled swagger-enterprise-gen: @echo "skipping re-generating swagger for enterprise: not enabled" else swagger-enterprise-gen: $(SWAGGER) ## Generate API Swagger specification @echo "re-generating swagger for enterprise" rm -f $(ENTERPRISE_SPEC_TARGET) SWAGGER_GENERATE_EXTENSION=false $(SWAGGER) generate spec -m -w pkg/server -o $(ENTERPRISE_SPEC_TARGET) \ -x "github.com/grafana/grafana/pkg/services/ngalert/api/tooling/definitions" \ -x "github.com/prometheus/alertmanager" \ -i pkg/api/swagger_tags.json \ --exclude-tag=alpha \ --include-tag=enterprise endif swagger-gen: gen-go $(MERGED_SPEC_TARGET) swagger-validate swagger-validate: $(MERGED_SPEC_TARGET) $(SWAGGER) ## Validate API spec $(SWAGGER) validate $(<) swagger-clean: rm -f $(SPEC_TARGET) $(MERGED_SPEC_TARGET) $(OAPI_SPEC_TARGET) .PHONY: cleanup-old-git-hooks cleanup-old-git-hooks: ./scripts/cleanup-husky.sh .PHONY: lefthook-install lefthook-install: cleanup-old-git-hooks $(LEFTHOOK) # install lefthook for pre-commit hooks $(LEFTHOOK) install -f .PHONY: lefthook-uninstall lefthook-uninstall: $(LEFTHOOK) $(LEFTHOOK) uninstall ##@ OpenAPI 3 OAPI_SPEC_TARGET = public/openapi3.json openapi3-gen: swagger-gen ## Generates OpenApi 3 specs from the Swagger 2 already generated $(GO) run scripts/openapi3/openapi3conv.go $(MERGED_SPEC_TARGET) $(OAPI_SPEC_TARGET) ##@ Building gen-cue: ## Do all CUE/Thema code generation @echo "generate code from .cue files" go generate ./pkg/plugins/plugindef go generate ./kinds/gen.go go generate ./public/app/plugins/gen.go go generate ./pkg/kindsysreport/codegen/report.go gen-go: $(WIRE) @echo "generate go files" $(WIRE) gen -tags $(WIRE_TAGS) ./pkg/server fix-cue: $(CUE) @echo "formatting cue files" $(CUE) fix kinds/**/*.cue $(CUE) fix public/app/plugins/**/**/*.cue gen-jsonnet: go generate ./devenv/jsonnet build-go: gen-go ## Build all Go binaries. @echo "build go files" $(GO) run build.go $(GO_BUILD_FLAGS) build build-backend: ## Build Grafana backend. @echo "build backend" $(GO) run build.go $(GO_BUILD_FLAGS) build-backend build-server: ## Build Grafana server. @echo "build server" $(GO) run build.go $(GO_BUILD_FLAGS) build-server build-cli: ## Build Grafana CLI application. @echo "build grafana-cli" $(GO) run build.go $(GO_BUILD_FLAGS) build-cli build-js: ## Build frontend assets. @echo "build frontend" yarn run build yarn run plugins:build-bundled build-plugins-go: ## Build decoupled plugins @echo "build plugins" @cd pkg/tsdb; \ mage -v PLUGIN_ID ?= build-plugin-go: ## Build decoupled plugins @echo "build plugin $(PLUGIN_ID)" @cd pkg/tsdb; \ if [ -z "$(PLUGIN_ID)" ]; then \ echo "PLUGIN_ID is not set"; \ exit 1; \ fi; \ mage -v buildplugin $(PLUGIN_ID) build: build-go build-js ## Build backend and frontend. run: $(BRA) ## Build and run web server on filesystem changes. $(BRA) run run-frontend: deps-js ## Fetch js dependencies and watch frontend for rebuild yarn start ##@ Testing .PHONY: test-go test-go: test-go-unit test-go-integration .PHONY: test-go-unit test-go-unit: ## Run unit tests for backend with flags. @echo "test backend unit tests" $(GO) test -short -covermode=atomic -timeout=30m ./pkg/... .PHONY: test-go-integration test-go-integration: ## Run integration tests for backend with flags. @echo "test backend integration tests" $(GO) test -count=1 -run "^TestIntegration" -covermode=atomic -timeout=5m $(GO_INTEGRATION_TESTS) .PHONY: test-go-integration-alertmanager test-go-integration-alertmanager: ## Run integration tests for the remote alertmanager (config taken from the mimir_backend block). @echo "test remote alertmanager integration tests" $(GO) clean -testcache AM_URL=http://localhost:8080 AM_TENANT_ID=test AM_PASSWORD=test \ $(GO) test -count=1 -run "^TestIntegrationRemoteAlertmanager" -covermode=atomic -timeout=5m ./pkg/services/ngalert/notifier/... .PHONY: test-go-integration-postgres test-go-integration-postgres: devenv-postgres ## Run integration tests for postgres backend with flags. @echo "test backend integration postgres tests" $(GO) clean -testcache GRAFANA_TEST_DB=postgres \ $(GO) test -p=1 -count=1 -run "^TestIntegration" -covermode=atomic -timeout=10m $(GO_INTEGRATION_TESTS) .PHONY: test-go-integration-mysql test-go-integration-mysql: devenv-mysql ## Run integration tests for mysql backend with flags. @echo "test backend integration mysql tests" GRAFANA_TEST_DB=mysql \ $(GO) test -p=1 -count=1 -run "^TestIntegration" -covermode=atomic -timeout=10m $(GO_INTEGRATION_TESTS) .PHONY: test-go-integration-redis test-go-integration-redis: ## Run integration tests for redis cache. @echo "test backend integration redis tests" $(GO) clean -testcache REDIS_URL=localhost:6379 $(GO) test -run IntegrationRedis -covermode=atomic -timeout=2m $(GO_INTEGRATION_TESTS) .PHONY: test-go-integration-memcached test-go-integration-memcached: ## Run integration tests for memcached cache. @echo "test backend integration memcached tests" $(GO) clean -testcache MEMCACHED_HOSTS=localhost:11211 $(GO) test -run IntegrationMemcached -covermode=atomic -timeout=2m $(GO_INTEGRATION_TESTS) test-js: ## Run tests for frontend. @echo "test frontend" yarn test test: test-go test-js ## Run all tests. ##@ Linting golangci-lint: $(GOLANGCI_LINT) @echo "lint via golangci-lint" $(GOLANGCI_LINT) run \ --config .golangci.toml \ $(GO_FILES) lint-go: golangci-lint ## Run all code checks for backend. You can use GO_FILES to specify exact files to check # with disabled SC1071 we are ignored some TCL,Expect `/usr/bin/env expect` scripts shellcheck: $(SH_FILES) ## Run checks for shell scripts. @docker run --rm -v "$$PWD:/mnt" koalaman/shellcheck:stable \ $(SH_FILES) -e SC1071 -e SC2162 ##@ Docker TAG_SUFFIX=$(if $(WIRE_TAGS)!=oss,-$(WIRE_TAGS)) PLATFORM=linux/amd64 build-docker-full: ## Build Docker image for development. @echo "build docker container" tar -ch . | \ docker buildx build - \ --platform $(PLATFORM) \ --build-arg BINGO=false \ --build-arg GO_BUILD_TAGS=$(GO_BUILD_TAGS) \ --build-arg WIRE_TAGS=$(WIRE_TAGS) \ --build-arg COMMIT_SHA=$$(git rev-parse HEAD) \ --build-arg BUILD_BRANCH=$$(git rev-parse --abbrev-ref HEAD) \ --tag grafana/grafana$(TAG_SUFFIX):dev \ $(DOCKER_BUILD_ARGS) build-docker-full-ubuntu: ## Build Docker image based on Ubuntu for development. @echo "build docker container" tar -ch . | \ docker buildx build - \ --platform $(PLATFORM) \ --build-arg BINGO=false \ --build-arg GO_BUILD_TAGS=$(GO_BUILD_TAGS) \ --build-arg WIRE_TAGS=$(WIRE_TAGS) \ --build-arg COMMIT_SHA=$$(git rev-parse HEAD) \ --build-arg BUILD_BRANCH=$$(git rev-parse --abbrev-ref HEAD) \ --build-arg BASE_IMAGE=ubuntu:22.04 \ --build-arg GO_IMAGE=golang:1.21.3 \ --tag grafana/grafana$(TAG_SUFFIX):dev-ubuntu \ $(DOCKER_BUILD_ARGS) ##@ Services # create docker-compose file with provided sources and start them # example: make devenv sources=postgres,auth/openldap ifeq ($(sources),) devenv: @printf 'You have to define sources for this command \nexample: make devenv sources=postgres,openldap\n' else devenv: devenv-down ## Start optional services, e.g. postgres, prometheus, and elasticsearch. @cd devenv; \ ./create_docker_compose.sh $(targets) || \ (rm -rf {docker-compose.yaml,conf.tmp,.env}; exit 1) @cd devenv; \ docker-compose up -d --build endif devenv-down: ## Stop optional services. @cd devenv; \ test -f docker-compose.yaml && \ docker-compose down || exit 0; devenv-postgres: @cd devenv; \ sources=postgres_tests devenv-mysql: @cd devenv; \ sources=mysql_tests ##@ Helpers # We separate the protobuf generation because most development tasks on # Grafana do not involve changing protobuf files and protoc is not a # go-gettable dependency and so getting it installed can be inconvenient. # # If you are working on changes to protobuf interfaces you may either use # this target or run the individual scripts below directly. protobuf: ## Compile protobuf definitions bash scripts/protobuf-check.sh bash pkg/plugins/backendplugin/pluginextensionv2/generate.sh bash pkg/plugins/backendplugin/secretsmanagerplugin/generate.sh bash pkg/services/store/entity/generate.sh bash pkg/infra/grn/generate.sh clean: ## Clean up intermediate build artifacts. @echo "cleaning" rm -rf node_modules rm -rf public/build gen-ts: @echo "generating TypeScript definitions" go get github.com/tkrajina/typescriptify-golang-structs/[email protected] tscriptify -interface -package=github.com/grafana/grafana/pkg/services/live/pipeline -import="import { FieldConfig } from '@grafana/data'" -target=public/app/features/live/pipeline/models.gen.ts pkg/services/live/pipeline/config.go go mod tidy # This repository's configuration is protected (https://readme.drone.io/signature/). # Use this make target to regenerate the configuration YAML files when # you modify starlark files. drone: $(DRONE) $(DRONE) starlark --format $(DRONE) lint .drone.yml --trusted $(DRONE) --server https://drone.grafana.net sign --save grafana/grafana # Generate an Emacs tags table (https://www.gnu.org/software/emacs/manual/html_node/emacs/Tags-Tables.html) for Starlark files. scripts/drone/TAGS: $(shell find scripts/drone -name '*.star') etags --lang none --regex="/def \(\w+\)[^:]+:/\1/" --regex="/\s*\(\w+\) =/\1/" $^ -o $@ format-drone: buildifier --lint=fix -r scripts/drone help: ## Display this help. @awk 'BEGIN {FS = ":.*##"; printf "\nUsage:\n make \033[36m<target>\033[0m\n"} /^[a-zA-Z_-]+:.*?##/ { printf " \033[36m%-15s\033[0m %s\n", $$1, $$2 } /^##@/ { printf "\n\033[1m%s\033[0m\n", substr($$0, 5) } ' $(MAKEFILE_LIST)
Makefile
1
https://github.com/grafana/grafana/commit/eef8525a4b7febf05863c19bac2d8c57bf4d545d
[ 0.10208726674318314, 0.004589602816849947, 0.000159843621077016, 0.0001687988406047225, 0.01793045364320278 ]
{ "id": 2, "code_window": [ " name: wait-for-remote-alertmanager\n", "- commands:\n", " - apk add --update build-base\n", " - go clean -testcache\n", " - go test -run TestIntegrationRemoteAlertmanager -covermode=atomic -timeout=2m ./pkg/services/ngalert/notifier/...\n", " depends_on:\n", " - wire-install\n", " - wait-for-remote-alertmanager\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " - go test -run TestIntegrationRemoteAlertmanager -covermode=atomic -timeout=2m ./pkg/services/ngalert/...\n" ], "file_path": ".drone.yml", "type": "replace", "edit_start_line_idx": 3991 }
import { kebabCase } from 'lodash'; import { SelectableValue } from '@grafana/data'; export const generateOptions = (desc = false) => { const values = [ 'Sharilyn Markowitz', 'Naomi Striplin', 'Beau Bevel', 'Garrett Starkes', 'Hildegarde Pedro', 'Gudrun Seyler', 'Eboni Raines', 'Hye Felix', 'Chau Brito', 'Heidy Zook', 'Karima Husain', 'Virgil Mckinny', 'Kaley Dodrill', 'Sharan Ruf', 'Edgar Loveland', 'Judie Sanger', 'Season Bundrick', 'Ok Vicente', 'Garry Spitz', 'Han Harnish', 'A very long value that is very long and takes up a lot of space and should be truncated preferrably if it does not fit', ]; return values.map<SelectableValue<string>>((name) => ({ value: kebabCase(name), label: name, description: desc ? `This is a description of ${name}` : undefined, })); }; export const generateThousandsOfOptions = () => { const options: Array<SelectableValue<string>> = new Array(10000).fill(null).map((_, index) => ({ value: String(index), label: 'Option ' + index, description: 'This is option number ' + index, })); return options; };
packages/grafana-ui/src/components/Select/mockOptions.tsx
0
https://github.com/grafana/grafana/commit/eef8525a4b7febf05863c19bac2d8c57bf4d545d
[ 0.00017574289813637733, 0.0001722174638416618, 0.00016953145677689463, 0.00017185676551889628, 0.0000020596760350599652 ]
{ "id": 2, "code_window": [ " name: wait-for-remote-alertmanager\n", "- commands:\n", " - apk add --update build-base\n", " - go clean -testcache\n", " - go test -run TestIntegrationRemoteAlertmanager -covermode=atomic -timeout=2m ./pkg/services/ngalert/notifier/...\n", " depends_on:\n", " - wire-install\n", " - wait-for-remote-alertmanager\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " - go test -run TestIntegrationRemoteAlertmanager -covermode=atomic -timeout=2m ./pkg/services/ngalert/...\n" ], "file_path": ".drone.yml", "type": "replace", "edit_start_line_idx": 3991 }
import { Registry } from '@grafana/data'; import { fieldNameByRegexMatcherItem } from './FieldNameByRegexMatcherEditor'; import { fieldNameMatcherItem } from './FieldNameMatcherEditor'; import { fieldNamesMatcherItem } from './FieldNamesMatcherEditor'; import { fieldTypeMatcherItem } from './FieldTypeMatcherEditor'; import { fieldValueMatcherItem } from './FieldValueMatcher'; import { fieldsByFrameRefIdItem } from './FieldsByFrameRefIdMatcher'; import { FieldMatcherUIRegistryItem } from './types'; export const fieldMatchersUI = new Registry<FieldMatcherUIRegistryItem<any>>(() => [ fieldNameMatcherItem, fieldNameByRegexMatcherItem, fieldTypeMatcherItem, fieldsByFrameRefIdItem, fieldNamesMatcherItem, fieldValueMatcherItem, ]);
packages/grafana-ui/src/components/MatchersUI/fieldMatchersUI.ts
0
https://github.com/grafana/grafana/commit/eef8525a4b7febf05863c19bac2d8c57bf4d545d
[ 0.0001731633092276752, 0.00017292489064857364, 0.00017268647206947207, 0.00017292489064857364, 2.384185791015625e-7 ]
{ "id": 2, "code_window": [ " name: wait-for-remote-alertmanager\n", "- commands:\n", " - apk add --update build-base\n", " - go clean -testcache\n", " - go test -run TestIntegrationRemoteAlertmanager -covermode=atomic -timeout=2m ./pkg/services/ngalert/notifier/...\n", " depends_on:\n", " - wire-install\n", " - wait-for-remote-alertmanager\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " - go test -run TestIntegrationRemoteAlertmanager -covermode=atomic -timeout=2m ./pkg/services/ngalert/...\n" ], "file_path": ".drone.yml", "type": "replace", "edit_start_line_idx": 3991 }
import { FieldConfigSource, PanelModel } from '@grafana/data'; import { TextMode, Options } from './panelcfg.gen'; import { textPanelMigrationHandler } from './textPanelMigrationHandler'; describe('textPanelMigrationHandler', () => { describe('when invoked and previous version was old Angular text panel', () => { it('then should migrate options', () => { const panel = { content: '<span>Hello World<span>', mode: 'html', options: {}, }; const result = textPanelMigrationHandler(panel as unknown as PanelModel); expect(result.content).toEqual('<span>Hello World<span>'); expect(result.mode).toEqual('html'); expect(panel.content).toBeUndefined(); expect(panel.mode).toBeUndefined(); }); }); describe('when invoked and previous version 7.1 or later', () => { it('then not migrate options', () => { const panel = { content: '<span>Hello World<span>', mode: 'html', options: { content: 'New content' }, pluginVersion: '7.1.0', }; const result = textPanelMigrationHandler(panel as unknown as PanelModel); expect(result.content).toEqual('New content'); }); }); describe('when invoked and previous version was not old Angular text panel', () => { it('then should just pass options through', () => { const panel: PanelModel<Options> = { id: 1, type: 'text', fieldConfig: {} as unknown as FieldConfigSource, options: { content: `# Title For markdown syntax help: [commonmark.org/help](https://commonmark.org/help/) `, mode: TextMode.Markdown, }, }; const result = textPanelMigrationHandler(panel); expect(result.content).toEqual(`# Title For markdown syntax help: [commonmark.org/help](https://commonmark.org/help/) `); expect(result.mode).toEqual('markdown'); }); }); describe('when invoked and previous version was using text mode', () => { it('then should switch to markdown', () => { const mode = 'text' as unknown as TextMode; const panel: PanelModel<Options> = { id: 1, type: 'text', fieldConfig: {} as unknown as FieldConfigSource, options: { content: `# Title For markdown syntax help: [commonmark.org/help](https://commonmark.org/help/) `, mode, }, }; const result = textPanelMigrationHandler(panel); expect(result.content).toEqual(`# Title For markdown syntax help: [commonmark.org/help](https://commonmark.org/help/) `); expect(result.mode).toEqual('markdown'); }); }); });
public/app/plugins/panel/text/textPanelMigrationHandler.test.ts
0
https://github.com/grafana/grafana/commit/eef8525a4b7febf05863c19bac2d8c57bf4d545d
[ 0.00017428556748200208, 0.00017118484538514167, 0.0001671137724770233, 0.00017229073273483664, 0.000002252922286061221 ]
{ "id": 0, "code_window": [ " : [],\n", " }),\n", " visibility: isRawMode,\n", "};\n", "\n", "const dnd_all_columns: typeof sharedControls.groupby = {\n", " type: 'DndColumnSelect',\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " resetOnHide: false,\n" ], "file_path": "superset-frontend/plugins/plugin-chart-table/src/controlPanel.tsx", "type": "add", "edit_start_line_idx": 119 }
/* eslint-disable camelcase */ /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ import React from 'react'; import { addLocaleData, ChartDataResponseResult, ensureIsArray, FeatureFlag, GenericDataType, isFeatureEnabled, QueryFormColumn, QueryMode, smartDateFormatter, t, } from '@superset-ui/core'; import { ColumnOption, ControlConfig, ControlPanelConfig, ControlPanelsContainerProps, ControlStateMapping, D3_TIME_FORMAT_OPTIONS, QueryModeLabel, sections, sharedControls, ControlPanelState, ExtraControlProps, ControlState, emitFilterControl, } from '@superset-ui/chart-controls'; import i18n from './i18n'; import { PAGE_SIZE_OPTIONS } from './consts'; addLocaleData(i18n); function getQueryMode(controls: ControlStateMapping): QueryMode { const mode = controls?.query_mode?.value; if (mode === QueryMode.aggregate || mode === QueryMode.raw) { return mode as QueryMode; } const rawColumns = controls?.all_columns?.value as | QueryFormColumn[] | undefined; const hasRawColumns = rawColumns && rawColumns.length > 0; return hasRawColumns ? QueryMode.raw : QueryMode.aggregate; } /** * Visibility check */ function isQueryMode(mode: QueryMode) { return ({ controls }: Pick<ControlPanelsContainerProps, 'controls'>) => getQueryMode(controls) === mode; } const isAggMode = isQueryMode(QueryMode.aggregate); const isRawMode = isQueryMode(QueryMode.raw); const validateAggControlValues = ( controls: ControlStateMapping, values: any[], ) => { const areControlsEmpty = values.every(val => ensureIsArray(val).length === 0); return areControlsEmpty && isAggMode({ controls }) ? [t('Group By, Metrics or Percentage Metrics must have a value')] : []; }; const queryMode: ControlConfig<'RadioButtonControl'> = { type: 'RadioButtonControl', label: t('Query mode'), default: null, options: [ [QueryMode.aggregate, QueryModeLabel[QueryMode.aggregate]], [QueryMode.raw, QueryModeLabel[QueryMode.raw]], ], mapStateToProps: ({ controls }) => ({ value: getQueryMode(controls) }), rerender: ['all_columns', 'groupby', 'metrics', 'percent_metrics'], }; const all_columns: typeof sharedControls.groupby = { type: 'SelectControl', label: t('Columns'), description: t('Columns to display'), multi: true, freeForm: true, allowAll: true, commaChoosesOption: false, default: [], optionRenderer: c => <ColumnOption showType column={c} />, valueRenderer: c => <ColumnOption column={c} />, valueKey: 'column_name', mapStateToProps: ({ datasource, controls }, controlState) => ({ options: datasource?.columns || [], queryMode: getQueryMode(controls), externalValidationErrors: isRawMode({ controls }) && ensureIsArray(controlState.value).length === 0 ? [t('must have a value')] : [], }), visibility: isRawMode, }; const dnd_all_columns: typeof sharedControls.groupby = { type: 'DndColumnSelect', label: t('Columns'), description: t('Columns to display'), default: [], mapStateToProps({ datasource, controls }, controlState) { const newState: ExtraControlProps = {}; if (datasource) { const options = datasource.columns; newState.options = Object.fromEntries( options.map(option => [option.column_name, option]), ); } newState.queryMode = getQueryMode(controls); newState.externalValidationErrors = isRawMode({ controls }) && ensureIsArray(controlState.value).length === 0 ? [t('must have a value')] : []; return newState; }, visibility: isRawMode, }; const percent_metrics: typeof sharedControls.metrics = { type: 'MetricsControl', label: t('Percentage metrics'), description: t( 'Metrics for which percentage of total are to be displayed. Calculated from only data within the row limit.', ), multi: true, visibility: isAggMode, mapStateToProps: ({ datasource, controls }, controlState) => ({ columns: datasource?.columns || [], savedMetrics: datasource?.metrics || [], datasource, datasourceType: datasource?.type, queryMode: getQueryMode(controls), externalValidationErrors: validateAggControlValues(controls, [ controls.groupby?.value, controls.metrics?.value, controlState.value, ]), }), rerender: ['groupby', 'metrics'], default: [], validators: [], }; const dnd_percent_metrics = { ...percent_metrics, type: 'DndMetricSelect', }; const config: ControlPanelConfig = { controlPanelSections: [ sections.legacyTimeseriesTime, { label: t('Query'), expanded: true, controlSetRows: [ [ { name: 'query_mode', config: queryMode, }, ], [ { name: 'groupby', override: { visibility: isAggMode, mapStateToProps: ( state: ControlPanelState, controlState: ControlState, ) => { const { controls } = state; const originalMapStateToProps = sharedControls?.groupby?.mapStateToProps; const newState = originalMapStateToProps?.(state, controlState) ?? {}; newState.externalValidationErrors = validateAggControlValues( controls, [ controls.metrics?.value, controls.percent_metrics?.value, controlState.value, ], ); return newState; }, rerender: ['metrics', 'percent_metrics'], }, }, ], [ { name: 'metrics', override: { validators: [], visibility: isAggMode, mapStateToProps: ( { controls, datasource, form_data }: ControlPanelState, controlState: ControlState, ) => ({ columns: datasource?.columns.filter(c => c.filterable) || [], savedMetrics: datasource?.metrics || [], // current active adhoc metrics selectedMetrics: form_data.metrics || (form_data.metric ? [form_data.metric] : []), datasource, externalValidationErrors: validateAggControlValues(controls, [ controls.groupby?.value, controls.percent_metrics?.value, controlState.value, ]), }), rerender: ['groupby', 'percent_metrics'], }, }, { name: 'all_columns', config: isFeatureEnabled(FeatureFlag.ENABLE_EXPLORE_DRAG_AND_DROP) ? dnd_all_columns : all_columns, }, ], [ { name: 'percent_metrics', config: { ...(isFeatureEnabled(FeatureFlag.ENABLE_EXPLORE_DRAG_AND_DROP) ? dnd_percent_metrics : percent_metrics), }, }, ], ['adhoc_filters'], [ { name: 'timeseries_limit_metric', override: { visibility: isAggMode, }, }, { name: 'order_by_cols', config: { type: 'SelectControl', label: t('Ordering'), description: t('Order results by selected columns'), multi: true, default: [], mapStateToProps: ({ datasource }) => ({ choices: datasource?.order_by_choices || [], }), visibility: isRawMode, }, }, ], isFeatureEnabled(FeatureFlag.DASHBOARD_CROSS_FILTERS) || isFeatureEnabled(FeatureFlag.DASHBOARD_NATIVE_FILTERS) ? [ { name: 'server_pagination', config: { type: 'CheckboxControl', label: t('Server pagination'), description: t( 'Enable server side pagination of results (experimental feature)', ), default: false, }, }, ] : [], [ { name: 'row_limit', override: { visibility: ({ controls }: ControlPanelsContainerProps) => !controls?.server_pagination?.value, }, }, { name: 'server_page_length', config: { type: 'SelectControl', freeForm: true, label: t('Server Page Length'), default: 10, choices: PAGE_SIZE_OPTIONS, description: t('Rows per page, 0 means no pagination'), visibility: ({ controls }: ControlPanelsContainerProps) => Boolean(controls?.server_pagination?.value), }, }, ], [ { name: 'include_time', config: { type: 'CheckboxControl', label: t('Include time'), description: t( 'Whether to include the time granularity as defined in the time section', ), default: false, visibility: isAggMode, }, }, { name: 'order_desc', config: { type: 'CheckboxControl', label: t('Sort descending'), default: true, description: t('Whether to sort descending or ascending'), visibility: isAggMode, }, }, ], [ { name: 'show_totals', config: { type: 'CheckboxControl', label: t('Show totals'), default: false, description: t( 'Show total aggregations of selected metrics. Note that row limit does not apply to the result.', ), visibility: isAggMode, }, }, ], emitFilterControl, ], }, { label: t('Options'), expanded: true, controlSetRows: [ [ { name: 'table_timestamp_format', config: { type: 'SelectControl', freeForm: true, label: t('Timestamp format'), default: smartDateFormatter.id, renderTrigger: true, clearable: false, choices: D3_TIME_FORMAT_OPTIONS, description: t('D3 time format for datetime columns'), }, }, ], [ { name: 'page_length', config: { type: 'SelectControl', freeForm: true, renderTrigger: true, label: t('Page length'), default: null, choices: PAGE_SIZE_OPTIONS, description: t('Rows per page, 0 means no pagination'), visibility: ({ controls }: ControlPanelsContainerProps) => !controls?.server_pagination?.value, }, }, null, ], [ { name: 'include_search', config: { type: 'CheckboxControl', label: t('Search box'), renderTrigger: true, default: false, description: t('Whether to include a client-side search box'), }, }, { name: 'show_cell_bars', config: { type: 'CheckboxControl', label: t('Cell bars'), renderTrigger: true, default: true, description: t( 'Whether to display a bar chart background in table columns', ), }, }, ], [ { name: 'align_pn', config: { type: 'CheckboxControl', label: t('Align +/-'), renderTrigger: true, default: false, description: t( 'Whether to align background charts with both positive and negative values at 0', ), }, }, { name: 'color_pn', config: { type: 'CheckboxControl', label: t('Color +/-'), renderTrigger: true, default: true, description: t( 'Whether to colorize numeric values by if they are positive or negative', ), }, }, ], [ { name: 'column_config', config: { type: 'ColumnConfigControl', label: t('Customize columns'), description: t('Further customize how to display each column'), renderTrigger: true, shouldMapStateToProps() { return true; }, mapStateToProps(explore, _, chart) { return { queryResponse: chart?.queriesResponse?.[0] as | ChartDataResponseResult | undefined, emitFilter: explore?.controls?.table_filter?.value, }; }, }, }, ], [ { name: 'conditional_formatting', config: { type: 'ConditionalFormattingControl', renderTrigger: true, label: t('Conditional formatting'), description: t( 'Apply conditional color formatting to numeric columns', ), shouldMapStateToProps() { return true; }, mapStateToProps(explore, _, chart) { const verboseMap = explore?.datasource?.verbose_map ?? {}; const { colnames, coltypes } = chart?.queriesResponse?.[0] ?? {}; const numericColumns = Array.isArray(colnames) && Array.isArray(coltypes) ? colnames .filter( (colname: string, index: number) => coltypes[index] === GenericDataType.NUMERIC, ) .map(colname => ({ value: colname, label: verboseMap[colname] ?? colname, })) : []; return { columnOptions: numericColumns, verboseMap, }; }, }, }, ], ], }, ], }; export default config;
superset-frontend/plugins/plugin-chart-table/src/controlPanel.tsx
1
https://github.com/apache/superset/commit/fcc8080ff3b99e2f5f5cdbd48335d7ab83aba16a
[ 0.999116837978363, 0.06209612637758255, 0.00016653601778671145, 0.0003137392923235893, 0.22729244828224182 ]
{ "id": 0, "code_window": [ " : [],\n", " }),\n", " visibility: isRawMode,\n", "};\n", "\n", "const dnd_all_columns: typeof sharedControls.groupby = {\n", " type: 'DndColumnSelect',\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " resetOnHide: false,\n" ], "file_path": "superset-frontend/plugins/plugin-chart-table/src/controlPanel.tsx", "type": "add", "edit_start_line_idx": 119 }
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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. import functools from typing import Any, Callable, Dict, Optional, Tuple, Type class _memoized: """Decorator that caches a function's return value each time it is called If called later with the same arguments, the cached value is returned, and not re-evaluated. Define ``watch`` as a tuple of attribute names if this Decorator should account for instance variable changes. """ def __init__( self, func: Callable[..., Any], watch: Optional[Tuple[str, ...]] = None ) -> None: self.func = func self.cache: Dict[Any, Any] = {} self.is_method = False self.watch = watch or () def __call__(self, *args: Any, **kwargs: Any) -> Any: key = [args, frozenset(kwargs.items())] if self.is_method: key.append(tuple(getattr(args[0], v, None) for v in self.watch)) key = tuple(key) # type: ignore try: if key in self.cache: return self.cache[key] except TypeError as ex: # Uncachable -- for instance, passing a list as an argument. raise TypeError("Function cannot be memoized") from ex value = self.func(*args, **kwargs) try: self.cache[key] = value except TypeError as ex: raise TypeError("Function cannot be memoized") from ex return value def __repr__(self) -> str: """Return the function's docstring.""" return self.func.__doc__ or "" def __get__( self, obj: Any, objtype: Type[Any] ) -> functools.partial: # type: ignore if not self.is_method: self.is_method = True # Support instance methods. func = functools.partial(self.__call__, obj) func.__func__ = self.func # type: ignore return func def memoized( func: Optional[Callable[..., Any]] = None, watch: Optional[Tuple[str, ...]] = None ) -> Callable[..., Any]: if func: return _memoized(func) def wrapper(f: Callable[..., Any]) -> Callable[..., Any]: return _memoized(f, watch) return wrapper
superset/utils/memoized.py
0
https://github.com/apache/superset/commit/fcc8080ff3b99e2f5f5cdbd48335d7ab83aba16a
[ 0.0023396038450300694, 0.0004125066625420004, 0.00016900368791539222, 0.00017049747111741453, 0.0006813366780988872 ]
{ "id": 0, "code_window": [ " : [],\n", " }),\n", " visibility: isRawMode,\n", "};\n", "\n", "const dnd_all_columns: typeof sharedControls.groupby = {\n", " type: 'DndColumnSelect',\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " resetOnHide: false,\n" ], "file_path": "superset-frontend/plugins/plugin-chart-table/src/controlPanel.tsx", "type": "add", "edit_start_line_idx": 119 }
#!/bin/bash # # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You 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. # set -e GITHUB_WORKSPACE=${GITHUB_WORKSPACE:-.} ASSETS_MANIFEST="$GITHUB_WORKSPACE/superset/static/assets/manifest.json" # Rounded job start time, used to create a unique Cypress build id for # parallelization so we can manually rerun a job after 20 minutes NONCE=$(echo "$(date "+%Y%m%d%H%M") - ($(date +%M)%20)" | bc) # Echo only when not in parallel mode say() { if [[ $(echo "$INPUT_PARALLEL" | tr '[:lower:]' '[:upper:]') != 'TRUE' ]]; then echo "$1" fi } # default command to run when the `run` input is empty default-setup-command() { apt-get-install pip-upgrade } apt-get-install() { say "::group::apt-get install dependencies" sudo apt-get update && sudo apt-get install --yes \ libsasl2-dev say "::endgroup::" } pip-upgrade() { say "::group::Upgrade pip" pip install --upgrade pip say "::endgroup::" } # prepare (lint and build) frontend code npm-install() { cd "$GITHUB_WORKSPACE/superset-frontend" # cache-restore npm say "::group::Install npm packages" echo "npm: $(npm --version)" echo "node: $(node --version)" npm ci say "::endgroup::" # cache-save npm } build-assets() { cd "$GITHUB_WORKSPACE/superset-frontend" say "::group::Build static assets" npm run build say "::endgroup::" } build-instrumented-assets() { cd "$GITHUB_WORKSPACE/superset-frontend" say "::group::Build static assets with JS instrumented for test coverage" cache-restore instrumented-assets if [[ -f "$ASSETS_MANIFEST" ]]; then echo 'Skip frontend build because instrumented static assets already exist.' else npm run build-instrumented cache-save instrumented-assets fi say "::endgroup::" } setup-postgres() { say "::group::Install dependency for unit tests" sudo apt-get update && sudo apt-get install --yes libecpg-dev say "::group::Initialize database" psql "postgresql://superset:[email protected]:15432/superset" <<-EOF DROP SCHEMA IF EXISTS sqllab_test_db CASCADE; DROP SCHEMA IF EXISTS admin_database CASCADE; CREATE SCHEMA sqllab_test_db; CREATE SCHEMA admin_database; EOF say "::endgroup::" } setup-mysql() { say "::group::Initialize database" mysql -h 127.0.0.1 -P 13306 -u root --password=root <<-EOF DROP DATABASE IF EXISTS superset; CREATE DATABASE superset DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci; DROP DATABASE IF EXISTS sqllab_test_db; CREATE DATABASE sqllab_test_db DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci; DROP DATABASE IF EXISTS admin_database; CREATE DATABASE admin_database DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci; CREATE USER 'superset'@'%' IDENTIFIED BY 'superset'; GRANT ALL ON *.* TO 'superset'@'%'; FLUSH PRIVILEGES; EOF say "::endgroup::" } testdata() { cd "$GITHUB_WORKSPACE" say "::group::Load test data" # must specify PYTHONPATH to make `tests.superset_test_config` importable export PYTHONPATH="$GITHUB_WORKSPACE" pip install -e . superset db upgrade superset load_test_users superset load_examples --load-test-data superset init say "::endgroup::" } codecov() { say "::group::Upload code coverage" bash ".github/workflows/codecov.sh" "$@" say "::endgroup::" } cypress-install() { cd "$GITHUB_WORKSPACE/superset-frontend/cypress-base" cache-restore cypress say "::group::Install Cypress" npm ci say "::endgroup::" cache-save cypress } # Run Cypress and upload coverage reports cypress-run() { cd "$GITHUB_WORKSPACE/superset-frontend/cypress-base" local page=$1 local group=${2:-Default} local cypress="./node_modules/.bin/cypress run" local browser=${CYPRESS_BROWSER:-chrome} export TERM="xterm" say "::group::Run Cypress for [$page]" if [[ -z $CYPRESS_KEY ]]; then $cypress --spec "cypress/integration/$page" --browser "$browser" else export CYPRESS_RECORD_KEY=$(echo $CYPRESS_KEY | base64 --decode) # additional flags for Cypress dashboard recording $cypress --spec "cypress/integration/$page" --browser "$browser" \ --record --group "$group" --tag "${GITHUB_REPOSITORY},${GITHUB_EVENT_NAME}" \ --parallel --ci-build-id "${GITHUB_SHA:0:8}-${NONCE}" fi # don't add quotes to $record because we do want word splitting say "::endgroup::" } cypress-run-all() { # Start Flask and run it in background # --no-debugger means disable the interactive debugger on the 500 page # so errors can print to stderr. local flasklog="${HOME}/flask.log" local port=8081 export CYPRESS_BASE_URL="http://localhost:${port}" nohup flask run --no-debugger -p $port >"$flasklog" 2>&1 </dev/null & local flaskProcessId=$! cypress-run "*/**/*" # After job is done, print out Flask log for debugging say "::group::Flask log for default run" cat "$flasklog" say "::endgroup::" # Rerun SQL Lab tests with backend persist disabled export SUPERSET_CONFIG=tests.integration_tests.superset_test_config_sqllab_backend_persist_off # Restart Flask with new configs kill $flaskProcessId nohup flask run --no-debugger -p $port >"$flasklog" 2>&1 </dev/null & local flaskProcessId=$! cypress-run "sqllab/*" "Backend persist" # Upload code coverage separately so each page can have separate flags # -c will clean existing coverage reports, -F means add flags # || true to prevent CI failure on codecov upload codecov -c -F "cypress" || true say "::group::Flask log for backend persist" cat "$flasklog" say "::endgroup::" # make sure the program exits kill $flaskProcessId }
.github/workflows/bashlib.sh
0
https://github.com/apache/superset/commit/fcc8080ff3b99e2f5f5cdbd48335d7ab83aba16a
[ 0.00018692793673835695, 0.00017050030874088407, 0.00016647919255774468, 0.00016914996376726776, 0.000004538294888334349 ]
{ "id": 0, "code_window": [ " : [],\n", " }),\n", " visibility: isRawMode,\n", "};\n", "\n", "const dnd_all_columns: typeof sharedControls.groupby = {\n", " type: 'DndColumnSelect',\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " resetOnHide: false,\n" ], "file_path": "superset-frontend/plugins/plugin-chart-table/src/controlPanel.tsx", "type": "add", "edit_start_line_idx": 119 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ import { sanitizeFormData } from './formData'; test('sanitizeFormData removes temporary control values', () => { expect( sanitizeFormData({ url_params: { foo: 'bar' }, metrics: ['foo', 'bar'], }), ).toEqual({ metrics: ['foo', 'bar'] }); });
superset-frontend/src/explore/exploreUtils/formData.test.ts
0
https://github.com/apache/superset/commit/fcc8080ff3b99e2f5f5cdbd48335d7ab83aba16a
[ 0.00017393344023730606, 0.00017305114306509495, 0.00017255329294130206, 0.00017266671056859195, 6.255907578633924e-7 ]
{ "id": 1, "code_window": [ " : [];\n", " return newState;\n", " },\n", " visibility: isRawMode,\n", "};\n", "\n", "const percent_metrics: typeof sharedControls.metrics = {\n", " type: 'MetricsControl',\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " resetOnHide: false,\n" ], "file_path": "superset-frontend/plugins/plugin-chart-table/src/controlPanel.tsx", "type": "add", "edit_start_line_idx": 142 }
/* eslint-disable camelcase */ /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ import React from 'react'; import { addLocaleData, ChartDataResponseResult, ensureIsArray, FeatureFlag, GenericDataType, isFeatureEnabled, QueryFormColumn, QueryMode, smartDateFormatter, t, } from '@superset-ui/core'; import { ColumnOption, ControlConfig, ControlPanelConfig, ControlPanelsContainerProps, ControlStateMapping, D3_TIME_FORMAT_OPTIONS, QueryModeLabel, sections, sharedControls, ControlPanelState, ExtraControlProps, ControlState, emitFilterControl, } from '@superset-ui/chart-controls'; import i18n from './i18n'; import { PAGE_SIZE_OPTIONS } from './consts'; addLocaleData(i18n); function getQueryMode(controls: ControlStateMapping): QueryMode { const mode = controls?.query_mode?.value; if (mode === QueryMode.aggregate || mode === QueryMode.raw) { return mode as QueryMode; } const rawColumns = controls?.all_columns?.value as | QueryFormColumn[] | undefined; const hasRawColumns = rawColumns && rawColumns.length > 0; return hasRawColumns ? QueryMode.raw : QueryMode.aggregate; } /** * Visibility check */ function isQueryMode(mode: QueryMode) { return ({ controls }: Pick<ControlPanelsContainerProps, 'controls'>) => getQueryMode(controls) === mode; } const isAggMode = isQueryMode(QueryMode.aggregate); const isRawMode = isQueryMode(QueryMode.raw); const validateAggControlValues = ( controls: ControlStateMapping, values: any[], ) => { const areControlsEmpty = values.every(val => ensureIsArray(val).length === 0); return areControlsEmpty && isAggMode({ controls }) ? [t('Group By, Metrics or Percentage Metrics must have a value')] : []; }; const queryMode: ControlConfig<'RadioButtonControl'> = { type: 'RadioButtonControl', label: t('Query mode'), default: null, options: [ [QueryMode.aggregate, QueryModeLabel[QueryMode.aggregate]], [QueryMode.raw, QueryModeLabel[QueryMode.raw]], ], mapStateToProps: ({ controls }) => ({ value: getQueryMode(controls) }), rerender: ['all_columns', 'groupby', 'metrics', 'percent_metrics'], }; const all_columns: typeof sharedControls.groupby = { type: 'SelectControl', label: t('Columns'), description: t('Columns to display'), multi: true, freeForm: true, allowAll: true, commaChoosesOption: false, default: [], optionRenderer: c => <ColumnOption showType column={c} />, valueRenderer: c => <ColumnOption column={c} />, valueKey: 'column_name', mapStateToProps: ({ datasource, controls }, controlState) => ({ options: datasource?.columns || [], queryMode: getQueryMode(controls), externalValidationErrors: isRawMode({ controls }) && ensureIsArray(controlState.value).length === 0 ? [t('must have a value')] : [], }), visibility: isRawMode, }; const dnd_all_columns: typeof sharedControls.groupby = { type: 'DndColumnSelect', label: t('Columns'), description: t('Columns to display'), default: [], mapStateToProps({ datasource, controls }, controlState) { const newState: ExtraControlProps = {}; if (datasource) { const options = datasource.columns; newState.options = Object.fromEntries( options.map(option => [option.column_name, option]), ); } newState.queryMode = getQueryMode(controls); newState.externalValidationErrors = isRawMode({ controls }) && ensureIsArray(controlState.value).length === 0 ? [t('must have a value')] : []; return newState; }, visibility: isRawMode, }; const percent_metrics: typeof sharedControls.metrics = { type: 'MetricsControl', label: t('Percentage metrics'), description: t( 'Metrics for which percentage of total are to be displayed. Calculated from only data within the row limit.', ), multi: true, visibility: isAggMode, mapStateToProps: ({ datasource, controls }, controlState) => ({ columns: datasource?.columns || [], savedMetrics: datasource?.metrics || [], datasource, datasourceType: datasource?.type, queryMode: getQueryMode(controls), externalValidationErrors: validateAggControlValues(controls, [ controls.groupby?.value, controls.metrics?.value, controlState.value, ]), }), rerender: ['groupby', 'metrics'], default: [], validators: [], }; const dnd_percent_metrics = { ...percent_metrics, type: 'DndMetricSelect', }; const config: ControlPanelConfig = { controlPanelSections: [ sections.legacyTimeseriesTime, { label: t('Query'), expanded: true, controlSetRows: [ [ { name: 'query_mode', config: queryMode, }, ], [ { name: 'groupby', override: { visibility: isAggMode, mapStateToProps: ( state: ControlPanelState, controlState: ControlState, ) => { const { controls } = state; const originalMapStateToProps = sharedControls?.groupby?.mapStateToProps; const newState = originalMapStateToProps?.(state, controlState) ?? {}; newState.externalValidationErrors = validateAggControlValues( controls, [ controls.metrics?.value, controls.percent_metrics?.value, controlState.value, ], ); return newState; }, rerender: ['metrics', 'percent_metrics'], }, }, ], [ { name: 'metrics', override: { validators: [], visibility: isAggMode, mapStateToProps: ( { controls, datasource, form_data }: ControlPanelState, controlState: ControlState, ) => ({ columns: datasource?.columns.filter(c => c.filterable) || [], savedMetrics: datasource?.metrics || [], // current active adhoc metrics selectedMetrics: form_data.metrics || (form_data.metric ? [form_data.metric] : []), datasource, externalValidationErrors: validateAggControlValues(controls, [ controls.groupby?.value, controls.percent_metrics?.value, controlState.value, ]), }), rerender: ['groupby', 'percent_metrics'], }, }, { name: 'all_columns', config: isFeatureEnabled(FeatureFlag.ENABLE_EXPLORE_DRAG_AND_DROP) ? dnd_all_columns : all_columns, }, ], [ { name: 'percent_metrics', config: { ...(isFeatureEnabled(FeatureFlag.ENABLE_EXPLORE_DRAG_AND_DROP) ? dnd_percent_metrics : percent_metrics), }, }, ], ['adhoc_filters'], [ { name: 'timeseries_limit_metric', override: { visibility: isAggMode, }, }, { name: 'order_by_cols', config: { type: 'SelectControl', label: t('Ordering'), description: t('Order results by selected columns'), multi: true, default: [], mapStateToProps: ({ datasource }) => ({ choices: datasource?.order_by_choices || [], }), visibility: isRawMode, }, }, ], isFeatureEnabled(FeatureFlag.DASHBOARD_CROSS_FILTERS) || isFeatureEnabled(FeatureFlag.DASHBOARD_NATIVE_FILTERS) ? [ { name: 'server_pagination', config: { type: 'CheckboxControl', label: t('Server pagination'), description: t( 'Enable server side pagination of results (experimental feature)', ), default: false, }, }, ] : [], [ { name: 'row_limit', override: { visibility: ({ controls }: ControlPanelsContainerProps) => !controls?.server_pagination?.value, }, }, { name: 'server_page_length', config: { type: 'SelectControl', freeForm: true, label: t('Server Page Length'), default: 10, choices: PAGE_SIZE_OPTIONS, description: t('Rows per page, 0 means no pagination'), visibility: ({ controls }: ControlPanelsContainerProps) => Boolean(controls?.server_pagination?.value), }, }, ], [ { name: 'include_time', config: { type: 'CheckboxControl', label: t('Include time'), description: t( 'Whether to include the time granularity as defined in the time section', ), default: false, visibility: isAggMode, }, }, { name: 'order_desc', config: { type: 'CheckboxControl', label: t('Sort descending'), default: true, description: t('Whether to sort descending or ascending'), visibility: isAggMode, }, }, ], [ { name: 'show_totals', config: { type: 'CheckboxControl', label: t('Show totals'), default: false, description: t( 'Show total aggregations of selected metrics. Note that row limit does not apply to the result.', ), visibility: isAggMode, }, }, ], emitFilterControl, ], }, { label: t('Options'), expanded: true, controlSetRows: [ [ { name: 'table_timestamp_format', config: { type: 'SelectControl', freeForm: true, label: t('Timestamp format'), default: smartDateFormatter.id, renderTrigger: true, clearable: false, choices: D3_TIME_FORMAT_OPTIONS, description: t('D3 time format for datetime columns'), }, }, ], [ { name: 'page_length', config: { type: 'SelectControl', freeForm: true, renderTrigger: true, label: t('Page length'), default: null, choices: PAGE_SIZE_OPTIONS, description: t('Rows per page, 0 means no pagination'), visibility: ({ controls }: ControlPanelsContainerProps) => !controls?.server_pagination?.value, }, }, null, ], [ { name: 'include_search', config: { type: 'CheckboxControl', label: t('Search box'), renderTrigger: true, default: false, description: t('Whether to include a client-side search box'), }, }, { name: 'show_cell_bars', config: { type: 'CheckboxControl', label: t('Cell bars'), renderTrigger: true, default: true, description: t( 'Whether to display a bar chart background in table columns', ), }, }, ], [ { name: 'align_pn', config: { type: 'CheckboxControl', label: t('Align +/-'), renderTrigger: true, default: false, description: t( 'Whether to align background charts with both positive and negative values at 0', ), }, }, { name: 'color_pn', config: { type: 'CheckboxControl', label: t('Color +/-'), renderTrigger: true, default: true, description: t( 'Whether to colorize numeric values by if they are positive or negative', ), }, }, ], [ { name: 'column_config', config: { type: 'ColumnConfigControl', label: t('Customize columns'), description: t('Further customize how to display each column'), renderTrigger: true, shouldMapStateToProps() { return true; }, mapStateToProps(explore, _, chart) { return { queryResponse: chart?.queriesResponse?.[0] as | ChartDataResponseResult | undefined, emitFilter: explore?.controls?.table_filter?.value, }; }, }, }, ], [ { name: 'conditional_formatting', config: { type: 'ConditionalFormattingControl', renderTrigger: true, label: t('Conditional formatting'), description: t( 'Apply conditional color formatting to numeric columns', ), shouldMapStateToProps() { return true; }, mapStateToProps(explore, _, chart) { const verboseMap = explore?.datasource?.verbose_map ?? {}; const { colnames, coltypes } = chart?.queriesResponse?.[0] ?? {}; const numericColumns = Array.isArray(colnames) && Array.isArray(coltypes) ? colnames .filter( (colname: string, index: number) => coltypes[index] === GenericDataType.NUMERIC, ) .map(colname => ({ value: colname, label: verboseMap[colname] ?? colname, })) : []; return { columnOptions: numericColumns, verboseMap, }; }, }, }, ], ], }, ], }; export default config;
superset-frontend/plugins/plugin-chart-table/src/controlPanel.tsx
1
https://github.com/apache/superset/commit/fcc8080ff3b99e2f5f5cdbd48335d7ab83aba16a
[ 0.9992076754570007, 0.15282264351844788, 0.00016544094251003116, 0.0001740690495353192, 0.3561916947364807 ]
{ "id": 1, "code_window": [ " : [];\n", " return newState;\n", " },\n", " visibility: isRawMode,\n", "};\n", "\n", "const percent_metrics: typeof sharedControls.metrics = {\n", " type: 'MetricsControl',\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " resetOnHide: false,\n" ], "file_path": "superset-frontend/plugins/plugin-chart-table/src/controlPanel.tsx", "type": "add", "edit_start_line_idx": 142 }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ import { SVG_NS } from './constants'; export default function createHiddenSvgNode() { const svgNode = document.createElementNS(SVG_NS, 'svg'); svgNode.style.position = 'absolute'; // so it won't disrupt page layout svgNode.style.top = '-100%'; svgNode.style.left = '-100%'; svgNode.style.width = '0'; // no dimensions svgNode.style.height = '0'; svgNode.style.opacity = '0'; // not visible svgNode.style.pointerEvents = 'none'; // won't capture mouse events return svgNode; }
superset-frontend/packages/superset-ui-core/src/dimension/svg/createHiddenSvgNode.ts
0
https://github.com/apache/superset/commit/fcc8080ff3b99e2f5f5cdbd48335d7ab83aba16a
[ 0.00017425000260118395, 0.0001728067873045802, 0.0001709588395897299, 0.00017300914623774588, 0.00000135435936954309 ]
{ "id": 1, "code_window": [ " : [];\n", " return newState;\n", " },\n", " visibility: isRawMode,\n", "};\n", "\n", "const percent_metrics: typeof sharedControls.metrics = {\n", " type: 'MetricsControl',\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " resetOnHide: false,\n" ], "file_path": "superset-frontend/plugins/plugin-chart-table/src/controlPanel.tsx", "type": "add", "edit_start_line_idx": 142 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ export const REFRESH_TIMING_BUFFER_MS = 5000 // refresh guest token early to avoid failed superset requests export const MIN_REFRESH_WAIT_MS = 10000 // avoid blasting requests as fast as the cpu can handle export const DEFAULT_TOKEN_EXP_MS = 300000 // (5 min) used only when parsing guest token exp fails // when do we refresh the guest token? export function getGuestTokenRefreshTiming(currentGuestToken: string) { const parsedJwt = JSON.parse(Buffer.from(currentGuestToken.split('.')[1], 'base64').toString()); // if exp is int, it is in seconds, but Date() takes milliseconds const exp = new Date(/[^0-9\.]/g.test(parsedJwt.exp) ? parsedJwt.exp : parseFloat(parsedJwt.exp) * 1000); const isValidDate = exp.toString() !== 'Invalid Date'; const ttl = isValidDate ? Math.max(MIN_REFRESH_WAIT_MS, exp.getTime() - Date.now()) : DEFAULT_TOKEN_EXP_MS; return ttl - REFRESH_TIMING_BUFFER_MS; }
superset-embedded-sdk/src/guestTokenRefresh.ts
0
https://github.com/apache/superset/commit/fcc8080ff3b99e2f5f5cdbd48335d7ab83aba16a
[ 0.0023059279192239046, 0.000703641795553267, 0.00016693395446054637, 0.0001708525960566476, 0.0009250841103494167 ]
{ "id": 1, "code_window": [ " : [];\n", " return newState;\n", " },\n", " visibility: isRawMode,\n", "};\n", "\n", "const percent_metrics: typeof sharedControls.metrics = {\n", " type: 'MetricsControl',\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " resetOnHide: false,\n" ], "file_path": "superset-frontend/plugins/plugin-chart-table/src/controlPanel.tsx", "type": "add", "edit_start_line_idx": 142 }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ import { WordCloudFormData } from '../../src'; import buildQuery from '../../src/plugin/buildQuery'; describe('WordCloud buildQuery', () => { const formData: WordCloudFormData = { datasource: '5__table', granularity_sqla: 'ds', series: 'foo', viz_type: 'word_cloud', }; it('should build columns from series in form data', () => { const queryContext = buildQuery(formData); const [query] = queryContext.queries; expect(query.columns).toEqual(['foo']); }); });
superset-frontend/plugins/plugin-chart-word-cloud/test/plugin/buildQuery.test.ts
0
https://github.com/apache/superset/commit/fcc8080ff3b99e2f5f5cdbd48335d7ab83aba16a
[ 0.00017422241216991097, 0.00017239610315300524, 0.00016992699238471687, 0.00017271749675273895, 0.0000017789566300052684 ]
{ "id": 2, "code_window": [ " ),\n", " multi: true,\n", " visibility: isAggMode,\n", " mapStateToProps: ({ datasource, controls }, controlState) => ({\n", " columns: datasource?.columns || [],\n", " savedMetrics: datasource?.metrics || [],\n", " datasource,\n", " datasourceType: datasource?.type,\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " resetOnHide: false,\n" ], "file_path": "superset-frontend/plugins/plugin-chart-table/src/controlPanel.tsx", "type": "add", "edit_start_line_idx": 152 }
/* eslint-disable camelcase */ /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ import React from 'react'; import { addLocaleData, ChartDataResponseResult, ensureIsArray, FeatureFlag, GenericDataType, isFeatureEnabled, QueryFormColumn, QueryMode, smartDateFormatter, t, } from '@superset-ui/core'; import { ColumnOption, ControlConfig, ControlPanelConfig, ControlPanelsContainerProps, ControlStateMapping, D3_TIME_FORMAT_OPTIONS, QueryModeLabel, sections, sharedControls, ControlPanelState, ExtraControlProps, ControlState, emitFilterControl, } from '@superset-ui/chart-controls'; import i18n from './i18n'; import { PAGE_SIZE_OPTIONS } from './consts'; addLocaleData(i18n); function getQueryMode(controls: ControlStateMapping): QueryMode { const mode = controls?.query_mode?.value; if (mode === QueryMode.aggregate || mode === QueryMode.raw) { return mode as QueryMode; } const rawColumns = controls?.all_columns?.value as | QueryFormColumn[] | undefined; const hasRawColumns = rawColumns && rawColumns.length > 0; return hasRawColumns ? QueryMode.raw : QueryMode.aggregate; } /** * Visibility check */ function isQueryMode(mode: QueryMode) { return ({ controls }: Pick<ControlPanelsContainerProps, 'controls'>) => getQueryMode(controls) === mode; } const isAggMode = isQueryMode(QueryMode.aggregate); const isRawMode = isQueryMode(QueryMode.raw); const validateAggControlValues = ( controls: ControlStateMapping, values: any[], ) => { const areControlsEmpty = values.every(val => ensureIsArray(val).length === 0); return areControlsEmpty && isAggMode({ controls }) ? [t('Group By, Metrics or Percentage Metrics must have a value')] : []; }; const queryMode: ControlConfig<'RadioButtonControl'> = { type: 'RadioButtonControl', label: t('Query mode'), default: null, options: [ [QueryMode.aggregate, QueryModeLabel[QueryMode.aggregate]], [QueryMode.raw, QueryModeLabel[QueryMode.raw]], ], mapStateToProps: ({ controls }) => ({ value: getQueryMode(controls) }), rerender: ['all_columns', 'groupby', 'metrics', 'percent_metrics'], }; const all_columns: typeof sharedControls.groupby = { type: 'SelectControl', label: t('Columns'), description: t('Columns to display'), multi: true, freeForm: true, allowAll: true, commaChoosesOption: false, default: [], optionRenderer: c => <ColumnOption showType column={c} />, valueRenderer: c => <ColumnOption column={c} />, valueKey: 'column_name', mapStateToProps: ({ datasource, controls }, controlState) => ({ options: datasource?.columns || [], queryMode: getQueryMode(controls), externalValidationErrors: isRawMode({ controls }) && ensureIsArray(controlState.value).length === 0 ? [t('must have a value')] : [], }), visibility: isRawMode, }; const dnd_all_columns: typeof sharedControls.groupby = { type: 'DndColumnSelect', label: t('Columns'), description: t('Columns to display'), default: [], mapStateToProps({ datasource, controls }, controlState) { const newState: ExtraControlProps = {}; if (datasource) { const options = datasource.columns; newState.options = Object.fromEntries( options.map(option => [option.column_name, option]), ); } newState.queryMode = getQueryMode(controls); newState.externalValidationErrors = isRawMode({ controls }) && ensureIsArray(controlState.value).length === 0 ? [t('must have a value')] : []; return newState; }, visibility: isRawMode, }; const percent_metrics: typeof sharedControls.metrics = { type: 'MetricsControl', label: t('Percentage metrics'), description: t( 'Metrics for which percentage of total are to be displayed. Calculated from only data within the row limit.', ), multi: true, visibility: isAggMode, mapStateToProps: ({ datasource, controls }, controlState) => ({ columns: datasource?.columns || [], savedMetrics: datasource?.metrics || [], datasource, datasourceType: datasource?.type, queryMode: getQueryMode(controls), externalValidationErrors: validateAggControlValues(controls, [ controls.groupby?.value, controls.metrics?.value, controlState.value, ]), }), rerender: ['groupby', 'metrics'], default: [], validators: [], }; const dnd_percent_metrics = { ...percent_metrics, type: 'DndMetricSelect', }; const config: ControlPanelConfig = { controlPanelSections: [ sections.legacyTimeseriesTime, { label: t('Query'), expanded: true, controlSetRows: [ [ { name: 'query_mode', config: queryMode, }, ], [ { name: 'groupby', override: { visibility: isAggMode, mapStateToProps: ( state: ControlPanelState, controlState: ControlState, ) => { const { controls } = state; const originalMapStateToProps = sharedControls?.groupby?.mapStateToProps; const newState = originalMapStateToProps?.(state, controlState) ?? {}; newState.externalValidationErrors = validateAggControlValues( controls, [ controls.metrics?.value, controls.percent_metrics?.value, controlState.value, ], ); return newState; }, rerender: ['metrics', 'percent_metrics'], }, }, ], [ { name: 'metrics', override: { validators: [], visibility: isAggMode, mapStateToProps: ( { controls, datasource, form_data }: ControlPanelState, controlState: ControlState, ) => ({ columns: datasource?.columns.filter(c => c.filterable) || [], savedMetrics: datasource?.metrics || [], // current active adhoc metrics selectedMetrics: form_data.metrics || (form_data.metric ? [form_data.metric] : []), datasource, externalValidationErrors: validateAggControlValues(controls, [ controls.groupby?.value, controls.percent_metrics?.value, controlState.value, ]), }), rerender: ['groupby', 'percent_metrics'], }, }, { name: 'all_columns', config: isFeatureEnabled(FeatureFlag.ENABLE_EXPLORE_DRAG_AND_DROP) ? dnd_all_columns : all_columns, }, ], [ { name: 'percent_metrics', config: { ...(isFeatureEnabled(FeatureFlag.ENABLE_EXPLORE_DRAG_AND_DROP) ? dnd_percent_metrics : percent_metrics), }, }, ], ['adhoc_filters'], [ { name: 'timeseries_limit_metric', override: { visibility: isAggMode, }, }, { name: 'order_by_cols', config: { type: 'SelectControl', label: t('Ordering'), description: t('Order results by selected columns'), multi: true, default: [], mapStateToProps: ({ datasource }) => ({ choices: datasource?.order_by_choices || [], }), visibility: isRawMode, }, }, ], isFeatureEnabled(FeatureFlag.DASHBOARD_CROSS_FILTERS) || isFeatureEnabled(FeatureFlag.DASHBOARD_NATIVE_FILTERS) ? [ { name: 'server_pagination', config: { type: 'CheckboxControl', label: t('Server pagination'), description: t( 'Enable server side pagination of results (experimental feature)', ), default: false, }, }, ] : [], [ { name: 'row_limit', override: { visibility: ({ controls }: ControlPanelsContainerProps) => !controls?.server_pagination?.value, }, }, { name: 'server_page_length', config: { type: 'SelectControl', freeForm: true, label: t('Server Page Length'), default: 10, choices: PAGE_SIZE_OPTIONS, description: t('Rows per page, 0 means no pagination'), visibility: ({ controls }: ControlPanelsContainerProps) => Boolean(controls?.server_pagination?.value), }, }, ], [ { name: 'include_time', config: { type: 'CheckboxControl', label: t('Include time'), description: t( 'Whether to include the time granularity as defined in the time section', ), default: false, visibility: isAggMode, }, }, { name: 'order_desc', config: { type: 'CheckboxControl', label: t('Sort descending'), default: true, description: t('Whether to sort descending or ascending'), visibility: isAggMode, }, }, ], [ { name: 'show_totals', config: { type: 'CheckboxControl', label: t('Show totals'), default: false, description: t( 'Show total aggregations of selected metrics. Note that row limit does not apply to the result.', ), visibility: isAggMode, }, }, ], emitFilterControl, ], }, { label: t('Options'), expanded: true, controlSetRows: [ [ { name: 'table_timestamp_format', config: { type: 'SelectControl', freeForm: true, label: t('Timestamp format'), default: smartDateFormatter.id, renderTrigger: true, clearable: false, choices: D3_TIME_FORMAT_OPTIONS, description: t('D3 time format for datetime columns'), }, }, ], [ { name: 'page_length', config: { type: 'SelectControl', freeForm: true, renderTrigger: true, label: t('Page length'), default: null, choices: PAGE_SIZE_OPTIONS, description: t('Rows per page, 0 means no pagination'), visibility: ({ controls }: ControlPanelsContainerProps) => !controls?.server_pagination?.value, }, }, null, ], [ { name: 'include_search', config: { type: 'CheckboxControl', label: t('Search box'), renderTrigger: true, default: false, description: t('Whether to include a client-side search box'), }, }, { name: 'show_cell_bars', config: { type: 'CheckboxControl', label: t('Cell bars'), renderTrigger: true, default: true, description: t( 'Whether to display a bar chart background in table columns', ), }, }, ], [ { name: 'align_pn', config: { type: 'CheckboxControl', label: t('Align +/-'), renderTrigger: true, default: false, description: t( 'Whether to align background charts with both positive and negative values at 0', ), }, }, { name: 'color_pn', config: { type: 'CheckboxControl', label: t('Color +/-'), renderTrigger: true, default: true, description: t( 'Whether to colorize numeric values by if they are positive or negative', ), }, }, ], [ { name: 'column_config', config: { type: 'ColumnConfigControl', label: t('Customize columns'), description: t('Further customize how to display each column'), renderTrigger: true, shouldMapStateToProps() { return true; }, mapStateToProps(explore, _, chart) { return { queryResponse: chart?.queriesResponse?.[0] as | ChartDataResponseResult | undefined, emitFilter: explore?.controls?.table_filter?.value, }; }, }, }, ], [ { name: 'conditional_formatting', config: { type: 'ConditionalFormattingControl', renderTrigger: true, label: t('Conditional formatting'), description: t( 'Apply conditional color formatting to numeric columns', ), shouldMapStateToProps() { return true; }, mapStateToProps(explore, _, chart) { const verboseMap = explore?.datasource?.verbose_map ?? {}; const { colnames, coltypes } = chart?.queriesResponse?.[0] ?? {}; const numericColumns = Array.isArray(colnames) && Array.isArray(coltypes) ? colnames .filter( (colname: string, index: number) => coltypes[index] === GenericDataType.NUMERIC, ) .map(colname => ({ value: colname, label: verboseMap[colname] ?? colname, })) : []; return { columnOptions: numericColumns, verboseMap, }; }, }, }, ], ], }, ], }; export default config;
superset-frontend/plugins/plugin-chart-table/src/controlPanel.tsx
1
https://github.com/apache/superset/commit/fcc8080ff3b99e2f5f5cdbd48335d7ab83aba16a
[ 0.9715966582298279, 0.03242943808436394, 0.00016587326535955071, 0.00018893633387051523, 0.1411735713481903 ]
{ "id": 2, "code_window": [ " ),\n", " multi: true,\n", " visibility: isAggMode,\n", " mapStateToProps: ({ datasource, controls }, controlState) => ({\n", " columns: datasource?.columns || [],\n", " savedMetrics: datasource?.metrics || [],\n", " datasource,\n", " datasourceType: datasource?.type,\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " resetOnHide: false,\n" ], "file_path": "superset-frontend/plugins/plugin-chart-table/src/controlPanel.tsx", "type": "add", "edit_start_line_idx": 152 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ import { FORM_DATA_DEFAULTS, NUM_METRIC } from './shared.helper'; describe('Visualization > Time TableViz', () => { const VIZ_DEFAULTS = { ...FORM_DATA_DEFAULTS, viz_type: 'time_table' }; beforeEach(() => { cy.login(); cy.intercept('POST', '/superset/explore_json/**').as('getJson'); }); it('Test time series table multiple metrics last year total', () => { const formData = { ...VIZ_DEFAULTS, metrics: [NUM_METRIC, 'count'], column_collection: [ { key: '9g4K-B-YL', label: 'Last+Year', colType: 'time', timeLag: '1', comparisonType: 'value', }, ], url: '', }; cy.visitChartByParams(JSON.stringify(formData)); cy.verifySliceSuccess({ waitAlias: '@getJson', querySubstring: NUM_METRIC.label, }); cy.get('[data-test="time-table"]').within(() => { cy.get('span').contains('Sum(num)'); cy.get('span').contains('COUNT(*)'); }); }); it('Test time series table metric and group by last year total', () => { const formData = { ...VIZ_DEFAULTS, metrics: [NUM_METRIC], groupby: ['gender'], column_collection: [ { key: '9g4K-B-YL', label: 'Last+Year', colType: 'time', timeLag: '1', comparisonType: 'value', }, ], url: '', }; cy.visitChartByParams(JSON.stringify(formData)); cy.verifySliceSuccess({ waitAlias: '@getJson', querySubstring: NUM_METRIC.label, }); cy.get('[data-test="time-table"]').within(() => { cy.get('td').contains('boy'); cy.get('td').contains('girl'); }); }); it('Test time series various time columns', () => { const formData = { ...VIZ_DEFAULTS, metrics: [NUM_METRIC, 'count'], column_collection: [ { key: 'LHHNPhamU', label: 'Current', colType: 'time', timeLag: 0 }, { key: '9g4K-B-YL', label: 'Last Year', colType: 'time', timeLag: '1', comparisonType: 'value', }, { key: 'JVZXtNu7_', label: 'YoY', colType: 'time', timeLag: 1, comparisonType: 'perc', d3format: '%', }, { key: 'tN5Gba36u', label: 'Trend', colType: 'spark' }, ], url: '', }; cy.visitChartByParams(JSON.stringify(formData)); cy.verifySliceSuccess({ waitAlias: '@getJson', querySubstring: NUM_METRIC.label, }); cy.get('[data-test="time-table"]').within(() => { cy.get('th').contains('Current'); cy.get('th').contains('Last Year'); cy.get('th').contains('YoY'); cy.get('th').contains('Trend'); cy.get('span').contains('%'); cy.get('svg') .first() .then(charts => { const firstChart = charts[0]; expect(firstChart.clientWidth).greaterThan(0); expect(firstChart.clientHeight).greaterThan(0); }); }); }); });
superset-frontend/cypress-base/cypress/integration/explore/visualizations/time_table.js
0
https://github.com/apache/superset/commit/fcc8080ff3b99e2f5f5cdbd48335d7ab83aba16a
[ 0.0001787731162039563, 0.0001745975314406678, 0.00016904689255170524, 0.00017509175813756883, 0.000002451714863127563 ]
{ "id": 2, "code_window": [ " ),\n", " multi: true,\n", " visibility: isAggMode,\n", " mapStateToProps: ({ datasource, controls }, controlState) => ({\n", " columns: datasource?.columns || [],\n", " savedMetrics: datasource?.metrics || [],\n", " datasource,\n", " datasourceType: datasource?.type,\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " resetOnHide: false,\n" ], "file_path": "superset-frontend/plugins/plugin-chart-table/src/controlPanel.tsx", "type": "add", "edit_start_line_idx": 152 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ import { ControlPanelConfig, sections, sharedControls, } from '@superset-ui/chart-controls'; import { t } from '@superset-ui/core'; import { DEFAULT_FORM_DATA } from './types'; const { multiSelect } = DEFAULT_FORM_DATA; const config: ControlPanelConfig = { controlPanelSections: [ // @ts-ignore sections.legacyRegularTime, { label: t('Query'), expanded: true, controlSetRows: [ [ { name: 'groupby', config: { ...sharedControls.groupby, label: 'Columns to show', multiple: true, required: false, }, }, ], ], }, { label: t('UI Configuration'), expanded: true, controlSetRows: [ [ { name: 'multiSelect', config: { type: 'CheckboxControl', label: t('Can select multiple values'), default: multiSelect, affectsDataMask: true, resetConfig: true, renderTrigger: true, }, }, ], [ { name: 'enableEmptyFilter', config: { type: 'CheckboxControl', label: t('Filter value is required'), default: false, renderTrigger: true, description: t( 'User must select a value before applying the filter', ), }, }, ], ], }, ], }; export default config;
superset-frontend/src/filters/components/GroupBy/controlPanel.ts
0
https://github.com/apache/superset/commit/fcc8080ff3b99e2f5f5cdbd48335d7ab83aba16a
[ 0.00022779815481044352, 0.000176763060153462, 0.0001659688277868554, 0.0001719859428703785, 0.000018301454474567436 ]
{ "id": 2, "code_window": [ " ),\n", " multi: true,\n", " visibility: isAggMode,\n", " mapStateToProps: ({ datasource, controls }, controlState) => ({\n", " columns: datasource?.columns || [],\n", " savedMetrics: datasource?.metrics || [],\n", " datasource,\n", " datasourceType: datasource?.type,\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " resetOnHide: false,\n" ], "file_path": "superset-frontend/plugins/plugin-chart-table/src/controlPanel.tsx", "type": "add", "edit_start_line_idx": 152 }
{ "name": "@superset-ui/plugin-chart-table", "version": "0.18.25", "description": "Superset Chart - Table", "main": "lib/index.js", "module": "esm/index.js", "sideEffects": false, "files": [ "esm", "lib" ], "repository": { "type": "git", "url": "git+https://github.com/apache-superset/superset-ui.git" }, "keywords": [ "superset" ], "author": "Superset", "license": "Apache-2.0", "bugs": { "url": "https://github.com/apache-superset/superset-ui/issues" }, "homepage": "https://github.com/apache-superset/superset-ui#readme", "publishConfig": { "access": "public" }, "dependencies": { "@react-icons/all-files": "^4.1.0", "@types/d3-array": "^2.9.0", "@types/react-table": "^7.0.29", "@types/enzyme": "^3.10.5", "d3-array": "^2.4.0", "match-sorter": "^6.3.0", "memoize-one": "^5.1.1", "react-table": "^7.6.3", "regenerator-runtime": "^0.13.7", "xss": "^1.0.10" }, "peerDependencies": { "@types/react": "*", "@superset-ui/chart-controls": "*", "@superset-ui/core": "*", "react": "^16.13.1", "react-dom": "^16.13.1" } }
superset-frontend/plugins/plugin-chart-table/package.json
0
https://github.com/apache/superset/commit/fcc8080ff3b99e2f5f5cdbd48335d7ab83aba16a
[ 0.00017774479056242853, 0.00017524768190924078, 0.00017247122013941407, 0.00017468685109633952, 0.000001987058112717932 ]
{ "id": 3, "code_window": [ " [\n", " {\n", " name: 'groupby',\n", " override: {\n", " visibility: isAggMode,\n", " mapStateToProps: (\n", " state: ControlPanelState,\n", " controlState: ControlState,\n", " ) => {\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " resetOnHide: false,\n" ], "file_path": "superset-frontend/plugins/plugin-chart-table/src/controlPanel.tsx", "type": "add", "edit_start_line_idx": 192 }
/* eslint-disable camelcase */ /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ import React from 'react'; import { addLocaleData, ChartDataResponseResult, ensureIsArray, FeatureFlag, GenericDataType, isFeatureEnabled, QueryFormColumn, QueryMode, smartDateFormatter, t, } from '@superset-ui/core'; import { ColumnOption, ControlConfig, ControlPanelConfig, ControlPanelsContainerProps, ControlStateMapping, D3_TIME_FORMAT_OPTIONS, QueryModeLabel, sections, sharedControls, ControlPanelState, ExtraControlProps, ControlState, emitFilterControl, } from '@superset-ui/chart-controls'; import i18n from './i18n'; import { PAGE_SIZE_OPTIONS } from './consts'; addLocaleData(i18n); function getQueryMode(controls: ControlStateMapping): QueryMode { const mode = controls?.query_mode?.value; if (mode === QueryMode.aggregate || mode === QueryMode.raw) { return mode as QueryMode; } const rawColumns = controls?.all_columns?.value as | QueryFormColumn[] | undefined; const hasRawColumns = rawColumns && rawColumns.length > 0; return hasRawColumns ? QueryMode.raw : QueryMode.aggregate; } /** * Visibility check */ function isQueryMode(mode: QueryMode) { return ({ controls }: Pick<ControlPanelsContainerProps, 'controls'>) => getQueryMode(controls) === mode; } const isAggMode = isQueryMode(QueryMode.aggregate); const isRawMode = isQueryMode(QueryMode.raw); const validateAggControlValues = ( controls: ControlStateMapping, values: any[], ) => { const areControlsEmpty = values.every(val => ensureIsArray(val).length === 0); return areControlsEmpty && isAggMode({ controls }) ? [t('Group By, Metrics or Percentage Metrics must have a value')] : []; }; const queryMode: ControlConfig<'RadioButtonControl'> = { type: 'RadioButtonControl', label: t('Query mode'), default: null, options: [ [QueryMode.aggregate, QueryModeLabel[QueryMode.aggregate]], [QueryMode.raw, QueryModeLabel[QueryMode.raw]], ], mapStateToProps: ({ controls }) => ({ value: getQueryMode(controls) }), rerender: ['all_columns', 'groupby', 'metrics', 'percent_metrics'], }; const all_columns: typeof sharedControls.groupby = { type: 'SelectControl', label: t('Columns'), description: t('Columns to display'), multi: true, freeForm: true, allowAll: true, commaChoosesOption: false, default: [], optionRenderer: c => <ColumnOption showType column={c} />, valueRenderer: c => <ColumnOption column={c} />, valueKey: 'column_name', mapStateToProps: ({ datasource, controls }, controlState) => ({ options: datasource?.columns || [], queryMode: getQueryMode(controls), externalValidationErrors: isRawMode({ controls }) && ensureIsArray(controlState.value).length === 0 ? [t('must have a value')] : [], }), visibility: isRawMode, }; const dnd_all_columns: typeof sharedControls.groupby = { type: 'DndColumnSelect', label: t('Columns'), description: t('Columns to display'), default: [], mapStateToProps({ datasource, controls }, controlState) { const newState: ExtraControlProps = {}; if (datasource) { const options = datasource.columns; newState.options = Object.fromEntries( options.map(option => [option.column_name, option]), ); } newState.queryMode = getQueryMode(controls); newState.externalValidationErrors = isRawMode({ controls }) && ensureIsArray(controlState.value).length === 0 ? [t('must have a value')] : []; return newState; }, visibility: isRawMode, }; const percent_metrics: typeof sharedControls.metrics = { type: 'MetricsControl', label: t('Percentage metrics'), description: t( 'Metrics for which percentage of total are to be displayed. Calculated from only data within the row limit.', ), multi: true, visibility: isAggMode, mapStateToProps: ({ datasource, controls }, controlState) => ({ columns: datasource?.columns || [], savedMetrics: datasource?.metrics || [], datasource, datasourceType: datasource?.type, queryMode: getQueryMode(controls), externalValidationErrors: validateAggControlValues(controls, [ controls.groupby?.value, controls.metrics?.value, controlState.value, ]), }), rerender: ['groupby', 'metrics'], default: [], validators: [], }; const dnd_percent_metrics = { ...percent_metrics, type: 'DndMetricSelect', }; const config: ControlPanelConfig = { controlPanelSections: [ sections.legacyTimeseriesTime, { label: t('Query'), expanded: true, controlSetRows: [ [ { name: 'query_mode', config: queryMode, }, ], [ { name: 'groupby', override: { visibility: isAggMode, mapStateToProps: ( state: ControlPanelState, controlState: ControlState, ) => { const { controls } = state; const originalMapStateToProps = sharedControls?.groupby?.mapStateToProps; const newState = originalMapStateToProps?.(state, controlState) ?? {}; newState.externalValidationErrors = validateAggControlValues( controls, [ controls.metrics?.value, controls.percent_metrics?.value, controlState.value, ], ); return newState; }, rerender: ['metrics', 'percent_metrics'], }, }, ], [ { name: 'metrics', override: { validators: [], visibility: isAggMode, mapStateToProps: ( { controls, datasource, form_data }: ControlPanelState, controlState: ControlState, ) => ({ columns: datasource?.columns.filter(c => c.filterable) || [], savedMetrics: datasource?.metrics || [], // current active adhoc metrics selectedMetrics: form_data.metrics || (form_data.metric ? [form_data.metric] : []), datasource, externalValidationErrors: validateAggControlValues(controls, [ controls.groupby?.value, controls.percent_metrics?.value, controlState.value, ]), }), rerender: ['groupby', 'percent_metrics'], }, }, { name: 'all_columns', config: isFeatureEnabled(FeatureFlag.ENABLE_EXPLORE_DRAG_AND_DROP) ? dnd_all_columns : all_columns, }, ], [ { name: 'percent_metrics', config: { ...(isFeatureEnabled(FeatureFlag.ENABLE_EXPLORE_DRAG_AND_DROP) ? dnd_percent_metrics : percent_metrics), }, }, ], ['adhoc_filters'], [ { name: 'timeseries_limit_metric', override: { visibility: isAggMode, }, }, { name: 'order_by_cols', config: { type: 'SelectControl', label: t('Ordering'), description: t('Order results by selected columns'), multi: true, default: [], mapStateToProps: ({ datasource }) => ({ choices: datasource?.order_by_choices || [], }), visibility: isRawMode, }, }, ], isFeatureEnabled(FeatureFlag.DASHBOARD_CROSS_FILTERS) || isFeatureEnabled(FeatureFlag.DASHBOARD_NATIVE_FILTERS) ? [ { name: 'server_pagination', config: { type: 'CheckboxControl', label: t('Server pagination'), description: t( 'Enable server side pagination of results (experimental feature)', ), default: false, }, }, ] : [], [ { name: 'row_limit', override: { visibility: ({ controls }: ControlPanelsContainerProps) => !controls?.server_pagination?.value, }, }, { name: 'server_page_length', config: { type: 'SelectControl', freeForm: true, label: t('Server Page Length'), default: 10, choices: PAGE_SIZE_OPTIONS, description: t('Rows per page, 0 means no pagination'), visibility: ({ controls }: ControlPanelsContainerProps) => Boolean(controls?.server_pagination?.value), }, }, ], [ { name: 'include_time', config: { type: 'CheckboxControl', label: t('Include time'), description: t( 'Whether to include the time granularity as defined in the time section', ), default: false, visibility: isAggMode, }, }, { name: 'order_desc', config: { type: 'CheckboxControl', label: t('Sort descending'), default: true, description: t('Whether to sort descending or ascending'), visibility: isAggMode, }, }, ], [ { name: 'show_totals', config: { type: 'CheckboxControl', label: t('Show totals'), default: false, description: t( 'Show total aggregations of selected metrics. Note that row limit does not apply to the result.', ), visibility: isAggMode, }, }, ], emitFilterControl, ], }, { label: t('Options'), expanded: true, controlSetRows: [ [ { name: 'table_timestamp_format', config: { type: 'SelectControl', freeForm: true, label: t('Timestamp format'), default: smartDateFormatter.id, renderTrigger: true, clearable: false, choices: D3_TIME_FORMAT_OPTIONS, description: t('D3 time format for datetime columns'), }, }, ], [ { name: 'page_length', config: { type: 'SelectControl', freeForm: true, renderTrigger: true, label: t('Page length'), default: null, choices: PAGE_SIZE_OPTIONS, description: t('Rows per page, 0 means no pagination'), visibility: ({ controls }: ControlPanelsContainerProps) => !controls?.server_pagination?.value, }, }, null, ], [ { name: 'include_search', config: { type: 'CheckboxControl', label: t('Search box'), renderTrigger: true, default: false, description: t('Whether to include a client-side search box'), }, }, { name: 'show_cell_bars', config: { type: 'CheckboxControl', label: t('Cell bars'), renderTrigger: true, default: true, description: t( 'Whether to display a bar chart background in table columns', ), }, }, ], [ { name: 'align_pn', config: { type: 'CheckboxControl', label: t('Align +/-'), renderTrigger: true, default: false, description: t( 'Whether to align background charts with both positive and negative values at 0', ), }, }, { name: 'color_pn', config: { type: 'CheckboxControl', label: t('Color +/-'), renderTrigger: true, default: true, description: t( 'Whether to colorize numeric values by if they are positive or negative', ), }, }, ], [ { name: 'column_config', config: { type: 'ColumnConfigControl', label: t('Customize columns'), description: t('Further customize how to display each column'), renderTrigger: true, shouldMapStateToProps() { return true; }, mapStateToProps(explore, _, chart) { return { queryResponse: chart?.queriesResponse?.[0] as | ChartDataResponseResult | undefined, emitFilter: explore?.controls?.table_filter?.value, }; }, }, }, ], [ { name: 'conditional_formatting', config: { type: 'ConditionalFormattingControl', renderTrigger: true, label: t('Conditional formatting'), description: t( 'Apply conditional color formatting to numeric columns', ), shouldMapStateToProps() { return true; }, mapStateToProps(explore, _, chart) { const verboseMap = explore?.datasource?.verbose_map ?? {}; const { colnames, coltypes } = chart?.queriesResponse?.[0] ?? {}; const numericColumns = Array.isArray(colnames) && Array.isArray(coltypes) ? colnames .filter( (colname: string, index: number) => coltypes[index] === GenericDataType.NUMERIC, ) .map(colname => ({ value: colname, label: verboseMap[colname] ?? colname, })) : []; return { columnOptions: numericColumns, verboseMap, }; }, }, }, ], ], }, ], }; export default config;
superset-frontend/plugins/plugin-chart-table/src/controlPanel.tsx
1
https://github.com/apache/superset/commit/fcc8080ff3b99e2f5f5cdbd48335d7ab83aba16a
[ 0.14721037447452545, 0.005404290743172169, 0.0001642460556467995, 0.0001746809866745025, 0.02059146575629711 ]
{ "id": 3, "code_window": [ " [\n", " {\n", " name: 'groupby',\n", " override: {\n", " visibility: isAggMode,\n", " mapStateToProps: (\n", " state: ControlPanelState,\n", " controlState: ControlState,\n", " ) => {\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " resetOnHide: false,\n" ], "file_path": "superset-frontend/plugins/plugin-chart-table/src/controlPanel.tsx", "type": "add", "edit_start_line_idx": 192 }
--- title: Amazon Athena hide_title: true sidebar_position: 4 version: 1 --- ## AWS Athena ### PyAthenaJDBC [PyAthenaJDBC](https://pypi.org/project/PyAthenaJDBC/) is a Python DB 2.0 compliant wrapper for the [Amazon Athena JDBC driver](https://docs.aws.amazon.com/athena/latest/ug/connect-with-jdbc.html). The connection string for Amazon Athena is as follows: ``` awsathena+jdbc://{aws_access_key_id}:{aws_secret_access_key}@athena.{region_name}.amazonaws.com/{schema_name}?s3_staging_dir={s3_staging_dir}&... ``` Note that you'll need to escape & encode when forming the connection string like so: ``` s3://... -> s3%3A//... ``` ### PyAthena You can also use [PyAthena library](https://pypi.org/project/PyAthena/) (no Java required) with the following connection string: ``` awsathena+rest://{aws_access_key_id}:{aws_secret_access_key}@athena.{region_name}.amazonaws.com/{schema_name}?s3_staging_dir={s3_staging_dir}&... ```
docs/docs/databases/athena.mdx
0
https://github.com/apache/superset/commit/fcc8080ff3b99e2f5f5cdbd48335d7ab83aba16a
[ 0.00017098164244089276, 0.00016566991689614952, 0.00016112811863422394, 0.0001652849605306983, 0.000003676813776110066 ]
{ "id": 3, "code_window": [ " [\n", " {\n", " name: 'groupby',\n", " override: {\n", " visibility: isAggMode,\n", " mapStateToProps: (\n", " state: ControlPanelState,\n", " controlState: ControlState,\n", " ) => {\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " resetOnHide: false,\n" ], "file_path": "superset-frontend/plugins/plugin-chart-table/src/controlPanel.tsx", "type": "add", "edit_start_line_idx": 192 }
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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. """Add tables for SQL Lab state Revision ID: db4b49eb0782 Revises: 78ee127d0d1d Create Date: 2019-11-13 11:05:30.122167 """ # revision identifiers, used by Alembic. revision = "db4b49eb0782" down_revision = "78ee127d0d1d" import sqlalchemy as sa from alembic import op from sqlalchemy.dialects import mysql def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table( "tab_state", sa.Column("created_on", sa.DateTime(), nullable=True), sa.Column("changed_on", sa.DateTime(), nullable=True), sa.Column("extra_json", sa.Text(), nullable=True), sa.Column("id", sa.Integer(), nullable=False, autoincrement=True), sa.Column("user_id", sa.Integer(), nullable=True), sa.Column("label", sa.String(length=256), nullable=True), sa.Column("active", sa.Boolean(), nullable=True), sa.Column("database_id", sa.Integer(), nullable=True), sa.Column("schema", sa.String(length=256), nullable=True), sa.Column("sql", sa.Text(), nullable=True), sa.Column("query_limit", sa.Integer(), nullable=True), sa.Column("latest_query_id", sa.String(11), nullable=True), sa.Column("autorun", sa.Boolean(), nullable=False, default=False), sa.Column("template_params", sa.Text(), nullable=True), sa.Column("created_by_fk", sa.Integer(), nullable=True), sa.Column("changed_by_fk", sa.Integer(), nullable=True), sa.ForeignKeyConstraint(["changed_by_fk"], ["ab_user.id"]), sa.ForeignKeyConstraint(["created_by_fk"], ["ab_user.id"]), sa.ForeignKeyConstraint(["database_id"], ["dbs.id"]), sa.ForeignKeyConstraint(["latest_query_id"], ["query.client_id"]), sa.ForeignKeyConstraint(["user_id"], ["ab_user.id"]), sa.PrimaryKeyConstraint("id"), sqlite_autoincrement=True, ) op.create_index(op.f("ix_tab_state_id"), "tab_state", ["id"], unique=True) op.create_table( "table_schema", sa.Column("created_on", sa.DateTime(), nullable=True), sa.Column("changed_on", sa.DateTime(), nullable=True), sa.Column("extra_json", sa.Text(), nullable=True), sa.Column("id", sa.Integer(), nullable=False, autoincrement=True), sa.Column("tab_state_id", sa.Integer(), nullable=True), sa.Column("database_id", sa.Integer(), nullable=False), sa.Column("schema", sa.String(length=256), nullable=True), sa.Column("table", sa.String(length=256), nullable=True), sa.Column("description", sa.Text(), nullable=True), sa.Column("expanded", sa.Boolean(), nullable=True), sa.Column("created_by_fk", sa.Integer(), nullable=True), sa.Column("changed_by_fk", sa.Integer(), nullable=True), sa.ForeignKeyConstraint(["changed_by_fk"], ["ab_user.id"]), sa.ForeignKeyConstraint(["created_by_fk"], ["ab_user.id"]), sa.ForeignKeyConstraint(["database_id"], ["dbs.id"]), sa.ForeignKeyConstraint(["tab_state_id"], ["tab_state.id"], ondelete="CASCADE"), sa.PrimaryKeyConstraint("id"), sqlite_autoincrement=True, ) op.create_index(op.f("ix_table_schema_id"), "table_schema", ["id"], unique=True) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_index(op.f("ix_table_schema_id"), table_name="table_schema") op.drop_table("table_schema") op.drop_index(op.f("ix_tab_state_id"), table_name="tab_state") op.drop_table("tab_state") # ### end Alembic commands ###
superset/migrations/versions/db4b49eb0782_add_tables_for_sql_lab_state.py
0
https://github.com/apache/superset/commit/fcc8080ff3b99e2f5f5cdbd48335d7ab83aba16a
[ 0.0001772839023033157, 0.00017277106235269457, 0.00016575577319599688, 0.00017276147264055908, 0.000002944029347418109 ]
{ "id": 3, "code_window": [ " [\n", " {\n", " name: 'groupby',\n", " override: {\n", " visibility: isAggMode,\n", " mapStateToProps: (\n", " state: ControlPanelState,\n", " controlState: ControlState,\n", " ) => {\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " resetOnHide: false,\n" ], "file_path": "superset-frontend/plugins/plugin-chart-table/src/controlPanel.tsx", "type": "add", "edit_start_line_idx": 192 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ import { Column } from './Column'; import { Metric } from './Metric'; export enum DatasourceType { Table = 'table', Druid = 'druid', } /** * Datasource metadata. */ export interface Datasource { id: number; name: string; type: DatasourceType; columns: Column[]; metrics: Metric[]; description?: string; // key is column names (labels) columnFormats?: { [key: string]: string; }; verboseMap?: { [key: string]: string; }; } export default {};
superset-frontend/packages/superset-ui-core/src/query/types/Datasource.ts
0
https://github.com/apache/superset/commit/fcc8080ff3b99e2f5f5cdbd48335d7ab83aba16a
[ 0.0001770389499142766, 0.00017181879957206547, 0.00016553798923268914, 0.00017499476962257177, 0.000004841334884986281 ]
{ "id": 4, "code_window": [ " name: 'metrics',\n", " override: {\n", " validators: [],\n", " visibility: isAggMode,\n", " mapStateToProps: (\n", " { controls, datasource, form_data }: ControlPanelState,\n", " controlState: ControlState,\n", " ) => ({\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " resetOnHide: false,\n" ], "file_path": "superset-frontend/plugins/plugin-chart-table/src/controlPanel.tsx", "type": "add", "edit_start_line_idx": 222 }
/* eslint-disable camelcase */ /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ import React from 'react'; import { addLocaleData, ChartDataResponseResult, ensureIsArray, FeatureFlag, GenericDataType, isFeatureEnabled, QueryFormColumn, QueryMode, smartDateFormatter, t, } from '@superset-ui/core'; import { ColumnOption, ControlConfig, ControlPanelConfig, ControlPanelsContainerProps, ControlStateMapping, D3_TIME_FORMAT_OPTIONS, QueryModeLabel, sections, sharedControls, ControlPanelState, ExtraControlProps, ControlState, emitFilterControl, } from '@superset-ui/chart-controls'; import i18n from './i18n'; import { PAGE_SIZE_OPTIONS } from './consts'; addLocaleData(i18n); function getQueryMode(controls: ControlStateMapping): QueryMode { const mode = controls?.query_mode?.value; if (mode === QueryMode.aggregate || mode === QueryMode.raw) { return mode as QueryMode; } const rawColumns = controls?.all_columns?.value as | QueryFormColumn[] | undefined; const hasRawColumns = rawColumns && rawColumns.length > 0; return hasRawColumns ? QueryMode.raw : QueryMode.aggregate; } /** * Visibility check */ function isQueryMode(mode: QueryMode) { return ({ controls }: Pick<ControlPanelsContainerProps, 'controls'>) => getQueryMode(controls) === mode; } const isAggMode = isQueryMode(QueryMode.aggregate); const isRawMode = isQueryMode(QueryMode.raw); const validateAggControlValues = ( controls: ControlStateMapping, values: any[], ) => { const areControlsEmpty = values.every(val => ensureIsArray(val).length === 0); return areControlsEmpty && isAggMode({ controls }) ? [t('Group By, Metrics or Percentage Metrics must have a value')] : []; }; const queryMode: ControlConfig<'RadioButtonControl'> = { type: 'RadioButtonControl', label: t('Query mode'), default: null, options: [ [QueryMode.aggregate, QueryModeLabel[QueryMode.aggregate]], [QueryMode.raw, QueryModeLabel[QueryMode.raw]], ], mapStateToProps: ({ controls }) => ({ value: getQueryMode(controls) }), rerender: ['all_columns', 'groupby', 'metrics', 'percent_metrics'], }; const all_columns: typeof sharedControls.groupby = { type: 'SelectControl', label: t('Columns'), description: t('Columns to display'), multi: true, freeForm: true, allowAll: true, commaChoosesOption: false, default: [], optionRenderer: c => <ColumnOption showType column={c} />, valueRenderer: c => <ColumnOption column={c} />, valueKey: 'column_name', mapStateToProps: ({ datasource, controls }, controlState) => ({ options: datasource?.columns || [], queryMode: getQueryMode(controls), externalValidationErrors: isRawMode({ controls }) && ensureIsArray(controlState.value).length === 0 ? [t('must have a value')] : [], }), visibility: isRawMode, }; const dnd_all_columns: typeof sharedControls.groupby = { type: 'DndColumnSelect', label: t('Columns'), description: t('Columns to display'), default: [], mapStateToProps({ datasource, controls }, controlState) { const newState: ExtraControlProps = {}; if (datasource) { const options = datasource.columns; newState.options = Object.fromEntries( options.map(option => [option.column_name, option]), ); } newState.queryMode = getQueryMode(controls); newState.externalValidationErrors = isRawMode({ controls }) && ensureIsArray(controlState.value).length === 0 ? [t('must have a value')] : []; return newState; }, visibility: isRawMode, }; const percent_metrics: typeof sharedControls.metrics = { type: 'MetricsControl', label: t('Percentage metrics'), description: t( 'Metrics for which percentage of total are to be displayed. Calculated from only data within the row limit.', ), multi: true, visibility: isAggMode, mapStateToProps: ({ datasource, controls }, controlState) => ({ columns: datasource?.columns || [], savedMetrics: datasource?.metrics || [], datasource, datasourceType: datasource?.type, queryMode: getQueryMode(controls), externalValidationErrors: validateAggControlValues(controls, [ controls.groupby?.value, controls.metrics?.value, controlState.value, ]), }), rerender: ['groupby', 'metrics'], default: [], validators: [], }; const dnd_percent_metrics = { ...percent_metrics, type: 'DndMetricSelect', }; const config: ControlPanelConfig = { controlPanelSections: [ sections.legacyTimeseriesTime, { label: t('Query'), expanded: true, controlSetRows: [ [ { name: 'query_mode', config: queryMode, }, ], [ { name: 'groupby', override: { visibility: isAggMode, mapStateToProps: ( state: ControlPanelState, controlState: ControlState, ) => { const { controls } = state; const originalMapStateToProps = sharedControls?.groupby?.mapStateToProps; const newState = originalMapStateToProps?.(state, controlState) ?? {}; newState.externalValidationErrors = validateAggControlValues( controls, [ controls.metrics?.value, controls.percent_metrics?.value, controlState.value, ], ); return newState; }, rerender: ['metrics', 'percent_metrics'], }, }, ], [ { name: 'metrics', override: { validators: [], visibility: isAggMode, mapStateToProps: ( { controls, datasource, form_data }: ControlPanelState, controlState: ControlState, ) => ({ columns: datasource?.columns.filter(c => c.filterable) || [], savedMetrics: datasource?.metrics || [], // current active adhoc metrics selectedMetrics: form_data.metrics || (form_data.metric ? [form_data.metric] : []), datasource, externalValidationErrors: validateAggControlValues(controls, [ controls.groupby?.value, controls.percent_metrics?.value, controlState.value, ]), }), rerender: ['groupby', 'percent_metrics'], }, }, { name: 'all_columns', config: isFeatureEnabled(FeatureFlag.ENABLE_EXPLORE_DRAG_AND_DROP) ? dnd_all_columns : all_columns, }, ], [ { name: 'percent_metrics', config: { ...(isFeatureEnabled(FeatureFlag.ENABLE_EXPLORE_DRAG_AND_DROP) ? dnd_percent_metrics : percent_metrics), }, }, ], ['adhoc_filters'], [ { name: 'timeseries_limit_metric', override: { visibility: isAggMode, }, }, { name: 'order_by_cols', config: { type: 'SelectControl', label: t('Ordering'), description: t('Order results by selected columns'), multi: true, default: [], mapStateToProps: ({ datasource }) => ({ choices: datasource?.order_by_choices || [], }), visibility: isRawMode, }, }, ], isFeatureEnabled(FeatureFlag.DASHBOARD_CROSS_FILTERS) || isFeatureEnabled(FeatureFlag.DASHBOARD_NATIVE_FILTERS) ? [ { name: 'server_pagination', config: { type: 'CheckboxControl', label: t('Server pagination'), description: t( 'Enable server side pagination of results (experimental feature)', ), default: false, }, }, ] : [], [ { name: 'row_limit', override: { visibility: ({ controls }: ControlPanelsContainerProps) => !controls?.server_pagination?.value, }, }, { name: 'server_page_length', config: { type: 'SelectControl', freeForm: true, label: t('Server Page Length'), default: 10, choices: PAGE_SIZE_OPTIONS, description: t('Rows per page, 0 means no pagination'), visibility: ({ controls }: ControlPanelsContainerProps) => Boolean(controls?.server_pagination?.value), }, }, ], [ { name: 'include_time', config: { type: 'CheckboxControl', label: t('Include time'), description: t( 'Whether to include the time granularity as defined in the time section', ), default: false, visibility: isAggMode, }, }, { name: 'order_desc', config: { type: 'CheckboxControl', label: t('Sort descending'), default: true, description: t('Whether to sort descending or ascending'), visibility: isAggMode, }, }, ], [ { name: 'show_totals', config: { type: 'CheckboxControl', label: t('Show totals'), default: false, description: t( 'Show total aggregations of selected metrics. Note that row limit does not apply to the result.', ), visibility: isAggMode, }, }, ], emitFilterControl, ], }, { label: t('Options'), expanded: true, controlSetRows: [ [ { name: 'table_timestamp_format', config: { type: 'SelectControl', freeForm: true, label: t('Timestamp format'), default: smartDateFormatter.id, renderTrigger: true, clearable: false, choices: D3_TIME_FORMAT_OPTIONS, description: t('D3 time format for datetime columns'), }, }, ], [ { name: 'page_length', config: { type: 'SelectControl', freeForm: true, renderTrigger: true, label: t('Page length'), default: null, choices: PAGE_SIZE_OPTIONS, description: t('Rows per page, 0 means no pagination'), visibility: ({ controls }: ControlPanelsContainerProps) => !controls?.server_pagination?.value, }, }, null, ], [ { name: 'include_search', config: { type: 'CheckboxControl', label: t('Search box'), renderTrigger: true, default: false, description: t('Whether to include a client-side search box'), }, }, { name: 'show_cell_bars', config: { type: 'CheckboxControl', label: t('Cell bars'), renderTrigger: true, default: true, description: t( 'Whether to display a bar chart background in table columns', ), }, }, ], [ { name: 'align_pn', config: { type: 'CheckboxControl', label: t('Align +/-'), renderTrigger: true, default: false, description: t( 'Whether to align background charts with both positive and negative values at 0', ), }, }, { name: 'color_pn', config: { type: 'CheckboxControl', label: t('Color +/-'), renderTrigger: true, default: true, description: t( 'Whether to colorize numeric values by if they are positive or negative', ), }, }, ], [ { name: 'column_config', config: { type: 'ColumnConfigControl', label: t('Customize columns'), description: t('Further customize how to display each column'), renderTrigger: true, shouldMapStateToProps() { return true; }, mapStateToProps(explore, _, chart) { return { queryResponse: chart?.queriesResponse?.[0] as | ChartDataResponseResult | undefined, emitFilter: explore?.controls?.table_filter?.value, }; }, }, }, ], [ { name: 'conditional_formatting', config: { type: 'ConditionalFormattingControl', renderTrigger: true, label: t('Conditional formatting'), description: t( 'Apply conditional color formatting to numeric columns', ), shouldMapStateToProps() { return true; }, mapStateToProps(explore, _, chart) { const verboseMap = explore?.datasource?.verbose_map ?? {}; const { colnames, coltypes } = chart?.queriesResponse?.[0] ?? {}; const numericColumns = Array.isArray(colnames) && Array.isArray(coltypes) ? colnames .filter( (colname: string, index: number) => coltypes[index] === GenericDataType.NUMERIC, ) .map(colname => ({ value: colname, label: verboseMap[colname] ?? colname, })) : []; return { columnOptions: numericColumns, verboseMap, }; }, }, }, ], ], }, ], }; export default config;
superset-frontend/plugins/plugin-chart-table/src/controlPanel.tsx
1
https://github.com/apache/superset/commit/fcc8080ff3b99e2f5f5cdbd48335d7ab83aba16a
[ 0.9950736165046692, 0.029962945729494095, 0.00016561913071200252, 0.0002572396770119667, 0.14190171658992767 ]
{ "id": 4, "code_window": [ " name: 'metrics',\n", " override: {\n", " validators: [],\n", " visibility: isAggMode,\n", " mapStateToProps: (\n", " { controls, datasource, form_data }: ControlPanelState,\n", " controlState: ControlState,\n", " ) => ({\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " resetOnHide: false,\n" ], "file_path": "superset-frontend/plugins/plugin-chart-table/src/controlPanel.tsx", "type": "add", "edit_start_line_idx": 222 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ import userEvent from '@testing-library/user-event'; import { AppSection } from '@superset-ui/core'; import React from 'react'; import { render, screen } from 'spec/helpers/testing-library'; import { NULL_STRING } from 'src/utils/common'; import SelectFilterPlugin from './SelectFilterPlugin'; import transformProps from './transformProps'; const selectMultipleProps = { formData: { sortAscending: true, multiSelect: true, enableEmptyFilter: true, defaultToFirstItem: false, inverseSelection: false, searchAllOptions: false, datasource: '3__table', groupby: ['gender'], adhocFilters: [], extraFilters: [], extraFormData: {}, granularitySqla: 'ds', metrics: ['count'], rowLimit: 1000, showSearch: true, defaultValue: ['boy'], timeRangeEndpoints: ['inclusive', 'exclusive'], urlParams: {}, vizType: 'filter_select', inputRef: { current: null }, }, height: 20, hooks: {}, ownState: {}, filterState: { value: ['boy'] }, queriesData: [ { rowcount: 2, colnames: ['gender'], coltypes: [1], data: [{ gender: 'boy' }, { gender: 'girl' }, { gender: null }], applied_filters: [{ column: 'gender' }], rejected_filters: [], }, ], width: 220, behaviors: ['NATIVE_FILTER'], isRefreshing: false, appSection: AppSection.DASHBOARD, }; describe('SelectFilterPlugin', () => { const setDataMask = jest.fn(); const getWrapper = (props = {}) => render( // @ts-ignore <SelectFilterPlugin // @ts-ignore {...transformProps({ ...selectMultipleProps, formData: { ...selectMultipleProps.formData, ...props }, })} setDataMask={setDataMask} />, ); beforeEach(() => { jest.clearAllMocks(); }); it('Add multiple values with first render', () => { getWrapper(); expect(setDataMask).toHaveBeenCalledWith({ extraFormData: {}, filterState: { value: ['boy'], }, }); expect(setDataMask).toHaveBeenCalledWith({ __cache: { value: ['boy'], }, extraFormData: { filters: [ { col: 'gender', op: 'IN', val: ['boy'], }, ], }, filterState: { label: 'boy', value: ['boy'], }, }); userEvent.click(screen.getByRole('combobox')); userEvent.click(screen.getByTitle('girl')); expect(setDataMask).toHaveBeenCalledWith({ __cache: { value: ['boy'], }, extraFormData: { filters: [ { col: 'gender', op: 'IN', val: ['boy', 'girl'], }, ], }, filterState: { label: 'boy, girl', value: ['boy', 'girl'], }, }); }); it('Remove multiple values when required', () => { getWrapper(); userEvent.click(document.querySelector('[data-icon="close"]')!); expect(setDataMask).toHaveBeenCalledWith({ __cache: { value: ['boy'], }, extraFormData: { adhoc_filters: [ { clause: 'WHERE', expressionType: 'SQL', sqlExpression: '1 = 0', }, ], }, filterState: { label: undefined, value: null, }, }); }); it('Remove multiple values when not required', () => { getWrapper({ enableEmptyFilter: false }); userEvent.click(document.querySelector('[data-icon="close"]')!); expect(setDataMask).toHaveBeenCalledWith({ __cache: { value: ['boy'], }, extraFormData: {}, filterState: { label: undefined, value: null, }, }); }); it('Select single values with inverse', () => { getWrapper({ multiSelect: false, inverseSelection: true }); userEvent.click(screen.getByRole('combobox')); userEvent.click(screen.getByTitle('girl')); expect(setDataMask).toHaveBeenCalledWith({ __cache: { value: ['boy'], }, extraFormData: { filters: [ { col: 'gender', op: 'NOT IN', val: ['girl'], }, ], }, filterState: { label: 'girl (excluded)', value: ['girl'], }, }); }); it('Select single null (empty) value', () => { getWrapper(); userEvent.click(screen.getByRole('combobox')); userEvent.click(screen.getByTitle(NULL_STRING)); expect(setDataMask).toHaveBeenLastCalledWith({ __cache: { value: ['boy'], }, extraFormData: { filters: [ { col: 'gender', op: 'IN', val: ['boy', null], }, ], }, filterState: { label: `boy, ${NULL_STRING}`, value: ['boy', null], }, }); }); it('Add ownState with column types when search all options', () => { getWrapper({ searchAllOptions: true, multiSelect: false }); userEvent.click(screen.getByRole('combobox')); userEvent.click(screen.getByTitle('girl')); expect(setDataMask).toHaveBeenCalledWith({ __cache: { value: ['boy'], }, extraFormData: { filters: [ { col: 'gender', op: 'IN', val: ['girl'], }, ], }, filterState: { label: 'girl', value: ['girl'], }, ownState: { coltypeMap: { gender: 1, }, search: null, }, }); }); });
superset-frontend/src/filters/components/Select/SelectFilterPlugin.test.tsx
0
https://github.com/apache/superset/commit/fcc8080ff3b99e2f5f5cdbd48335d7ab83aba16a
[ 0.00027408645837567747, 0.00017401017248630524, 0.0001647010212764144, 0.00017012711032293737, 0.000020206662156851962 ]
{ "id": 4, "code_window": [ " name: 'metrics',\n", " override: {\n", " validators: [],\n", " visibility: isAggMode,\n", " mapStateToProps: (\n", " { controls, datasource, form_data }: ControlPanelState,\n", " controlState: ControlState,\n", " ) => ({\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " resetOnHide: false,\n" ], "file_path": "superset-frontend/plugins/plugin-chart-table/src/controlPanel.tsx", "type": "add", "edit_start_line_idx": 222 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ /* eslint-disable no-param-reassign */ /* eslint-disable react/sort-prop-types */ import d3 from 'd3'; import PropTypes from 'prop-types'; import { sankey as d3Sankey } from 'd3-sankey'; import { getNumberFormatter, NumberFormats, CategoricalColorNamespace, } from '@superset-ui/core'; import { getOverlappingElements } from './utils'; const propTypes = { data: PropTypes.arrayOf( PropTypes.shape({ source: PropTypes.string, target: PropTypes.string, value: PropTypes.number, }), ), width: PropTypes.number, height: PropTypes.number, colorScheme: PropTypes.string, }; const formatNumber = getNumberFormatter(NumberFormats.FLOAT); function Sankey(element, props) { const { data, width, height, colorScheme, sliceId } = props; const div = d3.select(element); div.classed(`superset-legacy-chart-sankey`, true); const margin = { top: 5, right: 5, bottom: 5, left: 5, }; const innerWidth = width - margin.left - margin.right; const innerHeight = height - margin.top - margin.bottom; div.selectAll('*').remove(); const tooltip = div .append('div') .attr('class', 'sankey-tooltip') .style('opacity', 0); const svg = div .append('svg') .attr('width', innerWidth + margin.left + margin.right) .attr('height', innerHeight + margin.top + margin.bottom) .append('g') .attr('transform', `translate(${margin.left},${margin.top})`); const colorFn = CategoricalColorNamespace.getScale(colorScheme); const sankey = d3Sankey() .nodeWidth(15) .nodePadding(10) .size([innerWidth, innerHeight]); const path = sankey.link(); let nodes = {}; // Compute the distinct nodes from the links. const links = data.map(row => { const link = { ...row }; link.source = nodes[link.source] || (nodes[link.source] = { name: link.source }); link.target = nodes[link.target] || (nodes[link.target] = { name: link.target }); link.value = Number(link.value); return link; }); nodes = d3.values(nodes); sankey.nodes(nodes).links(links).layout(32); function getTooltipHtml(d) { let html; if (d.sourceLinks) { // is node html = `${d.name} Value: <span class='emph'>${formatNumber( d.value, )}</span>`; } else { const val = formatNumber(d.value); const sourcePercent = d3.round((d.value / d.source.value) * 100, 1); const targetPercent = d3.round((d.value / d.target.value) * 100, 1); html = [ "<div class=''>Path Value: <span class='emph'>", val, '</span></div>', "<div class='percents'>", "<span class='emph'>", Number.isFinite(sourcePercent) ? sourcePercent : '100', '%</span> of ', d.source.name, '<br/>', `<span class='emph'>${ Number.isFinite(targetPercent) ? targetPercent : '--' }%</span> of `, d.target.name, '</div>', ].join(''); } return html; } function onmouseover(d) { tooltip .html(() => getTooltipHtml(d)) .transition() .duration(200); const { height: tooltipHeight, width: tooltipWidth } = tooltip .node() .getBoundingClientRect(); tooltip .style( 'left', `${Math.min(d3.event.offsetX + 10, width - tooltipWidth)}px`, ) .style( 'top', `${Math.min(d3.event.offsetY + 10, height - tooltipHeight)}px`, ) .style('position', 'absolute') .style('opacity', 0.95); } function onmouseout() { tooltip.transition().duration(100).style('opacity', 0); } const link = svg .append('g') .selectAll('.link') .data(links) .enter() .append('path') .attr('class', 'link') .attr('d', path) .style('stroke-width', d => Math.max(1, d.dy)) .sort((a, b) => b.dy - a.dy) .on('mouseover', onmouseover) .on('mouseout', onmouseout); function dragmove(d) { d3.select(this).attr( 'transform', `translate(${d.x},${(d.y = Math.max( 0, Math.min(height - d.dy, d3.event.y), ))})`, ); sankey.relayout(); link.attr('d', path); } function checkVisibility() { const elements = div.selectAll('.node')[0] ?? []; const overlappingElements = getOverlappingElements(elements); elements.forEach(el => { const text = el.getElementsByTagName('text')[0]; if (text) { if (overlappingElements.includes(el)) { text.classList.add('opacity-0'); } else { text.classList.remove('opacity-0'); } } }); } const node = svg .append('g') .selectAll('.node') .data(nodes) .enter() .append('g') .attr('class', 'node') .attr('transform', d => `translate(${d.x},${d.y})`) .call( d3.behavior .drag() .origin(d => d) .on('dragstart', function dragStart() { this.parentNode.append(this); }) .on('drag', dragmove) .on('dragend', checkVisibility), ); const minRectHeight = 5; node .append('rect') .attr('height', d => (d.dy > minRectHeight ? d.dy : minRectHeight)) .attr('width', sankey.nodeWidth()) .style('fill', d => { const name = d.name || 'N/A'; d.color = colorFn(name, sliceId); return d.color; }) .style('stroke', d => d3.rgb(d.color).darker(2)) .on('mouseover', onmouseover) .on('mouseout', onmouseout); node .append('text') .attr('x', -6) .attr('y', d => d.dy / 2) .attr('dy', '.35em') .attr('text-anchor', 'end') .attr('transform', null) .text(d => d.name) .attr('class', 'opacity-0') .filter(d => d.x < innerWidth / 2) .attr('x', 6 + sankey.nodeWidth()) .attr('text-anchor', 'start'); checkVisibility(); } Sankey.displayName = 'Sankey'; Sankey.propTypes = propTypes; export default Sankey;
superset-frontend/plugins/legacy-plugin-chart-sankey/src/Sankey.js
0
https://github.com/apache/superset/commit/fcc8080ff3b99e2f5f5cdbd48335d7ab83aba16a
[ 0.00017483382544014603, 0.00017131242202594876, 0.0001664107694523409, 0.0001715957623673603, 0.000001878991838566435 ]
{ "id": 4, "code_window": [ " name: 'metrics',\n", " override: {\n", " validators: [],\n", " visibility: isAggMode,\n", " mapStateToProps: (\n", " { controls, datasource, form_data }: ControlPanelState,\n", " controlState: ControlState,\n", " ) => ({\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " resetOnHide: false,\n" ], "file_path": "superset-frontend/plugins/plugin-chart-table/src/controlPanel.tsx", "type": "add", "edit_start_line_idx": 222 }
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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. """ Superset utilities for pandas.DataFrame. """ import logging from typing import Any, Dict, List import pandas as pd from superset.utils.core import JS_MAX_INTEGER logger = logging.getLogger(__name__) def _convert_big_integers(val: Any) -> Any: """ Cast integers larger than ``JS_MAX_INTEGER`` to strings. :param val: the value to process :returns: the same value but recast as a string if it was an integer over ``JS_MAX_INTEGER`` """ return str(val) if isinstance(val, int) and abs(val) > JS_MAX_INTEGER else val def df_to_records(dframe: pd.DataFrame) -> List[Dict[str, Any]]: """ Convert a DataFrame to a set of records. :param dframe: the DataFrame to convert :returns: a list of dictionaries reflecting each single row of the DataFrame """ if not dframe.columns.is_unique: logger.warning( "DataFrame columns are not unique, some columns will be omitted." ) columns = dframe.columns return list( dict(zip(columns, map(_convert_big_integers, row))) for row in zip(*[dframe[col] for col in columns]) )
superset/dataframe.py
0
https://github.com/apache/superset/commit/fcc8080ff3b99e2f5f5cdbd48335d7ab83aba16a
[ 0.00017509091412648559, 0.00017058361845556647, 0.00016565751866437495, 0.00017072155606001616, 0.000003888749233738054 ]
{ "id": 5, "code_window": [ " [\n", " {\n", " name: 'timeseries_limit_metric',\n", " override: {\n", " visibility: isAggMode,\n", " },\n", " },\n", " {\n", " name: 'order_by_cols',\n", " config: {\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " resetOnHide: false,\n" ], "file_path": "superset-frontend/plugins/plugin-chart-table/src/controlPanel.tsx", "type": "add", "edit_start_line_idx": 265 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ import React, { ReactNode, useCallback, useState, useEffect } from 'react'; import { isEqual } from 'lodash'; import { ControlType, ControlComponentProps as BaseControlComponentProps, } from '@superset-ui/chart-controls'; import { styled, JsonValue, QueryFormData } from '@superset-ui/core'; import { usePrevious } from 'src/hooks/usePrevious'; import ErrorBoundary from 'src/components/ErrorBoundary'; import { ExploreActions } from 'src/explore/actions/exploreActions'; import controlMap from './controls'; export type ControlProps = { // the actual action dispatcher (via bindActionCreators) has identical // signature to the original action factory. actions: Partial<ExploreActions> & Pick<ExploreActions, 'setControlValue'>; type: ControlType; label?: ReactNode; name: string; description?: ReactNode; tooltipOnClick?: () => ReactNode; places?: number; rightNode?: ReactNode; formData?: QueryFormData | null; value?: JsonValue; validationErrors?: any[]; hidden?: boolean; renderTrigger?: boolean; default?: JsonValue; isVisible?: boolean; }; /** * */ export type ControlComponentProps<ValueType extends JsonValue = JsonValue> = Omit<ControlProps, 'value'> & BaseControlComponentProps<ValueType>; const StyledControl = styled.div` padding-bottom: ${({ theme }) => theme.gridUnit * 4}px; `; export default function Control(props: ControlProps) { const { actions: { setControlValue }, name, type, hidden, isVisible, } = props; const [hovered, setHovered] = useState(false); const wasVisible = usePrevious(isVisible); const onChange = useCallback( (value: any, errors: any[]) => setControlValue(name, value, errors), [name, setControlValue], ); useEffect(() => { if ( wasVisible === true && isVisible === false && props.default !== undefined && !isEqual(props.value, props.default) ) { // reset control value if setting to invisible setControlValue?.(name, props.default); } }, [ name, wasVisible, isVisible, setControlValue, props.value, props.default, ]); if (!type || isVisible === false) return null; const ControlComponent = typeof type === 'string' ? controlMap[type] : type; if (!ControlComponent) { // eslint-disable-next-line no-console console.warn(`Unknown controlType: ${type}`); return null; } return ( <StyledControl className="Control" data-test={name} style={hidden ? { display: 'none' } : undefined} onMouseEnter={() => setHovered(true)} onMouseLeave={() => setHovered(false)} > <ErrorBoundary> <ControlComponent onChange={onChange} hovered={hovered} {...props} /> </ErrorBoundary> </StyledControl> ); }
superset-frontend/src/explore/components/Control.tsx
1
https://github.com/apache/superset/commit/fcc8080ff3b99e2f5f5cdbd48335d7ab83aba16a
[ 0.00017547415336593986, 0.00017092873167712241, 0.00016403381596319377, 0.00017142768774647266, 0.0000032264481433230685 ]
{ "id": 5, "code_window": [ " [\n", " {\n", " name: 'timeseries_limit_metric',\n", " override: {\n", " visibility: isAggMode,\n", " },\n", " },\n", " {\n", " name: 'order_by_cols',\n", " config: {\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " resetOnHide: false,\n" ], "file_path": "superset-frontend/plugins/plugin-chart-table/src/controlPanel.tsx", "type": "add", "edit_start_line_idx": 265 }
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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. import logging from logging.config import fileConfig from typing import List from alembic import context from alembic.operations.ops import MigrationScript from alembic.runtime.migration import MigrationContext from flask import current_app from flask_appbuilder import Base from sqlalchemy import engine_from_config, pool # this is the Alembic Config object, which provides # access to the values within the .ini file in use. config = context.config # Interpret the config file for Python logging. # This line sets up loggers basically. if not current_app.config["ALEMBIC_SKIP_LOG_CONFIG"]: # Skip loading logger config if the user has this config set fileConfig(config.config_file_name) logger = logging.getLogger("alembic.env") DATABASE_URI = current_app.config["SQLALCHEMY_DATABASE_URI"] if "sqlite" in DATABASE_URI: logger.warning( "SQLite Database support for metadata databases will \ be removed in a future version of Superset." ) config.set_main_option("sqlalchemy.url", DATABASE_URI) target_metadata = Base.metadata # pylint: disable=no-member # other values from the config, defined by the needs of env.py, # can be acquired: # my_important_option = config.get_main_option("my_important_option") # ... etc. def run_migrations_offline() -> None: """Run migrations in 'offline' mode. This configures the context with just a URL and not an Engine, though an Engine is acceptable here as well. By skipping the Engine creation we don't even need a DBAPI to be available. Calls to context.execute() here emit the given string to the script output. """ url = config.get_main_option("sqlalchemy.url") context.configure(url=url) with context.begin_transaction(): context.run_migrations() def run_migrations_online() -> None: """Run migrations in 'online' mode. In this scenario we need to create an Engine and associate a connection with the context. """ # this callback is used to prevent an auto-migration from being generated # when there are no changes to the schema # reference: https://alembic.sqlalchemy.org/en/latest/cookbook.html def process_revision_directives( # pylint: disable=redefined-outer-name, unused-argument context: MigrationContext, revision: str, directives: List[MigrationScript] ) -> None: if getattr(config.cmd_opts, "autogenerate", False): script = directives[0] if script.upgrade_ops.is_empty(): directives[:] = [] logger.info("No changes in schema detected.") engine = engine_from_config( config.get_section(config.config_ini_section), prefix="sqlalchemy.", poolclass=pool.NullPool, ) connection = engine.connect() kwargs = {} if engine.name in ("sqlite", "mysql"): kwargs = {"transaction_per_migration": True, "transactional_ddl": True} configure_args = current_app.extensions["migrate"].configure_args if configure_args: kwargs.update(configure_args) context.configure( connection=connection, target_metadata=target_metadata, # compare_type=True, process_revision_directives=process_revision_directives, **kwargs ) try: with context.begin_transaction(): context.run_migrations() finally: connection.close() if context.is_offline_mode(): run_migrations_offline() else: run_migrations_online()
superset/migrations/env.py
0
https://github.com/apache/superset/commit/fcc8080ff3b99e2f5f5cdbd48335d7ab83aba16a
[ 0.0008659958257339895, 0.00025699366233311594, 0.00016507567488588393, 0.00017438280337955803, 0.0001885667152237147 ]
{ "id": 5, "code_window": [ " [\n", " {\n", " name: 'timeseries_limit_metric',\n", " override: {\n", " visibility: isAggMode,\n", " },\n", " },\n", " {\n", " name: 'order_by_cols',\n", " config: {\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " resetOnHide: false,\n" ], "file_path": "superset-frontend/plugins/plugin-chart-table/src/controlPanel.tsx", "type": "add", "edit_start_line_idx": 265 }
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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. from datetime import datetime from typing import Any, Dict, Optional, TYPE_CHECKING from superset.db_engine_specs.base import BaseEngineSpec from superset.utils import core as utils if TYPE_CHECKING: from superset.connectors.sqla.models import TableColumn class RocksetEngineSpec(BaseEngineSpec): engine = "rockset" engine_name = "Rockset" _time_grain_expressions = { None: "{col}", "PT1S": "DATE_TRUNC('second', {col})", "PT1M": "DATE_TRUNC('minute', {col})", "PT1H": "DATE_TRUNC('hour', {col})", "P1D": "DATE_TRUNC('day', {col})", "P1W": "DATE_TRUNC('week', {col})", "P1M": "DATE_TRUNC('month', {col})", "P3M": "DATE_TRUNC('quarter', {col})", "P1Y": "DATE_TRUNC('year', {col})", } @classmethod def epoch_to_dttm(cls) -> str: return "{col} * 1000" @classmethod def epoch_ms_to_dttm(cls) -> str: return "{col}" @classmethod def convert_dttm( cls, target_type: str, dttm: datetime, db_extra: Optional[Dict[str, Any]] = None ) -> Optional[str]: tt = target_type.upper() if tt == utils.TemporalType.DATE: return f"DATE '{dttm.date().isoformat()}'" if tt == utils.TemporalType.DATETIME: dttm_formatted = dttm.isoformat(sep=" ", timespec="microseconds") return f"""DATETIME '{dttm_formatted}'""" if tt == utils.TemporalType.TIMESTAMP: dttm_formatted = dttm.isoformat(timespec="microseconds") return f"""TIMESTAMP '{dttm_formatted}'""" return None @classmethod def alter_new_orm_column(cls, orm_col: "TableColumn") -> None: if orm_col.type == "TIMESTAMP": orm_col.python_date_format = "epoch_ms"
superset/db_engine_specs/rockset.py
0
https://github.com/apache/superset/commit/fcc8080ff3b99e2f5f5cdbd48335d7ab83aba16a
[ 0.00021278140775393695, 0.00017670780653133988, 0.00016766808403190225, 0.0001712032244540751, 0.000013955807844467927 ]
{ "id": 5, "code_window": [ " [\n", " {\n", " name: 'timeseries_limit_metric',\n", " override: {\n", " visibility: isAggMode,\n", " },\n", " },\n", " {\n", " name: 'order_by_cols',\n", " config: {\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " resetOnHide: false,\n" ], "file_path": "superset-frontend/plugins/plugin-chart-table/src/controlPanel.tsx", "type": "add", "edit_start_line_idx": 265 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ /* eslint-disable react/sort-prop-types */ import d3 from 'd3'; import PropTypes from 'prop-types'; import { getSequentialSchemeRegistry } from '@superset-ui/core'; import parcoords from './vendor/parcoords/d3.parcoords'; import divgrid from './vendor/parcoords/divgrid'; const propTypes = { // Standard tabular data [{ fieldName1: value1, fieldName2: value2 }] data: PropTypes.arrayOf(PropTypes.object), width: PropTypes.number, height: PropTypes.number, colorMetric: PropTypes.string, includeSeries: PropTypes.bool, linearColorScheme: PropTypes.string, metrics: PropTypes.arrayOf(PropTypes.string), series: PropTypes.string, showDatatable: PropTypes.bool, }; function ParallelCoordinates(element, props) { const { data, width, height, colorMetric, includeSeries, linearColorScheme, metrics, series, showDatatable, } = props; const cols = includeSeries ? [series].concat(metrics) : metrics; const ttypes = {}; ttypes[series] = 'string'; metrics.forEach(v => { ttypes[v] = 'number'; }); const colorScale = colorMetric ? getSequentialSchemeRegistry() .get(linearColorScheme) .createLinearScale(d3.extent(data, d => d[colorMetric])) : () => 'grey'; const color = d => colorScale(d[colorMetric]); const container = d3 .select(element) .classed('superset-legacy-chart-parallel-coordinates', true); container.selectAll('*').remove(); const effHeight = showDatatable ? height / 2 : height; const div = container .append('div') .style('height', `${effHeight}px`) .classed('parcoords', true); const chart = parcoords()(div.node()) .width(width) .color(color) .alpha(0.5) .composite('darken') .height(effHeight) .data(data) .dimensions(cols) .types(ttypes) .render() .createAxes() .shadows() .reorderable() .brushMode('1D-axes'); if (showDatatable) { // create data table, row hover highlighting const grid = divgrid(); container .append('div') .style('height', `${effHeight}px`) .datum(data) .call(grid) .classed('parcoords grid', true) .selectAll('.row') .on({ mouseover(d) { chart.highlight([d]); }, mouseout: chart.unhighlight, }); // update data table on brush event chart.on('brush', d => { d3.select('.grid') .datum(d) .call(grid) .selectAll('.row') .on({ mouseover(dd) { chart.highlight([dd]); }, mouseout: chart.unhighlight, }); }); } } ParallelCoordinates.displayName = 'ParallelCoordinates'; ParallelCoordinates.propTypes = propTypes; export default ParallelCoordinates;
superset-frontend/plugins/legacy-plugin-chart-parallel-coordinates/src/ParallelCoordinates.js
0
https://github.com/apache/superset/commit/fcc8080ff3b99e2f5f5cdbd48335d7ab83aba16a
[ 0.00017612168448977172, 0.00017273795674555004, 0.00016920958296395838, 0.00017315306467935443, 0.0000021782379917567596 ]
{ "id": 6, "code_window": [ " default: [],\n", " mapStateToProps: ({ datasource }) => ({\n", " choices: datasource?.order_by_choices || [],\n", " }),\n", " visibility: isRawMode,\n", " },\n", " },\n", " ],\n", " isFeatureEnabled(FeatureFlag.DASHBOARD_CROSS_FILTERS) ||\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " resetOnHide: false,\n" ], "file_path": "superset-frontend/plugins/plugin-chart-table/src/controlPanel.tsx", "type": "add", "edit_start_line_idx": 279 }
/* eslint-disable camelcase */ /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ import React from 'react'; import { addLocaleData, ChartDataResponseResult, ensureIsArray, FeatureFlag, GenericDataType, isFeatureEnabled, QueryFormColumn, QueryMode, smartDateFormatter, t, } from '@superset-ui/core'; import { ColumnOption, ControlConfig, ControlPanelConfig, ControlPanelsContainerProps, ControlStateMapping, D3_TIME_FORMAT_OPTIONS, QueryModeLabel, sections, sharedControls, ControlPanelState, ExtraControlProps, ControlState, emitFilterControl, } from '@superset-ui/chart-controls'; import i18n from './i18n'; import { PAGE_SIZE_OPTIONS } from './consts'; addLocaleData(i18n); function getQueryMode(controls: ControlStateMapping): QueryMode { const mode = controls?.query_mode?.value; if (mode === QueryMode.aggregate || mode === QueryMode.raw) { return mode as QueryMode; } const rawColumns = controls?.all_columns?.value as | QueryFormColumn[] | undefined; const hasRawColumns = rawColumns && rawColumns.length > 0; return hasRawColumns ? QueryMode.raw : QueryMode.aggregate; } /** * Visibility check */ function isQueryMode(mode: QueryMode) { return ({ controls }: Pick<ControlPanelsContainerProps, 'controls'>) => getQueryMode(controls) === mode; } const isAggMode = isQueryMode(QueryMode.aggregate); const isRawMode = isQueryMode(QueryMode.raw); const validateAggControlValues = ( controls: ControlStateMapping, values: any[], ) => { const areControlsEmpty = values.every(val => ensureIsArray(val).length === 0); return areControlsEmpty && isAggMode({ controls }) ? [t('Group By, Metrics or Percentage Metrics must have a value')] : []; }; const queryMode: ControlConfig<'RadioButtonControl'> = { type: 'RadioButtonControl', label: t('Query mode'), default: null, options: [ [QueryMode.aggregate, QueryModeLabel[QueryMode.aggregate]], [QueryMode.raw, QueryModeLabel[QueryMode.raw]], ], mapStateToProps: ({ controls }) => ({ value: getQueryMode(controls) }), rerender: ['all_columns', 'groupby', 'metrics', 'percent_metrics'], }; const all_columns: typeof sharedControls.groupby = { type: 'SelectControl', label: t('Columns'), description: t('Columns to display'), multi: true, freeForm: true, allowAll: true, commaChoosesOption: false, default: [], optionRenderer: c => <ColumnOption showType column={c} />, valueRenderer: c => <ColumnOption column={c} />, valueKey: 'column_name', mapStateToProps: ({ datasource, controls }, controlState) => ({ options: datasource?.columns || [], queryMode: getQueryMode(controls), externalValidationErrors: isRawMode({ controls }) && ensureIsArray(controlState.value).length === 0 ? [t('must have a value')] : [], }), visibility: isRawMode, }; const dnd_all_columns: typeof sharedControls.groupby = { type: 'DndColumnSelect', label: t('Columns'), description: t('Columns to display'), default: [], mapStateToProps({ datasource, controls }, controlState) { const newState: ExtraControlProps = {}; if (datasource) { const options = datasource.columns; newState.options = Object.fromEntries( options.map(option => [option.column_name, option]), ); } newState.queryMode = getQueryMode(controls); newState.externalValidationErrors = isRawMode({ controls }) && ensureIsArray(controlState.value).length === 0 ? [t('must have a value')] : []; return newState; }, visibility: isRawMode, }; const percent_metrics: typeof sharedControls.metrics = { type: 'MetricsControl', label: t('Percentage metrics'), description: t( 'Metrics for which percentage of total are to be displayed. Calculated from only data within the row limit.', ), multi: true, visibility: isAggMode, mapStateToProps: ({ datasource, controls }, controlState) => ({ columns: datasource?.columns || [], savedMetrics: datasource?.metrics || [], datasource, datasourceType: datasource?.type, queryMode: getQueryMode(controls), externalValidationErrors: validateAggControlValues(controls, [ controls.groupby?.value, controls.metrics?.value, controlState.value, ]), }), rerender: ['groupby', 'metrics'], default: [], validators: [], }; const dnd_percent_metrics = { ...percent_metrics, type: 'DndMetricSelect', }; const config: ControlPanelConfig = { controlPanelSections: [ sections.legacyTimeseriesTime, { label: t('Query'), expanded: true, controlSetRows: [ [ { name: 'query_mode', config: queryMode, }, ], [ { name: 'groupby', override: { visibility: isAggMode, mapStateToProps: ( state: ControlPanelState, controlState: ControlState, ) => { const { controls } = state; const originalMapStateToProps = sharedControls?.groupby?.mapStateToProps; const newState = originalMapStateToProps?.(state, controlState) ?? {}; newState.externalValidationErrors = validateAggControlValues( controls, [ controls.metrics?.value, controls.percent_metrics?.value, controlState.value, ], ); return newState; }, rerender: ['metrics', 'percent_metrics'], }, }, ], [ { name: 'metrics', override: { validators: [], visibility: isAggMode, mapStateToProps: ( { controls, datasource, form_data }: ControlPanelState, controlState: ControlState, ) => ({ columns: datasource?.columns.filter(c => c.filterable) || [], savedMetrics: datasource?.metrics || [], // current active adhoc metrics selectedMetrics: form_data.metrics || (form_data.metric ? [form_data.metric] : []), datasource, externalValidationErrors: validateAggControlValues(controls, [ controls.groupby?.value, controls.percent_metrics?.value, controlState.value, ]), }), rerender: ['groupby', 'percent_metrics'], }, }, { name: 'all_columns', config: isFeatureEnabled(FeatureFlag.ENABLE_EXPLORE_DRAG_AND_DROP) ? dnd_all_columns : all_columns, }, ], [ { name: 'percent_metrics', config: { ...(isFeatureEnabled(FeatureFlag.ENABLE_EXPLORE_DRAG_AND_DROP) ? dnd_percent_metrics : percent_metrics), }, }, ], ['adhoc_filters'], [ { name: 'timeseries_limit_metric', override: { visibility: isAggMode, }, }, { name: 'order_by_cols', config: { type: 'SelectControl', label: t('Ordering'), description: t('Order results by selected columns'), multi: true, default: [], mapStateToProps: ({ datasource }) => ({ choices: datasource?.order_by_choices || [], }), visibility: isRawMode, }, }, ], isFeatureEnabled(FeatureFlag.DASHBOARD_CROSS_FILTERS) || isFeatureEnabled(FeatureFlag.DASHBOARD_NATIVE_FILTERS) ? [ { name: 'server_pagination', config: { type: 'CheckboxControl', label: t('Server pagination'), description: t( 'Enable server side pagination of results (experimental feature)', ), default: false, }, }, ] : [], [ { name: 'row_limit', override: { visibility: ({ controls }: ControlPanelsContainerProps) => !controls?.server_pagination?.value, }, }, { name: 'server_page_length', config: { type: 'SelectControl', freeForm: true, label: t('Server Page Length'), default: 10, choices: PAGE_SIZE_OPTIONS, description: t('Rows per page, 0 means no pagination'), visibility: ({ controls }: ControlPanelsContainerProps) => Boolean(controls?.server_pagination?.value), }, }, ], [ { name: 'include_time', config: { type: 'CheckboxControl', label: t('Include time'), description: t( 'Whether to include the time granularity as defined in the time section', ), default: false, visibility: isAggMode, }, }, { name: 'order_desc', config: { type: 'CheckboxControl', label: t('Sort descending'), default: true, description: t('Whether to sort descending or ascending'), visibility: isAggMode, }, }, ], [ { name: 'show_totals', config: { type: 'CheckboxControl', label: t('Show totals'), default: false, description: t( 'Show total aggregations of selected metrics. Note that row limit does not apply to the result.', ), visibility: isAggMode, }, }, ], emitFilterControl, ], }, { label: t('Options'), expanded: true, controlSetRows: [ [ { name: 'table_timestamp_format', config: { type: 'SelectControl', freeForm: true, label: t('Timestamp format'), default: smartDateFormatter.id, renderTrigger: true, clearable: false, choices: D3_TIME_FORMAT_OPTIONS, description: t('D3 time format for datetime columns'), }, }, ], [ { name: 'page_length', config: { type: 'SelectControl', freeForm: true, renderTrigger: true, label: t('Page length'), default: null, choices: PAGE_SIZE_OPTIONS, description: t('Rows per page, 0 means no pagination'), visibility: ({ controls }: ControlPanelsContainerProps) => !controls?.server_pagination?.value, }, }, null, ], [ { name: 'include_search', config: { type: 'CheckboxControl', label: t('Search box'), renderTrigger: true, default: false, description: t('Whether to include a client-side search box'), }, }, { name: 'show_cell_bars', config: { type: 'CheckboxControl', label: t('Cell bars'), renderTrigger: true, default: true, description: t( 'Whether to display a bar chart background in table columns', ), }, }, ], [ { name: 'align_pn', config: { type: 'CheckboxControl', label: t('Align +/-'), renderTrigger: true, default: false, description: t( 'Whether to align background charts with both positive and negative values at 0', ), }, }, { name: 'color_pn', config: { type: 'CheckboxControl', label: t('Color +/-'), renderTrigger: true, default: true, description: t( 'Whether to colorize numeric values by if they are positive or negative', ), }, }, ], [ { name: 'column_config', config: { type: 'ColumnConfigControl', label: t('Customize columns'), description: t('Further customize how to display each column'), renderTrigger: true, shouldMapStateToProps() { return true; }, mapStateToProps(explore, _, chart) { return { queryResponse: chart?.queriesResponse?.[0] as | ChartDataResponseResult | undefined, emitFilter: explore?.controls?.table_filter?.value, }; }, }, }, ], [ { name: 'conditional_formatting', config: { type: 'ConditionalFormattingControl', renderTrigger: true, label: t('Conditional formatting'), description: t( 'Apply conditional color formatting to numeric columns', ), shouldMapStateToProps() { return true; }, mapStateToProps(explore, _, chart) { const verboseMap = explore?.datasource?.verbose_map ?? {}; const { colnames, coltypes } = chart?.queriesResponse?.[0] ?? {}; const numericColumns = Array.isArray(colnames) && Array.isArray(coltypes) ? colnames .filter( (colname: string, index: number) => coltypes[index] === GenericDataType.NUMERIC, ) .map(colname => ({ value: colname, label: verboseMap[colname] ?? colname, })) : []; return { columnOptions: numericColumns, verboseMap, }; }, }, }, ], ], }, ], }; export default config;
superset-frontend/plugins/plugin-chart-table/src/controlPanel.tsx
1
https://github.com/apache/superset/commit/fcc8080ff3b99e2f5f5cdbd48335d7ab83aba16a
[ 0.8705689311027527, 0.019994156435132027, 0.0001639833062654361, 0.00017030557501129806, 0.11949451267719269 ]
{ "id": 6, "code_window": [ " default: [],\n", " mapStateToProps: ({ datasource }) => ({\n", " choices: datasource?.order_by_choices || [],\n", " }),\n", " visibility: isRawMode,\n", " },\n", " },\n", " ],\n", " isFeatureEnabled(FeatureFlag.DASHBOARD_CROSS_FILTERS) ||\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " resetOnHide: false,\n" ], "file_path": "superset-frontend/plugins/plugin-chart-table/src/controlPanel.tsx", "type": "add", "edit_start_line_idx": 279 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ import React, { FunctionComponent, useState, useEffect } from 'react'; import { styled, t } from '@superset-ui/core'; import { useSingleViewResource } from 'src/views/CRUD/hooks'; import { RangePicker } from 'src/components/DatePicker'; import moment from 'moment'; import Icons from 'src/components/Icons'; import Modal from 'src/components/Modal'; import { StyledIcon } from 'src/views/CRUD/utils'; import withToasts from 'src/components/MessageToasts/withToasts'; import { JsonEditor } from 'src/components/AsyncAceEditor'; import { AnnotationObject } from './types'; interface AnnotationModalProps { addDangerToast: (msg: string) => void; addSuccessToast: (msg: string) => void; annnotationLayerId: number; annotation?: AnnotationObject | null; onAnnotationAdd?: (annotation?: AnnotationObject) => void; onHide: () => void; show: boolean; } const StyledAnnotationTitle = styled.div` margin: ${({ theme }) => theme.gridUnit * 2}px auto ${({ theme }) => theme.gridUnit * 4}px auto; `; const StyledJsonEditor = styled(JsonEditor)` border-radius: ${({ theme }) => theme.borderRadius}px; border: 1px solid ${({ theme }) => theme.colors.secondary.light2}; `; const AnnotationContainer = styled.div` margin-bottom: ${({ theme }) => theme.gridUnit * 5}px; .control-label { margin-bottom: ${({ theme }) => theme.gridUnit * 2}px; } .required { margin-left: ${({ theme }) => theme.gridUnit / 2}px; color: ${({ theme }) => theme.colors.error.base}; } textarea { flex: 1 1 auto; height: ${({ theme }) => theme.gridUnit * 17}px; resize: none; width: 100%; } textarea, input[type='text'] { padding: ${({ theme }) => theme.gridUnit * 1.5}px ${({ theme }) => theme.gridUnit * 2}px; border: 1px solid ${({ theme }) => theme.colors.grayscale.light2}; border-radius: ${({ theme }) => theme.gridUnit}px; } input[type='text'] { width: 65%; } `; const AnnotationModal: FunctionComponent<AnnotationModalProps> = ({ addDangerToast, addSuccessToast, annnotationLayerId, annotation = null, onAnnotationAdd, onHide, show, }) => { const [disableSave, setDisableSave] = useState<boolean>(true); const [currentAnnotation, setCurrentAnnotation] = useState<AnnotationObject | null>(null); const isEditMode = annotation !== null; // annotation fetch logic const { state: { loading, resource }, fetchResource, createResource, updateResource, } = useSingleViewResource<AnnotationObject>( `annotation_layer/${annnotationLayerId}/annotation`, t('annotation'), addDangerToast, ); const resetAnnotation = () => { // Reset annotation setCurrentAnnotation({ short_descr: '', start_dttm: '', end_dttm: '', json_metadata: '', long_descr: '', }); }; const hide = () => { if (isEditMode) { setCurrentAnnotation(resource); } else { resetAnnotation(); } onHide(); }; const onSave = () => { if (isEditMode) { // Edit if (currentAnnotation && currentAnnotation.id) { const update_id = currentAnnotation.id; delete currentAnnotation.id; delete currentAnnotation.created_by; delete currentAnnotation.changed_by; delete currentAnnotation.changed_on_delta_humanized; delete currentAnnotation.layer; updateResource(update_id, currentAnnotation).then(response => { // No response on error if (!response) { return; } if (onAnnotationAdd) { onAnnotationAdd(); } hide(); addSuccessToast(t('The annotation has been updated')); }); } } else if (currentAnnotation) { // Create createResource(currentAnnotation).then(response => { if (!response) { return; } if (onAnnotationAdd) { onAnnotationAdd(); } hide(); addSuccessToast(t('The annotation has been saved')); }); } }; const onAnnotationTextChange = ( event: | React.ChangeEvent<HTMLInputElement> | React.ChangeEvent<HTMLTextAreaElement>, ) => { const { target } = event; const data = { ...currentAnnotation, end_dttm: currentAnnotation ? currentAnnotation.end_dttm : '', short_descr: currentAnnotation ? currentAnnotation.short_descr : '', start_dttm: currentAnnotation ? currentAnnotation.start_dttm : '', }; data[target.name] = target.value; setCurrentAnnotation(data); }; const onJsonChange = (json: string) => { const data = { ...currentAnnotation, end_dttm: currentAnnotation ? currentAnnotation.end_dttm : '', json_metadata: json, short_descr: currentAnnotation ? currentAnnotation.short_descr : '', start_dttm: currentAnnotation ? currentAnnotation.start_dttm : '', }; setCurrentAnnotation(data); }; const onDateChange = (value: any, dateString: Array<string>) => { const data = { ...currentAnnotation, end_dttm: currentAnnotation && dateString[1].length ? moment(dateString[1]).format('YYYY-MM-DD HH:mm') : '', short_descr: currentAnnotation ? currentAnnotation.short_descr : '', start_dttm: currentAnnotation && dateString[0].length ? moment(dateString[0]).format('YYYY-MM-DD HH:mm') : '', }; setCurrentAnnotation(data); }; const validate = () => { if ( currentAnnotation && currentAnnotation.short_descr?.length && currentAnnotation.start_dttm?.length && currentAnnotation.end_dttm?.length ) { setDisableSave(false); } else { setDisableSave(true); } }; // Initialize useEffect(() => { if ( isEditMode && (!currentAnnotation || !currentAnnotation.id || (annotation && annotation.id !== currentAnnotation.id) || show) ) { if (annotation && annotation.id !== null && !loading) { const id = annotation.id || 0; fetchResource(id); } } else if ( !isEditMode && (!currentAnnotation || currentAnnotation.id || show) ) { resetAnnotation(); } }, [annotation]); useEffect(() => { if (resource) { setCurrentAnnotation(resource); } }, [resource]); // Validation useEffect(() => { validate(); }, [ currentAnnotation ? currentAnnotation.short_descr : '', currentAnnotation ? currentAnnotation.start_dttm : '', currentAnnotation ? currentAnnotation.end_dttm : '', ]); return ( <Modal disablePrimaryButton={disableSave} onHandledPrimaryAction={onSave} onHide={hide} primaryButtonName={isEditMode ? t('Save') : t('Add')} show={show} width="55%" title={ <h4 data-test="annotaion-modal-title"> {isEditMode ? ( <Icons.EditAlt css={StyledIcon} /> ) : ( <Icons.PlusLarge css={StyledIcon} /> )} {isEditMode ? t('Edit annotation') : t('Add annotation')} </h4> } > <StyledAnnotationTitle> <h4>{t('Basic information')}</h4> </StyledAnnotationTitle> <AnnotationContainer> <div className="control-label"> {t('Annotation name')} <span className="required">*</span> </div> <input name="short_descr" onChange={onAnnotationTextChange} type="text" value={currentAnnotation?.short_descr} /> </AnnotationContainer> <AnnotationContainer> <div className="control-label"> {t('date')} <span className="required">*</span> </div> <RangePicker format="YYYY-MM-DD HH:mm" onChange={onDateChange} showTime={{ format: 'hh:mm a' }} use12Hours value={ currentAnnotation?.start_dttm?.length || currentAnnotation?.end_dttm?.length ? [ moment(currentAnnotation.start_dttm), moment(currentAnnotation.end_dttm), ] : null } /> </AnnotationContainer> <StyledAnnotationTitle> <h4>{t('Additional information')}</h4> </StyledAnnotationTitle> <AnnotationContainer> <div className="control-label">{t('description')}</div> <textarea name="long_descr" value={currentAnnotation ? currentAnnotation.long_descr : ''} placeholder={t('Description (this can be seen in the list)')} onChange={onAnnotationTextChange} /> </AnnotationContainer> <AnnotationContainer> <div className="control-label">{t('JSON metadata')}</div> <StyledJsonEditor onChange={onJsonChange} value={ currentAnnotation && currentAnnotation.json_metadata ? currentAnnotation.json_metadata : '' } width="100%" height="120px" /> </AnnotationContainer> </Modal> ); }; export default withToasts(AnnotationModal);
superset-frontend/src/views/CRUD/annotation/AnnotationModal.tsx
0
https://github.com/apache/superset/commit/fcc8080ff3b99e2f5f5cdbd48335d7ab83aba16a
[ 0.00017961736011784524, 0.00017112518253270537, 0.00016179353406187147, 0.00017146502796094865, 0.000003613326043705456 ]
{ "id": 6, "code_window": [ " default: [],\n", " mapStateToProps: ({ datasource }) => ({\n", " choices: datasource?.order_by_choices || [],\n", " }),\n", " visibility: isRawMode,\n", " },\n", " },\n", " ],\n", " isFeatureEnabled(FeatureFlag.DASHBOARD_CROSS_FILTERS) ||\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " resetOnHide: false,\n" ], "file_path": "superset-frontend/plugins/plugin-chart-table/src/controlPanel.tsx", "type": "add", "edit_start_line_idx": 279 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ module.exports = { root: true, parser: '@typescript-eslint/parser', env: { node: true, browser: true, }, plugins: [ '@typescript-eslint', ], extends: [ 'eslint:recommended', 'plugin:@typescript-eslint/recommended', 'prettier', ], rules: { "@typescript-eslint/explicit-module-boundary-types": 0, "@typescript-eslint/no-var-requires": 0, }, };
superset-websocket/.eslintrc.js
0
https://github.com/apache/superset/commit/fcc8080ff3b99e2f5f5cdbd48335d7ab83aba16a
[ 0.00017452288011554629, 0.00017310268594883382, 0.00017135833331849426, 0.00017326475062873214, 0.0000014095334108787938 ]
{ "id": 6, "code_window": [ " default: [],\n", " mapStateToProps: ({ datasource }) => ({\n", " choices: datasource?.order_by_choices || [],\n", " }),\n", " visibility: isRawMode,\n", " },\n", " },\n", " ],\n", " isFeatureEnabled(FeatureFlag.DASHBOARD_CROSS_FILTERS) ||\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " resetOnHide: false,\n" ], "file_path": "superset-frontend/plugins/plugin-chart-table/src/controlPanel.tsx", "type": "add", "edit_start_line_idx": 279 }
<!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you 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. --> <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"> <path fill-rule="evenodd" clip-rule="evenodd" d="M17.826 9.336L14.664 6.174C14.549 6.06436 14.3969 6.00221 14.238 6H9.762C9.60314 6.00221 9.45098 6.06436 9.336 6.174L6.174 9.336C6.06436 9.45098 6.00221 9.60314 6 9.762V14.238C6.00221 14.3969 6.06436 14.549 6.174 14.664L9.336 17.826C9.45098 17.9356 9.60314 17.9978 9.762 18H14.238C14.3969 17.9978 14.549 17.9356 14.664 17.826L17.826 14.664C17.9356 14.549 17.9978 14.3969 18 14.238V9.762C17.9978 9.60314 17.9356 9.45098 17.826 9.336Z" fill="#E04355"/> <path fill-rule="evenodd" clip-rule="evenodd" d="M11 8.83333C11 8.3731 11.4477 8 12 8C12.5523 8 13 8.3731 13 8.83333V12.1667C13 12.6269 12.5523 13 12 13C11.4477 13 11 12.6269 11 12.1667V8.83333ZM11 15C11 14.4477 11.4477 14 12 14C12.5523 14 13 14.4477 13 15C13 15.5523 12.5523 16 12 16C11.4477 16 11 15.5523 11 15Z" fill="white"/> </svg>
superset-frontend/src/assets/images/icons/error_solid_small_red.svg
0
https://github.com/apache/superset/commit/fcc8080ff3b99e2f5f5cdbd48335d7ab83aba16a
[ 0.0001762266765581444, 0.00017419090727344155, 0.00017113954527303576, 0.00017520648543722928, 0.000002197465619246941 ]
{ "id": 7, "code_window": [ " ),\n", " default: false,\n", " visibility: isAggMode,\n", " },\n", " },\n", " {\n", " name: 'order_desc',\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " resetOnHide: false,\n" ], "file_path": "superset-frontend/plugins/plugin-chart-table/src/controlPanel.tsx", "type": "add", "edit_start_line_idx": 331 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ import React, { ReactNode, useCallback, useState, useEffect } from 'react'; import { isEqual } from 'lodash'; import { ControlType, ControlComponentProps as BaseControlComponentProps, } from '@superset-ui/chart-controls'; import { styled, JsonValue, QueryFormData } from '@superset-ui/core'; import { usePrevious } from 'src/hooks/usePrevious'; import ErrorBoundary from 'src/components/ErrorBoundary'; import { ExploreActions } from 'src/explore/actions/exploreActions'; import controlMap from './controls'; export type ControlProps = { // the actual action dispatcher (via bindActionCreators) has identical // signature to the original action factory. actions: Partial<ExploreActions> & Pick<ExploreActions, 'setControlValue'>; type: ControlType; label?: ReactNode; name: string; description?: ReactNode; tooltipOnClick?: () => ReactNode; places?: number; rightNode?: ReactNode; formData?: QueryFormData | null; value?: JsonValue; validationErrors?: any[]; hidden?: boolean; renderTrigger?: boolean; default?: JsonValue; isVisible?: boolean; }; /** * */ export type ControlComponentProps<ValueType extends JsonValue = JsonValue> = Omit<ControlProps, 'value'> & BaseControlComponentProps<ValueType>; const StyledControl = styled.div` padding-bottom: ${({ theme }) => theme.gridUnit * 4}px; `; export default function Control(props: ControlProps) { const { actions: { setControlValue }, name, type, hidden, isVisible, } = props; const [hovered, setHovered] = useState(false); const wasVisible = usePrevious(isVisible); const onChange = useCallback( (value: any, errors: any[]) => setControlValue(name, value, errors), [name, setControlValue], ); useEffect(() => { if ( wasVisible === true && isVisible === false && props.default !== undefined && !isEqual(props.value, props.default) ) { // reset control value if setting to invisible setControlValue?.(name, props.default); } }, [ name, wasVisible, isVisible, setControlValue, props.value, props.default, ]); if (!type || isVisible === false) return null; const ControlComponent = typeof type === 'string' ? controlMap[type] : type; if (!ControlComponent) { // eslint-disable-next-line no-console console.warn(`Unknown controlType: ${type}`); return null; } return ( <StyledControl className="Control" data-test={name} style={hidden ? { display: 'none' } : undefined} onMouseEnter={() => setHovered(true)} onMouseLeave={() => setHovered(false)} > <ErrorBoundary> <ControlComponent onChange={onChange} hovered={hovered} {...props} /> </ErrorBoundary> </StyledControl> ); }
superset-frontend/src/explore/components/Control.tsx
1
https://github.com/apache/superset/commit/fcc8080ff3b99e2f5f5cdbd48335d7ab83aba16a
[ 0.00023511295148637146, 0.0001732220407575369, 0.00016320166469085962, 0.0001675176026765257, 0.000018797016309690662 ]
{ "id": 7, "code_window": [ " ),\n", " default: false,\n", " visibility: isAggMode,\n", " },\n", " },\n", " {\n", " name: 'order_desc',\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " resetOnHide: false,\n" ], "file_path": "superset-frontend/plugins/plugin-chart-table/src/controlPanel.tsx", "type": "add", "edit_start_line_idx": 331 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ export default function transformProps(chartProps) { const { width, height, formData, queriesData } = chartProps; const { yAxisFormat, colorScheme, sliceId } = formData; return { colorScheme, data: queriesData[0].data, height, numberFormat: yAxisFormat, width, sliceId, }; }
superset-frontend/plugins/legacy-plugin-chart-chord/src/transformProps.js
0
https://github.com/apache/superset/commit/fcc8080ff3b99e2f5f5cdbd48335d7ab83aba16a
[ 0.00017256266437470913, 0.000169059494510293, 0.00016614758351352066, 0.00016876387235242873, 0.0000023332440832746215 ]
{ "id": 7, "code_window": [ " ),\n", " default: false,\n", " visibility: isAggMode,\n", " },\n", " },\n", " {\n", " name: 'order_desc',\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " resetOnHide: false,\n" ], "file_path": "superset-frontend/plugins/plugin-chart-table/src/controlPanel.tsx", "type": "add", "edit_start_line_idx": 331 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ import { t, ChartMetadata, ChartPlugin, Behavior } from '@superset-ui/core'; import buildQuery from './buildQuery'; import controlPanel from './controlPanel'; import transformProps from './transformProps'; import example from './images/BoxPlot.jpg'; import thumbnail from './images/thumbnail.png'; import { BoxPlotQueryFormData, EchartsBoxPlotChartProps } from './types'; export default class EchartsBoxPlotChartPlugin extends ChartPlugin< BoxPlotQueryFormData, EchartsBoxPlotChartProps > { /** * The constructor is used to pass relevant metadata and callbacks that get * registered in respective registries that are used throughout the library * and application. A more thorough description of each property is given in * the respective imported file. * * It is worth noting that `buildQuery` and is optional, and only needed for * advanced visualizations that require either post processing operations * (pivoting, rolling aggregations, sorting etc) or submitting multiple queries. */ constructor() { super({ buildQuery, controlPanel, loadChart: () => import('./EchartsBoxPlot'), metadata: new ChartMetadata({ behaviors: [Behavior.INTERACTIVE_CHART], category: t('Distribution'), credits: ['https://echarts.apache.org'], description: t( 'Also known as a box and whisker plot, this visualization compares the distributions of a related metric across multiple groups. The box in the middle emphasizes the mean, median, and inner 2 quartiles. The whiskers around each box visualize the min, max, range, and outer 2 quartiles.', ), exampleGallery: [{ url: example }], name: t('Box Plot'), tags: [t('ECharts'), t('Range'), t('Statistical')], thumbnail, }), transformProps, }); } }
superset-frontend/plugins/plugin-chart-echarts/src/BoxPlot/index.ts
0
https://github.com/apache/superset/commit/fcc8080ff3b99e2f5f5cdbd48335d7ab83aba16a
[ 0.00018684826500248164, 0.00017115342780016363, 0.00016475975280627608, 0.00016941575449891388, 0.000006877874966448871 ]
{ "id": 7, "code_window": [ " ),\n", " default: false,\n", " visibility: isAggMode,\n", " },\n", " },\n", " {\n", " name: 'order_desc',\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " resetOnHide: false,\n" ], "file_path": "superset-frontend/plugins/plugin-chart-table/src/controlPanel.tsx", "type": "add", "edit_start_line_idx": 331 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ /* eslint-env browser */ import PropTypes from 'prop-types'; import React from 'react'; import { getCategoricalSchemeRegistry, t } from '@superset-ui/core'; import ColorSchemeControl from 'src/explore/components/controls/ColorSchemeControl'; const propTypes = { onChange: PropTypes.func, labelMargin: PropTypes.number, colorScheme: PropTypes.string, hasCustomLabelColors: PropTypes.bool, }; const defaultProps = { hasCustomLabelColors: false, colorScheme: undefined, onChange: () => {}, }; class ColorSchemeControlWrapper extends React.PureComponent { constructor(props) { super(props); this.state = { hovered: false }; this.categoricalSchemeRegistry = getCategoricalSchemeRegistry(); this.choices = this.categoricalSchemeRegistry.keys().map(s => [s, s]); this.schemes = this.categoricalSchemeRegistry.getMap(); } setHover(hovered) { this.setState({ hovered }); } render() { const { colorScheme, labelMargin = 0, hasCustomLabelColors } = this.props; return ( <ColorSchemeControl description={t( "Any color palette selected here will override the colors applied to this dashboard's individual charts", )} labelMargin={labelMargin} name="color_scheme" onChange={this.props.onChange} value={colorScheme} choices={this.choices} clearable schemes={this.schemes} hovered={this.state.hovered} hasCustomLabelColors={hasCustomLabelColors} /> ); } } ColorSchemeControlWrapper.propTypes = propTypes; ColorSchemeControlWrapper.defaultProps = defaultProps; export default ColorSchemeControlWrapper;
superset-frontend/src/dashboard/components/ColorSchemeControlWrapper.jsx
0
https://github.com/apache/superset/commit/fcc8080ff3b99e2f5f5cdbd48335d7ab83aba16a
[ 0.0002460366813465953, 0.00017946642765309662, 0.00016692154167685658, 0.0001708981435513124, 0.000025231382096535526 ]
{ "id": 8, "code_window": [ " default: true,\n", " description: t('Whether to sort descending or ascending'),\n", " visibility: isAggMode,\n", " },\n", " },\n", " ],\n", " [\n", " {\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " resetOnHide: false,\n" ], "file_path": "superset-frontend/plugins/plugin-chart-table/src/controlPanel.tsx", "type": "add", "edit_start_line_idx": 341 }
/* eslint-disable camelcase */ /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ import React from 'react'; import { addLocaleData, ChartDataResponseResult, ensureIsArray, FeatureFlag, GenericDataType, isFeatureEnabled, QueryFormColumn, QueryMode, smartDateFormatter, t, } from '@superset-ui/core'; import { ColumnOption, ControlConfig, ControlPanelConfig, ControlPanelsContainerProps, ControlStateMapping, D3_TIME_FORMAT_OPTIONS, QueryModeLabel, sections, sharedControls, ControlPanelState, ExtraControlProps, ControlState, emitFilterControl, } from '@superset-ui/chart-controls'; import i18n from './i18n'; import { PAGE_SIZE_OPTIONS } from './consts'; addLocaleData(i18n); function getQueryMode(controls: ControlStateMapping): QueryMode { const mode = controls?.query_mode?.value; if (mode === QueryMode.aggregate || mode === QueryMode.raw) { return mode as QueryMode; } const rawColumns = controls?.all_columns?.value as | QueryFormColumn[] | undefined; const hasRawColumns = rawColumns && rawColumns.length > 0; return hasRawColumns ? QueryMode.raw : QueryMode.aggregate; } /** * Visibility check */ function isQueryMode(mode: QueryMode) { return ({ controls }: Pick<ControlPanelsContainerProps, 'controls'>) => getQueryMode(controls) === mode; } const isAggMode = isQueryMode(QueryMode.aggregate); const isRawMode = isQueryMode(QueryMode.raw); const validateAggControlValues = ( controls: ControlStateMapping, values: any[], ) => { const areControlsEmpty = values.every(val => ensureIsArray(val).length === 0); return areControlsEmpty && isAggMode({ controls }) ? [t('Group By, Metrics or Percentage Metrics must have a value')] : []; }; const queryMode: ControlConfig<'RadioButtonControl'> = { type: 'RadioButtonControl', label: t('Query mode'), default: null, options: [ [QueryMode.aggregate, QueryModeLabel[QueryMode.aggregate]], [QueryMode.raw, QueryModeLabel[QueryMode.raw]], ], mapStateToProps: ({ controls }) => ({ value: getQueryMode(controls) }), rerender: ['all_columns', 'groupby', 'metrics', 'percent_metrics'], }; const all_columns: typeof sharedControls.groupby = { type: 'SelectControl', label: t('Columns'), description: t('Columns to display'), multi: true, freeForm: true, allowAll: true, commaChoosesOption: false, default: [], optionRenderer: c => <ColumnOption showType column={c} />, valueRenderer: c => <ColumnOption column={c} />, valueKey: 'column_name', mapStateToProps: ({ datasource, controls }, controlState) => ({ options: datasource?.columns || [], queryMode: getQueryMode(controls), externalValidationErrors: isRawMode({ controls }) && ensureIsArray(controlState.value).length === 0 ? [t('must have a value')] : [], }), visibility: isRawMode, }; const dnd_all_columns: typeof sharedControls.groupby = { type: 'DndColumnSelect', label: t('Columns'), description: t('Columns to display'), default: [], mapStateToProps({ datasource, controls }, controlState) { const newState: ExtraControlProps = {}; if (datasource) { const options = datasource.columns; newState.options = Object.fromEntries( options.map(option => [option.column_name, option]), ); } newState.queryMode = getQueryMode(controls); newState.externalValidationErrors = isRawMode({ controls }) && ensureIsArray(controlState.value).length === 0 ? [t('must have a value')] : []; return newState; }, visibility: isRawMode, }; const percent_metrics: typeof sharedControls.metrics = { type: 'MetricsControl', label: t('Percentage metrics'), description: t( 'Metrics for which percentage of total are to be displayed. Calculated from only data within the row limit.', ), multi: true, visibility: isAggMode, mapStateToProps: ({ datasource, controls }, controlState) => ({ columns: datasource?.columns || [], savedMetrics: datasource?.metrics || [], datasource, datasourceType: datasource?.type, queryMode: getQueryMode(controls), externalValidationErrors: validateAggControlValues(controls, [ controls.groupby?.value, controls.metrics?.value, controlState.value, ]), }), rerender: ['groupby', 'metrics'], default: [], validators: [], }; const dnd_percent_metrics = { ...percent_metrics, type: 'DndMetricSelect', }; const config: ControlPanelConfig = { controlPanelSections: [ sections.legacyTimeseriesTime, { label: t('Query'), expanded: true, controlSetRows: [ [ { name: 'query_mode', config: queryMode, }, ], [ { name: 'groupby', override: { visibility: isAggMode, mapStateToProps: ( state: ControlPanelState, controlState: ControlState, ) => { const { controls } = state; const originalMapStateToProps = sharedControls?.groupby?.mapStateToProps; const newState = originalMapStateToProps?.(state, controlState) ?? {}; newState.externalValidationErrors = validateAggControlValues( controls, [ controls.metrics?.value, controls.percent_metrics?.value, controlState.value, ], ); return newState; }, rerender: ['metrics', 'percent_metrics'], }, }, ], [ { name: 'metrics', override: { validators: [], visibility: isAggMode, mapStateToProps: ( { controls, datasource, form_data }: ControlPanelState, controlState: ControlState, ) => ({ columns: datasource?.columns.filter(c => c.filterable) || [], savedMetrics: datasource?.metrics || [], // current active adhoc metrics selectedMetrics: form_data.metrics || (form_data.metric ? [form_data.metric] : []), datasource, externalValidationErrors: validateAggControlValues(controls, [ controls.groupby?.value, controls.percent_metrics?.value, controlState.value, ]), }), rerender: ['groupby', 'percent_metrics'], }, }, { name: 'all_columns', config: isFeatureEnabled(FeatureFlag.ENABLE_EXPLORE_DRAG_AND_DROP) ? dnd_all_columns : all_columns, }, ], [ { name: 'percent_metrics', config: { ...(isFeatureEnabled(FeatureFlag.ENABLE_EXPLORE_DRAG_AND_DROP) ? dnd_percent_metrics : percent_metrics), }, }, ], ['adhoc_filters'], [ { name: 'timeseries_limit_metric', override: { visibility: isAggMode, }, }, { name: 'order_by_cols', config: { type: 'SelectControl', label: t('Ordering'), description: t('Order results by selected columns'), multi: true, default: [], mapStateToProps: ({ datasource }) => ({ choices: datasource?.order_by_choices || [], }), visibility: isRawMode, }, }, ], isFeatureEnabled(FeatureFlag.DASHBOARD_CROSS_FILTERS) || isFeatureEnabled(FeatureFlag.DASHBOARD_NATIVE_FILTERS) ? [ { name: 'server_pagination', config: { type: 'CheckboxControl', label: t('Server pagination'), description: t( 'Enable server side pagination of results (experimental feature)', ), default: false, }, }, ] : [], [ { name: 'row_limit', override: { visibility: ({ controls }: ControlPanelsContainerProps) => !controls?.server_pagination?.value, }, }, { name: 'server_page_length', config: { type: 'SelectControl', freeForm: true, label: t('Server Page Length'), default: 10, choices: PAGE_SIZE_OPTIONS, description: t('Rows per page, 0 means no pagination'), visibility: ({ controls }: ControlPanelsContainerProps) => Boolean(controls?.server_pagination?.value), }, }, ], [ { name: 'include_time', config: { type: 'CheckboxControl', label: t('Include time'), description: t( 'Whether to include the time granularity as defined in the time section', ), default: false, visibility: isAggMode, }, }, { name: 'order_desc', config: { type: 'CheckboxControl', label: t('Sort descending'), default: true, description: t('Whether to sort descending or ascending'), visibility: isAggMode, }, }, ], [ { name: 'show_totals', config: { type: 'CheckboxControl', label: t('Show totals'), default: false, description: t( 'Show total aggregations of selected metrics. Note that row limit does not apply to the result.', ), visibility: isAggMode, }, }, ], emitFilterControl, ], }, { label: t('Options'), expanded: true, controlSetRows: [ [ { name: 'table_timestamp_format', config: { type: 'SelectControl', freeForm: true, label: t('Timestamp format'), default: smartDateFormatter.id, renderTrigger: true, clearable: false, choices: D3_TIME_FORMAT_OPTIONS, description: t('D3 time format for datetime columns'), }, }, ], [ { name: 'page_length', config: { type: 'SelectControl', freeForm: true, renderTrigger: true, label: t('Page length'), default: null, choices: PAGE_SIZE_OPTIONS, description: t('Rows per page, 0 means no pagination'), visibility: ({ controls }: ControlPanelsContainerProps) => !controls?.server_pagination?.value, }, }, null, ], [ { name: 'include_search', config: { type: 'CheckboxControl', label: t('Search box'), renderTrigger: true, default: false, description: t('Whether to include a client-side search box'), }, }, { name: 'show_cell_bars', config: { type: 'CheckboxControl', label: t('Cell bars'), renderTrigger: true, default: true, description: t( 'Whether to display a bar chart background in table columns', ), }, }, ], [ { name: 'align_pn', config: { type: 'CheckboxControl', label: t('Align +/-'), renderTrigger: true, default: false, description: t( 'Whether to align background charts with both positive and negative values at 0', ), }, }, { name: 'color_pn', config: { type: 'CheckboxControl', label: t('Color +/-'), renderTrigger: true, default: true, description: t( 'Whether to colorize numeric values by if they are positive or negative', ), }, }, ], [ { name: 'column_config', config: { type: 'ColumnConfigControl', label: t('Customize columns'), description: t('Further customize how to display each column'), renderTrigger: true, shouldMapStateToProps() { return true; }, mapStateToProps(explore, _, chart) { return { queryResponse: chart?.queriesResponse?.[0] as | ChartDataResponseResult | undefined, emitFilter: explore?.controls?.table_filter?.value, }; }, }, }, ], [ { name: 'conditional_formatting', config: { type: 'ConditionalFormattingControl', renderTrigger: true, label: t('Conditional formatting'), description: t( 'Apply conditional color formatting to numeric columns', ), shouldMapStateToProps() { return true; }, mapStateToProps(explore, _, chart) { const verboseMap = explore?.datasource?.verbose_map ?? {}; const { colnames, coltypes } = chart?.queriesResponse?.[0] ?? {}; const numericColumns = Array.isArray(colnames) && Array.isArray(coltypes) ? colnames .filter( (colname: string, index: number) => coltypes[index] === GenericDataType.NUMERIC, ) .map(colname => ({ value: colname, label: verboseMap[colname] ?? colname, })) : []; return { columnOptions: numericColumns, verboseMap, }; }, }, }, ], ], }, ], }; export default config;
superset-frontend/plugins/plugin-chart-table/src/controlPanel.tsx
1
https://github.com/apache/superset/commit/fcc8080ff3b99e2f5f5cdbd48335d7ab83aba16a
[ 0.9712944626808167, 0.019209299236536026, 0.00016168509318958968, 0.00017416365153621882, 0.133324533700943 ]
{ "id": 8, "code_window": [ " default: true,\n", " description: t('Whether to sort descending or ascending'),\n", " visibility: isAggMode,\n", " },\n", " },\n", " ],\n", " [\n", " {\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " resetOnHide: false,\n" ], "file_path": "superset-frontend/plugins/plugin-chart-table/src/controlPanel.tsx", "type": "add", "edit_start_line_idx": 341 }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ import { DatasourceType } from './types/Datasource'; export default class DatasourceKey { readonly id: number; readonly type: DatasourceType; constructor(key: string) { const [idStr, typeStr] = key.split('__'); this.id = parseInt(idStr, 10); this.type = typeStr === 'table' ? DatasourceType.Table : DatasourceType.Druid; } public toString() { return `${this.id}__${this.type}`; } public toObject() { return { id: this.id, type: this.type, }; } }
superset-frontend/packages/superset-ui-core/src/query/DatasourceKey.ts
0
https://github.com/apache/superset/commit/fcc8080ff3b99e2f5f5cdbd48335d7ab83aba16a
[ 0.00033563064062036574, 0.00020229404617566615, 0.00016546428378205746, 0.00017149695486295968, 0.00006671682058367878 ]