hunk
dict | file
stringlengths 0
11.8M
| file_path
stringlengths 2
234
| label
int64 0
1
| commit_url
stringlengths 74
103
| dependency_score
listlengths 5
5
|
---|---|---|---|---|---|
{
"id": 2,
"code_window": [
"\tconstructor(parent: HTMLElement | null, contextViewProvider: IContextViewProvider, private readonly _showOptionButtons: boolean, options: IFindInputOptions) {\n",
"\t\tsuper();\n",
"\t\tthis.contextViewProvider = contextViewProvider;\n",
"\t\tthis.width = options.width || 100;\n",
"\t\tthis.placeholder = options.placeholder || '';\n",
"\t\tthis.validation = options.validation;\n",
"\t\tthis.label = options.label || NLS_DEFAULT_LABEL;\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/base/browser/ui/findinput/findInput.ts",
"type": "replace",
"edit_start_line_idx": 95
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Event } from 'vs/base/common/event';
import { IRawFileChange } from 'vs/workbench/services/files/node/watcher/common';
export interface IWatcherRequest {
basePath: string;
ignored: string[];
}
export interface IWatcherOptions {
verboseLogging: boolean;
}
export interface IWatchError {
message: string;
}
export interface IWatcherService {
watch(options: IWatcherOptions): Event<IRawFileChange[] | IWatchError>;
setRoots(roots: IWatcherRequest[]): Promise<void>;
setVerboseLogging(enabled: boolean): Promise<void>;
stop(): Promise<void>;
} | src/vs/workbench/services/files/node/watcher/unix/watcher.ts | 0 | https://github.com/microsoft/vscode/commit/bbff11633c7e56e7fd5d16cc20daa9a3284afbfe | [
0.0003560689219739288,
0.0002317336475243792,
0.00016579957446083426,
0.0001733324461383745,
0.00008797209011390805
]
|
{
"id": 2,
"code_window": [
"\tconstructor(parent: HTMLElement | null, contextViewProvider: IContextViewProvider, private readonly _showOptionButtons: boolean, options: IFindInputOptions) {\n",
"\t\tsuper();\n",
"\t\tthis.contextViewProvider = contextViewProvider;\n",
"\t\tthis.width = options.width || 100;\n",
"\t\tthis.placeholder = options.placeholder || '';\n",
"\t\tthis.validation = options.validation;\n",
"\t\tthis.label = options.label || NLS_DEFAULT_LABEL;\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/base/browser/ui/findinput/findInput.ts",
"type": "replace",
"edit_start_line_idx": 95
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as nls from 'vs/nls';
import { join, dirname } from 'vs/base/common/path';
import * as strings from 'vs/base/common/strings';
import * as extfs from 'vs/base/node/extfs';
import { Event, Emitter } from 'vs/base/common/event';
import { URI } from 'vs/base/common/uri';
import { IDisposable, dispose, Disposable, toDisposable } from 'vs/base/common/lifecycle';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage';
import { Registry } from 'vs/platform/registry/common/platform';
import { EditorOptions } from 'vs/workbench/common/editor';
import { IOutputChannelDescriptor, IOutputChannel, IOutputService, Extensions, OUTPUT_PANEL_ID, IOutputChannelRegistry, OUTPUT_SCHEME, OUTPUT_MIME, LOG_SCHEME, LOG_MIME, CONTEXT_ACTIVE_LOG_OUTPUT, MAX_OUTPUT_LENGTH } from 'vs/workbench/contrib/output/common/output';
import { OutputPanel } from 'vs/workbench/contrib/output/browser/outputPanel';
import { IPanelService } from 'vs/workbench/services/panel/common/panelService';
import { IModelService } from 'vs/editor/common/services/modelService';
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
import { OutputLinkProvider } from 'vs/workbench/contrib/output/common/outputLinkProvider';
import { ITextModelService, ITextModelContentProvider } from 'vs/editor/common/services/resolverService';
import { ITextModel } from 'vs/editor/common/model';
import { IModeService } from 'vs/editor/common/services/modeService';
import { RunOnceScheduler, ThrottledDelayer } from 'vs/base/common/async';
import { EditOperation } from 'vs/editor/common/core/editOperation';
import { Position } from 'vs/editor/common/core/position';
import { IFileService } from 'vs/platform/files/common/files';
import { IPanel } from 'vs/workbench/common/panel';
import { ResourceEditorInput } from 'vs/workbench/common/editor/resourceEditorInput';
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
import { toLocalISOString } from 'vs/base/common/date';
import { IWindowService } from 'vs/platform/windows/common/windows';
import { ILogService } from 'vs/platform/log/common/log';
import { binarySearch } from 'vs/base/common/arrays';
import { ILifecycleService } from 'vs/platform/lifecycle/common/lifecycle';
import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { CancellationToken } from 'vs/base/common/cancellation';
import { OutputAppender } from 'vs/workbench/contrib/output/node/outputAppender';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { isNumber } from 'vs/base/common/types';
const OUTPUT_ACTIVE_CHANNEL_KEY = 'output.activechannel';
let watchingOutputDir = false;
let callbacks: ((eventType: string, fileName: string) => void)[] = [];
function watchOutputDirectory(outputDir: string, logService: ILogService, onChange: (eventType: string, fileName: string) => void): IDisposable {
callbacks.push(onChange);
if (!watchingOutputDir) {
const watcherDisposable = extfs.watch(outputDir, (eventType, fileName) => {
for (const callback of callbacks) {
callback(eventType, fileName);
}
}, (error: string) => {
logService.error(error);
});
watchingOutputDir = true;
return toDisposable(() => {
callbacks = [];
watcherDisposable.dispose();
});
}
return toDisposable(() => { });
}
interface OutputChannel extends IOutputChannel {
readonly file: URI;
readonly onDidAppendedContent: Event<void>;
readonly onDispose: Event<void>;
loadModel(): Promise<ITextModel>;
}
abstract class AbstractFileOutputChannel extends Disposable implements OutputChannel {
scrollLock: boolean = false;
protected _onDidAppendedContent = new Emitter<void>();
readonly onDidAppendedContent: Event<void> = this._onDidAppendedContent.event;
protected _onDispose = new Emitter<void>();
readonly onDispose: Event<void> = this._onDispose.event;
private readonly mimeType: string;
protected modelUpdater: RunOnceScheduler;
protected model: ITextModel;
readonly file: URI;
protected startOffset: number = 0;
protected endOffset: number = 0;
constructor(
readonly outputChannelDescriptor: IOutputChannelDescriptor,
private readonly modelUri: URI,
protected fileService: IFileService,
protected modelService: IModelService,
protected modeService: IModeService,
) {
super();
this.mimeType = outputChannelDescriptor.log ? LOG_MIME : OUTPUT_MIME;
this.file = this.outputChannelDescriptor.file;
this.modelUpdater = new RunOnceScheduler(() => this.updateModel(), 300);
this._register(toDisposable(() => this.modelUpdater.cancel()));
}
get id(): string {
return this.outputChannelDescriptor.id;
}
get label(): string {
return this.outputChannelDescriptor.label;
}
clear(till?: number): void {
if (this.modelUpdater.isScheduled()) {
this.modelUpdater.cancel();
this.onUpdateModelCancelled();
}
if (this.model) {
this.model.setValue('');
}
this.endOffset = isNumber(till) ? till : this.endOffset;
this.startOffset = this.endOffset;
}
update(): void { }
protected createModel(content: string): ITextModel {
if (this.model) {
this.model.setValue(content);
} else {
this.model = this.modelService.createModel(content, this.modeService.create(this.mimeType), this.modelUri);
this.onModelCreated(this.model);
const disposables: IDisposable[] = [];
disposables.push(this.model.onWillDispose(() => {
this.onModelWillDispose(this.model);
this.model = null;
dispose(disposables);
}));
}
return this.model;
}
appendToModel(content: string): void {
if (this.model && content) {
const lastLine = this.model.getLineCount();
const lastLineMaxColumn = this.model.getLineMaxColumn(lastLine);
this.model.applyEdits([EditOperation.insert(new Position(lastLine, lastLineMaxColumn), content)]);
this._onDidAppendedContent.fire();
}
}
abstract loadModel(): Promise<ITextModel>;
abstract append(message: string);
protected onModelCreated(model: ITextModel) { }
protected onModelWillDispose(model: ITextModel) { }
protected onUpdateModelCancelled() { }
protected updateModel() { }
dispose(): void {
this._onDispose.fire();
super.dispose();
}
}
/**
* An output channel that stores appended messages in a backup file.
*/
class OutputChannelBackedByFile extends AbstractFileOutputChannel implements OutputChannel {
private appender: OutputAppender;
private appendedMessage = '';
private loadingFromFileInProgress: boolean = false;
private resettingDelayer: ThrottledDelayer<void>;
private readonly rotatingFilePath: string;
constructor(
outputChannelDescriptor: IOutputChannelDescriptor,
outputDir: string,
modelUri: URI,
@IFileService fileService: IFileService,
@IModelService modelService: IModelService,
@IModeService modeService: IModeService,
@ILogService logService: ILogService
) {
super({ ...outputChannelDescriptor, file: URI.file(join(outputDir, `${outputChannelDescriptor.id}.log`)) }, modelUri, fileService, modelService, modeService);
// Use one rotating file to check for main file reset
this.appender = new OutputAppender(this.id, this.file.fsPath);
this.rotatingFilePath = `${outputChannelDescriptor.id}.1.log`;
this._register(watchOutputDirectory(dirname(this.file.fsPath), logService, (eventType, file) => this.onFileChangedInOutputDirector(eventType, file)));
this.resettingDelayer = new ThrottledDelayer<void>(50);
}
append(message: string): void {
// update end offset always as message is read
this.endOffset = this.endOffset + Buffer.from(message).byteLength;
if (this.loadingFromFileInProgress) {
this.appendedMessage += message;
} else {
this.write(message);
if (this.model) {
this.appendedMessage += message;
if (!this.modelUpdater.isScheduled()) {
this.modelUpdater.schedule();
}
}
}
}
clear(till?: number): void {
super.clear(till);
this.appendedMessage = '';
}
loadModel(): Promise<ITextModel> {
this.loadingFromFileInProgress = true;
if (this.modelUpdater.isScheduled()) {
this.modelUpdater.cancel();
}
this.appendedMessage = '';
return this.loadFile()
.then(content => {
if (this.endOffset !== this.startOffset + Buffer.from(content).byteLength) {
// Queue content is not written into the file
// Flush it and load file again
this.flush();
return this.loadFile();
}
return content;
})
.then(content => {
if (this.appendedMessage) {
this.write(this.appendedMessage);
this.appendedMessage = '';
}
this.loadingFromFileInProgress = false;
return this.createModel(content);
});
}
private resetModel(): Promise<void> {
this.startOffset = 0;
this.endOffset = 0;
if (this.model) {
return this.loadModel().then(() => undefined);
}
return Promise.resolve(undefined);
}
private loadFile(): Promise<string> {
return this.fileService.resolveContent(this.file, { position: this.startOffset, encoding: 'utf8' })
.then(content => this.appendedMessage ? content.value + this.appendedMessage : content.value);
}
protected updateModel(): void {
if (this.model && this.appendedMessage) {
this.appendToModel(this.appendedMessage);
this.appendedMessage = '';
}
}
private onFileChangedInOutputDirector(eventType: string, fileName: string): void {
// Check if rotating file has changed. It changes only when the main file exceeds its limit.
if (this.rotatingFilePath === fileName) {
this.resettingDelayer.trigger(() => this.resetModel());
}
}
private write(content: string): void {
this.appender.append(content);
}
private flush(): void {
this.appender.flush();
}
}
class OutputFileListener extends Disposable {
private readonly _onDidContentChange = new Emitter<number>();
readonly onDidContentChange: Event<number> = this._onDidContentChange.event;
private watching: boolean = false;
private syncDelayer: ThrottledDelayer<void>;
private etag: string;
constructor(
private readonly file: URI,
private readonly fileService: IFileService
) {
super();
this.syncDelayer = new ThrottledDelayer<void>(500);
}
watch(eTag: string): void {
if (!this.watching) {
this.etag = eTag;
this.poll();
this.watching = true;
}
}
private poll(): void {
const loop = () => this.doWatch().then(() => this.poll());
this.syncDelayer.trigger(loop);
}
private doWatch(): Promise<void> {
return this.fileService.resolveFile(this.file)
.then(stat => {
if (stat.etag !== this.etag) {
this.etag = stat.etag;
this._onDidContentChange.fire(stat.size);
}
});
}
unwatch(): void {
if (this.watching) {
this.syncDelayer.cancel();
this.watching = false;
}
}
dispose(): void {
this.unwatch();
super.dispose();
}
}
/**
* An output channel driven by a file and does not support appending messages.
*/
class FileOutputChannel extends AbstractFileOutputChannel implements OutputChannel {
private readonly fileHandler: OutputFileListener;
private updateInProgress: boolean = false;
private etag: string = '';
private loadModelPromise: Promise<ITextModel> = Promise.resolve(undefined);
constructor(
outputChannelDescriptor: IOutputChannelDescriptor,
modelUri: URI,
@IFileService fileService: IFileService,
@IModelService modelService: IModelService,
@IModeService modeService: IModeService
) {
super(outputChannelDescriptor, modelUri, fileService, modelService, modeService);
this.fileHandler = this._register(new OutputFileListener(this.file, this.fileService));
this._register(this.fileHandler.onDidContentChange(size => this.update(size)));
this._register(toDisposable(() => this.fileHandler.unwatch()));
}
loadModel(): Promise<ITextModel> {
this.loadModelPromise = this.fileService.resolveContent(this.file, { position: this.startOffset, encoding: 'utf8' })
.then(content => {
this.endOffset = this.startOffset + Buffer.from(content.value).byteLength;
this.etag = content.etag;
return this.createModel(content.value);
});
return this.loadModelPromise;
}
clear(till?: number): void {
this.loadModelPromise.then(() => {
super.clear(till);
this.update();
});
}
append(message: string): void {
throw new Error('Not supported');
}
protected updateModel(): void {
if (this.model) {
this.fileService.resolveContent(this.file, { position: this.endOffset, encoding: 'utf8' })
.then(content => {
this.etag = content.etag;
if (content.value) {
this.endOffset = this.endOffset + Buffer.from(content.value).byteLength;
this.appendToModel(content.value);
}
this.updateInProgress = false;
}, () => this.updateInProgress = false);
} else {
this.updateInProgress = false;
}
}
protected onModelCreated(model: ITextModel): void {
this.fileHandler.watch(this.etag);
}
protected onModelWillDispose(model: ITextModel): void {
this.fileHandler.unwatch();
}
protected onUpdateModelCancelled(): void {
this.updateInProgress = false;
}
update(size?: number): void {
if (!this.updateInProgress) {
this.updateInProgress = true;
if (isNumber(size) && this.endOffset > size) { // Reset - Content is removed
this.startOffset = this.endOffset = 0;
this.model.setValue('');
}
this.modelUpdater.schedule();
}
}
}
export class OutputService extends Disposable implements IOutputService, ITextModelContentProvider {
public _serviceBrand: any;
private channels: Map<string, OutputChannel> = new Map<string, OutputChannel>();
private activeChannelIdInStorage: string;
private activeChannel: IOutputChannel;
private readonly outputDir: string;
private readonly _onActiveOutputChannel = new Emitter<string>();
readonly onActiveOutputChannel: Event<string> = this._onActiveOutputChannel.event;
private _outputPanel: OutputPanel;
constructor(
@IStorageService private readonly storageService: IStorageService,
@IInstantiationService private readonly instantiationService: IInstantiationService,
@IPanelService private readonly panelService: IPanelService,
@IWorkspaceContextService contextService: IWorkspaceContextService,
@ITextModelService textModelResolverService: ITextModelService,
@IEnvironmentService environmentService: IEnvironmentService,
@IWindowService windowService: IWindowService,
@ILogService private readonly logService: ILogService,
@ITelemetryService private readonly telemetryService: ITelemetryService,
@ILifecycleService private readonly lifecycleService: ILifecycleService,
@IContextKeyService private readonly contextKeyService: IContextKeyService,
) {
super();
this.activeChannelIdInStorage = this.storageService.get(OUTPUT_ACTIVE_CHANNEL_KEY, StorageScope.WORKSPACE, null);
this.outputDir = join(environmentService.logsPath, `output_${windowService.getCurrentWindowId()}_${toLocalISOString(new Date()).replace(/-|:|\.\d+Z$/g, '')}`);
// Register as text model content provider for output
textModelResolverService.registerTextModelContentProvider(OUTPUT_SCHEME, this);
instantiationService.createInstance(OutputLinkProvider);
// Create output channels for already registered channels
const registry = Registry.as<IOutputChannelRegistry>(Extensions.OutputChannels);
for (const channelIdentifier of registry.getChannels()) {
this.onDidRegisterChannel(channelIdentifier.id);
}
this._register(registry.onDidRegisterChannel(this.onDidRegisterChannel, this));
this._register(panelService.onDidPanelOpen(({ panel, focus }) => this.onDidPanelOpen(panel, !focus), this));
this._register(panelService.onDidPanelClose(this.onDidPanelClose, this));
// Set active channel to first channel if not set
if (!this.activeChannel) {
const channels = this.getChannelDescriptors();
this.activeChannel = channels && channels.length > 0 ? this.getChannel(channels[0].id) : null;
}
this._register(this.lifecycleService.onShutdown(() => this.dispose()));
this._register(this.storageService.onWillSaveState(() => this.saveState()));
}
provideTextContent(resource: URI): Promise<ITextModel> {
const channel = <OutputChannel>this.getChannel(resource.path);
if (channel) {
return channel.loadModel();
}
return null;
}
showChannel(id: string, preserveFocus?: boolean): Promise<void> {
const channel = this.getChannel(id);
if (!channel || this.isChannelShown(channel)) {
if (this._outputPanel && !preserveFocus) {
this._outputPanel.focus();
}
return Promise.resolve(undefined);
}
this.activeChannel = channel;
let promise: Promise<void>;
if (this.isPanelShown()) {
promise = this.doShowChannel(channel, !!preserveFocus);
} else {
this.panelService.openPanel(OUTPUT_PANEL_ID);
promise = this.doShowChannel(this.activeChannel, !!preserveFocus);
}
return promise.then(() => this._onActiveOutputChannel.fire(id));
}
getChannel(id: string): IOutputChannel {
return this.channels.get(id);
}
getChannelDescriptors(): IOutputChannelDescriptor[] {
return Registry.as<IOutputChannelRegistry>(Extensions.OutputChannels).getChannels();
}
getActiveChannel(): IOutputChannel {
return this.activeChannel;
}
private onDidRegisterChannel(channelId: string): void {
const channel = this.createChannel(channelId);
this.channels.set(channelId, channel);
if (this.activeChannelIdInStorage === channelId) {
this.activeChannel = channel;
this.onDidPanelOpen(this.panelService.getActivePanel(), true)
.then(() => this._onActiveOutputChannel.fire(channelId));
}
}
private onDidPanelOpen(panel: IPanel, preserveFocus: boolean): Promise<void> {
if (panel && panel.getId() === OUTPUT_PANEL_ID) {
this._outputPanel = <OutputPanel>this.panelService.getActivePanel();
if (this.activeChannel) {
return this.doShowChannel(this.activeChannel, preserveFocus);
}
}
return Promise.resolve(undefined);
}
private onDidPanelClose(panel: IPanel): void {
if (this._outputPanel && panel.getId() === OUTPUT_PANEL_ID) {
CONTEXT_ACTIVE_LOG_OUTPUT.bindTo(this.contextKeyService).set(false);
this._outputPanel.clearInput();
}
}
private createChannel(id: string): OutputChannel {
const channelDisposables: IDisposable[] = [];
const channel = this.instantiateChannel(id);
channel.onDidAppendedContent(() => {
if (!channel.scrollLock) {
const panel = this.panelService.getActivePanel();
if (panel && panel.getId() === OUTPUT_PANEL_ID && this.isChannelShown(channel)) {
let outputPanel = <OutputPanel>panel;
outputPanel.revealLastLine();
}
}
}, channelDisposables);
channel.onDispose(() => {
if (this.activeChannel === channel) {
const channels = this.getChannelDescriptors();
const channel = channels.length ? this.getChannel(channels[0].id) : null;
if (channel && this.isPanelShown()) {
this.showChannel(channel.id, true);
} else {
this.activeChannel = channel;
this._onActiveOutputChannel.fire(channel ? channel.id : undefined);
}
}
Registry.as<IOutputChannelRegistry>(Extensions.OutputChannels).removeChannel(id);
dispose(channelDisposables);
}, channelDisposables);
return channel;
}
private instantiateChannel(id: string): OutputChannel {
const channelData = Registry.as<IOutputChannelRegistry>(Extensions.OutputChannels).getChannel(id);
if (!channelData) {
this.logService.error(`Channel '${id}' is not registered yet`);
throw new Error(`Channel '${id}' is not registered yet`);
}
const uri = URI.from({ scheme: OUTPUT_SCHEME, path: id });
if (channelData && channelData.file) {
return this.instantiationService.createInstance(FileOutputChannel, channelData, uri);
}
try {
return this.instantiationService.createInstance(OutputChannelBackedByFile, { id, label: channelData ? channelData.label : '' }, this.outputDir, uri);
} catch (e) {
// Do not crash if spdlog rotating logger cannot be loaded (workaround for https://github.com/Microsoft/vscode/issues/47883)
this.logService.error(e);
/* __GDPR__
"output.channel.creation.error" : {}
*/
this.telemetryService.publicLog('output.channel.creation.error');
return this.instantiationService.createInstance(BufferredOutputChannel, { id, label: channelData ? channelData.label : '' });
}
}
private doShowChannel(channel: IOutputChannel, preserveFocus: boolean): Promise<void> {
if (this._outputPanel) {
CONTEXT_ACTIVE_LOG_OUTPUT.bindTo(this.contextKeyService).set(channel instanceof FileOutputChannel && channel.outputChannelDescriptor.log);
return this._outputPanel.setInput(this.createInput(channel), EditorOptions.create({ preserveFocus }), CancellationToken.None)
.then(() => {
if (!preserveFocus) {
this._outputPanel.focus();
}
});
}
return Promise.resolve(undefined);
}
private isChannelShown(channel: IOutputChannel): boolean {
return this.isPanelShown() && this.activeChannel === channel;
}
private isPanelShown(): boolean {
const panel = this.panelService.getActivePanel();
return !!panel && panel.getId() === OUTPUT_PANEL_ID;
}
private createInput(channel: IOutputChannel): ResourceEditorInput {
const resource = URI.from({ scheme: OUTPUT_SCHEME, path: channel.id });
return this.instantiationService.createInstance(ResourceEditorInput, nls.localize('output', "{0} - Output", channel.label), nls.localize('channel', "Output channel for '{0}'", channel.label), resource);
}
private saveState(): void {
if (this.activeChannel) {
this.storageService.store(OUTPUT_ACTIVE_CHANNEL_KEY, this.activeChannel.id, StorageScope.WORKSPACE);
}
}
}
export class LogContentProvider {
private channels: Map<string, OutputChannel> = new Map<string, OutputChannel>();
constructor(
@IOutputService private readonly outputService: IOutputService,
@IInstantiationService private readonly instantiationService: IInstantiationService
) {
}
provideTextContent(resource: URI): Promise<ITextModel> {
if (resource.scheme === LOG_SCHEME) {
let channel = this.getChannel(resource);
if (channel) {
return channel.loadModel();
}
}
return null;
}
private getChannel(resource: URI): OutputChannel {
const channelId = resource.path;
let channel = this.channels.get(channelId);
if (!channel) {
const channelDisposables: IDisposable[] = [];
const outputChannelDescriptor = this.outputService.getChannelDescriptors().filter(({ id }) => id === channelId)[0];
if (outputChannelDescriptor && outputChannelDescriptor.file) {
channel = this.instantiationService.createInstance(FileOutputChannel, outputChannelDescriptor, resource);
channel.onDispose(() => dispose(channelDisposables), channelDisposables);
this.channels.set(channelId, channel);
}
}
return channel;
}
}
// Remove this channel when https://github.com/Microsoft/vscode/issues/47883 is fixed
class BufferredOutputChannel extends Disposable implements OutputChannel {
readonly id: string;
readonly label: string;
readonly file: URI | null = null;
scrollLock: boolean = false;
protected _onDidAppendedContent = new Emitter<void>();
readonly onDidAppendedContent: Event<void> = this._onDidAppendedContent.event;
private readonly _onDispose = new Emitter<void>();
readonly onDispose: Event<void> = this._onDispose.event;
private modelUpdater: RunOnceScheduler;
private model: ITextModel;
private readonly bufferredContent: BufferedContent;
private lastReadId: number = undefined;
constructor(
protected readonly outputChannelIdentifier: IOutputChannelDescriptor,
@IModelService private readonly modelService: IModelService,
@IModeService private readonly modeService: IModeService
) {
super();
this.id = outputChannelIdentifier.id;
this.label = outputChannelIdentifier.label;
this.modelUpdater = new RunOnceScheduler(() => this.updateModel(), 300);
this._register(toDisposable(() => this.modelUpdater.cancel()));
this.bufferredContent = new BufferedContent();
this._register(toDisposable(() => this.bufferredContent.clear()));
}
append(output: string) {
this.bufferredContent.append(output);
if (!this.modelUpdater.isScheduled()) {
this.modelUpdater.schedule();
}
}
update(): void { }
clear(): void {
if (this.modelUpdater.isScheduled()) {
this.modelUpdater.cancel();
}
if (this.model) {
this.model.setValue('');
}
this.bufferredContent.clear();
this.lastReadId = undefined;
}
loadModel(): Promise<ITextModel> {
const { value, id } = this.bufferredContent.getDelta(this.lastReadId);
if (this.model) {
this.model.setValue(value);
} else {
this.model = this.createModel(value);
}
this.lastReadId = id;
return Promise.resolve(this.model);
}
private createModel(content: string): ITextModel {
const model = this.modelService.createModel(content, this.modeService.create(OUTPUT_MIME), URI.from({ scheme: OUTPUT_SCHEME, path: this.id }));
const disposables: IDisposable[] = [];
disposables.push(model.onWillDispose(() => {
this.model = null;
dispose(disposables);
}));
return model;
}
private updateModel(): void {
if (this.model) {
const { value, id } = this.bufferredContent.getDelta(this.lastReadId);
this.lastReadId = id;
const lastLine = this.model.getLineCount();
const lastLineMaxColumn = this.model.getLineMaxColumn(lastLine);
this.model.applyEdits([EditOperation.insert(new Position(lastLine, lastLineMaxColumn), value)]);
this._onDidAppendedContent.fire();
}
}
dispose(): void {
this._onDispose.fire();
super.dispose();
}
}
class BufferedContent {
private data: string[] = [];
private dataIds: number[] = [];
private idPool = 0;
private length = 0;
public append(content: string): void {
this.data.push(content);
this.dataIds.push(++this.idPool);
this.length += content.length;
this.trim();
}
public clear(): void {
this.data.length = 0;
this.dataIds.length = 0;
this.length = 0;
}
private trim(): void {
if (this.length < MAX_OUTPUT_LENGTH * 1.2) {
return;
}
while (this.length > MAX_OUTPUT_LENGTH) {
this.dataIds.shift();
const removed = this.data.shift();
this.length -= removed.length;
}
}
public getDelta(previousId?: number): { value: string, id: number } {
let idx = -1;
if (previousId !== undefined) {
idx = binarySearch(this.dataIds, previousId, (a, b) => a - b);
}
const id = this.idPool;
if (idx >= 0) {
const value = strings.removeAnsiEscapeCodes(this.data.slice(idx + 1).join(''));
return { value, id };
} else {
const value = strings.removeAnsiEscapeCodes(this.data.join(''));
return { value, id };
}
}
}
| src/vs/workbench/contrib/output/electron-browser/outputServices.ts | 0 | https://github.com/microsoft/vscode/commit/bbff11633c7e56e7fd5d16cc20daa9a3284afbfe | [
0.0004661303828470409,
0.00018450642528478056,
0.00016552898159716278,
0.00017118507821578532,
0.00005566230902331881
]
|
{
"id": 3,
"code_window": [
"\t\tthis.clearValidation();\n",
"\t\tthis.setValue('');\n",
"\t\tthis.focus();\n",
"\t}\n",
"\n",
"\tpublic setWidth(newWidth: number): void {\n",
"\t\tthis.width = newWidth;\n",
"\t\tthis.domNode.style.width = this.width + 'px';\n",
"\t\tthis.contextViewProvider.layout();\n",
"\t\tthis.setInputWidth();\n",
"\t}\n",
"\n",
"\tpublic getValue(): string {\n",
"\t\treturn this.inputBox.value;\n",
"\t}\n",
"\n",
"\tpublic setValue(value: string): void {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/base/browser/ui/findinput/findInput.ts",
"type": "replace",
"edit_start_line_idx": 161
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import 'vs/css!./findInput';
import * as nls from 'vs/nls';
import * as dom from 'vs/base/browser/dom';
import { IMessage as InputBoxMessage, IInputValidator, IInputBoxStyles, HistoryInputBox } from 'vs/base/browser/ui/inputbox/inputBox';
import { IContextViewProvider } from 'vs/base/browser/ui/contextview/contextview';
import { Widget } from 'vs/base/browser/ui/widget';
import { Event, Emitter } from 'vs/base/common/event';
import { IKeyboardEvent } from 'vs/base/browser/keyboardEvent';
import { IMouseEvent } from 'vs/base/browser/mouseEvent';
import { KeyCode } from 'vs/base/common/keyCodes';
import { CaseSensitiveCheckbox, WholeWordsCheckbox, RegexCheckbox } from 'vs/base/browser/ui/findinput/findInputCheckboxes';
import { Color } from 'vs/base/common/color';
import { ICheckboxStyles } from 'vs/base/browser/ui/checkbox/checkbox';
export interface IFindInputOptions extends IFindInputStyles {
readonly placeholder?: string;
readonly width?: number;
readonly validation?: IInputValidator;
readonly label: string;
readonly flexibleHeight?: boolean;
readonly appendCaseSensitiveLabel?: string;
readonly appendWholeWordsLabel?: string;
readonly appendRegexLabel?: string;
readonly history?: string[];
}
export interface IFindInputStyles extends IInputBoxStyles {
inputActiveOptionBorder?: Color;
}
const NLS_DEFAULT_LABEL = nls.localize('defaultLabel', "input");
export class FindInput extends Widget {
static readonly OPTION_CHANGE: string = 'optionChange';
private contextViewProvider: IContextViewProvider;
private width: number;
private placeholder: string;
private validation?: IInputValidator;
private label: string;
private fixFocusOnOptionClickEnabled = true;
private inputActiveOptionBorder?: Color;
private inputBackground?: Color;
private inputForeground?: Color;
private inputBorder?: Color;
private inputValidationInfoBorder?: Color;
private inputValidationInfoBackground?: Color;
private inputValidationInfoForeground?: Color;
private inputValidationWarningBorder?: Color;
private inputValidationWarningBackground?: Color;
private inputValidationWarningForeground?: Color;
private inputValidationErrorBorder?: Color;
private inputValidationErrorBackground?: Color;
private inputValidationErrorForeground?: Color;
private regex: RegexCheckbox;
private wholeWords: WholeWordsCheckbox;
private caseSensitive: CaseSensitiveCheckbox;
public domNode: HTMLElement;
public inputBox: HistoryInputBox;
private readonly _onDidOptionChange = this._register(new Emitter<boolean>());
public readonly onDidOptionChange: Event<boolean /* via keyboard */> = this._onDidOptionChange.event;
private readonly _onKeyDown = this._register(new Emitter<IKeyboardEvent>());
public readonly onKeyDown: Event<IKeyboardEvent> = this._onKeyDown.event;
private readonly _onMouseDown = this._register(new Emitter<IMouseEvent>());
public readonly onMouseDown: Event<IMouseEvent> = this._onMouseDown.event;
private readonly _onInput = this._register(new Emitter<void>());
public readonly onInput: Event<void> = this._onInput.event;
private readonly _onKeyUp = this._register(new Emitter<IKeyboardEvent>());
public readonly onKeyUp: Event<IKeyboardEvent> = this._onKeyUp.event;
private _onCaseSensitiveKeyDown = this._register(new Emitter<IKeyboardEvent>());
public readonly onCaseSensitiveKeyDown: Event<IKeyboardEvent> = this._onCaseSensitiveKeyDown.event;
private _onRegexKeyDown = this._register(new Emitter<IKeyboardEvent>());
public readonly onRegexKeyDown: Event<IKeyboardEvent> = this._onRegexKeyDown.event;
constructor(parent: HTMLElement | null, contextViewProvider: IContextViewProvider, private readonly _showOptionButtons: boolean, options: IFindInputOptions) {
super();
this.contextViewProvider = contextViewProvider;
this.width = options.width || 100;
this.placeholder = options.placeholder || '';
this.validation = options.validation;
this.label = options.label || NLS_DEFAULT_LABEL;
this.inputActiveOptionBorder = options.inputActiveOptionBorder;
this.inputBackground = options.inputBackground;
this.inputForeground = options.inputForeground;
this.inputBorder = options.inputBorder;
this.inputValidationInfoBorder = options.inputValidationInfoBorder;
this.inputValidationInfoBackground = options.inputValidationInfoBackground;
this.inputValidationInfoForeground = options.inputValidationInfoForeground;
this.inputValidationWarningBorder = options.inputValidationWarningBorder;
this.inputValidationWarningBackground = options.inputValidationWarningBackground;
this.inputValidationWarningForeground = options.inputValidationWarningForeground;
this.inputValidationErrorBorder = options.inputValidationErrorBorder;
this.inputValidationErrorBackground = options.inputValidationErrorBackground;
this.inputValidationErrorForeground = options.inputValidationErrorForeground;
this.buildDomNode(options.appendCaseSensitiveLabel || '', options.appendWholeWordsLabel || '', options.appendRegexLabel || '', options.history || [], !!options.flexibleHeight);
if (parent) {
parent.appendChild(this.domNode);
}
this.onkeydown(this.inputBox.inputElement, (e) => this._onKeyDown.fire(e));
this.onkeyup(this.inputBox.inputElement, (e) => this._onKeyUp.fire(e));
this.oninput(this.inputBox.inputElement, (e) => this._onInput.fire());
this.onmousedown(this.inputBox.inputElement, (e) => this._onMouseDown.fire(e));
}
public enable(): void {
dom.removeClass(this.domNode, 'disabled');
this.inputBox.enable();
this.regex.enable();
this.wholeWords.enable();
this.caseSensitive.enable();
}
public disable(): void {
dom.addClass(this.domNode, 'disabled');
this.inputBox.disable();
this.regex.disable();
this.wholeWords.disable();
this.caseSensitive.disable();
}
public setFocusInputOnOptionClick(value: boolean): void {
this.fixFocusOnOptionClickEnabled = value;
}
public setEnabled(enabled: boolean): void {
if (enabled) {
this.enable();
} else {
this.disable();
}
}
public clear(): void {
this.clearValidation();
this.setValue('');
this.focus();
}
public setWidth(newWidth: number): void {
this.width = newWidth;
this.domNode.style.width = this.width + 'px';
this.contextViewProvider.layout();
this.setInputWidth();
}
public getValue(): string {
return this.inputBox.value;
}
public setValue(value: string): void {
if (this.inputBox.value !== value) {
this.inputBox.value = value;
}
}
public onSearchSubmit(): void {
this.inputBox.addToHistory();
}
public style(styles: IFindInputStyles): void {
this.inputActiveOptionBorder = styles.inputActiveOptionBorder;
this.inputBackground = styles.inputBackground;
this.inputForeground = styles.inputForeground;
this.inputBorder = styles.inputBorder;
this.inputValidationInfoBackground = styles.inputValidationInfoBackground;
this.inputValidationInfoForeground = styles.inputValidationInfoForeground;
this.inputValidationInfoBorder = styles.inputValidationInfoBorder;
this.inputValidationWarningBackground = styles.inputValidationWarningBackground;
this.inputValidationWarningForeground = styles.inputValidationWarningForeground;
this.inputValidationWarningBorder = styles.inputValidationWarningBorder;
this.inputValidationErrorBackground = styles.inputValidationErrorBackground;
this.inputValidationErrorForeground = styles.inputValidationErrorForeground;
this.inputValidationErrorBorder = styles.inputValidationErrorBorder;
this.applyStyles();
}
protected applyStyles(): void {
if (this.domNode) {
const checkBoxStyles: ICheckboxStyles = {
inputActiveOptionBorder: this.inputActiveOptionBorder,
};
this.regex.style(checkBoxStyles);
this.wholeWords.style(checkBoxStyles);
this.caseSensitive.style(checkBoxStyles);
const inputBoxStyles: IInputBoxStyles = {
inputBackground: this.inputBackground,
inputForeground: this.inputForeground,
inputBorder: this.inputBorder,
inputValidationInfoBackground: this.inputValidationInfoBackground,
inputValidationInfoForeground: this.inputValidationInfoForeground,
inputValidationInfoBorder: this.inputValidationInfoBorder,
inputValidationWarningBackground: this.inputValidationWarningBackground,
inputValidationWarningForeground: this.inputValidationWarningForeground,
inputValidationWarningBorder: this.inputValidationWarningBorder,
inputValidationErrorBackground: this.inputValidationErrorBackground,
inputValidationErrorForeground: this.inputValidationErrorForeground,
inputValidationErrorBorder: this.inputValidationErrorBorder
};
this.inputBox.style(inputBoxStyles);
}
}
public select(): void {
this.inputBox.select();
}
public focus(): void {
this.inputBox.focus();
}
public getCaseSensitive(): boolean {
return this.caseSensitive.checked;
}
public setCaseSensitive(value: boolean): void {
this.caseSensitive.checked = value;
this.setInputWidth();
}
public getWholeWords(): boolean {
return this.wholeWords.checked;
}
public setWholeWords(value: boolean): void {
this.wholeWords.checked = value;
this.setInputWidth();
}
public getRegex(): boolean {
return this.regex.checked;
}
public setRegex(value: boolean): void {
this.regex.checked = value;
this.setInputWidth();
this.validate();
}
public focusOnCaseSensitive(): void {
this.caseSensitive.focus();
}
public focusOnRegex(): void {
this.regex.focus();
}
private _lastHighlightFindOptions: number = 0;
public highlightFindOptions(): void {
dom.removeClass(this.domNode, 'highlight-' + (this._lastHighlightFindOptions));
this._lastHighlightFindOptions = 1 - this._lastHighlightFindOptions;
dom.addClass(this.domNode, 'highlight-' + (this._lastHighlightFindOptions));
}
private setInputWidth(): void {
let w = this.width - this.caseSensitive.width() - this.wholeWords.width() - this.regex.width();
this.inputBox.width = w;
this.inputBox.layout();
}
private buildDomNode(appendCaseSensitiveLabel: string, appendWholeWordsLabel: string, appendRegexLabel: string, history: string[], flexibleHeight: boolean): void {
this.domNode = document.createElement('div');
this.domNode.style.width = this.width + 'px';
dom.addClass(this.domNode, 'monaco-findInput');
this.inputBox = this._register(new HistoryInputBox(this.domNode, this.contextViewProvider, {
placeholder: this.placeholder || '',
ariaLabel: this.label || '',
validationOptions: {
validation: this.validation
},
inputBackground: this.inputBackground,
inputForeground: this.inputForeground,
inputBorder: this.inputBorder,
inputValidationInfoBackground: this.inputValidationInfoBackground,
inputValidationInfoForeground: this.inputValidationInfoForeground,
inputValidationInfoBorder: this.inputValidationInfoBorder,
inputValidationWarningBackground: this.inputValidationWarningBackground,
inputValidationWarningForeground: this.inputValidationWarningForeground,
inputValidationWarningBorder: this.inputValidationWarningBorder,
inputValidationErrorBackground: this.inputValidationErrorBackground,
inputValidationErrorForeground: this.inputValidationErrorForeground,
inputValidationErrorBorder: this.inputValidationErrorBorder,
history,
flexibleHeight
}));
this.regex = this._register(new RegexCheckbox({
appendTitle: appendRegexLabel,
isChecked: false,
inputActiveOptionBorder: this.inputActiveOptionBorder
}));
this._register(this.regex.onChange(viaKeyboard => {
this._onDidOptionChange.fire(viaKeyboard);
if (!viaKeyboard && this.fixFocusOnOptionClickEnabled) {
this.inputBox.focus();
}
this.setInputWidth();
this.validate();
}));
this._register(this.regex.onKeyDown(e => {
this._onRegexKeyDown.fire(e);
}));
this.wholeWords = this._register(new WholeWordsCheckbox({
appendTitle: appendWholeWordsLabel,
isChecked: false,
inputActiveOptionBorder: this.inputActiveOptionBorder
}));
this._register(this.wholeWords.onChange(viaKeyboard => {
this._onDidOptionChange.fire(viaKeyboard);
if (!viaKeyboard && this.fixFocusOnOptionClickEnabled) {
this.inputBox.focus();
}
this.setInputWidth();
this.validate();
}));
this.caseSensitive = this._register(new CaseSensitiveCheckbox({
appendTitle: appendCaseSensitiveLabel,
isChecked: false,
inputActiveOptionBorder: this.inputActiveOptionBorder
}));
this._register(this.caseSensitive.onChange(viaKeyboard => {
this._onDidOptionChange.fire(viaKeyboard);
if (!viaKeyboard && this.fixFocusOnOptionClickEnabled) {
this.inputBox.focus();
}
this.setInputWidth();
this.validate();
}));
this._register(this.caseSensitive.onKeyDown(e => {
this._onCaseSensitiveKeyDown.fire(e);
}));
if (this._showOptionButtons) {
this.inputBox.inputElement.style.paddingRight = (this.caseSensitive.width() + this.wholeWords.width() + this.regex.width()) + 'px';
}
// Arrow-Key support to navigate between options
let indexes = [this.caseSensitive.domNode, this.wholeWords.domNode, this.regex.domNode];
this.onkeydown(this.domNode, (event: IKeyboardEvent) => {
if (event.equals(KeyCode.LeftArrow) || event.equals(KeyCode.RightArrow) || event.equals(KeyCode.Escape)) {
let index = indexes.indexOf(<HTMLElement>document.activeElement);
if (index >= 0) {
let newIndex: number = -1;
if (event.equals(KeyCode.RightArrow)) {
newIndex = (index + 1) % indexes.length;
} else if (event.equals(KeyCode.LeftArrow)) {
if (index === 0) {
newIndex = indexes.length - 1;
} else {
newIndex = index - 1;
}
}
if (event.equals(KeyCode.Escape)) {
indexes[index].blur();
} else if (newIndex >= 0) {
indexes[newIndex].focus();
}
dom.EventHelper.stop(event, true);
}
}
});
this.setInputWidth();
let controls = document.createElement('div');
controls.className = 'controls';
controls.style.display = this._showOptionButtons ? 'block' : 'none';
controls.appendChild(this.caseSensitive.domNode);
controls.appendChild(this.wholeWords.domNode);
controls.appendChild(this.regex.domNode);
this.domNode.appendChild(controls);
}
public validate(): void {
if (this.inputBox) {
this.inputBox.validate();
}
}
public showMessage(message: InputBoxMessage): void {
if (this.inputBox) {
this.inputBox.showMessage(message);
}
}
public clearMessage(): void {
if (this.inputBox) {
this.inputBox.hideMessage();
}
}
private clearValidation(): void {
if (this.inputBox) {
this.inputBox.hideMessage();
}
}
public dispose(): void {
super.dispose();
}
}
| src/vs/base/browser/ui/findinput/findInput.ts | 1 | https://github.com/microsoft/vscode/commit/bbff11633c7e56e7fd5d16cc20daa9a3284afbfe | [
0.9948223829269409,
0.1622171700000763,
0.00016538384079467505,
0.0011732642306014895,
0.349763423204422
]
|
{
"id": 3,
"code_window": [
"\t\tthis.clearValidation();\n",
"\t\tthis.setValue('');\n",
"\t\tthis.focus();\n",
"\t}\n",
"\n",
"\tpublic setWidth(newWidth: number): void {\n",
"\t\tthis.width = newWidth;\n",
"\t\tthis.domNode.style.width = this.width + 'px';\n",
"\t\tthis.contextViewProvider.layout();\n",
"\t\tthis.setInputWidth();\n",
"\t}\n",
"\n",
"\tpublic getValue(): string {\n",
"\t\treturn this.inputBox.value;\n",
"\t}\n",
"\n",
"\tpublic setValue(value: string): void {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/base/browser/ui/findinput/findInput.ts",
"type": "replace",
"edit_start_line_idx": 161
} | /*---------------------------------------------------------------------------------------------
* 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 { basename } from 'vs/base/common/resources';
import { IDisposable, dispose, Disposable, combinedDisposable } from 'vs/base/common/lifecycle';
import { Event } from 'vs/base/common/event';
import { VIEWLET_ID, ISCMService, ISCMRepository } from 'vs/workbench/contrib/scm/common/scm';
import { IActivityService, NumberBadge } from 'vs/workbench/services/activity/common/activity';
import { IWorkbenchContribution } from 'vs/workbench/common/contributions';
import { IContextKeyService, IContextKey } from 'vs/platform/contextkey/common/contextkey';
import { IStatusbarService, StatusbarAlignment as MainThreadStatusBarAlignment } from 'vs/platform/statusbar/common/statusbar';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { commonPrefixLength } from 'vs/base/common/strings';
import { ILogService } from 'vs/platform/log/common/log';
export class StatusUpdater implements IWorkbenchContribution {
private badgeDisposable: IDisposable = Disposable.None;
private disposables: IDisposable[] = [];
constructor(
@ISCMService private readonly scmService: ISCMService,
@IActivityService private readonly activityService: IActivityService,
@ILogService private readonly logService: ILogService
) {
for (const repository of this.scmService.repositories) {
this.onDidAddRepository(repository);
}
this.scmService.onDidAddRepository(this.onDidAddRepository, this, this.disposables);
this.render();
}
private onDidAddRepository(repository: ISCMRepository): void {
const provider = repository.provider;
const onDidChange = Event.any(provider.onDidChange, provider.onDidChangeResources);
const changeDisposable = onDidChange(() => this.render());
const onDidRemove = Event.filter(this.scmService.onDidRemoveRepository, e => e === repository);
const removeDisposable = onDidRemove(() => {
disposable.dispose();
this.disposables = this.disposables.filter(d => d !== removeDisposable);
this.render();
});
const disposable = combinedDisposable([changeDisposable, removeDisposable]);
this.disposables.push(disposable);
}
private render(): void {
this.badgeDisposable.dispose();
const count = this.scmService.repositories.reduce((r, repository) => {
if (typeof repository.provider.count === 'number') {
return r + repository.provider.count;
} else {
return r + repository.provider.groups.elements.reduce<number>((r, g) => r + g.elements.length, 0);
}
}, 0);
// TODO@joao: remove
this.logService.trace('SCM#StatusUpdater.render', count);
if (count > 0) {
const badge = new NumberBadge(count, num => localize('scmPendingChangesBadge', '{0} pending changes', num));
this.badgeDisposable = this.activityService.showActivity(VIEWLET_ID, badge, 'scm-viewlet-label');
} else {
this.badgeDisposable = Disposable.None;
}
}
dispose(): void {
this.badgeDisposable.dispose();
this.disposables = dispose(this.disposables);
}
}
export class StatusBarController implements IWorkbenchContribution {
private statusBarDisposable: IDisposable = Disposable.None;
private focusDisposable: IDisposable = Disposable.None;
private focusedRepository: ISCMRepository | undefined = undefined;
private focusedProviderContextKey: IContextKey<string | undefined>;
private disposables: IDisposable[] = [];
constructor(
@ISCMService private readonly scmService: ISCMService,
@IStatusbarService private readonly statusbarService: IStatusbarService,
@IContextKeyService contextKeyService: IContextKeyService,
@IEditorService private readonly editorService: IEditorService
) {
this.focusedProviderContextKey = contextKeyService.createKey<string | undefined>('scmProvider', undefined);
this.scmService.onDidAddRepository(this.onDidAddRepository, this, this.disposables);
for (const repository of this.scmService.repositories) {
this.onDidAddRepository(repository);
}
editorService.onDidActiveEditorChange(this.onDidActiveEditorChange, this, this.disposables);
}
private onDidActiveEditorChange(): void {
if (!this.editorService.activeEditor) {
return;
}
const resource = this.editorService.activeEditor.getResource();
if (!resource || resource.scheme !== 'file') {
return;
}
let bestRepository: ISCMRepository | null = null;
let bestMatchLength = Number.NEGATIVE_INFINITY;
for (const repository of this.scmService.repositories) {
const root = repository.provider.rootUri;
if (!root) {
continue;
}
const rootFSPath = root.fsPath;
const prefixLength = commonPrefixLength(rootFSPath, resource.fsPath);
if (prefixLength === rootFSPath.length && prefixLength > bestMatchLength) {
bestRepository = repository;
bestMatchLength = prefixLength;
}
}
if (bestRepository) {
this.onDidFocusRepository(bestRepository);
}
}
private onDidAddRepository(repository: ISCMRepository): void {
const changeDisposable = repository.onDidFocus(() => this.onDidFocusRepository(repository));
const onDidRemove = Event.filter(this.scmService.onDidRemoveRepository, e => e === repository);
const removeDisposable = onDidRemove(() => {
disposable.dispose();
this.disposables = this.disposables.filter(d => d !== removeDisposable);
if (this.scmService.repositories.length === 0) {
this.onDidFocusRepository(undefined);
} else if (this.focusedRepository === repository) {
this.scmService.repositories[0].focus();
}
});
const disposable = combinedDisposable([changeDisposable, removeDisposable]);
this.disposables.push(disposable);
if (!this.focusedRepository) {
this.onDidFocusRepository(repository);
}
}
private onDidFocusRepository(repository: ISCMRepository | undefined): void {
if (this.focusedRepository === repository) {
return;
}
this.focusedRepository = repository;
this.focusedProviderContextKey.set(repository && repository.provider.id);
this.focusDisposable.dispose();
if (repository && repository.provider.onDidChangeStatusBarCommands) {
this.focusDisposable = repository.provider.onDidChangeStatusBarCommands(() => this.render(repository));
}
this.render(repository);
}
private render(repository: ISCMRepository | undefined): void {
this.statusBarDisposable.dispose();
if (!repository) {
return;
}
const commands = repository.provider.statusBarCommands || [];
const label = repository.provider.rootUri
? `${basename(repository.provider.rootUri)} (${repository.provider.label})`
: repository.provider.label;
const disposables = commands.map(c => this.statusbarService.addEntry({
text: c.title,
tooltip: `${label} - ${c.tooltip}`,
command: c.id,
arguments: c.arguments
}, MainThreadStatusBarAlignment.LEFT, 10000));
this.statusBarDisposable = combinedDisposable(disposables);
}
dispose(): void {
this.focusDisposable.dispose();
this.statusBarDisposable.dispose();
this.disposables = dispose(this.disposables);
}
}
| src/vs/workbench/contrib/scm/electron-browser/scmActivity.ts | 0 | https://github.com/microsoft/vscode/commit/bbff11633c7e56e7fd5d16cc20daa9a3284afbfe | [
0.0005927179008722305,
0.0001944647665368393,
0.000165467121405527,
0.0001683678710833192,
0.00009281293750973418
]
|
{
"id": 3,
"code_window": [
"\t\tthis.clearValidation();\n",
"\t\tthis.setValue('');\n",
"\t\tthis.focus();\n",
"\t}\n",
"\n",
"\tpublic setWidth(newWidth: number): void {\n",
"\t\tthis.width = newWidth;\n",
"\t\tthis.domNode.style.width = this.width + 'px';\n",
"\t\tthis.contextViewProvider.layout();\n",
"\t\tthis.setInputWidth();\n",
"\t}\n",
"\n",
"\tpublic getValue(): string {\n",
"\t\treturn this.inputBox.value;\n",
"\t}\n",
"\n",
"\tpublic setValue(value: string): void {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/base/browser/ui/findinput/findInput.ts",
"type": "replace",
"edit_start_line_idx": 161
} | test/**
src/**
tsconfig.json
cgmanifest.json
| extensions/python/.vscodeignore | 0 | https://github.com/microsoft/vscode/commit/bbff11633c7e56e7fd5d16cc20daa9a3284afbfe | [
0.00016980744840111583,
0.00016980744840111583,
0.00016980744840111583,
0.00016980744840111583,
0
]
|
{
"id": 3,
"code_window": [
"\t\tthis.clearValidation();\n",
"\t\tthis.setValue('');\n",
"\t\tthis.focus();\n",
"\t}\n",
"\n",
"\tpublic setWidth(newWidth: number): void {\n",
"\t\tthis.width = newWidth;\n",
"\t\tthis.domNode.style.width = this.width + 'px';\n",
"\t\tthis.contextViewProvider.layout();\n",
"\t\tthis.setInputWidth();\n",
"\t}\n",
"\n",
"\tpublic getValue(): string {\n",
"\t\treturn this.inputBox.value;\n",
"\t}\n",
"\n",
"\tpublic setValue(value: string): void {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/base/browser/ui/findinput/findInput.ts",
"type": "replace",
"edit_start_line_idx": 161
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { createDecorator, ServiceIdentifier } from 'vs/platform/instantiation/common/instantiation';
import { IResourceInput } from 'vs/platform/editor/common/editor';
import { IEditorInput } from 'vs/workbench/common/editor';
import { URI } from 'vs/base/common/uri';
export const IHistoryService = createDecorator<IHistoryService>('historyService');
export interface IHistoryService {
_serviceBrand: ServiceIdentifier<any>;
/**
* Re-opens the last closed editor if any.
*/
reopenLastClosedEditor(): void;
/**
* Navigates to the last location where an edit happened.
*/
openLastEditLocation(): void;
/**
* Navigate forwards in history.
*
* @param acrossEditors instructs the history to skip navigation entries that
* are only within the same document.
*/
forward(acrossEditors?: boolean): void;
/**
* Navigate backwards in history.
*
* @param acrossEditors instructs the history to skip navigation entries that
* are only within the same document.
*/
back(acrossEditors?: boolean): void;
/**
* Navigate forward or backwards to previous entry in history.
*/
last(): void;
/**
* Removes an entry from history.
*/
remove(input: IEditorInput | IResourceInput): void;
/**
* Clears all history.
*/
clear(): void;
/**
* Clear list of recently opened editors.
*/
clearRecentlyOpened(): void;
/**
* Get the entire history of opened editors.
*/
getHistory(): Array<IEditorInput | IResourceInput>;
/**
* Looking at the editor history, returns the workspace root of the last file that was
* inside the workspace and part of the editor history.
*
* @param schemeFilter filter to restrict roots by scheme.
*/
getLastActiveWorkspaceRoot(schemeFilter?: string): URI | undefined;
/**
* Looking at the editor history, returns the resource of the last file that was opened.
*
* @param schemeFilter filter to restrict roots by scheme.
*/
getLastActiveFile(schemeFilter: string): URI | undefined;
}
| src/vs/workbench/services/history/common/history.ts | 0 | https://github.com/microsoft/vscode/commit/bbff11633c7e56e7fd5d16cc20daa9a3284afbfe | [
0.00019012288248632103,
0.0001705626491457224,
0.00016412799595855176,
0.0001684470335021615,
0.000007341553100559395
]
|
{
"id": 4,
"code_window": [
"\t}\n",
"\n",
"\tpublic setCaseSensitive(value: boolean): void {\n",
"\t\tthis.caseSensitive.checked = value;\n",
"\t\tthis.setInputWidth();\n",
"\t}\n",
"\n",
"\tpublic getWholeWords(): boolean {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/base/browser/ui/findinput/findInput.ts",
"type": "replace",
"edit_start_line_idx": 242
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import 'vs/css!./findInput';
import * as nls from 'vs/nls';
import * as dom from 'vs/base/browser/dom';
import { IMessage as InputBoxMessage, IInputValidator, IInputBoxStyles, HistoryInputBox } from 'vs/base/browser/ui/inputbox/inputBox';
import { IContextViewProvider } from 'vs/base/browser/ui/contextview/contextview';
import { Widget } from 'vs/base/browser/ui/widget';
import { Event, Emitter } from 'vs/base/common/event';
import { IKeyboardEvent } from 'vs/base/browser/keyboardEvent';
import { IMouseEvent } from 'vs/base/browser/mouseEvent';
import { KeyCode } from 'vs/base/common/keyCodes';
import { CaseSensitiveCheckbox, WholeWordsCheckbox, RegexCheckbox } from 'vs/base/browser/ui/findinput/findInputCheckboxes';
import { Color } from 'vs/base/common/color';
import { ICheckboxStyles } from 'vs/base/browser/ui/checkbox/checkbox';
export interface IFindInputOptions extends IFindInputStyles {
readonly placeholder?: string;
readonly width?: number;
readonly validation?: IInputValidator;
readonly label: string;
readonly flexibleHeight?: boolean;
readonly appendCaseSensitiveLabel?: string;
readonly appendWholeWordsLabel?: string;
readonly appendRegexLabel?: string;
readonly history?: string[];
}
export interface IFindInputStyles extends IInputBoxStyles {
inputActiveOptionBorder?: Color;
}
const NLS_DEFAULT_LABEL = nls.localize('defaultLabel', "input");
export class FindInput extends Widget {
static readonly OPTION_CHANGE: string = 'optionChange';
private contextViewProvider: IContextViewProvider;
private width: number;
private placeholder: string;
private validation?: IInputValidator;
private label: string;
private fixFocusOnOptionClickEnabled = true;
private inputActiveOptionBorder?: Color;
private inputBackground?: Color;
private inputForeground?: Color;
private inputBorder?: Color;
private inputValidationInfoBorder?: Color;
private inputValidationInfoBackground?: Color;
private inputValidationInfoForeground?: Color;
private inputValidationWarningBorder?: Color;
private inputValidationWarningBackground?: Color;
private inputValidationWarningForeground?: Color;
private inputValidationErrorBorder?: Color;
private inputValidationErrorBackground?: Color;
private inputValidationErrorForeground?: Color;
private regex: RegexCheckbox;
private wholeWords: WholeWordsCheckbox;
private caseSensitive: CaseSensitiveCheckbox;
public domNode: HTMLElement;
public inputBox: HistoryInputBox;
private readonly _onDidOptionChange = this._register(new Emitter<boolean>());
public readonly onDidOptionChange: Event<boolean /* via keyboard */> = this._onDidOptionChange.event;
private readonly _onKeyDown = this._register(new Emitter<IKeyboardEvent>());
public readonly onKeyDown: Event<IKeyboardEvent> = this._onKeyDown.event;
private readonly _onMouseDown = this._register(new Emitter<IMouseEvent>());
public readonly onMouseDown: Event<IMouseEvent> = this._onMouseDown.event;
private readonly _onInput = this._register(new Emitter<void>());
public readonly onInput: Event<void> = this._onInput.event;
private readonly _onKeyUp = this._register(new Emitter<IKeyboardEvent>());
public readonly onKeyUp: Event<IKeyboardEvent> = this._onKeyUp.event;
private _onCaseSensitiveKeyDown = this._register(new Emitter<IKeyboardEvent>());
public readonly onCaseSensitiveKeyDown: Event<IKeyboardEvent> = this._onCaseSensitiveKeyDown.event;
private _onRegexKeyDown = this._register(new Emitter<IKeyboardEvent>());
public readonly onRegexKeyDown: Event<IKeyboardEvent> = this._onRegexKeyDown.event;
constructor(parent: HTMLElement | null, contextViewProvider: IContextViewProvider, private readonly _showOptionButtons: boolean, options: IFindInputOptions) {
super();
this.contextViewProvider = contextViewProvider;
this.width = options.width || 100;
this.placeholder = options.placeholder || '';
this.validation = options.validation;
this.label = options.label || NLS_DEFAULT_LABEL;
this.inputActiveOptionBorder = options.inputActiveOptionBorder;
this.inputBackground = options.inputBackground;
this.inputForeground = options.inputForeground;
this.inputBorder = options.inputBorder;
this.inputValidationInfoBorder = options.inputValidationInfoBorder;
this.inputValidationInfoBackground = options.inputValidationInfoBackground;
this.inputValidationInfoForeground = options.inputValidationInfoForeground;
this.inputValidationWarningBorder = options.inputValidationWarningBorder;
this.inputValidationWarningBackground = options.inputValidationWarningBackground;
this.inputValidationWarningForeground = options.inputValidationWarningForeground;
this.inputValidationErrorBorder = options.inputValidationErrorBorder;
this.inputValidationErrorBackground = options.inputValidationErrorBackground;
this.inputValidationErrorForeground = options.inputValidationErrorForeground;
this.buildDomNode(options.appendCaseSensitiveLabel || '', options.appendWholeWordsLabel || '', options.appendRegexLabel || '', options.history || [], !!options.flexibleHeight);
if (parent) {
parent.appendChild(this.domNode);
}
this.onkeydown(this.inputBox.inputElement, (e) => this._onKeyDown.fire(e));
this.onkeyup(this.inputBox.inputElement, (e) => this._onKeyUp.fire(e));
this.oninput(this.inputBox.inputElement, (e) => this._onInput.fire());
this.onmousedown(this.inputBox.inputElement, (e) => this._onMouseDown.fire(e));
}
public enable(): void {
dom.removeClass(this.domNode, 'disabled');
this.inputBox.enable();
this.regex.enable();
this.wholeWords.enable();
this.caseSensitive.enable();
}
public disable(): void {
dom.addClass(this.domNode, 'disabled');
this.inputBox.disable();
this.regex.disable();
this.wholeWords.disable();
this.caseSensitive.disable();
}
public setFocusInputOnOptionClick(value: boolean): void {
this.fixFocusOnOptionClickEnabled = value;
}
public setEnabled(enabled: boolean): void {
if (enabled) {
this.enable();
} else {
this.disable();
}
}
public clear(): void {
this.clearValidation();
this.setValue('');
this.focus();
}
public setWidth(newWidth: number): void {
this.width = newWidth;
this.domNode.style.width = this.width + 'px';
this.contextViewProvider.layout();
this.setInputWidth();
}
public getValue(): string {
return this.inputBox.value;
}
public setValue(value: string): void {
if (this.inputBox.value !== value) {
this.inputBox.value = value;
}
}
public onSearchSubmit(): void {
this.inputBox.addToHistory();
}
public style(styles: IFindInputStyles): void {
this.inputActiveOptionBorder = styles.inputActiveOptionBorder;
this.inputBackground = styles.inputBackground;
this.inputForeground = styles.inputForeground;
this.inputBorder = styles.inputBorder;
this.inputValidationInfoBackground = styles.inputValidationInfoBackground;
this.inputValidationInfoForeground = styles.inputValidationInfoForeground;
this.inputValidationInfoBorder = styles.inputValidationInfoBorder;
this.inputValidationWarningBackground = styles.inputValidationWarningBackground;
this.inputValidationWarningForeground = styles.inputValidationWarningForeground;
this.inputValidationWarningBorder = styles.inputValidationWarningBorder;
this.inputValidationErrorBackground = styles.inputValidationErrorBackground;
this.inputValidationErrorForeground = styles.inputValidationErrorForeground;
this.inputValidationErrorBorder = styles.inputValidationErrorBorder;
this.applyStyles();
}
protected applyStyles(): void {
if (this.domNode) {
const checkBoxStyles: ICheckboxStyles = {
inputActiveOptionBorder: this.inputActiveOptionBorder,
};
this.regex.style(checkBoxStyles);
this.wholeWords.style(checkBoxStyles);
this.caseSensitive.style(checkBoxStyles);
const inputBoxStyles: IInputBoxStyles = {
inputBackground: this.inputBackground,
inputForeground: this.inputForeground,
inputBorder: this.inputBorder,
inputValidationInfoBackground: this.inputValidationInfoBackground,
inputValidationInfoForeground: this.inputValidationInfoForeground,
inputValidationInfoBorder: this.inputValidationInfoBorder,
inputValidationWarningBackground: this.inputValidationWarningBackground,
inputValidationWarningForeground: this.inputValidationWarningForeground,
inputValidationWarningBorder: this.inputValidationWarningBorder,
inputValidationErrorBackground: this.inputValidationErrorBackground,
inputValidationErrorForeground: this.inputValidationErrorForeground,
inputValidationErrorBorder: this.inputValidationErrorBorder
};
this.inputBox.style(inputBoxStyles);
}
}
public select(): void {
this.inputBox.select();
}
public focus(): void {
this.inputBox.focus();
}
public getCaseSensitive(): boolean {
return this.caseSensitive.checked;
}
public setCaseSensitive(value: boolean): void {
this.caseSensitive.checked = value;
this.setInputWidth();
}
public getWholeWords(): boolean {
return this.wholeWords.checked;
}
public setWholeWords(value: boolean): void {
this.wholeWords.checked = value;
this.setInputWidth();
}
public getRegex(): boolean {
return this.regex.checked;
}
public setRegex(value: boolean): void {
this.regex.checked = value;
this.setInputWidth();
this.validate();
}
public focusOnCaseSensitive(): void {
this.caseSensitive.focus();
}
public focusOnRegex(): void {
this.regex.focus();
}
private _lastHighlightFindOptions: number = 0;
public highlightFindOptions(): void {
dom.removeClass(this.domNode, 'highlight-' + (this._lastHighlightFindOptions));
this._lastHighlightFindOptions = 1 - this._lastHighlightFindOptions;
dom.addClass(this.domNode, 'highlight-' + (this._lastHighlightFindOptions));
}
private setInputWidth(): void {
let w = this.width - this.caseSensitive.width() - this.wholeWords.width() - this.regex.width();
this.inputBox.width = w;
this.inputBox.layout();
}
private buildDomNode(appendCaseSensitiveLabel: string, appendWholeWordsLabel: string, appendRegexLabel: string, history: string[], flexibleHeight: boolean): void {
this.domNode = document.createElement('div');
this.domNode.style.width = this.width + 'px';
dom.addClass(this.domNode, 'monaco-findInput');
this.inputBox = this._register(new HistoryInputBox(this.domNode, this.contextViewProvider, {
placeholder: this.placeholder || '',
ariaLabel: this.label || '',
validationOptions: {
validation: this.validation
},
inputBackground: this.inputBackground,
inputForeground: this.inputForeground,
inputBorder: this.inputBorder,
inputValidationInfoBackground: this.inputValidationInfoBackground,
inputValidationInfoForeground: this.inputValidationInfoForeground,
inputValidationInfoBorder: this.inputValidationInfoBorder,
inputValidationWarningBackground: this.inputValidationWarningBackground,
inputValidationWarningForeground: this.inputValidationWarningForeground,
inputValidationWarningBorder: this.inputValidationWarningBorder,
inputValidationErrorBackground: this.inputValidationErrorBackground,
inputValidationErrorForeground: this.inputValidationErrorForeground,
inputValidationErrorBorder: this.inputValidationErrorBorder,
history,
flexibleHeight
}));
this.regex = this._register(new RegexCheckbox({
appendTitle: appendRegexLabel,
isChecked: false,
inputActiveOptionBorder: this.inputActiveOptionBorder
}));
this._register(this.regex.onChange(viaKeyboard => {
this._onDidOptionChange.fire(viaKeyboard);
if (!viaKeyboard && this.fixFocusOnOptionClickEnabled) {
this.inputBox.focus();
}
this.setInputWidth();
this.validate();
}));
this._register(this.regex.onKeyDown(e => {
this._onRegexKeyDown.fire(e);
}));
this.wholeWords = this._register(new WholeWordsCheckbox({
appendTitle: appendWholeWordsLabel,
isChecked: false,
inputActiveOptionBorder: this.inputActiveOptionBorder
}));
this._register(this.wholeWords.onChange(viaKeyboard => {
this._onDidOptionChange.fire(viaKeyboard);
if (!viaKeyboard && this.fixFocusOnOptionClickEnabled) {
this.inputBox.focus();
}
this.setInputWidth();
this.validate();
}));
this.caseSensitive = this._register(new CaseSensitiveCheckbox({
appendTitle: appendCaseSensitiveLabel,
isChecked: false,
inputActiveOptionBorder: this.inputActiveOptionBorder
}));
this._register(this.caseSensitive.onChange(viaKeyboard => {
this._onDidOptionChange.fire(viaKeyboard);
if (!viaKeyboard && this.fixFocusOnOptionClickEnabled) {
this.inputBox.focus();
}
this.setInputWidth();
this.validate();
}));
this._register(this.caseSensitive.onKeyDown(e => {
this._onCaseSensitiveKeyDown.fire(e);
}));
if (this._showOptionButtons) {
this.inputBox.inputElement.style.paddingRight = (this.caseSensitive.width() + this.wholeWords.width() + this.regex.width()) + 'px';
}
// Arrow-Key support to navigate between options
let indexes = [this.caseSensitive.domNode, this.wholeWords.domNode, this.regex.domNode];
this.onkeydown(this.domNode, (event: IKeyboardEvent) => {
if (event.equals(KeyCode.LeftArrow) || event.equals(KeyCode.RightArrow) || event.equals(KeyCode.Escape)) {
let index = indexes.indexOf(<HTMLElement>document.activeElement);
if (index >= 0) {
let newIndex: number = -1;
if (event.equals(KeyCode.RightArrow)) {
newIndex = (index + 1) % indexes.length;
} else if (event.equals(KeyCode.LeftArrow)) {
if (index === 0) {
newIndex = indexes.length - 1;
} else {
newIndex = index - 1;
}
}
if (event.equals(KeyCode.Escape)) {
indexes[index].blur();
} else if (newIndex >= 0) {
indexes[newIndex].focus();
}
dom.EventHelper.stop(event, true);
}
}
});
this.setInputWidth();
let controls = document.createElement('div');
controls.className = 'controls';
controls.style.display = this._showOptionButtons ? 'block' : 'none';
controls.appendChild(this.caseSensitive.domNode);
controls.appendChild(this.wholeWords.domNode);
controls.appendChild(this.regex.domNode);
this.domNode.appendChild(controls);
}
public validate(): void {
if (this.inputBox) {
this.inputBox.validate();
}
}
public showMessage(message: InputBoxMessage): void {
if (this.inputBox) {
this.inputBox.showMessage(message);
}
}
public clearMessage(): void {
if (this.inputBox) {
this.inputBox.hideMessage();
}
}
private clearValidation(): void {
if (this.inputBox) {
this.inputBox.hideMessage();
}
}
public dispose(): void {
super.dispose();
}
}
| src/vs/base/browser/ui/findinput/findInput.ts | 1 | https://github.com/microsoft/vscode/commit/bbff11633c7e56e7fd5d16cc20daa9a3284afbfe | [
0.9988526105880737,
0.30607837438583374,
0.0001640020782360807,
0.00024177739396691322,
0.44839927554130554
]
|
{
"id": 4,
"code_window": [
"\t}\n",
"\n",
"\tpublic setCaseSensitive(value: boolean): void {\n",
"\t\tthis.caseSensitive.checked = value;\n",
"\t\tthis.setInputWidth();\n",
"\t}\n",
"\n",
"\tpublic getWholeWords(): boolean {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/base/browser/ui/findinput/findInput.ts",
"type": "replace",
"edit_start_line_idx": 242
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
.monaco-action-bar .action-item.markers-panel-action-filter-container {
cursor: default;
margin-right: 10px;
min-width: 150px;
max-width: 500px;
display: flex;
}
.monaco-action-bar .markers-panel-action-filter-container {
flex: 0.7;
}
.monaco-action-bar .markers-panel-action-filter-container.small {
flex: 0.5;
}
.monaco-action-bar .markers-panel-action-filter {
display: flex;
align-items: center;
flex: 1;
}
.monaco-action-bar .markers-panel-action-filter .monaco-inputbox {
height: 24px;
font-size: 12px;
flex: 1;
}
.vs .monaco-action-bar .markers-panel-action-filter .monaco-inputbox {
height: 25px;
border: 1px solid #ddd;
}
.markers-panel-action-filter > .markers-panel-filter-controls {
position: absolute;
top: 0px;
bottom: 0;
right: 4px;
display: flex;
align-items: center;
}
.markers-panel-action-filter > .markers-panel-filter-controls > .markers-panel-filter-badge {
margin: 4px 0px;
padding: 0px 8px;
border-radius: 2px;
}
.markers-panel-action-filter > .markers-panel-filter-controls > .markers-panel-filter-badge.hidden,
.markers-panel-action-filter-container.small .markers-panel-action-filter > .markers-panel-filter-controls > .markers-panel-filter-badge {
display: none;
}
.vs .markers-panel-action-filter > .markers-panel-filter-controls > .markers-panel-filter-filesExclude {
background: url('excludeSettings.svg') center center no-repeat;
}
.vs-dark .markers-panel-action-filter > .markers-panel-filter-controls > .markers-panel-filter-filesExclude,
.hc-black .markers-panel-action-filter > .markers-panel-filter-controls > .markers-panel-filter-filesExclude {
background: url('excludeSettings-dark.svg') center center no-repeat;
}
.markers-panel .markers-panel-container {
height: 100%;
}
.markers-panel .markers-panel-container .message-box-container {
line-height: 22px;
padding-left: 20px;
height: 100%;
}
.markers-panel .markers-panel-container .message-box-container .messageAction {
margin-left: 4px;
cursor: pointer;
text-decoration: underline;
}
.markers-panel .markers-panel-container .hidden {
display: none;
}
.markers-panel .markers-panel-container .tree-container.hidden {
display: none;
visibility: hidden;
}
.markers-panel .markers-panel-container .tree-container .monaco-tl-contents {
display: flex;
line-height: 22px;
margin-right: 20px;
}
.hc-black .markers-panel .markers-panel-container .tree-container .monaco-tl-contents {
line-height: 20px;
}
.markers-panel .markers-panel-container .tree-container .monaco-tl-contents .marker-stats {
display: inline-block;
margin-left: 10px;
}
.markers-panel .markers-panel-container .tree-container .monaco-tl-contents .count-badge-wrapper {
margin-left: 10px;
}
.markers-panel .markers-panel-container .tree-container .monaco-tl-contents .marker-message-details,
.markers-panel .markers-panel-container .tree-container .monaco-tl-contents .marker-message:not(.multiline) {
display: flex;
overflow: hidden;
}
.markers-panel .markers-panel-container .tree-container .monaco-tl-contents .marker-message.multiline {
white-space: pre;
flex: 1;
}
.markers-panel .markers-panel-container .tree-container .monaco-tl-contents .marker-message:not(.multiline) .marker-message-line {
overflow: hidden;
text-overflow: ellipsis;
}
.markers-panel .markers-panel-container .tree-container .monaco-tl-contents .marker-message .details-container {
display: flex;
}
.markers-panel .markers-panel-container .tree-container .monaco-tl-contents .marker-code:before {
content: '(';
}
.markers-panel .markers-panel-container .tree-container .monaco-tl-contents .marker-code:after {
content: ')';
}
.markers-panel .markers-panel-container .tree-container .monaco-tl-contents .details-container .marker-source,
.markers-panel .markers-panel-container .tree-container .monaco-tl-contents .details-container .marker-line {
margin-left: 6px;
}
.markers-panel .monaco-tl-contents .marker-icon,
.markers-panel .monaco-tl-contents .actions .action-item {
margin-right: 6px;
}
.markers-panel .markers-panel-container .tree-container .monaco-tl-contents .marker-source,
.markers-panel .markers-panel-container .tree-container .monaco-tl-contents .related-info-resource,
.markers-panel .markers-panel-container .tree-container .monaco-tl-contents .related-info-resource-separator,
.markers-panel .markers-panel-container .tree-container .monaco-tl-contents .marker-line,
.markers-panel .markers-panel-container .tree-container .monaco-tl-contents .marker-code {
opacity: 0.7;
}
.markers-panel .markers-panel-container .tree-container .monaco-tl-contents .highlight {
font-weight: bold;
}
.markers-panel .monaco-tl-contents .marker-icon {
height: 22px;
flex: 0 0 16px;
}
.markers-panel .marker-icon.warning {
background: url('status-warning.svg') center center no-repeat;
}
.markers-panel .marker-icon.error {
background: url('status-error.svg') center center no-repeat;
}
.markers-panel .marker-icon.info {
background: url('status-info.svg') center center no-repeat;
}
.vs-dark .markers-panel .marker-icon.warning {
background: url('status-warning-inverse.svg') center center no-repeat;
}
.vs-dark .markers-panel .marker-icon.error {
background: url('status-error-inverse.svg') center center no-repeat;
}
.vs-dark .markers-panel .marker-icon.info {
background: url('status-info-inverse.svg') center center no-repeat;
}
.markers-panel .monaco-tl-contents .actions .action-label.icon.markers-panel-action-quickfix {
background: url('lightbulb.svg') center/80% no-repeat;
margin-right: 0px;
}
.vs-dark .markers-panel .monaco-tl-contents .actions .action-label.icon.markers-panel-action-quickfix {
background: url('lightbulb-dark.svg') center/80% no-repeat;
}
.markers-panel .monaco-tl-contents .actions .monaco-action-bar {
display: none;
}
.markers-panel .monaco-list-row:hover .monaco-tl-contents > .marker-icon.quickFix,
.markers-panel .monaco-list-row.selected .monaco-tl-contents > .marker-icon.quickFix,
.markers-panel .monaco-list-row.focused .monaco-tl-contents > .marker-icon.quickFix {
display: none;
}
.markers-panel .monaco-list-row:hover .monaco-tl-contents .actions .monaco-action-bar,
.markers-panel .monaco-list-row.selected .monaco-tl-contents .actions .monaco-action-bar,
.markers-panel .monaco-list-row.focused .monaco-tl-contents .actions .monaco-action-bar {
display: block;
}
.markers-panel .monaco-tl-contents .multiline-actions .action-label,
.markers-panel .monaco-tl-contents .actions .action-label {
width: 16px;
height: 100%;
background-position: 50% 50%;
background-repeat: no-repeat;
}
.markers-panel .monaco-tl-contents .multiline-actions .action-label {
line-height: 22px;
}
.markers-panel .monaco-tl-contents .multiline-actions .action-item.disabled,
.markers-panel .monaco-tl-contents .actions .action-item.disabled {
display: none;
} | src/vs/workbench/contrib/markers/electron-browser/media/markers.css | 0 | https://github.com/microsoft/vscode/commit/bbff11633c7e56e7fd5d16cc20daa9a3284afbfe | [
0.0001787657820386812,
0.00017060637765098363,
0.00016575120389461517,
0.00017027222202159464,
0.0000027045800834457623
]
|
{
"id": 4,
"code_window": [
"\t}\n",
"\n",
"\tpublic setCaseSensitive(value: boolean): void {\n",
"\t\tthis.caseSensitive.checked = value;\n",
"\t\tthis.setInputWidth();\n",
"\t}\n",
"\n",
"\tpublic getWholeWords(): boolean {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/base/browser/ui/findinput/findInput.ts",
"type": "replace",
"edit_start_line_idx": 242
} | /*---------------------------------------------------------------------------------------------
* 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 'mocha';
import * as vscode from 'vscode';
import { disposeAll } from '../utils/dispose';
const testDocumentUri = vscode.Uri.parse('untitled:test.ts');
type VsCodeConfiguration = { [key: string]: any };
async function updateConfig(newConfig: VsCodeConfiguration): Promise<VsCodeConfiguration> {
const oldConfig: VsCodeConfiguration = {};
const config = vscode.workspace.getConfiguration(undefined, testDocumentUri);
for (const configKey of Object.keys(newConfig)) {
oldConfig[configKey] = config.get(configKey);
await new Promise((resolve, reject) =>
config.update(configKey, newConfig[configKey], vscode.ConfigurationTarget.Global)
.then(() => resolve(), reject));
}
return oldConfig;
}
namespace Config {
export const suggestSelection = 'editor.suggestSelection';
export const completeFunctionCalls = 'typescript.suggest.completeFunctionCalls';
}
suite('TypeScript Completions', () => {
const configDefaults: VsCodeConfiguration = Object.freeze({
[Config.suggestSelection]: 'first',
[Config.completeFunctionCalls]: false,
});
const _disposables: vscode.Disposable[] = [];
let oldConfig: { [key: string]: any } = {};
setup(async () => {
await wait(100);
// Save off config and apply defaults
oldConfig = await updateConfig(configDefaults);
});
teardown(async () => {
disposeAll(_disposables);
// Restore config
await updateConfig(oldConfig);
return vscode.commands.executeCommand('workbench.action.closeAllEditors');
});
test('Basic var completion', async () => {
await createTestEditor(testDocumentUri,
`const abcdef = 123;`,
`ab$0;`
);
const document = await acceptFirstSuggestion(testDocumentUri, _disposables);
assert.strictEqual(
document.getText(),
joinLines(
`const abcdef = 123;`,
`abcdef;`
));
});
test('Should treat period as commit character for var completions', async () => {
await createTestEditor(testDocumentUri,
`const abcdef = 123;`,
`ab$0;`
);
const document = await typeCommitCharacter(testDocumentUri, '.', _disposables);
assert.strictEqual(
document.getText(),
joinLines(
`const abcdef = 123;`,
`abcdef.;`
));
});
test('Should treat paren as commit character for function completions', async () => {
await createTestEditor(testDocumentUri,
`function abcdef() {};`,
`ab$0;`
);
const document = await typeCommitCharacter(testDocumentUri, '(', _disposables);
assert.strictEqual(
document.getText(),
joinLines(
`function abcdef() {};`,
`abcdef();`
));
});
test('Should insert backets when completing dot properties with spaces in name', async () => {
await createTestEditor(testDocumentUri,
'const x = { "hello world": 1 };',
'x.$0'
);
const document = await acceptFirstSuggestion(testDocumentUri, _disposables);
assert.strictEqual(
document.getText(),
joinLines(
'const x = { "hello world": 1 };',
'x["hello world"]'
));
});
test('Should allow commit characters for backet completions', async () => {
for (const { char, insert } of [
{ char: '.', insert: '.' },
{ char: '(', insert: '()' },
]) {
await createTestEditor(testDocumentUri,
'const x = { "hello world2": 1 };',
'x.$0'
);
const document = await typeCommitCharacter(testDocumentUri, char, _disposables);
assert.strictEqual(
document.getText(),
joinLines(
'const x = { "hello world2": 1 };',
`x["hello world2"]${insert}`
));
}
});
test('Should not prioritize bracket accessor completions. #63100', async () => {
// 'a' should be first entry in completion list
await createTestEditor(testDocumentUri,
'const x = { "z-z": 1, a: 1 };',
'x.$0'
);
const document = await acceptFirstSuggestion(testDocumentUri, _disposables);
assert.strictEqual(
document.getText(),
joinLines(
'const x = { "z-z": 1, a: 1 };',
'x.a'
));
});
test('Accepting a string completion should replace the entire string. #53962', async () => {
await createTestEditor(testDocumentUri,
'interface TFunction {',
` (_: 'abc.abc2', __ ?: {}): string;`,
` (_: 'abc.abc', __?: {}): string;`,
`}`,
'const f: TFunction = (() => { }) as any;',
`f('abc.abc$0')`
);
const document = await acceptFirstSuggestion(testDocumentUri, _disposables);
assert.strictEqual(
document.getText(),
joinLines(
'interface TFunction {',
` (_: 'abc.abc2', __ ?: {}): string;`,
` (_: 'abc.abc', __?: {}): string;`,
`}`,
'const f: TFunction = (() => { }) as any;',
`f('abc.abc')`
));
});
test.skip('Accepting a member completion should result in valid code. #58597', async () => {
await createTestEditor(testDocumentUri,
`const abc = 123;`,
`ab$0c`
);
const document = await acceptFirstSuggestion(testDocumentUri, _disposables);
assert.strictEqual(
document.getText(),
joinLines(
`const abc = 123;`,
`abc`
));
});
test('completeFunctionCalls should complete function parameters when at end of word', async () => {
await updateConfig({
[Config.completeFunctionCalls]: true,
});
// Complete with-in word
await createTestEditor(testDocumentUri,
`function abcdef(x, y, z) { }`,
`abcdef$0`
);
const document = await acceptFirstSuggestion(testDocumentUri, _disposables);
assert.strictEqual(
document.getText(),
joinLines(
`function abcdef(x, y, z) { }`,
`abcdef(x, y, z)`
));
});
test.skip('completeFunctionCalls should complete function parameters when within word', async () => {
await updateConfig({
[Config.completeFunctionCalls]: true,
});
await createTestEditor(testDocumentUri,
`function abcdef(x, y, z) { }`,
`abcd$0ef`
);
const document = await acceptFirstSuggestion(testDocumentUri, _disposables);
assert.strictEqual(
document.getText(),
joinLines(
`function abcdef(x, y, z) { }`,
`abcdef(x, y, z)`
));
});
test('completeFunctionCalls should not complete function parameters at end of word if we are already in something that looks like a function call, #18131', async () => {
await updateConfig({
[Config.completeFunctionCalls]: true,
});
await createTestEditor(testDocumentUri,
`function abcdef(x, y, z) { }`,
`abcdef$0(1, 2, 3)`
);
const document = await acceptFirstSuggestion(testDocumentUri, _disposables);
assert.strictEqual(
document.getText(),
joinLines(
`function abcdef(x, y, z) { }`,
`abcdef(1, 2, 3)`
));
});
test.skip('completeFunctionCalls should not complete function parameters within word if we are already in something that looks like a function call, #18131', async () => {
await updateConfig({
[Config.completeFunctionCalls]: true,
});
await createTestEditor(testDocumentUri,
`function abcdef(x, y, z) { }`,
`abcd$0ef(1, 2, 3)`
);
const document = await acceptFirstSuggestion(testDocumentUri, _disposables);
assert.strictEqual(
document.getText(),
joinLines(
`function abcdef(x, y, z) { }`,
`abcdef(1, 2, 3)`
));
});
});
const joinLines = (...args: string[]) => args.join('\n');
const wait = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
async function acceptFirstSuggestion(uri: vscode.Uri, _disposables: vscode.Disposable[]) {
const didChangeDocument = onChangedDocument(uri, _disposables);
const didSuggest = onDidSuggest(_disposables);
await vscode.commands.executeCommand('editor.action.triggerSuggest');
await didSuggest;
// TODO: depends on reverting fix for https://github.com/Microsoft/vscode/issues/64257
// Make sure we have time to resolve the suggestion because `acceptSelectedSuggestion` doesn't
await wait(40);
await vscode.commands.executeCommand('acceptSelectedSuggestion');
return await didChangeDocument;
}
async function typeCommitCharacter(uri: vscode.Uri, character: string, _disposables: vscode.Disposable[]) {
const didChangeDocument = onChangedDocument(uri, _disposables);
const didSuggest = onDidSuggest(_disposables);
await vscode.commands.executeCommand('editor.action.triggerSuggest');
await didSuggest;
await vscode.commands.executeCommand('type', { text: character });
return await didChangeDocument;
}
function onChangedDocument(documentUri: vscode.Uri, disposables: vscode.Disposable[]) {
return new Promise<vscode.TextDocument>(resolve => vscode.workspace.onDidChangeTextDocument(e => {
if (e.document.uri.toString() === documentUri.toString()) {
resolve(e.document);
}
}, undefined, disposables));
}
async function createTestEditor(uri: vscode.Uri, ...lines: string[]) {
const document = await vscode.workspace.openTextDocument(uri);
await vscode.window.showTextDocument(document);
const activeEditor = vscode.window.activeTextEditor;
if (!activeEditor) {
throw new Error('no active editor');
}
await activeEditor.insertSnippet(new vscode.SnippetString(joinLines(...lines)), new vscode.Range(0, 0, 1000, 0));
}
function onDidSuggest(disposables: vscode.Disposable[]) {
return new Promise(resolve =>
disposables.push(vscode.languages.registerCompletionItemProvider('typescript', new class implements vscode.CompletionItemProvider {
provideCompletionItems(doc: vscode.TextDocument, position: vscode.Position): vscode.ProviderResult<vscode.CompletionItem[] | vscode.CompletionList> {
// Return a fake item that will come first
const range = new vscode.Range(new vscode.Position(position.line, 0), position);
return [{
label: '🦄',
insertText: doc.getText(range),
filterText: doc.getText(range),
preselect: true,
sortText: '\0',
range: range
}];
}
async resolveCompletionItem(item: vscode.CompletionItem) {
await vscode.commands.executeCommand('selectNextSuggestion');
resolve();
return item;
}
})));
} | extensions/typescript-language-features/src/test/completions.test.ts | 0 | https://github.com/microsoft/vscode/commit/bbff11633c7e56e7fd5d16cc20daa9a3284afbfe | [
0.0001769916998455301,
0.00017422589007765055,
0.00017046448192559183,
0.0001744475739542395,
0.0000016281223906844389
]
|
{
"id": 4,
"code_window": [
"\t}\n",
"\n",
"\tpublic setCaseSensitive(value: boolean): void {\n",
"\t\tthis.caseSensitive.checked = value;\n",
"\t\tthis.setInputWidth();\n",
"\t}\n",
"\n",
"\tpublic getWholeWords(): boolean {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/base/browser/ui/findinput/findInput.ts",
"type": "replace",
"edit_start_line_idx": 242
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as arrays from 'vs/base/common/arrays';
import * as strings from 'vs/base/common/strings';
import * as extpath from 'vs/base/common/extpath';
import * as paths from 'vs/base/common/path';
import { LRUCache } from 'vs/base/common/map';
import { CharCode } from 'vs/base/common/charCode';
import { isThenable } from 'vs/base/common/async';
export interface IExpression {
[pattern: string]: boolean | SiblingClause | any;
}
export interface IRelativePattern {
base: string;
pattern: string;
}
export function getEmptyExpression(): IExpression {
return Object.create(null);
}
export interface SiblingClause {
when: string;
}
const GLOBSTAR = '**';
const GLOB_SPLIT = '/';
const PATH_REGEX = '[/\\\\]'; // any slash or backslash
const NO_PATH_REGEX = '[^/\\\\]'; // any non-slash and non-backslash
const ALL_FORWARD_SLASHES = /\//g;
function starsToRegExp(starCount: number): string {
switch (starCount) {
case 0:
return '';
case 1:
return `${NO_PATH_REGEX}*?`; // 1 star matches any number of characters except path separator (/ and \) - non greedy (?)
default:
// Matches: (Path Sep OR Path Val followed by Path Sep OR Path Sep followed by Path Val) 0-many times
// Group is non capturing because we don't need to capture at all (?:...)
// Overall we use non-greedy matching because it could be that we match too much
return `(?:${PATH_REGEX}|${NO_PATH_REGEX}+${PATH_REGEX}|${PATH_REGEX}${NO_PATH_REGEX}+)*?`;
}
}
export function splitGlobAware(pattern: string, splitChar: string): string[] {
if (!pattern) {
return [];
}
let segments: string[] = [];
let inBraces = false;
let inBrackets = false;
let curVal = '';
for (const char of pattern) {
switch (char) {
case splitChar:
if (!inBraces && !inBrackets) {
segments.push(curVal);
curVal = '';
continue;
}
break;
case '{':
inBraces = true;
break;
case '}':
inBraces = false;
break;
case '[':
inBrackets = true;
break;
case ']':
inBrackets = false;
break;
}
curVal += char;
}
// Tail
if (curVal) {
segments.push(curVal);
}
return segments;
}
function parseRegExp(pattern: string): string {
if (!pattern) {
return '';
}
let regEx = '';
// Split up into segments for each slash found
let segments = splitGlobAware(pattern, GLOB_SPLIT);
// Special case where we only have globstars
if (segments.every(s => s === GLOBSTAR)) {
regEx = '.*';
}
// Build regex over segments
else {
let previousSegmentWasGlobStar = false;
segments.forEach((segment, index) => {
// Globstar is special
if (segment === GLOBSTAR) {
// if we have more than one globstar after another, just ignore it
if (!previousSegmentWasGlobStar) {
regEx += starsToRegExp(2);
previousSegmentWasGlobStar = true;
}
return;
}
// States
let inBraces = false;
let braceVal = '';
let inBrackets = false;
let bracketVal = '';
for (const char of segment) {
// Support brace expansion
if (char !== '}' && inBraces) {
braceVal += char;
continue;
}
// Support brackets
if (inBrackets && (char !== ']' || !bracketVal) /* ] is literally only allowed as first character in brackets to match it */) {
let res: string;
// range operator
if (char === '-') {
res = char;
}
// negation operator (only valid on first index in bracket)
else if ((char === '^' || char === '!') && !bracketVal) {
res = '^';
}
// glob split matching is not allowed within character ranges
// see http://man7.org/linux/man-pages/man7/glob.7.html
else if (char === GLOB_SPLIT) {
res = '';
}
// anything else gets escaped
else {
res = strings.escapeRegExpCharacters(char);
}
bracketVal += res;
continue;
}
switch (char) {
case '{':
inBraces = true;
continue;
case '[':
inBrackets = true;
continue;
case '}':
let choices = splitGlobAware(braceVal, ',');
// Converts {foo,bar} => [foo|bar]
let braceRegExp = `(?:${choices.map(c => parseRegExp(c)).join('|')})`;
regEx += braceRegExp;
inBraces = false;
braceVal = '';
break;
case ']':
regEx += ('[' + bracketVal + ']');
inBrackets = false;
bracketVal = '';
break;
case '?':
regEx += NO_PATH_REGEX; // 1 ? matches any single character except path separator (/ and \)
continue;
case '*':
regEx += starsToRegExp(1);
continue;
default:
regEx += strings.escapeRegExpCharacters(char);
}
}
// Tail: Add the slash we had split on if there is more to come and the remaining pattern is not a globstar
// For example if pattern: some/**/*.js we want the "/" after some to be included in the RegEx to prevent
// a folder called "something" to match as well.
// However, if pattern: some/**, we tolerate that we also match on "something" because our globstar behaviour
// is to match 0-N segments.
if (index < segments.length - 1 && (segments[index + 1] !== GLOBSTAR || index + 2 < segments.length)) {
regEx += PATH_REGEX;
}
// reset state
previousSegmentWasGlobStar = false;
});
}
return regEx;
}
// regexes to check for trival glob patterns that just check for String#endsWith
const T1 = /^\*\*\/\*\.[\w\.-]+$/; // **/*.something
const T2 = /^\*\*\/([\w\.-]+)\/?$/; // **/something
const T3 = /^{\*\*\/[\*\.]?[\w\.-]+\/?(,\*\*\/[\*\.]?[\w\.-]+\/?)*}$/; // {**/*.something,**/*.else} or {**/package.json,**/project.json}
const T3_2 = /^{\*\*\/[\*\.]?[\w\.-]+(\/(\*\*)?)?(,\*\*\/[\*\.]?[\w\.-]+(\/(\*\*)?)?)*}$/; // Like T3, with optional trailing /**
const T4 = /^\*\*((\/[\w\.-]+)+)\/?$/; // **/something/else
const T5 = /^([\w\.-]+(\/[\w\.-]+)*)\/?$/; // something/else
export type ParsedPattern = (path: string, basename?: string) => boolean;
// The ParsedExpression returns a Promise iff hasSibling returns a Promise.
export type ParsedExpression = (path: string, basename?: string, hasSibling?: (name: string) => boolean | Promise<boolean>) => string | null | Promise<string | null> /* the matching pattern */;
export interface IGlobOptions {
/**
* Simplify patterns for use as exclusion filters during tree traversal to skip entire subtrees. Cannot be used outside of a tree traversal.
*/
trimForExclusions?: boolean;
}
interface ParsedStringPattern {
(path: string, basename: string): string | null | Promise<string | null> /* the matching pattern */;
basenames?: string[];
patterns?: string[];
allBasenames?: string[];
allPaths?: string[];
}
interface ParsedExpressionPattern {
(path: string, basename: string, name?: string, hasSibling?: (name: string) => boolean | Promise<boolean>): string | null | Promise<string | null> /* the matching pattern */;
requiresSiblings?: boolean;
allBasenames?: string[];
allPaths?: string[];
}
const CACHE = new LRUCache<string, ParsedStringPattern>(10000); // bounded to 10000 elements
const FALSE = function () {
return false;
};
const NULL = function (): string | null {
return null;
};
function parsePattern(arg1: string | IRelativePattern, options: IGlobOptions): ParsedStringPattern {
if (!arg1) {
return NULL;
}
// Handle IRelativePattern
let pattern: string;
if (typeof arg1 !== 'string') {
pattern = arg1.pattern;
} else {
pattern = arg1;
}
// Whitespace trimming
pattern = pattern.trim();
// Check cache
const patternKey = `${pattern}_${!!options.trimForExclusions}`;
let parsedPattern = CACHE.get(patternKey);
if (parsedPattern) {
return wrapRelativePattern(parsedPattern, arg1);
}
// Check for Trivias
let match: RegExpExecArray | null;
if (T1.test(pattern)) { // common pattern: **/*.txt just need endsWith check
const base = pattern.substr(4); // '**/*'.length === 4
parsedPattern = function (path, basename) {
return typeof path === 'string' && strings.endsWith(path, base) ? pattern : null;
};
} else if (match = T2.exec(trimForExclusions(pattern, options))) { // common pattern: **/some.txt just need basename check
parsedPattern = trivia2(match[1], pattern);
} else if ((options.trimForExclusions ? T3_2 : T3).test(pattern)) { // repetition of common patterns (see above) {**/*.txt,**/*.png}
parsedPattern = trivia3(pattern, options);
} else if (match = T4.exec(trimForExclusions(pattern, options))) { // common pattern: **/something/else just need endsWith check
parsedPattern = trivia4and5(match[1].substr(1), pattern, true);
} else if (match = T5.exec(trimForExclusions(pattern, options))) { // common pattern: something/else just need equals check
parsedPattern = trivia4and5(match[1], pattern, false);
}
// Otherwise convert to pattern
else {
parsedPattern = toRegExp(pattern);
}
// Cache
CACHE.set(patternKey, parsedPattern);
return wrapRelativePattern(parsedPattern, arg1);
}
function wrapRelativePattern(parsedPattern: ParsedStringPattern, arg2: string | IRelativePattern): ParsedStringPattern {
if (typeof arg2 === 'string') {
return parsedPattern;
}
return function (path, basename) {
if (!extpath.isEqualOrParent(path, arg2.base)) {
return null;
}
return parsedPattern(paths.relative(arg2.base, path), basename);
};
}
function trimForExclusions(pattern: string, options: IGlobOptions): string {
return options.trimForExclusions && strings.endsWith(pattern, '/**') ? pattern.substr(0, pattern.length - 2) : pattern; // dropping **, tailing / is dropped later
}
// common pattern: **/some.txt just need basename check
function trivia2(base: string, originalPattern: string): ParsedStringPattern {
const slashBase = `/${base}`;
const backslashBase = `\\${base}`;
const parsedPattern: ParsedStringPattern = function (path, basename) {
if (typeof path !== 'string') {
return null;
}
if (basename) {
return basename === base ? originalPattern : null;
}
return path === base || strings.endsWith(path, slashBase) || strings.endsWith(path, backslashBase) ? originalPattern : null;
};
const basenames = [base];
parsedPattern.basenames = basenames;
parsedPattern.patterns = [originalPattern];
parsedPattern.allBasenames = basenames;
return parsedPattern;
}
// repetition of common patterns (see above) {**/*.txt,**/*.png}
function trivia3(pattern: string, options: IGlobOptions): ParsedStringPattern {
const parsedPatterns = aggregateBasenameMatches(pattern.slice(1, -1).split(',')
.map(pattern => parsePattern(pattern, options))
.filter(pattern => pattern !== NULL), pattern);
const n = parsedPatterns.length;
if (!n) {
return NULL;
}
if (n === 1) {
return <ParsedStringPattern>parsedPatterns[0];
}
const parsedPattern: ParsedStringPattern = function (path: string, basename: string) {
for (let i = 0, n = parsedPatterns.length; i < n; i++) {
if ((<ParsedStringPattern>parsedPatterns[i])(path, basename)) {
return pattern;
}
}
return null;
};
const withBasenames = arrays.first(parsedPatterns, pattern => !!(<ParsedStringPattern>pattern).allBasenames);
if (withBasenames) {
parsedPattern.allBasenames = (<ParsedStringPattern>withBasenames).allBasenames;
}
const allPaths = parsedPatterns.reduce((all, current) => current.allPaths ? all.concat(current.allPaths) : all, <string[]>[]);
if (allPaths.length) {
parsedPattern.allPaths = allPaths;
}
return parsedPattern;
}
// common patterns: **/something/else just need endsWith check, something/else just needs and equals check
function trivia4and5(path: string, pattern: string, matchPathEnds: boolean): ParsedStringPattern {
const nativePath = paths.sep !== paths.posix.sep ? path.replace(ALL_FORWARD_SLASHES, paths.sep) : path;
const nativePathEnd = paths.sep + nativePath;
const parsedPattern: ParsedStringPattern = matchPathEnds ? function (path, basename) {
return typeof path === 'string' && (path === nativePath || strings.endsWith(path, nativePathEnd)) ? pattern : null;
} : function (path, basename) {
return typeof path === 'string' && path === nativePath ? pattern : null;
};
parsedPattern.allPaths = [(matchPathEnds ? '*/' : './') + path];
return parsedPattern;
}
function toRegExp(pattern: string): ParsedStringPattern {
try {
const regExp = new RegExp(`^${parseRegExp(pattern)}$`);
return function (path: string, basename: string) {
regExp.lastIndex = 0; // reset RegExp to its initial state to reuse it!
return typeof path === 'string' && regExp.test(path) ? pattern : null;
};
} catch (error) {
return NULL;
}
}
/**
* Simplified glob matching. Supports a subset of glob patterns:
* - * matches anything inside a path segment
* - ? matches 1 character inside a path segment
* - ** matches anything including an empty path segment
* - simple brace expansion ({js,ts} => js or ts)
* - character ranges (using [...])
*/
export function match(pattern: string | IRelativePattern, path: string): boolean;
export function match(expression: IExpression, path: string, hasSibling?: (name: string) => boolean): string /* the matching pattern */;
export function match(arg1: string | IExpression | IRelativePattern, path: string, hasSibling?: (name: string) => boolean): any {
if (!arg1 || typeof path !== 'string') {
return false;
}
return parse(<IExpression>arg1)(path, undefined, hasSibling);
}
/**
* Simplified glob matching. Supports a subset of glob patterns:
* - * matches anything inside a path segment
* - ? matches 1 character inside a path segment
* - ** matches anything including an empty path segment
* - simple brace expansion ({js,ts} => js or ts)
* - character ranges (using [...])
*/
export function parse(pattern: string | IRelativePattern, options?: IGlobOptions): ParsedPattern;
export function parse(expression: IExpression, options?: IGlobOptions): ParsedExpression;
export function parse(arg1: string | IExpression | IRelativePattern, options: IGlobOptions = {}): any {
if (!arg1) {
return FALSE;
}
// Glob with String
if (typeof arg1 === 'string' || isRelativePattern(arg1)) {
const parsedPattern = parsePattern(arg1 as string | IRelativePattern, options);
if (parsedPattern === NULL) {
return FALSE;
}
const resultPattern = function (path: string, basename: string) {
return !!parsedPattern(path, basename);
};
if (parsedPattern.allBasenames) {
(<ParsedStringPattern><any>resultPattern).allBasenames = parsedPattern.allBasenames;
}
if (parsedPattern.allPaths) {
(<ParsedStringPattern><any>resultPattern).allPaths = parsedPattern.allPaths;
}
return resultPattern;
}
// Glob with Expression
return parsedExpression(<IExpression>arg1, options);
}
export function hasSiblingPromiseFn(siblingsFn?: () => Promise<string[]>) {
if (!siblingsFn) {
return undefined;
}
let siblings: Promise<Record<string, true>>;
return (name: string) => {
if (!siblings) {
siblings = (siblingsFn() || Promise.resolve([]))
.then(list => list ? listToMap(list) : {});
}
return siblings.then(map => !!map[name]);
};
}
export function hasSiblingFn(siblingsFn?: () => string[]) {
if (!siblingsFn) {
return undefined;
}
let siblings: Record<string, true>;
return (name: string) => {
if (!siblings) {
const list = siblingsFn();
siblings = list ? listToMap(list) : {};
}
return !!siblings[name];
};
}
function listToMap(list: string[]) {
const map: Record<string, true> = {};
for (const key of list) {
map[key] = true;
}
return map;
}
export function isRelativePattern(obj: any): obj is IRelativePattern {
const rp = obj as IRelativePattern;
return rp && typeof rp.base === 'string' && typeof rp.pattern === 'string';
}
/**
* Same as `parse`, but the ParsedExpression is guaranteed to return a Promise
*/
export function parseToAsync(expression: IExpression, options?: IGlobOptions): ParsedExpression {
const parsedExpression = parse(expression, options);
return (path: string, basename?: string, hasSibling?: (name: string) => boolean | Promise<boolean>): string | null | Promise<string | null> => {
const result = parsedExpression(path, basename, hasSibling);
return isThenable(result) ? result : Promise.resolve(result);
};
}
export function getBasenameTerms(patternOrExpression: ParsedPattern | ParsedExpression): string[] {
return (<ParsedStringPattern>patternOrExpression).allBasenames || [];
}
export function getPathTerms(patternOrExpression: ParsedPattern | ParsedExpression): string[] {
return (<ParsedStringPattern>patternOrExpression).allPaths || [];
}
function parsedExpression(expression: IExpression, options: IGlobOptions): ParsedExpression {
const parsedPatterns = aggregateBasenameMatches(Object.getOwnPropertyNames(expression)
.map(pattern => parseExpressionPattern(pattern, expression[pattern], options))
.filter(pattern => pattern !== NULL));
const n = parsedPatterns.length;
if (!n) {
return NULL;
}
if (!parsedPatterns.some(parsedPattern => !!(<ParsedExpressionPattern>parsedPattern).requiresSiblings)) {
if (n === 1) {
return <ParsedStringPattern>parsedPatterns[0];
}
const resultExpression: ParsedStringPattern = function (path: string, basename: string) {
for (let i = 0, n = parsedPatterns.length; i < n; i++) {
// Pattern matches path
const result = (<ParsedStringPattern>parsedPatterns[i])(path, basename);
if (result) {
return result;
}
}
return null;
};
const withBasenames = arrays.first(parsedPatterns, pattern => !!(<ParsedStringPattern>pattern).allBasenames);
if (withBasenames) {
resultExpression.allBasenames = (<ParsedStringPattern>withBasenames).allBasenames;
}
const allPaths = parsedPatterns.reduce((all, current) => current.allPaths ? all.concat(current.allPaths) : all, <string[]>[]);
if (allPaths.length) {
resultExpression.allPaths = allPaths;
}
return resultExpression;
}
const resultExpression: ParsedStringPattern = function (path: string, basename: string, hasSibling?: (name: string) => boolean | Promise<boolean>) {
let name: string | undefined = undefined;
for (let i = 0, n = parsedPatterns.length; i < n; i++) {
// Pattern matches path
const parsedPattern = (<ParsedExpressionPattern>parsedPatterns[i]);
if (parsedPattern.requiresSiblings && hasSibling) {
if (!basename) {
basename = paths.basename(path);
}
if (!name) {
name = basename.substr(0, basename.length - paths.extname(path).length);
}
}
const result = parsedPattern(path, basename, name, hasSibling);
if (result) {
return result;
}
}
return null;
};
const withBasenames = arrays.first(parsedPatterns, pattern => !!(<ParsedStringPattern>pattern).allBasenames);
if (withBasenames) {
resultExpression.allBasenames = (<ParsedStringPattern>withBasenames).allBasenames;
}
const allPaths = parsedPatterns.reduce((all, current) => current.allPaths ? all.concat(current.allPaths) : all, <string[]>[]);
if (allPaths.length) {
resultExpression.allPaths = allPaths;
}
return resultExpression;
}
function parseExpressionPattern(pattern: string, value: any, options: IGlobOptions): (ParsedStringPattern | ParsedExpressionPattern) {
if (value === false) {
return NULL; // pattern is disabled
}
const parsedPattern = parsePattern(pattern, options);
if (parsedPattern === NULL) {
return NULL;
}
// Expression Pattern is <boolean>
if (typeof value === 'boolean') {
return parsedPattern;
}
// Expression Pattern is <SiblingClause>
if (value) {
const when = (<SiblingClause>value).when;
if (typeof when === 'string') {
const result: ParsedExpressionPattern = (path: string, basename: string, name: string, hasSibling: (name: string) => boolean | Promise<boolean>) => {
if (!hasSibling || !parsedPattern(path, basename)) {
return null;
}
const clausePattern = when.replace('$(basename)', name);
const matched = hasSibling(clausePattern);
return isThenable(matched) ?
matched.then(m => m ? pattern : null) :
matched ? pattern : null;
};
result.requiresSiblings = true;
return result;
}
}
// Expression is Anything
return parsedPattern;
}
function aggregateBasenameMatches(parsedPatterns: Array<ParsedStringPattern | ParsedExpressionPattern>, result?: string): Array<ParsedStringPattern | ParsedExpressionPattern> {
const basenamePatterns = parsedPatterns.filter(parsedPattern => !!(<ParsedStringPattern>parsedPattern).basenames);
if (basenamePatterns.length < 2) {
return parsedPatterns;
}
const basenames = basenamePatterns.reduce<string[]>((all, current) => {
const basenames = (<ParsedStringPattern>current).basenames;
return basenames ? all.concat(basenames) : all;
}, <string[]>[]);
let patterns: string[];
if (result) {
patterns = [];
for (let i = 0, n = basenames.length; i < n; i++) {
patterns.push(result);
}
} else {
patterns = basenamePatterns.reduce((all, current) => {
const patterns = (<ParsedStringPattern>current).patterns;
return patterns ? all.concat(patterns) : all;
}, <string[]>[]);
}
const aggregate: ParsedStringPattern = function (path, basename) {
if (typeof path !== 'string') {
return null;
}
if (!basename) {
let i: number;
for (i = path.length; i > 0; i--) {
const ch = path.charCodeAt(i - 1);
if (ch === CharCode.Slash || ch === CharCode.Backslash) {
break;
}
}
basename = path.substr(i);
}
const index = basenames.indexOf(basename);
return index !== -1 ? patterns[index] : null;
};
aggregate.basenames = basenames;
aggregate.patterns = patterns;
aggregate.allBasenames = basenames;
const aggregatedPatterns = parsedPatterns.filter(parsedPattern => !(<ParsedStringPattern>parsedPattern).basenames);
aggregatedPatterns.push(aggregate);
return aggregatedPatterns;
}
| src/vs/base/common/glob.ts | 0 | https://github.com/microsoft/vscode/commit/bbff11633c7e56e7fd5d16cc20daa9a3284afbfe | [
0.00027666703681461513,
0.00017446785932406783,
0.00016447657253593206,
0.00017207830387633294,
0.000015507268471992575
]
|
{
"id": 5,
"code_window": [
"\t}\n",
"\n",
"\tpublic setWholeWords(value: boolean): void {\n",
"\t\tthis.wholeWords.checked = value;\n",
"\t\tthis.setInputWidth();\n",
"\t}\n",
"\n",
"\tpublic getRegex(): boolean {\n",
"\t\treturn this.regex.checked;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/base/browser/ui/findinput/findInput.ts",
"type": "replace",
"edit_start_line_idx": 251
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
.search-view .search-widgets-container {
margin: 0px 9px 0 2px;
padding-top: 6px;
}
.search-view .search-widget .toggle-replace-button {
position: absolute;
top: 0;
left: 0;
width: 16px;
height: 100%;
box-sizing: border-box;
background-position: center center;
background-repeat: no-repeat;
cursor: pointer;
}
.search-view .search-widget .search-container,
.search-view .search-widget .replace-container {
margin-left: 17px;
}
.search-view .search-widget .monaco-inputbox > .wrapper {
height: 100%;
}
.search-view .search-widget .monaco-inputbox > .wrapper > .mirror,
.search-view .search-widget .monaco-inputbox > .wrapper > textarea.input {
padding: 3px;
padding-left: 4px;
}
.search-view .search-widget .monaco-inputbox > .wrapper > .mirror {
max-height: 134px;
}
.search-view .search-widget .monaco-inputbox > .wrapper > textarea.input {
overflow: initial;
height: 24px; /* set initial height before measure */
}
.search-view .monaco-inputbox > .wrapper > textarea.input::-webkit-scrollbar {
display: none;
}
.search-view .search-widget .monaco-findInput {
display: inline-block;
vertical-align: middle;
}
.search-view .search-widget .replace-container {
margin-top: 6px;
position: relative;
display: inline-flex;
}
.search-view .search-widget .replace-container.disabled {
display: none;
}
.search-view .search-widget .replace-container .monaco-action-bar {
margin-left: 3px;
}
.search-view .search-widget .replace-container .monaco-action-bar {
height: 25px;
}
.search-view .search-widget .replace-container .monaco-action-bar .action-item .icon {
background-repeat: no-repeat;
width: 20px;
height: 25px;
}
.search-view .query-details {
min-height: 1em;
position: relative;
margin: 0 0 0 17px;
}
.search-view .query-details .more {
position: absolute;
margin-right: 0.3em;
right: 0;
cursor: pointer;
width: 16px;
height: 13px;
z-index: 2; /* Force it above the search results message, which has a negative top margin */
}
.hc-black .monaco-workbench .search-view .query-details .more,
.vs-dark .monaco-workbench .search-view .query-details .more {
background: url('ellipsis-inverse.svg') top center no-repeat;
}
.vs .monaco-workbench .search-view .query-details .more {
background: url('ellipsis.svg') top center no-repeat;
}
.search-view .query-details .file-types {
display: none;
}
.search-view .query-details .file-types > .monaco-inputbox {
width: 100%;
height: 25px;
}
.search-view .query-details.more .file-types {
display: inherit;
}
.search-view .query-details.more .file-types:last-child {
padding-bottom: 10px;
}
.search-view .query-details.more h4 {
text-overflow: ellipsis;
overflow: hidden;
white-space: nowrap;
padding: 4px 0 0;
margin: 0;
font-size: 11px;
font-weight: normal;
}
.search-view .messages {
margin-top: -5px;
cursor: default;
}
.search-view .message {
padding-left: 22px;
padding-right: 22px;
padding-top: 0px;
}
.search-view .message p:first-child {
margin-top: 0px;
margin-bottom: 0px;
padding-bottom: 4px;
user-select: text;
}
.search-view .foldermatch,
.search-view .filematch {
display: flex;
position: relative;
line-height: 22px;
padding: 0;
}
.search-view:not(.wide) .foldermatch .monaco-icon-label,
.search-view:not(.wide) .filematch .monaco-icon-label {
flex: 1;
}
.search-view:not(.wide) .monaco-list .monaco-list-row:hover:not(.highlighted) .foldermatch .monaco-icon-label,
.search-view:not(.wide) .monaco-list .monaco-list-row.focused .foldermatch .monaco-icon-label,
.search-view:not(.wide) .monaco-list .monaco-list-row:hover:not(.highlighted) .filematch .monaco-icon-label,
.search-view:not(.wide) .monaco-list .monaco-list-row.focused .filematch .monaco-icon-label {
flex: 1;
}
.search-view.wide .foldermatch .badge,
.search-view.wide .filematch .badge {
margin-left: 10px;
}
.search-view .linematch {
position: relative;
line-height: 22px;
display: flex;
overflow: hidden;
}
.search-view .linematch > .match {
overflow: hidden;
text-overflow: ellipsis;
white-space: pre;
}
.search-view .linematch .matchLineNum {
margin-left: 7px;
margin-right: 4px;
opacity: .7;
font-size: 0.9em;
display: none;
}
.search-view .linematch .matchLineNum.show {
display: block;
}
.search-view.wide .monaco-list .monaco-list-row .foldermatch .actionBarContainer,
.search-view.wide .monaco-list .monaco-list-row .filematch .actionBarContainer,
.search-view .monaco-list .monaco-list-row .linematch .actionBarContainer {
flex: 1 0 auto;
}
.search-view:not(.wide) .monaco-list .monaco-list-row .foldermatch .actionBarContainer,
.search-view:not(.wide) .monaco-list .monaco-list-row .filematch .actionBarContainer {
flex: 0 0 auto;
}
.search-view.actions-right .monaco-list .monaco-list-row .foldermatch .actionBarContainer,
.search-view.actions-right .monaco-list .monaco-list-row .filematch .actionBarContainer,
.search-view.actions-right .monaco-list .monaco-list-row .linematch .actionBarContainer,
.search-view:not(.wide) .monaco-list .monaco-list-row .linematch .actionBarContainer {
text-align: right;
}
.search-view .monaco-list .monaco-list-row .monaco-action-bar {
line-height: 1em;
display: none;
padding: 0 0.8em 0 0.4em;
}
.search-view .monaco-list .monaco-list-row .monaco-action-bar .action-item {
margin: 0;
}
.search-view .monaco-list .monaco-list-row:hover:not(.highlighted) .monaco-action-bar,
.search-view .monaco-list .monaco-list-row.focused .monaco-action-bar {
display: inline-block;
}
.search-view .monaco-list .monaco-list-row .monaco-action-bar .action-label {
margin-right: 0.2em;
margin-top: 4px;
background-repeat: no-repeat;
width: 16px;
height: 16px;
}
/* Adjusts spacing in high contrast mode so that actions are vertically centered */
.hc-black .monaco-list .monaco-list-row .monaco-action-bar .action-label {
margin-top: 2px;
}
.search-view .action-remove {
background: url("action-remove.svg") center center no-repeat;
}
.search-view .action-replace {
background-image: url('replace.svg');
}
.search-view .action-replace-all {
background: url('replace-all.svg') center center no-repeat;
}
.hc-black .search-view .action-replace,
.vs-dark .search-view .action-replace {
background-image: url('replace-inverse.svg');
}
.hc-black .search-view .action-replace-all,
.vs-dark .search-view .action-replace-all {
background: url('replace-all-inverse.svg') center center no-repeat;
}
.search-view .monaco-count-badge {
margin-right: 12px;
}
.search-view:not(.wide) > .results > .monaco-list .monaco-list-row:hover .filematch .monaco-count-badge,
.search-view:not(.wide) > .results > .monaco-list .monaco-list-row:hover .foldermatch .monaco-count-badge,
.search-view:not(.wide) > .results > .monaco-list .monaco-list-row:hover .linematch .monaco-count-badge,
.search-view:not(.wide) > .results > .monaco-list .monaco-list-row.focused .filematch .monaco-count-badge,
.search-view:not(.wide) > .results > .monaco-list .monaco-list-row.focused .foldermatch .monaco-count-badge,
.search-view:not(.wide) > .results > .monaco-list .monaco-list-row.focused .linematch .monaco-count-badge {
display: none;
}
.monaco-workbench .search-action.refresh {
background: url('Refresh.svg') center center no-repeat;
}
.vs-dark .monaco-workbench .search-action.refresh,
.hc-black .monaco-workbench .search-action.refresh {
background: url('Refresh_inverse.svg') center center no-repeat;
}
.monaco-workbench .search-action.collapse {
background: url('CollapseAll.svg') center center no-repeat;
}
.vs-dark .monaco-workbench .search-action.collapse,
.hc-black .monaco-workbench .search-action.collapse {
background: url('CollapseAll_inverse.svg') center center no-repeat;
}
.monaco-workbench .search-action.clear-search-results {
background: url('clear-search-results.svg') center center no-repeat;
}
.vs-dark .monaco-workbench .search-action.clear-search-results,
.hc-black .monaco-workbench .search-action.clear-search-results {
background: url('clear-search-results-dark.svg') center center no-repeat;
}
.monaco-workbench .search-action.cancel-search {
background: url('stop.svg') center center no-repeat;
}
.vs-dark .monaco-workbench .search-action.cancel-search,
.hc-black .monaco-workbench .search-action.cancel-search {
background: url('stop-inverse.svg') center center no-repeat;
}
.vs .monaco-workbench .search-view .query-details .file-types .controls>.monaco-custom-checkbox.useExcludesAndIgnoreFiles {
background: url('excludeSettings.svg') center center no-repeat;
}
.vs-dark .monaco-workbench .search-view .query-details .file-types .controls>.monaco-custom-checkbox.useExcludesAndIgnoreFiles,
.hc-black .monaco-workbench .search-view .query-details .file-types .controls>.monaco-custom-checkbox.useExcludesAndIgnoreFiles {
background: url('excludeSettings-dark.svg') center center no-repeat;
}
.search-view .replace.findInFileMatch {
text-decoration: line-through;
}
.search-view .findInFileMatch,
.search-view .replaceMatch {
white-space: pre;
}
.hc-black .monaco-workbench .search-view .replaceMatch,
.hc-black .monaco-workbench .search-view .findInFileMatch {
background: none !important;
box-sizing: border-box;
}
.monaco-workbench .search-view a.prominent {
text-decoration: underline;
}
/* Theming */
.vs .search-view .search-widget .toggle-replace-button:hover {
background-color: rgba(0, 0, 0, 0.1) !important;
}
.vs-dark .search-view .search-widget .toggle-replace-button:hover {
background-color: rgba(255, 255, 255, 0.1) !important;
}
.vs .search-view .search-widget .toggle-replace-button.collapse {
background-image: url('expando-collapsed.svg');
}
.vs .search-view .search-widget .toggle-replace-button.expand {
background-image: url('expando-expanded.svg');
}
.vs-dark .search-view .action-remove,
.hc-black .search-view .action-remove {
background: url("action-remove-dark.svg") center center no-repeat;
}
.vs-dark .search-view .message {
opacity: .5;
}
.vs-dark .search-view .foldermatch,
.vs-dark .search-view .filematch {
padding: 0;
}
.vs-dark .search-view .search-widget .toggle-replace-button.expand,
.hc-black .search-view .search-widget .toggle-replace-button.expand {
background-image: url('expando-expanded-dark.svg');
}
.vs-dark .search-view .search-widget .toggle-replace-button.collapse,
.hc-black .search-view .search-widget .toggle-replace-button.collapse {
background-image: url('expando-collapsed-dark.svg');
}
/* High Contrast Theming */
.hc-black .monaco-workbench .search-view .foldermatch,
.hc-black .monaco-workbench .search-view .filematch,
.hc-black .monaco-workbench .search-view .linematch {
line-height: 20px;
}
.vs .panel .search-view .monaco-inputbox {
border: 1px solid #ddd;
}
| src/vs/workbench/contrib/search/browser/media/searchview.css | 1 | https://github.com/microsoft/vscode/commit/bbff11633c7e56e7fd5d16cc20daa9a3284afbfe | [
0.0001766536443028599,
0.00017234496772289276,
0.00016374237020500004,
0.0001725675247143954,
0.0000026180273380305152
]
|
{
"id": 5,
"code_window": [
"\t}\n",
"\n",
"\tpublic setWholeWords(value: boolean): void {\n",
"\t\tthis.wholeWords.checked = value;\n",
"\t\tthis.setInputWidth();\n",
"\t}\n",
"\n",
"\tpublic getRegex(): boolean {\n",
"\t\treturn this.regex.checked;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/base/browser/ui/findinput/findInput.ts",
"type": "replace",
"edit_start_line_idx": 251
} | {
"name": "gulp",
"publisher": "vscode",
"description": "%description%",
"displayName": "%displayName%",
"version": "1.0.0",
"icon": "images/gulp.png",
"engines": {
"vscode": "*"
},
"categories": [
"Other"
],
"scripts": {
"compile": "gulp compile-extension:gulp",
"watch": "gulp watch-extension:gulp"
},
"dependencies": {
"vscode-nls": "^4.0.0"
},
"devDependencies": {
"@types/node": "^10.12.21"
},
"main": "./out/main",
"activationEvents": [
"onCommand:workbench.action.tasks.runTask"
],
"contributes": {
"configuration": {
"id": "gulp",
"type": "object",
"title": "Gulp",
"properties": {
"gulp.autoDetect": {
"scope": "resource",
"type": "string",
"enum": [
"off",
"on"
],
"default": "on",
"description": "%config.gulp.autoDetect%"
}
}
},
"taskDefinitions": [
{
"type": "gulp",
"required": [
"task"
],
"properties": {
"task": {
"type": "string",
"description": "%gulp.taskDefinition.type.description%"
},
"file": {
"type": "string",
"description": "%gulp.taskDefinition.file.description%"
}
}
}
]
}
}
| extensions/gulp/package.json | 0 | https://github.com/microsoft/vscode/commit/bbff11633c7e56e7fd5d16cc20daa9a3284afbfe | [
0.00017663749167695642,
0.00017540396947879344,
0.00017428422870580107,
0.00017508490418549627,
8.233291168835422e-7
]
|
{
"id": 5,
"code_window": [
"\t}\n",
"\n",
"\tpublic setWholeWords(value: boolean): void {\n",
"\t\tthis.wholeWords.checked = value;\n",
"\t\tthis.setInputWidth();\n",
"\t}\n",
"\n",
"\tpublic getRegex(): boolean {\n",
"\t\treturn this.regex.checked;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/base/browser/ui/findinput/findInput.ts",
"type": "replace",
"edit_start_line_idx": 251
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
export interface ICommonContextMenuItem {
label?: string;
type?: 'normal' | 'separator' | 'submenu' | 'checkbox' | 'radio';
accelerator?: string;
enabled?: boolean;
visible?: boolean;
checked?: boolean;
}
export interface ISerializableContextMenuItem extends ICommonContextMenuItem {
id: number;
submenu?: ISerializableContextMenuItem[];
}
export interface IContextMenuItem extends ICommonContextMenuItem {
click?: (event: IContextMenuEvent) => void;
submenu?: IContextMenuItem[];
}
export interface IContextMenuEvent {
shiftKey?: boolean;
ctrlKey?: boolean;
altKey?: boolean;
metaKey?: boolean;
}
export interface IPopupOptions {
x?: number;
y?: number;
positioningItem?: number;
onHide?: () => void;
}
export const CONTEXT_MENU_CHANNEL = 'vscode:contextmenu';
export const CONTEXT_MENU_CLOSE_CHANNEL = 'vscode:onCloseContextMenu'; | src/vs/base/parts/contextmenu/common/contextmenu.ts | 0 | https://github.com/microsoft/vscode/commit/bbff11633c7e56e7fd5d16cc20daa9a3284afbfe | [
0.00017485582793597132,
0.00017098887474276125,
0.00016826242790557444,
0.00017091514018829912,
0.0000023365498691418907
]
|
{
"id": 5,
"code_window": [
"\t}\n",
"\n",
"\tpublic setWholeWords(value: boolean): void {\n",
"\t\tthis.wholeWords.checked = value;\n",
"\t\tthis.setInputWidth();\n",
"\t}\n",
"\n",
"\tpublic getRegex(): boolean {\n",
"\t\treturn this.regex.checked;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/base/browser/ui/findinput/findInput.ts",
"type": "replace",
"edit_start_line_idx": 251
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import 'vs/css!./terminalFindWidget';
import { SimpleFindWidget } from 'vs/editor/contrib/find/simpleFindWidget';
import { IContextViewService } from 'vs/platform/contextview/browser/contextView';
import { ITerminalService, KEYBINDING_CONTEXT_TERMINAL_FIND_WIDGET_INPUT_FOCUSED, KEYBINDING_CONTEXT_TERMINAL_FIND_WIDGET_FOCUSED } from 'vs/workbench/contrib/terminal/common/terminal';
import { IContextKeyService, IContextKey } from 'vs/platform/contextkey/common/contextkey';
import { FindReplaceState } from 'vs/editor/contrib/find/findState';
export class TerminalFindWidget extends SimpleFindWidget {
protected _findInputFocused: IContextKey<boolean>;
protected _findWidgetFocused: IContextKey<boolean>;
constructor(
findState: FindReplaceState,
@IContextViewService _contextViewService: IContextViewService,
@IContextKeyService private readonly _contextKeyService: IContextKeyService,
@ITerminalService private readonly _terminalService: ITerminalService
) {
super(_contextViewService, _contextKeyService, findState, true);
this._register(findState.onFindReplaceStateChange(() => {
this.show();
}));
this._findInputFocused = KEYBINDING_CONTEXT_TERMINAL_FIND_WIDGET_INPUT_FOCUSED.bindTo(this._contextKeyService);
this._findWidgetFocused = KEYBINDING_CONTEXT_TERMINAL_FIND_WIDGET_FOCUSED.bindTo(this._contextKeyService);
}
public find(previous: boolean) {
const instance = this._terminalService.getActiveInstance();
if (instance !== null) {
if (previous) {
instance.findPrevious(this.inputValue, { regex: this._getRegexValue(), wholeWord: this._getWholeWordValue(), caseSensitive: this._getCaseSensitiveValue() });
} else {
instance.findNext(this.inputValue, { regex: this._getRegexValue(), wholeWord: this._getWholeWordValue(), caseSensitive: this._getCaseSensitiveValue() });
}
}
}
public hide() {
super.hide();
const instance = this._terminalService.getActiveInstance();
if (instance) {
instance.focus();
}
}
protected onInputChanged() {
// Ignore input changes for now
const instance = this._terminalService.getActiveInstance();
if (instance !== null) {
instance.findNext(this.inputValue, { regex: this._getRegexValue(), wholeWord: this._getWholeWordValue(), caseSensitive: this._getCaseSensitiveValue(), incremental: true });
}
}
protected onFocusTrackerFocus() {
const instance = this._terminalService.getActiveInstance();
if (instance) {
instance.notifyFindWidgetFocusChanged(true);
}
this._findWidgetFocused.set(true);
}
protected onFocusTrackerBlur() {
const instance = this._terminalService.getActiveInstance();
if (instance) {
instance.notifyFindWidgetFocusChanged(false);
}
this._findWidgetFocused.reset();
}
protected onFindInputFocusTrackerFocus() {
this._findInputFocused.set(true);
}
protected onFindInputFocusTrackerBlur() {
this._findInputFocused.reset();
}
} | src/vs/workbench/contrib/terminal/browser/terminalFindWidget.ts | 0 | https://github.com/microsoft/vscode/commit/bbff11633c7e56e7fd5d16cc20daa9a3284afbfe | [
0.9987437129020691,
0.22206205129623413,
0.00016756021068431437,
0.0001738026476232335,
0.4151063859462738
]
|
{
"id": 6,
"code_window": [
"\t}\n",
"\n",
"\tpublic setRegex(value: boolean): void {\n",
"\t\tthis.regex.checked = value;\n",
"\t\tthis.setInputWidth();\n",
"\t\tthis.validate();\n",
"\t}\n",
"\n",
"\tpublic focusOnCaseSensitive(): void {\n",
"\t\tthis.caseSensitive.focus();\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/base/browser/ui/findinput/findInput.ts",
"type": "replace",
"edit_start_line_idx": 260
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
.search-view .search-widgets-container {
margin: 0px 9px 0 2px;
padding-top: 6px;
}
.search-view .search-widget .toggle-replace-button {
position: absolute;
top: 0;
left: 0;
width: 16px;
height: 100%;
box-sizing: border-box;
background-position: center center;
background-repeat: no-repeat;
cursor: pointer;
}
.search-view .search-widget .search-container,
.search-view .search-widget .replace-container {
margin-left: 17px;
}
.search-view .search-widget .monaco-inputbox > .wrapper {
height: 100%;
}
.search-view .search-widget .monaco-inputbox > .wrapper > .mirror,
.search-view .search-widget .monaco-inputbox > .wrapper > textarea.input {
padding: 3px;
padding-left: 4px;
}
.search-view .search-widget .monaco-inputbox > .wrapper > .mirror {
max-height: 134px;
}
.search-view .search-widget .monaco-inputbox > .wrapper > textarea.input {
overflow: initial;
height: 24px; /* set initial height before measure */
}
.search-view .monaco-inputbox > .wrapper > textarea.input::-webkit-scrollbar {
display: none;
}
.search-view .search-widget .monaco-findInput {
display: inline-block;
vertical-align: middle;
}
.search-view .search-widget .replace-container {
margin-top: 6px;
position: relative;
display: inline-flex;
}
.search-view .search-widget .replace-container.disabled {
display: none;
}
.search-view .search-widget .replace-container .monaco-action-bar {
margin-left: 3px;
}
.search-view .search-widget .replace-container .monaco-action-bar {
height: 25px;
}
.search-view .search-widget .replace-container .monaco-action-bar .action-item .icon {
background-repeat: no-repeat;
width: 20px;
height: 25px;
}
.search-view .query-details {
min-height: 1em;
position: relative;
margin: 0 0 0 17px;
}
.search-view .query-details .more {
position: absolute;
margin-right: 0.3em;
right: 0;
cursor: pointer;
width: 16px;
height: 13px;
z-index: 2; /* Force it above the search results message, which has a negative top margin */
}
.hc-black .monaco-workbench .search-view .query-details .more,
.vs-dark .monaco-workbench .search-view .query-details .more {
background: url('ellipsis-inverse.svg') top center no-repeat;
}
.vs .monaco-workbench .search-view .query-details .more {
background: url('ellipsis.svg') top center no-repeat;
}
.search-view .query-details .file-types {
display: none;
}
.search-view .query-details .file-types > .monaco-inputbox {
width: 100%;
height: 25px;
}
.search-view .query-details.more .file-types {
display: inherit;
}
.search-view .query-details.more .file-types:last-child {
padding-bottom: 10px;
}
.search-view .query-details.more h4 {
text-overflow: ellipsis;
overflow: hidden;
white-space: nowrap;
padding: 4px 0 0;
margin: 0;
font-size: 11px;
font-weight: normal;
}
.search-view .messages {
margin-top: -5px;
cursor: default;
}
.search-view .message {
padding-left: 22px;
padding-right: 22px;
padding-top: 0px;
}
.search-view .message p:first-child {
margin-top: 0px;
margin-bottom: 0px;
padding-bottom: 4px;
user-select: text;
}
.search-view .foldermatch,
.search-view .filematch {
display: flex;
position: relative;
line-height: 22px;
padding: 0;
}
.search-view:not(.wide) .foldermatch .monaco-icon-label,
.search-view:not(.wide) .filematch .monaco-icon-label {
flex: 1;
}
.search-view:not(.wide) .monaco-list .monaco-list-row:hover:not(.highlighted) .foldermatch .monaco-icon-label,
.search-view:not(.wide) .monaco-list .monaco-list-row.focused .foldermatch .monaco-icon-label,
.search-view:not(.wide) .monaco-list .monaco-list-row:hover:not(.highlighted) .filematch .monaco-icon-label,
.search-view:not(.wide) .monaco-list .monaco-list-row.focused .filematch .monaco-icon-label {
flex: 1;
}
.search-view.wide .foldermatch .badge,
.search-view.wide .filematch .badge {
margin-left: 10px;
}
.search-view .linematch {
position: relative;
line-height: 22px;
display: flex;
overflow: hidden;
}
.search-view .linematch > .match {
overflow: hidden;
text-overflow: ellipsis;
white-space: pre;
}
.search-view .linematch .matchLineNum {
margin-left: 7px;
margin-right: 4px;
opacity: .7;
font-size: 0.9em;
display: none;
}
.search-view .linematch .matchLineNum.show {
display: block;
}
.search-view.wide .monaco-list .monaco-list-row .foldermatch .actionBarContainer,
.search-view.wide .monaco-list .monaco-list-row .filematch .actionBarContainer,
.search-view .monaco-list .monaco-list-row .linematch .actionBarContainer {
flex: 1 0 auto;
}
.search-view:not(.wide) .monaco-list .monaco-list-row .foldermatch .actionBarContainer,
.search-view:not(.wide) .monaco-list .monaco-list-row .filematch .actionBarContainer {
flex: 0 0 auto;
}
.search-view.actions-right .monaco-list .monaco-list-row .foldermatch .actionBarContainer,
.search-view.actions-right .monaco-list .monaco-list-row .filematch .actionBarContainer,
.search-view.actions-right .monaco-list .monaco-list-row .linematch .actionBarContainer,
.search-view:not(.wide) .monaco-list .monaco-list-row .linematch .actionBarContainer {
text-align: right;
}
.search-view .monaco-list .monaco-list-row .monaco-action-bar {
line-height: 1em;
display: none;
padding: 0 0.8em 0 0.4em;
}
.search-view .monaco-list .monaco-list-row .monaco-action-bar .action-item {
margin: 0;
}
.search-view .monaco-list .monaco-list-row:hover:not(.highlighted) .monaco-action-bar,
.search-view .monaco-list .monaco-list-row.focused .monaco-action-bar {
display: inline-block;
}
.search-view .monaco-list .monaco-list-row .monaco-action-bar .action-label {
margin-right: 0.2em;
margin-top: 4px;
background-repeat: no-repeat;
width: 16px;
height: 16px;
}
/* Adjusts spacing in high contrast mode so that actions are vertically centered */
.hc-black .monaco-list .monaco-list-row .monaco-action-bar .action-label {
margin-top: 2px;
}
.search-view .action-remove {
background: url("action-remove.svg") center center no-repeat;
}
.search-view .action-replace {
background-image: url('replace.svg');
}
.search-view .action-replace-all {
background: url('replace-all.svg') center center no-repeat;
}
.hc-black .search-view .action-replace,
.vs-dark .search-view .action-replace {
background-image: url('replace-inverse.svg');
}
.hc-black .search-view .action-replace-all,
.vs-dark .search-view .action-replace-all {
background: url('replace-all-inverse.svg') center center no-repeat;
}
.search-view .monaco-count-badge {
margin-right: 12px;
}
.search-view:not(.wide) > .results > .monaco-list .monaco-list-row:hover .filematch .monaco-count-badge,
.search-view:not(.wide) > .results > .monaco-list .monaco-list-row:hover .foldermatch .monaco-count-badge,
.search-view:not(.wide) > .results > .monaco-list .monaco-list-row:hover .linematch .monaco-count-badge,
.search-view:not(.wide) > .results > .monaco-list .monaco-list-row.focused .filematch .monaco-count-badge,
.search-view:not(.wide) > .results > .monaco-list .monaco-list-row.focused .foldermatch .monaco-count-badge,
.search-view:not(.wide) > .results > .monaco-list .monaco-list-row.focused .linematch .monaco-count-badge {
display: none;
}
.monaco-workbench .search-action.refresh {
background: url('Refresh.svg') center center no-repeat;
}
.vs-dark .monaco-workbench .search-action.refresh,
.hc-black .monaco-workbench .search-action.refresh {
background: url('Refresh_inverse.svg') center center no-repeat;
}
.monaco-workbench .search-action.collapse {
background: url('CollapseAll.svg') center center no-repeat;
}
.vs-dark .monaco-workbench .search-action.collapse,
.hc-black .monaco-workbench .search-action.collapse {
background: url('CollapseAll_inverse.svg') center center no-repeat;
}
.monaco-workbench .search-action.clear-search-results {
background: url('clear-search-results.svg') center center no-repeat;
}
.vs-dark .monaco-workbench .search-action.clear-search-results,
.hc-black .monaco-workbench .search-action.clear-search-results {
background: url('clear-search-results-dark.svg') center center no-repeat;
}
.monaco-workbench .search-action.cancel-search {
background: url('stop.svg') center center no-repeat;
}
.vs-dark .monaco-workbench .search-action.cancel-search,
.hc-black .monaco-workbench .search-action.cancel-search {
background: url('stop-inverse.svg') center center no-repeat;
}
.vs .monaco-workbench .search-view .query-details .file-types .controls>.monaco-custom-checkbox.useExcludesAndIgnoreFiles {
background: url('excludeSettings.svg') center center no-repeat;
}
.vs-dark .monaco-workbench .search-view .query-details .file-types .controls>.monaco-custom-checkbox.useExcludesAndIgnoreFiles,
.hc-black .monaco-workbench .search-view .query-details .file-types .controls>.monaco-custom-checkbox.useExcludesAndIgnoreFiles {
background: url('excludeSettings-dark.svg') center center no-repeat;
}
.search-view .replace.findInFileMatch {
text-decoration: line-through;
}
.search-view .findInFileMatch,
.search-view .replaceMatch {
white-space: pre;
}
.hc-black .monaco-workbench .search-view .replaceMatch,
.hc-black .monaco-workbench .search-view .findInFileMatch {
background: none !important;
box-sizing: border-box;
}
.monaco-workbench .search-view a.prominent {
text-decoration: underline;
}
/* Theming */
.vs .search-view .search-widget .toggle-replace-button:hover {
background-color: rgba(0, 0, 0, 0.1) !important;
}
.vs-dark .search-view .search-widget .toggle-replace-button:hover {
background-color: rgba(255, 255, 255, 0.1) !important;
}
.vs .search-view .search-widget .toggle-replace-button.collapse {
background-image: url('expando-collapsed.svg');
}
.vs .search-view .search-widget .toggle-replace-button.expand {
background-image: url('expando-expanded.svg');
}
.vs-dark .search-view .action-remove,
.hc-black .search-view .action-remove {
background: url("action-remove-dark.svg") center center no-repeat;
}
.vs-dark .search-view .message {
opacity: .5;
}
.vs-dark .search-view .foldermatch,
.vs-dark .search-view .filematch {
padding: 0;
}
.vs-dark .search-view .search-widget .toggle-replace-button.expand,
.hc-black .search-view .search-widget .toggle-replace-button.expand {
background-image: url('expando-expanded-dark.svg');
}
.vs-dark .search-view .search-widget .toggle-replace-button.collapse,
.hc-black .search-view .search-widget .toggle-replace-button.collapse {
background-image: url('expando-collapsed-dark.svg');
}
/* High Contrast Theming */
.hc-black .monaco-workbench .search-view .foldermatch,
.hc-black .monaco-workbench .search-view .filematch,
.hc-black .monaco-workbench .search-view .linematch {
line-height: 20px;
}
.vs .panel .search-view .monaco-inputbox {
border: 1px solid #ddd;
}
| src/vs/workbench/contrib/search/browser/media/searchview.css | 1 | https://github.com/microsoft/vscode/commit/bbff11633c7e56e7fd5d16cc20daa9a3284afbfe | [
0.00017585956084076315,
0.00017163448501378298,
0.00016644013521727175,
0.0001716960105113685,
0.000002055576032944373
]
|
{
"id": 6,
"code_window": [
"\t}\n",
"\n",
"\tpublic setRegex(value: boolean): void {\n",
"\t\tthis.regex.checked = value;\n",
"\t\tthis.setInputWidth();\n",
"\t\tthis.validate();\n",
"\t}\n",
"\n",
"\tpublic focusOnCaseSensitive(): void {\n",
"\t\tthis.caseSensitive.focus();\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/base/browser/ui/findinput/findInput.ts",
"type": "replace",
"edit_start_line_idx": 260
} | {
"name": "code-oss-dev-build",
"version": "1.0.0",
"devDependencies": {
"@types/ansi-colors": "^3.2.0",
"@types/azure": "0.9.19",
"@types/debounce": "^1.0.0",
"@types/documentdb": "1.10.2",
"@types/fancy-log": "^1.3.0",
"@types/glob": "^7.1.1",
"@types/gulp": "^4.0.5",
"@types/gulp-concat": "^0.0.32",
"@types/gulp-filter": "^3.0.32",
"@types/gulp-json-editor": "^2.2.31",
"@types/gulp-rename": "^0.0.33",
"@types/gulp-sourcemaps": "^0.0.32",
"@types/gulp-uglify": "^3.0.5",
"@types/mime": "0.0.29",
"@types/minimatch": "^3.0.3",
"@types/minimist": "^1.2.0",
"@types/mocha": "2.2.39",
"@types/node": "8.0.33",
"@types/pump": "^1.0.1",
"@types/request": "^2.47.0",
"@types/rimraf": "^2.0.2",
"@types/through": "^0.0.29",
"@types/through2": "^2.0.34",
"@types/uglify-es": "^3.0.0",
"@types/underscore": "^1.8.9",
"@types/xml2js": "0.0.33",
"applicationinsights": "1.0.6",
"azure-storage": "^2.1.0",
"documentdb": "1.13.0",
"github-releases": "^0.4.1",
"gulp-bom": "^1.0.0",
"gulp-sourcemaps": "^1.11.0",
"iconv-lite": "0.4.23",
"mime": "^1.3.4",
"minimist": "^1.2.0",
"request": "^2.85.0",
"tslint": "^5.9.1",
"typescript": "3.3.1",
"vsce": "1.48.0",
"xml2js": "^0.4.17"
},
"scripts": {
"compile": "tsc -p tsconfig.build.json",
"watch": "tsc -p tsconfig.build.json --watch",
"postinstall": "npm run compile",
"npmCheckJs": "tsc --noEmit"
}
} | build/package.json | 0 | https://github.com/microsoft/vscode/commit/bbff11633c7e56e7fd5d16cc20daa9a3284afbfe | [
0.00017781378119252622,
0.0001726455520838499,
0.00016999684157781303,
0.00017187408229801804,
0.000002497513605703716
]
|
{
"id": 6,
"code_window": [
"\t}\n",
"\n",
"\tpublic setRegex(value: boolean): void {\n",
"\t\tthis.regex.checked = value;\n",
"\t\tthis.setInputWidth();\n",
"\t\tthis.validate();\n",
"\t}\n",
"\n",
"\tpublic focusOnCaseSensitive(): void {\n",
"\t\tthis.caseSensitive.focus();\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/base/browser/ui/findinput/findInput.ts",
"type": "replace",
"edit_start_line_idx": 260
} | {
"displayName": "HLSL Language Basics",
"description": "Provides syntax highlighting and bracket matching in HLSL files."
} | extensions/hlsl/package.nls.json | 0 | https://github.com/microsoft/vscode/commit/bbff11633c7e56e7fd5d16cc20daa9a3284afbfe | [
0.00017261007451452315,
0.00017261007451452315,
0.00017261007451452315,
0.00017261007451452315,
0
]
|
{
"id": 6,
"code_window": [
"\t}\n",
"\n",
"\tpublic setRegex(value: boolean): void {\n",
"\t\tthis.regex.checked = value;\n",
"\t\tthis.setInputWidth();\n",
"\t\tthis.validate();\n",
"\t}\n",
"\n",
"\tpublic focusOnCaseSensitive(): void {\n",
"\t\tthis.caseSensitive.focus();\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/base/browser/ui/findinput/findInput.ts",
"type": "replace",
"edit_start_line_idx": 260
} | /*---------------------------------------------------------------------------------------------
* 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 { basename } from 'vs/base/common/resources';
import { IDisposable, dispose, Disposable, combinedDisposable } from 'vs/base/common/lifecycle';
import { Event } from 'vs/base/common/event';
import { VIEWLET_ID, ISCMService, ISCMRepository } from 'vs/workbench/contrib/scm/common/scm';
import { IActivityService, NumberBadge } from 'vs/workbench/services/activity/common/activity';
import { IWorkbenchContribution } from 'vs/workbench/common/contributions';
import { IContextKeyService, IContextKey } from 'vs/platform/contextkey/common/contextkey';
import { IStatusbarService, StatusbarAlignment as MainThreadStatusBarAlignment } from 'vs/platform/statusbar/common/statusbar';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { commonPrefixLength } from 'vs/base/common/strings';
import { ILogService } from 'vs/platform/log/common/log';
export class StatusUpdater implements IWorkbenchContribution {
private badgeDisposable: IDisposable = Disposable.None;
private disposables: IDisposable[] = [];
constructor(
@ISCMService private readonly scmService: ISCMService,
@IActivityService private readonly activityService: IActivityService,
@ILogService private readonly logService: ILogService
) {
for (const repository of this.scmService.repositories) {
this.onDidAddRepository(repository);
}
this.scmService.onDidAddRepository(this.onDidAddRepository, this, this.disposables);
this.render();
}
private onDidAddRepository(repository: ISCMRepository): void {
const provider = repository.provider;
const onDidChange = Event.any(provider.onDidChange, provider.onDidChangeResources);
const changeDisposable = onDidChange(() => this.render());
const onDidRemove = Event.filter(this.scmService.onDidRemoveRepository, e => e === repository);
const removeDisposable = onDidRemove(() => {
disposable.dispose();
this.disposables = this.disposables.filter(d => d !== removeDisposable);
this.render();
});
const disposable = combinedDisposable([changeDisposable, removeDisposable]);
this.disposables.push(disposable);
}
private render(): void {
this.badgeDisposable.dispose();
const count = this.scmService.repositories.reduce((r, repository) => {
if (typeof repository.provider.count === 'number') {
return r + repository.provider.count;
} else {
return r + repository.provider.groups.elements.reduce<number>((r, g) => r + g.elements.length, 0);
}
}, 0);
// TODO@joao: remove
this.logService.trace('SCM#StatusUpdater.render', count);
if (count > 0) {
const badge = new NumberBadge(count, num => localize('scmPendingChangesBadge', '{0} pending changes', num));
this.badgeDisposable = this.activityService.showActivity(VIEWLET_ID, badge, 'scm-viewlet-label');
} else {
this.badgeDisposable = Disposable.None;
}
}
dispose(): void {
this.badgeDisposable.dispose();
this.disposables = dispose(this.disposables);
}
}
export class StatusBarController implements IWorkbenchContribution {
private statusBarDisposable: IDisposable = Disposable.None;
private focusDisposable: IDisposable = Disposable.None;
private focusedRepository: ISCMRepository | undefined = undefined;
private focusedProviderContextKey: IContextKey<string | undefined>;
private disposables: IDisposable[] = [];
constructor(
@ISCMService private readonly scmService: ISCMService,
@IStatusbarService private readonly statusbarService: IStatusbarService,
@IContextKeyService contextKeyService: IContextKeyService,
@IEditorService private readonly editorService: IEditorService
) {
this.focusedProviderContextKey = contextKeyService.createKey<string | undefined>('scmProvider', undefined);
this.scmService.onDidAddRepository(this.onDidAddRepository, this, this.disposables);
for (const repository of this.scmService.repositories) {
this.onDidAddRepository(repository);
}
editorService.onDidActiveEditorChange(this.onDidActiveEditorChange, this, this.disposables);
}
private onDidActiveEditorChange(): void {
if (!this.editorService.activeEditor) {
return;
}
const resource = this.editorService.activeEditor.getResource();
if (!resource || resource.scheme !== 'file') {
return;
}
let bestRepository: ISCMRepository | null = null;
let bestMatchLength = Number.NEGATIVE_INFINITY;
for (const repository of this.scmService.repositories) {
const root = repository.provider.rootUri;
if (!root) {
continue;
}
const rootFSPath = root.fsPath;
const prefixLength = commonPrefixLength(rootFSPath, resource.fsPath);
if (prefixLength === rootFSPath.length && prefixLength > bestMatchLength) {
bestRepository = repository;
bestMatchLength = prefixLength;
}
}
if (bestRepository) {
this.onDidFocusRepository(bestRepository);
}
}
private onDidAddRepository(repository: ISCMRepository): void {
const changeDisposable = repository.onDidFocus(() => this.onDidFocusRepository(repository));
const onDidRemove = Event.filter(this.scmService.onDidRemoveRepository, e => e === repository);
const removeDisposable = onDidRemove(() => {
disposable.dispose();
this.disposables = this.disposables.filter(d => d !== removeDisposable);
if (this.scmService.repositories.length === 0) {
this.onDidFocusRepository(undefined);
} else if (this.focusedRepository === repository) {
this.scmService.repositories[0].focus();
}
});
const disposable = combinedDisposable([changeDisposable, removeDisposable]);
this.disposables.push(disposable);
if (!this.focusedRepository) {
this.onDidFocusRepository(repository);
}
}
private onDidFocusRepository(repository: ISCMRepository | undefined): void {
if (this.focusedRepository === repository) {
return;
}
this.focusedRepository = repository;
this.focusedProviderContextKey.set(repository && repository.provider.id);
this.focusDisposable.dispose();
if (repository && repository.provider.onDidChangeStatusBarCommands) {
this.focusDisposable = repository.provider.onDidChangeStatusBarCommands(() => this.render(repository));
}
this.render(repository);
}
private render(repository: ISCMRepository | undefined): void {
this.statusBarDisposable.dispose();
if (!repository) {
return;
}
const commands = repository.provider.statusBarCommands || [];
const label = repository.provider.rootUri
? `${basename(repository.provider.rootUri)} (${repository.provider.label})`
: repository.provider.label;
const disposables = commands.map(c => this.statusbarService.addEntry({
text: c.title,
tooltip: `${label} - ${c.tooltip}`,
command: c.id,
arguments: c.arguments
}, MainThreadStatusBarAlignment.LEFT, 10000));
this.statusBarDisposable = combinedDisposable(disposables);
}
dispose(): void {
this.focusDisposable.dispose();
this.statusBarDisposable.dispose();
this.disposables = dispose(this.disposables);
}
}
| src/vs/workbench/contrib/scm/electron-browser/scmActivity.ts | 0 | https://github.com/microsoft/vscode/commit/bbff11633c7e56e7fd5d16cc20daa9a3284afbfe | [
0.0028233497869223356,
0.00030965564656071365,
0.00016690052871126682,
0.00017310536350123584,
0.0005640012677758932
]
|
{
"id": 7,
"code_window": [
"\t\tdom.addClass(this.domNode, 'highlight-' + (this._lastHighlightFindOptions));\n",
"\t}\n",
"\n",
"\tprivate setInputWidth(): void {\n",
"\t\tlet w = this.width - this.caseSensitive.width() - this.wholeWords.width() - this.regex.width();\n",
"\t\tthis.inputBox.width = w;\n",
"\t\tthis.inputBox.layout();\n",
"\t}\n",
"\n",
"\tprivate buildDomNode(appendCaseSensitiveLabel: string, appendWholeWordsLabel: string, appendRegexLabel: string, history: string[], flexibleHeight: boolean): void {\n",
"\t\tthis.domNode = document.createElement('div');\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/base/browser/ui/findinput/findInput.ts",
"type": "replace",
"edit_start_line_idx": 279
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import 'vs/css!./findInput';
import * as nls from 'vs/nls';
import * as dom from 'vs/base/browser/dom';
import { IMessage as InputBoxMessage, IInputValidator, IInputBoxStyles, HistoryInputBox } from 'vs/base/browser/ui/inputbox/inputBox';
import { IContextViewProvider } from 'vs/base/browser/ui/contextview/contextview';
import { Widget } from 'vs/base/browser/ui/widget';
import { Event, Emitter } from 'vs/base/common/event';
import { IKeyboardEvent } from 'vs/base/browser/keyboardEvent';
import { IMouseEvent } from 'vs/base/browser/mouseEvent';
import { KeyCode } from 'vs/base/common/keyCodes';
import { CaseSensitiveCheckbox, WholeWordsCheckbox, RegexCheckbox } from 'vs/base/browser/ui/findinput/findInputCheckboxes';
import { Color } from 'vs/base/common/color';
import { ICheckboxStyles } from 'vs/base/browser/ui/checkbox/checkbox';
export interface IFindInputOptions extends IFindInputStyles {
readonly placeholder?: string;
readonly width?: number;
readonly validation?: IInputValidator;
readonly label: string;
readonly flexibleHeight?: boolean;
readonly appendCaseSensitiveLabel?: string;
readonly appendWholeWordsLabel?: string;
readonly appendRegexLabel?: string;
readonly history?: string[];
}
export interface IFindInputStyles extends IInputBoxStyles {
inputActiveOptionBorder?: Color;
}
const NLS_DEFAULT_LABEL = nls.localize('defaultLabel', "input");
export class FindInput extends Widget {
static readonly OPTION_CHANGE: string = 'optionChange';
private contextViewProvider: IContextViewProvider;
private width: number;
private placeholder: string;
private validation?: IInputValidator;
private label: string;
private fixFocusOnOptionClickEnabled = true;
private inputActiveOptionBorder?: Color;
private inputBackground?: Color;
private inputForeground?: Color;
private inputBorder?: Color;
private inputValidationInfoBorder?: Color;
private inputValidationInfoBackground?: Color;
private inputValidationInfoForeground?: Color;
private inputValidationWarningBorder?: Color;
private inputValidationWarningBackground?: Color;
private inputValidationWarningForeground?: Color;
private inputValidationErrorBorder?: Color;
private inputValidationErrorBackground?: Color;
private inputValidationErrorForeground?: Color;
private regex: RegexCheckbox;
private wholeWords: WholeWordsCheckbox;
private caseSensitive: CaseSensitiveCheckbox;
public domNode: HTMLElement;
public inputBox: HistoryInputBox;
private readonly _onDidOptionChange = this._register(new Emitter<boolean>());
public readonly onDidOptionChange: Event<boolean /* via keyboard */> = this._onDidOptionChange.event;
private readonly _onKeyDown = this._register(new Emitter<IKeyboardEvent>());
public readonly onKeyDown: Event<IKeyboardEvent> = this._onKeyDown.event;
private readonly _onMouseDown = this._register(new Emitter<IMouseEvent>());
public readonly onMouseDown: Event<IMouseEvent> = this._onMouseDown.event;
private readonly _onInput = this._register(new Emitter<void>());
public readonly onInput: Event<void> = this._onInput.event;
private readonly _onKeyUp = this._register(new Emitter<IKeyboardEvent>());
public readonly onKeyUp: Event<IKeyboardEvent> = this._onKeyUp.event;
private _onCaseSensitiveKeyDown = this._register(new Emitter<IKeyboardEvent>());
public readonly onCaseSensitiveKeyDown: Event<IKeyboardEvent> = this._onCaseSensitiveKeyDown.event;
private _onRegexKeyDown = this._register(new Emitter<IKeyboardEvent>());
public readonly onRegexKeyDown: Event<IKeyboardEvent> = this._onRegexKeyDown.event;
constructor(parent: HTMLElement | null, contextViewProvider: IContextViewProvider, private readonly _showOptionButtons: boolean, options: IFindInputOptions) {
super();
this.contextViewProvider = contextViewProvider;
this.width = options.width || 100;
this.placeholder = options.placeholder || '';
this.validation = options.validation;
this.label = options.label || NLS_DEFAULT_LABEL;
this.inputActiveOptionBorder = options.inputActiveOptionBorder;
this.inputBackground = options.inputBackground;
this.inputForeground = options.inputForeground;
this.inputBorder = options.inputBorder;
this.inputValidationInfoBorder = options.inputValidationInfoBorder;
this.inputValidationInfoBackground = options.inputValidationInfoBackground;
this.inputValidationInfoForeground = options.inputValidationInfoForeground;
this.inputValidationWarningBorder = options.inputValidationWarningBorder;
this.inputValidationWarningBackground = options.inputValidationWarningBackground;
this.inputValidationWarningForeground = options.inputValidationWarningForeground;
this.inputValidationErrorBorder = options.inputValidationErrorBorder;
this.inputValidationErrorBackground = options.inputValidationErrorBackground;
this.inputValidationErrorForeground = options.inputValidationErrorForeground;
this.buildDomNode(options.appendCaseSensitiveLabel || '', options.appendWholeWordsLabel || '', options.appendRegexLabel || '', options.history || [], !!options.flexibleHeight);
if (parent) {
parent.appendChild(this.domNode);
}
this.onkeydown(this.inputBox.inputElement, (e) => this._onKeyDown.fire(e));
this.onkeyup(this.inputBox.inputElement, (e) => this._onKeyUp.fire(e));
this.oninput(this.inputBox.inputElement, (e) => this._onInput.fire());
this.onmousedown(this.inputBox.inputElement, (e) => this._onMouseDown.fire(e));
}
public enable(): void {
dom.removeClass(this.domNode, 'disabled');
this.inputBox.enable();
this.regex.enable();
this.wholeWords.enable();
this.caseSensitive.enable();
}
public disable(): void {
dom.addClass(this.domNode, 'disabled');
this.inputBox.disable();
this.regex.disable();
this.wholeWords.disable();
this.caseSensitive.disable();
}
public setFocusInputOnOptionClick(value: boolean): void {
this.fixFocusOnOptionClickEnabled = value;
}
public setEnabled(enabled: boolean): void {
if (enabled) {
this.enable();
} else {
this.disable();
}
}
public clear(): void {
this.clearValidation();
this.setValue('');
this.focus();
}
public setWidth(newWidth: number): void {
this.width = newWidth;
this.domNode.style.width = this.width + 'px';
this.contextViewProvider.layout();
this.setInputWidth();
}
public getValue(): string {
return this.inputBox.value;
}
public setValue(value: string): void {
if (this.inputBox.value !== value) {
this.inputBox.value = value;
}
}
public onSearchSubmit(): void {
this.inputBox.addToHistory();
}
public style(styles: IFindInputStyles): void {
this.inputActiveOptionBorder = styles.inputActiveOptionBorder;
this.inputBackground = styles.inputBackground;
this.inputForeground = styles.inputForeground;
this.inputBorder = styles.inputBorder;
this.inputValidationInfoBackground = styles.inputValidationInfoBackground;
this.inputValidationInfoForeground = styles.inputValidationInfoForeground;
this.inputValidationInfoBorder = styles.inputValidationInfoBorder;
this.inputValidationWarningBackground = styles.inputValidationWarningBackground;
this.inputValidationWarningForeground = styles.inputValidationWarningForeground;
this.inputValidationWarningBorder = styles.inputValidationWarningBorder;
this.inputValidationErrorBackground = styles.inputValidationErrorBackground;
this.inputValidationErrorForeground = styles.inputValidationErrorForeground;
this.inputValidationErrorBorder = styles.inputValidationErrorBorder;
this.applyStyles();
}
protected applyStyles(): void {
if (this.domNode) {
const checkBoxStyles: ICheckboxStyles = {
inputActiveOptionBorder: this.inputActiveOptionBorder,
};
this.regex.style(checkBoxStyles);
this.wholeWords.style(checkBoxStyles);
this.caseSensitive.style(checkBoxStyles);
const inputBoxStyles: IInputBoxStyles = {
inputBackground: this.inputBackground,
inputForeground: this.inputForeground,
inputBorder: this.inputBorder,
inputValidationInfoBackground: this.inputValidationInfoBackground,
inputValidationInfoForeground: this.inputValidationInfoForeground,
inputValidationInfoBorder: this.inputValidationInfoBorder,
inputValidationWarningBackground: this.inputValidationWarningBackground,
inputValidationWarningForeground: this.inputValidationWarningForeground,
inputValidationWarningBorder: this.inputValidationWarningBorder,
inputValidationErrorBackground: this.inputValidationErrorBackground,
inputValidationErrorForeground: this.inputValidationErrorForeground,
inputValidationErrorBorder: this.inputValidationErrorBorder
};
this.inputBox.style(inputBoxStyles);
}
}
public select(): void {
this.inputBox.select();
}
public focus(): void {
this.inputBox.focus();
}
public getCaseSensitive(): boolean {
return this.caseSensitive.checked;
}
public setCaseSensitive(value: boolean): void {
this.caseSensitive.checked = value;
this.setInputWidth();
}
public getWholeWords(): boolean {
return this.wholeWords.checked;
}
public setWholeWords(value: boolean): void {
this.wholeWords.checked = value;
this.setInputWidth();
}
public getRegex(): boolean {
return this.regex.checked;
}
public setRegex(value: boolean): void {
this.regex.checked = value;
this.setInputWidth();
this.validate();
}
public focusOnCaseSensitive(): void {
this.caseSensitive.focus();
}
public focusOnRegex(): void {
this.regex.focus();
}
private _lastHighlightFindOptions: number = 0;
public highlightFindOptions(): void {
dom.removeClass(this.domNode, 'highlight-' + (this._lastHighlightFindOptions));
this._lastHighlightFindOptions = 1 - this._lastHighlightFindOptions;
dom.addClass(this.domNode, 'highlight-' + (this._lastHighlightFindOptions));
}
private setInputWidth(): void {
let w = this.width - this.caseSensitive.width() - this.wholeWords.width() - this.regex.width();
this.inputBox.width = w;
this.inputBox.layout();
}
private buildDomNode(appendCaseSensitiveLabel: string, appendWholeWordsLabel: string, appendRegexLabel: string, history: string[], flexibleHeight: boolean): void {
this.domNode = document.createElement('div');
this.domNode.style.width = this.width + 'px';
dom.addClass(this.domNode, 'monaco-findInput');
this.inputBox = this._register(new HistoryInputBox(this.domNode, this.contextViewProvider, {
placeholder: this.placeholder || '',
ariaLabel: this.label || '',
validationOptions: {
validation: this.validation
},
inputBackground: this.inputBackground,
inputForeground: this.inputForeground,
inputBorder: this.inputBorder,
inputValidationInfoBackground: this.inputValidationInfoBackground,
inputValidationInfoForeground: this.inputValidationInfoForeground,
inputValidationInfoBorder: this.inputValidationInfoBorder,
inputValidationWarningBackground: this.inputValidationWarningBackground,
inputValidationWarningForeground: this.inputValidationWarningForeground,
inputValidationWarningBorder: this.inputValidationWarningBorder,
inputValidationErrorBackground: this.inputValidationErrorBackground,
inputValidationErrorForeground: this.inputValidationErrorForeground,
inputValidationErrorBorder: this.inputValidationErrorBorder,
history,
flexibleHeight
}));
this.regex = this._register(new RegexCheckbox({
appendTitle: appendRegexLabel,
isChecked: false,
inputActiveOptionBorder: this.inputActiveOptionBorder
}));
this._register(this.regex.onChange(viaKeyboard => {
this._onDidOptionChange.fire(viaKeyboard);
if (!viaKeyboard && this.fixFocusOnOptionClickEnabled) {
this.inputBox.focus();
}
this.setInputWidth();
this.validate();
}));
this._register(this.regex.onKeyDown(e => {
this._onRegexKeyDown.fire(e);
}));
this.wholeWords = this._register(new WholeWordsCheckbox({
appendTitle: appendWholeWordsLabel,
isChecked: false,
inputActiveOptionBorder: this.inputActiveOptionBorder
}));
this._register(this.wholeWords.onChange(viaKeyboard => {
this._onDidOptionChange.fire(viaKeyboard);
if (!viaKeyboard && this.fixFocusOnOptionClickEnabled) {
this.inputBox.focus();
}
this.setInputWidth();
this.validate();
}));
this.caseSensitive = this._register(new CaseSensitiveCheckbox({
appendTitle: appendCaseSensitiveLabel,
isChecked: false,
inputActiveOptionBorder: this.inputActiveOptionBorder
}));
this._register(this.caseSensitive.onChange(viaKeyboard => {
this._onDidOptionChange.fire(viaKeyboard);
if (!viaKeyboard && this.fixFocusOnOptionClickEnabled) {
this.inputBox.focus();
}
this.setInputWidth();
this.validate();
}));
this._register(this.caseSensitive.onKeyDown(e => {
this._onCaseSensitiveKeyDown.fire(e);
}));
if (this._showOptionButtons) {
this.inputBox.inputElement.style.paddingRight = (this.caseSensitive.width() + this.wholeWords.width() + this.regex.width()) + 'px';
}
// Arrow-Key support to navigate between options
let indexes = [this.caseSensitive.domNode, this.wholeWords.domNode, this.regex.domNode];
this.onkeydown(this.domNode, (event: IKeyboardEvent) => {
if (event.equals(KeyCode.LeftArrow) || event.equals(KeyCode.RightArrow) || event.equals(KeyCode.Escape)) {
let index = indexes.indexOf(<HTMLElement>document.activeElement);
if (index >= 0) {
let newIndex: number = -1;
if (event.equals(KeyCode.RightArrow)) {
newIndex = (index + 1) % indexes.length;
} else if (event.equals(KeyCode.LeftArrow)) {
if (index === 0) {
newIndex = indexes.length - 1;
} else {
newIndex = index - 1;
}
}
if (event.equals(KeyCode.Escape)) {
indexes[index].blur();
} else if (newIndex >= 0) {
indexes[newIndex].focus();
}
dom.EventHelper.stop(event, true);
}
}
});
this.setInputWidth();
let controls = document.createElement('div');
controls.className = 'controls';
controls.style.display = this._showOptionButtons ? 'block' : 'none';
controls.appendChild(this.caseSensitive.domNode);
controls.appendChild(this.wholeWords.domNode);
controls.appendChild(this.regex.domNode);
this.domNode.appendChild(controls);
}
public validate(): void {
if (this.inputBox) {
this.inputBox.validate();
}
}
public showMessage(message: InputBoxMessage): void {
if (this.inputBox) {
this.inputBox.showMessage(message);
}
}
public clearMessage(): void {
if (this.inputBox) {
this.inputBox.hideMessage();
}
}
private clearValidation(): void {
if (this.inputBox) {
this.inputBox.hideMessage();
}
}
public dispose(): void {
super.dispose();
}
}
| src/vs/base/browser/ui/findinput/findInput.ts | 1 | https://github.com/microsoft/vscode/commit/bbff11633c7e56e7fd5d16cc20daa9a3284afbfe | [
0.9990829229354858,
0.28200480341911316,
0.00016474089352414012,
0.0012363381683826447,
0.43945708870887756
]
|
{
"id": 7,
"code_window": [
"\t\tdom.addClass(this.domNode, 'highlight-' + (this._lastHighlightFindOptions));\n",
"\t}\n",
"\n",
"\tprivate setInputWidth(): void {\n",
"\t\tlet w = this.width - this.caseSensitive.width() - this.wholeWords.width() - this.regex.width();\n",
"\t\tthis.inputBox.width = w;\n",
"\t\tthis.inputBox.layout();\n",
"\t}\n",
"\n",
"\tprivate buildDomNode(appendCaseSensitiveLabel: string, appendWholeWordsLabel: string, appendRegexLabel: string, history: string[], flexibleHeight: boolean): void {\n",
"\t\tthis.domNode = document.createElement('div');\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/base/browser/ui/findinput/findInput.ts",
"type": "replace",
"edit_start_line_idx": 279
} | <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" clip-rule="evenodd" d="M10 5H9V4H10V5V5ZM3 6H2V7H3V6V6ZM8 4H7V5H8V4V4ZM4 4H2V5H4V4V4ZM12 11H14V10H12V11V11ZM8 7H9V6H8V7V7ZM4 10H2V11H4V10V10ZM12 4H11V5H12V4V4ZM14 4H13V5H14V4V4ZM12 9H14V6H12V9V9ZM16 3V12C16 12.55 15.55 13 15 13H1C0.45 13 0 12.55 0 12V3C0 2.45 0.45 2 1 2H15C15.55 2 16 2.45 16 3V3ZM15 3H1V12H15V3V3ZM6 7H7V6H6V7V7ZM6 4H5V5H6V4V4ZM4 7H5V6H4V7V7ZM5 11H11V10H5V11V11ZM10 7H11V6H10V7V7ZM3 8H2V9H3V8V8ZM8 8V9H9V8H8V8ZM6 8V9H7V8H6V8ZM5 8H4V9H5V8V8ZM10 9H11V8H10V9V9Z" fill="#424242"/>
</svg>
| src/vs/workbench/contrib/preferences/browser/media/record-keys.svg | 0 | https://github.com/microsoft/vscode/commit/bbff11633c7e56e7fd5d16cc20daa9a3284afbfe | [
0.00029050270677544177,
0.00029050270677544177,
0.00029050270677544177,
0.00029050270677544177,
0
]
|
{
"id": 7,
"code_window": [
"\t\tdom.addClass(this.domNode, 'highlight-' + (this._lastHighlightFindOptions));\n",
"\t}\n",
"\n",
"\tprivate setInputWidth(): void {\n",
"\t\tlet w = this.width - this.caseSensitive.width() - this.wholeWords.width() - this.regex.width();\n",
"\t\tthis.inputBox.width = w;\n",
"\t\tthis.inputBox.layout();\n",
"\t}\n",
"\n",
"\tprivate buildDomNode(appendCaseSensitiveLabel: string, appendWholeWordsLabel: string, appendRegexLabel: string, history: string[], flexibleHeight: boolean): void {\n",
"\t\tthis.domNode = document.createElement('div');\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/base/browser/ui/findinput/findInput.ts",
"type": "replace",
"edit_start_line_idx": 279
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import './actions/showEmmetCommands';
| src/vs/workbench/contrib/emmet/browser/emmet.browser.contribution.ts | 0 | https://github.com/microsoft/vscode/commit/bbff11633c7e56e7fd5d16cc20daa9a3284afbfe | [
0.00017462274990975857,
0.00017462274990975857,
0.00017462274990975857,
0.00017462274990975857,
0
]
|
{
"id": 7,
"code_window": [
"\t\tdom.addClass(this.domNode, 'highlight-' + (this._lastHighlightFindOptions));\n",
"\t}\n",
"\n",
"\tprivate setInputWidth(): void {\n",
"\t\tlet w = this.width - this.caseSensitive.width() - this.wholeWords.width() - this.regex.width();\n",
"\t\tthis.inputBox.width = w;\n",
"\t\tthis.inputBox.layout();\n",
"\t}\n",
"\n",
"\tprivate buildDomNode(appendCaseSensitiveLabel: string, appendWholeWordsLabel: string, appendRegexLabel: string, history: string[], flexibleHeight: boolean): void {\n",
"\t\tthis.domNode = document.createElement('div');\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/base/browser/ui/findinput/findInput.ts",
"type": "replace",
"edit_start_line_idx": 279
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as vscode from 'vscode';
import * as nls from 'vscode-nls';
import { memoize } from './memoize';
const localize = nls.loadMessageBundle();
type LogLevel = 'Trace' | 'Info' | 'Error';
export default class Logger {
@memoize
private get output(): vscode.OutputChannel {
return vscode.window.createOutputChannel(localize('channelName', 'TypeScript'));
}
private data2String(data: any): string {
if (data instanceof Error) {
return data.stack || data.message;
}
if (data.success === false && data.message) {
return data.message;
}
return data.toString();
}
public info(message: string, data?: any): void {
this.logLevel('Info', message, data);
}
public error(message: string, data?: any): void {
// See https://github.com/Microsoft/TypeScript/issues/10496
if (data && data.message === 'No content available.') {
return;
}
this.logLevel('Error', message, data);
}
public logLevel(level: LogLevel, message: string, data?: any): void {
this.output.appendLine(`[${level} - ${(new Date().toLocaleTimeString())}] ${message}`);
if (data) {
this.output.appendLine(this.data2String(data));
}
}
} | extensions/typescript-language-features/src/utils/logger.ts | 0 | https://github.com/microsoft/vscode/commit/bbff11633c7e56e7fd5d16cc20daa9a3284afbfe | [
0.00017495105566922575,
0.00017044185369741172,
0.00016555629554204643,
0.00017077763914130628,
0.000003061765710299369
]
|
{
"id": 8,
"code_window": [
"\tprivate buildDomNode(appendCaseSensitiveLabel: string, appendWholeWordsLabel: string, appendRegexLabel: string, history: string[], flexibleHeight: boolean): void {\n",
"\t\tthis.domNode = document.createElement('div');\n",
"\t\tthis.domNode.style.width = this.width + 'px';\n",
"\t\tdom.addClass(this.domNode, 'monaco-findInput');\n",
"\n",
"\t\tthis.inputBox = this._register(new HistoryInputBox(this.domNode, this.contextViewProvider, {\n",
"\t\t\tplaceholder: this.placeholder || '',\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/base/browser/ui/findinput/findInput.ts",
"type": "replace",
"edit_start_line_idx": 287
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import 'vs/css!./findInput';
import * as nls from 'vs/nls';
import * as dom from 'vs/base/browser/dom';
import { IMessage as InputBoxMessage, IInputValidator, IInputBoxStyles, HistoryInputBox } from 'vs/base/browser/ui/inputbox/inputBox';
import { IContextViewProvider } from 'vs/base/browser/ui/contextview/contextview';
import { Widget } from 'vs/base/browser/ui/widget';
import { Event, Emitter } from 'vs/base/common/event';
import { IKeyboardEvent } from 'vs/base/browser/keyboardEvent';
import { IMouseEvent } from 'vs/base/browser/mouseEvent';
import { KeyCode } from 'vs/base/common/keyCodes';
import { CaseSensitiveCheckbox, WholeWordsCheckbox, RegexCheckbox } from 'vs/base/browser/ui/findinput/findInputCheckboxes';
import { Color } from 'vs/base/common/color';
import { ICheckboxStyles } from 'vs/base/browser/ui/checkbox/checkbox';
export interface IFindInputOptions extends IFindInputStyles {
readonly placeholder?: string;
readonly width?: number;
readonly validation?: IInputValidator;
readonly label: string;
readonly flexibleHeight?: boolean;
readonly appendCaseSensitiveLabel?: string;
readonly appendWholeWordsLabel?: string;
readonly appendRegexLabel?: string;
readonly history?: string[];
}
export interface IFindInputStyles extends IInputBoxStyles {
inputActiveOptionBorder?: Color;
}
const NLS_DEFAULT_LABEL = nls.localize('defaultLabel', "input");
export class FindInput extends Widget {
static readonly OPTION_CHANGE: string = 'optionChange';
private contextViewProvider: IContextViewProvider;
private width: number;
private placeholder: string;
private validation?: IInputValidator;
private label: string;
private fixFocusOnOptionClickEnabled = true;
private inputActiveOptionBorder?: Color;
private inputBackground?: Color;
private inputForeground?: Color;
private inputBorder?: Color;
private inputValidationInfoBorder?: Color;
private inputValidationInfoBackground?: Color;
private inputValidationInfoForeground?: Color;
private inputValidationWarningBorder?: Color;
private inputValidationWarningBackground?: Color;
private inputValidationWarningForeground?: Color;
private inputValidationErrorBorder?: Color;
private inputValidationErrorBackground?: Color;
private inputValidationErrorForeground?: Color;
private regex: RegexCheckbox;
private wholeWords: WholeWordsCheckbox;
private caseSensitive: CaseSensitiveCheckbox;
public domNode: HTMLElement;
public inputBox: HistoryInputBox;
private readonly _onDidOptionChange = this._register(new Emitter<boolean>());
public readonly onDidOptionChange: Event<boolean /* via keyboard */> = this._onDidOptionChange.event;
private readonly _onKeyDown = this._register(new Emitter<IKeyboardEvent>());
public readonly onKeyDown: Event<IKeyboardEvent> = this._onKeyDown.event;
private readonly _onMouseDown = this._register(new Emitter<IMouseEvent>());
public readonly onMouseDown: Event<IMouseEvent> = this._onMouseDown.event;
private readonly _onInput = this._register(new Emitter<void>());
public readonly onInput: Event<void> = this._onInput.event;
private readonly _onKeyUp = this._register(new Emitter<IKeyboardEvent>());
public readonly onKeyUp: Event<IKeyboardEvent> = this._onKeyUp.event;
private _onCaseSensitiveKeyDown = this._register(new Emitter<IKeyboardEvent>());
public readonly onCaseSensitiveKeyDown: Event<IKeyboardEvent> = this._onCaseSensitiveKeyDown.event;
private _onRegexKeyDown = this._register(new Emitter<IKeyboardEvent>());
public readonly onRegexKeyDown: Event<IKeyboardEvent> = this._onRegexKeyDown.event;
constructor(parent: HTMLElement | null, contextViewProvider: IContextViewProvider, private readonly _showOptionButtons: boolean, options: IFindInputOptions) {
super();
this.contextViewProvider = contextViewProvider;
this.width = options.width || 100;
this.placeholder = options.placeholder || '';
this.validation = options.validation;
this.label = options.label || NLS_DEFAULT_LABEL;
this.inputActiveOptionBorder = options.inputActiveOptionBorder;
this.inputBackground = options.inputBackground;
this.inputForeground = options.inputForeground;
this.inputBorder = options.inputBorder;
this.inputValidationInfoBorder = options.inputValidationInfoBorder;
this.inputValidationInfoBackground = options.inputValidationInfoBackground;
this.inputValidationInfoForeground = options.inputValidationInfoForeground;
this.inputValidationWarningBorder = options.inputValidationWarningBorder;
this.inputValidationWarningBackground = options.inputValidationWarningBackground;
this.inputValidationWarningForeground = options.inputValidationWarningForeground;
this.inputValidationErrorBorder = options.inputValidationErrorBorder;
this.inputValidationErrorBackground = options.inputValidationErrorBackground;
this.inputValidationErrorForeground = options.inputValidationErrorForeground;
this.buildDomNode(options.appendCaseSensitiveLabel || '', options.appendWholeWordsLabel || '', options.appendRegexLabel || '', options.history || [], !!options.flexibleHeight);
if (parent) {
parent.appendChild(this.domNode);
}
this.onkeydown(this.inputBox.inputElement, (e) => this._onKeyDown.fire(e));
this.onkeyup(this.inputBox.inputElement, (e) => this._onKeyUp.fire(e));
this.oninput(this.inputBox.inputElement, (e) => this._onInput.fire());
this.onmousedown(this.inputBox.inputElement, (e) => this._onMouseDown.fire(e));
}
public enable(): void {
dom.removeClass(this.domNode, 'disabled');
this.inputBox.enable();
this.regex.enable();
this.wholeWords.enable();
this.caseSensitive.enable();
}
public disable(): void {
dom.addClass(this.domNode, 'disabled');
this.inputBox.disable();
this.regex.disable();
this.wholeWords.disable();
this.caseSensitive.disable();
}
public setFocusInputOnOptionClick(value: boolean): void {
this.fixFocusOnOptionClickEnabled = value;
}
public setEnabled(enabled: boolean): void {
if (enabled) {
this.enable();
} else {
this.disable();
}
}
public clear(): void {
this.clearValidation();
this.setValue('');
this.focus();
}
public setWidth(newWidth: number): void {
this.width = newWidth;
this.domNode.style.width = this.width + 'px';
this.contextViewProvider.layout();
this.setInputWidth();
}
public getValue(): string {
return this.inputBox.value;
}
public setValue(value: string): void {
if (this.inputBox.value !== value) {
this.inputBox.value = value;
}
}
public onSearchSubmit(): void {
this.inputBox.addToHistory();
}
public style(styles: IFindInputStyles): void {
this.inputActiveOptionBorder = styles.inputActiveOptionBorder;
this.inputBackground = styles.inputBackground;
this.inputForeground = styles.inputForeground;
this.inputBorder = styles.inputBorder;
this.inputValidationInfoBackground = styles.inputValidationInfoBackground;
this.inputValidationInfoForeground = styles.inputValidationInfoForeground;
this.inputValidationInfoBorder = styles.inputValidationInfoBorder;
this.inputValidationWarningBackground = styles.inputValidationWarningBackground;
this.inputValidationWarningForeground = styles.inputValidationWarningForeground;
this.inputValidationWarningBorder = styles.inputValidationWarningBorder;
this.inputValidationErrorBackground = styles.inputValidationErrorBackground;
this.inputValidationErrorForeground = styles.inputValidationErrorForeground;
this.inputValidationErrorBorder = styles.inputValidationErrorBorder;
this.applyStyles();
}
protected applyStyles(): void {
if (this.domNode) {
const checkBoxStyles: ICheckboxStyles = {
inputActiveOptionBorder: this.inputActiveOptionBorder,
};
this.regex.style(checkBoxStyles);
this.wholeWords.style(checkBoxStyles);
this.caseSensitive.style(checkBoxStyles);
const inputBoxStyles: IInputBoxStyles = {
inputBackground: this.inputBackground,
inputForeground: this.inputForeground,
inputBorder: this.inputBorder,
inputValidationInfoBackground: this.inputValidationInfoBackground,
inputValidationInfoForeground: this.inputValidationInfoForeground,
inputValidationInfoBorder: this.inputValidationInfoBorder,
inputValidationWarningBackground: this.inputValidationWarningBackground,
inputValidationWarningForeground: this.inputValidationWarningForeground,
inputValidationWarningBorder: this.inputValidationWarningBorder,
inputValidationErrorBackground: this.inputValidationErrorBackground,
inputValidationErrorForeground: this.inputValidationErrorForeground,
inputValidationErrorBorder: this.inputValidationErrorBorder
};
this.inputBox.style(inputBoxStyles);
}
}
public select(): void {
this.inputBox.select();
}
public focus(): void {
this.inputBox.focus();
}
public getCaseSensitive(): boolean {
return this.caseSensitive.checked;
}
public setCaseSensitive(value: boolean): void {
this.caseSensitive.checked = value;
this.setInputWidth();
}
public getWholeWords(): boolean {
return this.wholeWords.checked;
}
public setWholeWords(value: boolean): void {
this.wholeWords.checked = value;
this.setInputWidth();
}
public getRegex(): boolean {
return this.regex.checked;
}
public setRegex(value: boolean): void {
this.regex.checked = value;
this.setInputWidth();
this.validate();
}
public focusOnCaseSensitive(): void {
this.caseSensitive.focus();
}
public focusOnRegex(): void {
this.regex.focus();
}
private _lastHighlightFindOptions: number = 0;
public highlightFindOptions(): void {
dom.removeClass(this.domNode, 'highlight-' + (this._lastHighlightFindOptions));
this._lastHighlightFindOptions = 1 - this._lastHighlightFindOptions;
dom.addClass(this.domNode, 'highlight-' + (this._lastHighlightFindOptions));
}
private setInputWidth(): void {
let w = this.width - this.caseSensitive.width() - this.wholeWords.width() - this.regex.width();
this.inputBox.width = w;
this.inputBox.layout();
}
private buildDomNode(appendCaseSensitiveLabel: string, appendWholeWordsLabel: string, appendRegexLabel: string, history: string[], flexibleHeight: boolean): void {
this.domNode = document.createElement('div');
this.domNode.style.width = this.width + 'px';
dom.addClass(this.domNode, 'monaco-findInput');
this.inputBox = this._register(new HistoryInputBox(this.domNode, this.contextViewProvider, {
placeholder: this.placeholder || '',
ariaLabel: this.label || '',
validationOptions: {
validation: this.validation
},
inputBackground: this.inputBackground,
inputForeground: this.inputForeground,
inputBorder: this.inputBorder,
inputValidationInfoBackground: this.inputValidationInfoBackground,
inputValidationInfoForeground: this.inputValidationInfoForeground,
inputValidationInfoBorder: this.inputValidationInfoBorder,
inputValidationWarningBackground: this.inputValidationWarningBackground,
inputValidationWarningForeground: this.inputValidationWarningForeground,
inputValidationWarningBorder: this.inputValidationWarningBorder,
inputValidationErrorBackground: this.inputValidationErrorBackground,
inputValidationErrorForeground: this.inputValidationErrorForeground,
inputValidationErrorBorder: this.inputValidationErrorBorder,
history,
flexibleHeight
}));
this.regex = this._register(new RegexCheckbox({
appendTitle: appendRegexLabel,
isChecked: false,
inputActiveOptionBorder: this.inputActiveOptionBorder
}));
this._register(this.regex.onChange(viaKeyboard => {
this._onDidOptionChange.fire(viaKeyboard);
if (!viaKeyboard && this.fixFocusOnOptionClickEnabled) {
this.inputBox.focus();
}
this.setInputWidth();
this.validate();
}));
this._register(this.regex.onKeyDown(e => {
this._onRegexKeyDown.fire(e);
}));
this.wholeWords = this._register(new WholeWordsCheckbox({
appendTitle: appendWholeWordsLabel,
isChecked: false,
inputActiveOptionBorder: this.inputActiveOptionBorder
}));
this._register(this.wholeWords.onChange(viaKeyboard => {
this._onDidOptionChange.fire(viaKeyboard);
if (!viaKeyboard && this.fixFocusOnOptionClickEnabled) {
this.inputBox.focus();
}
this.setInputWidth();
this.validate();
}));
this.caseSensitive = this._register(new CaseSensitiveCheckbox({
appendTitle: appendCaseSensitiveLabel,
isChecked: false,
inputActiveOptionBorder: this.inputActiveOptionBorder
}));
this._register(this.caseSensitive.onChange(viaKeyboard => {
this._onDidOptionChange.fire(viaKeyboard);
if (!viaKeyboard && this.fixFocusOnOptionClickEnabled) {
this.inputBox.focus();
}
this.setInputWidth();
this.validate();
}));
this._register(this.caseSensitive.onKeyDown(e => {
this._onCaseSensitiveKeyDown.fire(e);
}));
if (this._showOptionButtons) {
this.inputBox.inputElement.style.paddingRight = (this.caseSensitive.width() + this.wholeWords.width() + this.regex.width()) + 'px';
}
// Arrow-Key support to navigate between options
let indexes = [this.caseSensitive.domNode, this.wholeWords.domNode, this.regex.domNode];
this.onkeydown(this.domNode, (event: IKeyboardEvent) => {
if (event.equals(KeyCode.LeftArrow) || event.equals(KeyCode.RightArrow) || event.equals(KeyCode.Escape)) {
let index = indexes.indexOf(<HTMLElement>document.activeElement);
if (index >= 0) {
let newIndex: number = -1;
if (event.equals(KeyCode.RightArrow)) {
newIndex = (index + 1) % indexes.length;
} else if (event.equals(KeyCode.LeftArrow)) {
if (index === 0) {
newIndex = indexes.length - 1;
} else {
newIndex = index - 1;
}
}
if (event.equals(KeyCode.Escape)) {
indexes[index].blur();
} else if (newIndex >= 0) {
indexes[newIndex].focus();
}
dom.EventHelper.stop(event, true);
}
}
});
this.setInputWidth();
let controls = document.createElement('div');
controls.className = 'controls';
controls.style.display = this._showOptionButtons ? 'block' : 'none';
controls.appendChild(this.caseSensitive.domNode);
controls.appendChild(this.wholeWords.domNode);
controls.appendChild(this.regex.domNode);
this.domNode.appendChild(controls);
}
public validate(): void {
if (this.inputBox) {
this.inputBox.validate();
}
}
public showMessage(message: InputBoxMessage): void {
if (this.inputBox) {
this.inputBox.showMessage(message);
}
}
public clearMessage(): void {
if (this.inputBox) {
this.inputBox.hideMessage();
}
}
private clearValidation(): void {
if (this.inputBox) {
this.inputBox.hideMessage();
}
}
public dispose(): void {
super.dispose();
}
}
| src/vs/base/browser/ui/findinput/findInput.ts | 1 | https://github.com/microsoft/vscode/commit/bbff11633c7e56e7fd5d16cc20daa9a3284afbfe | [
0.9987848401069641,
0.10511355847120285,
0.0001649417681619525,
0.0008457956137135625,
0.280676007270813
]
|
{
"id": 8,
"code_window": [
"\tprivate buildDomNode(appendCaseSensitiveLabel: string, appendWholeWordsLabel: string, appendRegexLabel: string, history: string[], flexibleHeight: boolean): void {\n",
"\t\tthis.domNode = document.createElement('div');\n",
"\t\tthis.domNode.style.width = this.width + 'px';\n",
"\t\tdom.addClass(this.domNode, 'monaco-findInput');\n",
"\n",
"\t\tthis.inputBox = this._register(new HistoryInputBox(this.domNode, this.contextViewProvider, {\n",
"\t\t\tplaceholder: this.placeholder || '',\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/base/browser/ui/findinput/findInput.ts",
"type": "replace",
"edit_start_line_idx": 287
} | #!/bin/bash
if [[ "$OSTYPE" == "darwin"* ]]; then
realpath() { [[ $1 = /* ]] && echo "$1" || echo "$PWD/${1#./}"; }
ROOT=$(dirname $(dirname $(realpath "$0")))
else
ROOT=$(dirname $(dirname $(readlink -f $0)))
fi
pushd $ROOT
if [[ "$OSTYPE" == "darwin"* ]]; then
NAME=`node -p "require('./product.json').nameLong"`
CODE="$ROOT/.build/electron/$NAME.app/Contents/MacOS/Electron"
else
NAME=`node -p "require('./product.json').applicationName"`
CODE="$ROOT/.build/electron/$NAME"
fi
# Get electron
node build/lib/electron.js || ./node_modules/.bin/gulp electron
popd
export VSCODE_DEV=1
if [[ "$OSTYPE" == "darwin"* ]]; then
ulimit -n 4096 ; ELECTRON_RUN_AS_NODE=1 \
"$CODE" \
"$@"
else
ELECTRON_RUN_AS_NODE=1 \
"$CODE" \
"$@"
fi
| scripts/node-electron.sh | 0 | https://github.com/microsoft/vscode/commit/bbff11633c7e56e7fd5d16cc20daa9a3284afbfe | [
0.00017270637908950448,
0.0001699098211247474,
0.00016818352742120624,
0.00016937468899413943,
0.0000017362913240503985
]
|
{
"id": 8,
"code_window": [
"\tprivate buildDomNode(appendCaseSensitiveLabel: string, appendWholeWordsLabel: string, appendRegexLabel: string, history: string[], flexibleHeight: boolean): void {\n",
"\t\tthis.domNode = document.createElement('div');\n",
"\t\tthis.domNode.style.width = this.width + 'px';\n",
"\t\tdom.addClass(this.domNode, 'monaco-findInput');\n",
"\n",
"\t\tthis.inputBox = this._register(new HistoryInputBox(this.domNode, this.contextViewProvider, {\n",
"\t\t\tplaceholder: this.placeholder || '',\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/base/browser/ui/findinput/findInput.ts",
"type": "replace",
"edit_start_line_idx": 287
} | /*---------------------------------------------------------------------------------------------
* 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 * as Objects from 'vs/base/common/objects';
import { asPromise } from 'vs/base/common/async';
import { Event, Emitter } from 'vs/base/common/event';
import { win32 } from 'vs/base/node/processes';
import { IExtensionDescription } from 'vs/workbench/services/extensions/common/extensions';
import { MainContext, MainThreadTaskShape, ExtHostTaskShape, IMainContext } from 'vs/workbench/api/node/extHost.protocol';
import * as types from 'vs/workbench/api/node/extHostTypes';
import { ExtHostWorkspace, ExtHostWorkspaceProvider } from 'vs/workbench/api/node/extHostWorkspace';
import * as vscode from 'vscode';
import {
TaskDefinitionDTO, TaskExecutionDTO, TaskPresentationOptionsDTO, ProcessExecutionOptionsDTO, ProcessExecutionDTO,
ShellExecutionOptionsDTO, ShellExecutionDTO, TaskDTO, TaskHandleDTO, TaskFilterDTO, TaskProcessStartedDTO, TaskProcessEndedDTO, TaskSystemInfoDTO, TaskSetDTO
} from '../shared/tasks';
import { ExtHostVariableResolverService } from 'vs/workbench/api/node/extHostDebugService';
import { ExtHostDocumentsAndEditors } from 'vs/workbench/api/node/extHostDocumentsAndEditors';
import { ExtHostConfiguration } from 'vs/workbench/api/node/extHostConfiguration';
import { IWorkspaceFolder } from 'vs/platform/workspace/common/workspace';
import { CancellationToken } from 'vs/base/common/cancellation';
namespace TaskDefinitionDTO {
export function from(value: vscode.TaskDefinition): TaskDefinitionDTO {
if (value === undefined || value === null) {
return undefined;
}
return value;
}
export function to(value: TaskDefinitionDTO): vscode.TaskDefinition {
if (value === undefined || value === null) {
return undefined;
}
return value;
}
}
namespace TaskPresentationOptionsDTO {
export function from(value: vscode.TaskPresentationOptions): TaskPresentationOptionsDTO {
if (value === undefined || value === null) {
return undefined;
}
return value;
}
export function to(value: TaskPresentationOptionsDTO): vscode.TaskPresentationOptions {
if (value === undefined || value === null) {
return undefined;
}
return value;
}
}
namespace ProcessExecutionOptionsDTO {
export function from(value: vscode.ProcessExecutionOptions): ProcessExecutionOptionsDTO {
if (value === undefined || value === null) {
return undefined;
}
return value;
}
export function to(value: ProcessExecutionOptionsDTO): vscode.ProcessExecutionOptions {
if (value === undefined || value === null) {
return undefined;
}
return value;
}
}
namespace ProcessExecutionDTO {
export function is(value: ShellExecutionDTO | ProcessExecutionDTO): value is ProcessExecutionDTO {
let candidate = value as ProcessExecutionDTO;
return candidate && !!candidate.process;
}
export function from(value: vscode.ProcessExecution): ProcessExecutionDTO {
if (value === undefined || value === null) {
return undefined;
}
let result: ProcessExecutionDTO = {
process: value.process,
args: value.args
};
if (value.options) {
result.options = ProcessExecutionOptionsDTO.from(value.options);
}
return result;
}
export function to(value: ProcessExecutionDTO): types.ProcessExecution {
if (value === undefined || value === null) {
return undefined;
}
return new types.ProcessExecution(value.process, value.args, value.options);
}
}
namespace ShellExecutionOptionsDTO {
export function from(value: vscode.ShellExecutionOptions): ShellExecutionOptionsDTO {
if (value === undefined || value === null) {
return undefined;
}
return value;
}
export function to(value: ShellExecutionOptionsDTO): vscode.ShellExecutionOptions {
if (value === undefined || value === null) {
return undefined;
}
return value;
}
}
namespace ShellExecutionDTO {
export function is(value: ShellExecutionDTO | ProcessExecutionDTO): value is ShellExecutionDTO {
let candidate = value as ShellExecutionDTO;
return candidate && (!!candidate.commandLine || !!candidate.command);
}
export function from(value: vscode.ShellExecution): ShellExecutionDTO {
if (value === undefined || value === null) {
return undefined;
}
let result: ShellExecutionDTO = {
};
if (value.commandLine !== undefined) {
result.commandLine = value.commandLine;
} else {
result.command = value.command;
result.args = value.args;
}
if (value.options) {
result.options = ShellExecutionOptionsDTO.from(value.options);
}
return result;
}
export function to(value: ShellExecutionDTO): types.ShellExecution {
if (value === undefined || value === null) {
return undefined;
}
if (value.commandLine) {
return new types.ShellExecution(value.commandLine, value.options);
} else {
return new types.ShellExecution(value.command, value.args ? value.args : [], value.options);
}
}
}
namespace TaskHandleDTO {
export function from(value: types.Task): TaskHandleDTO {
let folder: UriComponents;
if (value.scope !== undefined && typeof value.scope !== 'number') {
folder = value.scope.uri;
}
return {
id: value._id,
workspaceFolder: folder
};
}
}
namespace TaskDTO {
export function fromMany(tasks: vscode.Task[], extension: IExtensionDescription): TaskDTO[] {
if (tasks === undefined || tasks === null) {
return [];
}
let result: TaskDTO[] = [];
for (let task of tasks) {
let converted = from(task, extension);
if (converted) {
result.push(converted);
}
}
return result;
}
export function from(value: vscode.Task, extension: IExtensionDescription): TaskDTO {
if (value === undefined || value === null) {
return undefined;
}
let execution: ShellExecutionDTO | ProcessExecutionDTO;
if (value.execution instanceof types.ProcessExecution) {
execution = ProcessExecutionDTO.from(value.execution);
} else if (value.execution instanceof types.ShellExecution) {
execution = ShellExecutionDTO.from(value.execution);
}
let definition: TaskDefinitionDTO = TaskDefinitionDTO.from(value.definition);
let scope: number | UriComponents;
if (value.scope) {
if (typeof value.scope === 'number') {
scope = value.scope;
} else {
scope = value.scope.uri;
}
} else {
// To continue to support the deprecated task constructor that doesn't take a scope, we must add a scope here:
scope = types.TaskScope.Workspace;
}
if (!definition || !scope) {
return undefined;
}
let group = (value.group as types.TaskGroup) ? (value.group as types.TaskGroup).id : undefined;
let result: TaskDTO = {
_id: (value as types.Task)._id,
definition,
name: value.name,
source: {
extensionId: extension.identifier.value,
label: value.source,
scope: scope
},
execution,
isBackground: value.isBackground,
group: group,
presentationOptions: TaskPresentationOptionsDTO.from(value.presentationOptions),
problemMatchers: value.problemMatchers,
hasDefinedMatchers: (value as types.Task).hasDefinedMatchers,
runOptions: (<vscode.Task>value).runOptions ? (<vscode.Task>value).runOptions : { reevaluateOnRerun: true },
};
return result;
}
export function to(value: TaskDTO, workspace: ExtHostWorkspaceProvider): types.Task {
if (value === undefined || value === null) {
return undefined;
}
let execution: types.ShellExecution | types.ProcessExecution;
if (ProcessExecutionDTO.is(value.execution)) {
execution = ProcessExecutionDTO.to(value.execution);
} else if (ShellExecutionDTO.is(value.execution)) {
execution = ShellExecutionDTO.to(value.execution);
}
let definition: vscode.TaskDefinition = TaskDefinitionDTO.to(value.definition);
let scope: vscode.TaskScope.Global | vscode.TaskScope.Workspace | vscode.WorkspaceFolder;
if (value.source) {
if (value.source.scope !== undefined) {
if (typeof value.source.scope === 'number') {
scope = value.source.scope;
} else {
scope = workspace.resolveWorkspaceFolder(URI.revive(value.source.scope));
}
} else {
scope = types.TaskScope.Workspace;
}
}
if (!definition || !scope) {
return undefined;
}
let result = new types.Task(definition, scope, value.name, value.source.label, execution, value.problemMatchers);
if (value.isBackground !== undefined) {
result.isBackground = value.isBackground;
}
if (value.group !== undefined) {
result.group = types.TaskGroup.from(value.group);
}
if (value.presentationOptions) {
result.presentationOptions = TaskPresentationOptionsDTO.to(value.presentationOptions);
}
if (value._id) {
result._id = value._id;
}
return result;
}
}
namespace TaskFilterDTO {
export function from(value: vscode.TaskFilter): TaskFilterDTO {
return value;
}
export function to(value: TaskFilterDTO): vscode.TaskFilter {
if (!value) {
return undefined;
}
return Objects.assign(Object.create(null), value);
}
}
class TaskExecutionImpl implements vscode.TaskExecution {
constructor(private readonly _tasks: ExtHostTask, readonly _id: string, private readonly _task: vscode.Task) {
}
public get task(): vscode.Task {
return this._task;
}
public terminate(): void {
this._tasks.terminateTask(this);
}
public fireDidStartProcess(value: TaskProcessStartedDTO): void {
}
public fireDidEndProcess(value: TaskProcessEndedDTO): void {
}
}
namespace TaskExecutionDTO {
export function to(value: TaskExecutionDTO, tasks: ExtHostTask, workspaceProvider: ExtHostWorkspaceProvider): vscode.TaskExecution {
return new TaskExecutionImpl(tasks, value.id, TaskDTO.to(value.task, workspaceProvider));
}
export function from(value: vscode.TaskExecution): TaskExecutionDTO {
return {
id: (value as TaskExecutionImpl)._id,
task: undefined
};
}
}
interface HandlerData {
provider: vscode.TaskProvider;
extension: IExtensionDescription;
}
export class ExtHostTask implements ExtHostTaskShape {
private _proxy: MainThreadTaskShape;
private _workspaceService: ExtHostWorkspace;
private _editorService: ExtHostDocumentsAndEditors;
private _configurationService: ExtHostConfiguration;
private _handleCounter: number;
private _handlers: Map<number, HandlerData>;
private _taskExecutions: Map<string, TaskExecutionImpl>;
private readonly _onDidExecuteTask: Emitter<vscode.TaskStartEvent> = new Emitter<vscode.TaskStartEvent>();
private readonly _onDidTerminateTask: Emitter<vscode.TaskEndEvent> = new Emitter<vscode.TaskEndEvent>();
private readonly _onDidTaskProcessStarted: Emitter<vscode.TaskProcessStartEvent> = new Emitter<vscode.TaskProcessStartEvent>();
private readonly _onDidTaskProcessEnded: Emitter<vscode.TaskProcessEndEvent> = new Emitter<vscode.TaskProcessEndEvent>();
constructor(mainContext: IMainContext, workspaceService: ExtHostWorkspace, editorService: ExtHostDocumentsAndEditors, configurationService: ExtHostConfiguration) {
this._proxy = mainContext.getProxy(MainContext.MainThreadTask);
this._workspaceService = workspaceService;
this._editorService = editorService;
this._configurationService = configurationService;
this._handleCounter = 0;
this._handlers = new Map<number, HandlerData>();
this._taskExecutions = new Map<string, TaskExecutionImpl>();
}
public registerTaskProvider(extension: IExtensionDescription, provider: vscode.TaskProvider): vscode.Disposable {
if (!provider) {
return new types.Disposable(() => { });
}
let handle = this.nextHandle();
this._handlers.set(handle, { provider, extension });
this._proxy.$registerTaskProvider(handle);
return new types.Disposable(() => {
this._handlers.delete(handle);
this._proxy.$unregisterTaskProvider(handle);
});
}
public registerTaskSystem(scheme: string, info: TaskSystemInfoDTO): void {
this._proxy.$registerTaskSystem(scheme, info);
}
public fetchTasks(filter?: vscode.TaskFilter): Promise<vscode.Task[]> {
return this._proxy.$fetchTasks(TaskFilterDTO.from(filter)).then(async (values) => {
let result: vscode.Task[] = [];
const workspaceProvider = await this._workspaceService.getWorkspaceProvider();
for (let value of values) {
let task = TaskDTO.to(value, workspaceProvider);
if (task) {
result.push(task);
}
}
return result;
});
}
public async executeTask(extension: IExtensionDescription, task: vscode.Task): Promise<vscode.TaskExecution> {
const workspaceProvider = await this._workspaceService.getWorkspaceProvider();
let tTask = (task as types.Task);
// We have a preserved ID. So the task didn't change.
if (tTask._id !== undefined) {
return this._proxy.$executeTask(TaskHandleDTO.from(tTask)).then(value => this.getTaskExecution(value, workspaceProvider, task));
} else {
let dto = TaskDTO.from(task, extension);
if (dto === undefined) {
return Promise.reject(new Error('Task is not valid'));
}
return this._proxy.$executeTask(dto).then(value => this.getTaskExecution(value, workspaceProvider, task));
}
}
public get taskExecutions(): vscode.TaskExecution[] {
let result: vscode.TaskExecution[] = [];
this._taskExecutions.forEach(value => result.push(value));
return result;
}
public terminateTask(execution: vscode.TaskExecution): Promise<void> {
if (!(execution instanceof TaskExecutionImpl)) {
throw new Error('No valid task execution provided');
}
return this._proxy.$terminateTask((execution as TaskExecutionImpl)._id);
}
public get onDidStartTask(): Event<vscode.TaskStartEvent> {
return this._onDidExecuteTask.event;
}
public async $onDidStartTask(execution: TaskExecutionDTO): Promise<void> {
const workspaceProvider = await this._workspaceService.getWorkspaceProvider();
this._onDidExecuteTask.fire({
execution: this.getTaskExecution(execution, workspaceProvider)
});
}
public get onDidEndTask(): Event<vscode.TaskEndEvent> {
return this._onDidTerminateTask.event;
}
public async $OnDidEndTask(execution: TaskExecutionDTO): Promise<void> {
const workspaceProvider = await this._workspaceService.getWorkspaceProvider();
const _execution = this.getTaskExecution(execution, workspaceProvider);
this._taskExecutions.delete(execution.id);
this._onDidTerminateTask.fire({
execution: _execution
});
}
public get onDidStartTaskProcess(): Event<vscode.TaskProcessStartEvent> {
return this._onDidTaskProcessStarted.event;
}
public async $onDidStartTaskProcess(value: TaskProcessStartedDTO): Promise<void> {
const workspaceProvider = await this._workspaceService.getWorkspaceProvider();
const execution = this.getTaskExecution(value.id, workspaceProvider);
if (execution) {
this._onDidTaskProcessStarted.fire({
execution: execution,
processId: value.processId
});
}
}
public get onDidEndTaskProcess(): Event<vscode.TaskProcessEndEvent> {
return this._onDidTaskProcessEnded.event;
}
public async $onDidEndTaskProcess(value: TaskProcessEndedDTO): Promise<void> {
const workspaceProvider = await this._workspaceService.getWorkspaceProvider();
const execution = this.getTaskExecution(value.id, workspaceProvider);
if (execution) {
this._onDidTaskProcessEnded.fire({
execution: execution,
exitCode: value.exitCode
});
}
}
public $provideTasks(handle: number, validTypes: { [key: string]: boolean; }): Thenable<TaskSetDTO> {
let handler = this._handlers.get(handle);
if (!handler) {
return Promise.reject(new Error('no handler found'));
}
return asPromise(() => handler.provider.provideTasks(CancellationToken.None)).then(value => {
let sanitized: vscode.Task[] = [];
for (let task of value) {
if (task.definition && validTypes[task.definition.type] === true) {
sanitized.push(task);
} else {
sanitized.push(task);
console.warn(`The task [${task.source}, ${task.name}] uses an undefined task type. The task will be ignored in the future.`);
}
}
return {
tasks: TaskDTO.fromMany(sanitized, handler.extension),
extension: handler.extension
};
});
}
public async $resolveVariables(uriComponents: UriComponents, toResolve: { process?: { name: string; cwd?: string; path?: string }, variables: string[] }): Promise<{ process?: string, variables: { [key: string]: string; } }> {
const configProvider = await this._configurationService.getConfigProvider();
const workspaceProvider = await this._workspaceService.getWorkspaceProvider();
let uri: URI = URI.revive(uriComponents);
let result = {
process: undefined as string,
variables: Object.create(null)
};
let workspaceFolder = workspaceProvider.resolveWorkspaceFolder(uri);
let resolver = new ExtHostVariableResolverService(workspaceProvider, this._editorService, configProvider);
let ws: IWorkspaceFolder = {
uri: workspaceFolder.uri,
name: workspaceFolder.name,
index: workspaceFolder.index,
toResource: () => {
throw new Error('Not implemented');
}
};
for (let variable of toResolve.variables) {
result.variables[variable] = resolver.resolve(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] = resolver.resolve(ws, paths[i]);
}
}
result.process = win32.findExecutable(
resolver.resolve(ws, toResolve.process.name),
toResolve.process.cwd !== undefined ? resolver.resolve(ws, toResolve.process.cwd) : undefined,
paths
);
}
return result;
}
private nextHandle(): number {
return this._handleCounter++;
}
private getTaskExecution(execution: TaskExecutionDTO | string, workspaceProvider: ExtHostWorkspaceProvider, task?: vscode.Task): TaskExecutionImpl {
if (typeof execution === 'string') {
return this._taskExecutions.get(execution);
}
let result: TaskExecutionImpl = this._taskExecutions.get(execution.id);
if (result) {
return result;
}
result = new TaskExecutionImpl(this, execution.id, task ? task : TaskDTO.to(execution.task, workspaceProvider));
this._taskExecutions.set(execution.id, result);
return result;
}
}
| src/vs/workbench/api/node/extHostTask.ts | 0 | https://github.com/microsoft/vscode/commit/bbff11633c7e56e7fd5d16cc20daa9a3284afbfe | [
0.00017564071458764374,
0.00017108851170632988,
0.00016245579172391444,
0.00017176095570903271,
0.000002556225808802992
]
|
{
"id": 8,
"code_window": [
"\tprivate buildDomNode(appendCaseSensitiveLabel: string, appendWholeWordsLabel: string, appendRegexLabel: string, history: string[], flexibleHeight: boolean): void {\n",
"\t\tthis.domNode = document.createElement('div');\n",
"\t\tthis.domNode.style.width = this.width + 'px';\n",
"\t\tdom.addClass(this.domNode, 'monaco-findInput');\n",
"\n",
"\t\tthis.inputBox = this._register(new HistoryInputBox(this.domNode, this.contextViewProvider, {\n",
"\t\t\tplaceholder: this.placeholder || '',\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/base/browser/ui/findinput/findInput.ts",
"type": "replace",
"edit_start_line_idx": 287
} | <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16"><path d="M13.451 5.609l-.579-.939-1.068.812-.076.094c-.335.415-.927 1.341-1.124 2.876l-.021.165.033.163.071.345c0 1.654-1.346 3-3 3-.795 0-1.545-.311-2.107-.868-.563-.567-.873-1.317-.873-2.111 0-1.431 1.007-2.632 2.351-2.929v2.926s2.528-2.087 2.984-2.461h.012l3.061-2.582-4.919-4.1h-1.137v2.404c-3.429.318-6.121 3.211-6.121 6.721 0 1.809.707 3.508 1.986 4.782 1.277 1.282 2.976 1.988 4.784 1.988 3.722 0 6.75-3.028 6.75-6.75 0-1.245-.349-2.468-1.007-3.536z" fill="#2D2D30"/><path d="M12.6 6.134l-.094.071c-.269.333-.746 1.096-.91 2.375.057.277.092.495.092.545 0 2.206-1.794 4-4 4-1.098 0-2.093-.445-2.817-1.164-.718-.724-1.163-1.718-1.163-2.815 0-2.206 1.794-4 4-4l.351.025v1.85s1.626-1.342 1.631-1.339l1.869-1.577-3.5-2.917v2.218l-.371-.03c-3.176 0-5.75 2.574-5.75 5.75 0 1.593.648 3.034 1.695 4.076 1.042 1.046 2.482 1.694 4.076 1.694 3.176 0 5.75-2.574 5.75-5.75-.001-1.106-.318-2.135-.859-3.012z" fill="#C5C5C5"/></svg> | src/vs/workbench/contrib/search/browser/media/Refresh_inverse.svg | 0 | https://github.com/microsoft/vscode/commit/bbff11633c7e56e7fd5d16cc20daa9a3284afbfe | [
0.0003414562961552292,
0.0003414562961552292,
0.0003414562961552292,
0.0003414562961552292,
0
]
|
{
"id": 9,
"code_window": [
"\t\tthis._register(this.regex.onChange(viaKeyboard => {\n",
"\t\t\tthis._onDidOptionChange.fire(viaKeyboard);\n",
"\t\t\tif (!viaKeyboard && this.fixFocusOnOptionClickEnabled) {\n",
"\t\t\t\tthis.inputBox.focus();\n",
"\t\t\t}\n",
"\t\t\tthis.setInputWidth();\n",
"\t\t\tthis.validate();\n",
"\t\t}));\n",
"\t\tthis._register(this.regex.onKeyDown(e => {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/base/browser/ui/findinput/findInput.ts",
"type": "replace",
"edit_start_line_idx": 322
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import 'vs/css!./findInput';
import * as nls from 'vs/nls';
import * as dom from 'vs/base/browser/dom';
import { IMessage as InputBoxMessage, IInputValidator, IInputBoxStyles, HistoryInputBox } from 'vs/base/browser/ui/inputbox/inputBox';
import { IContextViewProvider } from 'vs/base/browser/ui/contextview/contextview';
import { Widget } from 'vs/base/browser/ui/widget';
import { Event, Emitter } from 'vs/base/common/event';
import { IKeyboardEvent } from 'vs/base/browser/keyboardEvent';
import { IMouseEvent } from 'vs/base/browser/mouseEvent';
import { KeyCode } from 'vs/base/common/keyCodes';
import { CaseSensitiveCheckbox, WholeWordsCheckbox, RegexCheckbox } from 'vs/base/browser/ui/findinput/findInputCheckboxes';
import { Color } from 'vs/base/common/color';
import { ICheckboxStyles } from 'vs/base/browser/ui/checkbox/checkbox';
export interface IFindInputOptions extends IFindInputStyles {
readonly placeholder?: string;
readonly width?: number;
readonly validation?: IInputValidator;
readonly label: string;
readonly flexibleHeight?: boolean;
readonly appendCaseSensitiveLabel?: string;
readonly appendWholeWordsLabel?: string;
readonly appendRegexLabel?: string;
readonly history?: string[];
}
export interface IFindInputStyles extends IInputBoxStyles {
inputActiveOptionBorder?: Color;
}
const NLS_DEFAULT_LABEL = nls.localize('defaultLabel', "input");
export class FindInput extends Widget {
static readonly OPTION_CHANGE: string = 'optionChange';
private contextViewProvider: IContextViewProvider;
private width: number;
private placeholder: string;
private validation?: IInputValidator;
private label: string;
private fixFocusOnOptionClickEnabled = true;
private inputActiveOptionBorder?: Color;
private inputBackground?: Color;
private inputForeground?: Color;
private inputBorder?: Color;
private inputValidationInfoBorder?: Color;
private inputValidationInfoBackground?: Color;
private inputValidationInfoForeground?: Color;
private inputValidationWarningBorder?: Color;
private inputValidationWarningBackground?: Color;
private inputValidationWarningForeground?: Color;
private inputValidationErrorBorder?: Color;
private inputValidationErrorBackground?: Color;
private inputValidationErrorForeground?: Color;
private regex: RegexCheckbox;
private wholeWords: WholeWordsCheckbox;
private caseSensitive: CaseSensitiveCheckbox;
public domNode: HTMLElement;
public inputBox: HistoryInputBox;
private readonly _onDidOptionChange = this._register(new Emitter<boolean>());
public readonly onDidOptionChange: Event<boolean /* via keyboard */> = this._onDidOptionChange.event;
private readonly _onKeyDown = this._register(new Emitter<IKeyboardEvent>());
public readonly onKeyDown: Event<IKeyboardEvent> = this._onKeyDown.event;
private readonly _onMouseDown = this._register(new Emitter<IMouseEvent>());
public readonly onMouseDown: Event<IMouseEvent> = this._onMouseDown.event;
private readonly _onInput = this._register(new Emitter<void>());
public readonly onInput: Event<void> = this._onInput.event;
private readonly _onKeyUp = this._register(new Emitter<IKeyboardEvent>());
public readonly onKeyUp: Event<IKeyboardEvent> = this._onKeyUp.event;
private _onCaseSensitiveKeyDown = this._register(new Emitter<IKeyboardEvent>());
public readonly onCaseSensitiveKeyDown: Event<IKeyboardEvent> = this._onCaseSensitiveKeyDown.event;
private _onRegexKeyDown = this._register(new Emitter<IKeyboardEvent>());
public readonly onRegexKeyDown: Event<IKeyboardEvent> = this._onRegexKeyDown.event;
constructor(parent: HTMLElement | null, contextViewProvider: IContextViewProvider, private readonly _showOptionButtons: boolean, options: IFindInputOptions) {
super();
this.contextViewProvider = contextViewProvider;
this.width = options.width || 100;
this.placeholder = options.placeholder || '';
this.validation = options.validation;
this.label = options.label || NLS_DEFAULT_LABEL;
this.inputActiveOptionBorder = options.inputActiveOptionBorder;
this.inputBackground = options.inputBackground;
this.inputForeground = options.inputForeground;
this.inputBorder = options.inputBorder;
this.inputValidationInfoBorder = options.inputValidationInfoBorder;
this.inputValidationInfoBackground = options.inputValidationInfoBackground;
this.inputValidationInfoForeground = options.inputValidationInfoForeground;
this.inputValidationWarningBorder = options.inputValidationWarningBorder;
this.inputValidationWarningBackground = options.inputValidationWarningBackground;
this.inputValidationWarningForeground = options.inputValidationWarningForeground;
this.inputValidationErrorBorder = options.inputValidationErrorBorder;
this.inputValidationErrorBackground = options.inputValidationErrorBackground;
this.inputValidationErrorForeground = options.inputValidationErrorForeground;
this.buildDomNode(options.appendCaseSensitiveLabel || '', options.appendWholeWordsLabel || '', options.appendRegexLabel || '', options.history || [], !!options.flexibleHeight);
if (parent) {
parent.appendChild(this.domNode);
}
this.onkeydown(this.inputBox.inputElement, (e) => this._onKeyDown.fire(e));
this.onkeyup(this.inputBox.inputElement, (e) => this._onKeyUp.fire(e));
this.oninput(this.inputBox.inputElement, (e) => this._onInput.fire());
this.onmousedown(this.inputBox.inputElement, (e) => this._onMouseDown.fire(e));
}
public enable(): void {
dom.removeClass(this.domNode, 'disabled');
this.inputBox.enable();
this.regex.enable();
this.wholeWords.enable();
this.caseSensitive.enable();
}
public disable(): void {
dom.addClass(this.domNode, 'disabled');
this.inputBox.disable();
this.regex.disable();
this.wholeWords.disable();
this.caseSensitive.disable();
}
public setFocusInputOnOptionClick(value: boolean): void {
this.fixFocusOnOptionClickEnabled = value;
}
public setEnabled(enabled: boolean): void {
if (enabled) {
this.enable();
} else {
this.disable();
}
}
public clear(): void {
this.clearValidation();
this.setValue('');
this.focus();
}
public setWidth(newWidth: number): void {
this.width = newWidth;
this.domNode.style.width = this.width + 'px';
this.contextViewProvider.layout();
this.setInputWidth();
}
public getValue(): string {
return this.inputBox.value;
}
public setValue(value: string): void {
if (this.inputBox.value !== value) {
this.inputBox.value = value;
}
}
public onSearchSubmit(): void {
this.inputBox.addToHistory();
}
public style(styles: IFindInputStyles): void {
this.inputActiveOptionBorder = styles.inputActiveOptionBorder;
this.inputBackground = styles.inputBackground;
this.inputForeground = styles.inputForeground;
this.inputBorder = styles.inputBorder;
this.inputValidationInfoBackground = styles.inputValidationInfoBackground;
this.inputValidationInfoForeground = styles.inputValidationInfoForeground;
this.inputValidationInfoBorder = styles.inputValidationInfoBorder;
this.inputValidationWarningBackground = styles.inputValidationWarningBackground;
this.inputValidationWarningForeground = styles.inputValidationWarningForeground;
this.inputValidationWarningBorder = styles.inputValidationWarningBorder;
this.inputValidationErrorBackground = styles.inputValidationErrorBackground;
this.inputValidationErrorForeground = styles.inputValidationErrorForeground;
this.inputValidationErrorBorder = styles.inputValidationErrorBorder;
this.applyStyles();
}
protected applyStyles(): void {
if (this.domNode) {
const checkBoxStyles: ICheckboxStyles = {
inputActiveOptionBorder: this.inputActiveOptionBorder,
};
this.regex.style(checkBoxStyles);
this.wholeWords.style(checkBoxStyles);
this.caseSensitive.style(checkBoxStyles);
const inputBoxStyles: IInputBoxStyles = {
inputBackground: this.inputBackground,
inputForeground: this.inputForeground,
inputBorder: this.inputBorder,
inputValidationInfoBackground: this.inputValidationInfoBackground,
inputValidationInfoForeground: this.inputValidationInfoForeground,
inputValidationInfoBorder: this.inputValidationInfoBorder,
inputValidationWarningBackground: this.inputValidationWarningBackground,
inputValidationWarningForeground: this.inputValidationWarningForeground,
inputValidationWarningBorder: this.inputValidationWarningBorder,
inputValidationErrorBackground: this.inputValidationErrorBackground,
inputValidationErrorForeground: this.inputValidationErrorForeground,
inputValidationErrorBorder: this.inputValidationErrorBorder
};
this.inputBox.style(inputBoxStyles);
}
}
public select(): void {
this.inputBox.select();
}
public focus(): void {
this.inputBox.focus();
}
public getCaseSensitive(): boolean {
return this.caseSensitive.checked;
}
public setCaseSensitive(value: boolean): void {
this.caseSensitive.checked = value;
this.setInputWidth();
}
public getWholeWords(): boolean {
return this.wholeWords.checked;
}
public setWholeWords(value: boolean): void {
this.wholeWords.checked = value;
this.setInputWidth();
}
public getRegex(): boolean {
return this.regex.checked;
}
public setRegex(value: boolean): void {
this.regex.checked = value;
this.setInputWidth();
this.validate();
}
public focusOnCaseSensitive(): void {
this.caseSensitive.focus();
}
public focusOnRegex(): void {
this.regex.focus();
}
private _lastHighlightFindOptions: number = 0;
public highlightFindOptions(): void {
dom.removeClass(this.domNode, 'highlight-' + (this._lastHighlightFindOptions));
this._lastHighlightFindOptions = 1 - this._lastHighlightFindOptions;
dom.addClass(this.domNode, 'highlight-' + (this._lastHighlightFindOptions));
}
private setInputWidth(): void {
let w = this.width - this.caseSensitive.width() - this.wholeWords.width() - this.regex.width();
this.inputBox.width = w;
this.inputBox.layout();
}
private buildDomNode(appendCaseSensitiveLabel: string, appendWholeWordsLabel: string, appendRegexLabel: string, history: string[], flexibleHeight: boolean): void {
this.domNode = document.createElement('div');
this.domNode.style.width = this.width + 'px';
dom.addClass(this.domNode, 'monaco-findInput');
this.inputBox = this._register(new HistoryInputBox(this.domNode, this.contextViewProvider, {
placeholder: this.placeholder || '',
ariaLabel: this.label || '',
validationOptions: {
validation: this.validation
},
inputBackground: this.inputBackground,
inputForeground: this.inputForeground,
inputBorder: this.inputBorder,
inputValidationInfoBackground: this.inputValidationInfoBackground,
inputValidationInfoForeground: this.inputValidationInfoForeground,
inputValidationInfoBorder: this.inputValidationInfoBorder,
inputValidationWarningBackground: this.inputValidationWarningBackground,
inputValidationWarningForeground: this.inputValidationWarningForeground,
inputValidationWarningBorder: this.inputValidationWarningBorder,
inputValidationErrorBackground: this.inputValidationErrorBackground,
inputValidationErrorForeground: this.inputValidationErrorForeground,
inputValidationErrorBorder: this.inputValidationErrorBorder,
history,
flexibleHeight
}));
this.regex = this._register(new RegexCheckbox({
appendTitle: appendRegexLabel,
isChecked: false,
inputActiveOptionBorder: this.inputActiveOptionBorder
}));
this._register(this.regex.onChange(viaKeyboard => {
this._onDidOptionChange.fire(viaKeyboard);
if (!viaKeyboard && this.fixFocusOnOptionClickEnabled) {
this.inputBox.focus();
}
this.setInputWidth();
this.validate();
}));
this._register(this.regex.onKeyDown(e => {
this._onRegexKeyDown.fire(e);
}));
this.wholeWords = this._register(new WholeWordsCheckbox({
appendTitle: appendWholeWordsLabel,
isChecked: false,
inputActiveOptionBorder: this.inputActiveOptionBorder
}));
this._register(this.wholeWords.onChange(viaKeyboard => {
this._onDidOptionChange.fire(viaKeyboard);
if (!viaKeyboard && this.fixFocusOnOptionClickEnabled) {
this.inputBox.focus();
}
this.setInputWidth();
this.validate();
}));
this.caseSensitive = this._register(new CaseSensitiveCheckbox({
appendTitle: appendCaseSensitiveLabel,
isChecked: false,
inputActiveOptionBorder: this.inputActiveOptionBorder
}));
this._register(this.caseSensitive.onChange(viaKeyboard => {
this._onDidOptionChange.fire(viaKeyboard);
if (!viaKeyboard && this.fixFocusOnOptionClickEnabled) {
this.inputBox.focus();
}
this.setInputWidth();
this.validate();
}));
this._register(this.caseSensitive.onKeyDown(e => {
this._onCaseSensitiveKeyDown.fire(e);
}));
if (this._showOptionButtons) {
this.inputBox.inputElement.style.paddingRight = (this.caseSensitive.width() + this.wholeWords.width() + this.regex.width()) + 'px';
}
// Arrow-Key support to navigate between options
let indexes = [this.caseSensitive.domNode, this.wholeWords.domNode, this.regex.domNode];
this.onkeydown(this.domNode, (event: IKeyboardEvent) => {
if (event.equals(KeyCode.LeftArrow) || event.equals(KeyCode.RightArrow) || event.equals(KeyCode.Escape)) {
let index = indexes.indexOf(<HTMLElement>document.activeElement);
if (index >= 0) {
let newIndex: number = -1;
if (event.equals(KeyCode.RightArrow)) {
newIndex = (index + 1) % indexes.length;
} else if (event.equals(KeyCode.LeftArrow)) {
if (index === 0) {
newIndex = indexes.length - 1;
} else {
newIndex = index - 1;
}
}
if (event.equals(KeyCode.Escape)) {
indexes[index].blur();
} else if (newIndex >= 0) {
indexes[newIndex].focus();
}
dom.EventHelper.stop(event, true);
}
}
});
this.setInputWidth();
let controls = document.createElement('div');
controls.className = 'controls';
controls.style.display = this._showOptionButtons ? 'block' : 'none';
controls.appendChild(this.caseSensitive.domNode);
controls.appendChild(this.wholeWords.domNode);
controls.appendChild(this.regex.domNode);
this.domNode.appendChild(controls);
}
public validate(): void {
if (this.inputBox) {
this.inputBox.validate();
}
}
public showMessage(message: InputBoxMessage): void {
if (this.inputBox) {
this.inputBox.showMessage(message);
}
}
public clearMessage(): void {
if (this.inputBox) {
this.inputBox.hideMessage();
}
}
private clearValidation(): void {
if (this.inputBox) {
this.inputBox.hideMessage();
}
}
public dispose(): void {
super.dispose();
}
}
| src/vs/base/browser/ui/findinput/findInput.ts | 1 | https://github.com/microsoft/vscode/commit/bbff11633c7e56e7fd5d16cc20daa9a3284afbfe | [
0.9760608077049255,
0.04957687482237816,
0.00016490703274030238,
0.0013949796557426453,
0.1750522404909134
]
|
{
"id": 9,
"code_window": [
"\t\tthis._register(this.regex.onChange(viaKeyboard => {\n",
"\t\t\tthis._onDidOptionChange.fire(viaKeyboard);\n",
"\t\t\tif (!viaKeyboard && this.fixFocusOnOptionClickEnabled) {\n",
"\t\t\t\tthis.inputBox.focus();\n",
"\t\t\t}\n",
"\t\t\tthis.setInputWidth();\n",
"\t\t\tthis.validate();\n",
"\t\t}));\n",
"\t\tthis._register(this.regex.onKeyDown(e => {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/base/browser/ui/findinput/findInput.ts",
"type": "replace",
"edit_start_line_idx": 322
} | /*---------------------------------------------------------------------------------------------
* 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 { CharCode } from 'vs/base/common/charCode';
import * as platform from 'vs/base/common/platform';
import { URI } from 'vs/base/common/uri';
import { EditOperation } from 'vs/editor/common/core/editOperation';
import { Range } from 'vs/editor/common/core/range';
import { createStringBuilder } from 'vs/editor/common/core/stringBuilder';
import { DefaultEndOfLine } from 'vs/editor/common/model';
import { TextModel, createTextBuffer } from 'vs/editor/common/model/textModel';
import { ModelServiceImpl } from 'vs/editor/common/services/modelServiceImpl';
import { ITextResourcePropertiesService } from 'vs/editor/common/services/resourceConfiguration';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { TestConfigurationService } from 'vs/platform/configuration/test/common/testConfigurationService';
const GENERATE_TESTS = false;
suite('ModelService', () => {
let modelService: ModelServiceImpl;
setup(() => {
const configService = new TestConfigurationService();
configService.setUserConfiguration('files', { 'eol': '\n' });
configService.setUserConfiguration('files', { 'eol': '\r\n' }, URI.file(platform.isWindows ? 'c:\\myroot' : '/myroot'));
modelService = new ModelServiceImpl(configService, new TestTextResourcePropertiesService(configService));
});
teardown(() => {
modelService.dispose();
});
test('EOL setting respected depending on root', () => {
const model1 = modelService.createModel('farboo', null, null);
const model2 = modelService.createModel('farboo', null, URI.file(platform.isWindows ? 'c:\\myroot\\myfile.txt' : '/myroot/myfile.txt'));
const model3 = modelService.createModel('farboo', null, URI.file(platform.isWindows ? 'c:\\other\\myfile.txt' : '/other/myfile.txt'));
assert.equal(model1.getOptions().defaultEOL, DefaultEndOfLine.LF);
assert.equal(model2.getOptions().defaultEOL, DefaultEndOfLine.CRLF);
assert.equal(model3.getOptions().defaultEOL, DefaultEndOfLine.LF);
});
test('_computeEdits no change', function () {
const model = TextModel.createFromString(
[
'This is line one', //16
'and this is line number two', //27
'it is followed by #3', //20
'and finished with the fourth.', //29
].join('\n')
);
const textBuffer = createTextBuffer(
[
'This is line one', //16
'and this is line number two', //27
'it is followed by #3', //20
'and finished with the fourth.', //29
].join('\n'),
DefaultEndOfLine.LF
);
const actual = ModelServiceImpl._computeEdits(model, textBuffer);
assert.deepEqual(actual, []);
});
test('_computeEdits first line changed', function () {
const model = TextModel.createFromString(
[
'This is line one', //16
'and this is line number two', //27
'it is followed by #3', //20
'and finished with the fourth.', //29
].join('\n')
);
const textBuffer = createTextBuffer(
[
'This is line One', //16
'and this is line number two', //27
'it is followed by #3', //20
'and finished with the fourth.', //29
].join('\n'),
DefaultEndOfLine.LF
);
const actual = ModelServiceImpl._computeEdits(model, textBuffer);
assert.deepEqual(actual, [
EditOperation.replaceMove(new Range(1, 1, 2, 1), 'This is line One\n')
]);
});
test('_computeEdits EOL changed', function () {
const model = TextModel.createFromString(
[
'This is line one', //16
'and this is line number two', //27
'it is followed by #3', //20
'and finished with the fourth.', //29
].join('\n')
);
const textBuffer = createTextBuffer(
[
'This is line one', //16
'and this is line number two', //27
'it is followed by #3', //20
'and finished with the fourth.', //29
].join('\r\n'),
DefaultEndOfLine.LF
);
const actual = ModelServiceImpl._computeEdits(model, textBuffer);
assert.deepEqual(actual, []);
});
test('_computeEdits EOL and other change 1', function () {
const model = TextModel.createFromString(
[
'This is line one', //16
'and this is line number two', //27
'it is followed by #3', //20
'and finished with the fourth.', //29
].join('\n')
);
const textBuffer = createTextBuffer(
[
'This is line One', //16
'and this is line number two', //27
'It is followed by #3', //20
'and finished with the fourth.', //29
].join('\r\n'),
DefaultEndOfLine.LF
);
const actual = ModelServiceImpl._computeEdits(model, textBuffer);
assert.deepEqual(actual, [
EditOperation.replaceMove(
new Range(1, 1, 4, 1),
[
'This is line One',
'and this is line number two',
'It is followed by #3',
''
].join('\r\n')
)
]);
});
test('_computeEdits EOL and other change 2', function () {
const model = TextModel.createFromString(
[
'package main', // 1
'func foo() {', // 2
'}' // 3
].join('\n')
);
const textBuffer = createTextBuffer(
[
'package main', // 1
'func foo() {', // 2
'}', // 3
''
].join('\r\n'),
DefaultEndOfLine.LF
);
const actual = ModelServiceImpl._computeEdits(model, textBuffer);
assert.deepEqual(actual, [
EditOperation.replaceMove(new Range(3, 2, 3, 2), '\r\n')
]);
});
test('generated1', () => {
const file1 = ['pram', 'okctibad', 'pjuwtemued', 'knnnm', 'u', ''];
const file2 = ['tcnr', 'rxwlicro', 'vnzy', '', '', 'pjzcogzur', 'ptmxyp', 'dfyshia', 'pee', 'ygg'];
assertComputeEdits(file1, file2);
});
test('generated2', () => {
const file1 = ['', 'itls', 'hrilyhesv', ''];
const file2 = ['vdl', '', 'tchgz', 'bhx', 'nyl'];
assertComputeEdits(file1, file2);
});
test('generated3', () => {
const file1 = ['ubrbrcv', 'wv', 'xodspybszt', 's', 'wednjxm', 'fklajt', 'fyfc', 'lvejgge', 'rtpjlodmmk', 'arivtgmjdm'];
const file2 = ['s', 'qj', 'tu', 'ur', 'qerhjjhyvx', 't'];
assertComputeEdits(file1, file2);
});
test('generated4', () => {
const file1 = ['ig', 'kh', 'hxegci', 'smvker', 'pkdmjjdqnv', 'vgkkqqx', '', 'jrzeb'];
const file2 = ['yk', ''];
assertComputeEdits(file1, file2);
});
test('does insertions in the middle of the document', () => {
const file1 = [
'line 1',
'line 2',
'line 3'
];
const file2 = [
'line 1',
'line 2',
'line 5',
'line 3'
];
assertComputeEdits(file1, file2);
});
test('does insertions at the end of the document', () => {
const file1 = [
'line 1',
'line 2',
'line 3'
];
const file2 = [
'line 1',
'line 2',
'line 3',
'line 4'
];
assertComputeEdits(file1, file2);
});
test('does insertions at the beginning of the document', () => {
const file1 = [
'line 1',
'line 2',
'line 3'
];
const file2 = [
'line 0',
'line 1',
'line 2',
'line 3'
];
assertComputeEdits(file1, file2);
});
test('does replacements', () => {
const file1 = [
'line 1',
'line 2',
'line 3'
];
const file2 = [
'line 1',
'line 7',
'line 3'
];
assertComputeEdits(file1, file2);
});
test('does deletions', () => {
const file1 = [
'line 1',
'line 2',
'line 3'
];
const file2 = [
'line 1',
'line 3'
];
assertComputeEdits(file1, file2);
});
test('does insert, replace, and delete', () => {
const file1 = [
'line 1',
'line 2',
'line 3',
'line 4',
'line 5',
];
const file2 = [
'line 0', // insert line 0
'line 1',
'replace line 2', // replace line 2
'line 3',
// delete line 4
'line 5',
];
assertComputeEdits(file1, file2);
});
});
function assertComputeEdits(lines1: string[], lines2: string[]): void {
const model = TextModel.createFromString(lines1.join('\n'));
const textBuffer = createTextBuffer(lines2.join('\n'), DefaultEndOfLine.LF);
// compute required edits
// let start = Date.now();
const edits = ModelServiceImpl._computeEdits(model, textBuffer);
// console.log(`took ${Date.now() - start} ms.`);
// apply edits
model.pushEditOperations([], edits, null);
assert.equal(model.getValue(), lines2.join('\n'));
}
function getRandomInt(min: number, max: number): number {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function getRandomString(minLength: number, maxLength: number): string {
let length = getRandomInt(minLength, maxLength);
let t = createStringBuilder(length);
for (let i = 0; i < length; i++) {
t.appendASCII(getRandomInt(CharCode.a, CharCode.z));
}
return t.build();
}
function generateFile(small: boolean): string[] {
let lineCount = getRandomInt(1, small ? 3 : 10000);
let lines: string[] = [];
for (let i = 0; i < lineCount; i++) {
lines.push(getRandomString(0, small ? 3 : 10000));
}
return lines;
}
if (GENERATE_TESTS) {
let number = 1;
while (true) {
console.log('------TEST: ' + number++);
const file1 = generateFile(true);
const file2 = generateFile(true);
console.log('------TEST GENERATED');
try {
assertComputeEdits(file1, file2);
} catch (err) {
console.log(err);
console.log(`
const file1 = ${JSON.stringify(file1).replace(/"/g, '\'')};
const file2 = ${JSON.stringify(file2).replace(/"/g, '\'')};
assertComputeEdits(file1, file2);
`);
break;
}
}
}
class TestTextResourcePropertiesService implements ITextResourcePropertiesService {
_serviceBrand: any;
constructor(
@IConfigurationService private readonly configurationService: IConfigurationService,
) {
}
getEOL(resource: URI, language?: string): string {
const filesConfiguration = this.configurationService.getValue<{ eol: string }>('files', { overrideIdentifier: language, resource });
if (filesConfiguration && filesConfiguration.eol) {
if (filesConfiguration.eol !== 'auto') {
return filesConfiguration.eol;
}
}
return (platform.isLinux || platform.isMacintosh) ? '\n' : '\r\n';
}
}
| src/vs/editor/test/common/services/modelService.test.ts | 0 | https://github.com/microsoft/vscode/commit/bbff11633c7e56e7fd5d16cc20daa9a3284afbfe | [
0.0001770063681760803,
0.00017404240497853607,
0.00016802080790512264,
0.00017464322445448488,
0.0000020590991880453657
]
|
{
"id": 9,
"code_window": [
"\t\tthis._register(this.regex.onChange(viaKeyboard => {\n",
"\t\t\tthis._onDidOptionChange.fire(viaKeyboard);\n",
"\t\t\tif (!viaKeyboard && this.fixFocusOnOptionClickEnabled) {\n",
"\t\t\t\tthis.inputBox.focus();\n",
"\t\t\t}\n",
"\t\t\tthis.setInputWidth();\n",
"\t\t\tthis.validate();\n",
"\t\t}));\n",
"\t\tthis._register(this.regex.onKeyDown(e => {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/base/browser/ui/findinput/findInput.ts",
"type": "replace",
"edit_start_line_idx": 322
} | {
"compilerOptions": {
"outDir": "./dist/",
"module": "commonjs",
"target": "es6",
"jsx": "react",
"sourceMap": true,
"strict": true,
"strictBindCallApply": true,
"noImplicitAny": true,
"noUnusedLocals": true
}
} | extensions/markdown-language-features/preview-src/tsconfig.json | 0 | https://github.com/microsoft/vscode/commit/bbff11633c7e56e7fd5d16cc20daa9a3284afbfe | [
0.00017582469445187598,
0.00017367971304338425,
0.00017153473163489252,
0.00017367971304338425,
0.0000021449814084917307
]
|
{
"id": 9,
"code_window": [
"\t\tthis._register(this.regex.onChange(viaKeyboard => {\n",
"\t\t\tthis._onDidOptionChange.fire(viaKeyboard);\n",
"\t\t\tif (!viaKeyboard && this.fixFocusOnOptionClickEnabled) {\n",
"\t\t\t\tthis.inputBox.focus();\n",
"\t\t\t}\n",
"\t\t\tthis.setInputWidth();\n",
"\t\t\tthis.validate();\n",
"\t\t}));\n",
"\t\tthis._register(this.regex.onKeyDown(e => {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/base/browser/ui/findinput/findInput.ts",
"type": "replace",
"edit_start_line_idx": 322
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
define({
KeyA: {
value: 'a',
valueIsDeadKey: false,
withShift: 'A',
withShiftIsDeadKey: false,
withAltGr: 'å',
withAltGrIsDeadKey: false,
withShiftAltGr: 'Å',
withShiftAltGrIsDeadKey: false
},
KeyB: {
value: 'b',
valueIsDeadKey: false,
withShift: 'B',
withShiftIsDeadKey: false,
withAltGr: '∫',
withAltGrIsDeadKey: false,
withShiftAltGr: 'ı',
withShiftAltGrIsDeadKey: false
},
KeyC: {
value: 'c',
valueIsDeadKey: false,
withShift: 'C',
withShiftIsDeadKey: false,
withAltGr: 'ç',
withAltGrIsDeadKey: false,
withShiftAltGr: 'Ç',
withShiftAltGrIsDeadKey: false
},
KeyD: {
value: 'd',
valueIsDeadKey: false,
withShift: 'D',
withShiftIsDeadKey: false,
withAltGr: '∂',
withAltGrIsDeadKey: false,
withShiftAltGr: 'Î',
withShiftAltGrIsDeadKey: false
},
KeyE: {
value: 'e',
valueIsDeadKey: false,
withShift: 'E',
withShiftIsDeadKey: false,
withAltGr: '´',
withAltGrIsDeadKey: true,
withShiftAltGr: '´',
withShiftAltGrIsDeadKey: false
},
KeyF: {
value: 'f',
valueIsDeadKey: false,
withShift: 'F',
withShiftIsDeadKey: false,
withAltGr: 'ƒ',
withAltGrIsDeadKey: false,
withShiftAltGr: 'Ï',
withShiftAltGrIsDeadKey: false
},
KeyG: {
value: 'g',
valueIsDeadKey: false,
withShift: 'G',
withShiftIsDeadKey: false,
withAltGr: '©',
withAltGrIsDeadKey: false,
withShiftAltGr: '˝',
withShiftAltGrIsDeadKey: false
},
KeyH: {
value: 'h',
valueIsDeadKey: false,
withShift: 'H',
withShiftIsDeadKey: false,
withAltGr: '˙',
withAltGrIsDeadKey: false,
withShiftAltGr: 'Ó',
withShiftAltGrIsDeadKey: false
},
KeyI: {
value: 'i',
valueIsDeadKey: false,
withShift: 'I',
withShiftIsDeadKey: false,
withAltGr: 'ˆ',
withAltGrIsDeadKey: true,
withShiftAltGr: 'ˆ',
withShiftAltGrIsDeadKey: false
},
KeyJ: {
value: 'j',
valueIsDeadKey: false,
withShift: 'J',
withShiftIsDeadKey: false,
withAltGr: '∆',
withAltGrIsDeadKey: false,
withShiftAltGr: 'Ô',
withShiftAltGrIsDeadKey: false
},
KeyK: {
value: 'k',
valueIsDeadKey: false,
withShift: 'K',
withShiftIsDeadKey: false,
withAltGr: '˚',
withAltGrIsDeadKey: false,
withShiftAltGr: '',
withShiftAltGrIsDeadKey: false
},
KeyL: {
value: 'l',
valueIsDeadKey: false,
withShift: 'L',
withShiftIsDeadKey: false,
withAltGr: '¬',
withAltGrIsDeadKey: false,
withShiftAltGr: 'Ò',
withShiftAltGrIsDeadKey: false
},
KeyM: {
value: 'm',
valueIsDeadKey: false,
withShift: 'M',
withShiftIsDeadKey: false,
withAltGr: 'µ',
withAltGrIsDeadKey: false,
withShiftAltGr: 'Â',
withShiftAltGrIsDeadKey: false
},
KeyN: {
value: 'n',
valueIsDeadKey: false,
withShift: 'N',
withShiftIsDeadKey: false,
withAltGr: '˜',
withAltGrIsDeadKey: true,
withShiftAltGr: '˜',
withShiftAltGrIsDeadKey: false
},
KeyO: {
value: 'o',
valueIsDeadKey: false,
withShift: 'O',
withShiftIsDeadKey: false,
withAltGr: 'ø',
withAltGrIsDeadKey: false,
withShiftAltGr: 'Ø',
withShiftAltGrIsDeadKey: false
},
KeyP: {
value: 'p',
valueIsDeadKey: false,
withShift: 'P',
withShiftIsDeadKey: false,
withAltGr: 'π',
withAltGrIsDeadKey: false,
withShiftAltGr: '∏',
withShiftAltGrIsDeadKey: false
},
KeyQ: {
value: 'q',
valueIsDeadKey: false,
withShift: 'Q',
withShiftIsDeadKey: false,
withAltGr: 'œ',
withAltGrIsDeadKey: false,
withShiftAltGr: 'Œ',
withShiftAltGrIsDeadKey: false
},
KeyR: {
value: 'r',
valueIsDeadKey: false,
withShift: 'R',
withShiftIsDeadKey: false,
withAltGr: '®',
withAltGrIsDeadKey: false,
withShiftAltGr: '‰',
withShiftAltGrIsDeadKey: false
},
KeyS: {
value: 's',
valueIsDeadKey: false,
withShift: 'S',
withShiftIsDeadKey: false,
withAltGr: 'ß',
withAltGrIsDeadKey: false,
withShiftAltGr: 'Í',
withShiftAltGrIsDeadKey: false
},
KeyT: {
value: 't',
valueIsDeadKey: false,
withShift: 'T',
withShiftIsDeadKey: false,
withAltGr: '†',
withAltGrIsDeadKey: false,
withShiftAltGr: 'ˇ',
withShiftAltGrIsDeadKey: false
},
KeyU: {
value: 'u',
valueIsDeadKey: false,
withShift: 'U',
withShiftIsDeadKey: false,
withAltGr: '¨',
withAltGrIsDeadKey: true,
withShiftAltGr: '¨',
withShiftAltGrIsDeadKey: false
},
KeyV: {
value: 'v',
valueIsDeadKey: false,
withShift: 'V',
withShiftIsDeadKey: false,
withAltGr: '√',
withAltGrIsDeadKey: false,
withShiftAltGr: '◊',
withShiftAltGrIsDeadKey: false
},
KeyW: {
value: 'w',
valueIsDeadKey: false,
withShift: 'W',
withShiftIsDeadKey: false,
withAltGr: '∑',
withAltGrIsDeadKey: false,
withShiftAltGr: '„',
withShiftAltGrIsDeadKey: false
},
KeyX: {
value: 'x',
valueIsDeadKey: false,
withShift: 'X',
withShiftIsDeadKey: false,
withAltGr: '≈',
withAltGrIsDeadKey: false,
withShiftAltGr: '˛',
withShiftAltGrIsDeadKey: false
},
KeyY: {
value: 'y',
valueIsDeadKey: false,
withShift: 'Y',
withShiftIsDeadKey: false,
withAltGr: '¥',
withAltGrIsDeadKey: false,
withShiftAltGr: 'Á',
withShiftAltGrIsDeadKey: false
},
KeyZ: {
value: 'z',
valueIsDeadKey: false,
withShift: 'Z',
withShiftIsDeadKey: false,
withAltGr: 'Ω',
withAltGrIsDeadKey: false,
withShiftAltGr: '¸',
withShiftAltGrIsDeadKey: false
},
Digit1: {
value: '1',
valueIsDeadKey: false,
withShift: '!',
withShiftIsDeadKey: false,
withAltGr: '¡',
withAltGrIsDeadKey: false,
withShiftAltGr: '⁄',
withShiftAltGrIsDeadKey: false
},
Digit2: {
value: '2',
valueIsDeadKey: false,
withShift: '@',
withShiftIsDeadKey: false,
withAltGr: '™',
withAltGrIsDeadKey: false,
withShiftAltGr: '€',
withShiftAltGrIsDeadKey: false
},
Digit3: {
value: '3',
valueIsDeadKey: false,
withShift: '#',
withShiftIsDeadKey: false,
withAltGr: '£',
withAltGrIsDeadKey: false,
withShiftAltGr: '‹',
withShiftAltGrIsDeadKey: false
},
Digit4: {
value: '4',
valueIsDeadKey: false,
withShift: '$',
withShiftIsDeadKey: false,
withAltGr: '¢',
withAltGrIsDeadKey: false,
withShiftAltGr: '›',
withShiftAltGrIsDeadKey: false
},
Digit5: {
value: '5',
valueIsDeadKey: false,
withShift: '%',
withShiftIsDeadKey: false,
withAltGr: '∞',
withAltGrIsDeadKey: false,
withShiftAltGr: 'fi',
withShiftAltGrIsDeadKey: false
},
Digit6: {
value: '6',
valueIsDeadKey: false,
withShift: '^',
withShiftIsDeadKey: false,
withAltGr: '§',
withAltGrIsDeadKey: false,
withShiftAltGr: 'fl',
withShiftAltGrIsDeadKey: false
},
Digit7: {
value: '7',
valueIsDeadKey: false,
withShift: '&',
withShiftIsDeadKey: false,
withAltGr: '¶',
withAltGrIsDeadKey: false,
withShiftAltGr: '‡',
withShiftAltGrIsDeadKey: false
},
Digit8: {
value: '8',
valueIsDeadKey: false,
withShift: '*',
withShiftIsDeadKey: false,
withAltGr: '•',
withAltGrIsDeadKey: false,
withShiftAltGr: '°',
withShiftAltGrIsDeadKey: false
},
Digit9: {
value: '9',
valueIsDeadKey: false,
withShift: '(',
withShiftIsDeadKey: false,
withAltGr: 'ª',
withAltGrIsDeadKey: false,
withShiftAltGr: '·',
withShiftAltGrIsDeadKey: false
},
Digit0: {
value: '0',
valueIsDeadKey: false,
withShift: ')',
withShiftIsDeadKey: false,
withAltGr: 'º',
withAltGrIsDeadKey: false,
withShiftAltGr: '‚',
withShiftAltGrIsDeadKey: false
},
Enter: {
value: '',
valueIsDeadKey: false,
withShift: '',
withShiftIsDeadKey: false,
withAltGr: '',
withAltGrIsDeadKey: false,
withShiftAltGr: '',
withShiftAltGrIsDeadKey: false
},
Escape: {
value: '',
valueIsDeadKey: false,
withShift: '',
withShiftIsDeadKey: false,
withAltGr: '',
withAltGrIsDeadKey: false,
withShiftAltGr: '',
withShiftAltGrIsDeadKey: false
},
Backspace: {
value: '',
valueIsDeadKey: false,
withShift: '',
withShiftIsDeadKey: false,
withAltGr: '',
withAltGrIsDeadKey: false,
withShiftAltGr: '',
withShiftAltGrIsDeadKey: false
},
Tab: {
value: '',
valueIsDeadKey: false,
withShift: '',
withShiftIsDeadKey: false,
withAltGr: '',
withAltGrIsDeadKey: false,
withShiftAltGr: '',
withShiftAltGrIsDeadKey: false
},
Space: {
value: ' ',
valueIsDeadKey: false,
withShift: ' ',
withShiftIsDeadKey: false,
withAltGr: ' ',
withAltGrIsDeadKey: false,
withShiftAltGr: ' ',
withShiftAltGrIsDeadKey: false
},
Minus: {
value: '-',
valueIsDeadKey: false,
withShift: '_',
withShiftIsDeadKey: false,
withAltGr: '–',
withAltGrIsDeadKey: false,
withShiftAltGr: '—',
withShiftAltGrIsDeadKey: false
},
Equal: {
value: '=',
valueIsDeadKey: false,
withShift: '+',
withShiftIsDeadKey: false,
withAltGr: '≠',
withAltGrIsDeadKey: false,
withShiftAltGr: '±',
withShiftAltGrIsDeadKey: false
},
BracketLeft: {
value: '[',
valueIsDeadKey: false,
withShift: '{',
withShiftIsDeadKey: false,
withAltGr: '“',
withAltGrIsDeadKey: false,
withShiftAltGr: '”',
withShiftAltGrIsDeadKey: false
},
BracketRight: {
value: ']',
valueIsDeadKey: false,
withShift: '}',
withShiftIsDeadKey: false,
withAltGr: '‘',
withAltGrIsDeadKey: false,
withShiftAltGr: '’',
withShiftAltGrIsDeadKey: false
},
Backslash: {
value: '\\',
valueIsDeadKey: false,
withShift: '|',
withShiftIsDeadKey: false,
withAltGr: '«',
withAltGrIsDeadKey: false,
withShiftAltGr: '»',
withShiftAltGrIsDeadKey: false
},
Semicolon: {
value: ';',
valueIsDeadKey: false,
withShift: ':',
withShiftIsDeadKey: false,
withAltGr: '…',
withAltGrIsDeadKey: false,
withShiftAltGr: 'Ú',
withShiftAltGrIsDeadKey: false
},
Quote: {
value: '\'',
valueIsDeadKey: false,
withShift: '"',
withShiftIsDeadKey: false,
withAltGr: 'æ',
withAltGrIsDeadKey: false,
withShiftAltGr: 'Æ',
withShiftAltGrIsDeadKey: false
},
Backquote: {
value: '`',
valueIsDeadKey: false,
withShift: '~',
withShiftIsDeadKey: false,
withAltGr: '`',
withAltGrIsDeadKey: true,
withShiftAltGr: '`',
withShiftAltGrIsDeadKey: false
},
Comma: {
value: ',',
valueIsDeadKey: false,
withShift: '<',
withShiftIsDeadKey: false,
withAltGr: '≤',
withAltGrIsDeadKey: false,
withShiftAltGr: '¯',
withShiftAltGrIsDeadKey: false
},
Period: {
value: '.',
valueIsDeadKey: false,
withShift: '>',
withShiftIsDeadKey: false,
withAltGr: '≥',
withAltGrIsDeadKey: false,
withShiftAltGr: '˘',
withShiftAltGrIsDeadKey: false
},
Slash: {
value: '/',
valueIsDeadKey: false,
withShift: '?',
withShiftIsDeadKey: false,
withAltGr: '÷',
withAltGrIsDeadKey: false,
withShiftAltGr: '¿',
withShiftAltGrIsDeadKey: false
},
CapsLock: {
value: '',
valueIsDeadKey: false,
withShift: '',
withShiftIsDeadKey: false,
withAltGr: '',
withAltGrIsDeadKey: false,
withShiftAltGr: '',
withShiftAltGrIsDeadKey: false
},
F1: {
value: '',
valueIsDeadKey: false,
withShift: '',
withShiftIsDeadKey: false,
withAltGr: '',
withAltGrIsDeadKey: false,
withShiftAltGr: '',
withShiftAltGrIsDeadKey: false
},
F2: {
value: '',
valueIsDeadKey: false,
withShift: '',
withShiftIsDeadKey: false,
withAltGr: '',
withAltGrIsDeadKey: false,
withShiftAltGr: '',
withShiftAltGrIsDeadKey: false
},
F3: {
value: '',
valueIsDeadKey: false,
withShift: '',
withShiftIsDeadKey: false,
withAltGr: '',
withAltGrIsDeadKey: false,
withShiftAltGr: '',
withShiftAltGrIsDeadKey: false
},
F4: {
value: '',
valueIsDeadKey: false,
withShift: '',
withShiftIsDeadKey: false,
withAltGr: '',
withAltGrIsDeadKey: false,
withShiftAltGr: '',
withShiftAltGrIsDeadKey: false
},
F5: {
value: '',
valueIsDeadKey: false,
withShift: '',
withShiftIsDeadKey: false,
withAltGr: '',
withAltGrIsDeadKey: false,
withShiftAltGr: '',
withShiftAltGrIsDeadKey: false
},
F6: {
value: '',
valueIsDeadKey: false,
withShift: '',
withShiftIsDeadKey: false,
withAltGr: '',
withAltGrIsDeadKey: false,
withShiftAltGr: '',
withShiftAltGrIsDeadKey: false
},
F7: {
value: '',
valueIsDeadKey: false,
withShift: '',
withShiftIsDeadKey: false,
withAltGr: '',
withAltGrIsDeadKey: false,
withShiftAltGr: '',
withShiftAltGrIsDeadKey: false
},
F8: {
value: '',
valueIsDeadKey: false,
withShift: '',
withShiftIsDeadKey: false,
withAltGr: '',
withAltGrIsDeadKey: false,
withShiftAltGr: '',
withShiftAltGrIsDeadKey: false
},
F9: {
value: '',
valueIsDeadKey: false,
withShift: '',
withShiftIsDeadKey: false,
withAltGr: '',
withAltGrIsDeadKey: false,
withShiftAltGr: '',
withShiftAltGrIsDeadKey: false
},
F10: {
value: '',
valueIsDeadKey: false,
withShift: '',
withShiftIsDeadKey: false,
withAltGr: '',
withAltGrIsDeadKey: false,
withShiftAltGr: '',
withShiftAltGrIsDeadKey: false
},
F11: {
value: '',
valueIsDeadKey: false,
withShift: '',
withShiftIsDeadKey: false,
withAltGr: '',
withAltGrIsDeadKey: false,
withShiftAltGr: '',
withShiftAltGrIsDeadKey: false
},
F12: {
value: '',
valueIsDeadKey: false,
withShift: '',
withShiftIsDeadKey: false,
withAltGr: '',
withAltGrIsDeadKey: false,
withShiftAltGr: '',
withShiftAltGrIsDeadKey: false
},
Insert: {
value: '',
valueIsDeadKey: false,
withShift: '',
withShiftIsDeadKey: false,
withAltGr: '',
withAltGrIsDeadKey: false,
withShiftAltGr: '',
withShiftAltGrIsDeadKey: false
},
Home: {
value: '',
valueIsDeadKey: false,
withShift: '',
withShiftIsDeadKey: false,
withAltGr: '',
withAltGrIsDeadKey: false,
withShiftAltGr: '',
withShiftAltGrIsDeadKey: false
},
PageUp: {
value: '',
valueIsDeadKey: false,
withShift: '',
withShiftIsDeadKey: false,
withAltGr: '',
withAltGrIsDeadKey: false,
withShiftAltGr: '',
withShiftAltGrIsDeadKey: false
},
Delete: {
value: '',
valueIsDeadKey: false,
withShift: '',
withShiftIsDeadKey: false,
withAltGr: '',
withAltGrIsDeadKey: false,
withShiftAltGr: '',
withShiftAltGrIsDeadKey: false
},
End: {
value: '',
valueIsDeadKey: false,
withShift: '',
withShiftIsDeadKey: false,
withAltGr: '',
withAltGrIsDeadKey: false,
withShiftAltGr: '',
withShiftAltGrIsDeadKey: false
},
PageDown: {
value: '',
valueIsDeadKey: false,
withShift: '',
withShiftIsDeadKey: false,
withAltGr: '',
withAltGrIsDeadKey: false,
withShiftAltGr: '',
withShiftAltGrIsDeadKey: false
},
ArrowRight: {
value: '',
valueIsDeadKey: false,
withShift: '',
withShiftIsDeadKey: false,
withAltGr: '',
withAltGrIsDeadKey: false,
withShiftAltGr: '',
withShiftAltGrIsDeadKey: false
},
ArrowLeft: {
value: '',
valueIsDeadKey: false,
withShift: '',
withShiftIsDeadKey: false,
withAltGr: '',
withAltGrIsDeadKey: false,
withShiftAltGr: '',
withShiftAltGrIsDeadKey: false
},
ArrowDown: {
value: '',
valueIsDeadKey: false,
withShift: '',
withShiftIsDeadKey: false,
withAltGr: '',
withAltGrIsDeadKey: false,
withShiftAltGr: '',
withShiftAltGrIsDeadKey: false
},
ArrowUp: {
value: '',
valueIsDeadKey: false,
withShift: '',
withShiftIsDeadKey: false,
withAltGr: '',
withAltGrIsDeadKey: false,
withShiftAltGr: '',
withShiftAltGrIsDeadKey: false
},
NumLock: {
value: '',
valueIsDeadKey: false,
withShift: '',
withShiftIsDeadKey: false,
withAltGr: '',
withAltGrIsDeadKey: false,
withShiftAltGr: '',
withShiftAltGrIsDeadKey: false
},
NumpadDivide: {
value: '/',
valueIsDeadKey: false,
withShift: '/',
withShiftIsDeadKey: false,
withAltGr: '/',
withAltGrIsDeadKey: false,
withShiftAltGr: '/',
withShiftAltGrIsDeadKey: false
},
NumpadMultiply: {
value: '*',
valueIsDeadKey: false,
withShift: '*',
withShiftIsDeadKey: false,
withAltGr: '*',
withAltGrIsDeadKey: false,
withShiftAltGr: '*',
withShiftAltGrIsDeadKey: false
},
NumpadSubtract: {
value: '-',
valueIsDeadKey: false,
withShift: '-',
withShiftIsDeadKey: false,
withAltGr: '-',
withAltGrIsDeadKey: false,
withShiftAltGr: '-',
withShiftAltGrIsDeadKey: false
},
NumpadAdd: {
value: '+',
valueIsDeadKey: false,
withShift: '+',
withShiftIsDeadKey: false,
withAltGr: '+',
withAltGrIsDeadKey: false,
withShiftAltGr: '+',
withShiftAltGrIsDeadKey: false
},
NumpadEnter: {
value: '',
valueIsDeadKey: false,
withShift: '',
withShiftIsDeadKey: false,
withAltGr: '',
withAltGrIsDeadKey: false,
withShiftAltGr: '',
withShiftAltGrIsDeadKey: false
},
Numpad1: {
value: '1',
valueIsDeadKey: false,
withShift: '1',
withShiftIsDeadKey: false,
withAltGr: '1',
withAltGrIsDeadKey: false,
withShiftAltGr: '1',
withShiftAltGrIsDeadKey: false
},
Numpad2: {
value: '2',
valueIsDeadKey: false,
withShift: '2',
withShiftIsDeadKey: false,
withAltGr: '2',
withAltGrIsDeadKey: false,
withShiftAltGr: '2',
withShiftAltGrIsDeadKey: false
},
Numpad3: {
value: '3',
valueIsDeadKey: false,
withShift: '3',
withShiftIsDeadKey: false,
withAltGr: '3',
withAltGrIsDeadKey: false,
withShiftAltGr: '3',
withShiftAltGrIsDeadKey: false
},
Numpad4: {
value: '4',
valueIsDeadKey: false,
withShift: '4',
withShiftIsDeadKey: false,
withAltGr: '4',
withAltGrIsDeadKey: false,
withShiftAltGr: '4',
withShiftAltGrIsDeadKey: false
},
Numpad5: {
value: '5',
valueIsDeadKey: false,
withShift: '5',
withShiftIsDeadKey: false,
withAltGr: '5',
withAltGrIsDeadKey: false,
withShiftAltGr: '5',
withShiftAltGrIsDeadKey: false
},
Numpad6: {
value: '6',
valueIsDeadKey: false,
withShift: '6',
withShiftIsDeadKey: false,
withAltGr: '6',
withAltGrIsDeadKey: false,
withShiftAltGr: '6',
withShiftAltGrIsDeadKey: false
},
Numpad7: {
value: '7',
valueIsDeadKey: false,
withShift: '7',
withShiftIsDeadKey: false,
withAltGr: '7',
withAltGrIsDeadKey: false,
withShiftAltGr: '7',
withShiftAltGrIsDeadKey: false
},
Numpad8: {
value: '8',
valueIsDeadKey: false,
withShift: '8',
withShiftIsDeadKey: false,
withAltGr: '8',
withAltGrIsDeadKey: false,
withShiftAltGr: '8',
withShiftAltGrIsDeadKey: false
},
Numpad9: {
value: '9',
valueIsDeadKey: false,
withShift: '9',
withShiftIsDeadKey: false,
withAltGr: '9',
withAltGrIsDeadKey: false,
withShiftAltGr: '9',
withShiftAltGrIsDeadKey: false
},
Numpad0: {
value: '0',
valueIsDeadKey: false,
withShift: '0',
withShiftIsDeadKey: false,
withAltGr: '0',
withAltGrIsDeadKey: false,
withShiftAltGr: '0',
withShiftAltGrIsDeadKey: false
},
NumpadDecimal: {
value: '.',
valueIsDeadKey: false,
withShift: '.',
withShiftIsDeadKey: false,
withAltGr: '.',
withAltGrIsDeadKey: false,
withShiftAltGr: '.',
withShiftAltGrIsDeadKey: false
},
IntlBackslash: {
value: '§',
valueIsDeadKey: false,
withShift: '±',
withShiftIsDeadKey: false,
withAltGr: '§',
withAltGrIsDeadKey: false,
withShiftAltGr: '±',
withShiftAltGrIsDeadKey: false
},
ContextMenu: {
value: '',
valueIsDeadKey: false,
withShift: '',
withShiftIsDeadKey: false,
withAltGr: '',
withAltGrIsDeadKey: false,
withShiftAltGr: '',
withShiftAltGrIsDeadKey: false
},
NumpadEqual: {
value: '=',
valueIsDeadKey: false,
withShift: '=',
withShiftIsDeadKey: false,
withAltGr: '=',
withAltGrIsDeadKey: false,
withShiftAltGr: '=',
withShiftAltGrIsDeadKey: false
},
F13: {
value: '',
valueIsDeadKey: false,
withShift: '',
withShiftIsDeadKey: false,
withAltGr: '',
withAltGrIsDeadKey: false,
withShiftAltGr: '',
withShiftAltGrIsDeadKey: false
},
F14: {
value: '',
valueIsDeadKey: false,
withShift: '',
withShiftIsDeadKey: false,
withAltGr: '',
withAltGrIsDeadKey: false,
withShiftAltGr: '',
withShiftAltGrIsDeadKey: false
},
F15: {
value: '',
valueIsDeadKey: false,
withShift: '',
withShiftIsDeadKey: false,
withAltGr: '',
withAltGrIsDeadKey: false,
withShiftAltGr: '',
withShiftAltGrIsDeadKey: false
},
F16: {
value: '',
valueIsDeadKey: false,
withShift: '',
withShiftIsDeadKey: false,
withAltGr: '',
withAltGrIsDeadKey: false,
withShiftAltGr: '',
withShiftAltGrIsDeadKey: false
},
F17: {
value: '',
valueIsDeadKey: false,
withShift: '',
withShiftIsDeadKey: false,
withAltGr: '',
withAltGrIsDeadKey: false,
withShiftAltGr: '',
withShiftAltGrIsDeadKey: false
},
F18: {
value: '',
valueIsDeadKey: false,
withShift: '',
withShiftIsDeadKey: false,
withAltGr: '',
withAltGrIsDeadKey: false,
withShiftAltGr: '',
withShiftAltGrIsDeadKey: false
},
F19: {
value: '',
valueIsDeadKey: false,
withShift: '',
withShiftIsDeadKey: false,
withAltGr: '',
withAltGrIsDeadKey: false,
withShiftAltGr: '',
withShiftAltGrIsDeadKey: false
},
F20: {
value: '',
valueIsDeadKey: false,
withShift: '',
withShiftIsDeadKey: false,
withAltGr: '',
withAltGrIsDeadKey: false,
withShiftAltGr: '',
withShiftAltGrIsDeadKey: false
},
AudioVolumeMute: {
value: '',
valueIsDeadKey: false,
withShift: '',
withShiftIsDeadKey: false,
withAltGr: '',
withAltGrIsDeadKey: false,
withShiftAltGr: '',
withShiftAltGrIsDeadKey: false
},
AudioVolumeUp: {
value: '',
valueIsDeadKey: false,
withShift: '=',
withShiftIsDeadKey: false,
withAltGr: '',
withAltGrIsDeadKey: false,
withShiftAltGr: '=',
withShiftAltGrIsDeadKey: false
},
AudioVolumeDown: {
value: '',
valueIsDeadKey: false,
withShift: '',
withShiftIsDeadKey: false,
withAltGr: '',
withAltGrIsDeadKey: false,
withShiftAltGr: '',
withShiftAltGrIsDeadKey: false
},
NumpadComma: {
value: '',
valueIsDeadKey: false,
withShift: '',
withShiftIsDeadKey: false,
withAltGr: '',
withAltGrIsDeadKey: false,
withShiftAltGr: '',
withShiftAltGrIsDeadKey: false
},
IntlRo: {
value: '',
valueIsDeadKey: false,
withShift: '',
withShiftIsDeadKey: false,
withAltGr: '',
withAltGrIsDeadKey: false,
withShiftAltGr: '',
withShiftAltGrIsDeadKey: false
},
KanaMode: {
value: '',
valueIsDeadKey: false,
withShift: '',
withShiftIsDeadKey: false,
withAltGr: '',
withAltGrIsDeadKey: false,
withShiftAltGr: '',
withShiftAltGrIsDeadKey: false
},
IntlYen: {
value: '',
valueIsDeadKey: false,
withShift: '',
withShiftIsDeadKey: false,
withAltGr: '',
withAltGrIsDeadKey: false,
withShiftAltGr: '',
withShiftAltGrIsDeadKey: false
},
ControlLeft: {
value: '',
valueIsDeadKey: false,
withShift: '',
withShiftIsDeadKey: false,
withAltGr: '',
withAltGrIsDeadKey: false,
withShiftAltGr: '',
withShiftAltGrIsDeadKey: false
},
ShiftLeft: {
value: '',
valueIsDeadKey: false,
withShift: '',
withShiftIsDeadKey: false,
withAltGr: '',
withAltGrIsDeadKey: false,
withShiftAltGr: '',
withShiftAltGrIsDeadKey: false
},
AltLeft: {
value: '',
valueIsDeadKey: false,
withShift: '',
withShiftIsDeadKey: false,
withAltGr: '',
withAltGrIsDeadKey: false,
withShiftAltGr: '',
withShiftAltGrIsDeadKey: false
},
MetaLeft: {
value: '',
valueIsDeadKey: false,
withShift: '',
withShiftIsDeadKey: false,
withAltGr: '',
withAltGrIsDeadKey: false,
withShiftAltGr: '',
withShiftAltGrIsDeadKey: false
},
ControlRight: {
value: '',
valueIsDeadKey: false,
withShift: '',
withShiftIsDeadKey: false,
withAltGr: '',
withAltGrIsDeadKey: false,
withShiftAltGr: '',
withShiftAltGrIsDeadKey: false
},
ShiftRight: {
value: '',
valueIsDeadKey: false,
withShift: '',
withShiftIsDeadKey: false,
withAltGr: '',
withAltGrIsDeadKey: false,
withShiftAltGr: '',
withShiftAltGrIsDeadKey: false
},
AltRight: {
value: '',
valueIsDeadKey: false,
withShift: '',
withShiftIsDeadKey: false,
withAltGr: '',
withAltGrIsDeadKey: false,
withShiftAltGr: '',
withShiftAltGrIsDeadKey: false
},
MetaRight: {
value: '',
valueIsDeadKey: false,
withShift: '',
withShiftIsDeadKey: false,
withAltGr: '',
withAltGrIsDeadKey: false,
withShiftAltGr: '',
withShiftAltGrIsDeadKey: false
}
});
| src/vs/workbench/services/keybinding/test/mac_en_us.js | 0 | https://github.com/microsoft/vscode/commit/bbff11633c7e56e7fd5d16cc20daa9a3284afbfe | [
0.00017665028281044215,
0.00017475313507020473,
0.00017237420252058655,
0.0001749790826579556,
6.886016308271792e-7
]
|
{
"id": 10,
"code_window": [
"\t\tthis._register(this.wholeWords.onChange(viaKeyboard => {\n",
"\t\t\tthis._onDidOptionChange.fire(viaKeyboard);\n",
"\t\t\tif (!viaKeyboard && this.fixFocusOnOptionClickEnabled) {\n",
"\t\t\t\tthis.inputBox.focus();\n",
"\t\t\t}\n",
"\t\t\tthis.setInputWidth();\n",
"\t\t\tthis.validate();\n",
"\t\t}));\n",
"\n",
"\t\tthis.caseSensitive = this._register(new CaseSensitiveCheckbox({\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/base/browser/ui/findinput/findInput.ts",
"type": "replace",
"edit_start_line_idx": 339
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import 'vs/css!./findInput';
import * as nls from 'vs/nls';
import * as dom from 'vs/base/browser/dom';
import { IMessage as InputBoxMessage, IInputValidator, IInputBoxStyles, HistoryInputBox } from 'vs/base/browser/ui/inputbox/inputBox';
import { IContextViewProvider } from 'vs/base/browser/ui/contextview/contextview';
import { Widget } from 'vs/base/browser/ui/widget';
import { Event, Emitter } from 'vs/base/common/event';
import { IKeyboardEvent } from 'vs/base/browser/keyboardEvent';
import { IMouseEvent } from 'vs/base/browser/mouseEvent';
import { KeyCode } from 'vs/base/common/keyCodes';
import { CaseSensitiveCheckbox, WholeWordsCheckbox, RegexCheckbox } from 'vs/base/browser/ui/findinput/findInputCheckboxes';
import { Color } from 'vs/base/common/color';
import { ICheckboxStyles } from 'vs/base/browser/ui/checkbox/checkbox';
export interface IFindInputOptions extends IFindInputStyles {
readonly placeholder?: string;
readonly width?: number;
readonly validation?: IInputValidator;
readonly label: string;
readonly flexibleHeight?: boolean;
readonly appendCaseSensitiveLabel?: string;
readonly appendWholeWordsLabel?: string;
readonly appendRegexLabel?: string;
readonly history?: string[];
}
export interface IFindInputStyles extends IInputBoxStyles {
inputActiveOptionBorder?: Color;
}
const NLS_DEFAULT_LABEL = nls.localize('defaultLabel', "input");
export class FindInput extends Widget {
static readonly OPTION_CHANGE: string = 'optionChange';
private contextViewProvider: IContextViewProvider;
private width: number;
private placeholder: string;
private validation?: IInputValidator;
private label: string;
private fixFocusOnOptionClickEnabled = true;
private inputActiveOptionBorder?: Color;
private inputBackground?: Color;
private inputForeground?: Color;
private inputBorder?: Color;
private inputValidationInfoBorder?: Color;
private inputValidationInfoBackground?: Color;
private inputValidationInfoForeground?: Color;
private inputValidationWarningBorder?: Color;
private inputValidationWarningBackground?: Color;
private inputValidationWarningForeground?: Color;
private inputValidationErrorBorder?: Color;
private inputValidationErrorBackground?: Color;
private inputValidationErrorForeground?: Color;
private regex: RegexCheckbox;
private wholeWords: WholeWordsCheckbox;
private caseSensitive: CaseSensitiveCheckbox;
public domNode: HTMLElement;
public inputBox: HistoryInputBox;
private readonly _onDidOptionChange = this._register(new Emitter<boolean>());
public readonly onDidOptionChange: Event<boolean /* via keyboard */> = this._onDidOptionChange.event;
private readonly _onKeyDown = this._register(new Emitter<IKeyboardEvent>());
public readonly onKeyDown: Event<IKeyboardEvent> = this._onKeyDown.event;
private readonly _onMouseDown = this._register(new Emitter<IMouseEvent>());
public readonly onMouseDown: Event<IMouseEvent> = this._onMouseDown.event;
private readonly _onInput = this._register(new Emitter<void>());
public readonly onInput: Event<void> = this._onInput.event;
private readonly _onKeyUp = this._register(new Emitter<IKeyboardEvent>());
public readonly onKeyUp: Event<IKeyboardEvent> = this._onKeyUp.event;
private _onCaseSensitiveKeyDown = this._register(new Emitter<IKeyboardEvent>());
public readonly onCaseSensitiveKeyDown: Event<IKeyboardEvent> = this._onCaseSensitiveKeyDown.event;
private _onRegexKeyDown = this._register(new Emitter<IKeyboardEvent>());
public readonly onRegexKeyDown: Event<IKeyboardEvent> = this._onRegexKeyDown.event;
constructor(parent: HTMLElement | null, contextViewProvider: IContextViewProvider, private readonly _showOptionButtons: boolean, options: IFindInputOptions) {
super();
this.contextViewProvider = contextViewProvider;
this.width = options.width || 100;
this.placeholder = options.placeholder || '';
this.validation = options.validation;
this.label = options.label || NLS_DEFAULT_LABEL;
this.inputActiveOptionBorder = options.inputActiveOptionBorder;
this.inputBackground = options.inputBackground;
this.inputForeground = options.inputForeground;
this.inputBorder = options.inputBorder;
this.inputValidationInfoBorder = options.inputValidationInfoBorder;
this.inputValidationInfoBackground = options.inputValidationInfoBackground;
this.inputValidationInfoForeground = options.inputValidationInfoForeground;
this.inputValidationWarningBorder = options.inputValidationWarningBorder;
this.inputValidationWarningBackground = options.inputValidationWarningBackground;
this.inputValidationWarningForeground = options.inputValidationWarningForeground;
this.inputValidationErrorBorder = options.inputValidationErrorBorder;
this.inputValidationErrorBackground = options.inputValidationErrorBackground;
this.inputValidationErrorForeground = options.inputValidationErrorForeground;
this.buildDomNode(options.appendCaseSensitiveLabel || '', options.appendWholeWordsLabel || '', options.appendRegexLabel || '', options.history || [], !!options.flexibleHeight);
if (parent) {
parent.appendChild(this.domNode);
}
this.onkeydown(this.inputBox.inputElement, (e) => this._onKeyDown.fire(e));
this.onkeyup(this.inputBox.inputElement, (e) => this._onKeyUp.fire(e));
this.oninput(this.inputBox.inputElement, (e) => this._onInput.fire());
this.onmousedown(this.inputBox.inputElement, (e) => this._onMouseDown.fire(e));
}
public enable(): void {
dom.removeClass(this.domNode, 'disabled');
this.inputBox.enable();
this.regex.enable();
this.wholeWords.enable();
this.caseSensitive.enable();
}
public disable(): void {
dom.addClass(this.domNode, 'disabled');
this.inputBox.disable();
this.regex.disable();
this.wholeWords.disable();
this.caseSensitive.disable();
}
public setFocusInputOnOptionClick(value: boolean): void {
this.fixFocusOnOptionClickEnabled = value;
}
public setEnabled(enabled: boolean): void {
if (enabled) {
this.enable();
} else {
this.disable();
}
}
public clear(): void {
this.clearValidation();
this.setValue('');
this.focus();
}
public setWidth(newWidth: number): void {
this.width = newWidth;
this.domNode.style.width = this.width + 'px';
this.contextViewProvider.layout();
this.setInputWidth();
}
public getValue(): string {
return this.inputBox.value;
}
public setValue(value: string): void {
if (this.inputBox.value !== value) {
this.inputBox.value = value;
}
}
public onSearchSubmit(): void {
this.inputBox.addToHistory();
}
public style(styles: IFindInputStyles): void {
this.inputActiveOptionBorder = styles.inputActiveOptionBorder;
this.inputBackground = styles.inputBackground;
this.inputForeground = styles.inputForeground;
this.inputBorder = styles.inputBorder;
this.inputValidationInfoBackground = styles.inputValidationInfoBackground;
this.inputValidationInfoForeground = styles.inputValidationInfoForeground;
this.inputValidationInfoBorder = styles.inputValidationInfoBorder;
this.inputValidationWarningBackground = styles.inputValidationWarningBackground;
this.inputValidationWarningForeground = styles.inputValidationWarningForeground;
this.inputValidationWarningBorder = styles.inputValidationWarningBorder;
this.inputValidationErrorBackground = styles.inputValidationErrorBackground;
this.inputValidationErrorForeground = styles.inputValidationErrorForeground;
this.inputValidationErrorBorder = styles.inputValidationErrorBorder;
this.applyStyles();
}
protected applyStyles(): void {
if (this.domNode) {
const checkBoxStyles: ICheckboxStyles = {
inputActiveOptionBorder: this.inputActiveOptionBorder,
};
this.regex.style(checkBoxStyles);
this.wholeWords.style(checkBoxStyles);
this.caseSensitive.style(checkBoxStyles);
const inputBoxStyles: IInputBoxStyles = {
inputBackground: this.inputBackground,
inputForeground: this.inputForeground,
inputBorder: this.inputBorder,
inputValidationInfoBackground: this.inputValidationInfoBackground,
inputValidationInfoForeground: this.inputValidationInfoForeground,
inputValidationInfoBorder: this.inputValidationInfoBorder,
inputValidationWarningBackground: this.inputValidationWarningBackground,
inputValidationWarningForeground: this.inputValidationWarningForeground,
inputValidationWarningBorder: this.inputValidationWarningBorder,
inputValidationErrorBackground: this.inputValidationErrorBackground,
inputValidationErrorForeground: this.inputValidationErrorForeground,
inputValidationErrorBorder: this.inputValidationErrorBorder
};
this.inputBox.style(inputBoxStyles);
}
}
public select(): void {
this.inputBox.select();
}
public focus(): void {
this.inputBox.focus();
}
public getCaseSensitive(): boolean {
return this.caseSensitive.checked;
}
public setCaseSensitive(value: boolean): void {
this.caseSensitive.checked = value;
this.setInputWidth();
}
public getWholeWords(): boolean {
return this.wholeWords.checked;
}
public setWholeWords(value: boolean): void {
this.wholeWords.checked = value;
this.setInputWidth();
}
public getRegex(): boolean {
return this.regex.checked;
}
public setRegex(value: boolean): void {
this.regex.checked = value;
this.setInputWidth();
this.validate();
}
public focusOnCaseSensitive(): void {
this.caseSensitive.focus();
}
public focusOnRegex(): void {
this.regex.focus();
}
private _lastHighlightFindOptions: number = 0;
public highlightFindOptions(): void {
dom.removeClass(this.domNode, 'highlight-' + (this._lastHighlightFindOptions));
this._lastHighlightFindOptions = 1 - this._lastHighlightFindOptions;
dom.addClass(this.domNode, 'highlight-' + (this._lastHighlightFindOptions));
}
private setInputWidth(): void {
let w = this.width - this.caseSensitive.width() - this.wholeWords.width() - this.regex.width();
this.inputBox.width = w;
this.inputBox.layout();
}
private buildDomNode(appendCaseSensitiveLabel: string, appendWholeWordsLabel: string, appendRegexLabel: string, history: string[], flexibleHeight: boolean): void {
this.domNode = document.createElement('div');
this.domNode.style.width = this.width + 'px';
dom.addClass(this.domNode, 'monaco-findInput');
this.inputBox = this._register(new HistoryInputBox(this.domNode, this.contextViewProvider, {
placeholder: this.placeholder || '',
ariaLabel: this.label || '',
validationOptions: {
validation: this.validation
},
inputBackground: this.inputBackground,
inputForeground: this.inputForeground,
inputBorder: this.inputBorder,
inputValidationInfoBackground: this.inputValidationInfoBackground,
inputValidationInfoForeground: this.inputValidationInfoForeground,
inputValidationInfoBorder: this.inputValidationInfoBorder,
inputValidationWarningBackground: this.inputValidationWarningBackground,
inputValidationWarningForeground: this.inputValidationWarningForeground,
inputValidationWarningBorder: this.inputValidationWarningBorder,
inputValidationErrorBackground: this.inputValidationErrorBackground,
inputValidationErrorForeground: this.inputValidationErrorForeground,
inputValidationErrorBorder: this.inputValidationErrorBorder,
history,
flexibleHeight
}));
this.regex = this._register(new RegexCheckbox({
appendTitle: appendRegexLabel,
isChecked: false,
inputActiveOptionBorder: this.inputActiveOptionBorder
}));
this._register(this.regex.onChange(viaKeyboard => {
this._onDidOptionChange.fire(viaKeyboard);
if (!viaKeyboard && this.fixFocusOnOptionClickEnabled) {
this.inputBox.focus();
}
this.setInputWidth();
this.validate();
}));
this._register(this.regex.onKeyDown(e => {
this._onRegexKeyDown.fire(e);
}));
this.wholeWords = this._register(new WholeWordsCheckbox({
appendTitle: appendWholeWordsLabel,
isChecked: false,
inputActiveOptionBorder: this.inputActiveOptionBorder
}));
this._register(this.wholeWords.onChange(viaKeyboard => {
this._onDidOptionChange.fire(viaKeyboard);
if (!viaKeyboard && this.fixFocusOnOptionClickEnabled) {
this.inputBox.focus();
}
this.setInputWidth();
this.validate();
}));
this.caseSensitive = this._register(new CaseSensitiveCheckbox({
appendTitle: appendCaseSensitiveLabel,
isChecked: false,
inputActiveOptionBorder: this.inputActiveOptionBorder
}));
this._register(this.caseSensitive.onChange(viaKeyboard => {
this._onDidOptionChange.fire(viaKeyboard);
if (!viaKeyboard && this.fixFocusOnOptionClickEnabled) {
this.inputBox.focus();
}
this.setInputWidth();
this.validate();
}));
this._register(this.caseSensitive.onKeyDown(e => {
this._onCaseSensitiveKeyDown.fire(e);
}));
if (this._showOptionButtons) {
this.inputBox.inputElement.style.paddingRight = (this.caseSensitive.width() + this.wholeWords.width() + this.regex.width()) + 'px';
}
// Arrow-Key support to navigate between options
let indexes = [this.caseSensitive.domNode, this.wholeWords.domNode, this.regex.domNode];
this.onkeydown(this.domNode, (event: IKeyboardEvent) => {
if (event.equals(KeyCode.LeftArrow) || event.equals(KeyCode.RightArrow) || event.equals(KeyCode.Escape)) {
let index = indexes.indexOf(<HTMLElement>document.activeElement);
if (index >= 0) {
let newIndex: number = -1;
if (event.equals(KeyCode.RightArrow)) {
newIndex = (index + 1) % indexes.length;
} else if (event.equals(KeyCode.LeftArrow)) {
if (index === 0) {
newIndex = indexes.length - 1;
} else {
newIndex = index - 1;
}
}
if (event.equals(KeyCode.Escape)) {
indexes[index].blur();
} else if (newIndex >= 0) {
indexes[newIndex].focus();
}
dom.EventHelper.stop(event, true);
}
}
});
this.setInputWidth();
let controls = document.createElement('div');
controls.className = 'controls';
controls.style.display = this._showOptionButtons ? 'block' : 'none';
controls.appendChild(this.caseSensitive.domNode);
controls.appendChild(this.wholeWords.domNode);
controls.appendChild(this.regex.domNode);
this.domNode.appendChild(controls);
}
public validate(): void {
if (this.inputBox) {
this.inputBox.validate();
}
}
public showMessage(message: InputBoxMessage): void {
if (this.inputBox) {
this.inputBox.showMessage(message);
}
}
public clearMessage(): void {
if (this.inputBox) {
this.inputBox.hideMessage();
}
}
private clearValidation(): void {
if (this.inputBox) {
this.inputBox.hideMessage();
}
}
public dispose(): void {
super.dispose();
}
}
| src/vs/base/browser/ui/findinput/findInput.ts | 1 | https://github.com/microsoft/vscode/commit/bbff11633c7e56e7fd5d16cc20daa9a3284afbfe | [
0.9978412389755249,
0.1025882288813591,
0.00016315514221787453,
0.0018268281128257513,
0.27438995242118835
]
|
{
"id": 10,
"code_window": [
"\t\tthis._register(this.wholeWords.onChange(viaKeyboard => {\n",
"\t\t\tthis._onDidOptionChange.fire(viaKeyboard);\n",
"\t\t\tif (!viaKeyboard && this.fixFocusOnOptionClickEnabled) {\n",
"\t\t\t\tthis.inputBox.focus();\n",
"\t\t\t}\n",
"\t\t\tthis.setInputWidth();\n",
"\t\t\tthis.validate();\n",
"\t\t}));\n",
"\n",
"\t\tthis.caseSensitive = this._register(new CaseSensitiveCheckbox({\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/base/browser/ui/findinput/findInput.ts",
"type": "replace",
"edit_start_line_idx": 339
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import 'mocha';
import * as assert from 'assert';
import { Selection, workspace, ConfigurationTarget } from 'vscode';
import { withRandomFileEditor, closeAllEditors } from './testUtils';
import { removeTag } from '../removeTag';
import { updateTag } from '../updateTag';
import { matchTag } from '../matchTag';
import { splitJoinTag } from '../splitJoinTag';
import { mergeLines } from '../mergeLines';
suite('Tests for Emmet actions on html tags', () => {
teardown(() => {
// close all editors
return closeAllEditors;
});
const contents = `
<div class="hello">
<ul>
<li><span>Hello</span></li>
<li><span>There</span></li>
<div><li><span>Bye</span></li></div>
</ul>
<span/>
</div>
`;
let contentsWithTemplate = `
<script type="text/template">
<ul>
<li><span>Hello</span></li>
<li><span>There</span></li>
<div><li><span>Bye</span></li></div>
</ul>
<span/>
</script>
`;
test('update tag with multiple cursors', () => {
const expectedContents = `
<div class="hello">
<ul>
<li><section>Hello</section></li>
<section><span>There</span></section>
<section><li><span>Bye</span></li></section>
</ul>
<span/>
</div>
`;
return withRandomFileEditor(contents, 'html', (editor, doc) => {
editor.selections = [
new Selection(3, 17, 3, 17), // cursor inside tags
new Selection(4, 5, 4, 5), // cursor inside opening tag
new Selection(5, 35, 5, 35), // cursor inside closing tag
];
return updateTag('section')!.then(() => {
assert.equal(doc.getText(), expectedContents);
return Promise.resolve();
});
});
});
// #region update tag
test('update tag with entire node selected', () => {
const expectedContents = `
<div class="hello">
<ul>
<li><section>Hello</section></li>
<li><span>There</span></li>
<section><li><span>Bye</span></li></section>
</ul>
<span/>
</div>
`;
return withRandomFileEditor(contents, 'html', (editor, doc) => {
editor.selections = [
new Selection(3, 7, 3, 25),
new Selection(5, 3, 5, 39),
];
return updateTag('section')!.then(() => {
assert.equal(doc.getText(), expectedContents);
return Promise.resolve();
});
});
});
test('update tag with template', () => {
const expectedContents = `
<script type="text/template">
<section>
<li><span>Hello</span></li>
<li><span>There</span></li>
<div><li><span>Bye</span></li></div>
</section>
<span/>
</script>
`;
return withRandomFileEditor(contentsWithTemplate, 'html', (editor, doc) => {
editor.selections = [
new Selection(2, 4, 2, 4), // cursor inside ul tag
];
return updateTag('section')!.then(() => {
assert.equal(doc.getText(), expectedContents);
return Promise.resolve();
});
});
});
// #endregion
// #region remove tag
test('remove tag with mutliple cursors', () => {
const expectedContents = `
<div class="hello">
<ul>
<li>Hello</li>
<span>There</span>
<li><span>Bye</span></li>
</ul>
<span/>
</div>
`;
return withRandomFileEditor(contents, 'html', (editor, doc) => {
editor.selections = [
new Selection(3, 17, 3, 17), // cursor inside tags
new Selection(4, 5, 4, 5), // cursor inside opening tag
new Selection(5, 35, 5, 35), // cursor inside closing tag
];
return removeTag()!.then(() => {
assert.equal(doc.getText(), expectedContents);
return Promise.resolve();
});
});
});
test('remove tag with boundary conditions', () => {
const expectedContents = `
<div class="hello">
<ul>
<li>Hello</li>
<li><span>There</span></li>
<li><span>Bye</span></li>
</ul>
<span/>
</div>
`;
return withRandomFileEditor(contents, 'html', (editor, doc) => {
editor.selections = [
new Selection(3, 7, 3, 25),
new Selection(5, 3, 5, 39),
];
return removeTag()!.then(() => {
assert.equal(doc.getText(), expectedContents);
return Promise.resolve();
});
});
});
test('remove tag with template', () => {
const expectedContents = `
<script type="text/template">
\t\t
<li><span>Hello</span></li>
<li><span>There</span></li>
<div><li><span>Bye</span></li></div>
\t
<span/>
</script>
`;
return withRandomFileEditor(contentsWithTemplate, 'html', (editor, doc) => {
editor.selections = [
new Selection(2, 4, 2, 4), // cursor inside ul tag
];
return removeTag()!.then(() => {
assert.equal(doc.getText(), expectedContents);
return Promise.resolve();
});
});
});
// #endregion
// #region split/join tag
test('split/join tag with mutliple cursors', () => {
const expectedContents = `
<div class="hello">
<ul>
<li><span/></li>
<li><span>There</span></li>
<div><li><span>Bye</span></li></div>
</ul>
<span></span>
</div>
`;
return withRandomFileEditor(contents, 'html', (editor, doc) => {
editor.selections = [
new Selection(3, 17, 3, 17), // join tag
new Selection(7, 5, 7, 5), // split tag
];
return splitJoinTag()!.then(() => {
assert.equal(doc.getText(), expectedContents);
return Promise.resolve();
});
});
});
test('split/join tag with boundary selection', () => {
const expectedContents = `
<div class="hello">
<ul>
<li><span/></li>
<li><span>There</span></li>
<div><li><span>Bye</span></li></div>
</ul>
<span></span>
</div>
`;
return withRandomFileEditor(contents, 'html', (editor, doc) => {
editor.selections = [
new Selection(3, 7, 3, 25), // join tag
new Selection(7, 2, 7, 9), // split tag
];
return splitJoinTag()!.then(() => {
assert.equal(doc.getText(), expectedContents);
return Promise.resolve();
});
});
});
test('split/join tag with templates', () => {
const expectedContents = `
<script type="text/template">
<ul>
<li><span/></li>
<li><span>There</span></li>
<div><li><span>Bye</span></li></div>
</ul>
<span></span>
</script>
`;
return withRandomFileEditor(contentsWithTemplate, 'html', (editor, doc) => {
editor.selections = [
new Selection(3, 17, 3, 17), // join tag
new Selection(7, 5, 7, 5), // split tag
];
return splitJoinTag()!.then(() => {
assert.equal(doc.getText(), expectedContents);
return Promise.resolve();
});
});
});
test('split/join tag in jsx with xhtml self closing tag', () => {
const expectedContents = `
<div class="hello">
<ul>
<li><span /></li>
<li><span>There</span></li>
<div><li><span>Bye</span></li></div>
</ul>
<span></span>
</div>
`;
const oldValueForSyntaxProfiles = workspace.getConfiguration('emmet').inspect('syntaxProfiles');
return workspace.getConfiguration('emmet').update('syntaxProfiles', { jsx: { selfClosingStyle: 'xhtml' } }, ConfigurationTarget.Global).then(() => {
return withRandomFileEditor(contents, 'jsx', (editor, doc) => {
editor.selections = [
new Selection(3, 17, 3, 17), // join tag
new Selection(7, 5, 7, 5), // split tag
];
return splitJoinTag()!.then(() => {
assert.equal(doc.getText(), expectedContents);
return workspace.getConfiguration('emmet').update('syntaxProfiles', oldValueForSyntaxProfiles ? oldValueForSyntaxProfiles.globalValue : undefined, ConfigurationTarget.Global);
});
});
});
});
// #endregion
// #region match tag
test('match tag with mutliple cursors', () => {
return withRandomFileEditor(contents, 'html', (editor, _) => {
editor.selections = [
new Selection(1, 0, 1, 0), // just before tag starts, i.e before <
new Selection(1, 1, 1, 1), // just before tag name starts
new Selection(1, 2, 1, 2), // inside tag name
new Selection(1, 6, 1, 6), // after tag name but before opening tag ends
new Selection(1, 18, 1, 18), // just before opening tag ends
new Selection(1, 19, 1, 19), // just after opening tag ends
];
matchTag();
editor.selections.forEach(selection => {
assert.equal(selection.active.line, 8);
assert.equal(selection.active.character, 3);
assert.equal(selection.anchor.line, 8);
assert.equal(selection.anchor.character, 3);
});
return Promise.resolve();
});
});
test('match tag with template scripts', () => {
let templateScript = `
<script type="text/template">
<div>
Hello
</div>
</script>`;
return withRandomFileEditor(templateScript, 'html', (editor, _) => {
editor.selections = [
new Selection(2, 2, 2, 2), // just before div tag starts, i.e before <
];
matchTag();
editor.selections.forEach(selection => {
assert.equal(selection.active.line, 4);
assert.equal(selection.active.character, 4);
assert.equal(selection.anchor.line, 4);
assert.equal(selection.anchor.character, 4);
});
return Promise.resolve();
});
});
// #endregion
// #region merge lines
test('merge lines of tag with children when empty selection', () => {
const expectedContents = `
<div class="hello">
<ul><li><span>Hello</span></li><li><span>There</span></li><div><li><span>Bye</span></li></div></ul>
<span/>
</div>
`;
return withRandomFileEditor(contents, 'html', (editor, doc) => {
editor.selections = [
new Selection(2, 3, 2, 3)
];
return mergeLines()!.then(() => {
assert.equal(doc.getText(), expectedContents);
return Promise.resolve();
});
});
});
test('merge lines of tag with children when full node selection', () => {
const expectedContents = `
<div class="hello">
<ul><li><span>Hello</span></li><li><span>There</span></li><div><li><span>Bye</span></li></div></ul>
<span/>
</div>
`;
return withRandomFileEditor(contents, 'html', (editor, doc) => {
editor.selections = [
new Selection(2, 3, 6, 7)
];
return mergeLines()!.then(() => {
assert.equal(doc.getText(), expectedContents);
return Promise.resolve();
});
});
});
test('merge lines is no-op when start and end nodes are on the same line', () => {
return withRandomFileEditor(contents, 'html', (editor, doc) => {
editor.selections = [
new Selection(3, 9, 3, 9), // cursor is inside the <span> in <li><span>Hello</span></li>
new Selection(4, 5, 4, 5), // cursor is inside the <li> in <li><span>Hello</span></li>
new Selection(5, 5, 5, 20) // selection spans multiple nodes in the same line
];
return mergeLines()!.then(() => {
assert.equal(doc.getText(), contents);
return Promise.resolve();
});
});
});
// #endregion
});
| extensions/emmet/src/test/tagActions.test.ts | 0 | https://github.com/microsoft/vscode/commit/bbff11633c7e56e7fd5d16cc20daa9a3284afbfe | [
0.00017551648488733917,
0.0001726151822367683,
0.000168911850778386,
0.00017274539277423173,
0.0000016818678432173328
]
|
{
"id": 10,
"code_window": [
"\t\tthis._register(this.wholeWords.onChange(viaKeyboard => {\n",
"\t\t\tthis._onDidOptionChange.fire(viaKeyboard);\n",
"\t\t\tif (!viaKeyboard && this.fixFocusOnOptionClickEnabled) {\n",
"\t\t\t\tthis.inputBox.focus();\n",
"\t\t\t}\n",
"\t\t\tthis.setInputWidth();\n",
"\t\t\tthis.validate();\n",
"\t\t}));\n",
"\n",
"\t\tthis.caseSensitive = this._register(new CaseSensitiveCheckbox({\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/base/browser/ui/findinput/findInput.ts",
"type": "replace",
"edit_start_line_idx": 339
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as nls from 'vs/nls';
import * as path from 'vs/base/common/path';
import * as platform from 'vs/base/common/platform';
import { EDITOR_FONT_DEFAULTS, IEditorOptions } from 'vs/editor/common/config/editorOptions';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IWorkspaceConfigurationService } from 'vs/workbench/services/configuration/common/configuration';
import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage';
import { ITerminalConfiguration, ITerminalConfigHelper, ITerminalFont, IShellLaunchConfig, IS_WORKSPACE_SHELL_ALLOWED_STORAGE_KEY, TERMINAL_CONFIG_SECTION, DEFAULT_LETTER_SPACING, DEFAULT_LINE_HEIGHT, MINIMUM_LETTER_SPACING } from 'vs/workbench/contrib/terminal/common/terminal';
import Severity from 'vs/base/common/severity';
import { isFedora, isUbuntu } from 'vs/workbench/contrib/terminal/node/terminal';
import { Terminal as XTermTerminal } from 'vscode-xterm';
import { INotificationService } from 'vs/platform/notification/common/notification';
const MINIMUM_FONT_SIZE = 6;
const MAXIMUM_FONT_SIZE = 25;
/**
* Encapsulates terminal configuration logic, the primary purpose of this file is so that platform
* specific test cases can be written.
*/
export class TerminalConfigHelper implements ITerminalConfigHelper {
public panelContainer: HTMLElement;
private _charMeasureElement: HTMLElement;
private _lastFontMeasurement: ITerminalFont;
public config: ITerminalConfiguration;
public constructor(
@IConfigurationService private readonly _configurationService: IConfigurationService,
@IWorkspaceConfigurationService private readonly _workspaceConfigurationService: IWorkspaceConfigurationService,
@INotificationService private readonly _notificationService: INotificationService,
@IStorageService private readonly _storageService: IStorageService
) {
this._updateConfig();
this._configurationService.onDidChangeConfiguration(e => {
if (e.affectsConfiguration(TERMINAL_CONFIG_SECTION)) {
this._updateConfig();
}
});
}
private _updateConfig(): void {
this.config = this._configurationService.getValue<ITerminalConfiguration>(TERMINAL_CONFIG_SECTION);
}
public configFontIsMonospace(): boolean {
this._createCharMeasureElementIfNecessary();
const fontSize = 15;
const fontFamily = this.config.fontFamily || this._configurationService.getValue<IEditorOptions>('editor').fontFamily || EDITOR_FONT_DEFAULTS.fontFamily;
const i_rect = this._getBoundingRectFor('i', fontFamily, fontSize);
const w_rect = this._getBoundingRectFor('w', fontFamily, fontSize);
const invalidBounds = !i_rect.width || !w_rect.width;
if (invalidBounds) {
// There is no reason to believe the font is not Monospace.
return true;
}
return i_rect.width === w_rect.width;
}
private _createCharMeasureElementIfNecessary() {
// Create charMeasureElement if it hasn't been created or if it was orphaned by its parent
if (!this._charMeasureElement || !this._charMeasureElement.parentElement) {
this._charMeasureElement = document.createElement('div');
this.panelContainer.appendChild(this._charMeasureElement);
}
}
private _getBoundingRectFor(char: string, fontFamily: string, fontSize: number): ClientRect | DOMRect {
const style = this._charMeasureElement.style;
style.display = 'inline-block';
style.fontFamily = fontFamily;
style.fontSize = fontSize + 'px';
style.lineHeight = 'normal';
this._charMeasureElement.innerText = char;
const rect = this._charMeasureElement.getBoundingClientRect();
style.display = 'none';
return rect;
}
private _measureFont(fontFamily: string, fontSize: number, letterSpacing: number, lineHeight: number): ITerminalFont {
this._createCharMeasureElementIfNecessary();
const rect = this._getBoundingRectFor('X', fontFamily, fontSize);
// Bounding client rect was invalid, use last font measurement if available.
if (this._lastFontMeasurement && !rect.width && !rect.height) {
return this._lastFontMeasurement;
}
this._lastFontMeasurement = {
fontFamily,
fontSize,
letterSpacing,
lineHeight,
charWidth: rect.width,
charHeight: Math.ceil(rect.height)
};
return this._lastFontMeasurement;
}
/**
* Gets the font information based on the terminal.integrated.fontFamily
* terminal.integrated.fontSize, terminal.integrated.lineHeight configuration properties
*/
public getFont(xterm?: XTermTerminal, excludeDimensions?: boolean): ITerminalFont {
const editorConfig = this._configurationService.getValue<IEditorOptions>('editor');
let fontFamily = this.config.fontFamily || editorConfig.fontFamily || EDITOR_FONT_DEFAULTS.fontFamily;
let fontSize = this._toInteger(this.config.fontSize, MINIMUM_FONT_SIZE, MAXIMUM_FONT_SIZE, EDITOR_FONT_DEFAULTS.fontSize);
// Work around bad font on Fedora/Ubuntu
if (!this.config.fontFamily) {
if (isFedora) {
fontFamily = '\'DejaVu Sans Mono\', monospace';
}
if (isUbuntu) {
fontFamily = '\'Ubuntu Mono\', monospace';
// Ubuntu mono is somehow smaller, so set fontSize a bit larger to get the same perceived size.
fontSize = this._toInteger(fontSize + 2, MINIMUM_FONT_SIZE, MAXIMUM_FONT_SIZE, EDITOR_FONT_DEFAULTS.fontSize);
}
}
const letterSpacing = this.config.letterSpacing ? Math.max(Math.floor(this.config.letterSpacing), MINIMUM_LETTER_SPACING) : DEFAULT_LETTER_SPACING;
const lineHeight = this.config.lineHeight ? Math.max(this.config.lineHeight, 1) : DEFAULT_LINE_HEIGHT;
if (excludeDimensions) {
return {
fontFamily,
fontSize,
letterSpacing,
lineHeight
};
}
// Get the character dimensions from xterm if it's available
if (xterm) {
if (xterm._core.charMeasure && xterm._core.charMeasure.width && xterm._core.charMeasure.height) {
return {
fontFamily,
fontSize,
letterSpacing,
lineHeight,
charHeight: xterm._core.charMeasure.height,
charWidth: xterm._core.charMeasure.width
};
}
}
// Fall back to measuring the font ourselves
return this._measureFont(fontFamily, fontSize, letterSpacing, lineHeight);
}
public setWorkspaceShellAllowed(isAllowed: boolean): void {
this._storageService.store(IS_WORKSPACE_SHELL_ALLOWED_STORAGE_KEY, isAllowed, StorageScope.WORKSPACE);
}
public isWorkspaceShellAllowed(defaultValue: boolean | undefined = undefined): boolean | undefined {
return this._storageService.getBoolean(IS_WORKSPACE_SHELL_ALLOWED_STORAGE_KEY, StorageScope.WORKSPACE, defaultValue);
}
public checkWorkspaceShellPermissions(platformOverride: platform.Platform = platform.platform): boolean {
// Check whether there is a workspace setting
const platformKey = platformOverride === platform.Platform.Windows ? 'windows' : platformOverride === platform.Platform.Mac ? 'osx' : 'linux';
const shellConfigValue = this._workspaceConfigurationService.inspect<string>(`terminal.integrated.shell.${platformKey}`);
const shellArgsConfigValue = this._workspaceConfigurationService.inspect<string[]>(`terminal.integrated.shellArgs.${platformKey}`);
const envConfigValue = this._workspaceConfigurationService.inspect<string[]>(`terminal.integrated.env.${platformKey}`);
// Check if workspace setting exists and whether it's whitelisted
let isWorkspaceShellAllowed: boolean | undefined = false;
if (shellConfigValue.workspace !== undefined || shellArgsConfigValue.workspace !== undefined || envConfigValue.workspace !== undefined) {
isWorkspaceShellAllowed = this.isWorkspaceShellAllowed(undefined);
}
// Always allow [] args as it would lead to an odd error message and should not be dangerous
if (shellConfigValue.workspace === undefined && envConfigValue.workspace === undefined &&
shellArgsConfigValue.workspace && shellArgsConfigValue.workspace.length === 0) {
isWorkspaceShellAllowed = true;
}
// Check if the value is neither blacklisted (false) or whitelisted (true) and ask for
// permission
if (isWorkspaceShellAllowed === undefined) {
let shellString: string | undefined;
if (shellConfigValue.workspace) {
shellString = `shell: "${shellConfigValue.workspace}"`;
}
let argsString: string | undefined;
if (shellArgsConfigValue.workspace) {
argsString = `shellArgs: [${shellArgsConfigValue.workspace.map(v => '"' + v + '"').join(', ')}]`;
}
let envString: string | undefined;
if (envConfigValue.workspace) {
envString = `env: {${Object.keys(envConfigValue.workspace).map(k => `${k}:${envConfigValue.workspace![k]}`).join(', ')}}`;
}
// Should not be localized as it's json-like syntax referencing settings keys
const workspaceConfigStrings: string[] = [];
if (shellString) {
workspaceConfigStrings.push(shellString);
}
if (argsString) {
workspaceConfigStrings.push(argsString);
}
if (envString) {
workspaceConfigStrings.push(envString);
}
const workspaceConfigString = workspaceConfigStrings.join(', ');
this._notificationService.prompt(Severity.Info, nls.localize('terminal.integrated.allowWorkspaceShell', "Do you allow this workspace to modify your terminal shell? {0}", workspaceConfigString),
[{
label: nls.localize('allow', "Allow"),
run: () => this.setWorkspaceShellAllowed(true)
},
{
label: nls.localize('disallow', "Disallow"),
run: () => this.setWorkspaceShellAllowed(false)
}]
);
}
return !!isWorkspaceShellAllowed;
}
public mergeDefaultShellPathAndArgs(shell: IShellLaunchConfig, platformOverride: platform.Platform = platform.platform): void {
const isWorkspaceShellAllowed = this.checkWorkspaceShellPermissions(platformOverride);
const platformKey = platformOverride === platform.Platform.Windows ? 'windows' : platformOverride === platform.Platform.Mac ? 'osx' : 'linux';
const shellConfigValue = this._workspaceConfigurationService.inspect<string>(`terminal.integrated.shell.${platformKey}`);
const shellArgsConfigValue = this._workspaceConfigurationService.inspect<string[]>(`terminal.integrated.shellArgs.${platformKey}`);
shell.executable = (isWorkspaceShellAllowed ? shellConfigValue.value : shellConfigValue.user) || shellConfigValue.default;
shell.args = (isWorkspaceShellAllowed ? shellArgsConfigValue.value : shellArgsConfigValue.user) || shellArgsConfigValue.default;
// Change Sysnative to System32 if the OS is Windows but NOT WoW64. It's
// safe to assume that this was used by accident as Sysnative does not
// exist and will break the terminal in non-WoW64 environments.
if (platform.isWindows && !process.env.hasOwnProperty('PROCESSOR_ARCHITEW6432') && process.env.windir) {
const sysnativePath = path.join(process.env.windir, 'Sysnative').toLowerCase();
if (shell.executable.toLowerCase().indexOf(sysnativePath) === 0) {
shell.executable = path.join(process.env.windir, 'System32', shell.executable.substr(sysnativePath.length));
}
}
// Convert / to \ on Windows for convenience
if (platform.isWindows) {
shell.executable = shell.executable.replace(/\//g, '\\');
}
}
private _toInteger(source: any, minimum: number, maximum: number, fallback: number): number {
let r = parseInt(source, 10);
if (isNaN(r)) {
return fallback;
}
if (typeof minimum === 'number') {
r = Math.max(minimum, r);
}
if (typeof maximum === 'number') {
r = Math.min(maximum, r);
}
return r;
}
}
| src/vs/workbench/contrib/terminal/electron-browser/terminalConfigHelper.ts | 0 | https://github.com/microsoft/vscode/commit/bbff11633c7e56e7fd5d16cc20daa9a3284afbfe | [
0.00017626953194849193,
0.0001704382011666894,
0.00016496710304636508,
0.00017088792810682207,
0.0000031045892683323473
]
|
{
"id": 10,
"code_window": [
"\t\tthis._register(this.wholeWords.onChange(viaKeyboard => {\n",
"\t\t\tthis._onDidOptionChange.fire(viaKeyboard);\n",
"\t\t\tif (!viaKeyboard && this.fixFocusOnOptionClickEnabled) {\n",
"\t\t\t\tthis.inputBox.focus();\n",
"\t\t\t}\n",
"\t\t\tthis.setInputWidth();\n",
"\t\t\tthis.validate();\n",
"\t\t}));\n",
"\n",
"\t\tthis.caseSensitive = this._register(new CaseSensitiveCheckbox({\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/base/browser/ui/findinput/findInput.ts",
"type": "replace",
"edit_start_line_idx": 339
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Application } from '../../application';
export function setup() {
describe('Editor', () => {
it('shows correct quick outline', async function () {
const app = this.app as Application;
await app.workbench.quickopen.openFile('www');
await app.workbench.quickopen.openQuickOutline();
await app.workbench.quickopen.waitForQuickOpenElements(names => names.length >= 6);
});
it(`finds 'All References' to 'app'`, async function () {
const app = this.app as Application;
await app.workbench.quickopen.openFile('www');
const references = await app.workbench.editor.findReferences('www', 'app', 7);
await references.waitForReferencesCountInTitle(3);
await references.waitForReferencesCount(3);
await references.close();
});
it(`renames local 'app' variable`, async function () {
const app = this.app as Application;
await app.workbench.quickopen.openFile('www');
await app.workbench.editor.rename('www', 7, 'app', 'newApp');
await app.workbench.editor.waitForEditorContents('www', contents => contents.indexOf('newApp') > -1);
});
// it('folds/unfolds the code correctly', async function () {
// await app.workbench.quickopen.openFile('www');
// // Fold
// await app.workbench.editor.foldAtLine(3);
// await app.workbench.editor.waitUntilShown(3);
// await app.workbench.editor.waitUntilHidden(4);
// await app.workbench.editor.waitUntilHidden(5);
// // Unfold
// await app.workbench.editor.unfoldAtLine(3);
// await app.workbench.editor.waitUntilShown(3);
// await app.workbench.editor.waitUntilShown(4);
// await app.workbench.editor.waitUntilShown(5);
// });
it(`verifies that 'Go To Definition' works`, async function () {
const app = this.app as Application;
await app.workbench.quickopen.openFile('app.js');
await app.workbench.editor.gotoDefinition('app.js', 'app', 14);
await app.workbench.editor.waitForHighlightingLine('app.js', 11);
});
it(`verifies that 'Peek Definition' works`, async function () {
const app = this.app as Application;
await app.workbench.quickopen.openFile('app.js');
const peek = await app.workbench.editor.peekDefinition('app.js', 'app', 14);
await peek.waitForFile('app.js');
});
});
} | test/smoke/src/areas/editor/editor.test.ts | 0 | https://github.com/microsoft/vscode/commit/bbff11633c7e56e7fd5d16cc20daa9a3284afbfe | [
0.0001756656711222604,
0.00017135709640569985,
0.00016935454914346337,
0.00017118801770266145,
0.0000017785915815693443
]
|
{
"id": 11,
"code_window": [
"\t\tthis._register(this.caseSensitive.onChange(viaKeyboard => {\n",
"\t\t\tthis._onDidOptionChange.fire(viaKeyboard);\n",
"\t\t\tif (!viaKeyboard && this.fixFocusOnOptionClickEnabled) {\n",
"\t\t\t\tthis.inputBox.focus();\n",
"\t\t\t}\n",
"\t\t\tthis.setInputWidth();\n",
"\t\t\tthis.validate();\n",
"\t\t}));\n",
"\t\tthis._register(this.caseSensitive.onKeyDown(e => {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/base/browser/ui/findinput/findInput.ts",
"type": "replace",
"edit_start_line_idx": 353
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
/* ---------- Find input ---------- */
.monaco-findInput {
position: relative;
}
.monaco-findInput .monaco-inputbox {
font-size: 13px;
width: 100%;
}
.monaco-findInput .monaco-inputbox > .wrapper > .input {
width: 100% !important;
}
.monaco-findInput > .controls {
position: absolute;
top: 3px;
right: 2px;
}
.vs .monaco-findInput.disabled {
background-color: #E1E1E1;
}
/* Theming */
.vs-dark .monaco-findInput.disabled {
background-color: #333;
}
/* Highlighting */
.monaco-findInput.highlight-0 .controls {
animation: monaco-findInput-highlight-0 100ms linear 0s;
}
.monaco-findInput.highlight-1 .controls {
animation: monaco-findInput-highlight-1 100ms linear 0s;
}
.hc-black .monaco-findInput.highlight-0 .controls,
.vs-dark .monaco-findInput.highlight-0 .controls {
animation: monaco-findInput-highlight-dark-0 100ms linear 0s;
}
.hc-black .monaco-findInput.highlight-1 .controls,
.vs-dark .monaco-findInput.highlight-1 .controls {
animation: monaco-findInput-highlight-dark-1 100ms linear 0s;
}
@keyframes monaco-findInput-highlight-0 {
0% { background: rgba(253, 255, 0, 0.8); }
100% { background: transparent; }
}
@keyframes monaco-findInput-highlight-1 {
0% { background: rgba(253, 255, 0, 0.8); }
/* Made intentionally different such that the CSS minifier does not collapse the two animations into a single one*/
99% { background: transparent; }
}
@keyframes monaco-findInput-highlight-dark-0 {
0% { background: rgba(255, 255, 255, 0.44); }
100% { background: transparent; }
}
@keyframes monaco-findInput-highlight-dark-1 {
0% { background: rgba(255, 255, 255, 0.44); }
/* Made intentionally different such that the CSS minifier does not collapse the two animations into a single one*/
99% { background: transparent; }
} | src/vs/base/browser/ui/findinput/findInput.css | 1 | https://github.com/microsoft/vscode/commit/bbff11633c7e56e7fd5d16cc20daa9a3284afbfe | [
0.00017397076589986682,
0.00017340484191663563,
0.00017247976211365312,
0.00017370439309161156,
5.32381932316639e-7
]
|
{
"id": 11,
"code_window": [
"\t\tthis._register(this.caseSensitive.onChange(viaKeyboard => {\n",
"\t\t\tthis._onDidOptionChange.fire(viaKeyboard);\n",
"\t\t\tif (!viaKeyboard && this.fixFocusOnOptionClickEnabled) {\n",
"\t\t\t\tthis.inputBox.focus();\n",
"\t\t\t}\n",
"\t\t\tthis.setInputWidth();\n",
"\t\t\tthis.validate();\n",
"\t\t}));\n",
"\t\tthis._register(this.caseSensitive.onKeyDown(e => {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/base/browser/ui/findinput/findInput.ts",
"type": "replace",
"edit_start_line_idx": 353
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as nls from 'vs/nls';
import * as crypto from 'crypto';
import * as Objects from 'vs/base/common/objects';
import { TaskIdentifier, KeyedTaskIdentifier, TaskDefinition } from 'vs/workbench/contrib/tasks/common/tasks';
import { TaskDefinitionRegistry } from 'vs/workbench/contrib/tasks/common/taskDefinitionRegistry';
namespace KeyedTaskIdentifier {
export function create(value: TaskIdentifier): KeyedTaskIdentifier {
const hash = crypto.createHash('md5');
hash.update(JSON.stringify(value));
let result = { _key: hash.digest('hex'), type: value.taskType };
Objects.assign(result, value);
return result;
}
}
namespace TaskDefinition {
export function createTaskIdentifier(external: TaskIdentifier, reporter: { error(message: string): void; }): KeyedTaskIdentifier | undefined {
let definition = TaskDefinitionRegistry.get(external.type);
if (definition === undefined) {
// We have no task definition so we can't sanitize the literal. Take it as is
let copy = Objects.deepClone(external);
delete copy._key;
return KeyedTaskIdentifier.create(copy);
}
let literal: { type: string;[name: string]: any } = Object.create(null);
literal.type = definition.taskType;
let required: Set<string> = new Set();
definition.required.forEach(element => required.add(element));
let properties = definition.properties;
for (let property of Object.keys(properties)) {
let value = external[property];
if (value !== undefined && value !== null) {
literal[property] = value;
} else if (required.has(property)) {
let schema = properties[property];
if (schema.default !== undefined) {
literal[property] = Objects.deepClone(schema.default);
} else {
switch (schema.type) {
case 'boolean':
literal[property] = false;
break;
case 'number':
case 'integer':
literal[property] = 0;
break;
case 'string':
literal[property] = '';
break;
default:
reporter.error(nls.localize(
'TaskDefinition.missingRequiredProperty',
'Error: the task identifier \'{0}\' is missing the required property \'{1}\'. The task identifier will be ignored.', JSON.stringify(external, undefined, 0), property
));
return undefined;
}
}
}
}
return KeyedTaskIdentifier.create(literal);
}
}
export { KeyedTaskIdentifier, TaskDefinition };
| src/vs/workbench/contrib/tasks/node/tasks.ts | 0 | https://github.com/microsoft/vscode/commit/bbff11633c7e56e7fd5d16cc20daa9a3284afbfe | [
0.00017643414321355522,
0.00017203547758981586,
0.00016743881860747933,
0.00017249408119823784,
0.000002932114739451208
]
|
{
"id": 11,
"code_window": [
"\t\tthis._register(this.caseSensitive.onChange(viaKeyboard => {\n",
"\t\t\tthis._onDidOptionChange.fire(viaKeyboard);\n",
"\t\t\tif (!viaKeyboard && this.fixFocusOnOptionClickEnabled) {\n",
"\t\t\t\tthis.inputBox.focus();\n",
"\t\t\t}\n",
"\t\t\tthis.setInputWidth();\n",
"\t\t\tthis.validate();\n",
"\t\t}));\n",
"\t\tthis._register(this.caseSensitive.onKeyDown(e => {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/base/browser/ui/findinput/findInput.ts",
"type": "replace",
"edit_start_line_idx": 353
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as assert from 'assert';
import { URI } from 'vs/base/common/uri';
import { parse, stringify } from 'vs/base/common/marshalling';
suite('Marshalling', () => {
test('RegExp', () => {
let value = /foo/img;
let raw = stringify(value);
let clone = <RegExp>parse(raw);
assert.equal(value.source, clone.source);
assert.equal(value.global, clone.global);
assert.equal(value.ignoreCase, clone.ignoreCase);
assert.equal(value.multiline, clone.multiline);
});
test('URI', () => {
const value = URI.from({ scheme: 'file', authority: 'server', path: '/shares/c#files', query: 'q', fragment: 'f' });
const raw = stringify(value);
const clone = <URI>parse(raw);
assert.equal(value.scheme, clone.scheme);
assert.equal(value.authority, clone.authority);
assert.equal(value.path, clone.path);
assert.equal(value.query, clone.query);
assert.equal(value.fragment, clone.fragment);
});
test('Bug 16793:# in folder name => mirror models get out of sync', () => {
const uri1 = URI.file('C:\\C#\\file.txt');
assert.equal(parse(stringify(uri1)).toString(), uri1.toString());
});
}); | src/vs/base/test/common/marshalling.test.ts | 0 | https://github.com/microsoft/vscode/commit/bbff11633c7e56e7fd5d16cc20daa9a3284afbfe | [
0.0001754065597197041,
0.00017448012658860534,
0.00017308290989603847,
0.00017471550381742418,
8.62218939801096e-7
]
|
{
"id": 11,
"code_window": [
"\t\tthis._register(this.caseSensitive.onChange(viaKeyboard => {\n",
"\t\t\tthis._onDidOptionChange.fire(viaKeyboard);\n",
"\t\t\tif (!viaKeyboard && this.fixFocusOnOptionClickEnabled) {\n",
"\t\t\t\tthis.inputBox.focus();\n",
"\t\t\t}\n",
"\t\t\tthis.setInputWidth();\n",
"\t\t\tthis.validate();\n",
"\t\t}));\n",
"\t\tthis._register(this.caseSensitive.onKeyDown(e => {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/base/browser/ui/findinput/findInput.ts",
"type": "replace",
"edit_start_line_idx": 353
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as path from 'path';
import * as fs from 'fs';
import { URL } from 'url';
import * as nls from 'vscode-nls';
const localize = nls.loadMessageBundle();
import { parseTree, findNodeAtLocation, Node as JsonNode } from 'jsonc-parser';
import * as MarkdownItType from 'markdown-it';
import { languages, workspace, Disposable, TextDocument, Uri, Diagnostic, Range, DiagnosticSeverity, Position, env } from 'vscode';
const product = JSON.parse(fs.readFileSync(path.join(env.appRoot, 'product.json'), { encoding: 'utf-8' }));
const allowedBadgeProviders: string[] = (product.extensionAllowedBadgeProviders || []).map((s: string) => s.toLowerCase());
const httpsRequired = localize('httpsRequired', "Images must use the HTTPS protocol.");
const svgsNotValid = localize('svgsNotValid', "SVGs are not a valid image source.");
const embeddedSvgsNotValid = localize('embeddedSvgsNotValid', "Embedded SVGs are not a valid image source.");
const dataUrlsNotValid = localize('dataUrlsNotValid', "Data URLs are not a valid image source.");
const relativeUrlRequiresHttpsRepository = localize('relativeUrlRequiresHttpsRepository', "Relative image URLs require a repository with HTTPS protocol to be specified in the package.json.");
const relativeIconUrlRequiresHttpsRepository = localize('relativeIconUrlRequiresHttpsRepository', "An icon requires a repository with HTTPS protocol to be specified in this package.json.");
const relativeBadgeUrlRequiresHttpsRepository = localize('relativeBadgeUrlRequiresHttpsRepository', "Relative badge URLs require a repository with HTTPS protocol to be specified in this package.json.");
enum Context {
ICON,
BADGE,
MARKDOWN
}
interface TokenAndPosition {
token: MarkdownItType.Token;
begin: number;
end: number;
}
interface PackageJsonInfo {
isExtension: boolean;
hasHttpsRepository: boolean;
repository: Uri;
}
export class ExtensionLinter {
private diagnosticsCollection = languages.createDiagnosticCollection('extension-editing');
private fileWatcher = workspace.createFileSystemWatcher('**/package.json');
private disposables: Disposable[] = [this.diagnosticsCollection, this.fileWatcher];
private folderToPackageJsonInfo: Record<string, PackageJsonInfo> = {};
private packageJsonQ = new Set<TextDocument>();
private readmeQ = new Set<TextDocument>();
private timer: NodeJS.Timer | undefined;
private markdownIt: MarkdownItType.MarkdownIt | undefined;
constructor() {
this.disposables.push(
workspace.onDidOpenTextDocument(document => this.queue(document)),
workspace.onDidChangeTextDocument(event => this.queue(event.document)),
workspace.onDidCloseTextDocument(document => this.clear(document)),
this.fileWatcher.onDidChange(uri => this.packageJsonChanged(this.getUriFolder(uri))),
this.fileWatcher.onDidCreate(uri => this.packageJsonChanged(this.getUriFolder(uri))),
this.fileWatcher.onDidDelete(uri => this.packageJsonChanged(this.getUriFolder(uri))),
);
workspace.textDocuments.forEach(document => this.queue(document));
}
private queue(document: TextDocument) {
const p = document.uri.path;
if (document.languageId === 'json' && endsWith(p, '/package.json')) {
this.packageJsonQ.add(document);
this.startTimer();
}
this.queueReadme(document);
}
private queueReadme(document: TextDocument) {
const p = document.uri.path;
if (document.languageId === 'markdown' && (endsWith(p.toLowerCase(), '/readme.md') || endsWith(p.toLowerCase(), '/changelog.md'))) {
this.readmeQ.add(document);
this.startTimer();
}
}
private startTimer() {
if (this.timer) {
clearTimeout(this.timer);
}
this.timer = setTimeout(() => {
this.lint()
.catch(console.error);
}, 300);
}
private async lint() {
this.lintPackageJson();
await this.lintReadme();
}
private lintPackageJson() {
this.packageJsonQ.forEach(document => {
this.packageJsonQ.delete(document);
if (document.isClosed) {
return;
}
const diagnostics: Diagnostic[] = [];
const tree = parseTree(document.getText());
const info = this.readPackageJsonInfo(this.getUriFolder(document.uri), tree);
if (info.isExtension) {
const icon = findNodeAtLocation(tree, ['icon']);
if (icon && icon.type === 'string') {
this.addDiagnostics(diagnostics, document, icon.offset + 1, icon.offset + icon.length - 1, icon.value, Context.ICON, info);
}
const badges = findNodeAtLocation(tree, ['badges']);
if (badges && badges.type === 'array' && badges.children) {
badges.children.map(child => findNodeAtLocation(child, ['url']))
.filter(url => url && url.type === 'string')
.map(url => this.addDiagnostics(diagnostics, document, url!.offset + 1, url!.offset + url!.length - 1, url!.value, Context.BADGE, info));
}
}
this.diagnosticsCollection.set(document.uri, diagnostics);
});
}
private async lintReadme() {
for (const document of Array.from(this.readmeQ)) {
this.readmeQ.delete(document);
if (document.isClosed) {
return;
}
const folder = this.getUriFolder(document.uri);
let info = this.folderToPackageJsonInfo[folder.toString()];
if (!info) {
const tree = await this.loadPackageJson(folder);
info = this.readPackageJsonInfo(folder, tree);
}
if (!info.isExtension) {
this.diagnosticsCollection.set(document.uri, []);
return;
}
const text = document.getText();
if (!this.markdownIt) {
this.markdownIt = new (await import('markdown-it'));
}
const tokens = this.markdownIt.parse(text, {});
const tokensAndPositions: TokenAndPosition[] = (function toTokensAndPositions(this: ExtensionLinter, tokens: MarkdownItType.Token[], begin = 0, end = text.length): TokenAndPosition[] {
const tokensAndPositions = tokens.map<TokenAndPosition>(token => {
if (token.map) {
const tokenBegin = document.offsetAt(new Position(token.map[0], 0));
const tokenEnd = begin = document.offsetAt(new Position(token.map[1], 0));
return {
token,
begin: tokenBegin,
end: tokenEnd
};
}
const image = token.type === 'image' && this.locateToken(text, begin, end, token, token.attrGet('src'));
const other = image || this.locateToken(text, begin, end, token, token.content);
return other || {
token,
begin,
end: begin
};
});
return tokensAndPositions.concat(
...tokensAndPositions.filter(tnp => tnp.token.children && tnp.token.children.length)
.map(tnp => toTokensAndPositions.call(this, tnp.token.children, tnp.begin, tnp.end))
);
}).call(this, tokens);
const diagnostics: Diagnostic[] = [];
tokensAndPositions.filter(tnp => tnp.token.type === 'image' && tnp.token.attrGet('src'))
.map(inp => {
const src = inp.token.attrGet('src')!;
const begin = text.indexOf(src, inp.begin);
if (begin !== -1 && begin < inp.end) {
this.addDiagnostics(diagnostics, document, begin, begin + src.length, src, Context.MARKDOWN, info);
} else {
const content = inp.token.content;
const begin = text.indexOf(content, inp.begin);
if (begin !== -1 && begin < inp.end) {
this.addDiagnostics(diagnostics, document, begin, begin + content.length, src, Context.MARKDOWN, info);
}
}
});
let svgStart: Diagnostic;
for (const tnp of tokensAndPositions) {
if (tnp.token.type === 'text' && tnp.token.content) {
const parse5 = await import('parse5');
const parser = new parse5.SAXParser({ locationInfo: true });
parser.on('startTag', (name, attrs, _selfClosing, location) => {
if (name === 'img') {
const src = attrs.find(a => a.name === 'src');
if (src && src.value && location) {
const begin = text.indexOf(src.value, tnp.begin + location.startOffset);
if (begin !== -1 && begin < tnp.end) {
this.addDiagnostics(diagnostics, document, begin, begin + src.value.length, src.value, Context.MARKDOWN, info);
}
}
} else if (name === 'svg' && location) {
const begin = tnp.begin + location.startOffset;
const end = tnp.begin + location.endOffset;
const range = new Range(document.positionAt(begin), document.positionAt(end));
svgStart = new Diagnostic(range, embeddedSvgsNotValid, DiagnosticSeverity.Warning);
diagnostics.push(svgStart);
}
});
parser.on('endTag', (name, location) => {
if (name === 'svg' && svgStart && location) {
const end = tnp.begin + location.endOffset;
svgStart.range = new Range(svgStart.range.start, document.positionAt(end));
}
});
parser.write(tnp.token.content);
parser.end();
}
}
this.diagnosticsCollection.set(document.uri, diagnostics);
}
}
private locateToken(text: string, begin: number, end: number, token: MarkdownItType.Token, content: string | null) {
if (content) {
const tokenBegin = text.indexOf(content, begin);
if (tokenBegin !== -1) {
const tokenEnd = tokenBegin + content.length;
if (tokenEnd <= end) {
begin = tokenEnd;
return {
token,
begin: tokenBegin,
end: tokenEnd
};
}
}
}
return undefined;
}
private readPackageJsonInfo(folder: Uri, tree: JsonNode | undefined) {
const engine = tree && findNodeAtLocation(tree, ['engines', 'vscode']);
const repo = tree && findNodeAtLocation(tree, ['repository', 'url']);
const uri = repo && parseUri(repo.value);
const info: PackageJsonInfo = {
isExtension: !!(engine && engine.type === 'string'),
hasHttpsRepository: !!(repo && repo.type === 'string' && repo.value && uri && uri.scheme.toLowerCase() === 'https'),
repository: uri!
};
const str = folder.toString();
const oldInfo = this.folderToPackageJsonInfo[str];
if (oldInfo && (oldInfo.isExtension !== info.isExtension || oldInfo.hasHttpsRepository !== info.hasHttpsRepository)) {
this.packageJsonChanged(folder); // clears this.folderToPackageJsonInfo[str]
}
this.folderToPackageJsonInfo[str] = info;
return info;
}
private async loadPackageJson(folder: Uri) {
if (folder.scheme === 'git') { // #36236
return undefined;
}
const file = folder.with({ path: path.posix.join(folder.path, 'package.json') });
try {
const document = await workspace.openTextDocument(file);
return parseTree(document.getText());
} catch (err) {
return undefined;
}
}
private packageJsonChanged(folder: Uri) {
delete this.folderToPackageJsonInfo[folder.toString()];
const str = folder.toString().toLowerCase();
workspace.textDocuments.filter(document => this.getUriFolder(document.uri).toString().toLowerCase() === str)
.forEach(document => this.queueReadme(document));
}
private getUriFolder(uri: Uri) {
return uri.with({ path: path.posix.dirname(uri.path) });
}
private addDiagnostics(diagnostics: Diagnostic[], document: TextDocument, begin: number, end: number, src: string, context: Context, info: PackageJsonInfo) {
const hasScheme = /^\w[\w\d+.-]*:/.test(src);
const uri = parseUri(src, info.repository ? info.repository.toString() : document.uri.toString());
if (!uri) {
return;
}
const scheme = uri.scheme.toLowerCase();
if (hasScheme && scheme !== 'https' && scheme !== 'data') {
const range = new Range(document.positionAt(begin), document.positionAt(end));
diagnostics.push(new Diagnostic(range, httpsRequired, DiagnosticSeverity.Warning));
}
if (hasScheme && scheme === 'data') {
const range = new Range(document.positionAt(begin), document.positionAt(end));
diagnostics.push(new Diagnostic(range, dataUrlsNotValid, DiagnosticSeverity.Warning));
}
if (!hasScheme && !info.hasHttpsRepository) {
const range = new Range(document.positionAt(begin), document.positionAt(end));
let message = (() => {
switch (context) {
case Context.ICON: return relativeIconUrlRequiresHttpsRepository;
case Context.BADGE: return relativeBadgeUrlRequiresHttpsRepository;
default: return relativeUrlRequiresHttpsRepository;
}
})();
diagnostics.push(new Diagnostic(range, message, DiagnosticSeverity.Warning));
}
if (endsWith(uri.path.toLowerCase(), '.svg') && allowedBadgeProviders.indexOf(uri.authority.toLowerCase()) === -1) {
const range = new Range(document.positionAt(begin), document.positionAt(end));
diagnostics.push(new Diagnostic(range, svgsNotValid, DiagnosticSeverity.Warning));
}
}
private clear(document: TextDocument) {
this.diagnosticsCollection.delete(document.uri);
this.packageJsonQ.delete(document);
}
public dispose() {
this.disposables.forEach(d => d.dispose());
this.disposables = [];
}
}
function endsWith(haystack: string, needle: string): boolean {
let diff = haystack.length - needle.length;
if (diff > 0) {
return haystack.indexOf(needle, diff) === diff;
} else if (diff === 0) {
return haystack === needle;
} else {
return false;
}
}
function parseUri(src: string, base?: string, retry: boolean = true): Uri | null {
try {
let url = new URL(src, base);
return Uri.parse(url.toString());
} catch (err) {
if (retry) {
return parseUri(encodeURI(src), base, false);
} else {
return null;
}
}
}
| extensions/extension-editing/src/extensionLinter.ts | 0 | https://github.com/microsoft/vscode/commit/bbff11633c7e56e7fd5d16cc20daa9a3284afbfe | [
0.00017698392912279814,
0.00017326897068414837,
0.00016634445637464523,
0.00017401207878720015,
0.0000026946127036353573
]
|
{
"id": 12,
"code_window": [
"\t\t\t}\n",
"\t\t});\n",
"\n",
"\t\tthis.setInputWidth();\n",
"\n",
"\t\tlet controls = document.createElement('div');\n",
"\t\tcontrols.className = 'controls';\n",
"\t\tcontrols.style.display = this._showOptionButtons ? 'block' : 'none';\n",
"\t\tcontrols.appendChild(this.caseSensitive.domNode);\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/base/browser/ui/findinput/findInput.ts",
"type": "replace",
"edit_start_line_idx": 392
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import 'vs/css!./findInput';
import * as nls from 'vs/nls';
import * as dom from 'vs/base/browser/dom';
import { IMessage as InputBoxMessage, IInputValidator, IInputBoxStyles, HistoryInputBox } from 'vs/base/browser/ui/inputbox/inputBox';
import { IContextViewProvider } from 'vs/base/browser/ui/contextview/contextview';
import { Widget } from 'vs/base/browser/ui/widget';
import { Event, Emitter } from 'vs/base/common/event';
import { IKeyboardEvent } from 'vs/base/browser/keyboardEvent';
import { IMouseEvent } from 'vs/base/browser/mouseEvent';
import { KeyCode } from 'vs/base/common/keyCodes';
import { CaseSensitiveCheckbox, WholeWordsCheckbox, RegexCheckbox } from 'vs/base/browser/ui/findinput/findInputCheckboxes';
import { Color } from 'vs/base/common/color';
import { ICheckboxStyles } from 'vs/base/browser/ui/checkbox/checkbox';
export interface IFindInputOptions extends IFindInputStyles {
readonly placeholder?: string;
readonly width?: number;
readonly validation?: IInputValidator;
readonly label: string;
readonly flexibleHeight?: boolean;
readonly appendCaseSensitiveLabel?: string;
readonly appendWholeWordsLabel?: string;
readonly appendRegexLabel?: string;
readonly history?: string[];
}
export interface IFindInputStyles extends IInputBoxStyles {
inputActiveOptionBorder?: Color;
}
const NLS_DEFAULT_LABEL = nls.localize('defaultLabel', "input");
export class FindInput extends Widget {
static readonly OPTION_CHANGE: string = 'optionChange';
private contextViewProvider: IContextViewProvider;
private width: number;
private placeholder: string;
private validation?: IInputValidator;
private label: string;
private fixFocusOnOptionClickEnabled = true;
private inputActiveOptionBorder?: Color;
private inputBackground?: Color;
private inputForeground?: Color;
private inputBorder?: Color;
private inputValidationInfoBorder?: Color;
private inputValidationInfoBackground?: Color;
private inputValidationInfoForeground?: Color;
private inputValidationWarningBorder?: Color;
private inputValidationWarningBackground?: Color;
private inputValidationWarningForeground?: Color;
private inputValidationErrorBorder?: Color;
private inputValidationErrorBackground?: Color;
private inputValidationErrorForeground?: Color;
private regex: RegexCheckbox;
private wholeWords: WholeWordsCheckbox;
private caseSensitive: CaseSensitiveCheckbox;
public domNode: HTMLElement;
public inputBox: HistoryInputBox;
private readonly _onDidOptionChange = this._register(new Emitter<boolean>());
public readonly onDidOptionChange: Event<boolean /* via keyboard */> = this._onDidOptionChange.event;
private readonly _onKeyDown = this._register(new Emitter<IKeyboardEvent>());
public readonly onKeyDown: Event<IKeyboardEvent> = this._onKeyDown.event;
private readonly _onMouseDown = this._register(new Emitter<IMouseEvent>());
public readonly onMouseDown: Event<IMouseEvent> = this._onMouseDown.event;
private readonly _onInput = this._register(new Emitter<void>());
public readonly onInput: Event<void> = this._onInput.event;
private readonly _onKeyUp = this._register(new Emitter<IKeyboardEvent>());
public readonly onKeyUp: Event<IKeyboardEvent> = this._onKeyUp.event;
private _onCaseSensitiveKeyDown = this._register(new Emitter<IKeyboardEvent>());
public readonly onCaseSensitiveKeyDown: Event<IKeyboardEvent> = this._onCaseSensitiveKeyDown.event;
private _onRegexKeyDown = this._register(new Emitter<IKeyboardEvent>());
public readonly onRegexKeyDown: Event<IKeyboardEvent> = this._onRegexKeyDown.event;
constructor(parent: HTMLElement | null, contextViewProvider: IContextViewProvider, private readonly _showOptionButtons: boolean, options: IFindInputOptions) {
super();
this.contextViewProvider = contextViewProvider;
this.width = options.width || 100;
this.placeholder = options.placeholder || '';
this.validation = options.validation;
this.label = options.label || NLS_DEFAULT_LABEL;
this.inputActiveOptionBorder = options.inputActiveOptionBorder;
this.inputBackground = options.inputBackground;
this.inputForeground = options.inputForeground;
this.inputBorder = options.inputBorder;
this.inputValidationInfoBorder = options.inputValidationInfoBorder;
this.inputValidationInfoBackground = options.inputValidationInfoBackground;
this.inputValidationInfoForeground = options.inputValidationInfoForeground;
this.inputValidationWarningBorder = options.inputValidationWarningBorder;
this.inputValidationWarningBackground = options.inputValidationWarningBackground;
this.inputValidationWarningForeground = options.inputValidationWarningForeground;
this.inputValidationErrorBorder = options.inputValidationErrorBorder;
this.inputValidationErrorBackground = options.inputValidationErrorBackground;
this.inputValidationErrorForeground = options.inputValidationErrorForeground;
this.buildDomNode(options.appendCaseSensitiveLabel || '', options.appendWholeWordsLabel || '', options.appendRegexLabel || '', options.history || [], !!options.flexibleHeight);
if (parent) {
parent.appendChild(this.domNode);
}
this.onkeydown(this.inputBox.inputElement, (e) => this._onKeyDown.fire(e));
this.onkeyup(this.inputBox.inputElement, (e) => this._onKeyUp.fire(e));
this.oninput(this.inputBox.inputElement, (e) => this._onInput.fire());
this.onmousedown(this.inputBox.inputElement, (e) => this._onMouseDown.fire(e));
}
public enable(): void {
dom.removeClass(this.domNode, 'disabled');
this.inputBox.enable();
this.regex.enable();
this.wholeWords.enable();
this.caseSensitive.enable();
}
public disable(): void {
dom.addClass(this.domNode, 'disabled');
this.inputBox.disable();
this.regex.disable();
this.wholeWords.disable();
this.caseSensitive.disable();
}
public setFocusInputOnOptionClick(value: boolean): void {
this.fixFocusOnOptionClickEnabled = value;
}
public setEnabled(enabled: boolean): void {
if (enabled) {
this.enable();
} else {
this.disable();
}
}
public clear(): void {
this.clearValidation();
this.setValue('');
this.focus();
}
public setWidth(newWidth: number): void {
this.width = newWidth;
this.domNode.style.width = this.width + 'px';
this.contextViewProvider.layout();
this.setInputWidth();
}
public getValue(): string {
return this.inputBox.value;
}
public setValue(value: string): void {
if (this.inputBox.value !== value) {
this.inputBox.value = value;
}
}
public onSearchSubmit(): void {
this.inputBox.addToHistory();
}
public style(styles: IFindInputStyles): void {
this.inputActiveOptionBorder = styles.inputActiveOptionBorder;
this.inputBackground = styles.inputBackground;
this.inputForeground = styles.inputForeground;
this.inputBorder = styles.inputBorder;
this.inputValidationInfoBackground = styles.inputValidationInfoBackground;
this.inputValidationInfoForeground = styles.inputValidationInfoForeground;
this.inputValidationInfoBorder = styles.inputValidationInfoBorder;
this.inputValidationWarningBackground = styles.inputValidationWarningBackground;
this.inputValidationWarningForeground = styles.inputValidationWarningForeground;
this.inputValidationWarningBorder = styles.inputValidationWarningBorder;
this.inputValidationErrorBackground = styles.inputValidationErrorBackground;
this.inputValidationErrorForeground = styles.inputValidationErrorForeground;
this.inputValidationErrorBorder = styles.inputValidationErrorBorder;
this.applyStyles();
}
protected applyStyles(): void {
if (this.domNode) {
const checkBoxStyles: ICheckboxStyles = {
inputActiveOptionBorder: this.inputActiveOptionBorder,
};
this.regex.style(checkBoxStyles);
this.wholeWords.style(checkBoxStyles);
this.caseSensitive.style(checkBoxStyles);
const inputBoxStyles: IInputBoxStyles = {
inputBackground: this.inputBackground,
inputForeground: this.inputForeground,
inputBorder: this.inputBorder,
inputValidationInfoBackground: this.inputValidationInfoBackground,
inputValidationInfoForeground: this.inputValidationInfoForeground,
inputValidationInfoBorder: this.inputValidationInfoBorder,
inputValidationWarningBackground: this.inputValidationWarningBackground,
inputValidationWarningForeground: this.inputValidationWarningForeground,
inputValidationWarningBorder: this.inputValidationWarningBorder,
inputValidationErrorBackground: this.inputValidationErrorBackground,
inputValidationErrorForeground: this.inputValidationErrorForeground,
inputValidationErrorBorder: this.inputValidationErrorBorder
};
this.inputBox.style(inputBoxStyles);
}
}
public select(): void {
this.inputBox.select();
}
public focus(): void {
this.inputBox.focus();
}
public getCaseSensitive(): boolean {
return this.caseSensitive.checked;
}
public setCaseSensitive(value: boolean): void {
this.caseSensitive.checked = value;
this.setInputWidth();
}
public getWholeWords(): boolean {
return this.wholeWords.checked;
}
public setWholeWords(value: boolean): void {
this.wholeWords.checked = value;
this.setInputWidth();
}
public getRegex(): boolean {
return this.regex.checked;
}
public setRegex(value: boolean): void {
this.regex.checked = value;
this.setInputWidth();
this.validate();
}
public focusOnCaseSensitive(): void {
this.caseSensitive.focus();
}
public focusOnRegex(): void {
this.regex.focus();
}
private _lastHighlightFindOptions: number = 0;
public highlightFindOptions(): void {
dom.removeClass(this.domNode, 'highlight-' + (this._lastHighlightFindOptions));
this._lastHighlightFindOptions = 1 - this._lastHighlightFindOptions;
dom.addClass(this.domNode, 'highlight-' + (this._lastHighlightFindOptions));
}
private setInputWidth(): void {
let w = this.width - this.caseSensitive.width() - this.wholeWords.width() - this.regex.width();
this.inputBox.width = w;
this.inputBox.layout();
}
private buildDomNode(appendCaseSensitiveLabel: string, appendWholeWordsLabel: string, appendRegexLabel: string, history: string[], flexibleHeight: boolean): void {
this.domNode = document.createElement('div');
this.domNode.style.width = this.width + 'px';
dom.addClass(this.domNode, 'monaco-findInput');
this.inputBox = this._register(new HistoryInputBox(this.domNode, this.contextViewProvider, {
placeholder: this.placeholder || '',
ariaLabel: this.label || '',
validationOptions: {
validation: this.validation
},
inputBackground: this.inputBackground,
inputForeground: this.inputForeground,
inputBorder: this.inputBorder,
inputValidationInfoBackground: this.inputValidationInfoBackground,
inputValidationInfoForeground: this.inputValidationInfoForeground,
inputValidationInfoBorder: this.inputValidationInfoBorder,
inputValidationWarningBackground: this.inputValidationWarningBackground,
inputValidationWarningForeground: this.inputValidationWarningForeground,
inputValidationWarningBorder: this.inputValidationWarningBorder,
inputValidationErrorBackground: this.inputValidationErrorBackground,
inputValidationErrorForeground: this.inputValidationErrorForeground,
inputValidationErrorBorder: this.inputValidationErrorBorder,
history,
flexibleHeight
}));
this.regex = this._register(new RegexCheckbox({
appendTitle: appendRegexLabel,
isChecked: false,
inputActiveOptionBorder: this.inputActiveOptionBorder
}));
this._register(this.regex.onChange(viaKeyboard => {
this._onDidOptionChange.fire(viaKeyboard);
if (!viaKeyboard && this.fixFocusOnOptionClickEnabled) {
this.inputBox.focus();
}
this.setInputWidth();
this.validate();
}));
this._register(this.regex.onKeyDown(e => {
this._onRegexKeyDown.fire(e);
}));
this.wholeWords = this._register(new WholeWordsCheckbox({
appendTitle: appendWholeWordsLabel,
isChecked: false,
inputActiveOptionBorder: this.inputActiveOptionBorder
}));
this._register(this.wholeWords.onChange(viaKeyboard => {
this._onDidOptionChange.fire(viaKeyboard);
if (!viaKeyboard && this.fixFocusOnOptionClickEnabled) {
this.inputBox.focus();
}
this.setInputWidth();
this.validate();
}));
this.caseSensitive = this._register(new CaseSensitiveCheckbox({
appendTitle: appendCaseSensitiveLabel,
isChecked: false,
inputActiveOptionBorder: this.inputActiveOptionBorder
}));
this._register(this.caseSensitive.onChange(viaKeyboard => {
this._onDidOptionChange.fire(viaKeyboard);
if (!viaKeyboard && this.fixFocusOnOptionClickEnabled) {
this.inputBox.focus();
}
this.setInputWidth();
this.validate();
}));
this._register(this.caseSensitive.onKeyDown(e => {
this._onCaseSensitiveKeyDown.fire(e);
}));
if (this._showOptionButtons) {
this.inputBox.inputElement.style.paddingRight = (this.caseSensitive.width() + this.wholeWords.width() + this.regex.width()) + 'px';
}
// Arrow-Key support to navigate between options
let indexes = [this.caseSensitive.domNode, this.wholeWords.domNode, this.regex.domNode];
this.onkeydown(this.domNode, (event: IKeyboardEvent) => {
if (event.equals(KeyCode.LeftArrow) || event.equals(KeyCode.RightArrow) || event.equals(KeyCode.Escape)) {
let index = indexes.indexOf(<HTMLElement>document.activeElement);
if (index >= 0) {
let newIndex: number = -1;
if (event.equals(KeyCode.RightArrow)) {
newIndex = (index + 1) % indexes.length;
} else if (event.equals(KeyCode.LeftArrow)) {
if (index === 0) {
newIndex = indexes.length - 1;
} else {
newIndex = index - 1;
}
}
if (event.equals(KeyCode.Escape)) {
indexes[index].blur();
} else if (newIndex >= 0) {
indexes[newIndex].focus();
}
dom.EventHelper.stop(event, true);
}
}
});
this.setInputWidth();
let controls = document.createElement('div');
controls.className = 'controls';
controls.style.display = this._showOptionButtons ? 'block' : 'none';
controls.appendChild(this.caseSensitive.domNode);
controls.appendChild(this.wholeWords.domNode);
controls.appendChild(this.regex.domNode);
this.domNode.appendChild(controls);
}
public validate(): void {
if (this.inputBox) {
this.inputBox.validate();
}
}
public showMessage(message: InputBoxMessage): void {
if (this.inputBox) {
this.inputBox.showMessage(message);
}
}
public clearMessage(): void {
if (this.inputBox) {
this.inputBox.hideMessage();
}
}
private clearValidation(): void {
if (this.inputBox) {
this.inputBox.hideMessage();
}
}
public dispose(): void {
super.dispose();
}
}
| src/vs/base/browser/ui/findinput/findInput.ts | 1 | https://github.com/microsoft/vscode/commit/bbff11633c7e56e7fd5d16cc20daa9a3284afbfe | [
0.9984567165374756,
0.0482565313577652,
0.0001622604177100584,
0.00021436664974316955,
0.20727664232254028
]
|
{
"id": 12,
"code_window": [
"\t\t\t}\n",
"\t\t});\n",
"\n",
"\t\tthis.setInputWidth();\n",
"\n",
"\t\tlet controls = document.createElement('div');\n",
"\t\tcontrols.className = 'controls';\n",
"\t\tcontrols.style.display = this._showOptionButtons ? 'block' : 'none';\n",
"\t\tcontrols.appendChild(this.caseSensitive.domNode);\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/base/browser/ui/findinput/findInput.ts",
"type": "replace",
"edit_start_line_idx": 392
} | {
"information_for_contributors": [
"This file has been converted from https://github.com/Microsoft/vscode-JSON.tmLanguage/blob/master/JSON.tmLanguage",
"If you want to provide a fix or improvement, please create a pull request against the original repository.",
"Once accepted there, we are happy to receive an update request."
],
"version": "https://github.com/Microsoft/vscode-JSON.tmLanguage/commit/9bd83f1c252b375e957203f21793316203f61f70",
"name": "JSON (Javascript Next)",
"scopeName": "source.json",
"patterns": [
{
"include": "#value"
}
],
"repository": {
"array": {
"begin": "\\[",
"beginCaptures": {
"0": {
"name": "punctuation.definition.array.begin.json"
}
},
"end": "\\]",
"endCaptures": {
"0": {
"name": "punctuation.definition.array.end.json"
}
},
"name": "meta.structure.array.json",
"patterns": [
{
"include": "#value"
},
{
"match": ",",
"name": "punctuation.separator.array.json"
},
{
"match": "[^\\s\\]]",
"name": "invalid.illegal.expected-array-separator.json"
}
]
},
"comments": {
"patterns": [
{
"begin": "/\\*\\*(?!/)",
"captures": {
"0": {
"name": "punctuation.definition.comment.json"
}
},
"end": "\\*/",
"name": "comment.block.documentation.json"
},
{
"begin": "/\\*",
"captures": {
"0": {
"name": "punctuation.definition.comment.json"
}
},
"end": "\\*/",
"name": "comment.block.json"
},
{
"captures": {
"1": {
"name": "punctuation.definition.comment.json"
}
},
"match": "(//).*$\\n?",
"name": "comment.line.double-slash.js"
}
]
},
"constant": {
"match": "\\b(?:true|false|null)\\b",
"name": "constant.language.json"
},
"number": {
"match": "(?x) # turn on extended mode\n -? # an optional minus\n (?:\n 0 # a zero\n | # ...or...\n [1-9] # a 1-9 character\n \\d* # followed by zero or more digits\n )\n (?:\n (?:\n \\. # a period\n \\d+ # followed by one or more digits\n )?\n (?:\n [eE] # an e character\n [+-]? # followed by an option +/-\n \\d+ # followed by one or more digits\n )? # make exponent optional\n )? # make decimal portion optional",
"name": "constant.numeric.json"
},
"object": {
"begin": "\\{",
"beginCaptures": {
"0": {
"name": "punctuation.definition.dictionary.begin.json"
}
},
"end": "\\}",
"endCaptures": {
"0": {
"name": "punctuation.definition.dictionary.end.json"
}
},
"name": "meta.structure.dictionary.json",
"patterns": [
{
"comment": "the JSON object key",
"include": "#objectkey"
},
{
"include": "#comments"
},
{
"begin": ":",
"beginCaptures": {
"0": {
"name": "punctuation.separator.dictionary.key-value.json"
}
},
"end": "(,)|(?=\\})",
"endCaptures": {
"1": {
"name": "punctuation.separator.dictionary.pair.json"
}
},
"name": "meta.structure.dictionary.value.json",
"patterns": [
{
"comment": "the JSON object value",
"include": "#value"
},
{
"match": "[^\\s,]",
"name": "invalid.illegal.expected-dictionary-separator.json"
}
]
},
{
"match": "[^\\s\\}]",
"name": "invalid.illegal.expected-dictionary-separator.json"
}
]
},
"string": {
"begin": "\"",
"beginCaptures": {
"0": {
"name": "punctuation.definition.string.begin.json"
}
},
"end": "\"",
"endCaptures": {
"0": {
"name": "punctuation.definition.string.end.json"
}
},
"name": "string.quoted.double.json",
"patterns": [
{
"include": "#stringcontent"
}
]
},
"objectkey": {
"begin": "\"",
"beginCaptures": {
"0": {
"name": "punctuation.support.type.property-name.begin.json"
}
},
"end": "\"",
"endCaptures": {
"0": {
"name": "punctuation.support.type.property-name.end.json"
}
},
"name": "string.json support.type.property-name.json",
"patterns": [
{
"include": "#stringcontent"
}
]
},
"stringcontent": {
"patterns": [
{
"match": "(?x) # turn on extended mode\n \\\\ # a literal backslash\n (?: # ...followed by...\n [\"\\\\/bfnrt] # one of these characters\n | # ...or...\n u # a u\n [0-9a-fA-F]{4}) # and four hex digits",
"name": "constant.character.escape.json"
},
{
"match": "\\\\.",
"name": "invalid.illegal.unrecognized-string-escape.json"
}
]
},
"value": {
"patterns": [
{
"include": "#constant"
},
{
"include": "#number"
},
{
"include": "#string"
},
{
"include": "#array"
},
{
"include": "#object"
},
{
"include": "#comments"
}
]
}
}
} | extensions/json/syntaxes/JSON.tmLanguage.json | 0 | https://github.com/microsoft/vscode/commit/bbff11633c7e56e7fd5d16cc20daa9a3284afbfe | [
0.00017506687436252832,
0.00017341622151434422,
0.00016937407781369984,
0.00017371238209307194,
0.0000013360721595745417
]
|
{
"id": 12,
"code_window": [
"\t\t\t}\n",
"\t\t});\n",
"\n",
"\t\tthis.setInputWidth();\n",
"\n",
"\t\tlet controls = document.createElement('div');\n",
"\t\tcontrols.className = 'controls';\n",
"\t\tcontrols.style.display = this._showOptionButtons ? 'block' : 'none';\n",
"\t\tcontrols.appendChild(this.caseSensitive.domNode);\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/base/browser/ui/findinput/findInput.ts",
"type": "replace",
"edit_start_line_idx": 392
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Event, Emitter } from 'vs/base/common/event';
import { timeout } from 'vs/base/common/async';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { ILifecycleService } from 'vs/platform/lifecycle/electron-main/lifecycleMain';
import product from 'vs/platform/node/product';
import { IUpdateService, State, StateType, AvailableForDownload, UpdateType } from 'vs/platform/update/common/update';
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
import { ILogService } from 'vs/platform/log/common/log';
import { IRequestService } from 'vs/platform/request/node/request';
import { CancellationToken } from 'vs/base/common/cancellation';
export function createUpdateURL(platform: string, quality: string): string {
return `${product.updateUrl}/api/update/${platform}/${quality}/${product.commit}`;
}
export abstract class AbstractUpdateService implements IUpdateService {
_serviceBrand: any;
protected readonly url: string | undefined;
private _state: State = State.Uninitialized;
private _onStateChange = new Emitter<State>();
get onStateChange(): Event<State> { return this._onStateChange.event; }
get state(): State {
return this._state;
}
protected setState(state: State): void {
this.logService.info('update#setState', state.type);
this._state = state;
this._onStateChange.fire(state);
}
constructor(
@ILifecycleService private readonly lifecycleService: ILifecycleService,
@IConfigurationService protected configurationService: IConfigurationService,
@IEnvironmentService private readonly environmentService: IEnvironmentService,
@IRequestService protected requestService: IRequestService,
@ILogService protected logService: ILogService,
) {
if (this.environmentService.disableUpdates) {
this.logService.info('update#ctor - updates are disabled by the environment');
return;
}
if (!product.updateUrl || !product.commit) {
this.logService.info('update#ctor - updates are disabled as there is no update URL');
return;
}
const updateChannel = this.configurationService.getValue<string>('update.channel');
const quality = this.getProductQuality(updateChannel);
if (!quality) {
this.logService.info('update#ctor - updates are disabled by user preference');
return;
}
this.url = this.buildUpdateFeedUrl(quality);
if (!this.url) {
this.logService.info('update#ctor - updates are disabled as the update URL is badly formed');
return;
}
this.setState(State.Idle(this.getUpdateType()));
if (updateChannel === 'manual') {
this.logService.info('update#ctor - manual checks only; automatic updates are disabled by user preference');
return;
}
// Start checking for updates after 30 seconds
this.scheduleCheckForUpdates(30 * 1000).then(undefined, err => this.logService.error(err));
}
private getProductQuality(updateChannel: string): string | undefined {
return updateChannel === 'none' ? undefined : product.quality;
}
private scheduleCheckForUpdates(delay = 60 * 60 * 1000): Promise<void> {
return timeout(delay)
.then(() => this.checkForUpdates(null))
.then(() => {
// Check again after 1 hour
return this.scheduleCheckForUpdates(60 * 60 * 1000);
});
}
async checkForUpdates(context: any): Promise<void> {
this.logService.trace('update#checkForUpdates, state = ', this.state.type);
if (this.state.type !== StateType.Idle) {
return;
}
this.doCheckForUpdates(context);
}
async downloadUpdate(): Promise<void> {
this.logService.trace('update#downloadUpdate, state = ', this.state.type);
if (this.state.type !== StateType.AvailableForDownload) {
return;
}
await this.doDownloadUpdate(this.state);
}
protected async doDownloadUpdate(state: AvailableForDownload): Promise<void> {
// noop
}
async applyUpdate(): Promise<void> {
this.logService.trace('update#applyUpdate, state = ', this.state.type);
if (this.state.type !== StateType.Downloaded) {
return;
}
await this.doApplyUpdate();
}
protected async doApplyUpdate(): Promise<void> {
// noop
}
quitAndInstall(): Promise<void> {
this.logService.trace('update#quitAndInstall, state = ', this.state.type);
if (this.state.type !== StateType.Ready) {
return Promise.resolve(undefined);
}
this.logService.trace('update#quitAndInstall(): before lifecycle quit()');
this.lifecycleService.quit(true /* from update */).then(vetod => {
this.logService.trace(`update#quitAndInstall(): after lifecycle quit() with veto: ${vetod}`);
if (vetod) {
return;
}
this.logService.trace('update#quitAndInstall(): running raw#quitAndInstall()');
this.doQuitAndInstall();
});
return Promise.resolve(undefined);
}
isLatestVersion(): Promise<boolean | undefined> {
if (!this.url) {
return Promise.resolve(undefined);
}
return this.requestService.request({ url: this.url }, CancellationToken.None).then(context => {
// The update server replies with 204 (No Content) when no
// update is available - that's all we want to know.
if (context.res.statusCode === 204) {
return true;
} else {
return false;
}
});
}
protected getUpdateType(): UpdateType {
return UpdateType.Archive;
}
protected doQuitAndInstall(): void {
// noop
}
protected abstract buildUpdateFeedUrl(quality: string): string | undefined;
protected abstract doCheckForUpdates(context: any): void;
}
| src/vs/platform/update/electron-main/abstractUpdateService.ts | 0 | https://github.com/microsoft/vscode/commit/bbff11633c7e56e7fd5d16cc20daa9a3284afbfe | [
0.0001760877639753744,
0.00017224760085809976,
0.00016399347805418074,
0.00017258520529139787,
0.0000029534332952607656
]
|
{
"id": 12,
"code_window": [
"\t\t\t}\n",
"\t\t});\n",
"\n",
"\t\tthis.setInputWidth();\n",
"\n",
"\t\tlet controls = document.createElement('div');\n",
"\t\tcontrols.className = 'controls';\n",
"\t\tcontrols.style.display = this._showOptionButtons ? 'block' : 'none';\n",
"\t\tcontrols.appendChild(this.caseSensitive.domNode);\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/base/browser/ui/findinput/findInput.ts",
"type": "replace",
"edit_start_line_idx": 392
} | <svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="575" height="6px">
<style>
circle {
animation: ball 2.5s cubic-bezier(0.000, 1.000, 1.000, 0.000) infinite;
fill: #bbb;
}
#balls {
animation: balls 2.5s linear infinite;
}
#circle2 { animation-delay: 0.1s; }
#circle3 { animation-delay: 0.2s; }
#circle4 { animation-delay: 0.3s; }
#circle5 { animation-delay: 0.4s; }
@keyframes ball {
from { transform: none; }
20% { transform: none; }
80% { transform: translateX(864px); }
to { transform: translateX(864px); }
}
@keyframes balls {
from { transform: translateX(-40px); }
to { transform: translateX(30px); }
}
</style>
<g id="balls">
<circle class="circle" id="circle1" cx="-115" cy="3" r="3"/>
<circle class="circle" id="circle2" cx="-130" cy="3" r="3" />
<circle class="circle" id="circle3" cx="-145" cy="3" r="3" />
<circle class="circle" id="circle4" cx="-160" cy="3" r="3" />
<circle class="circle" id="circle5" cx="-175" cy="3" r="3" />
</g>
</svg> | src/vs/workbench/contrib/extensions/electron-browser/media/loading.svg | 0 | https://github.com/microsoft/vscode/commit/bbff11633c7e56e7fd5d16cc20daa9a3284afbfe | [
0.00017891652532853186,
0.0001749780058162287,
0.00017147274047601968,
0.000174761371454224,
0.0000027073019737144932
]
|
{
"id": 13,
"code_window": [
"\n",
".search-view .search-widget .monaco-findInput {\n",
"\tdisplay: inline-block;\n",
"\tvertical-align: middle;\n",
"}\n",
"\n",
".search-view .search-widget .replace-container {\n",
"\tmargin-top: 6px;\n",
"\tposition: relative;\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\twidth: 100%;\n"
],
"file_path": "src/vs/workbench/contrib/search/browser/media/searchview.css",
"type": "add",
"edit_start_line_idx": 53
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
/* ---------- Find input ---------- */
.monaco-findInput {
position: relative;
}
.monaco-findInput .monaco-inputbox {
font-size: 13px;
width: 100%;
}
.monaco-findInput .monaco-inputbox > .wrapper > .input {
width: 100% !important;
}
.monaco-findInput > .controls {
position: absolute;
top: 3px;
right: 2px;
}
.vs .monaco-findInput.disabled {
background-color: #E1E1E1;
}
/* Theming */
.vs-dark .monaco-findInput.disabled {
background-color: #333;
}
/* Highlighting */
.monaco-findInput.highlight-0 .controls {
animation: monaco-findInput-highlight-0 100ms linear 0s;
}
.monaco-findInput.highlight-1 .controls {
animation: monaco-findInput-highlight-1 100ms linear 0s;
}
.hc-black .monaco-findInput.highlight-0 .controls,
.vs-dark .monaco-findInput.highlight-0 .controls {
animation: monaco-findInput-highlight-dark-0 100ms linear 0s;
}
.hc-black .monaco-findInput.highlight-1 .controls,
.vs-dark .monaco-findInput.highlight-1 .controls {
animation: monaco-findInput-highlight-dark-1 100ms linear 0s;
}
@keyframes monaco-findInput-highlight-0 {
0% { background: rgba(253, 255, 0, 0.8); }
100% { background: transparent; }
}
@keyframes monaco-findInput-highlight-1 {
0% { background: rgba(253, 255, 0, 0.8); }
/* Made intentionally different such that the CSS minifier does not collapse the two animations into a single one*/
99% { background: transparent; }
}
@keyframes monaco-findInput-highlight-dark-0 {
0% { background: rgba(255, 255, 255, 0.44); }
100% { background: transparent; }
}
@keyframes monaco-findInput-highlight-dark-1 {
0% { background: rgba(255, 255, 255, 0.44); }
/* Made intentionally different such that the CSS minifier does not collapse the two animations into a single one*/
99% { background: transparent; }
} | src/vs/base/browser/ui/findinput/findInput.css | 1 | https://github.com/microsoft/vscode/commit/bbff11633c7e56e7fd5d16cc20daa9a3284afbfe | [
0.009661328978836536,
0.003816779237240553,
0.00046594691229984164,
0.0029972416814416647,
0.0029505272395908833
]
|
{
"id": 13,
"code_window": [
"\n",
".search-view .search-widget .monaco-findInput {\n",
"\tdisplay: inline-block;\n",
"\tvertical-align: middle;\n",
"}\n",
"\n",
".search-view .search-widget .replace-container {\n",
"\tmargin-top: 6px;\n",
"\tposition: relative;\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\twidth: 100%;\n"
],
"file_path": "src/vs/workbench/contrib/search/browser/media/searchview.css",
"type": "add",
"edit_start_line_idx": 53
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import 'vs/css!./selectBoxCustom';
import { IDisposable, dispose } from 'vs/base/common/lifecycle';
import { Event, Emitter } from 'vs/base/common/event';
import { KeyCode, KeyCodeUtils } from 'vs/base/common/keyCodes';
import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent';
import * as dom from 'vs/base/browser/dom';
import * as arrays from 'vs/base/common/arrays';
import { IContextViewProvider, AnchorPosition } from 'vs/base/browser/ui/contextview/contextview';
import { List } from 'vs/base/browser/ui/list/listWidget';
import { IListVirtualDelegate, IListRenderer, IListEvent } from 'vs/base/browser/ui/list/list';
import { domEvent } from 'vs/base/browser/event';
import { ScrollbarVisibility } from 'vs/base/common/scrollable';
import { ISelectBoxDelegate, ISelectOptionItem, ISelectBoxOptions, ISelectBoxStyles, ISelectData } from 'vs/base/browser/ui/selectBox/selectBox';
import { isMacintosh } from 'vs/base/common/platform';
import { renderMarkdown } from 'vs/base/browser/htmlContentRenderer';
const $ = dom.$;
const SELECT_OPTION_ENTRY_TEMPLATE_ID = 'selectOption.entry.template';
interface ISelectListTemplateData {
root: HTMLElement;
text: HTMLElement;
itemDescription: HTMLElement;
decoratorRight: HTMLElement;
disposables: IDisposable[];
}
class SelectListRenderer implements IListRenderer<ISelectOptionItem, ISelectListTemplateData> {
get templateId(): string { return SELECT_OPTION_ENTRY_TEMPLATE_ID; }
constructor() { }
renderTemplate(container: HTMLElement): any {
const data = <ISelectListTemplateData>Object.create(null);
data.disposables = [];
data.root = container;
data.text = dom.append(container, $('.option-text'));
data.decoratorRight = dom.append(container, $('.option-decorator-right'));
data.itemDescription = dom.append(container, $('.option-text-description'));
dom.addClass(data.itemDescription, 'visually-hidden');
return data;
}
renderElement(element: ISelectOptionItem, index: number, templateData: ISelectListTemplateData): void {
const data = <ISelectListTemplateData>templateData;
const text = (<ISelectOptionItem>element).text;
const decoratorRight = (<ISelectOptionItem>element).decoratorRight;
const isDisabled = (<ISelectOptionItem>element).isDisabled;
data.text.textContent = text;
data.decoratorRight.innerText = (!!decoratorRight ? decoratorRight : '');
if (typeof element.description === 'string') {
const itemDescriptionId = (text.replace(/ /g, '_').toLowerCase() + '_description_' + data.root.id);
data.text.setAttribute('aria-describedby', itemDescriptionId);
data.itemDescription.id = itemDescriptionId;
data.itemDescription.innerText = element.description;
}
// pseudo-select disabled option
if (isDisabled) {
dom.addClass((<HTMLElement>data.root), 'option-disabled');
} else {
// Make sure we do class removal from prior template rendering
dom.removeClass((<HTMLElement>data.root), 'option-disabled');
}
}
disposeTemplate(templateData: ISelectListTemplateData): void {
templateData.disposables = dispose(templateData.disposables);
}
}
export class SelectBoxList implements ISelectBoxDelegate, IListVirtualDelegate<ISelectOptionItem> {
private static readonly DEFAULT_DROPDOWN_MINIMUM_BOTTOM_MARGIN = 32;
private static readonly DEFAULT_DROPDOWN_MINIMUM_TOP_MARGIN = 2;
private static readonly DEFAULT_MINIMUM_VISIBLE_OPTIONS = 3;
private _isVisible: boolean;
private selectBoxOptions: ISelectBoxOptions;
private selectElement: HTMLSelectElement;
private options: ISelectOptionItem[];
private selected: number;
private readonly _onDidSelect: Emitter<ISelectData>;
private toDispose: IDisposable[];
private styles: ISelectBoxStyles;
private listRenderer: SelectListRenderer;
private contextViewProvider: IContextViewProvider;
private selectDropDownContainer: HTMLElement;
private styleElement: HTMLStyleElement;
private selectList: List<ISelectOptionItem>;
private selectDropDownListContainer: HTMLElement;
private widthControlElement: HTMLElement;
private _currentSelection: number;
private _dropDownPosition: AnchorPosition;
private _hasDetails: boolean = false;
private selectionDetailsPane: HTMLElement;
private _skipLayout: boolean = false;
private _sticky: boolean = false; // for dev purposes only
constructor(options: ISelectOptionItem[], selected: number, contextViewProvider: IContextViewProvider, styles: ISelectBoxStyles, selectBoxOptions?: ISelectBoxOptions) {
this.toDispose = [];
this._isVisible = false;
this.selectBoxOptions = selectBoxOptions || Object.create(null);
if (typeof this.selectBoxOptions.minBottomMargin !== 'number') {
this.selectBoxOptions.minBottomMargin = SelectBoxList.DEFAULT_DROPDOWN_MINIMUM_BOTTOM_MARGIN;
} else if (this.selectBoxOptions.minBottomMargin < 0) {
this.selectBoxOptions.minBottomMargin = 0;
}
this.selectElement = document.createElement('select');
// Workaround for Electron 2.x
// Native select should not require explicit role attribute, however, Electron 2.x
// incorrectly exposes select as menuItem which interferes with labeling and results
// in the unlabeled not been read. Electron 3 appears to fix.
this.selectElement.setAttribute('role', 'combobox');
// Use custom CSS vars for padding calculation
this.selectElement.className = 'monaco-select-box monaco-select-box-dropdown-padding';
if (typeof this.selectBoxOptions.ariaLabel === 'string') {
this.selectElement.setAttribute('aria-label', this.selectBoxOptions.ariaLabel);
}
this._onDidSelect = new Emitter<ISelectData>();
this.toDispose.push(this._onDidSelect);
this.styles = styles;
this.registerListeners();
this.constructSelectDropDown(contextViewProvider);
this.selected = selected || 0;
if (options) {
this.setOptions(options, selected);
}
}
// IDelegate - List renderer
getHeight(): number {
return 18;
}
getTemplateId(): string {
return SELECT_OPTION_ENTRY_TEMPLATE_ID;
}
private constructSelectDropDown(contextViewProvider: IContextViewProvider) {
// SetUp ContextView container to hold select Dropdown
this.contextViewProvider = contextViewProvider;
this.selectDropDownContainer = dom.$('.monaco-select-box-dropdown-container');
// Use custom CSS vars for padding calculation (shared with parent select)
dom.addClass(this.selectDropDownContainer, 'monaco-select-box-dropdown-padding');
// Setup container for select option details
this.selectionDetailsPane = dom.append(this.selectDropDownContainer, $('.select-box-details-pane'));
// Create span flex box item/div we can measure and control
let widthControlOuterDiv = dom.append(this.selectDropDownContainer, $('.select-box-dropdown-container-width-control'));
let widthControlInnerDiv = dom.append(widthControlOuterDiv, $('.width-control-div'));
this.widthControlElement = document.createElement('span');
this.widthControlElement.className = 'option-text-width-control';
dom.append(widthControlInnerDiv, this.widthControlElement);
// Always default to below position
this._dropDownPosition = AnchorPosition.BELOW;
// Inline stylesheet for themes
this.styleElement = dom.createStyleSheet(this.selectDropDownContainer);
}
private registerListeners() {
// Parent native select keyboard listeners
this.toDispose.push(dom.addStandardDisposableListener(this.selectElement, 'change', (e) => {
this.selected = e.target.selectedIndex;
this._onDidSelect.fire({
index: e.target.selectedIndex,
selected: e.target.value
});
}));
// Have to implement both keyboard and mouse controllers to handle disabled options
// Intercept mouse events to override normal select actions on parents
this.toDispose.push(dom.addDisposableListener(this.selectElement, dom.EventType.CLICK, (e) => {
dom.EventHelper.stop(e);
if (this._isVisible) {
this.hideSelectDropDown(true);
} else {
this.showSelectDropDown();
}
}));
this.toDispose.push(dom.addDisposableListener(this.selectElement, dom.EventType.MOUSE_DOWN, (e) => {
dom.EventHelper.stop(e);
}));
// Intercept keyboard handling
this.toDispose.push(dom.addDisposableListener(this.selectElement, dom.EventType.KEY_DOWN, (e: KeyboardEvent) => {
const event = new StandardKeyboardEvent(e);
let showDropDown = false;
// Create and drop down select list on keyboard select
if (isMacintosh) {
if (event.keyCode === KeyCode.DownArrow || event.keyCode === KeyCode.UpArrow || event.keyCode === KeyCode.Space || event.keyCode === KeyCode.Enter) {
showDropDown = true;
}
} else {
if (event.keyCode === KeyCode.DownArrow && event.altKey || event.keyCode === KeyCode.UpArrow && event.altKey || event.keyCode === KeyCode.Space || event.keyCode === KeyCode.Enter) {
showDropDown = true;
}
}
if (showDropDown) {
this.showSelectDropDown();
dom.EventHelper.stop(e);
}
}));
}
public get onDidSelect(): Event<ISelectData> {
return this._onDidSelect.event;
}
public setOptions(options: ISelectOptionItem[], selected?: number): void {
if (!this.options || !arrays.equals(this.options, options)) {
this.options = options;
this.selectElement.options.length = 0;
this._hasDetails = false;
this.options.forEach((option, index) => {
this.selectElement.add(this.createOption(option.text, index, option.isDisabled));
if (typeof option.description === 'string') {
this._hasDetails = true;
}
});
}
if (selected !== undefined) {
this.select(selected);
// Set current = selected since this is not necessarily a user exit
this._currentSelection = this.selected;
}
}
private setOptionsList() {
// Mirror options in drop-down
// Populate select list for non-native select mode
if (this.selectList && !!this.options) {
this.selectList.splice(0, this.selectList.length, this.options);
}
}
public select(index: number): void {
if (index >= 0 && index < this.options.length) {
this.selected = index;
} else if (index > this.options.length - 1) {
// Adjust index to end of list
// This could make client out of sync with the select
this.select(this.options.length - 1);
} else if (this.selected < 0) {
this.selected = 0;
}
this.selectElement.selectedIndex = this.selected;
}
public setAriaLabel(label: string): void {
this.selectBoxOptions.ariaLabel = label;
this.selectElement.setAttribute('aria-label', this.selectBoxOptions.ariaLabel);
}
public focus(): void {
if (this.selectElement) {
this.selectElement.focus();
}
}
public blur(): void {
if (this.selectElement) {
this.selectElement.blur();
}
}
public render(container: HTMLElement): void {
dom.addClass(container, 'select-container');
container.appendChild(this.selectElement);
this.applyStyles();
}
public style(styles: ISelectBoxStyles): void {
const content: string[] = [];
this.styles = styles;
// Style non-native select mode
if (this.styles.listFocusBackground) {
content.push(`.monaco-select-box-dropdown-container > .select-box-dropdown-list-container .monaco-list .monaco-list-row.focused { background-color: ${this.styles.listFocusBackground} !important; }`);
}
if (this.styles.listFocusForeground) {
content.push(`.monaco-select-box-dropdown-container > .select-box-dropdown-list-container .monaco-list .monaco-list-row.focused:not(:hover) { color: ${this.styles.listFocusForeground} !important; }`);
}
if (this.styles.decoratorRightForeground) {
content.push(`.monaco-select-box-dropdown-container > .select-box-dropdown-list-container .monaco-list .monaco-list-row .option-decorator-right { color: ${this.styles.decoratorRightForeground} !important; }`);
}
if (this.styles.selectBackground && this.styles.selectBorder && !this.styles.selectBorder.equals(this.styles.selectBackground)) {
content.push(`.monaco-select-box-dropdown-container { border: 1px solid ${this.styles.selectBorder} } `);
content.push(`.monaco-select-box-dropdown-container > .select-box-details-pane.border-top { border-top: 1px solid ${this.styles.selectBorder} } `);
content.push(`.monaco-select-box-dropdown-container > .select-box-details-pane.border-bottom { border-bottom: 1px solid ${this.styles.selectBorder} } `);
}
else if (this.styles.selectListBorder) {
content.push(`.monaco-select-box-dropdown-container > .select-box-details-pane.border-top { border-top: 1px solid ${this.styles.selectListBorder} } `);
content.push(`.monaco-select-box-dropdown-container > .select-box-details-pane.border-bottom { border-bottom: 1px solid ${this.styles.selectListBorder} } `);
}
// Hover foreground - ignore for disabled options
if (this.styles.listHoverForeground) {
content.push(`.monaco-select-box-dropdown-container > .select-box-dropdown-list-container .monaco-list .monaco-list-row:hover { color: ${this.styles.listHoverForeground} !important; }`);
content.push(`.monaco-select-box-dropdown-container > .select-box-dropdown-list-container .monaco-list .monaco-list-row.option-disabled:hover { background-color: ${this.styles.listActiveSelectionForeground} !important; }`);
}
// Hover background - ignore for disabled options
if (this.styles.listHoverBackground) {
content.push(`.monaco-select-box-dropdown-container > .select-box-dropdown-list-container .monaco-list .monaco-list-row:not(.option-disabled):not(.focused):hover { background-color: ${this.styles.listHoverBackground} !important; }`);
content.push(`.monaco-select-box-dropdown-container > .select-box-dropdown-list-container .monaco-list .monaco-list-row.option-disabled:hover { background-color: ${this.styles.selectBackground} !important; }`);
}
// Match quickOpen outline styles - ignore for disabled options
if (this.styles.listFocusOutline) {
content.push(`.monaco-select-box-dropdown-container > .select-box-dropdown-list-container .monaco-list .monaco-list-row.focused { outline: 1.6px dotted ${this.styles.listFocusOutline} !important; outline-offset: -1.6px !important; }`);
}
if (this.styles.listHoverOutline) {
content.push(`.monaco-select-box-dropdown-container > .select-box-dropdown-list-container .monaco-list .monaco-list-row:hover:not(.focused) { outline: 1.6px dashed ${this.styles.listHoverOutline} !important; outline-offset: -1.6px !important; }`);
content.push(`.monaco-select-box-dropdown-container > .select-box-dropdown-list-container .monaco-list .monaco-list-row.option-disabled:hover { outline: none !important; }`);
}
this.styleElement.innerHTML = content.join('\n');
this.applyStyles();
}
public applyStyles(): void {
// Style parent select
if (this.selectElement) {
const background = this.styles.selectBackground ? this.styles.selectBackground.toString() : null;
const foreground = this.styles.selectForeground ? this.styles.selectForeground.toString() : null;
const border = this.styles.selectBorder ? this.styles.selectBorder.toString() : null;
this.selectElement.style.backgroundColor = background;
this.selectElement.style.color = foreground;
this.selectElement.style.borderColor = border;
}
// Style drop down select list (non-native mode only)
if (this.selectList) {
this.styleList();
}
}
private styleList() {
if (this.selectList) {
let background = this.styles.selectBackground ? this.styles.selectBackground.toString() : null;
this.selectList.style({});
let listBackground = this.styles.selectListBackground ? this.styles.selectListBackground.toString() : background;
this.selectDropDownListContainer.style.backgroundColor = listBackground;
this.selectionDetailsPane.style.backgroundColor = listBackground;
const optionsBorder = this.styles.focusBorder ? this.styles.focusBorder.toString() : null;
this.selectDropDownContainer.style.outlineColor = optionsBorder;
this.selectDropDownContainer.style.outlineOffset = '-1px';
}
}
private createOption(value: string, index: number, disabled?: boolean): HTMLOptionElement {
let option = document.createElement('option');
option.value = value;
option.text = value;
option.disabled = !!disabled;
return option;
}
// ContextView dropdown methods
private showSelectDropDown() {
if (!this.contextViewProvider || this._isVisible) {
return;
}
// Lazily create and populate list only at open, moved from constructor
this.createSelectList(this.selectDropDownContainer);
this.setOptionsList();
// This allows us to flip the position based on measurement
// Set drop-down position above/below from required height and margins
// If pre-layout cannot fit at least one option do not show drop-down
this.contextViewProvider.showContextView({
getAnchor: () => this.selectElement,
render: (container: HTMLElement) => this.renderSelectDropDown(container, true),
layout: () => {
this.layoutSelectDropDown();
},
onHide: () => {
dom.toggleClass(this.selectDropDownContainer, 'visible', false);
dom.toggleClass(this.selectElement, 'synthetic-focus', false);
},
anchorPosition: this._dropDownPosition
});
// Hide so we can relay out
this._isVisible = true;
this.hideSelectDropDown(false);
this.contextViewProvider.showContextView({
getAnchor: () => this.selectElement,
render: (container: HTMLElement) => this.renderSelectDropDown(container),
layout: () => this.layoutSelectDropDown(),
onHide: () => {
dom.toggleClass(this.selectDropDownContainer, 'visible', false);
dom.toggleClass(this.selectElement, 'synthetic-focus', false);
},
anchorPosition: this._dropDownPosition
});
// Track initial selection the case user escape, blur
this._currentSelection = this.selected;
this._isVisible = true;
}
private hideSelectDropDown(focusSelect: boolean) {
if (!this.contextViewProvider || !this._isVisible) {
return;
}
this._isVisible = false;
if (focusSelect) {
this.selectElement.focus();
}
this.contextViewProvider.hideContextView();
}
private renderSelectDropDown(container: HTMLElement, preLayoutPosition?: boolean): IDisposable {
container.appendChild(this.selectDropDownContainer);
// Pre-Layout allows us to change position
this.layoutSelectDropDown(preLayoutPosition);
return {
dispose: () => {
// contextView will dispose itself if moving from one View to another
try {
container.removeChild(this.selectDropDownContainer); // remove to take out the CSS rules we add
}
catch (error) {
// Ignore, removed already by change of focus
}
}
};
}
// Iterate over detailed descriptions, find max height
private measureMaxDetailsHeight(): number {
let maxDetailsPaneHeight = 0;
this.options.forEach((option, index) => {
this.selectionDetailsPane.innerText = '';
if (option.description) {
if (option.descriptionIsMarkdown) {
this.selectionDetailsPane.appendChild(this.renderDescriptionMarkdown(option.description));
} else {
this.selectionDetailsPane.innerText = option.description;
}
this.selectionDetailsPane.style.display = 'block';
} else {
this.selectionDetailsPane.style.display = 'none';
}
if (this.selectionDetailsPane.offsetHeight > maxDetailsPaneHeight) {
maxDetailsPaneHeight = this.selectionDetailsPane.offsetHeight;
}
});
// Reset description to selected
this.selectionDetailsPane.innerText = '';
const description = this.options[this.selected].description || null;
const descriptionIsMarkdown = this.options[this.selected].descriptionIsMarkdown || null;
if (description) {
if (descriptionIsMarkdown) {
this.selectionDetailsPane.appendChild(this.renderDescriptionMarkdown(description));
} else {
this.selectionDetailsPane.innerText = description;
}
this.selectionDetailsPane.style.display = 'block';
}
return maxDetailsPaneHeight;
}
private layoutSelectDropDown(preLayoutPosition?: boolean): boolean {
// Avoid recursion from layout called in onListFocus
if (this._skipLayout) {
return false;
}
// Layout ContextView drop down select list and container
// Have to manage our vertical overflow, sizing, position below or above
// Position has to be determined and set prior to contextView instantiation
if (this.selectList) {
// Make visible to enable measurements
dom.toggleClass(this.selectDropDownContainer, 'visible', true);
const selectPosition = dom.getDomNodePagePosition(this.selectElement);
const styles = getComputedStyle(this.selectElement);
const verticalPadding = parseFloat(styles.getPropertyValue('--dropdown-padding-top')) + parseFloat(styles.getPropertyValue('--dropdown-padding-bottom'));
const maxSelectDropDownHeightBelow = (window.innerHeight - selectPosition.top - selectPosition.height - (this.selectBoxOptions.minBottomMargin || 0));
const maxSelectDropDownHeightAbove = (selectPosition.top - SelectBoxList.DEFAULT_DROPDOWN_MINIMUM_TOP_MARGIN);
// Determine optimal width - min(longest option), opt(parent select, excluding margins), max(ContextView controlled)
const selectWidth = this.selectElement.offsetWidth;
const selectMinWidth = this.setWidthControlElement(this.widthControlElement);
const selectOptimalWidth = Math.max(selectMinWidth, Math.round(selectWidth)).toString() + 'px';
this.selectDropDownContainer.style.width = selectOptimalWidth;
// Get initial list height and determine space ab1you knowove and below
this.selectList.layout();
let listHeight = this.selectList.contentHeight;
const maxDetailsPaneHeight = this._hasDetails ? this.measureMaxDetailsHeight() : 0;
const minRequiredDropDownHeight = listHeight + verticalPadding + maxDetailsPaneHeight;
const maxVisibleOptionsBelow = ((Math.floor((maxSelectDropDownHeightBelow - verticalPadding - maxDetailsPaneHeight) / this.getHeight())));
const maxVisibleOptionsAbove = ((Math.floor((maxSelectDropDownHeightAbove - verticalPadding - maxDetailsPaneHeight) / this.getHeight())));
// If we are only doing pre-layout check/adjust position only
// Calculate vertical space available, flip up if insufficient
// Use reflected padding on parent select, ContextView style
// properties not available before DOM attachment
if (preLayoutPosition) {
// Check if select moved out of viewport , do not open
// If at least one option cannot be shown, don't open the drop-down or hide/remove if open
if ((selectPosition.top + selectPosition.height) > (window.innerHeight - 22)
|| selectPosition.top < SelectBoxList.DEFAULT_DROPDOWN_MINIMUM_TOP_MARGIN
|| ((maxVisibleOptionsBelow < 1) && (maxVisibleOptionsAbove < 1))) {
// Indicate we cannot open
return false;
}
// Determine if we have to flip up
// Always show complete list items - never more than Max available vertical height
if (maxVisibleOptionsBelow < SelectBoxList.DEFAULT_MINIMUM_VISIBLE_OPTIONS
&& maxVisibleOptionsAbove > maxVisibleOptionsBelow
&& this.options.length > maxVisibleOptionsBelow
) {
this._dropDownPosition = AnchorPosition.ABOVE;
this.selectDropDownContainer.removeChild(this.selectDropDownListContainer);
this.selectDropDownContainer.removeChild(this.selectionDetailsPane);
this.selectDropDownContainer.appendChild(this.selectionDetailsPane);
this.selectDropDownContainer.appendChild(this.selectDropDownListContainer);
dom.removeClass(this.selectionDetailsPane, 'border-top');
dom.addClass(this.selectionDetailsPane, 'border-bottom');
} else {
this._dropDownPosition = AnchorPosition.BELOW;
this.selectDropDownContainer.removeChild(this.selectDropDownListContainer);
this.selectDropDownContainer.removeChild(this.selectionDetailsPane);
this.selectDropDownContainer.appendChild(this.selectDropDownListContainer);
this.selectDropDownContainer.appendChild(this.selectionDetailsPane);
dom.removeClass(this.selectionDetailsPane, 'border-bottom');
dom.addClass(this.selectionDetailsPane, 'border-top');
}
// Do full layout on showSelectDropDown only
return true;
}
// Check if select out of viewport or cutting into status bar
if ((selectPosition.top + selectPosition.height) > (window.innerHeight - 22)
|| selectPosition.top < SelectBoxList.DEFAULT_DROPDOWN_MINIMUM_TOP_MARGIN
|| (this._dropDownPosition === AnchorPosition.BELOW && maxVisibleOptionsBelow < 1)
|| (this._dropDownPosition === AnchorPosition.ABOVE && maxVisibleOptionsAbove < 1)) {
// Cannot properly layout, close and hide
this.hideSelectDropDown(true);
return false;
}
// SetUp list dimensions and layout - account for container padding
// Use position to check above or below available space
if (this._dropDownPosition === AnchorPosition.BELOW) {
if (this._isVisible && maxVisibleOptionsBelow + maxVisibleOptionsAbove < 1) {
// If drop-down is visible, must be doing a DOM re-layout, hide since we don't fit
// Hide drop-down, hide contextview, focus on parent select
this.hideSelectDropDown(true);
return false;
}
// Adjust list height to max from select bottom to margin (default/minBottomMargin)
if (minRequiredDropDownHeight > maxSelectDropDownHeightBelow) {
listHeight = (maxVisibleOptionsBelow * this.getHeight());
}
} else {
if (minRequiredDropDownHeight > maxSelectDropDownHeightAbove) {
listHeight = (maxVisibleOptionsAbove * this.getHeight());
}
}
// Set adjusted list height and relayout
this.selectList.layout(listHeight);
this.selectList.domFocus();
// Finally set focus on selected item
if (this.selectList.length > 0) {
this.selectList.setFocus([this.selected || 0]);
this.selectList.reveal(this.selectList.getFocus()[0] || 0);
}
if (this._hasDetails) {
// Leave the selectDropDownContainer to size itself according to children (list + details) - #57447
this.selectList.getHTMLElement().style.height = (listHeight + verticalPadding) + 'px';
} else {
this.selectDropDownContainer.style.height = (listHeight + verticalPadding) + 'px';
}
this.selectDropDownContainer.style.width = selectOptimalWidth;
// Maintain focus outline on parent select as well as list container - tabindex for focus
this.selectDropDownListContainer.setAttribute('tabindex', '0');
dom.toggleClass(this.selectElement, 'synthetic-focus', true);
dom.toggleClass(this.selectDropDownContainer, 'synthetic-focus', true);
return true;
} else {
return false;
}
}
private setWidthControlElement(container: HTMLElement): number {
let elementWidth = 0;
if (container && !!this.options) {
let longest = 0;
let longestLength = 0;
this.options.forEach((option, index) => {
const len = option.text.length + (!!option.decoratorRight ? option.decoratorRight.length : 0);
if (len > longestLength) {
longest = index;
longestLength = len;
}
});
container.innerHTML = this.options[longest].text + (!!this.options[longest].decoratorRight ? (this.options[longest].decoratorRight + ' ') : '');
elementWidth = dom.getTotalWidth(container);
}
return elementWidth;
}
private createSelectList(parent: HTMLElement): void {
// If we have already constructive list on open, skip
if (this.selectList) {
return;
}
// SetUp container for list
this.selectDropDownListContainer = dom.append(parent, $('.select-box-dropdown-list-container'));
this.listRenderer = new SelectListRenderer();
this.selectList = new List(this.selectDropDownListContainer, this, [this.listRenderer], {
ariaLabel: this.selectBoxOptions.ariaLabel,
useShadows: false,
verticalScrollMode: ScrollbarVisibility.Visible,
keyboardSupport: false,
mouseSupport: false
});
// SetUp list keyboard controller - control navigation, disabled items, focus
const onSelectDropDownKeyDown = Event.chain(domEvent(this.selectDropDownListContainer, 'keydown'))
.filter(() => this.selectList.length > 0)
.map(e => new StandardKeyboardEvent(e));
onSelectDropDownKeyDown.filter(e => e.keyCode === KeyCode.Enter).on(e => this.onEnter(e), this, this.toDispose);
onSelectDropDownKeyDown.filter(e => e.keyCode === KeyCode.Escape).on(e => this.onEscape(e), this, this.toDispose);
onSelectDropDownKeyDown.filter(e => e.keyCode === KeyCode.UpArrow).on(this.onUpArrow, this, this.toDispose);
onSelectDropDownKeyDown.filter(e => e.keyCode === KeyCode.DownArrow).on(this.onDownArrow, this, this.toDispose);
onSelectDropDownKeyDown.filter(e => e.keyCode === KeyCode.PageDown).on(this.onPageDown, this, this.toDispose);
onSelectDropDownKeyDown.filter(e => e.keyCode === KeyCode.PageUp).on(this.onPageUp, this, this.toDispose);
onSelectDropDownKeyDown.filter(e => e.keyCode === KeyCode.Home).on(this.onHome, this, this.toDispose);
onSelectDropDownKeyDown.filter(e => e.keyCode === KeyCode.End).on(this.onEnd, this, this.toDispose);
onSelectDropDownKeyDown.filter(e => (e.keyCode >= KeyCode.KEY_0 && e.keyCode <= KeyCode.KEY_Z) || (e.keyCode >= KeyCode.US_SEMICOLON && e.keyCode <= KeyCode.NUMPAD_DIVIDE)).on(this.onCharacter, this, this.toDispose);
// SetUp list mouse controller - control navigation, disabled items, focus
Event.chain(domEvent(this.selectList.getHTMLElement(), 'mouseup'))
.filter(() => this.selectList.length > 0)
.on(e => this.onMouseUp(e), this, this.toDispose);
this.toDispose.push(
this.selectList.onDidBlur(_ => this.onListBlur()),
this.selectList.onMouseOver(e => typeof e.index !== 'undefined' && this.selectList.setFocus([e.index])),
this.selectList.onFocusChange(e => this.onListFocus(e))
);
this.selectList.getHTMLElement().setAttribute('aria-label', this.selectBoxOptions.ariaLabel || '');
this.selectList.getHTMLElement().setAttribute('aria-expanded', 'true');
this.styleList();
}
// List methods
// List mouse controller - active exit, select option, fire onDidSelect if change, return focus to parent select
private onMouseUp(e: MouseEvent): void {
dom.EventHelper.stop(e);
const target = <Element>e.target;
if (!target) {
return;
}
// Check our mouse event is on an option (not scrollbar)
if (!!target.classList.contains('slider')) {
return;
}
const listRowElement = target.closest('.monaco-list-row');
if (!listRowElement) {
return;
}
const index = Number(listRowElement.getAttribute('data-index'));
const disabled = listRowElement.classList.contains('option-disabled');
// Ignore mouse selection of disabled options
if (index >= 0 && index < this.options.length && !disabled) {
this.selected = index;
this.select(this.selected);
this.selectList.setFocus([this.selected]);
this.selectList.reveal(this.selectList.getFocus()[0]);
// Only fire if selection change
if (this.selected !== this._currentSelection) {
// Set current = selected
this._currentSelection = this.selected;
this._onDidSelect.fire({
index: this.selectElement.selectedIndex,
selected: this.options[this.selected].text
});
}
this.hideSelectDropDown(true);
}
}
// List Exit - passive - implicit no selection change, hide drop-down
private onListBlur(): void {
if (this._sticky) { return; }
if (this.selected !== this._currentSelection) {
// Reset selected to current if no change
this.select(this._currentSelection);
}
this.hideSelectDropDown(false);
}
private renderDescriptionMarkdown(text: string): HTMLElement {
const cleanRenderedMarkdown = (element: Node) => {
for (let i = 0; i < element.childNodes.length; i++) {
const child = element.childNodes.item(i);
const tagName = (<Element>child).tagName && (<Element>child).tagName.toLowerCase();
if (tagName === 'img') {
element.removeChild(child);
} else {
cleanRenderedMarkdown(child);
}
}
};
const renderedMarkdown = renderMarkdown({ value: text });
renderedMarkdown.classList.add('select-box-description-markdown');
cleanRenderedMarkdown(renderedMarkdown);
return renderedMarkdown;
}
// List Focus Change - passive - update details pane with newly focused element's data
private onListFocus(e: IListEvent<ISelectOptionItem>) {
// Skip during initial layout
if (!this._isVisible || !this._hasDetails) {
return;
}
this.selectionDetailsPane.innerText = '';
const selectedIndex = e.indexes[0];
const description = this.options[selectedIndex].description || null;
const descriptionIsMarkdown = this.options[selectedIndex].descriptionIsMarkdown || null;
if (description) {
if (descriptionIsMarkdown) {
this.selectionDetailsPane.appendChild(this.renderDescriptionMarkdown(description));
} else {
this.selectionDetailsPane.innerText = description;
}
this.selectionDetailsPane.style.display = 'block';
} else {
this.selectionDetailsPane.style.display = 'none';
}
// Avoid recursion
this._skipLayout = true;
this.contextViewProvider.layout();
this._skipLayout = false;
}
// List keyboard controller
// List exit - active - hide ContextView dropdown, reset selection, return focus to parent select
private onEscape(e: StandardKeyboardEvent): void {
dom.EventHelper.stop(e);
// Reset selection to value when opened
this.select(this._currentSelection);
this.hideSelectDropDown(true);
}
// List exit - active - hide ContextView dropdown, return focus to parent select, fire onDidSelect if change
private onEnter(e: StandardKeyboardEvent): void {
dom.EventHelper.stop(e);
// Only fire if selection change
if (this.selected !== this._currentSelection) {
this._currentSelection = this.selected;
this._onDidSelect.fire({
index: this.selectElement.selectedIndex,
selected: this.options[this.selected].text
});
}
this.hideSelectDropDown(true);
}
// List navigation - have to handle a disabled option (jump over)
private onDownArrow(): void {
if (this.selected < this.options.length - 1) {
// Skip disabled options
const nextOptionDisabled = this.options[this.selected + 1].isDisabled;
if (nextOptionDisabled && this.options.length > this.selected + 2) {
this.selected += 2;
} else if (nextOptionDisabled) {
return;
} else {
this.selected++;
}
// Set focus/selection - only fire event when closing drop-down or on blur
this.select(this.selected);
this.selectList.setFocus([this.selected]);
this.selectList.reveal(this.selectList.getFocus()[0]);
}
}
private onUpArrow(): void {
if (this.selected > 0) {
// Skip disabled options
const previousOptionDisabled = this.options[this.selected - 1].isDisabled;
if (previousOptionDisabled && this.selected > 1) {
this.selected -= 2;
} else {
this.selected--;
}
// Set focus/selection - only fire event when closing drop-down or on blur
this.select(this.selected);
this.selectList.setFocus([this.selected]);
this.selectList.reveal(this.selectList.getFocus()[0]);
}
}
private onPageUp(e: StandardKeyboardEvent): void {
dom.EventHelper.stop(e);
this.selectList.focusPreviousPage();
// Allow scrolling to settle
setTimeout(() => {
this.selected = this.selectList.getFocus()[0];
// Shift selection down if we land on a disabled option
if (this.options[this.selected].isDisabled && this.selected < this.options.length - 1) {
this.selected++;
this.selectList.setFocus([this.selected]);
}
this.selectList.reveal(this.selected);
this.select(this.selected);
}, 1);
}
private onPageDown(e: StandardKeyboardEvent): void {
dom.EventHelper.stop(e);
this.selectList.focusNextPage();
// Allow scrolling to settle
setTimeout(() => {
this.selected = this.selectList.getFocus()[0];
// Shift selection up if we land on a disabled option
if (this.options[this.selected].isDisabled && this.selected > 0) {
this.selected--;
this.selectList.setFocus([this.selected]);
}
this.selectList.reveal(this.selected);
this.select(this.selected);
}, 1);
}
private onHome(e: StandardKeyboardEvent): void {
dom.EventHelper.stop(e);
if (this.options.length < 2) {
return;
}
this.selected = 0;
if (this.options[this.selected].isDisabled && this.selected > 1) {
this.selected++;
}
this.selectList.setFocus([this.selected]);
this.selectList.reveal(this.selected);
this.select(this.selected);
}
private onEnd(e: StandardKeyboardEvent): void {
dom.EventHelper.stop(e);
if (this.options.length < 2) {
return;
}
this.selected = this.options.length - 1;
if (this.options[this.selected].isDisabled && this.selected > 1) {
this.selected--;
}
this.selectList.setFocus([this.selected]);
this.selectList.reveal(this.selected);
this.select(this.selected);
}
// Mimic option first character navigation of native select
private onCharacter(e: StandardKeyboardEvent): void {
const ch = KeyCodeUtils.toString(e.keyCode);
let optionIndex = -1;
for (let i = 0; i < this.options.length - 1; i++) {
optionIndex = (i + this.selected + 1) % this.options.length;
if (this.options[optionIndex].text.charAt(0).toUpperCase() === ch && !this.options[optionIndex].isDisabled) {
this.select(optionIndex);
this.selectList.setFocus([optionIndex]);
this.selectList.reveal(this.selectList.getFocus()[0]);
dom.EventHelper.stop(e);
break;
}
}
}
public dispose(): void {
this.hideSelectDropDown(false);
this.toDispose = dispose(this.toDispose);
}
}
| src/vs/base/browser/ui/selectBox/selectBoxCustom.ts | 0 | https://github.com/microsoft/vscode/commit/bbff11633c7e56e7fd5d16cc20daa9a3284afbfe | [
0.0007439877954311669,
0.00019276807142887264,
0.00016046653036028147,
0.0001691310462774709,
0.00009146401134785265
]
|
{
"id": 13,
"code_window": [
"\n",
".search-view .search-widget .monaco-findInput {\n",
"\tdisplay: inline-block;\n",
"\tvertical-align: middle;\n",
"}\n",
"\n",
".search-view .search-widget .replace-container {\n",
"\tmargin-top: 6px;\n",
"\tposition: relative;\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\twidth: 100%;\n"
],
"file_path": "src/vs/workbench/contrib/search/browser/media/searchview.css",
"type": "add",
"edit_start_line_idx": 53
} | <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" enable-background="new 0 0 16 16" height="16" width="16"><path fill="#1E1E1E" d="M16 2.6L13.4 0H6v6H0v10h10v-6h6z"/><g fill="#75BEFF"><path d="M5 7h1v2H5zM11 1h1v2h-1zM13 1v3H9V1H7v5h.4L10 8.6V9h5V3zM7 10H3V7H1v8h8V9L7 7z"/></g></svg> | src/vs/workbench/contrib/files/electron-browser/media/saveall_inverse.svg | 0 | https://github.com/microsoft/vscode/commit/bbff11633c7e56e7fd5d16cc20daa9a3284afbfe | [
0.00016942189540714025,
0.00016942189540714025,
0.00016942189540714025,
0.00016942189540714025,
0
]
|
{
"id": 13,
"code_window": [
"\n",
".search-view .search-widget .monaco-findInput {\n",
"\tdisplay: inline-block;\n",
"\tvertical-align: middle;\n",
"}\n",
"\n",
".search-view .search-widget .replace-container {\n",
"\tmargin-top: 6px;\n",
"\tposition: relative;\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\twidth: 100%;\n"
],
"file_path": "src/vs/workbench/contrib/search/browser/media/searchview.css",
"type": "add",
"edit_start_line_idx": 53
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
import { Event } from 'vs/base/common/event';
import { Color } from 'vs/base/common/color';
import { ITheme, IThemeService, IIconTheme } from 'vs/platform/theme/common/themeService';
import { ConfigurationTarget } from 'vs/platform/configuration/common/configuration';
export const IWorkbenchThemeService = createDecorator<IWorkbenchThemeService>('themeService');
export const VS_LIGHT_THEME = 'vs';
export const VS_DARK_THEME = 'vs-dark';
export const VS_HC_THEME = 'hc-black';
export const HC_THEME_ID = 'Default High Contrast';
export const COLOR_THEME_SETTING = 'workbench.colorTheme';
export const DETECT_HC_SETTING = 'window.autoDetectHighContrast';
export const ICON_THEME_SETTING = 'workbench.iconTheme';
export const CUSTOM_WORKBENCH_COLORS_SETTING = 'workbench.colorCustomizations';
export const CUSTOM_EDITOR_COLORS_SETTING = 'editor.tokenColorCustomizations';
export interface IColorTheme extends ITheme {
readonly id: string;
readonly label: string;
readonly settingsId: string;
readonly extensionData: ExtensionData;
readonly description?: string;
readonly isLoaded: boolean;
readonly tokenColors: ITokenColorizationRule[];
}
export interface IColorMap {
[id: string]: Color;
}
export interface IFileIconTheme extends IIconTheme {
readonly id: string;
readonly label: string;
readonly settingsId: string | null;
readonly description?: string;
readonly extensionData?: ExtensionData;
readonly isLoaded: boolean;
readonly hasFileIcons: boolean;
readonly hasFolderIcons: boolean;
readonly hidesExplorerArrows: boolean;
}
export interface IWorkbenchThemeService extends IThemeService {
_serviceBrand: any;
setColorTheme(themeId: string | undefined, settingsTarget: ConfigurationTarget | undefined): Promise<IColorTheme | null>;
getColorTheme(): IColorTheme;
getColorThemes(): Promise<IColorTheme[]>;
onDidColorThemeChange: Event<IColorTheme>;
restoreColorTheme();
setFileIconTheme(iconThemeId: string | undefined, settingsTarget: ConfigurationTarget | undefined): Promise<IFileIconTheme>;
getFileIconTheme(): IFileIconTheme;
getFileIconThemes(): Promise<IFileIconTheme[]>;
onDidFileIconThemeChange: Event<IFileIconTheme>;
}
export interface ITokenColorCustomizations {
comments?: string | ITokenColorizationSetting;
strings?: string | ITokenColorizationSetting;
numbers?: string | ITokenColorizationSetting;
keywords?: string | ITokenColorizationSetting;
types?: string | ITokenColorizationSetting;
functions?: string | ITokenColorizationSetting;
variables?: string | ITokenColorizationSetting;
textMateRules?: ITokenColorizationRule[];
}
export interface ITokenColorizationRule {
name?: string;
scope?: string | string[];
settings: ITokenColorizationSetting;
}
export interface ITokenColorizationSetting {
foreground?: string;
background?: string;
fontStyle?: string; // italic, underline, bold
}
export interface ExtensionData {
extensionId: string;
extensionPublisher: string;
extensionName: string;
extensionIsBuiltin: boolean;
}
export interface IThemeExtensionPoint {
id: string;
label?: string;
description?: string;
path: string;
_watch: boolean; // unsupported options to watch location
} | src/vs/workbench/services/themes/common/workbenchThemeService.ts | 0 | https://github.com/microsoft/vscode/commit/bbff11633c7e56e7fd5d16cc20daa9a3284afbfe | [
0.0002788084384519607,
0.00018224520317744464,
0.00016834492271300405,
0.00017084344290196896,
0.00003118479799013585
]
|
{
"id": 14,
"code_window": [
"\t}\n",
"\n",
"\tsetWidth(width: number) {\n",
"\t\tthis.searchInput.setWidth(width);\n",
"\t\tthis.replaceInput.width = width - 28;\n",
"\t\tthis.replaceInput.layout();\n",
"\t}\n",
"\n",
"\tclear() {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/contrib/search/browser/searchWidget.ts",
"type": "replace",
"edit_start_line_idx": 171
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import 'vs/css!./findInput';
import * as nls from 'vs/nls';
import * as dom from 'vs/base/browser/dom';
import { IMessage as InputBoxMessage, IInputValidator, IInputBoxStyles, HistoryInputBox } from 'vs/base/browser/ui/inputbox/inputBox';
import { IContextViewProvider } from 'vs/base/browser/ui/contextview/contextview';
import { Widget } from 'vs/base/browser/ui/widget';
import { Event, Emitter } from 'vs/base/common/event';
import { IKeyboardEvent } from 'vs/base/browser/keyboardEvent';
import { IMouseEvent } from 'vs/base/browser/mouseEvent';
import { KeyCode } from 'vs/base/common/keyCodes';
import { CaseSensitiveCheckbox, WholeWordsCheckbox, RegexCheckbox } from 'vs/base/browser/ui/findinput/findInputCheckboxes';
import { Color } from 'vs/base/common/color';
import { ICheckboxStyles } from 'vs/base/browser/ui/checkbox/checkbox';
export interface IFindInputOptions extends IFindInputStyles {
readonly placeholder?: string;
readonly width?: number;
readonly validation?: IInputValidator;
readonly label: string;
readonly flexibleHeight?: boolean;
readonly appendCaseSensitiveLabel?: string;
readonly appendWholeWordsLabel?: string;
readonly appendRegexLabel?: string;
readonly history?: string[];
}
export interface IFindInputStyles extends IInputBoxStyles {
inputActiveOptionBorder?: Color;
}
const NLS_DEFAULT_LABEL = nls.localize('defaultLabel', "input");
export class FindInput extends Widget {
static readonly OPTION_CHANGE: string = 'optionChange';
private contextViewProvider: IContextViewProvider;
private width: number;
private placeholder: string;
private validation?: IInputValidator;
private label: string;
private fixFocusOnOptionClickEnabled = true;
private inputActiveOptionBorder?: Color;
private inputBackground?: Color;
private inputForeground?: Color;
private inputBorder?: Color;
private inputValidationInfoBorder?: Color;
private inputValidationInfoBackground?: Color;
private inputValidationInfoForeground?: Color;
private inputValidationWarningBorder?: Color;
private inputValidationWarningBackground?: Color;
private inputValidationWarningForeground?: Color;
private inputValidationErrorBorder?: Color;
private inputValidationErrorBackground?: Color;
private inputValidationErrorForeground?: Color;
private regex: RegexCheckbox;
private wholeWords: WholeWordsCheckbox;
private caseSensitive: CaseSensitiveCheckbox;
public domNode: HTMLElement;
public inputBox: HistoryInputBox;
private readonly _onDidOptionChange = this._register(new Emitter<boolean>());
public readonly onDidOptionChange: Event<boolean /* via keyboard */> = this._onDidOptionChange.event;
private readonly _onKeyDown = this._register(new Emitter<IKeyboardEvent>());
public readonly onKeyDown: Event<IKeyboardEvent> = this._onKeyDown.event;
private readonly _onMouseDown = this._register(new Emitter<IMouseEvent>());
public readonly onMouseDown: Event<IMouseEvent> = this._onMouseDown.event;
private readonly _onInput = this._register(new Emitter<void>());
public readonly onInput: Event<void> = this._onInput.event;
private readonly _onKeyUp = this._register(new Emitter<IKeyboardEvent>());
public readonly onKeyUp: Event<IKeyboardEvent> = this._onKeyUp.event;
private _onCaseSensitiveKeyDown = this._register(new Emitter<IKeyboardEvent>());
public readonly onCaseSensitiveKeyDown: Event<IKeyboardEvent> = this._onCaseSensitiveKeyDown.event;
private _onRegexKeyDown = this._register(new Emitter<IKeyboardEvent>());
public readonly onRegexKeyDown: Event<IKeyboardEvent> = this._onRegexKeyDown.event;
constructor(parent: HTMLElement | null, contextViewProvider: IContextViewProvider, private readonly _showOptionButtons: boolean, options: IFindInputOptions) {
super();
this.contextViewProvider = contextViewProvider;
this.width = options.width || 100;
this.placeholder = options.placeholder || '';
this.validation = options.validation;
this.label = options.label || NLS_DEFAULT_LABEL;
this.inputActiveOptionBorder = options.inputActiveOptionBorder;
this.inputBackground = options.inputBackground;
this.inputForeground = options.inputForeground;
this.inputBorder = options.inputBorder;
this.inputValidationInfoBorder = options.inputValidationInfoBorder;
this.inputValidationInfoBackground = options.inputValidationInfoBackground;
this.inputValidationInfoForeground = options.inputValidationInfoForeground;
this.inputValidationWarningBorder = options.inputValidationWarningBorder;
this.inputValidationWarningBackground = options.inputValidationWarningBackground;
this.inputValidationWarningForeground = options.inputValidationWarningForeground;
this.inputValidationErrorBorder = options.inputValidationErrorBorder;
this.inputValidationErrorBackground = options.inputValidationErrorBackground;
this.inputValidationErrorForeground = options.inputValidationErrorForeground;
this.buildDomNode(options.appendCaseSensitiveLabel || '', options.appendWholeWordsLabel || '', options.appendRegexLabel || '', options.history || [], !!options.flexibleHeight);
if (parent) {
parent.appendChild(this.domNode);
}
this.onkeydown(this.inputBox.inputElement, (e) => this._onKeyDown.fire(e));
this.onkeyup(this.inputBox.inputElement, (e) => this._onKeyUp.fire(e));
this.oninput(this.inputBox.inputElement, (e) => this._onInput.fire());
this.onmousedown(this.inputBox.inputElement, (e) => this._onMouseDown.fire(e));
}
public enable(): void {
dom.removeClass(this.domNode, 'disabled');
this.inputBox.enable();
this.regex.enable();
this.wholeWords.enable();
this.caseSensitive.enable();
}
public disable(): void {
dom.addClass(this.domNode, 'disabled');
this.inputBox.disable();
this.regex.disable();
this.wholeWords.disable();
this.caseSensitive.disable();
}
public setFocusInputOnOptionClick(value: boolean): void {
this.fixFocusOnOptionClickEnabled = value;
}
public setEnabled(enabled: boolean): void {
if (enabled) {
this.enable();
} else {
this.disable();
}
}
public clear(): void {
this.clearValidation();
this.setValue('');
this.focus();
}
public setWidth(newWidth: number): void {
this.width = newWidth;
this.domNode.style.width = this.width + 'px';
this.contextViewProvider.layout();
this.setInputWidth();
}
public getValue(): string {
return this.inputBox.value;
}
public setValue(value: string): void {
if (this.inputBox.value !== value) {
this.inputBox.value = value;
}
}
public onSearchSubmit(): void {
this.inputBox.addToHistory();
}
public style(styles: IFindInputStyles): void {
this.inputActiveOptionBorder = styles.inputActiveOptionBorder;
this.inputBackground = styles.inputBackground;
this.inputForeground = styles.inputForeground;
this.inputBorder = styles.inputBorder;
this.inputValidationInfoBackground = styles.inputValidationInfoBackground;
this.inputValidationInfoForeground = styles.inputValidationInfoForeground;
this.inputValidationInfoBorder = styles.inputValidationInfoBorder;
this.inputValidationWarningBackground = styles.inputValidationWarningBackground;
this.inputValidationWarningForeground = styles.inputValidationWarningForeground;
this.inputValidationWarningBorder = styles.inputValidationWarningBorder;
this.inputValidationErrorBackground = styles.inputValidationErrorBackground;
this.inputValidationErrorForeground = styles.inputValidationErrorForeground;
this.inputValidationErrorBorder = styles.inputValidationErrorBorder;
this.applyStyles();
}
protected applyStyles(): void {
if (this.domNode) {
const checkBoxStyles: ICheckboxStyles = {
inputActiveOptionBorder: this.inputActiveOptionBorder,
};
this.regex.style(checkBoxStyles);
this.wholeWords.style(checkBoxStyles);
this.caseSensitive.style(checkBoxStyles);
const inputBoxStyles: IInputBoxStyles = {
inputBackground: this.inputBackground,
inputForeground: this.inputForeground,
inputBorder: this.inputBorder,
inputValidationInfoBackground: this.inputValidationInfoBackground,
inputValidationInfoForeground: this.inputValidationInfoForeground,
inputValidationInfoBorder: this.inputValidationInfoBorder,
inputValidationWarningBackground: this.inputValidationWarningBackground,
inputValidationWarningForeground: this.inputValidationWarningForeground,
inputValidationWarningBorder: this.inputValidationWarningBorder,
inputValidationErrorBackground: this.inputValidationErrorBackground,
inputValidationErrorForeground: this.inputValidationErrorForeground,
inputValidationErrorBorder: this.inputValidationErrorBorder
};
this.inputBox.style(inputBoxStyles);
}
}
public select(): void {
this.inputBox.select();
}
public focus(): void {
this.inputBox.focus();
}
public getCaseSensitive(): boolean {
return this.caseSensitive.checked;
}
public setCaseSensitive(value: boolean): void {
this.caseSensitive.checked = value;
this.setInputWidth();
}
public getWholeWords(): boolean {
return this.wholeWords.checked;
}
public setWholeWords(value: boolean): void {
this.wholeWords.checked = value;
this.setInputWidth();
}
public getRegex(): boolean {
return this.regex.checked;
}
public setRegex(value: boolean): void {
this.regex.checked = value;
this.setInputWidth();
this.validate();
}
public focusOnCaseSensitive(): void {
this.caseSensitive.focus();
}
public focusOnRegex(): void {
this.regex.focus();
}
private _lastHighlightFindOptions: number = 0;
public highlightFindOptions(): void {
dom.removeClass(this.domNode, 'highlight-' + (this._lastHighlightFindOptions));
this._lastHighlightFindOptions = 1 - this._lastHighlightFindOptions;
dom.addClass(this.domNode, 'highlight-' + (this._lastHighlightFindOptions));
}
private setInputWidth(): void {
let w = this.width - this.caseSensitive.width() - this.wholeWords.width() - this.regex.width();
this.inputBox.width = w;
this.inputBox.layout();
}
private buildDomNode(appendCaseSensitiveLabel: string, appendWholeWordsLabel: string, appendRegexLabel: string, history: string[], flexibleHeight: boolean): void {
this.domNode = document.createElement('div');
this.domNode.style.width = this.width + 'px';
dom.addClass(this.domNode, 'monaco-findInput');
this.inputBox = this._register(new HistoryInputBox(this.domNode, this.contextViewProvider, {
placeholder: this.placeholder || '',
ariaLabel: this.label || '',
validationOptions: {
validation: this.validation
},
inputBackground: this.inputBackground,
inputForeground: this.inputForeground,
inputBorder: this.inputBorder,
inputValidationInfoBackground: this.inputValidationInfoBackground,
inputValidationInfoForeground: this.inputValidationInfoForeground,
inputValidationInfoBorder: this.inputValidationInfoBorder,
inputValidationWarningBackground: this.inputValidationWarningBackground,
inputValidationWarningForeground: this.inputValidationWarningForeground,
inputValidationWarningBorder: this.inputValidationWarningBorder,
inputValidationErrorBackground: this.inputValidationErrorBackground,
inputValidationErrorForeground: this.inputValidationErrorForeground,
inputValidationErrorBorder: this.inputValidationErrorBorder,
history,
flexibleHeight
}));
this.regex = this._register(new RegexCheckbox({
appendTitle: appendRegexLabel,
isChecked: false,
inputActiveOptionBorder: this.inputActiveOptionBorder
}));
this._register(this.regex.onChange(viaKeyboard => {
this._onDidOptionChange.fire(viaKeyboard);
if (!viaKeyboard && this.fixFocusOnOptionClickEnabled) {
this.inputBox.focus();
}
this.setInputWidth();
this.validate();
}));
this._register(this.regex.onKeyDown(e => {
this._onRegexKeyDown.fire(e);
}));
this.wholeWords = this._register(new WholeWordsCheckbox({
appendTitle: appendWholeWordsLabel,
isChecked: false,
inputActiveOptionBorder: this.inputActiveOptionBorder
}));
this._register(this.wholeWords.onChange(viaKeyboard => {
this._onDidOptionChange.fire(viaKeyboard);
if (!viaKeyboard && this.fixFocusOnOptionClickEnabled) {
this.inputBox.focus();
}
this.setInputWidth();
this.validate();
}));
this.caseSensitive = this._register(new CaseSensitiveCheckbox({
appendTitle: appendCaseSensitiveLabel,
isChecked: false,
inputActiveOptionBorder: this.inputActiveOptionBorder
}));
this._register(this.caseSensitive.onChange(viaKeyboard => {
this._onDidOptionChange.fire(viaKeyboard);
if (!viaKeyboard && this.fixFocusOnOptionClickEnabled) {
this.inputBox.focus();
}
this.setInputWidth();
this.validate();
}));
this._register(this.caseSensitive.onKeyDown(e => {
this._onCaseSensitiveKeyDown.fire(e);
}));
if (this._showOptionButtons) {
this.inputBox.inputElement.style.paddingRight = (this.caseSensitive.width() + this.wholeWords.width() + this.regex.width()) + 'px';
}
// Arrow-Key support to navigate between options
let indexes = [this.caseSensitive.domNode, this.wholeWords.domNode, this.regex.domNode];
this.onkeydown(this.domNode, (event: IKeyboardEvent) => {
if (event.equals(KeyCode.LeftArrow) || event.equals(KeyCode.RightArrow) || event.equals(KeyCode.Escape)) {
let index = indexes.indexOf(<HTMLElement>document.activeElement);
if (index >= 0) {
let newIndex: number = -1;
if (event.equals(KeyCode.RightArrow)) {
newIndex = (index + 1) % indexes.length;
} else if (event.equals(KeyCode.LeftArrow)) {
if (index === 0) {
newIndex = indexes.length - 1;
} else {
newIndex = index - 1;
}
}
if (event.equals(KeyCode.Escape)) {
indexes[index].blur();
} else if (newIndex >= 0) {
indexes[newIndex].focus();
}
dom.EventHelper.stop(event, true);
}
}
});
this.setInputWidth();
let controls = document.createElement('div');
controls.className = 'controls';
controls.style.display = this._showOptionButtons ? 'block' : 'none';
controls.appendChild(this.caseSensitive.domNode);
controls.appendChild(this.wholeWords.domNode);
controls.appendChild(this.regex.domNode);
this.domNode.appendChild(controls);
}
public validate(): void {
if (this.inputBox) {
this.inputBox.validate();
}
}
public showMessage(message: InputBoxMessage): void {
if (this.inputBox) {
this.inputBox.showMessage(message);
}
}
public clearMessage(): void {
if (this.inputBox) {
this.inputBox.hideMessage();
}
}
private clearValidation(): void {
if (this.inputBox) {
this.inputBox.hideMessage();
}
}
public dispose(): void {
super.dispose();
}
}
| src/vs/base/browser/ui/findinput/findInput.ts | 1 | https://github.com/microsoft/vscode/commit/bbff11633c7e56e7fd5d16cc20daa9a3284afbfe | [
0.006564094219356775,
0.00042877180385403335,
0.0001609375758562237,
0.00017115430091507733,
0.0010042769135907292
]
|
{
"id": 14,
"code_window": [
"\t}\n",
"\n",
"\tsetWidth(width: number) {\n",
"\t\tthis.searchInput.setWidth(width);\n",
"\t\tthis.replaceInput.width = width - 28;\n",
"\t\tthis.replaceInput.layout();\n",
"\t}\n",
"\n",
"\tclear() {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/contrib/search/browser/searchWidget.ts",
"type": "replace",
"edit_start_line_idx": 171
} | {
"iconDefinitions": {
"_root_folder_dark": {
"iconPath": "./images/RootFolder_16x_inverse.svg"
},
"_root_folder_open_dark": {
"iconPath": "./images/RootFolderOpen_16x_inverse.svg"
},
"_folder_dark": {
"iconPath": "./images/Folder_16x_inverse.svg"
},
"_folder_open_dark": {
"iconPath": "./images/FolderOpen_16x_inverse.svg"
},
"_file_dark": {
"iconPath": "./images/Document_16x_inverse.svg"
},
"_root_folder": {
"iconPath": "./images/RootFolder_16x.svg"
},
"_root_folder_open": {
"iconPath": "./images/RootFolderOpen_16x.svg"
},
"_folder_light": {
"iconPath": "./images/Folder_16x.svg"
},
"_folder_open_light": {
"iconPath": "./images/FolderOpen_16x.svg"
},
"_file_light": {
"iconPath": "./images/Document_16x.svg"
}
},
"folderExpanded": "_folder_open_dark",
"folder": "_folder_dark",
"file": "_file_dark",
"rootFolderExpanded": "_root_folder_open_dark",
"rootFolder": "_root_folder_dark",
"fileExtensions": {
// icons by file extension
},
"fileNames": {
// icons by file name
},
"languageIds": {
// icons by language id
},
"light": {
"folderExpanded": "_folder_open_light",
"folder": "_folder_light",
"rootFolderExpanded": "_root_folder_open",
"rootFolder": "_root_folder",
"file": "_file_light",
"fileExtensions": {
// icons by file extension
},
"fileNames": {
// icons by file name
},
"languageIds": {
// icons by language id
}
},
"highContrast": {
// overrides for high contrast
}
} | extensions/theme-defaults/fileicons/vs_minimal-icon-theme.json | 0 | https://github.com/microsoft/vscode/commit/bbff11633c7e56e7fd5d16cc20daa9a3284afbfe | [
0.00017523521091789007,
0.00017285037029068917,
0.0001709589851088822,
0.00017257517902180552,
0.0000015950893157423707
]
|
{
"id": 14,
"code_window": [
"\t}\n",
"\n",
"\tsetWidth(width: number) {\n",
"\t\tthis.searchInput.setWidth(width);\n",
"\t\tthis.replaceInput.width = width - 28;\n",
"\t\tthis.replaceInput.layout();\n",
"\t}\n",
"\n",
"\tclear() {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/contrib/search/browser/searchWidget.ts",
"type": "replace",
"edit_start_line_idx": 171
} | /*---------------------------------------------------------------------------------------------
* 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 { joinPath } from 'vs/base/common/resources';
import { URI } from 'vs/base/common/uri';
import { Range } from 'vs/workbench/services/search/node/ripgrepSearchUtils';
import { fixRegexCRMatchingNonWordClass, fixRegexCRMatchingWhitespaceClass, fixRegexEndingPattern, fixRegexNewline, IRgMatch, IRgMessage, RipgrepParser, unicodeEscapesToPCRE2, fixNewline } from 'vs/workbench/services/search/node/ripgrepTextSearchEngine';
import { TextSearchResult } from 'vscode';
suite('RipgrepTextSearchEngine', () => {
test('unicodeEscapesToPCRE2', async () => {
assert.equal(unicodeEscapesToPCRE2('\\u1234'), '\\x{1234}');
assert.equal(unicodeEscapesToPCRE2('\\u1234\\u0001'), '\\x{1234}\\x{0001}');
assert.equal(unicodeEscapesToPCRE2('foo\\u1234bar'), 'foo\\x{1234}bar');
assert.equal(unicodeEscapesToPCRE2('\\\\\\u1234'), '\\\\\\x{1234}');
assert.equal(unicodeEscapesToPCRE2('foo\\\\\\u1234'), 'foo\\\\\\x{1234}');
assert.equal(unicodeEscapesToPCRE2('\\u123'), '\\u123');
assert.equal(unicodeEscapesToPCRE2('\\u12345'), '\\u12345');
assert.equal(unicodeEscapesToPCRE2('\\\\u12345'), '\\\\u12345');
assert.equal(unicodeEscapesToPCRE2('foo'), 'foo');
assert.equal(unicodeEscapesToPCRE2(''), '');
});
test('fixRegexEndingPattern', () => {
function testFixRegexEndingPattern([input, expectedResult]: string[]): void {
assert.equal(fixRegexEndingPattern(input), expectedResult);
}
[
['foo', 'foo'],
['', ''],
['^foo.*bar\\s+', '^foo.*bar\\s+'],
['foo$', 'foo\\r?$'],
['$', '\\r?$'],
['foo\\$', 'foo\\$'],
['foo\\\\$', 'foo\\\\\\r?$'],
].forEach(testFixRegexEndingPattern);
});
test('fixRegexCRMatchingWhitespaceClass', () => {
function testFixRegexCRMatchingWhitespaceClass([inputReg, isMultiline, testStr, shouldMatch]): void {
const fixed = fixRegexCRMatchingWhitespaceClass(inputReg, isMultiline);
const reg = new RegExp(fixed);
assert.equal(reg.test(testStr), shouldMatch, `${inputReg} => ${reg}, ${testStr}, ${shouldMatch}`);
}
[
['foo', false, 'foo', true],
['foo\\s', false, 'foo\r\n', false],
['foo\\sabc', true, 'foo\r\nabc', true],
['foo\\s', false, 'foo\n', false],
['foo\\s', true, 'foo\n', true],
['foo\\s\\n', true, 'foo\r\n', false],
['foo\\r\\s', true, 'foo\r\n', true],
['foo\\s+abc', true, 'foo \r\nabc', true],
['foo\\s+abc', false, 'foo \t abc', true],
].forEach(testFixRegexCRMatchingWhitespaceClass);
});
test('fixRegexCRMatchingNonWordClass', () => {
function testRegexCRMatchingNonWordClass([inputReg, isMultiline, testStr, shouldMatch]): void {
const fixed = fixRegexCRMatchingNonWordClass(inputReg, isMultiline);
const reg = new RegExp(fixed);
assert.equal(reg.test(testStr), shouldMatch, `${inputReg} => ${reg}, ${testStr}, ${shouldMatch}`);
}
[
['foo', false, 'foo', true],
['foo\\W', false, 'foo\r\n', false],
['foo\\Wabc', true, 'foo\r\nabc', true],
['foo\\W', false, 'foo\n', true],
['foo\\W', true, 'foo\n', true],
['foo\\W\\n', true, 'foo\r\n', false],
['foo\\r\\W', true, 'foo\r\n', true],
['foo\\W+abc', true, 'foo \r\nabc', true],
['foo\\W+abc', false, 'foo .-\t abc', true],
].forEach(testRegexCRMatchingNonWordClass);
});
test('fixRegexNewline', () => {
function testFixRegexNewline([inputReg, testStr, shouldMatch]): void {
const fixed = fixRegexNewline(inputReg);
const reg = new RegExp(fixed);
assert.equal(reg.test(testStr), shouldMatch, `${inputReg} => ${reg}, ${testStr}, ${shouldMatch}`);
}
[
['foo', 'foo', true],
['foo\\n', 'foo\r\n', true],
['foo\\n', 'foo\n', true],
['foo\\nabc', 'foo\r\nabc', true],
['foo\\nabc', 'foo\nabc', true],
['foo\\r\\n', 'foo\r\n', true],
['foo\\n+abc', 'foo\r\nabc', true],
['foo\\n+abc', 'foo\n\n\nabc', true],
].forEach(testFixRegexNewline);
});
test('fixNewline', () => {
function testFixNewline([inputReg, testStr, shouldMatch = true]): void {
const fixed = fixNewline(inputReg);
const reg = new RegExp(fixed);
assert.equal(reg.test(testStr), shouldMatch, `${inputReg} => ${reg}, ${testStr}, ${shouldMatch}`);
}
[
['foo', 'foo'],
['foo\n', 'foo\r\n'],
['foo\n', 'foo\n'],
['foo\nabc', 'foo\r\nabc'],
['foo\nabc', 'foo\nabc'],
['foo\r\n', 'foo\r\n'],
['foo\nbarc', 'foobar', false],
['foobar', 'foo\nbar', false],
].forEach(testFixNewline);
});
suite('RipgrepParser', () => {
const TEST_FOLDER = URI.file('/foo/bar');
function testParser(inputData: string[], expectedResults: TextSearchResult[]): void {
const testParser = new RipgrepParser(1000, TEST_FOLDER.fsPath);
const actualResults: TextSearchResult[] = [];
testParser.on('result', r => {
actualResults.push(r);
});
inputData.forEach(d => testParser.handleData(d));
testParser.flush();
assert.deepEqual(actualResults, expectedResults);
}
function makeRgMatch(relativePath: string, text: string, lineNumber: number, matchRanges: { start: number, end: number }[]): string {
return JSON.stringify(<IRgMessage>{
type: 'match',
data: <IRgMatch>{
path: {
text: relativePath
},
lines: {
text
},
line_number: lineNumber,
absolute_offset: 0, // unused
submatches: matchRanges.map(mr => {
return {
...mr,
match: { text: text.substring(mr.start, mr.end) }
};
})
}
}) + '\n';
}
test('single result', () => {
testParser(
[
makeRgMatch('file1.js', 'foobar', 4, [{ start: 3, end: 6 }])
],
[
{
preview: {
text: 'foobar',
matches: [new Range(0, 3, 0, 6)]
},
uri: joinPath(TEST_FOLDER, 'file1.js'),
ranges: [new Range(3, 3, 3, 6)]
}
]);
});
test('multiple results', () => {
testParser(
[
makeRgMatch('file1.js', 'foobar', 4, [{ start: 3, end: 6 }]),
makeRgMatch('app/file2.js', 'foobar', 4, [{ start: 3, end: 6 }]),
makeRgMatch('app2/file3.js', 'foobar', 4, [{ start: 3, end: 6 }]),
],
[
{
preview: {
text: 'foobar',
matches: [new Range(0, 3, 0, 6)]
},
uri: joinPath(TEST_FOLDER, 'file1.js'),
ranges: [new Range(3, 3, 3, 6)]
},
{
preview: {
text: 'foobar',
matches: [new Range(0, 3, 0, 6)]
},
uri: joinPath(TEST_FOLDER, 'app/file2.js'),
ranges: [new Range(3, 3, 3, 6)]
},
{
preview: {
text: 'foobar',
matches: [new Range(0, 3, 0, 6)]
},
uri: joinPath(TEST_FOLDER, 'app2/file3.js'),
ranges: [new Range(3, 3, 3, 6)]
}
]);
});
test('chopped-up input chunks', () => {
const dataStrs = [
makeRgMatch('file1.js', 'foobar', 4, [{ start: 3, end: 6 }]),
makeRgMatch('app/file2.js', 'foobar', 4, [{ start: 3, end: 6 }]),
makeRgMatch('app2/file3.js', 'foobar', 4, [{ start: 3, end: 6 }]),
];
testParser(
[
dataStrs[0].substring(0, 5),
dataStrs[0].substring(5),
'\n',
dataStrs[1].trim(),
'\n' + dataStrs[2].substring(0, 25),
dataStrs[2].substring(25)
],
[
{
preview: {
text: 'foobar',
matches: [new Range(0, 3, 0, 6)]
},
uri: joinPath(TEST_FOLDER, 'file1.js'),
ranges: [new Range(3, 3, 3, 6)]
},
{
preview: {
text: 'foobar',
matches: [new Range(0, 3, 0, 6)]
},
uri: joinPath(TEST_FOLDER, 'app/file2.js'),
ranges: [new Range(3, 3, 3, 6)]
},
{
preview: {
text: 'foobar',
matches: [new Range(0, 3, 0, 6)]
},
uri: joinPath(TEST_FOLDER, 'app2/file3.js'),
ranges: [new Range(3, 3, 3, 6)]
}
]);
});
});
});
| src/vs/workbench/services/search/test/node/ripgrepTextSearchEngine.test.ts | 0 | https://github.com/microsoft/vscode/commit/bbff11633c7e56e7fd5d16cc20daa9a3284afbfe | [
0.00017682419274933636,
0.00017166217730846256,
0.00016606759163551033,
0.00017175404354929924,
0.0000026503582830628147
]
|
{
"id": 14,
"code_window": [
"\t}\n",
"\n",
"\tsetWidth(width: number) {\n",
"\t\tthis.searchInput.setWidth(width);\n",
"\t\tthis.replaceInput.width = width - 28;\n",
"\t\tthis.replaceInput.layout();\n",
"\t}\n",
"\n",
"\tclear() {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "src/vs/workbench/contrib/search/browser/searchWidget.ts",
"type": "replace",
"edit_start_line_idx": 171
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Event } from 'vs/base/common/event';
import { IChannel, IServerChannel } from 'vs/base/parts/ipc/node/ipc';
import { IRawFileQuery, IRawTextQuery } from 'vs/workbench/services/search/common/search';
import { IRawSearchService, ISerializedSearchComplete, ISerializedSearchProgressItem } from './search';
export class SearchChannel implements IServerChannel {
constructor(private service: IRawSearchService) { }
listen<T>(_, event: string, arg?: any): Event<any> {
switch (event) {
case 'fileSearch': return this.service.fileSearch(arg);
case 'textSearch': return this.service.textSearch(arg);
}
throw new Error('Event not found');
}
call(_, command: string, arg?: any): Promise<any> {
switch (command) {
case 'clearCache': return this.service.clearCache(arg);
}
throw new Error('Call not found');
}
}
export class SearchChannelClient implements IRawSearchService {
constructor(private channel: IChannel) { }
fileSearch(search: IRawFileQuery): Event<ISerializedSearchProgressItem | ISerializedSearchComplete> {
return this.channel.listen('fileSearch', search);
}
textSearch(search: IRawTextQuery): Event<ISerializedSearchProgressItem | ISerializedSearchComplete> {
return this.channel.listen('textSearch', search);
}
clearCache(cacheKey: string): Promise<void> {
return this.channel.call('clearCache', cacheKey);
}
} | src/vs/workbench/services/search/node/searchIpc.ts | 0 | https://github.com/microsoft/vscode/commit/bbff11633c7e56e7fd5d16cc20daa9a3284afbfe | [
0.00017503800336271524,
0.00016967950796242803,
0.0001648075267439708,
0.00016992083692457527,
0.000003964756160712568
]
|
{
"id": 0,
"code_window": [
"}\n",
"\n",
"func AddOrgInvite(c *m.ReqContext, inviteDto dtos.AddInviteForm) Response {\n",
"\tif setting.DisableLoginForm {\n",
"\t\treturn Error(400, \"Cannot invite when login is disabled.\", nil)\n",
"\t}\n",
"\n",
"\tif !inviteDto.Role.IsValid() {\n",
"\t\treturn Error(400, \"Invalid role specified\", nil)\n",
"\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "pkg/api/org_invite.go",
"type": "replace",
"edit_start_line_idx": 29
} | import { Invitee, OrgUser, UsersState } from 'app/types';
import { Action, ActionTypes } from './actions';
import config from 'app/core/config';
export const initialState: UsersState = {
invitees: [] as Invitee[],
users: [] as OrgUser[],
searchQuery: '',
canInvite: !config.disableLoginForm && !config.externalUserMngLinkName,
externalUserMngInfo: config.externalUserMngInfo,
externalUserMngLinkName: config.externalUserMngLinkName,
externalUserMngLinkUrl: config.externalUserMngLinkUrl,
hasFetched: false,
};
export const usersReducer = (state = initialState, action: Action): UsersState => {
switch (action.type) {
case ActionTypes.LoadUsers:
return { ...state, hasFetched: true, users: action.payload };
case ActionTypes.LoadInvitees:
return { ...state, hasFetched: true, invitees: action.payload };
case ActionTypes.SetUsersSearchQuery:
return { ...state, searchQuery: action.payload };
}
return state;
};
export default {
users: usersReducer,
};
| public/app/features/users/state/reducers.ts | 1 | https://github.com/grafana/grafana/commit/09b434bdd08a65714e7fd09c802a0835c3261132 | [
0.0006313634803518653,
0.00028825493063777685,
0.00017126392049249262,
0.00017519621178507805,
0.00019810149387922138
]
|
{
"id": 0,
"code_window": [
"}\n",
"\n",
"func AddOrgInvite(c *m.ReqContext, inviteDto dtos.AddInviteForm) Response {\n",
"\tif setting.DisableLoginForm {\n",
"\t\treturn Error(400, \"Cannot invite when login is disabled.\", nil)\n",
"\t}\n",
"\n",
"\tif !inviteDto.Role.IsValid() {\n",
"\t\treturn Error(400, \"Invalid role specified\", nil)\n",
"\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "pkg/api/org_invite.go",
"type": "replace",
"edit_start_line_idx": 29
} | scripts/build/release_publisher/testdata/grafana-enterprise_5.4.0-123pre1_amd64.deb | 0 | https://github.com/grafana/grafana/commit/09b434bdd08a65714e7fd09c802a0835c3261132 | [
0.00017707525694277138,
0.00017707525694277138,
0.00017707525694277138,
0.00017707525694277138,
0
]
|
|
{
"id": 0,
"code_window": [
"}\n",
"\n",
"func AddOrgInvite(c *m.ReqContext, inviteDto dtos.AddInviteForm) Response {\n",
"\tif setting.DisableLoginForm {\n",
"\t\treturn Error(400, \"Cannot invite when login is disabled.\", nil)\n",
"\t}\n",
"\n",
"\tif !inviteDto.Role.IsValid() {\n",
"\t\treturn Error(400, \"Invalid role specified\", nil)\n",
"\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "pkg/api/org_invite.go",
"type": "replace",
"edit_start_line_idx": 29
} | <?xml version="1.0" encoding="utf-8"?>
<!-- Generator: Adobe Illustrator 20.1.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
width="351px" height="365px" viewBox="0 0 351 365" style="enable-background:new 0 0 351 365;" xml:space="preserve">
<style type="text/css">
.st0{fill:url(#SVGID_1_);}
</style>
<g id="Layer_1_1_">
</g>
<linearGradient id="SVGID_1_" gradientUnits="userSpaceOnUse" x1="175.5" y1="30%" x2="175.5" y2="99%">
<stop offset="0" style="stop-color:#F05A28"/>
<stop offset="1" style="stop-color:#FBCA0A"/>
</linearGradient>
<path class="st0" d="M342,161.2c-0.6-6.1-1.6-13.1-3.6-20.9c-2-7.7-5-16.2-9.4-25c-4.4-8.8-10.1-17.9-17.5-26.8
c-2.9-3.5-6.1-6.9-9.5-10.2c5.1-20.3-6.2-37.9-6.2-37.9c-19.5-1.2-31.9,6.1-36.5,9.4c-0.8-0.3-1.5-0.7-2.3-1
c-3.3-1.3-6.7-2.6-10.3-3.7c-3.5-1.1-7.1-2.1-10.8-3c-3.7-0.9-7.4-1.6-11.2-2.2c-0.7-0.1-1.3-0.2-2-0.3
c-8.5-27.2-32.9-38.6-32.9-38.6c-27.3,17.3-32.4,41.5-32.4,41.5s-0.1,0.5-0.3,1.4c-1.5,0.4-3,0.9-4.5,1.3c-2.1,0.6-4.2,1.4-6.2,2.2
c-2.1,0.8-4.1,1.6-6.2,2.5c-4.1,1.8-8.2,3.8-12.2,6c-3.9,2.2-7.7,4.6-11.4,7.1c-0.5-0.2-1-0.4-1-0.4c-37.8-14.4-71.3,2.9-71.3,2.9
c-3.1,40.2,15.1,65.5,18.7,70.1c-0.9,2.5-1.7,5-2.5,7.5c-2.8,9.1-4.9,18.4-6.2,28.1c-0.2,1.4-0.4,2.8-0.5,4.2
C18.8,192.7,8.5,228,8.5,228c29.1,33.5,63.1,35.6,63.1,35.6c0,0,0.1-0.1,0.1-0.1c4.3,7.7,9.3,15,14.9,21.9c2.4,2.9,4.8,5.6,7.4,8.3
c-10.6,30.4,1.5,55.6,1.5,55.6c32.4,1.2,53.7-14.2,58.2-17.7c3.2,1.1,6.5,2.1,9.8,2.9c10,2.6,20.2,4.1,30.4,4.5
c2.5,0.1,5.1,0.2,7.6,0.1l1.2,0l0.8,0l1.6,0l1.6-0.1l0,0.1c15.3,21.8,42.1,24.9,42.1,24.9c19.1-20.1,20.2-40.1,20.2-44.4l0,0
c0,0,0-0.1,0-0.3c0-0.4,0-0.6,0-0.6l0,0c0-0.3,0-0.6,0-0.9c4-2.8,7.8-5.8,11.4-9.1c7.6-6.9,14.3-14.8,19.9-23.3
c0.5-0.8,1-1.6,1.5-2.4c21.6,1.2,36.9-13.4,36.9-13.4c-3.6-22.5-16.4-33.5-19.1-35.6l0,0c0,0-0.1-0.1-0.3-0.2
c-0.2-0.1-0.2-0.2-0.2-0.2c0,0,0,0,0,0c-0.1-0.1-0.3-0.2-0.5-0.3c0.1-1.4,0.2-2.7,0.3-4.1c0.2-2.4,0.2-4.9,0.2-7.3l0-1.8l0-0.9
l0-0.5c0-0.6,0-0.4,0-0.6l-0.1-1.5l-0.1-2c0-0.7-0.1-1.3-0.2-1.9c-0.1-0.6-0.1-1.3-0.2-1.9l-0.2-1.9l-0.3-1.9
c-0.4-2.5-0.8-4.9-1.4-7.4c-2.3-9.7-6.1-18.9-11-27.2c-5-8.3-11.2-15.6-18.3-21.8c-7-6.2-14.9-11.2-23.1-14.9
c-8.3-3.7-16.9-6.1-25.5-7.2c-4.3-0.6-8.6-0.8-12.9-0.7l-1.6,0l-0.4,0c-0.1,0-0.6,0-0.5,0l-0.7,0l-1.6,0.1c-0.6,0-1.2,0.1-1.7,0.1
c-2.2,0.2-4.4,0.5-6.5,0.9c-8.6,1.6-16.7,4.7-23.8,9c-7.1,4.3-13.3,9.6-18.3,15.6c-5,6-8.9,12.7-11.6,19.6c-2.7,6.9-4.2,14.1-4.6,21
c-0.1,1.7-0.1,3.5-0.1,5.2c0,0.4,0,0.9,0,1.3l0.1,1.4c0.1,0.8,0.1,1.7,0.2,2.5c0.3,3.5,1,6.9,1.9,10.1c1.9,6.5,4.9,12.4,8.6,17.4
c3.7,5,8.2,9.1,12.9,12.4c4.7,3.2,9.8,5.5,14.8,7c5,1.5,10,2.1,14.7,2.1c0.6,0,1.2,0,1.7,0c0.3,0,0.6,0,0.9,0c0.3,0,0.6,0,0.9-0.1
c0.5,0,1-0.1,1.5-0.1c0.1,0,0.3,0,0.4-0.1l0.5-0.1c0.3,0,0.6-0.1,0.9-0.1c0.6-0.1,1.1-0.2,1.7-0.3c0.6-0.1,1.1-0.2,1.6-0.4
c1.1-0.2,2.1-0.6,3.1-0.9c2-0.7,4-1.5,5.7-2.4c1.8-0.9,3.4-2,5-3c0.4-0.3,0.9-0.6,1.3-1c1.6-1.3,1.9-3.7,0.6-5.3
c-1.1-1.4-3.1-1.8-4.7-0.9c-0.4,0.2-0.8,0.4-1.2,0.6c-1.4,0.7-2.8,1.3-4.3,1.8c-1.5,0.5-3.1,0.9-4.7,1.2c-0.8,0.1-1.6,0.2-2.5,0.3
c-0.4,0-0.8,0.1-1.3,0.1c-0.4,0-0.9,0-1.2,0c-0.4,0-0.8,0-1.2,0c-0.5,0-1,0-1.5-0.1c0,0-0.3,0-0.1,0l-0.2,0l-0.3,0
c-0.2,0-0.5,0-0.7-0.1c-0.5-0.1-0.9-0.1-1.4-0.2c-3.7-0.5-7.4-1.6-10.9-3.2c-3.6-1.6-7-3.8-10.1-6.6c-3.1-2.8-5.8-6.1-7.9-9.9
c-2.1-3.8-3.6-8-4.3-12.4c-0.3-2.2-0.5-4.5-0.4-6.7c0-0.6,0.1-1.2,0.1-1.8c0,0.2,0-0.1,0-0.1l0-0.2l0-0.5c0-0.3,0.1-0.6,0.1-0.9
c0.1-1.2,0.3-2.4,0.5-3.6c1.7-9.6,6.5-19,13.9-26.1c1.9-1.8,3.9-3.4,6-4.9c2.1-1.5,4.4-2.8,6.8-3.9c2.4-1.1,4.8-2,7.4-2.7
c2.5-0.7,5.1-1.1,7.8-1.4c1.3-0.1,2.6-0.2,4-0.2c0.4,0,0.6,0,0.9,0l1.1,0l0.7,0c0.3,0,0,0,0.1,0l0.3,0l1.1,0.1
c2.9,0.2,5.7,0.6,8.5,1.3c5.6,1.2,11.1,3.3,16.2,6.1c10.2,5.7,18.9,14.5,24.2,25.1c2.7,5.3,4.6,11,5.5,16.9c0.2,1.5,0.4,3,0.5,4.5
l0.1,1.1l0.1,1.1c0,0.4,0,0.8,0,1.1c0,0.4,0,0.8,0,1.1l0,1l0,1.1c0,0.7-0.1,1.9-0.1,2.6c-0.1,1.6-0.3,3.3-0.5,4.9
c-0.2,1.6-0.5,3.2-0.8,4.8c-0.3,1.6-0.7,3.2-1.1,4.7c-0.8,3.1-1.8,6.2-3,9.3c-2.4,6-5.6,11.8-9.4,17.1
c-7.7,10.6-18.2,19.2-30.2,24.7c-6,2.7-12.3,4.7-18.8,5.7c-3.2,0.6-6.5,0.9-9.8,1l-0.6,0l-0.5,0l-1.1,0l-1.6,0l-0.8,0
c0.4,0-0.1,0-0.1,0l-0.3,0c-1.8,0-3.5-0.1-5.3-0.3c-7-0.5-13.9-1.8-20.7-3.7c-6.7-1.9-13.2-4.6-19.4-7.8
c-12.3-6.6-23.4-15.6-32-26.5c-4.3-5.4-8.1-11.3-11.2-17.4c-3.1-6.1-5.6-12.6-7.4-19.1c-1.8-6.6-2.9-13.3-3.4-20.1l-0.1-1.3l0-0.3
l0-0.3l0-0.6l0-1.1l0-0.3l0-0.4l0-0.8l0-1.6l0-0.3c0,0,0,0.1,0-0.1l0-0.6c0-0.8,0-1.7,0-2.5c0.1-3.3,0.4-6.8,0.8-10.2
c0.4-3.4,1-6.9,1.7-10.3c0.7-3.4,1.5-6.8,2.5-10.2c1.9-6.7,4.3-13.2,7.1-19.3c5.7-12.2,13.1-23.1,22-31.8c2.2-2.2,4.5-4.2,6.9-6.2
c2.4-1.9,4.9-3.7,7.5-5.4c2.5-1.7,5.2-3.2,7.9-4.6c1.3-0.7,2.7-1.4,4.1-2c0.7-0.3,1.4-0.6,2.1-0.9c0.7-0.3,1.4-0.6,2.1-0.9
c2.8-1.2,5.7-2.2,8.7-3.1c0.7-0.2,1.5-0.4,2.2-0.7c0.7-0.2,1.5-0.4,2.2-0.6c1.5-0.4,3-0.8,4.5-1.1c0.7-0.2,1.5-0.3,2.3-0.5
c0.8-0.2,1.5-0.3,2.3-0.5c0.8-0.1,1.5-0.3,2.3-0.4l1.1-0.2l1.2-0.2c0.8-0.1,1.5-0.2,2.3-0.3c0.9-0.1,1.7-0.2,2.6-0.3
c0.7-0.1,1.9-0.2,2.6-0.3c0.5-0.1,1.1-0.1,1.6-0.2l1.1-0.1l0.5-0.1l0.6,0c0.9-0.1,1.7-0.1,2.6-0.2l1.3-0.1c0,0,0.5,0,0.1,0l0.3,0
l0.6,0c0.7,0,1.5-0.1,2.2-0.1c2.9-0.1,5.9-0.1,8.8,0c5.8,0.2,11.5,0.9,17,1.9c11.1,2.1,21.5,5.6,31,10.3
c9.5,4.6,17.9,10.3,25.3,16.5c0.5,0.4,0.9,0.8,1.4,1.2c0.4,0.4,0.9,0.8,1.3,1.2c0.9,0.8,1.7,1.6,2.6,2.4c0.9,0.8,1.7,1.6,2.5,2.4
c0.8,0.8,1.6,1.6,2.4,2.5c3.1,3.3,6,6.6,8.6,10c5.2,6.7,9.4,13.5,12.7,19.9c0.2,0.4,0.4,0.8,0.6,1.2c0.2,0.4,0.4,0.8,0.6,1.2
c0.4,0.8,0.8,1.6,1.1,2.4c0.4,0.8,0.7,1.5,1.1,2.3c0.3,0.8,0.7,1.5,1,2.3c1.2,3,2.4,5.9,3.3,8.6c1.5,4.4,2.6,8.3,3.5,11.7
c0.3,1.4,1.6,2.3,3,2.1c1.5-0.1,2.6-1.3,2.6-2.8C342.6,170.4,342.5,166.1,342,161.2z"/>
</svg>
| public/img/grafana_icon.svg | 0 | https://github.com/grafana/grafana/commit/09b434bdd08a65714e7fd09c802a0835c3261132 | [
0.0001761755847837776,
0.00016990579024422914,
0.0001639435940887779,
0.00017066372674889863,
0.000004235551386955194
]
|
{
"id": 0,
"code_window": [
"}\n",
"\n",
"func AddOrgInvite(c *m.ReqContext, inviteDto dtos.AddInviteForm) Response {\n",
"\tif setting.DisableLoginForm {\n",
"\t\treturn Error(400, \"Cannot invite when login is disabled.\", nil)\n",
"\t}\n",
"\n",
"\tif !inviteDto.Role.IsValid() {\n",
"\t\treturn Error(400, \"Invalid role specified\", nil)\n",
"\t}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "pkg/api/org_invite.go",
"type": "replace",
"edit_start_line_idx": 29
} | package api
import (
"github.com/grafana/grafana/pkg/api/dtos"
"github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/infra/metrics"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/util"
)
func AdminCreateUser(c *models.ReqContext, form dtos.AdminCreateUserForm) {
cmd := models.CreateUserCommand{
Login: form.Login,
Email: form.Email,
Password: form.Password,
Name: form.Name,
}
if len(cmd.Login) == 0 {
cmd.Login = cmd.Email
if len(cmd.Login) == 0 {
c.JsonApiErr(400, "Validation error, need specify either username or email", nil)
return
}
}
if len(cmd.Password) < 4 {
c.JsonApiErr(400, "Password is missing or too short", nil)
return
}
if err := bus.Dispatch(&cmd); err != nil {
c.JsonApiErr(500, "failed to create user", err)
return
}
metrics.MApiAdminUserCreate.Inc()
user := cmd.Result
result := models.UserIdDTO{
Message: "User created",
Id: user.Id,
}
c.JSON(200, result)
}
func AdminUpdateUserPassword(c *models.ReqContext, form dtos.AdminUpdateUserPasswordForm) {
userID := c.ParamsInt64(":id")
if len(form.Password) < 4 {
c.JsonApiErr(400, "New password too short", nil)
return
}
userQuery := models.GetUserByIdQuery{Id: userID}
if err := bus.Dispatch(&userQuery); err != nil {
c.JsonApiErr(500, "Could not read user from database", err)
return
}
passwordHashed := util.EncodePassword(form.Password, userQuery.Result.Salt)
cmd := models.ChangeUserPasswordCommand{
UserId: userID,
NewPassword: passwordHashed,
}
if err := bus.Dispatch(&cmd); err != nil {
c.JsonApiErr(500, "Failed to update user password", err)
return
}
c.JsonOK("User password updated")
}
// PUT /api/admin/users/:id/permissions
func AdminUpdateUserPermissions(c *models.ReqContext, form dtos.AdminUpdateUserPermissionsForm) {
userID := c.ParamsInt64(":id")
cmd := models.UpdateUserPermissionsCommand{
UserId: userID,
IsGrafanaAdmin: form.IsGrafanaAdmin,
}
if err := bus.Dispatch(&cmd); err != nil {
if err == models.ErrLastGrafanaAdmin {
c.JsonApiErr(400, models.ErrLastGrafanaAdmin.Error(), nil)
return
}
c.JsonApiErr(500, "Failed to update user permissions", err)
return
}
c.JsonOK("User permissions updated")
}
func AdminDeleteUser(c *models.ReqContext) {
userID := c.ParamsInt64(":id")
cmd := models.DeleteUserCommand{UserId: userID}
if err := bus.Dispatch(&cmd); err != nil {
c.JsonApiErr(500, "Failed to delete user", err)
return
}
c.JsonOK("User deleted")
}
// POST /api/admin/users/:id/disable
func (server *HTTPServer) AdminDisableUser(c *models.ReqContext) Response {
userID := c.ParamsInt64(":id")
// External users shouldn't be disabled from API
authInfoQuery := &models.GetAuthInfoQuery{UserId: userID}
if err := bus.Dispatch(authInfoQuery); err != models.ErrUserNotFound {
return Error(500, "Could not disable external user", nil)
}
disableCmd := models.DisableUserCommand{UserId: userID, IsDisabled: true}
if err := bus.Dispatch(&disableCmd); err != nil {
return Error(500, "Failed to disable user", err)
}
err := server.AuthTokenService.RevokeAllUserTokens(c.Req.Context(), userID)
if err != nil {
return Error(500, "Failed to disable user", err)
}
return Success("User disabled")
}
// POST /api/admin/users/:id/enable
func AdminEnableUser(c *models.ReqContext) Response {
userID := c.ParamsInt64(":id")
// External users shouldn't be disabled from API
authInfoQuery := &models.GetAuthInfoQuery{UserId: userID}
if err := bus.Dispatch(authInfoQuery); err != models.ErrUserNotFound {
return Error(500, "Could not enable external user", nil)
}
disableCmd := models.DisableUserCommand{UserId: userID, IsDisabled: false}
if err := bus.Dispatch(&disableCmd); err != nil {
return Error(500, "Failed to enable user", err)
}
return Success("User enabled")
}
// POST /api/admin/users/:id/logout
func (server *HTTPServer) AdminLogoutUser(c *models.ReqContext) Response {
userID := c.ParamsInt64(":id")
if c.UserId == userID {
return Error(400, "You cannot logout yourself", nil)
}
return server.logoutUserFromAllDevicesInternal(c.Req.Context(), userID)
}
// GET /api/admin/users/:id/auth-tokens
func (server *HTTPServer) AdminGetUserAuthTokens(c *models.ReqContext) Response {
userID := c.ParamsInt64(":id")
return server.getUserAuthTokensInternal(c, userID)
}
// POST /api/admin/users/:id/revoke-auth-token
func (server *HTTPServer) AdminRevokeUserAuthToken(c *models.ReqContext, cmd models.RevokeAuthTokenCmd) Response {
userID := c.ParamsInt64(":id")
return server.revokeUserAuthTokenInternal(c, userID, cmd)
}
| pkg/api/admin_users.go | 0 | https://github.com/grafana/grafana/commit/09b434bdd08a65714e7fd09c802a0835c3261132 | [
0.009166914969682693,
0.0008180963923223317,
0.00016929657431319356,
0.00018522988830227405,
0.0020599167328327894
]
|
{
"id": 1,
"code_window": [
"\t} else {\n",
"\t\treturn inviteExistingUserToOrg(c, userQuery.Result, &inviteDto)\n",
"\t}\n",
"\n",
"\tcmd := m.CreateTempUserCommand{}\n",
"\tcmd.OrgId = c.OrgId\n",
"\tcmd.Email = inviteDto.LoginOrEmail\n",
"\tcmd.Name = inviteDto.Name\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tif setting.DisableLoginForm {\n",
"\t\treturn Error(400, \"Cannot invite when login is disabled.\", nil)\n",
"\t}\n",
"\n"
],
"file_path": "pkg/api/org_invite.go",
"type": "add",
"edit_start_line_idx": 47
} | import { Invitee, OrgUser, UsersState } from 'app/types';
import { Action, ActionTypes } from './actions';
import config from 'app/core/config';
export const initialState: UsersState = {
invitees: [] as Invitee[],
users: [] as OrgUser[],
searchQuery: '',
canInvite: !config.disableLoginForm && !config.externalUserMngLinkName,
externalUserMngInfo: config.externalUserMngInfo,
externalUserMngLinkName: config.externalUserMngLinkName,
externalUserMngLinkUrl: config.externalUserMngLinkUrl,
hasFetched: false,
};
export const usersReducer = (state = initialState, action: Action): UsersState => {
switch (action.type) {
case ActionTypes.LoadUsers:
return { ...state, hasFetched: true, users: action.payload };
case ActionTypes.LoadInvitees:
return { ...state, hasFetched: true, invitees: action.payload };
case ActionTypes.SetUsersSearchQuery:
return { ...state, searchQuery: action.payload };
}
return state;
};
export default {
users: usersReducer,
};
| public/app/features/users/state/reducers.ts | 1 | https://github.com/grafana/grafana/commit/09b434bdd08a65714e7fd09c802a0835c3261132 | [
0.00017240543093066663,
0.00017102099081967026,
0.00016782261081971228,
0.00017192796804010868,
0.000001860206680248666
]
|
{
"id": 1,
"code_window": [
"\t} else {\n",
"\t\treturn inviteExistingUserToOrg(c, userQuery.Result, &inviteDto)\n",
"\t}\n",
"\n",
"\tcmd := m.CreateTempUserCommand{}\n",
"\tcmd.OrgId = c.OrgId\n",
"\tcmd.Email = inviteDto.LoginOrEmail\n",
"\tcmd.Name = inviteDto.Name\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tif setting.DisableLoginForm {\n",
"\t\treturn Error(400, \"Cannot invite when login is disabled.\", nil)\n",
"\t}\n",
"\n"
],
"file_path": "pkg/api/org_invite.go",
"type": "add",
"edit_start_line_idx": 47
} | package cp
var cp1253 *charsetMap = &charsetMap{
sb: [256]rune{
0x0000, //NULL
0x0001, //START OF HEADING
0x0002, //START OF TEXT
0x0003, //END OF TEXT
0x0004, //END OF TRANSMISSION
0x0005, //ENQUIRY
0x0006, //ACKNOWLEDGE
0x0007, //BELL
0x0008, //BACKSPACE
0x0009, //HORIZONTAL TABULATION
0x000A, //LINE FEED
0x000B, //VERTICAL TABULATION
0x000C, //FORM FEED
0x000D, //CARRIAGE RETURN
0x000E, //SHIFT OUT
0x000F, //SHIFT IN
0x0010, //DATA LINK ESCAPE
0x0011, //DEVICE CONTROL ONE
0x0012, //DEVICE CONTROL TWO
0x0013, //DEVICE CONTROL THREE
0x0014, //DEVICE CONTROL FOUR
0x0015, //NEGATIVE ACKNOWLEDGE
0x0016, //SYNCHRONOUS IDLE
0x0017, //END OF TRANSMISSION BLOCK
0x0018, //CANCEL
0x0019, //END OF MEDIUM
0x001A, //SUBSTITUTE
0x001B, //ESCAPE
0x001C, //FILE SEPARATOR
0x001D, //GROUP SEPARATOR
0x001E, //RECORD SEPARATOR
0x001F, //UNIT SEPARATOR
0x0020, //SPACE
0x0021, //EXCLAMATION MARK
0x0022, //QUOTATION MARK
0x0023, //NUMBER SIGN
0x0024, //DOLLAR SIGN
0x0025, //PERCENT SIGN
0x0026, //AMPERSAND
0x0027, //APOSTROPHE
0x0028, //LEFT PARENTHESIS
0x0029, //RIGHT PARENTHESIS
0x002A, //ASTERISK
0x002B, //PLUS SIGN
0x002C, //COMMA
0x002D, //HYPHEN-MINUS
0x002E, //FULL STOP
0x002F, //SOLIDUS
0x0030, //DIGIT ZERO
0x0031, //DIGIT ONE
0x0032, //DIGIT TWO
0x0033, //DIGIT THREE
0x0034, //DIGIT FOUR
0x0035, //DIGIT FIVE
0x0036, //DIGIT SIX
0x0037, //DIGIT SEVEN
0x0038, //DIGIT EIGHT
0x0039, //DIGIT NINE
0x003A, //COLON
0x003B, //SEMICOLON
0x003C, //LESS-THAN SIGN
0x003D, //EQUALS SIGN
0x003E, //GREATER-THAN SIGN
0x003F, //QUESTION MARK
0x0040, //COMMERCIAL AT
0x0041, //LATIN CAPITAL LETTER A
0x0042, //LATIN CAPITAL LETTER B
0x0043, //LATIN CAPITAL LETTER C
0x0044, //LATIN CAPITAL LETTER D
0x0045, //LATIN CAPITAL LETTER E
0x0046, //LATIN CAPITAL LETTER F
0x0047, //LATIN CAPITAL LETTER G
0x0048, //LATIN CAPITAL LETTER H
0x0049, //LATIN CAPITAL LETTER I
0x004A, //LATIN CAPITAL LETTER J
0x004B, //LATIN CAPITAL LETTER K
0x004C, //LATIN CAPITAL LETTER L
0x004D, //LATIN CAPITAL LETTER M
0x004E, //LATIN CAPITAL LETTER N
0x004F, //LATIN CAPITAL LETTER O
0x0050, //LATIN CAPITAL LETTER P
0x0051, //LATIN CAPITAL LETTER Q
0x0052, //LATIN CAPITAL LETTER R
0x0053, //LATIN CAPITAL LETTER S
0x0054, //LATIN CAPITAL LETTER T
0x0055, //LATIN CAPITAL LETTER U
0x0056, //LATIN CAPITAL LETTER V
0x0057, //LATIN CAPITAL LETTER W
0x0058, //LATIN CAPITAL LETTER X
0x0059, //LATIN CAPITAL LETTER Y
0x005A, //LATIN CAPITAL LETTER Z
0x005B, //LEFT SQUARE BRACKET
0x005C, //REVERSE SOLIDUS
0x005D, //RIGHT SQUARE BRACKET
0x005E, //CIRCUMFLEX ACCENT
0x005F, //LOW LINE
0x0060, //GRAVE ACCENT
0x0061, //LATIN SMALL LETTER A
0x0062, //LATIN SMALL LETTER B
0x0063, //LATIN SMALL LETTER C
0x0064, //LATIN SMALL LETTER D
0x0065, //LATIN SMALL LETTER E
0x0066, //LATIN SMALL LETTER F
0x0067, //LATIN SMALL LETTER G
0x0068, //LATIN SMALL LETTER H
0x0069, //LATIN SMALL LETTER I
0x006A, //LATIN SMALL LETTER J
0x006B, //LATIN SMALL LETTER K
0x006C, //LATIN SMALL LETTER L
0x006D, //LATIN SMALL LETTER M
0x006E, //LATIN SMALL LETTER N
0x006F, //LATIN SMALL LETTER O
0x0070, //LATIN SMALL LETTER P
0x0071, //LATIN SMALL LETTER Q
0x0072, //LATIN SMALL LETTER R
0x0073, //LATIN SMALL LETTER S
0x0074, //LATIN SMALL LETTER T
0x0075, //LATIN SMALL LETTER U
0x0076, //LATIN SMALL LETTER V
0x0077, //LATIN SMALL LETTER W
0x0078, //LATIN SMALL LETTER X
0x0079, //LATIN SMALL LETTER Y
0x007A, //LATIN SMALL LETTER Z
0x007B, //LEFT CURLY BRACKET
0x007C, //VERTICAL LINE
0x007D, //RIGHT CURLY BRACKET
0x007E, //TILDE
0x007F, //DELETE
0x20AC, //EURO SIGN
0xFFFD, //UNDEFINED
0x201A, //SINGLE LOW-9 QUOTATION MARK
0x0192, //LATIN SMALL LETTER F WITH HOOK
0x201E, //DOUBLE LOW-9 QUOTATION MARK
0x2026, //HORIZONTAL ELLIPSIS
0x2020, //DAGGER
0x2021, //DOUBLE DAGGER
0xFFFD, //UNDEFINED
0x2030, //PER MILLE SIGN
0xFFFD, //UNDEFINED
0x2039, //SINGLE LEFT-POINTING ANGLE QUOTATION MARK
0xFFFD, //UNDEFINED
0xFFFD, //UNDEFINED
0xFFFD, //UNDEFINED
0xFFFD, //UNDEFINED
0xFFFD, //UNDEFINED
0x2018, //LEFT SINGLE QUOTATION MARK
0x2019, //RIGHT SINGLE QUOTATION MARK
0x201C, //LEFT DOUBLE QUOTATION MARK
0x201D, //RIGHT DOUBLE QUOTATION MARK
0x2022, //BULLET
0x2013, //EN DASH
0x2014, //EM DASH
0xFFFD, //UNDEFINED
0x2122, //TRADE MARK SIGN
0xFFFD, //UNDEFINED
0x203A, //SINGLE RIGHT-POINTING ANGLE QUOTATION MARK
0xFFFD, //UNDEFINED
0xFFFD, //UNDEFINED
0xFFFD, //UNDEFINED
0xFFFD, //UNDEFINED
0x00A0, //NO-BREAK SPACE
0x0385, //GREEK DIALYTIKA TONOS
0x0386, //GREEK CAPITAL LETTER ALPHA WITH TONOS
0x00A3, //POUND SIGN
0x00A4, //CURRENCY SIGN
0x00A5, //YEN SIGN
0x00A6, //BROKEN BAR
0x00A7, //SECTION SIGN
0x00A8, //DIAERESIS
0x00A9, //COPYRIGHT SIGN
0xFFFD, //UNDEFINED
0x00AB, //LEFT-POINTING DOUBLE ANGLE QUOTATION MARK
0x00AC, //NOT SIGN
0x00AD, //SOFT HYPHEN
0x00AE, //REGISTERED SIGN
0x2015, //HORIZONTAL BAR
0x00B0, //DEGREE SIGN
0x00B1, //PLUS-MINUS SIGN
0x00B2, //SUPERSCRIPT TWO
0x00B3, //SUPERSCRIPT THREE
0x0384, //GREEK TONOS
0x00B5, //MICRO SIGN
0x00B6, //PILCROW SIGN
0x00B7, //MIDDLE DOT
0x0388, //GREEK CAPITAL LETTER EPSILON WITH TONOS
0x0389, //GREEK CAPITAL LETTER ETA WITH TONOS
0x038A, //GREEK CAPITAL LETTER IOTA WITH TONOS
0x00BB, //RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
0x038C, //GREEK CAPITAL LETTER OMICRON WITH TONOS
0x00BD, //VULGAR FRACTION ONE HALF
0x038E, //GREEK CAPITAL LETTER UPSILON WITH TONOS
0x038F, //GREEK CAPITAL LETTER OMEGA WITH TONOS
0x0390, //GREEK SMALL LETTER IOTA WITH DIALYTIKA AND TONOS
0x0391, //GREEK CAPITAL LETTER ALPHA
0x0392, //GREEK CAPITAL LETTER BETA
0x0393, //GREEK CAPITAL LETTER GAMMA
0x0394, //GREEK CAPITAL LETTER DELTA
0x0395, //GREEK CAPITAL LETTER EPSILON
0x0396, //GREEK CAPITAL LETTER ZETA
0x0397, //GREEK CAPITAL LETTER ETA
0x0398, //GREEK CAPITAL LETTER THETA
0x0399, //GREEK CAPITAL LETTER IOTA
0x039A, //GREEK CAPITAL LETTER KAPPA
0x039B, //GREEK CAPITAL LETTER LAMDA
0x039C, //GREEK CAPITAL LETTER MU
0x039D, //GREEK CAPITAL LETTER NU
0x039E, //GREEK CAPITAL LETTER XI
0x039F, //GREEK CAPITAL LETTER OMICRON
0x03A0, //GREEK CAPITAL LETTER PI
0x03A1, //GREEK CAPITAL LETTER RHO
0xFFFD, //UNDEFINED
0x03A3, //GREEK CAPITAL LETTER SIGMA
0x03A4, //GREEK CAPITAL LETTER TAU
0x03A5, //GREEK CAPITAL LETTER UPSILON
0x03A6, //GREEK CAPITAL LETTER PHI
0x03A7, //GREEK CAPITAL LETTER CHI
0x03A8, //GREEK CAPITAL LETTER PSI
0x03A9, //GREEK CAPITAL LETTER OMEGA
0x03AA, //GREEK CAPITAL LETTER IOTA WITH DIALYTIKA
0x03AB, //GREEK CAPITAL LETTER UPSILON WITH DIALYTIKA
0x03AC, //GREEK SMALL LETTER ALPHA WITH TONOS
0x03AD, //GREEK SMALL LETTER EPSILON WITH TONOS
0x03AE, //GREEK SMALL LETTER ETA WITH TONOS
0x03AF, //GREEK SMALL LETTER IOTA WITH TONOS
0x03B0, //GREEK SMALL LETTER UPSILON WITH DIALYTIKA AND TONOS
0x03B1, //GREEK SMALL LETTER ALPHA
0x03B2, //GREEK SMALL LETTER BETA
0x03B3, //GREEK SMALL LETTER GAMMA
0x03B4, //GREEK SMALL LETTER DELTA
0x03B5, //GREEK SMALL LETTER EPSILON
0x03B6, //GREEK SMALL LETTER ZETA
0x03B7, //GREEK SMALL LETTER ETA
0x03B8, //GREEK SMALL LETTER THETA
0x03B9, //GREEK SMALL LETTER IOTA
0x03BA, //GREEK SMALL LETTER KAPPA
0x03BB, //GREEK SMALL LETTER LAMDA
0x03BC, //GREEK SMALL LETTER MU
0x03BD, //GREEK SMALL LETTER NU
0x03BE, //GREEK SMALL LETTER XI
0x03BF, //GREEK SMALL LETTER OMICRON
0x03C0, //GREEK SMALL LETTER PI
0x03C1, //GREEK SMALL LETTER RHO
0x03C2, //GREEK SMALL LETTER FINAL SIGMA
0x03C3, //GREEK SMALL LETTER SIGMA
0x03C4, //GREEK SMALL LETTER TAU
0x03C5, //GREEK SMALL LETTER UPSILON
0x03C6, //GREEK SMALL LETTER PHI
0x03C7, //GREEK SMALL LETTER CHI
0x03C8, //GREEK SMALL LETTER PSI
0x03C9, //GREEK SMALL LETTER OMEGA
0x03CA, //GREEK SMALL LETTER IOTA WITH DIALYTIKA
0x03CB, //GREEK SMALL LETTER UPSILON WITH DIALYTIKA
0x03CC, //GREEK SMALL LETTER OMICRON WITH TONOS
0x03CD, //GREEK SMALL LETTER UPSILON WITH TONOS
0x03CE, //GREEK SMALL LETTER OMEGA WITH TONOS
0xFFFD, //UNDEFINED
},
}
| vendor/github.com/denisenkom/go-mssqldb/internal/cp/cp1253.go | 0 | https://github.com/grafana/grafana/commit/09b434bdd08a65714e7fd09c802a0835c3261132 | [
0.00017600903811398894,
0.0001678397093201056,
0.0001641618146095425,
0.0001677411637501791,
0.000002196290779465926
]
|
{
"id": 1,
"code_window": [
"\t} else {\n",
"\t\treturn inviteExistingUserToOrg(c, userQuery.Result, &inviteDto)\n",
"\t}\n",
"\n",
"\tcmd := m.CreateTempUserCommand{}\n",
"\tcmd.OrgId = c.OrgId\n",
"\tcmd.Email = inviteDto.LoginOrEmail\n",
"\tcmd.Name = inviteDto.Name\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tif setting.DisableLoginForm {\n",
"\t\treturn Error(400, \"Cannot invite when login is disabled.\", nil)\n",
"\t}\n",
"\n"
],
"file_path": "pkg/api/org_invite.go",
"type": "add",
"edit_start_line_idx": 47
} | {{.CommentFormat}}
func {{.DocInfo.Name}}f(t TestingT, {{.ParamsFormat}}) bool {
if h, ok := t.(tHelper); ok { h.Helper() }
return {{.DocInfo.Name}}(t, {{.ForwardedParamsFormat}})
}
| vendor/github.com/stretchr/testify/assert/assertion_format.go.tmpl | 0 | https://github.com/grafana/grafana/commit/09b434bdd08a65714e7fd09c802a0835c3261132 | [
0.00016482653154525906,
0.00016482653154525906,
0.00016482653154525906,
0.00016482653154525906,
0
]
|
{
"id": 1,
"code_window": [
"\t} else {\n",
"\t\treturn inviteExistingUserToOrg(c, userQuery.Result, &inviteDto)\n",
"\t}\n",
"\n",
"\tcmd := m.CreateTempUserCommand{}\n",
"\tcmd.OrgId = c.OrgId\n",
"\tcmd.Email = inviteDto.LoginOrEmail\n",
"\tcmd.Name = inviteDto.Name\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tif setting.DisableLoginForm {\n",
"\t\treturn Error(400, \"Cannot invite when login is disabled.\", nil)\n",
"\t}\n",
"\n"
],
"file_path": "pkg/api/org_invite.go",
"type": "add",
"edit_start_line_idx": 47
} | module.exports = {
src: {
files: [
//what are the files that we want to watch
'assets/css/*.css',
'templates/**/*.html',
'grunt/*.js',
],
tasks: ['default'],
options: {
nospawn: true,
livereload: false,
}
}
};
| emails/grunt/watch.js | 0 | https://github.com/grafana/grafana/commit/09b434bdd08a65714e7fd09c802a0835c3261132 | [
0.00017353883595205843,
0.00017228299111593515,
0.00017102714627981186,
0.00017228299111593515,
0.0000012558448361232877
]
|
{
"id": 2,
"code_window": [
"export const initialState: UsersState = {\n",
" invitees: [] as Invitee[],\n",
" users: [] as OrgUser[],\n",
" searchQuery: '',\n",
" canInvite: !config.disableLoginForm && !config.externalUserMngLinkName,\n",
" externalUserMngInfo: config.externalUserMngInfo,\n",
" externalUserMngLinkName: config.externalUserMngLinkName,\n",
" externalUserMngLinkUrl: config.externalUserMngLinkUrl,\n",
" hasFetched: false,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" canInvite: !config.externalUserMngLinkName,\n"
],
"file_path": "public/app/features/users/state/reducers.ts",
"type": "replace",
"edit_start_line_idx": 8
} | package api
import (
"fmt"
"github.com/grafana/grafana/pkg/api/dtos"
"github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/events"
"github.com/grafana/grafana/pkg/infra/metrics"
m "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/setting"
"github.com/grafana/grafana/pkg/util"
)
func GetPendingOrgInvites(c *m.ReqContext) Response {
query := m.GetTempUsersQuery{OrgId: c.OrgId, Status: m.TmpUserInvitePending}
if err := bus.Dispatch(&query); err != nil {
return Error(500, "Failed to get invites from db", err)
}
for _, invite := range query.Result {
invite.Url = setting.ToAbsUrl("invite/" + invite.Code)
}
return JSON(200, query.Result)
}
func AddOrgInvite(c *m.ReqContext, inviteDto dtos.AddInviteForm) Response {
if setting.DisableLoginForm {
return Error(400, "Cannot invite when login is disabled.", nil)
}
if !inviteDto.Role.IsValid() {
return Error(400, "Invalid role specified", nil)
}
// first try get existing user
userQuery := m.GetUserByLoginQuery{LoginOrEmail: inviteDto.LoginOrEmail}
if err := bus.Dispatch(&userQuery); err != nil {
if err != m.ErrUserNotFound {
return Error(500, "Failed to query db for existing user check", err)
}
} else {
return inviteExistingUserToOrg(c, userQuery.Result, &inviteDto)
}
cmd := m.CreateTempUserCommand{}
cmd.OrgId = c.OrgId
cmd.Email = inviteDto.LoginOrEmail
cmd.Name = inviteDto.Name
cmd.Status = m.TmpUserInvitePending
cmd.InvitedByUserId = c.UserId
cmd.Code = util.GetRandomString(30)
cmd.Role = inviteDto.Role
cmd.RemoteAddr = c.Req.RemoteAddr
if err := bus.Dispatch(&cmd); err != nil {
return Error(500, "Failed to save invite to database", err)
}
// send invite email
if inviteDto.SendEmail && util.IsEmail(inviteDto.LoginOrEmail) {
emailCmd := m.SendEmailCommand{
To: []string{inviteDto.LoginOrEmail},
Template: "new_user_invite.html",
Data: map[string]interface{}{
"Name": util.StringsFallback2(cmd.Name, cmd.Email),
"OrgName": c.OrgName,
"Email": c.Email,
"LinkUrl": setting.ToAbsUrl("invite/" + cmd.Code),
"InvitedBy": util.StringsFallback3(c.Name, c.Email, c.Login),
},
}
if err := bus.Dispatch(&emailCmd); err != nil {
if err == m.ErrSmtpNotEnabled {
return Error(412, err.Error(), err)
}
return Error(500, "Failed to send email invite", err)
}
emailSentCmd := m.UpdateTempUserWithEmailSentCommand{Code: cmd.Result.Code}
if err := bus.Dispatch(&emailSentCmd); err != nil {
return Error(500, "Failed to update invite with email sent info", err)
}
return Success(fmt.Sprintf("Sent invite to %s", inviteDto.LoginOrEmail))
}
return Success(fmt.Sprintf("Created invite for %s", inviteDto.LoginOrEmail))
}
func inviteExistingUserToOrg(c *m.ReqContext, user *m.User, inviteDto *dtos.AddInviteForm) Response {
// user exists, add org role
createOrgUserCmd := m.AddOrgUserCommand{OrgId: c.OrgId, UserId: user.Id, Role: inviteDto.Role}
if err := bus.Dispatch(&createOrgUserCmd); err != nil {
if err == m.ErrOrgUserAlreadyAdded {
return Error(412, fmt.Sprintf("User %s is already added to organization", inviteDto.LoginOrEmail), err)
}
return Error(500, "Error while trying to create org user", err)
}
if inviteDto.SendEmail && util.IsEmail(user.Email) {
emailCmd := m.SendEmailCommand{
To: []string{user.Email},
Template: "invited_to_org.html",
Data: map[string]interface{}{
"Name": user.NameOrFallback(),
"OrgName": c.OrgName,
"InvitedBy": util.StringsFallback3(c.Name, c.Email, c.Login),
},
}
if err := bus.Dispatch(&emailCmd); err != nil {
return Error(500, "Failed to send email invited_to_org", err)
}
}
return Success(fmt.Sprintf("Existing Grafana user %s added to org %s", user.NameOrFallback(), c.OrgName))
}
func RevokeInvite(c *m.ReqContext) Response {
if ok, rsp := updateTempUserStatus(c.Params(":code"), m.TmpUserRevoked); !ok {
return rsp
}
return Success("Invite revoked")
}
func GetInviteInfoByCode(c *m.ReqContext) Response {
query := m.GetTempUserByCodeQuery{Code: c.Params(":code")}
if err := bus.Dispatch(&query); err != nil {
if err == m.ErrTempUserNotFound {
return Error(404, "Invite not found", nil)
}
return Error(500, "Failed to get invite", err)
}
invite := query.Result
return JSON(200, dtos.InviteInfo{
Email: invite.Email,
Name: invite.Name,
Username: invite.Email,
InvitedBy: util.StringsFallback3(invite.InvitedByName, invite.InvitedByLogin, invite.InvitedByEmail),
})
}
func (hs *HTTPServer) CompleteInvite(c *m.ReqContext, completeInvite dtos.CompleteInviteForm) Response {
query := m.GetTempUserByCodeQuery{Code: completeInvite.InviteCode}
if err := bus.Dispatch(&query); err != nil {
if err == m.ErrTempUserNotFound {
return Error(404, "Invite not found", nil)
}
return Error(500, "Failed to get invite", err)
}
invite := query.Result
if invite.Status != m.TmpUserInvitePending {
return Error(412, fmt.Sprintf("Invite cannot be used in status %s", invite.Status), nil)
}
cmd := m.CreateUserCommand{
Email: completeInvite.Email,
Name: completeInvite.Name,
Login: completeInvite.Username,
Password: completeInvite.Password,
SkipOrgSetup: true,
}
if err := bus.Dispatch(&cmd); err != nil {
return Error(500, "failed to create user", err)
}
user := &cmd.Result
bus.Publish(&events.SignUpCompleted{
Name: user.NameOrFallback(),
Email: user.Email,
})
if ok, rsp := applyUserInvite(user, invite, true); !ok {
return rsp
}
hs.loginUserWithUser(user, c)
metrics.MApiUserSignUpCompleted.Inc()
metrics.MApiUserSignUpInvite.Inc()
return Success("User created and logged in")
}
func updateTempUserStatus(code string, status m.TempUserStatus) (bool, Response) {
// update temp user status
updateTmpUserCmd := m.UpdateTempUserStatusCommand{Code: code, Status: status}
if err := bus.Dispatch(&updateTmpUserCmd); err != nil {
return false, Error(500, "Failed to update invite status", err)
}
return true, nil
}
func applyUserInvite(user *m.User, invite *m.TempUserDTO, setActive bool) (bool, Response) {
// add to org
addOrgUserCmd := m.AddOrgUserCommand{OrgId: invite.OrgId, UserId: user.Id, Role: invite.Role}
if err := bus.Dispatch(&addOrgUserCmd); err != nil {
if err != m.ErrOrgUserAlreadyAdded {
return false, Error(500, "Error while trying to create org user", err)
}
}
// update temp user status
if ok, rsp := updateTempUserStatus(invite.Code, m.TmpUserCompleted); !ok {
return false, rsp
}
if setActive {
// set org to active
if err := bus.Dispatch(&m.SetUsingOrgCommand{OrgId: invite.OrgId, UserId: user.Id}); err != nil {
return false, Error(500, "Failed to set org as active", err)
}
}
return true, nil
}
| pkg/api/org_invite.go | 1 | https://github.com/grafana/grafana/commit/09b434bdd08a65714e7fd09c802a0835c3261132 | [
0.004677393939346075,
0.0004822338523808867,
0.00016645551659166813,
0.00023503809643443674,
0.000915293931029737
]
|
{
"id": 2,
"code_window": [
"export const initialState: UsersState = {\n",
" invitees: [] as Invitee[],\n",
" users: [] as OrgUser[],\n",
" searchQuery: '',\n",
" canInvite: !config.disableLoginForm && !config.externalUserMngLinkName,\n",
" externalUserMngInfo: config.externalUserMngInfo,\n",
" externalUserMngLinkName: config.externalUserMngLinkName,\n",
" externalUserMngLinkUrl: config.externalUserMngLinkUrl,\n",
" hasFetched: false,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" canInvite: !config.externalUserMngLinkName,\n"
],
"file_path": "public/app/features/users/state/reducers.ts",
"type": "replace",
"edit_start_line_idx": 8
} | // mkerrors.sh -m64
// Code generated by the command above; see README.md. DO NOT EDIT.
// +build amd64,dragonfly
// Code generated by cmd/cgo -godefs; DO NOT EDIT.
// cgo -godefs -- -m64 _const.go
package unix
import "syscall"
const (
AF_APPLETALK = 0x10
AF_ATM = 0x1e
AF_BLUETOOTH = 0x21
AF_CCITT = 0xa
AF_CHAOS = 0x5
AF_CNT = 0x15
AF_COIP = 0x14
AF_DATAKIT = 0x9
AF_DECnet = 0xc
AF_DLI = 0xd
AF_E164 = 0x1a
AF_ECMA = 0x8
AF_HYLINK = 0xf
AF_IEEE80211 = 0x23
AF_IMPLINK = 0x3
AF_INET = 0x2
AF_INET6 = 0x1c
AF_IPX = 0x17
AF_ISDN = 0x1a
AF_ISO = 0x7
AF_LAT = 0xe
AF_LINK = 0x12
AF_LOCAL = 0x1
AF_MAX = 0x24
AF_MPLS = 0x22
AF_NATM = 0x1d
AF_NETBIOS = 0x6
AF_NETGRAPH = 0x20
AF_OSI = 0x7
AF_PUP = 0x4
AF_ROUTE = 0x11
AF_SIP = 0x18
AF_SNA = 0xb
AF_UNIX = 0x1
AF_UNSPEC = 0x0
ALTWERASE = 0x200
B0 = 0x0
B110 = 0x6e
B115200 = 0x1c200
B1200 = 0x4b0
B134 = 0x86
B14400 = 0x3840
B150 = 0x96
B1800 = 0x708
B19200 = 0x4b00
B200 = 0xc8
B230400 = 0x38400
B2400 = 0x960
B28800 = 0x7080
B300 = 0x12c
B38400 = 0x9600
B4800 = 0x12c0
B50 = 0x32
B57600 = 0xe100
B600 = 0x258
B7200 = 0x1c20
B75 = 0x4b
B76800 = 0x12c00
B9600 = 0x2580
BIOCFLUSH = 0x20004268
BIOCGBLEN = 0x40044266
BIOCGDLT = 0x4004426a
BIOCGDLTLIST = 0xc0104279
BIOCGETIF = 0x4020426b
BIOCGHDRCMPLT = 0x40044274
BIOCGRSIG = 0x40044272
BIOCGRTIMEOUT = 0x4010426e
BIOCGSEESENT = 0x40044276
BIOCGSTATS = 0x4008426f
BIOCIMMEDIATE = 0x80044270
BIOCLOCK = 0x2000427a
BIOCPROMISC = 0x20004269
BIOCSBLEN = 0xc0044266
BIOCSDLT = 0x80044278
BIOCSETF = 0x80104267
BIOCSETIF = 0x8020426c
BIOCSETWF = 0x8010427b
BIOCSHDRCMPLT = 0x80044275
BIOCSRSIG = 0x80044273
BIOCSRTIMEOUT = 0x8010426d
BIOCSSEESENT = 0x80044277
BIOCVERSION = 0x40044271
BPF_A = 0x10
BPF_ABS = 0x20
BPF_ADD = 0x0
BPF_ALIGNMENT = 0x8
BPF_ALU = 0x4
BPF_AND = 0x50
BPF_B = 0x10
BPF_DEFAULTBUFSIZE = 0x1000
BPF_DIV = 0x30
BPF_H = 0x8
BPF_IMM = 0x0
BPF_IND = 0x40
BPF_JA = 0x0
BPF_JEQ = 0x10
BPF_JGE = 0x30
BPF_JGT = 0x20
BPF_JMP = 0x5
BPF_JSET = 0x40
BPF_K = 0x0
BPF_LD = 0x0
BPF_LDX = 0x1
BPF_LEN = 0x80
BPF_LSH = 0x60
BPF_MAJOR_VERSION = 0x1
BPF_MAXBUFSIZE = 0x80000
BPF_MAXINSNS = 0x200
BPF_MAX_CLONES = 0x80
BPF_MEM = 0x60
BPF_MEMWORDS = 0x10
BPF_MINBUFSIZE = 0x20
BPF_MINOR_VERSION = 0x1
BPF_MISC = 0x7
BPF_MSH = 0xa0
BPF_MUL = 0x20
BPF_NEG = 0x80
BPF_OR = 0x40
BPF_RELEASE = 0x30bb6
BPF_RET = 0x6
BPF_RSH = 0x70
BPF_ST = 0x2
BPF_STX = 0x3
BPF_SUB = 0x10
BPF_TAX = 0x0
BPF_TXA = 0x80
BPF_W = 0x0
BPF_X = 0x8
BRKINT = 0x2
CFLUSH = 0xf
CLOCAL = 0x8000
CLOCK_MONOTONIC = 0x4
CLOCK_MONOTONIC_FAST = 0xc
CLOCK_MONOTONIC_PRECISE = 0xb
CLOCK_PROCESS_CPUTIME_ID = 0xf
CLOCK_PROF = 0x2
CLOCK_REALTIME = 0x0
CLOCK_REALTIME_FAST = 0xa
CLOCK_REALTIME_PRECISE = 0x9
CLOCK_SECOND = 0xd
CLOCK_THREAD_CPUTIME_ID = 0xe
CLOCK_UPTIME = 0x5
CLOCK_UPTIME_FAST = 0x8
CLOCK_UPTIME_PRECISE = 0x7
CLOCK_VIRTUAL = 0x1
CREAD = 0x800
CRTSCTS = 0x30000
CS5 = 0x0
CS6 = 0x100
CS7 = 0x200
CS8 = 0x300
CSIZE = 0x300
CSTART = 0x11
CSTATUS = 0x14
CSTOP = 0x13
CSTOPB = 0x400
CSUSP = 0x1a
CTL_HW = 0x6
CTL_KERN = 0x1
CTL_MAXNAME = 0xc
CTL_NET = 0x4
DLT_A429 = 0xb8
DLT_A653_ICM = 0xb9
DLT_AIRONET_HEADER = 0x78
DLT_APPLE_IP_OVER_IEEE1394 = 0x8a
DLT_ARCNET = 0x7
DLT_ARCNET_LINUX = 0x81
DLT_ATM_CLIP = 0x13
DLT_ATM_RFC1483 = 0xb
DLT_AURORA = 0x7e
DLT_AX25 = 0x3
DLT_AX25_KISS = 0xca
DLT_BACNET_MS_TP = 0xa5
DLT_BLUETOOTH_HCI_H4 = 0xbb
DLT_BLUETOOTH_HCI_H4_WITH_PHDR = 0xc9
DLT_CAN20B = 0xbe
DLT_CHAOS = 0x5
DLT_CHDLC = 0x68
DLT_CISCO_IOS = 0x76
DLT_C_HDLC = 0x68
DLT_C_HDLC_WITH_DIR = 0xcd
DLT_DOCSIS = 0x8f
DLT_ECONET = 0x73
DLT_EN10MB = 0x1
DLT_EN3MB = 0x2
DLT_ENC = 0x6d
DLT_ERF = 0xc5
DLT_ERF_ETH = 0xaf
DLT_ERF_POS = 0xb0
DLT_FDDI = 0xa
DLT_FLEXRAY = 0xd2
DLT_FRELAY = 0x6b
DLT_FRELAY_WITH_DIR = 0xce
DLT_GCOM_SERIAL = 0xad
DLT_GCOM_T1E1 = 0xac
DLT_GPF_F = 0xab
DLT_GPF_T = 0xaa
DLT_GPRS_LLC = 0xa9
DLT_HHDLC = 0x79
DLT_IBM_SN = 0x92
DLT_IBM_SP = 0x91
DLT_IEEE802 = 0x6
DLT_IEEE802_11 = 0x69
DLT_IEEE802_11_RADIO = 0x7f
DLT_IEEE802_11_RADIO_AVS = 0xa3
DLT_IEEE802_15_4 = 0xc3
DLT_IEEE802_15_4_LINUX = 0xbf
DLT_IEEE802_15_4_NONASK_PHY = 0xd7
DLT_IEEE802_16_MAC_CPS = 0xbc
DLT_IEEE802_16_MAC_CPS_RADIO = 0xc1
DLT_IPFILTER = 0x74
DLT_IPMB = 0xc7
DLT_IPMB_LINUX = 0xd1
DLT_IP_OVER_FC = 0x7a
DLT_JUNIPER_ATM1 = 0x89
DLT_JUNIPER_ATM2 = 0x87
DLT_JUNIPER_CHDLC = 0xb5
DLT_JUNIPER_ES = 0x84
DLT_JUNIPER_ETHER = 0xb2
DLT_JUNIPER_FRELAY = 0xb4
DLT_JUNIPER_GGSN = 0x85
DLT_JUNIPER_ISM = 0xc2
DLT_JUNIPER_MFR = 0x86
DLT_JUNIPER_MLFR = 0x83
DLT_JUNIPER_MLPPP = 0x82
DLT_JUNIPER_MONITOR = 0xa4
DLT_JUNIPER_PIC_PEER = 0xae
DLT_JUNIPER_PPP = 0xb3
DLT_JUNIPER_PPPOE = 0xa7
DLT_JUNIPER_PPPOE_ATM = 0xa8
DLT_JUNIPER_SERVICES = 0x88
DLT_JUNIPER_ST = 0xc8
DLT_JUNIPER_VP = 0xb7
DLT_LAPB_WITH_DIR = 0xcf
DLT_LAPD = 0xcb
DLT_LIN = 0xd4
DLT_LINUX_IRDA = 0x90
DLT_LINUX_LAPD = 0xb1
DLT_LINUX_SLL = 0x71
DLT_LOOP = 0x6c
DLT_LTALK = 0x72
DLT_MFR = 0xb6
DLT_MOST = 0xd3
DLT_MTP2 = 0x8c
DLT_MTP2_WITH_PHDR = 0x8b
DLT_MTP3 = 0x8d
DLT_NULL = 0x0
DLT_PCI_EXP = 0x7d
DLT_PFLOG = 0x75
DLT_PFSYNC = 0x12
DLT_PPI = 0xc0
DLT_PPP = 0x9
DLT_PPP_BSDOS = 0x10
DLT_PPP_ETHER = 0x33
DLT_PPP_PPPD = 0xa6
DLT_PPP_SERIAL = 0x32
DLT_PPP_WITH_DIR = 0xcc
DLT_PRISM_HEADER = 0x77
DLT_PRONET = 0x4
DLT_RAIF1 = 0xc6
DLT_RAW = 0xc
DLT_REDBACK_SMARTEDGE = 0x20
DLT_RIO = 0x7c
DLT_SCCP = 0x8e
DLT_SITA = 0xc4
DLT_SLIP = 0x8
DLT_SLIP_BSDOS = 0xf
DLT_SUNATM = 0x7b
DLT_SYMANTEC_FIREWALL = 0x63
DLT_TZSP = 0x80
DLT_USB = 0xba
DLT_USB_LINUX = 0xbd
DLT_X2E_SERIAL = 0xd5
DLT_X2E_XORAYA = 0xd6
DT_BLK = 0x6
DT_CHR = 0x2
DT_DBF = 0xf
DT_DIR = 0x4
DT_FIFO = 0x1
DT_LNK = 0xa
DT_REG = 0x8
DT_SOCK = 0xc
DT_UNKNOWN = 0x0
DT_WHT = 0xe
ECHO = 0x8
ECHOCTL = 0x40
ECHOE = 0x2
ECHOK = 0x4
ECHOKE = 0x1
ECHONL = 0x10
ECHOPRT = 0x20
EVFILT_AIO = -0x3
EVFILT_EXCEPT = -0x8
EVFILT_FS = -0xa
EVFILT_MARKER = 0xf
EVFILT_PROC = -0x5
EVFILT_READ = -0x1
EVFILT_SIGNAL = -0x6
EVFILT_SYSCOUNT = 0xa
EVFILT_TIMER = -0x7
EVFILT_USER = -0x9
EVFILT_VNODE = -0x4
EVFILT_WRITE = -0x2
EV_ADD = 0x1
EV_CLEAR = 0x20
EV_DELETE = 0x2
EV_DISABLE = 0x8
EV_DISPATCH = 0x80
EV_ENABLE = 0x4
EV_EOF = 0x8000
EV_ERROR = 0x4000
EV_FLAG1 = 0x2000
EV_NODATA = 0x1000
EV_ONESHOT = 0x10
EV_RECEIPT = 0x40
EV_SYSFLAGS = 0xf000
EXTA = 0x4b00
EXTB = 0x9600
EXTEXIT_LWP = 0x10000
EXTEXIT_PROC = 0x0
EXTEXIT_SETINT = 0x1
EXTEXIT_SIMPLE = 0x0
EXTPROC = 0x800
FD_CLOEXEC = 0x1
FD_SETSIZE = 0x400
FLUSHO = 0x800000
F_DUP2FD = 0xa
F_DUP2FD_CLOEXEC = 0x12
F_DUPFD = 0x0
F_DUPFD_CLOEXEC = 0x11
F_GETFD = 0x1
F_GETFL = 0x3
F_GETLK = 0x7
F_GETOWN = 0x5
F_OK = 0x0
F_RDLCK = 0x1
F_SETFD = 0x2
F_SETFL = 0x4
F_SETLK = 0x8
F_SETLKW = 0x9
F_SETOWN = 0x6
F_UNLCK = 0x2
F_WRLCK = 0x3
HUPCL = 0x4000
HW_MACHINE = 0x1
ICANON = 0x100
ICMP6_FILTER = 0x12
ICRNL = 0x100
IEXTEN = 0x400
IFAN_ARRIVAL = 0x0
IFAN_DEPARTURE = 0x1
IFF_ALLMULTI = 0x200
IFF_ALTPHYS = 0x4000
IFF_BROADCAST = 0x2
IFF_CANTCHANGE = 0x118e72
IFF_DEBUG = 0x4
IFF_LINK0 = 0x1000
IFF_LINK1 = 0x2000
IFF_LINK2 = 0x4000
IFF_LOOPBACK = 0x8
IFF_MONITOR = 0x40000
IFF_MULTICAST = 0x8000
IFF_NOARP = 0x80
IFF_NPOLLING = 0x100000
IFF_OACTIVE = 0x400
IFF_OACTIVE_COMPAT = 0x400
IFF_POINTOPOINT = 0x10
IFF_POLLING = 0x10000
IFF_POLLING_COMPAT = 0x10000
IFF_PPROMISC = 0x20000
IFF_PROMISC = 0x100
IFF_RUNNING = 0x40
IFF_SIMPLEX = 0x800
IFF_SMART = 0x20
IFF_STATICARP = 0x80000
IFF_UP = 0x1
IFNAMSIZ = 0x10
IFT_1822 = 0x2
IFT_A12MPPSWITCH = 0x82
IFT_AAL2 = 0xbb
IFT_AAL5 = 0x31
IFT_ADSL = 0x5e
IFT_AFLANE8023 = 0x3b
IFT_AFLANE8025 = 0x3c
IFT_ARAP = 0x58
IFT_ARCNET = 0x23
IFT_ARCNETPLUS = 0x24
IFT_ASYNC = 0x54
IFT_ATM = 0x25
IFT_ATMDXI = 0x69
IFT_ATMFUNI = 0x6a
IFT_ATMIMA = 0x6b
IFT_ATMLOGICAL = 0x50
IFT_ATMRADIO = 0xbd
IFT_ATMSUBINTERFACE = 0x86
IFT_ATMVCIENDPT = 0xc2
IFT_ATMVIRTUAL = 0x95
IFT_BGPPOLICYACCOUNTING = 0xa2
IFT_BRIDGE = 0xd1
IFT_BSC = 0x53
IFT_CARP = 0xf8
IFT_CCTEMUL = 0x3d
IFT_CEPT = 0x13
IFT_CES = 0x85
IFT_CHANNEL = 0x46
IFT_CNR = 0x55
IFT_COFFEE = 0x84
IFT_COMPOSITELINK = 0x9b
IFT_DCN = 0x8d
IFT_DIGITALPOWERLINE = 0x8a
IFT_DIGITALWRAPPEROVERHEADCHANNEL = 0xba
IFT_DLSW = 0x4a
IFT_DOCSCABLEDOWNSTREAM = 0x80
IFT_DOCSCABLEMACLAYER = 0x7f
IFT_DOCSCABLEUPSTREAM = 0x81
IFT_DS0 = 0x51
IFT_DS0BUNDLE = 0x52
IFT_DS1FDL = 0xaa
IFT_DS3 = 0x1e
IFT_DTM = 0x8c
IFT_DVBASILN = 0xac
IFT_DVBASIOUT = 0xad
IFT_DVBRCCDOWNSTREAM = 0x93
IFT_DVBRCCMACLAYER = 0x92
IFT_DVBRCCUPSTREAM = 0x94
IFT_ENC = 0xf4
IFT_EON = 0x19
IFT_EPLRS = 0x57
IFT_ESCON = 0x49
IFT_ETHER = 0x6
IFT_FAITH = 0xf2
IFT_FAST = 0x7d
IFT_FASTETHER = 0x3e
IFT_FASTETHERFX = 0x45
IFT_FDDI = 0xf
IFT_FIBRECHANNEL = 0x38
IFT_FRAMERELAYINTERCONNECT = 0x3a
IFT_FRAMERELAYMPI = 0x5c
IFT_FRDLCIENDPT = 0xc1
IFT_FRELAY = 0x20
IFT_FRELAYDCE = 0x2c
IFT_FRF16MFRBUNDLE = 0xa3
IFT_FRFORWARD = 0x9e
IFT_G703AT2MB = 0x43
IFT_G703AT64K = 0x42
IFT_GIF = 0xf0
IFT_GIGABITETHERNET = 0x75
IFT_GR303IDT = 0xb2
IFT_GR303RDT = 0xb1
IFT_H323GATEKEEPER = 0xa4
IFT_H323PROXY = 0xa5
IFT_HDH1822 = 0x3
IFT_HDLC = 0x76
IFT_HDSL2 = 0xa8
IFT_HIPERLAN2 = 0xb7
IFT_HIPPI = 0x2f
IFT_HIPPIINTERFACE = 0x39
IFT_HOSTPAD = 0x5a
IFT_HSSI = 0x2e
IFT_HY = 0xe
IFT_IBM370PARCHAN = 0x48
IFT_IDSL = 0x9a
IFT_IEEE1394 = 0x90
IFT_IEEE80211 = 0x47
IFT_IEEE80212 = 0x37
IFT_IEEE8023ADLAG = 0xa1
IFT_IFGSN = 0x91
IFT_IMT = 0xbe
IFT_INTERLEAVE = 0x7c
IFT_IP = 0x7e
IFT_IPFORWARD = 0x8e
IFT_IPOVERATM = 0x72
IFT_IPOVERCDLC = 0x6d
IFT_IPOVERCLAW = 0x6e
IFT_IPSWITCH = 0x4e
IFT_ISDN = 0x3f
IFT_ISDNBASIC = 0x14
IFT_ISDNPRIMARY = 0x15
IFT_ISDNS = 0x4b
IFT_ISDNU = 0x4c
IFT_ISO88022LLC = 0x29
IFT_ISO88023 = 0x7
IFT_ISO88024 = 0x8
IFT_ISO88025 = 0x9
IFT_ISO88025CRFPINT = 0x62
IFT_ISO88025DTR = 0x56
IFT_ISO88025FIBER = 0x73
IFT_ISO88026 = 0xa
IFT_ISUP = 0xb3
IFT_L2VLAN = 0x87
IFT_L3IPVLAN = 0x88
IFT_L3IPXVLAN = 0x89
IFT_LAPB = 0x10
IFT_LAPD = 0x4d
IFT_LAPF = 0x77
IFT_LOCALTALK = 0x2a
IFT_LOOP = 0x18
IFT_MEDIAMAILOVERIP = 0x8b
IFT_MFSIGLINK = 0xa7
IFT_MIOX25 = 0x26
IFT_MODEM = 0x30
IFT_MPC = 0x71
IFT_MPLS = 0xa6
IFT_MPLSTUNNEL = 0x96
IFT_MSDSL = 0x8f
IFT_MVL = 0xbf
IFT_MYRINET = 0x63
IFT_NFAS = 0xaf
IFT_NSIP = 0x1b
IFT_OPTICALCHANNEL = 0xc3
IFT_OPTICALTRANSPORT = 0xc4
IFT_OTHER = 0x1
IFT_P10 = 0xc
IFT_P80 = 0xd
IFT_PARA = 0x22
IFT_PFLOG = 0xf5
IFT_PFSYNC = 0xf6
IFT_PLC = 0xae
IFT_POS = 0xab
IFT_PPP = 0x17
IFT_PPPMULTILINKBUNDLE = 0x6c
IFT_PROPBWAP2MP = 0xb8
IFT_PROPCNLS = 0x59
IFT_PROPDOCSWIRELESSDOWNSTREAM = 0xb5
IFT_PROPDOCSWIRELESSMACLAYER = 0xb4
IFT_PROPDOCSWIRELESSUPSTREAM = 0xb6
IFT_PROPMUX = 0x36
IFT_PROPVIRTUAL = 0x35
IFT_PROPWIRELESSP2P = 0x9d
IFT_PTPSERIAL = 0x16
IFT_PVC = 0xf1
IFT_QLLC = 0x44
IFT_RADIOMAC = 0xbc
IFT_RADSL = 0x5f
IFT_REACHDSL = 0xc0
IFT_RFC1483 = 0x9f
IFT_RS232 = 0x21
IFT_RSRB = 0x4f
IFT_SDLC = 0x11
IFT_SDSL = 0x60
IFT_SHDSL = 0xa9
IFT_SIP = 0x1f
IFT_SLIP = 0x1c
IFT_SMDSDXI = 0x2b
IFT_SMDSICIP = 0x34
IFT_SONET = 0x27
IFT_SONETOVERHEADCHANNEL = 0xb9
IFT_SONETPATH = 0x32
IFT_SONETVT = 0x33
IFT_SRP = 0x97
IFT_SS7SIGLINK = 0x9c
IFT_STACKTOSTACK = 0x6f
IFT_STARLAN = 0xb
IFT_STF = 0xf3
IFT_T1 = 0x12
IFT_TDLC = 0x74
IFT_TERMPAD = 0x5b
IFT_TR008 = 0xb0
IFT_TRANSPHDLC = 0x7b
IFT_TUNNEL = 0x83
IFT_ULTRA = 0x1d
IFT_USB = 0xa0
IFT_V11 = 0x40
IFT_V35 = 0x2d
IFT_V36 = 0x41
IFT_V37 = 0x78
IFT_VDSL = 0x61
IFT_VIRTUALIPADDRESS = 0x70
IFT_VOICEEM = 0x64
IFT_VOICEENCAP = 0x67
IFT_VOICEFXO = 0x65
IFT_VOICEFXS = 0x66
IFT_VOICEOVERATM = 0x98
IFT_VOICEOVERFRAMERELAY = 0x99
IFT_VOICEOVERIP = 0x68
IFT_X213 = 0x5d
IFT_X25 = 0x5
IFT_X25DDN = 0x4
IFT_X25HUNTGROUP = 0x7a
IFT_X25MLP = 0x79
IFT_X25PLE = 0x28
IFT_XETHER = 0x1a
IGNBRK = 0x1
IGNCR = 0x80
IGNPAR = 0x4
IMAXBEL = 0x2000
INLCR = 0x40
INPCK = 0x10
IN_CLASSA_HOST = 0xffffff
IN_CLASSA_MAX = 0x80
IN_CLASSA_NET = 0xff000000
IN_CLASSA_NSHIFT = 0x18
IN_CLASSB_HOST = 0xffff
IN_CLASSB_MAX = 0x10000
IN_CLASSB_NET = 0xffff0000
IN_CLASSB_NSHIFT = 0x10
IN_CLASSC_HOST = 0xff
IN_CLASSC_NET = 0xffffff00
IN_CLASSC_NSHIFT = 0x8
IN_CLASSD_HOST = 0xfffffff
IN_CLASSD_NET = 0xf0000000
IN_CLASSD_NSHIFT = 0x1c
IN_LOOPBACKNET = 0x7f
IPPROTO_3PC = 0x22
IPPROTO_ADFS = 0x44
IPPROTO_AH = 0x33
IPPROTO_AHIP = 0x3d
IPPROTO_APES = 0x63
IPPROTO_ARGUS = 0xd
IPPROTO_AX25 = 0x5d
IPPROTO_BHA = 0x31
IPPROTO_BLT = 0x1e
IPPROTO_BRSATMON = 0x4c
IPPROTO_CARP = 0x70
IPPROTO_CFTP = 0x3e
IPPROTO_CHAOS = 0x10
IPPROTO_CMTP = 0x26
IPPROTO_CPHB = 0x49
IPPROTO_CPNX = 0x48
IPPROTO_DDP = 0x25
IPPROTO_DGP = 0x56
IPPROTO_DIVERT = 0xfe
IPPROTO_DONE = 0x101
IPPROTO_DSTOPTS = 0x3c
IPPROTO_EGP = 0x8
IPPROTO_EMCON = 0xe
IPPROTO_ENCAP = 0x62
IPPROTO_EON = 0x50
IPPROTO_ESP = 0x32
IPPROTO_ETHERIP = 0x61
IPPROTO_FRAGMENT = 0x2c
IPPROTO_GGP = 0x3
IPPROTO_GMTP = 0x64
IPPROTO_GRE = 0x2f
IPPROTO_HELLO = 0x3f
IPPROTO_HMP = 0x14
IPPROTO_HOPOPTS = 0x0
IPPROTO_ICMP = 0x1
IPPROTO_ICMPV6 = 0x3a
IPPROTO_IDP = 0x16
IPPROTO_IDPR = 0x23
IPPROTO_IDRP = 0x2d
IPPROTO_IGMP = 0x2
IPPROTO_IGP = 0x55
IPPROTO_IGRP = 0x58
IPPROTO_IL = 0x28
IPPROTO_INLSP = 0x34
IPPROTO_INP = 0x20
IPPROTO_IP = 0x0
IPPROTO_IPCOMP = 0x6c
IPPROTO_IPCV = 0x47
IPPROTO_IPEIP = 0x5e
IPPROTO_IPIP = 0x4
IPPROTO_IPPC = 0x43
IPPROTO_IPV4 = 0x4
IPPROTO_IPV6 = 0x29
IPPROTO_IRTP = 0x1c
IPPROTO_KRYPTOLAN = 0x41
IPPROTO_LARP = 0x5b
IPPROTO_LEAF1 = 0x19
IPPROTO_LEAF2 = 0x1a
IPPROTO_MAX = 0x100
IPPROTO_MAXID = 0x34
IPPROTO_MEAS = 0x13
IPPROTO_MHRP = 0x30
IPPROTO_MICP = 0x5f
IPPROTO_MOBILE = 0x37
IPPROTO_MTP = 0x5c
IPPROTO_MUX = 0x12
IPPROTO_ND = 0x4d
IPPROTO_NHRP = 0x36
IPPROTO_NONE = 0x3b
IPPROTO_NSP = 0x1f
IPPROTO_NVPII = 0xb
IPPROTO_OSPFIGP = 0x59
IPPROTO_PFSYNC = 0xf0
IPPROTO_PGM = 0x71
IPPROTO_PIGP = 0x9
IPPROTO_PIM = 0x67
IPPROTO_PRM = 0x15
IPPROTO_PUP = 0xc
IPPROTO_PVP = 0x4b
IPPROTO_RAW = 0xff
IPPROTO_RCCMON = 0xa
IPPROTO_RDP = 0x1b
IPPROTO_ROUTING = 0x2b
IPPROTO_RSVP = 0x2e
IPPROTO_RVD = 0x42
IPPROTO_SATEXPAK = 0x40
IPPROTO_SATMON = 0x45
IPPROTO_SCCSP = 0x60
IPPROTO_SDRP = 0x2a
IPPROTO_SEP = 0x21
IPPROTO_SKIP = 0x39
IPPROTO_SRPC = 0x5a
IPPROTO_ST = 0x7
IPPROTO_SVMTP = 0x52
IPPROTO_SWIPE = 0x35
IPPROTO_TCF = 0x57
IPPROTO_TCP = 0x6
IPPROTO_TLSP = 0x38
IPPROTO_TP = 0x1d
IPPROTO_TPXX = 0x27
IPPROTO_TRUNK1 = 0x17
IPPROTO_TRUNK2 = 0x18
IPPROTO_TTP = 0x54
IPPROTO_UDP = 0x11
IPPROTO_UNKNOWN = 0x102
IPPROTO_VINES = 0x53
IPPROTO_VISA = 0x46
IPPROTO_VMTP = 0x51
IPPROTO_WBEXPAK = 0x4f
IPPROTO_WBMON = 0x4e
IPPROTO_WSN = 0x4a
IPPROTO_XNET = 0xf
IPPROTO_XTP = 0x24
IPV6_AUTOFLOWLABEL = 0x3b
IPV6_BINDV6ONLY = 0x1b
IPV6_CHECKSUM = 0x1a
IPV6_DEFAULT_MULTICAST_HOPS = 0x1
IPV6_DEFAULT_MULTICAST_LOOP = 0x1
IPV6_DEFHLIM = 0x40
IPV6_DONTFRAG = 0x3e
IPV6_DSTOPTS = 0x32
IPV6_FAITH = 0x1d
IPV6_FLOWINFO_MASK = 0xffffff0f
IPV6_FLOWLABEL_MASK = 0xffff0f00
IPV6_FRAGTTL = 0x78
IPV6_FW_ADD = 0x1e
IPV6_FW_DEL = 0x1f
IPV6_FW_FLUSH = 0x20
IPV6_FW_GET = 0x22
IPV6_FW_ZERO = 0x21
IPV6_HLIMDEC = 0x1
IPV6_HOPLIMIT = 0x2f
IPV6_HOPOPTS = 0x31
IPV6_IPSEC_POLICY = 0x1c
IPV6_JOIN_GROUP = 0xc
IPV6_LEAVE_GROUP = 0xd
IPV6_MAXHLIM = 0xff
IPV6_MAXPACKET = 0xffff
IPV6_MINHLIM = 0x28
IPV6_MMTU = 0x500
IPV6_MSFILTER = 0x4a
IPV6_MULTICAST_HOPS = 0xa
IPV6_MULTICAST_IF = 0x9
IPV6_MULTICAST_LOOP = 0xb
IPV6_NEXTHOP = 0x30
IPV6_PATHMTU = 0x2c
IPV6_PKTINFO = 0x2e
IPV6_PKTOPTIONS = 0x34
IPV6_PORTRANGE = 0xe
IPV6_PORTRANGE_DEFAULT = 0x0
IPV6_PORTRANGE_HIGH = 0x1
IPV6_PORTRANGE_LOW = 0x2
IPV6_PREFER_TEMPADDR = 0x3f
IPV6_RECVDSTOPTS = 0x28
IPV6_RECVHOPLIMIT = 0x25
IPV6_RECVHOPOPTS = 0x27
IPV6_RECVPATHMTU = 0x2b
IPV6_RECVPKTINFO = 0x24
IPV6_RECVRTHDR = 0x26
IPV6_RECVTCLASS = 0x39
IPV6_RTHDR = 0x33
IPV6_RTHDRDSTOPTS = 0x23
IPV6_RTHDR_LOOSE = 0x0
IPV6_RTHDR_STRICT = 0x1
IPV6_RTHDR_TYPE_0 = 0x0
IPV6_SOCKOPT_RESERVED1 = 0x3
IPV6_TCLASS = 0x3d
IPV6_UNICAST_HOPS = 0x4
IPV6_USE_MIN_MTU = 0x2a
IPV6_V6ONLY = 0x1b
IPV6_VERSION = 0x60
IPV6_VERSION_MASK = 0xf0
IP_ADD_MEMBERSHIP = 0xc
IP_DEFAULT_MULTICAST_LOOP = 0x1
IP_DEFAULT_MULTICAST_TTL = 0x1
IP_DF = 0x4000
IP_DROP_MEMBERSHIP = 0xd
IP_DUMMYNET_CONFIGURE = 0x3c
IP_DUMMYNET_DEL = 0x3d
IP_DUMMYNET_FLUSH = 0x3e
IP_DUMMYNET_GET = 0x40
IP_FAITH = 0x16
IP_FW_ADD = 0x32
IP_FW_DEL = 0x33
IP_FW_FLUSH = 0x34
IP_FW_GET = 0x36
IP_FW_RESETLOG = 0x37
IP_FW_X = 0x31
IP_FW_ZERO = 0x35
IP_HDRINCL = 0x2
IP_IPSEC_POLICY = 0x15
IP_MAXPACKET = 0xffff
IP_MAX_MEMBERSHIPS = 0x14
IP_MF = 0x2000
IP_MINTTL = 0x42
IP_MSS = 0x240
IP_MULTICAST_IF = 0x9
IP_MULTICAST_LOOP = 0xb
IP_MULTICAST_TTL = 0xa
IP_MULTICAST_VIF = 0xe
IP_OFFMASK = 0x1fff
IP_OPTIONS = 0x1
IP_PORTRANGE = 0x13
IP_PORTRANGE_DEFAULT = 0x0
IP_PORTRANGE_HIGH = 0x1
IP_PORTRANGE_LOW = 0x2
IP_RECVDSTADDR = 0x7
IP_RECVIF = 0x14
IP_RECVOPTS = 0x5
IP_RECVRETOPTS = 0x6
IP_RECVTTL = 0x41
IP_RETOPTS = 0x8
IP_RF = 0x8000
IP_RSVP_OFF = 0x10
IP_RSVP_ON = 0xf
IP_RSVP_VIF_OFF = 0x12
IP_RSVP_VIF_ON = 0x11
IP_TOS = 0x3
IP_TTL = 0x4
ISIG = 0x80
ISTRIP = 0x20
IXANY = 0x800
IXOFF = 0x400
IXON = 0x200
KERN_HOSTNAME = 0xa
KERN_OSRELEASE = 0x2
KERN_OSTYPE = 0x1
KERN_VERSION = 0x4
LOCK_EX = 0x2
LOCK_NB = 0x4
LOCK_SH = 0x1
LOCK_UN = 0x8
MADV_AUTOSYNC = 0x7
MADV_CONTROL_END = 0xb
MADV_CONTROL_START = 0xa
MADV_CORE = 0x9
MADV_DONTNEED = 0x4
MADV_FREE = 0x5
MADV_INVAL = 0xa
MADV_NOCORE = 0x8
MADV_NORMAL = 0x0
MADV_NOSYNC = 0x6
MADV_RANDOM = 0x1
MADV_SEQUENTIAL = 0x2
MADV_SETMAP = 0xb
MADV_WILLNEED = 0x3
MAP_ANON = 0x1000
MAP_ANONYMOUS = 0x1000
MAP_COPY = 0x2
MAP_FILE = 0x0
MAP_FIXED = 0x10
MAP_HASSEMAPHORE = 0x200
MAP_INHERIT = 0x80
MAP_NOCORE = 0x20000
MAP_NOEXTEND = 0x100
MAP_NORESERVE = 0x40
MAP_NOSYNC = 0x800
MAP_PRIVATE = 0x2
MAP_RENAME = 0x20
MAP_SHARED = 0x1
MAP_SIZEALIGN = 0x40000
MAP_STACK = 0x400
MAP_TRYFIXED = 0x10000
MAP_VPAGETABLE = 0x2000
MCL_CURRENT = 0x1
MCL_FUTURE = 0x2
MNT_ASYNC = 0x40
MNT_AUTOMOUNTED = 0x20
MNT_CMDFLAGS = 0xf0000
MNT_DEFEXPORTED = 0x200
MNT_DELEXPORT = 0x20000
MNT_EXKERB = 0x800
MNT_EXPORTANON = 0x400
MNT_EXPORTED = 0x100
MNT_EXPUBLIC = 0x20000000
MNT_EXRDONLY = 0x80
MNT_FORCE = 0x80000
MNT_IGNORE = 0x800000
MNT_LAZY = 0x4
MNT_LOCAL = 0x1000
MNT_NOATIME = 0x10000000
MNT_NOCLUSTERR = 0x40000000
MNT_NOCLUSTERW = 0x80000000
MNT_NODEV = 0x10
MNT_NOEXEC = 0x4
MNT_NOSUID = 0x8
MNT_NOSYMFOLLOW = 0x400000
MNT_NOWAIT = 0x2
MNT_QUOTA = 0x2000
MNT_RDONLY = 0x1
MNT_RELOAD = 0x40000
MNT_ROOTFS = 0x4000
MNT_SOFTDEP = 0x200000
MNT_SUIDDIR = 0x100000
MNT_SYNCHRONOUS = 0x2
MNT_TRIM = 0x1000000
MNT_UPDATE = 0x10000
MNT_USER = 0x8000
MNT_VISFLAGMASK = 0xf1f0ffff
MNT_WAIT = 0x1
MSG_CMSG_CLOEXEC = 0x1000
MSG_CTRUNC = 0x20
MSG_DONTROUTE = 0x4
MSG_DONTWAIT = 0x80
MSG_EOF = 0x100
MSG_EOR = 0x8
MSG_FBLOCKING = 0x10000
MSG_FMASK = 0xffff0000
MSG_FNONBLOCKING = 0x20000
MSG_NOSIGNAL = 0x400
MSG_OOB = 0x1
MSG_PEEK = 0x2
MSG_SYNC = 0x800
MSG_TRUNC = 0x10
MSG_UNUSED09 = 0x200
MSG_WAITALL = 0x40
MS_ASYNC = 0x1
MS_INVALIDATE = 0x2
MS_SYNC = 0x0
NAME_MAX = 0xff
NET_RT_DUMP = 0x1
NET_RT_FLAGS = 0x2
NET_RT_IFLIST = 0x3
NET_RT_MAXID = 0x4
NOFLSH = 0x80000000
NOKERNINFO = 0x2000000
NOTE_ATTRIB = 0x8
NOTE_CHILD = 0x4
NOTE_DELETE = 0x1
NOTE_EXEC = 0x20000000
NOTE_EXIT = 0x80000000
NOTE_EXTEND = 0x4
NOTE_FFAND = 0x40000000
NOTE_FFCOPY = 0xc0000000
NOTE_FFCTRLMASK = 0xc0000000
NOTE_FFLAGSMASK = 0xffffff
NOTE_FFNOP = 0x0
NOTE_FFOR = 0x80000000
NOTE_FORK = 0x40000000
NOTE_LINK = 0x10
NOTE_LOWAT = 0x1
NOTE_OOB = 0x2
NOTE_PCTRLMASK = 0xf0000000
NOTE_PDATAMASK = 0xfffff
NOTE_RENAME = 0x20
NOTE_REVOKE = 0x40
NOTE_TRACK = 0x1
NOTE_TRACKERR = 0x2
NOTE_TRIGGER = 0x1000000
NOTE_WRITE = 0x2
OCRNL = 0x10
ONLCR = 0x2
ONLRET = 0x40
ONOCR = 0x20
ONOEOT = 0x8
OPOST = 0x1
OXTABS = 0x4
O_ACCMODE = 0x3
O_APPEND = 0x8
O_ASYNC = 0x40
O_CLOEXEC = 0x20000
O_CREAT = 0x200
O_DIRECT = 0x10000
O_DIRECTORY = 0x8000000
O_EXCL = 0x800
O_EXLOCK = 0x20
O_FAPPEND = 0x100000
O_FASYNCWRITE = 0x800000
O_FBLOCKING = 0x40000
O_FMASK = 0xfc0000
O_FNONBLOCKING = 0x80000
O_FOFFSET = 0x200000
O_FSYNC = 0x80
O_FSYNCWRITE = 0x400000
O_NDELAY = 0x4
O_NOCTTY = 0x8000
O_NOFOLLOW = 0x100
O_NONBLOCK = 0x4
O_RDONLY = 0x0
O_RDWR = 0x2
O_SHLOCK = 0x10
O_SYNC = 0x80
O_TRUNC = 0x400
O_WRONLY = 0x1
PARENB = 0x1000
PARMRK = 0x8
PARODD = 0x2000
PENDIN = 0x20000000
PRIO_PGRP = 0x1
PRIO_PROCESS = 0x0
PRIO_USER = 0x2
PROT_EXEC = 0x4
PROT_NONE = 0x0
PROT_READ = 0x1
PROT_WRITE = 0x2
RLIMIT_AS = 0xa
RLIMIT_CORE = 0x4
RLIMIT_CPU = 0x0
RLIMIT_DATA = 0x2
RLIMIT_FSIZE = 0x1
RLIMIT_MEMLOCK = 0x6
RLIMIT_NOFILE = 0x8
RLIMIT_NPROC = 0x7
RLIMIT_RSS = 0x5
RLIMIT_STACK = 0x3
RLIM_INFINITY = 0x7fffffffffffffff
RTAX_AUTHOR = 0x6
RTAX_BRD = 0x7
RTAX_DST = 0x0
RTAX_GATEWAY = 0x1
RTAX_GENMASK = 0x3
RTAX_IFA = 0x5
RTAX_IFP = 0x4
RTAX_MAX = 0xb
RTAX_MPLS1 = 0x8
RTAX_MPLS2 = 0x9
RTAX_MPLS3 = 0xa
RTAX_NETMASK = 0x2
RTA_AUTHOR = 0x40
RTA_BRD = 0x80
RTA_DST = 0x1
RTA_GATEWAY = 0x2
RTA_GENMASK = 0x8
RTA_IFA = 0x20
RTA_IFP = 0x10
RTA_MPLS1 = 0x100
RTA_MPLS2 = 0x200
RTA_MPLS3 = 0x400
RTA_NETMASK = 0x4
RTF_BLACKHOLE = 0x1000
RTF_BROADCAST = 0x400000
RTF_CLONING = 0x100
RTF_DONE = 0x40
RTF_DYNAMIC = 0x10
RTF_GATEWAY = 0x2
RTF_HOST = 0x4
RTF_LLINFO = 0x400
RTF_LOCAL = 0x200000
RTF_MODIFIED = 0x20
RTF_MPLSOPS = 0x1000000
RTF_MULTICAST = 0x800000
RTF_PINNED = 0x100000
RTF_PRCLONING = 0x10000
RTF_PROTO1 = 0x8000
RTF_PROTO2 = 0x4000
RTF_PROTO3 = 0x40000
RTF_REJECT = 0x8
RTF_STATIC = 0x800
RTF_UP = 0x1
RTF_WASCLONED = 0x20000
RTF_XRESOLVE = 0x200
RTM_ADD = 0x1
RTM_CHANGE = 0x3
RTM_DELADDR = 0xd
RTM_DELETE = 0x2
RTM_DELMADDR = 0x10
RTM_GET = 0x4
RTM_IEEE80211 = 0x12
RTM_IFANNOUNCE = 0x11
RTM_IFINFO = 0xe
RTM_LOCK = 0x8
RTM_LOSING = 0x5
RTM_MISS = 0x7
RTM_NEWADDR = 0xc
RTM_NEWMADDR = 0xf
RTM_OLDADD = 0x9
RTM_OLDDEL = 0xa
RTM_REDIRECT = 0x6
RTM_RESOLVE = 0xb
RTM_RTTUNIT = 0xf4240
RTM_VERSION = 0x6
RTV_EXPIRE = 0x4
RTV_HOPCOUNT = 0x2
RTV_IWCAPSEGS = 0x400
RTV_IWMAXSEGS = 0x200
RTV_MSL = 0x100
RTV_MTU = 0x1
RTV_RPIPE = 0x8
RTV_RTT = 0x40
RTV_RTTVAR = 0x80
RTV_SPIPE = 0x10
RTV_SSTHRESH = 0x20
RUSAGE_CHILDREN = -0x1
RUSAGE_SELF = 0x0
SCM_CREDS = 0x3
SCM_RIGHTS = 0x1
SCM_TIMESTAMP = 0x2
SHUT_RD = 0x0
SHUT_RDWR = 0x2
SHUT_WR = 0x1
SIOCADDMULTI = 0x80206931
SIOCADDRT = 0x8040720a
SIOCAIFADDR = 0x8040691a
SIOCALIFADDR = 0x8118691b
SIOCATMARK = 0x40047307
SIOCDELMULTI = 0x80206932
SIOCDELRT = 0x8040720b
SIOCDIFADDR = 0x80206919
SIOCDIFPHYADDR = 0x80206949
SIOCDLIFADDR = 0x8118691d
SIOCGDRVSPEC = 0xc028697b
SIOCGETSGCNT = 0xc0207210
SIOCGETVIFCNT = 0xc028720f
SIOCGHIWAT = 0x40047301
SIOCGIFADDR = 0xc0206921
SIOCGIFBRDADDR = 0xc0206923
SIOCGIFCAP = 0xc020691f
SIOCGIFCONF = 0xc0106924
SIOCGIFDATA = 0xc0206926
SIOCGIFDSTADDR = 0xc0206922
SIOCGIFFLAGS = 0xc0206911
SIOCGIFGENERIC = 0xc020693a
SIOCGIFGMEMB = 0xc028698a
SIOCGIFINDEX = 0xc0206920
SIOCGIFMEDIA = 0xc0306938
SIOCGIFMETRIC = 0xc0206917
SIOCGIFMTU = 0xc0206933
SIOCGIFNETMASK = 0xc0206925
SIOCGIFPDSTADDR = 0xc0206948
SIOCGIFPHYS = 0xc0206935
SIOCGIFPOLLCPU = 0xc020697e
SIOCGIFPSRCADDR = 0xc0206947
SIOCGIFSTATUS = 0xc331693b
SIOCGIFTSOLEN = 0xc0206980
SIOCGLIFADDR = 0xc118691c
SIOCGLIFPHYADDR = 0xc118694b
SIOCGLOWAT = 0x40047303
SIOCGPGRP = 0x40047309
SIOCGPRIVATE_0 = 0xc0206950
SIOCGPRIVATE_1 = 0xc0206951
SIOCIFCREATE = 0xc020697a
SIOCIFCREATE2 = 0xc020697c
SIOCIFDESTROY = 0x80206979
SIOCIFGCLONERS = 0xc0106978
SIOCSDRVSPEC = 0x8028697b
SIOCSHIWAT = 0x80047300
SIOCSIFADDR = 0x8020690c
SIOCSIFBRDADDR = 0x80206913
SIOCSIFCAP = 0x8020691e
SIOCSIFDSTADDR = 0x8020690e
SIOCSIFFLAGS = 0x80206910
SIOCSIFGENERIC = 0x80206939
SIOCSIFLLADDR = 0x8020693c
SIOCSIFMEDIA = 0xc0206937
SIOCSIFMETRIC = 0x80206918
SIOCSIFMTU = 0x80206934
SIOCSIFNAME = 0x80206928
SIOCSIFNETMASK = 0x80206916
SIOCSIFPHYADDR = 0x80406946
SIOCSIFPHYS = 0x80206936
SIOCSIFPOLLCPU = 0x8020697d
SIOCSIFTSOLEN = 0x8020697f
SIOCSLIFPHYADDR = 0x8118694a
SIOCSLOWAT = 0x80047302
SIOCSPGRP = 0x80047308
SOCK_CLOEXEC = 0x10000000
SOCK_DGRAM = 0x2
SOCK_MAXADDRLEN = 0xff
SOCK_NONBLOCK = 0x20000000
SOCK_RAW = 0x3
SOCK_RDM = 0x4
SOCK_SEQPACKET = 0x5
SOCK_STREAM = 0x1
SOL_SOCKET = 0xffff
SOMAXCONN = 0x80
SO_ACCEPTCONN = 0x2
SO_ACCEPTFILTER = 0x1000
SO_BROADCAST = 0x20
SO_CPUHINT = 0x1030
SO_DEBUG = 0x1
SO_DONTROUTE = 0x10
SO_ERROR = 0x1007
SO_KEEPALIVE = 0x8
SO_LINGER = 0x80
SO_NOSIGPIPE = 0x800
SO_OOBINLINE = 0x100
SO_RCVBUF = 0x1002
SO_RCVLOWAT = 0x1004
SO_RCVTIMEO = 0x1006
SO_REUSEADDR = 0x4
SO_REUSEPORT = 0x200
SO_SNDBUF = 0x1001
SO_SNDLOWAT = 0x1003
SO_SNDSPACE = 0x100a
SO_SNDTIMEO = 0x1005
SO_TIMESTAMP = 0x400
SO_TYPE = 0x1008
SO_USELOOPBACK = 0x40
S_BLKSIZE = 0x200
S_IEXEC = 0x40
S_IFBLK = 0x6000
S_IFCHR = 0x2000
S_IFDB = 0x9000
S_IFDIR = 0x4000
S_IFIFO = 0x1000
S_IFLNK = 0xa000
S_IFMT = 0xf000
S_IFREG = 0x8000
S_IFSOCK = 0xc000
S_IFWHT = 0xe000
S_IREAD = 0x100
S_IRGRP = 0x20
S_IROTH = 0x4
S_IRUSR = 0x100
S_IRWXG = 0x38
S_IRWXO = 0x7
S_IRWXU = 0x1c0
S_ISGID = 0x400
S_ISTXT = 0x200
S_ISUID = 0x800
S_ISVTX = 0x200
S_IWGRP = 0x10
S_IWOTH = 0x2
S_IWRITE = 0x80
S_IWUSR = 0x80
S_IXGRP = 0x8
S_IXOTH = 0x1
S_IXUSR = 0x40
TCIFLUSH = 0x1
TCIOFF = 0x3
TCIOFLUSH = 0x3
TCION = 0x4
TCOFLUSH = 0x2
TCOOFF = 0x1
TCOON = 0x2
TCP_FASTKEEP = 0x80
TCP_KEEPCNT = 0x400
TCP_KEEPIDLE = 0x100
TCP_KEEPINIT = 0x20
TCP_KEEPINTVL = 0x200
TCP_MAXBURST = 0x4
TCP_MAXHLEN = 0x3c
TCP_MAXOLEN = 0x28
TCP_MAXSEG = 0x2
TCP_MAXWIN = 0xffff
TCP_MAX_WINSHIFT = 0xe
TCP_MINMSS = 0x100
TCP_MIN_WINSHIFT = 0x5
TCP_MSS = 0x200
TCP_NODELAY = 0x1
TCP_NOOPT = 0x8
TCP_NOPUSH = 0x4
TCP_SIGNATURE_ENABLE = 0x10
TCSAFLUSH = 0x2
TIOCCBRK = 0x2000747a
TIOCCDTR = 0x20007478
TIOCCONS = 0x80047462
TIOCDCDTIMESTAMP = 0x40107458
TIOCDRAIN = 0x2000745e
TIOCEXCL = 0x2000740d
TIOCEXT = 0x80047460
TIOCFLUSH = 0x80047410
TIOCGDRAINWAIT = 0x40047456
TIOCGETA = 0x402c7413
TIOCGETD = 0x4004741a
TIOCGPGRP = 0x40047477
TIOCGSID = 0x40047463
TIOCGSIZE = 0x40087468
TIOCGWINSZ = 0x40087468
TIOCISPTMASTER = 0x20007455
TIOCMBIC = 0x8004746b
TIOCMBIS = 0x8004746c
TIOCMGDTRWAIT = 0x4004745a
TIOCMGET = 0x4004746a
TIOCMODG = 0x40047403
TIOCMODS = 0x80047404
TIOCMSDTRWAIT = 0x8004745b
TIOCMSET = 0x8004746d
TIOCM_CAR = 0x40
TIOCM_CD = 0x40
TIOCM_CTS = 0x20
TIOCM_DSR = 0x100
TIOCM_DTR = 0x2
TIOCM_LE = 0x1
TIOCM_RI = 0x80
TIOCM_RNG = 0x80
TIOCM_RTS = 0x4
TIOCM_SR = 0x10
TIOCM_ST = 0x8
TIOCNOTTY = 0x20007471
TIOCNXCL = 0x2000740e
TIOCOUTQ = 0x40047473
TIOCPKT = 0x80047470
TIOCPKT_DATA = 0x0
TIOCPKT_DOSTOP = 0x20
TIOCPKT_FLUSHREAD = 0x1
TIOCPKT_FLUSHWRITE = 0x2
TIOCPKT_IOCTL = 0x40
TIOCPKT_NOSTOP = 0x10
TIOCPKT_START = 0x8
TIOCPKT_STOP = 0x4
TIOCREMOTE = 0x80047469
TIOCSBRK = 0x2000747b
TIOCSCTTY = 0x20007461
TIOCSDRAINWAIT = 0x80047457
TIOCSDTR = 0x20007479
TIOCSETA = 0x802c7414
TIOCSETAF = 0x802c7416
TIOCSETAW = 0x802c7415
TIOCSETD = 0x8004741b
TIOCSIG = 0x2000745f
TIOCSPGRP = 0x80047476
TIOCSSIZE = 0x80087467
TIOCSTART = 0x2000746e
TIOCSTAT = 0x20007465
TIOCSTI = 0x80017472
TIOCSTOP = 0x2000746f
TIOCSWINSZ = 0x80087467
TIOCTIMESTAMP = 0x40107459
TIOCUCNTL = 0x80047466
TOSTOP = 0x400000
VCHECKPT = 0x13
VDISCARD = 0xf
VDSUSP = 0xb
VEOF = 0x0
VEOL = 0x1
VEOL2 = 0x2
VERASE = 0x3
VERASE2 = 0x7
VINTR = 0x8
VKILL = 0x5
VLNEXT = 0xe
VMIN = 0x10
VM_BCACHE_SIZE_MAX = 0x0
VM_SWZONE_SIZE_MAX = 0x4000000000
VQUIT = 0x9
VREPRINT = 0x6
VSTART = 0xc
VSTATUS = 0x12
VSTOP = 0xd
VSUSP = 0xa
VTIME = 0x11
VWERASE = 0x4
WCONTINUED = 0x4
WCOREFLAG = 0x80
WLINUXCLONE = 0x80000000
WNOHANG = 0x1
WSTOPPED = 0x7f
WUNTRACED = 0x2
)
// Errors
const (
E2BIG = syscall.Errno(0x7)
EACCES = syscall.Errno(0xd)
EADDRINUSE = syscall.Errno(0x30)
EADDRNOTAVAIL = syscall.Errno(0x31)
EAFNOSUPPORT = syscall.Errno(0x2f)
EAGAIN = syscall.Errno(0x23)
EALREADY = syscall.Errno(0x25)
EASYNC = syscall.Errno(0x63)
EAUTH = syscall.Errno(0x50)
EBADF = syscall.Errno(0x9)
EBADMSG = syscall.Errno(0x59)
EBADRPC = syscall.Errno(0x48)
EBUSY = syscall.Errno(0x10)
ECANCELED = syscall.Errno(0x55)
ECHILD = syscall.Errno(0xa)
ECONNABORTED = syscall.Errno(0x35)
ECONNREFUSED = syscall.Errno(0x3d)
ECONNRESET = syscall.Errno(0x36)
EDEADLK = syscall.Errno(0xb)
EDESTADDRREQ = syscall.Errno(0x27)
EDOM = syscall.Errno(0x21)
EDOOFUS = syscall.Errno(0x58)
EDQUOT = syscall.Errno(0x45)
EEXIST = syscall.Errno(0x11)
EFAULT = syscall.Errno(0xe)
EFBIG = syscall.Errno(0x1b)
EFTYPE = syscall.Errno(0x4f)
EHOSTDOWN = syscall.Errno(0x40)
EHOSTUNREACH = syscall.Errno(0x41)
EIDRM = syscall.Errno(0x52)
EILSEQ = syscall.Errno(0x56)
EINPROGRESS = syscall.Errno(0x24)
EINTR = syscall.Errno(0x4)
EINVAL = syscall.Errno(0x16)
EIO = syscall.Errno(0x5)
EISCONN = syscall.Errno(0x38)
EISDIR = syscall.Errno(0x15)
ELAST = syscall.Errno(0x63)
ELOOP = syscall.Errno(0x3e)
EMFILE = syscall.Errno(0x18)
EMLINK = syscall.Errno(0x1f)
EMSGSIZE = syscall.Errno(0x28)
EMULTIHOP = syscall.Errno(0x5a)
ENAMETOOLONG = syscall.Errno(0x3f)
ENEEDAUTH = syscall.Errno(0x51)
ENETDOWN = syscall.Errno(0x32)
ENETRESET = syscall.Errno(0x34)
ENETUNREACH = syscall.Errno(0x33)
ENFILE = syscall.Errno(0x17)
ENOATTR = syscall.Errno(0x57)
ENOBUFS = syscall.Errno(0x37)
ENODEV = syscall.Errno(0x13)
ENOENT = syscall.Errno(0x2)
ENOEXEC = syscall.Errno(0x8)
ENOLCK = syscall.Errno(0x4d)
ENOLINK = syscall.Errno(0x5b)
ENOMEDIUM = syscall.Errno(0x5d)
ENOMEM = syscall.Errno(0xc)
ENOMSG = syscall.Errno(0x53)
ENOPROTOOPT = syscall.Errno(0x2a)
ENOSPC = syscall.Errno(0x1c)
ENOSYS = syscall.Errno(0x4e)
ENOTBLK = syscall.Errno(0xf)
ENOTCONN = syscall.Errno(0x39)
ENOTDIR = syscall.Errno(0x14)
ENOTEMPTY = syscall.Errno(0x42)
ENOTSOCK = syscall.Errno(0x26)
ENOTSUP = syscall.Errno(0x2d)
ENOTTY = syscall.Errno(0x19)
ENXIO = syscall.Errno(0x6)
EOPNOTSUPP = syscall.Errno(0x2d)
EOVERFLOW = syscall.Errno(0x54)
EPERM = syscall.Errno(0x1)
EPFNOSUPPORT = syscall.Errno(0x2e)
EPIPE = syscall.Errno(0x20)
EPROCLIM = syscall.Errno(0x43)
EPROCUNAVAIL = syscall.Errno(0x4c)
EPROGMISMATCH = syscall.Errno(0x4b)
EPROGUNAVAIL = syscall.Errno(0x4a)
EPROTO = syscall.Errno(0x5c)
EPROTONOSUPPORT = syscall.Errno(0x2b)
EPROTOTYPE = syscall.Errno(0x29)
ERANGE = syscall.Errno(0x22)
EREMOTE = syscall.Errno(0x47)
EROFS = syscall.Errno(0x1e)
ERPCMISMATCH = syscall.Errno(0x49)
ESHUTDOWN = syscall.Errno(0x3a)
ESOCKTNOSUPPORT = syscall.Errno(0x2c)
ESPIPE = syscall.Errno(0x1d)
ESRCH = syscall.Errno(0x3)
ESTALE = syscall.Errno(0x46)
ETIMEDOUT = syscall.Errno(0x3c)
ETOOMANYREFS = syscall.Errno(0x3b)
ETXTBSY = syscall.Errno(0x1a)
EUNUSED94 = syscall.Errno(0x5e)
EUNUSED95 = syscall.Errno(0x5f)
EUNUSED96 = syscall.Errno(0x60)
EUNUSED97 = syscall.Errno(0x61)
EUNUSED98 = syscall.Errno(0x62)
EUSERS = syscall.Errno(0x44)
EWOULDBLOCK = syscall.Errno(0x23)
EXDEV = syscall.Errno(0x12)
)
// Signals
const (
SIGABRT = syscall.Signal(0x6)
SIGALRM = syscall.Signal(0xe)
SIGBUS = syscall.Signal(0xa)
SIGCHLD = syscall.Signal(0x14)
SIGCKPT = syscall.Signal(0x21)
SIGCKPTEXIT = syscall.Signal(0x22)
SIGCONT = syscall.Signal(0x13)
SIGEMT = syscall.Signal(0x7)
SIGFPE = syscall.Signal(0x8)
SIGHUP = syscall.Signal(0x1)
SIGILL = syscall.Signal(0x4)
SIGINFO = syscall.Signal(0x1d)
SIGINT = syscall.Signal(0x2)
SIGIO = syscall.Signal(0x17)
SIGIOT = syscall.Signal(0x6)
SIGKILL = syscall.Signal(0x9)
SIGPIPE = syscall.Signal(0xd)
SIGPROF = syscall.Signal(0x1b)
SIGQUIT = syscall.Signal(0x3)
SIGSEGV = syscall.Signal(0xb)
SIGSTOP = syscall.Signal(0x11)
SIGSYS = syscall.Signal(0xc)
SIGTERM = syscall.Signal(0xf)
SIGTHR = syscall.Signal(0x20)
SIGTRAP = syscall.Signal(0x5)
SIGTSTP = syscall.Signal(0x12)
SIGTTIN = syscall.Signal(0x15)
SIGTTOU = syscall.Signal(0x16)
SIGURG = syscall.Signal(0x10)
SIGUSR1 = syscall.Signal(0x1e)
SIGUSR2 = syscall.Signal(0x1f)
SIGVTALRM = syscall.Signal(0x1a)
SIGWINCH = syscall.Signal(0x1c)
SIGXCPU = syscall.Signal(0x18)
SIGXFSZ = syscall.Signal(0x19)
)
// Error table
var errorList = [...]struct {
num syscall.Errno
name string
desc string
}{
{1, "EPERM", "operation not permitted"},
{2, "ENOENT", "no such file or directory"},
{3, "ESRCH", "no such process"},
{4, "EINTR", "interrupted system call"},
{5, "EIO", "input/output error"},
{6, "ENXIO", "device not configured"},
{7, "E2BIG", "argument list too long"},
{8, "ENOEXEC", "exec format error"},
{9, "EBADF", "bad file descriptor"},
{10, "ECHILD", "no child processes"},
{11, "EDEADLK", "resource deadlock avoided"},
{12, "ENOMEM", "cannot allocate memory"},
{13, "EACCES", "permission denied"},
{14, "EFAULT", "bad address"},
{15, "ENOTBLK", "block device required"},
{16, "EBUSY", "device busy"},
{17, "EEXIST", "file exists"},
{18, "EXDEV", "cross-device link"},
{19, "ENODEV", "operation not supported by device"},
{20, "ENOTDIR", "not a directory"},
{21, "EISDIR", "is a directory"},
{22, "EINVAL", "invalid argument"},
{23, "ENFILE", "too many open files in system"},
{24, "EMFILE", "too many open files"},
{25, "ENOTTY", "inappropriate ioctl for device"},
{26, "ETXTBSY", "text file busy"},
{27, "EFBIG", "file too large"},
{28, "ENOSPC", "no space left on device"},
{29, "ESPIPE", "illegal seek"},
{30, "EROFS", "read-only file system"},
{31, "EMLINK", "too many links"},
{32, "EPIPE", "broken pipe"},
{33, "EDOM", "numerical argument out of domain"},
{34, "ERANGE", "result too large"},
{35, "EWOULDBLOCK", "resource temporarily unavailable"},
{36, "EINPROGRESS", "operation now in progress"},
{37, "EALREADY", "operation already in progress"},
{38, "ENOTSOCK", "socket operation on non-socket"},
{39, "EDESTADDRREQ", "destination address required"},
{40, "EMSGSIZE", "message too long"},
{41, "EPROTOTYPE", "protocol wrong type for socket"},
{42, "ENOPROTOOPT", "protocol not available"},
{43, "EPROTONOSUPPORT", "protocol not supported"},
{44, "ESOCKTNOSUPPORT", "socket type not supported"},
{45, "EOPNOTSUPP", "operation not supported"},
{46, "EPFNOSUPPORT", "protocol family not supported"},
{47, "EAFNOSUPPORT", "address family not supported by protocol family"},
{48, "EADDRINUSE", "address already in use"},
{49, "EADDRNOTAVAIL", "can't assign requested address"},
{50, "ENETDOWN", "network is down"},
{51, "ENETUNREACH", "network is unreachable"},
{52, "ENETRESET", "network dropped connection on reset"},
{53, "ECONNABORTED", "software caused connection abort"},
{54, "ECONNRESET", "connection reset by peer"},
{55, "ENOBUFS", "no buffer space available"},
{56, "EISCONN", "socket is already connected"},
{57, "ENOTCONN", "socket is not connected"},
{58, "ESHUTDOWN", "can't send after socket shutdown"},
{59, "ETOOMANYREFS", "too many references: can't splice"},
{60, "ETIMEDOUT", "operation timed out"},
{61, "ECONNREFUSED", "connection refused"},
{62, "ELOOP", "too many levels of symbolic links"},
{63, "ENAMETOOLONG", "file name too long"},
{64, "EHOSTDOWN", "host is down"},
{65, "EHOSTUNREACH", "no route to host"},
{66, "ENOTEMPTY", "directory not empty"},
{67, "EPROCLIM", "too many processes"},
{68, "EUSERS", "too many users"},
{69, "EDQUOT", "disc quota exceeded"},
{70, "ESTALE", "stale NFS file handle"},
{71, "EREMOTE", "too many levels of remote in path"},
{72, "EBADRPC", "RPC struct is bad"},
{73, "ERPCMISMATCH", "RPC version wrong"},
{74, "EPROGUNAVAIL", "RPC prog. not avail"},
{75, "EPROGMISMATCH", "program version wrong"},
{76, "EPROCUNAVAIL", "bad procedure for program"},
{77, "ENOLCK", "no locks available"},
{78, "ENOSYS", "function not implemented"},
{79, "EFTYPE", "inappropriate file type or format"},
{80, "EAUTH", "authentication error"},
{81, "ENEEDAUTH", "need authenticator"},
{82, "EIDRM", "identifier removed"},
{83, "ENOMSG", "no message of desired type"},
{84, "EOVERFLOW", "value too large to be stored in data type"},
{85, "ECANCELED", "operation canceled"},
{86, "EILSEQ", "illegal byte sequence"},
{87, "ENOATTR", "attribute not found"},
{88, "EDOOFUS", "programming error"},
{89, "EBADMSG", "bad message"},
{90, "EMULTIHOP", "multihop attempted"},
{91, "ENOLINK", "link has been severed"},
{92, "EPROTO", "protocol error"},
{93, "ENOMEDIUM", "no medium found"},
{94, "EUNUSED94", "unknown error: 94"},
{95, "EUNUSED95", "unknown error: 95"},
{96, "EUNUSED96", "unknown error: 96"},
{97, "EUNUSED97", "unknown error: 97"},
{98, "EUNUSED98", "unknown error: 98"},
{99, "ELAST", "unknown error: 99"},
}
// Signal table
var signalList = [...]struct {
num syscall.Signal
name string
desc string
}{
{1, "SIGHUP", "hangup"},
{2, "SIGINT", "interrupt"},
{3, "SIGQUIT", "quit"},
{4, "SIGILL", "illegal instruction"},
{5, "SIGTRAP", "trace/BPT trap"},
{6, "SIGIOT", "abort trap"},
{7, "SIGEMT", "EMT trap"},
{8, "SIGFPE", "floating point exception"},
{9, "SIGKILL", "killed"},
{10, "SIGBUS", "bus error"},
{11, "SIGSEGV", "segmentation fault"},
{12, "SIGSYS", "bad system call"},
{13, "SIGPIPE", "broken pipe"},
{14, "SIGALRM", "alarm clock"},
{15, "SIGTERM", "terminated"},
{16, "SIGURG", "urgent I/O condition"},
{17, "SIGSTOP", "suspended (signal)"},
{18, "SIGTSTP", "suspended"},
{19, "SIGCONT", "continued"},
{20, "SIGCHLD", "child exited"},
{21, "SIGTTIN", "stopped (tty input)"},
{22, "SIGTTOU", "stopped (tty output)"},
{23, "SIGIO", "I/O possible"},
{24, "SIGXCPU", "cputime limit exceeded"},
{25, "SIGXFSZ", "filesize limit exceeded"},
{26, "SIGVTALRM", "virtual timer expired"},
{27, "SIGPROF", "profiling timer expired"},
{28, "SIGWINCH", "window size changes"},
{29, "SIGINFO", "information request"},
{30, "SIGUSR1", "user defined signal 1"},
{31, "SIGUSR2", "user defined signal 2"},
{32, "SIGTHR", "thread Scheduler"},
{33, "SIGCKPT", "checkPoint"},
{34, "SIGCKPTEXIT", "checkPointExit"},
}
| vendor/golang.org/x/sys/unix/zerrors_dragonfly_amd64.go | 0 | https://github.com/grafana/grafana/commit/09b434bdd08a65714e7fd09c802a0835c3261132 | [
0.00022296755923889577,
0.00016937515465542674,
0.0001639765832806006,
0.00016651212354190648,
0.000009262364073947538
]
|
{
"id": 2,
"code_window": [
"export const initialState: UsersState = {\n",
" invitees: [] as Invitee[],\n",
" users: [] as OrgUser[],\n",
" searchQuery: '',\n",
" canInvite: !config.disableLoginForm && !config.externalUserMngLinkName,\n",
" externalUserMngInfo: config.externalUserMngInfo,\n",
" externalUserMngLinkName: config.externalUserMngLinkName,\n",
" externalUserMngLinkUrl: config.externalUserMngLinkUrl,\n",
" hasFetched: false,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" canInvite: !config.externalUserMngLinkName,\n"
],
"file_path": "public/app/features/users/state/reducers.ts",
"type": "replace",
"edit_start_line_idx": 8
} | package pool
type SingleConnPool struct {
cn *Conn
}
var _ Pooler = (*SingleConnPool)(nil)
func NewSingleConnPool(cn *Conn) *SingleConnPool {
return &SingleConnPool{
cn: cn,
}
}
func (p *SingleConnPool) Get() (*Conn, bool, error) {
return p.cn, false, nil
}
func (p *SingleConnPool) Put(cn *Conn) error {
if p.cn != cn {
panic("p.cn != cn")
}
return nil
}
func (p *SingleConnPool) Remove(cn *Conn, _ error) error {
if p.cn != cn {
panic("p.cn != cn")
}
return nil
}
func (p *SingleConnPool) Len() int {
return 1
}
func (p *SingleConnPool) FreeLen() int {
return 0
}
func (p *SingleConnPool) Stats() *Stats {
return nil
}
func (p *SingleConnPool) Close() error {
return nil
}
| vendor/gopkg.in/redis.v5/internal/pool/pool_single.go | 0 | https://github.com/grafana/grafana/commit/09b434bdd08a65714e7fd09c802a0835c3261132 | [
0.00017109711188822985,
0.00016973436868283898,
0.0001671630161581561,
0.00017013288743328303,
0.0000013389454807111179
]
|
{
"id": 2,
"code_window": [
"export const initialState: UsersState = {\n",
" invitees: [] as Invitee[],\n",
" users: [] as OrgUser[],\n",
" searchQuery: '',\n",
" canInvite: !config.disableLoginForm && !config.externalUserMngLinkName,\n",
" externalUserMngInfo: config.externalUserMngInfo,\n",
" externalUserMngLinkName: config.externalUserMngLinkName,\n",
" externalUserMngLinkUrl: config.externalUserMngLinkUrl,\n",
" hasFetched: false,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" canInvite: !config.externalUserMngLinkName,\n"
],
"file_path": "public/app/features/users/state/reducers.ts",
"type": "replace",
"edit_start_line_idx": 8
} | import { auto } from 'angular';
export class QueryCtrl {
target: any;
datasource: any;
panelCtrl: any;
panel: any;
hasRawMode: boolean;
error: string;
constructor(public $scope: any, _$injector: auto.IInjectorService) {
this.panelCtrl = this.panelCtrl || { panel: {} };
this.target = this.target || { target: '' };
this.panel = this.panelCtrl.panel;
}
refresh() {}
}
| public/app/plugins/datasource/grafana-azure-monitor-datasource/__mocks__/query_ctrl.ts | 0 | https://github.com/grafana/grafana/commit/09b434bdd08a65714e7fd09c802a0835c3261132 | [
0.00017301244952250272,
0.00016958167543634772,
0.00016615090135019273,
0.00016958167543634772,
0.0000034307740861549973
]
|
{
"id": 0,
"code_window": [
"<template>\n",
" <div>\n",
" <router-link to=\"/\">Home</router-link> | \n",
" <router-link to=\"/about\">About</router-link>\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" <router-link to=\"/\">Home</router-link>|\n"
],
"file_path": "packages/playground/ssr-vue/src/App.vue",
"type": "replace",
"edit_start_line_idx": 2
} | <template>
<h1>About</h1>
</template>
<style scoped>
h1 {
color: red;
}
</style> | packages/playground/ssr-vue/src/pages/About.vue | 1 | https://github.com/vitejs/vite/commit/af2fe243f7bf0762c763e703bb50dd7f3648cd77 | [
0.0005230315728113055,
0.0005230315728113055,
0.0005230315728113055,
0.0005230315728113055,
0
]
|
{
"id": 0,
"code_window": [
"<template>\n",
" <div>\n",
" <router-link to=\"/\">Home</router-link> | \n",
" <router-link to=\"/about\">About</router-link>\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" <router-link to=\"/\">Home</router-link>|\n"
],
"file_path": "packages/playground/ssr-vue/src/App.vue",
"type": "replace",
"edit_start_line_idx": 2
} | import MagicString from 'magic-string'
import { SourceMap } from 'rollup'
import { TransformResult } from '../server/transformRequest'
import { parser } from '../server/pluginContainer'
import {
Identifier,
Node as _Node,
Property,
Function as FunctionNode
} from 'estree'
import { extract_names as extractNames } from 'periscopic'
import { walk as eswalk } from 'estree-walker'
import merge from 'merge-source-map'
type Node = _Node & {
start: number
end: number
}
export const ssrModuleExportsKey = `__vite_ssr_exports__`
export const ssrImportKey = `__vite_ssr_import__`
export const ssrDynamicImportKey = `__vite_ssr_dynamic_import__`
export const ssrExportAllKey = `__vite_ssr_exportAll__`
export const ssrImportMetaKey = `__vite_ssr_import_meta__`
export async function ssrTransform(
code: string,
inMap: SourceMap | null
): Promise<TransformResult | null> {
const s = new MagicString(code)
const ast = parser.parse(code, {
sourceType: 'module',
ecmaVersion: 2020,
locations: true
}) as any
let uid = 0
const deps = new Set<string>()
const idToImportMap = new Map<string, string>()
function defineImport(node: Node, source: string) {
deps.add(source)
const importId = `__vite_ssr_import_${uid++}__`
s.appendLeft(
node.start,
`const ${importId} = ${ssrImportKey}(${JSON.stringify(source)})\n`
)
return importId
}
function defineExport(name: string, local = name) {
s.append(
`\nObject.defineProperty(${ssrModuleExportsKey}, "${name}", ` +
`{ get(){ return ${local} }})`
)
}
// 1. check all import statements and record id -> importName map
for (const node of ast.body as Node[]) {
// import foo from 'foo' --> foo -> __import_foo__.default
// import { baz } from 'foo' --> baz -> __import_foo__.baz
// import * as ok from 'foo' --> ok -> __import_foo__
if (node.type === 'ImportDeclaration') {
const importId = defineImport(node, node.source.value as string)
for (const spec of node.specifiers) {
if (spec.type === 'ImportSpecifier') {
idToImportMap.set(
spec.local.name,
`${importId}.${spec.imported.name}`
)
} else if (spec.type === 'ImportDefaultSpecifier') {
idToImportMap.set(spec.local.name, `${importId}.default`)
} else {
// namespace specifier
idToImportMap.set(spec.local.name, importId)
}
}
s.remove(node.start, node.end)
}
}
// 2. check all export statements and define exports
for (const node of ast.body as Node[]) {
// named exports
if (node.type === 'ExportNamedDeclaration') {
if (node.declaration) {
if (
node.declaration.type === 'FunctionDeclaration' ||
node.declaration.type === 'ClassDeclaration'
) {
// export function foo() {}
defineExport(node.declaration.id!.name)
} else {
// export const foo = 1, bar = 2
for (const decl of node.declaration.declarations) {
const names = extractNames(decl.id as any)
for (const name of names) {
defineExport(name)
}
}
}
s.remove(node.start, (node.declaration as Node).start)
} else if (node.source) {
// export { foo, bar } from './foo'
const importId = defineImport(node, node.source.value as string)
for (const spec of node.specifiers) {
defineExport(spec.exported.name, `${importId}.${spec.local.name}`)
}
s.remove(node.start, node.end)
} else {
// export { foo, bar }
for (const spec of node.specifiers) {
const local = spec.local.name
const binding = idToImportMap.get(local)
defineExport(spec.exported.name, binding || local)
}
s.remove(node.start, node.end)
}
}
// default export
if (node.type === 'ExportDefaultDeclaration') {
s.overwrite(
node.start,
node.start + 14,
`${ssrModuleExportsKey}.default =`
)
}
// export * from './foo'
if (node.type === 'ExportAllDeclaration') {
const importId = defineImport(node, node.source.value as string)
s.remove(node.start, node.end)
s.append(`\n${ssrExportAllKey}(${importId})`)
}
}
// 2. convert references to import bindings & import.meta references
walk(ast, {
onIdentifier(id, parent, parentStack) {
const binding = idToImportMap.get(id.name)
if (!binding) {
return
}
if (isStaticProperty(parent) && parent.shorthand) {
// let binding used in a property shorthand
// { foo } -> { foo: __import_x__.foo }
// skip for destructure patterns
if (
!(parent as any).inPattern ||
isInDestructureAssignment(parent, parentStack)
) {
s.appendLeft(id.end, `: ${binding}`)
}
} else {
s.overwrite(id.start, id.end, binding)
}
},
onImportMeta(node) {
s.overwrite(node.start, node.end, ssrImportMetaKey)
},
onDynamicImport(node) {
s.overwrite(node.start, node.start + 6, ssrDynamicImportKey)
}
})
let map = s.generateMap({ hires: true })
if (inMap && inMap.mappings) {
map = merge(inMap, {
...map,
sources: inMap.sources,
sourcesContent: inMap.sourcesContent
}) as SourceMap
}
return {
code: s.toString(),
map,
deps: [...deps]
}
}
interface Visitors {
onIdentifier: (
node: Identifier & {
start: number
end: number
},
parent: Node,
parentStack: Node[]
) => void
onImportMeta: (node: Node) => void
onDynamicImport: (node: Node) => void
}
/**
* Same logic from \@vue/compiler-core & \@vue/compiler-sfc
* Except this is using acorn AST
*/
function walk(
root: Node,
{ onIdentifier, onImportMeta, onDynamicImport }: Visitors
) {
const parentStack: Node[] = []
const scope: Record<string, number> = Object.create(null)
const scopeMap = new WeakMap<_Node, Set<string>>()
;(eswalk as any)(root, {
enter(node: Node, parent: Node | null) {
parent && parentStack.push(parent)
if (node.type === 'ImportDeclaration') {
return this.skip()
}
if (node.type === 'MetaProperty' && node.meta.name === 'import') {
onImportMeta(node)
} else if (node.type === 'ImportExpression') {
onDynamicImport(node)
}
if (node.type === 'Identifier') {
if (!scope[node.name] && isRefIdentifier(node, parent!, parentStack)) {
onIdentifier(node, parent!, parentStack)
}
} else if (isFunction(node)) {
// walk function expressions and add its arguments to known identifiers
// so that we don't prefix them
node.params.forEach((p) =>
(eswalk as any)(p, {
enter(child: Node, parent: Node) {
if (
child.type === 'Identifier' &&
// do not record as scope variable if is a destructured key
!isStaticPropertyKey(child, parent) &&
// do not record if this is a default value
// assignment of a destructured variable
!(
parent &&
parent.type === 'AssignmentPattern' &&
parent.right === child
)
) {
const { name } = child
let scopeIds = scopeMap.get(node)
if (scopeIds && scopeIds.has(name)) {
return
}
if (name in scope) {
scope[name]++
} else {
scope[name] = 1
}
if (!scopeIds) {
scopeIds = new Set()
scopeMap.set(node, scopeIds)
}
scopeIds.add(name)
}
}
})
)
} else if (node.type === 'Property' && parent!.type === 'ObjectPattern') {
// mark property in destructure pattern
;(node as any).inPattern = true
}
},
leave(node: Node, parent: Node | null) {
parent && parentStack.pop()
const scopeIds = scopeMap.get(node)
if (scopeIds) {
scopeIds.forEach((id: string) => {
scope[id]--
if (scope[id] === 0) {
delete scope[id]
}
})
}
}
})
}
function isRefIdentifier(id: Identifier, parent: _Node, parentStack: _Node[]) {
// declaration id
if (
(parent.type === 'VariableDeclarator' ||
parent.type === 'ClassDeclaration') &&
parent.id === id
) {
return false
}
if (isFunction(parent)) {
// function decalration/expression id
if ((parent as any).id === id) {
return false
}
// params list
if (parent.params.includes(id)) {
return false
}
}
// property key
// this also covers object destructure pattern
if (isStaticPropertyKey(id, parent)) {
return false
}
// non-assignment array destructure pattern
if (
parent.type === 'ArrayPattern' &&
!isInDestructureAssignment(parent, parentStack)
) {
return false
}
// member expression property
if (
parent.type === 'MemberExpression' &&
parent.property === id &&
!parent.computed
) {
return false
}
if (parent.type === 'ExportSpecifier') {
return false
}
// is a special keyword but parsed as identifier
if (id.name === 'arguments') {
return false
}
return true
}
const isStaticProperty = (node: _Node): node is Property =>
node && node.type === 'Property' && !node.computed
const isStaticPropertyKey = (node: _Node, parent: _Node) =>
isStaticProperty(parent) && parent.key === node
function isFunction(node: _Node): node is FunctionNode {
return /Function(?:Expression|Declaration)$|Method$/.test(node.type)
}
function isInDestructureAssignment(
parent: _Node,
parentStack: _Node[]
): boolean {
if (
parent &&
(parent.type === 'Property' || parent.type === 'ArrayPattern')
) {
let i = parentStack.length
while (i--) {
const p = parentStack[i]
if (p.type === 'AssignmentExpression') {
return true
} else if (p.type !== 'Property' && !p.type.endsWith('Pattern')) {
break
}
}
}
return false
}
| packages/vite/src/node/ssr/ssrTransform.ts | 0 | https://github.com/vitejs/vite/commit/af2fe243f7bf0762c763e703bb50dd7f3648cd77 | [
0.00017608674534130841,
0.00016959791537374258,
0.00016529634012840688,
0.0001694076636340469,
0.000002416251845716033
]
|
{
"id": 0,
"code_window": [
"<template>\n",
" <div>\n",
" <router-link to=\"/\">Home</router-link> | \n",
" <router-link to=\"/about\">About</router-link>\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" <router-link to=\"/\">Home</router-link>|\n"
],
"file_path": "packages/playground/ssr-vue/src/App.vue",
"type": "replace",
"edit_start_line_idx": 2
} | import { cac } from 'cac'
import chalk from 'chalk'
import { BuildOptions } from './build'
import { ServerOptions } from './server'
import { createLogger, LogLevel } from './logger'
import { resolveConfig } from '.'
import { serve } from './serve'
const cli = cac('vite')
// global options
interface GlobalCLIOptions {
'--'?: string[]
debug?: boolean | string
d?: boolean | string
filter?: string
f?: string
config?: string
c?: boolean | string
root?: string
base?: string
r?: string
mode?: string
m?: string
logLevel?: LogLevel
l?: LogLevel
clearScreen?: boolean
}
/**
* removing global flags before passing as command specific sub-configs
*/
function cleanOptions(options: GlobalCLIOptions) {
const ret = { ...options }
delete ret['--']
delete ret.debug
delete ret.d
delete ret.filter
delete ret.f
delete ret.config
delete ret.c
delete ret.root
delete ret.base
delete ret.r
delete ret.mode
delete ret.m
delete ret.logLevel
delete ret.l
delete ret.clearScreen
return ret
}
cli
.option('-c, --config <file>', `[string] use specified config file`)
.option('-r, --root <path>', `[string] use specified root directory`)
.option('--base <path>', `[string] public base path (default: /)`)
.option('-l, --logLevel <level>', `[string] silent | error | warn | all`)
.option('--clearScreen', `[boolean] allow/disable clear screen when logging`)
.option('-d, --debug [feat]', `[string | boolean] show debug logs`)
.option('-f, --filter <filter>', `[string] filter debug logs`)
// dev
cli
.command('[root]') // default command
.alias('serve')
.option('--host <host>', `[string] specify hostname`)
.option('--port <port>', `[number] specify port`)
.option('--https', `[boolean] use TLS + HTTP/2`)
.option('--open [browser]', `[boolean | string] open browser on startup`)
.option('--cors', `[boolean] enable CORS`)
.option('--strictPort', `[boolean] exit if specified port is already in use`)
.option('-m, --mode <mode>', `[string] set env mode`)
.option(
'--force',
`[boolean] force the optimizer to ignore the cache and re-bundle`
)
.action(async (root: string, options: ServerOptions & GlobalCLIOptions) => {
// output structure is preserved even after bundling so require()
// is ok here
const { createServer } = await import('./server')
try {
const server = await createServer({
root,
base: options.base,
mode: options.mode,
configFile: options.config,
logLevel: options.logLevel,
clearScreen: options.clearScreen,
server: cleanOptions(options) as ServerOptions
})
await server.listen()
} catch (e) {
createLogger(options.logLevel).error(
chalk.red(`error when starting dev server:\n${e.stack}`)
)
process.exit(1)
}
})
// build
cli
.command('build [root]')
.option('--target <target>', `[string] transpile target (default: 'modules')`)
.option('--outDir <dir>', `[string] output directory (default: dist)`)
.option(
'--assetsDir <dir>',
`[string] directory under outDir to place assets in (default: _assets)`
)
.option(
'--assetsInlineLimit <number>',
`[number] static asset base64 inline threshold in bytes (default: 4096)`
)
.option(
'--ssr [entry]',
`[string] build specified entry for server-side rendering`
)
.option(
'--sourcemap',
`[boolean] output source maps for build (default: false)`
)
.option(
'--minify [minifier]',
`[boolean | "terser" | "esbuild"] enable/disable minification, ` +
`or specify minifier to use (default: terser)`
)
.option('--manifest', `[boolean] emit build manifest json`)
.option('--ssrManifest', `[boolean] emit ssr manifest json`)
.option(
'--emptyOutDir',
`[boolean] force empty outDir when it's outside of root`
)
.option('-m, --mode <mode>', `[string] set env mode`)
.action(async (root: string, options: BuildOptions & GlobalCLIOptions) => {
const { build } = await import('./build')
const buildOptions = cleanOptions(options) as BuildOptions
try {
await build({
root,
base: options.base,
mode: options.mode,
configFile: options.config,
logLevel: options.logLevel,
clearScreen: options.clearScreen,
build: buildOptions
})
} catch (e) {
createLogger(options.logLevel).error(
chalk.red(`error during build:\n${e.stack}`)
)
process.exit(1)
}
})
// optimize
cli
.command('optimize [root]')
.option(
'--force',
`[boolean] force the optimizer to ignore the cache and re-bundle`
)
.action(
async (root: string, options: { force?: boolean } & GlobalCLIOptions) => {
const { optimizeDeps } = await import('./optimizer')
try {
const config = await resolveConfig(
{
root,
base: options.base,
configFile: options.config,
logLevel: options.logLevel
},
'build',
'development'
)
await optimizeDeps(config, options.force, true)
} catch (e) {
createLogger(options.logLevel).error(
chalk.red(`error when optimizing deps:\n${e.stack}`)
)
process.exit(1)
}
}
)
cli
.command('preview [root]')
.option('--port <port>', `[number] specify port`)
.action(
async (root: string, options: { port?: number } & GlobalCLIOptions) => {
try {
const config = await resolveConfig(
{
root,
base: options.base,
configFile: options.config,
logLevel: options.logLevel
},
'serve',
'development'
)
await serve(config, options.port)
} catch (e) {
createLogger(options.logLevel).error(
chalk.red(`error when starting preview server:\n${e.stack}`)
)
process.exit(1)
}
}
)
cli.help()
cli.version(require('../../package.json').version)
cli.parse()
| packages/vite/src/node/cli.ts | 0 | https://github.com/vitejs/vite/commit/af2fe243f7bf0762c763e703bb50dd7f3648cd77 | [
0.0001756601413944736,
0.00017059576930478215,
0.00016600902017671615,
0.00017072207992896438,
0.0000024616977043478983
]
|
{
"id": 0,
"code_window": [
"<template>\n",
" <div>\n",
" <router-link to=\"/\">Home</router-link> | \n",
" <router-link to=\"/about\">About</router-link>\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" <router-link to=\"/\">Home</router-link>|\n"
],
"file_path": "packages/playground/ssr-vue/src/App.vue",
"type": "replace",
"edit_start_line_idx": 2
} | declare module 'connect' {
const connect: () => any
export = connect
}
declare module 'cors' {
function cors(options: any): any
export = cors
}
declare module 'selfsigned' {
export function generate(attrs: any, options: any, done?: any): any
}
declare module 'http-proxy' {
const proxy: any
export = proxy
}
declare module 'acorn-class-fields' {
const plugin: any
export = plugin
}
declare module 'acorn-static-class-features' {
const plugin: any
export default plugin
}
declare module 'acorn-numeric-separator' {
const plugin: any
export default plugin
}
declare module 'connect-history-api-fallback' {
const plugin: any
export = plugin
}
declare module 'launch-editor-middleware' {
const plugin: any
export = plugin
}
declare module 'merge-source-map' {
export default function merge(oldMap: object, newMap: object): object
}
declare module 'postcss-load-config' {
import { ProcessOptions, Plugin } from 'postcss'
function load(
inline: any,
root: string
): Promise<{
options: ProcessOptions
plugins: Plugin[]
}>
export = load
}
declare module 'postcss-import' {
import { Plugin } from 'postcss'
const plugin: (options: {
resolve: (
id: string,
basedir: string,
importOptions: any
) => string | string[] | Promise<string | string[]>
}) => Plugin
export = plugin
}
declare module 'postcss-modules' {
import { Plugin } from 'postcss'
const plugin: (options: any) => Plugin
export = plugin
}
declare module '@rollup/plugin-dynamic-import-vars' {
import { Plugin } from 'rollup'
interface Options {
include?: string | RegExp | (string | RegExp)[]
exclude?: string | RegExp | (string | RegExp)[]
warnOnError?: boolean
}
const p: (o?: Options) => Plugin
export default p
}
declare module 'rollup-plugin-web-worker-loader' {
import { Plugin } from 'rollup'
interface Options {
targetPlatform?: string
pattern?: RegExp
extensions?: string[]
sourcemap?: boolean
inline?: boolean
}
const p: (o?: Options) => Plugin
export default p
}
declare module 'minimatch' {
function match(path: string, pattern: string): boolean
export default match
}
declare module 'compression' {
function compression(): any
export default compression
}
// LESS' types somewhat references this which doesn't make sense in Node,
// so we have to shim it
declare interface HTMLLinkElement {}
| packages/vite/types/shims.d.ts | 0 | https://github.com/vitejs/vite/commit/af2fe243f7bf0762c763e703bb50dd7f3648cd77 | [
0.0001745919289533049,
0.00017069843306671828,
0.00016809164662845433,
0.00017091407789848745,
0.0000020316253994678846
]
|
{
"id": 1,
"code_window": [
" <router-link to=\"/about\">About</router-link>\n",
" <router-view/>\n",
" </div>\n",
"</template>\n",
"\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" <router-view v-slot=\"{ Component }\">\n",
" <Suspense>\n",
" <component :is=\"Component\" />\n",
" </Suspense>\n",
" </router-view>\n"
],
"file_path": "packages/playground/ssr-vue/src/App.vue",
"type": "replace",
"edit_start_line_idx": 4
} | <template>
<div>
<router-link to="/">Home</router-link> |
<router-link to="/about">About</router-link>
<router-view/>
</div>
</template>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style> | packages/playground/ssr-vue/src/App.vue | 1 | https://github.com/vitejs/vite/commit/af2fe243f7bf0762c763e703bb50dd7f3648cd77 | [
0.5495356321334839,
0.27485135197639465,
0.00016704668814782053,
0.27485135197639465,
0.2746843099594116
]
|
{
"id": 1,
"code_window": [
" <router-link to=\"/about\">About</router-link>\n",
" <router-view/>\n",
" </div>\n",
"</template>\n",
"\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" <router-view v-slot=\"{ Component }\">\n",
" <Suspense>\n",
" <component :is=\"Component\" />\n",
" </Suspense>\n",
" </router-view>\n"
],
"file_path": "packages/playground/ssr-vue/src/App.vue",
"type": "replace",
"edit_start_line_idx": 4
} | const vue = require('@vitejs/plugin-vue')
/**
* @type {import('vite').UserConfig}
*/
module.exports = {
resolve: {
dedupe: ['react']
},
optimizeDeps: {
include: ['dep-linked-include'],
plugins: [vue()]
},
build: {
// to make tests faster
minify: false
},
plugins: [
vue(),
// for axios request test
{
name: 'mock',
configureServer({ middlewares }) {
middlewares.use('/ping', (_, res) => {
res.statusCode = 200
res.end('pong')
})
}
}
]
}
| packages/playground/optimize-deps/vite.config.js | 0 | https://github.com/vitejs/vite/commit/af2fe243f7bf0762c763e703bb50dd7f3648cd77 | [
0.00017744963406585157,
0.0001748301147017628,
0.0001720010332064703,
0.00017493488849140704,
0.0000022410956717067165
]
|
{
"id": 1,
"code_window": [
" <router-link to=\"/about\">About</router-link>\n",
" <router-view/>\n",
" </div>\n",
"</template>\n",
"\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" <router-view v-slot=\"{ Component }\">\n",
" <Suspense>\n",
" <component :is=\"Component\" />\n",
" </Suspense>\n",
" </router-view>\n"
],
"file_path": "packages/playground/ssr-vue/src/App.vue",
"type": "replace",
"edit_start_line_idx": 4
} | import path from 'path'
import { OutputChunk } from 'rollup'
import { ResolvedConfig } from '..'
import { Plugin } from '../plugin'
import { chunkToEmittedCssFileMap } from './css'
import { chunkToEmittedAssetsMap } from './asset'
import { normalizePath } from '../utils'
type Manifest = Record<string, ManifestChunk>
interface ManifestChunk {
src?: string
file: string
css?: string[]
assets?: string[]
isEntry?: boolean
isDynamicEntry?: boolean
imports?: string[]
dynamicImports?: string[]
}
export function manifestPlugin(config: ResolvedConfig): Plugin {
const manifest: Manifest = {}
let outputCount = 0
return {
name: 'vite:manifest',
generateBundle({ format }, bundle) {
function getChunkName(chunk: OutputChunk) {
if (chunk.facadeModuleId) {
let name = normalizePath(
path.relative(config.root, chunk.facadeModuleId)
)
if (format === 'system' && !chunk.name.includes('-legacy')) {
const ext = path.extname(name)
name = name.slice(0, -ext.length) + `-legacy` + ext
}
return name
} else {
return `_` + path.basename(chunk.fileName)
}
}
function createChunk(chunk: OutputChunk): ManifestChunk {
const manifestChunk: ManifestChunk = {
file: chunk.fileName
}
if (chunk.facadeModuleId) {
manifestChunk.src = getChunkName(chunk)
}
if (chunk.isEntry) {
manifestChunk.isEntry = true
}
if (chunk.isDynamicEntry) {
manifestChunk.isDynamicEntry = true
}
if (chunk.imports.length) {
manifestChunk.imports = chunk.imports.map((file) =>
getChunkName(bundle[file] as OutputChunk)
)
}
if (chunk.dynamicImports.length) {
manifestChunk.dynamicImports = chunk.dynamicImports.map((file) =>
getChunkName(bundle[file] as OutputChunk)
)
}
const cssFiles = chunkToEmittedCssFileMap.get(chunk)
if (cssFiles) {
manifestChunk.css = [...cssFiles]
}
const assets = chunkToEmittedAssetsMap.get(chunk)
if (assets) [(manifestChunk.assets = [...assets])]
return manifestChunk
}
for (const file in bundle) {
const chunk = bundle[file]
if (chunk.type === 'chunk') {
manifest[getChunkName(chunk)] = createChunk(chunk)
}
}
outputCount++
const output = config.build.rollupOptions?.output
const outputLength = Array.isArray(output) ? output.length : 1
if (outputCount >= outputLength) {
this.emitFile({
fileName: `manifest.json`,
type: 'asset',
source: JSON.stringify(manifest, null, 2)
})
}
}
}
}
| packages/vite/src/node/plugins/manifest.ts | 0 | https://github.com/vitejs/vite/commit/af2fe243f7bf0762c763e703bb50dd7f3648cd77 | [
0.00017834032769314945,
0.00017369288252666593,
0.0001695193350315094,
0.00017407014092896134,
0.0000021048379039712017
]
|
{
"id": 1,
"code_window": [
" <router-link to=\"/about\">About</router-link>\n",
" <router-view/>\n",
" </div>\n",
"</template>\n",
"\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" <router-view v-slot=\"{ Component }\">\n",
" <Suspense>\n",
" <component :is=\"Component\" />\n",
" </Suspense>\n",
" </router-view>\n"
],
"file_path": "packages/playground/ssr-vue/src/App.vue",
"type": "replace",
"edit_start_line_idx": 4
} | // @ts-check
import fs from 'fs'
import path from 'path'
import nodeResolve from '@rollup/plugin-node-resolve'
import typescript from '@rollup/plugin-typescript'
import commonjs from '@rollup/plugin-commonjs'
import json from '@rollup/plugin-json'
import alias from '@rollup/plugin-alias'
import license from 'rollup-plugin-license'
import MagicString from 'magic-string'
import chalk from 'chalk'
/**
* @type { import('rollup').RollupOptions }
*/
const envConfig = {
input: path.resolve(__dirname, 'src/client/env.ts'),
plugins: [
typescript({
target: 'es2018',
include: ['src/client/env.ts'],
baseUrl: path.resolve(__dirname, 'src/env'),
paths: {
'types/*': ['../../types/*']
}
})
],
output: {
dir: path.resolve(__dirname, 'dist/client')
}
}
/**
* @type { import('rollup').RollupOptions }
*/
const clientConfig = {
input: path.resolve(__dirname, 'src/client/client.ts'),
external: ['./env'],
plugins: [
typescript({
target: 'es2018',
include: ['src/client/**/*.ts'],
baseUrl: path.resolve(__dirname, 'src/client'),
paths: {
'types/*': ['../../types/*']
}
})
],
output: {
dir: path.resolve(__dirname, 'dist/client')
}
}
/**
* @type { import('rollup').RollupOptions }
*/
const sharedNodeOptions = {
treeshake: {
moduleSideEffects: 'no-external',
propertyReadSideEffects: false,
tryCatchDeoptimization: false
},
output: {
dir: path.resolve(__dirname, 'dist/node'),
entryFileNames: `[name].js`,
chunkFileNames: 'chunks/dep-[hash].js',
exports: 'named',
format: 'cjs',
externalLiveBindings: false,
freeze: false
},
onwarn(warning, warn) {
// node-resolve complains a lot about this but seems to still work?
if (warning.message.includes('Package subpath')) {
return
}
// we use the eval('require') trick to deal with optional deps
if (warning.message.includes('Use of eval')) {
return
}
if (warning.message.includes('Circular dependency')) {
return
}
warn(warning)
}
}
/**
* @type { import('rollup').RollupOptions }
*/
const nodeConfig = {
...sharedNodeOptions,
input: {
index: path.resolve(__dirname, 'src/node/index.ts'),
cli: path.resolve(__dirname, 'src/node/cli.ts')
},
external: [
'fsevents',
...Object.keys(require('./package.json').dependencies)
],
plugins: [
alias({
// packages with "module" field that doesn't play well with cjs bundles
entries: {
'@vue/compiler-dom': require.resolve(
'@vue/compiler-dom/dist/compiler-dom.cjs.js'
),
'big.js': require.resolve('big.js/big.js')
}
}),
nodeResolve({ preferBuiltins: true }),
typescript({
target: 'es2019',
include: ['src/**/*.ts'],
esModuleInterop: true
}),
// Some deps have try...catch require of optional deps, but rollup will
// generate code that force require them upfront for side effects.
// Shim them with eval() so rollup can skip these calls.
shimDepsPlugin({
'plugins/terser.ts': {
src: `require.resolve('terser'`,
replacement: `require.resolve('vite/dist/node/terser'`
},
// chokidar -> fsevents
'fsevents-handler.js': {
src: `require('fsevents')`,
replacement: `eval('require')('fsevents')`
},
// cac re-assigns module.exports even in its mjs dist
'cac/dist/index.mjs': {
src: `if (typeof module !== "undefined") {`,
replacement: `if (false) {`
},
// postcss-import -> sugarss
'process-content.js': {
src: 'require("sugarss")',
replacement: `eval('require')('sugarss')`
},
'import-fresh/index.js': {
src: `require(filePath)`,
replacement: `eval('require')(filePath)`
},
'import-from/index.js': {
pattern: /require\(resolveFrom/g,
replacement: `eval('require')(resolveFrom`
}
}),
// Optional peer deps of ws. Native deps that are mostly for performance.
// Since ws is not that perf critical for us, just ignore these deps.
ignoreDepPlugin({
bufferutil: 1,
'utf-8-validate': 1
}),
commonjs({ extensions: ['.js'] }),
json(),
licensePlugin()
]
}
/**
* Terser needs to be run inside a worker, so it cannot be part of the main
* bundle. We produce a separate bundle for it and shims plugin/terser.ts to
* use the production path during build.
*
* @type { import('rollup').RollupOptions }
*/
const terserConfig = {
...sharedNodeOptions,
output: {
...sharedNodeOptions.output,
exports: 'default'
},
input: {
terser: require.resolve('terser')
},
plugins: [nodeResolve(), commonjs()]
}
/**
* @type { (deps: Record<string, { src?: string, replacement: string, pattern?: RegExp }>) => import('rollup').Plugin }
*/
function shimDepsPlugin(deps) {
const transformed = {}
return {
name: 'shim-deps',
transform(code, id) {
for (const file in deps) {
if (id.replace(/\\/g, '/').endsWith(file)) {
const { src, replacement, pattern } = deps[file]
const magicString = new MagicString(code)
if (src) {
const pos = code.indexOf(src)
if (pos < 0) {
this.error(
`Could not find expected src "${src}" in file "${file}"`
)
}
transformed[file] = true
magicString.overwrite(pos, pos + src.length, replacement)
console.log(`shimmed: ${file}`)
}
if (pattern) {
let match
while ((match = pattern.exec(code))) {
transformed[file] = true
const start = match.index
const end = start + match[0].length
magicString.overwrite(start, end, replacement)
}
if (!transformed[file]) {
this.error(
`Could not find expected pattern "${pattern}" in file "${file}"`
)
}
console.log(`shimmed: ${file}`)
}
return {
code: magicString.toString(),
map: magicString.generateMap({ hires: true })
}
}
}
},
buildEnd(err) {
if (!err) {
for (const file in deps) {
if (!transformed[file]) {
this.error(
`Did not find "${file}" which is supposed to be shimmed, was the file renamed?`
)
}
}
}
}
}
}
/**
* @type { (deps: Record<string, any>) => import('rollup').Plugin }
*/
function ignoreDepPlugin(ignoredDeps) {
return {
name: 'ignore-deps',
resolveId(id) {
if (id in ignoredDeps) {
return id
}
},
load(id) {
if (id in ignoredDeps) {
console.log(`ignored: ${id}`)
return ''
}
}
}
}
function licensePlugin() {
return license({
thirdParty(dependencies) {
// https://github.com/rollup/rollup/blob/master/build-plugins/generate-license-file.js
// MIT Licensed https://github.com/rollup/rollup/blob/master/LICENSE-CORE.md
const coreLicense = fs.readFileSync(
path.resolve(__dirname, '../../LICENSE')
)
const licenses = new Set()
const dependencyLicenseTexts = dependencies
.sort(({ name: nameA }, { name: nameB }) => (nameA > nameB ? 1 : -1))
.map(
({
name,
license,
licenseText,
author,
maintainers,
contributors,
repository
}) => {
let text = `## ${name}\n`
if (license) {
text += `License: ${license}\n`
}
const names = new Set()
if (author && author.name) {
names.add(author.name)
}
for (const person of maintainers.concat(contributors)) {
if (person && person.name) {
names.add(person.name)
}
}
if (names.size > 0) {
text += `By: ${Array.from(names).join(', ')}\n`
}
if (repository) {
text += `Repository: ${repository.url || repository}\n`
}
if (licenseText) {
text +=
'\n' +
licenseText
.trim()
.replace(/(\r\n|\r)/gm, '\n')
.split('\n')
.map((line) => `> ${line}`)
.join('\n') +
'\n'
}
licenses.add(license)
return text
}
)
.join('\n---------------------------------------\n\n')
const licenseText =
`# Vite core license\n` +
`Vite is released under the MIT license:\n\n` +
coreLicense +
`\n# Licenses of bundled dependencies\n` +
`The published Vite artifact additionally contains code with the following licenses:\n` +
`${Array.from(licenses).join(', ')}\n\n` +
`# Bundled dependencies:\n` +
dependencyLicenseTexts
const existingLicenseText = fs.readFileSync('LICENSE.md', 'utf8')
if (existingLicenseText !== licenseText) {
fs.writeFileSync('LICENSE.md', licenseText)
console.warn(
chalk.yellow(
'\nLICENSE.md updated. You should commit the updated file.\n'
)
)
}
}
})
}
export default [envConfig, clientConfig, nodeConfig, terserConfig]
| packages/vite/rollup.config.js | 0 | https://github.com/vitejs/vite/commit/af2fe243f7bf0762c763e703bb50dd7f3648cd77 | [
0.0001771997194737196,
0.00017190737708006054,
0.00016570379375480115,
0.00017151216161437333,
0.0000026486047772777965
]
|
{
"id": 2,
"code_window": [
"<template>\n",
" <h1>About</h1>\n",
"</template>\n",
"\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
" <h1>{{ msg }}</h1>\n"
],
"file_path": "packages/playground/ssr-vue/src/pages/About.vue",
"type": "replace",
"edit_start_line_idx": 1
} | <template>
<h1>About</h1>
</template>
<style scoped>
h1 {
color: red;
}
</style> | packages/playground/ssr-vue/src/pages/About.vue | 1 | https://github.com/vitejs/vite/commit/af2fe243f7bf0762c763e703bb50dd7f3648cd77 | [
0.17107996344566345,
0.17107996344566345,
0.17107996344566345,
0.17107996344566345,
0
]
|
{
"id": 2,
"code_window": [
"<template>\n",
" <h1>About</h1>\n",
"</template>\n",
"\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
" <h1>{{ msg }}</h1>\n"
],
"file_path": "packages/playground/ssr-vue/src/pages/About.vue",
"type": "replace",
"edit_start_line_idx": 1
} | import React, { useState } from 'react'
import logo from './logo.svg'
import './App.css'
function App() {
const [count, setCount] = useState(0)
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>Hello Vite + React!</p>
<p>
<button onClick={() => setCount((count) => count + 1)}>
count is: {count}
</button>
</p>
<p>
Edit <code>App.jsx</code> and save to test HMR updates.
</p>
<p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
{' | '}
<a
className="App-link"
href="https://vitejs.dev/guide/features.html"
target="_blank"
rel="noopener noreferrer"
>
Vite Docs
</a>
</p>
</header>
</div>
)
}
export default App
| packages/create-app/template-react/src/App.jsx | 0 | https://github.com/vitejs/vite/commit/af2fe243f7bf0762c763e703bb50dd7f3648cd77 | [
0.00017075828509405255,
0.00016836386930663139,
0.0001646713208174333,
0.0001686283212620765,
0.0000020758707250934094
]
|
{
"id": 2,
"code_window": [
"<template>\n",
" <h1>About</h1>\n",
"</template>\n",
"\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
" <h1>{{ msg }}</h1>\n"
],
"file_path": "packages/playground/ssr-vue/src/pages/About.vue",
"type": "replace",
"edit_start_line_idx": 1
} | {
"msg": "baz"
} | packages/playground/glob-import/dir/baz.json | 0 | https://github.com/vitejs/vite/commit/af2fe243f7bf0762c763e703bb50dd7f3648cd77 | [
0.00017957043019123375,
0.00017957043019123375,
0.00017957043019123375,
0.00017957043019123375,
0
]
|
{
"id": 2,
"code_window": [
"<template>\n",
" <h1>About</h1>\n",
"</template>\n",
"\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
" <h1>{{ msg }}</h1>\n"
],
"file_path": "packages/playground/ssr-vue/src/pages/About.vue",
"type": "replace",
"edit_start_line_idx": 1
} | test('string', async () => {
const defines = require('../vite.config.js').define
expect(await page.textContent('.string')).toBe(String(defines.__STRING__))
expect(await page.textContent('.number')).toBe(String(defines.__NUMBER__))
expect(await page.textContent('.boolean')).toBe(String(defines.__BOOLEAN__))
expect(await page.textContent('.object')).toBe(
JSON.stringify(defines.__OBJ__, null, 2)
)
})
| packages/playground/define/__tests__/define.spec.ts | 0 | https://github.com/vitejs/vite/commit/af2fe243f7bf0762c763e703bb50dd7f3648cd77 | [
0.00017987632600124925,
0.00017418987408746034,
0.00016850342217367142,
0.00017418987408746034,
0.000005686451913788915
]
|
{
"id": 3,
"code_window": [
"</template>\n",
"\n",
"<style scoped>\n",
"h1 {\n",
" color: red;\n",
"}\n",
"</style>\n"
],
"labels": [
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"<script>\n",
"export default {\n",
" async setup() {\n",
" return {\n",
" msg: 'About'\n",
" }\n",
" }\n",
"}\n",
"</script>\n",
"\n"
],
"file_path": "packages/playground/ssr-vue/src/pages/About.vue",
"type": "add",
"edit_start_line_idx": 4
} | <template>
<div>
<router-link to="/">Home</router-link> |
<router-link to="/about">About</router-link>
<router-view/>
</div>
</template>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style> | packages/playground/ssr-vue/src/App.vue | 1 | https://github.com/vitejs/vite/commit/af2fe243f7bf0762c763e703bb50dd7f3648cd77 | [
0.00041578360833227634,
0.00033427512971684337,
0.00025276662199757993,
0.00033427512971684337,
0.0000815084931673482
]
|
{
"id": 3,
"code_window": [
"</template>\n",
"\n",
"<style scoped>\n",
"h1 {\n",
" color: red;\n",
"}\n",
"</style>\n"
],
"labels": [
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"<script>\n",
"export default {\n",
" async setup() {\n",
" return {\n",
" msg: 'About'\n",
" }\n",
" }\n",
"}\n",
"</script>\n",
"\n"
],
"file_path": "packages/playground/ssr-vue/src/pages/About.vue",
"type": "add",
"edit_start_line_idx": 4
} | body {
color: grey;
} | packages/playground/alias/dir/test.css | 0 | https://github.com/vitejs/vite/commit/af2fe243f7bf0762c763e703bb50dd7f3648cd77 | [
0.00019417336443439126,
0.00019417336443439126,
0.00019417336443439126,
0.00019417336443439126,
0
]
|
{
"id": 3,
"code_window": [
"</template>\n",
"\n",
"<style scoped>\n",
"h1 {\n",
" color: red;\n",
"}\n",
"</style>\n"
],
"labels": [
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"<script>\n",
"export default {\n",
" async setup() {\n",
" return {\n",
" msg: 'About'\n",
" }\n",
" }\n",
"}\n",
"</script>\n",
"\n"
],
"file_path": "packages/playground/ssr-vue/src/pages/About.vue",
"type": "add",
"edit_start_line_idx": 4
} | blank_issues_enabled: false
contact_links:
- name: Discord Chat
url: https://chat.vitejs.dev
about: Ask questions and discuss with other Vite users in real time.
- name: Questions & Discussions
url: https://github.com/vitejs/vite/discussions
about: Use GitHub discussions for message-board style questions and discussions.
| .github/ISSUE_TEMPLATE/config.yml | 0 | https://github.com/vitejs/vite/commit/af2fe243f7bf0762c763e703bb50dd7f3648cd77 | [
0.0001676234824117273,
0.0001676234824117273,
0.0001676234824117273,
0.0001676234824117273,
0
]
|
{
"id": 3,
"code_window": [
"</template>\n",
"\n",
"<style scoped>\n",
"h1 {\n",
" color: red;\n",
"}\n",
"</style>\n"
],
"labels": [
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"<script>\n",
"export default {\n",
" async setup() {\n",
" return {\n",
" msg: 'About'\n",
" }\n",
" }\n",
"}\n",
"</script>\n",
"\n"
],
"file_path": "packages/playground/ssr-vue/src/pages/About.vue",
"type": "add",
"edit_start_line_idx": 4
} |
{
"compilerOptions": {
"target": "ESNext",
"lib": ["DOM", "DOM.Iterable", "ESNext"],
"types": [],
"allowJs": false,
"skipLibCheck": false,
"esModuleInterop": false,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "ESNext",
"moduleResolution": "Node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react",
"jsxFactory": "h",
"jsxFragmentFactory": "Fragment"
},
"include": ["src"]
}
| packages/create-app/template-preact-ts/tsconfig.json | 0 | https://github.com/vitejs/vite/commit/af2fe243f7bf0762c763e703bb50dd7f3648cd77 | [
0.00017773683066479862,
0.00017541814304422587,
0.0001732268719933927,
0.00017529069737065583,
0.0000018433865989209153
]
|
{
"id": 0,
"code_window": [
"node_modules\n",
"build\n",
"release\n",
"binaries\n"
],
"labels": [
"keep",
"keep",
"keep",
"add"
],
"after_edit": [
"source"
],
"file_path": ".gitignore",
"type": "add",
"edit_start_line_idx": 4
} | node_modules
build
release
binaries
| .gitignore | 1 | https://github.com/coder/code-server/commit/82e2b8a1698ece678f732a1d60f359997ac311ed | [
0.06893381476402283,
0.06893381476402283,
0.06893381476402283,
0.06893381476402283,
0
]
|
{
"id": 0,
"code_window": [
"node_modules\n",
"build\n",
"release\n",
"binaries\n"
],
"labels": [
"keep",
"keep",
"keep",
"add"
],
"after_edit": [
"source"
],
"file_path": ".gitignore",
"type": "add",
"edit_start_line_idx": 4
} | import * as cp from "child_process";
import * as os from "os";
import * as path from "path";
import { setUnexpectedErrorHandler } from "vs/base/common/errors";
import { main as vsCli } from "vs/code/node/cliProcessMain";
import { validatePaths } from "vs/code/node/paths";
import { ParsedArgs } from "vs/platform/environment/common/environment";
import { buildHelpMessage, buildVersionMessage, Option as VsOption, OPTIONS, OptionDescriptions } from "vs/platform/environment/node/argv";
import { parseMainProcessArgv } from "vs/platform/environment/node/argvHelper";
import product from "vs/platform/product/common/product";
import { ipcMain } from "vs/server/src/node/ipc";
import { enableCustomMarketplace } from "vs/server/src/node/marketplace";
import { MainServer } from "vs/server/src/node/server";
import { AuthType, buildAllowedMessage, enumToArray, FormatType, generateCertificate, generatePassword, localRequire, open, unpackExecutables } from "vs/server/src/node/util";
const { logger } = localRequire<typeof import("@coder/logger/out/index")>("@coder/logger/out/index");
setUnexpectedErrorHandler((error) => logger.warn(error.message));
interface Args extends ParsedArgs {
auth?: AuthType;
"base-path"?: string;
cert?: string;
"cert-key"?: string;
format?: string;
host?: string;
open?: boolean;
port?: string;
socket?: string;
}
// @ts-ignore: Force `keyof Args` to work.
interface Option extends VsOption {
id: keyof Args;
}
const getArgs = (): Args => {
// Remove options that won't work or don't make sense.
for (let key in OPTIONS) {
switch (key) {
case "add":
case "diff":
case "file-uri":
case "folder-uri":
case "goto":
case "new-window":
case "reuse-window":
case "wait":
case "disable-gpu":
// TODO: pretty sure these don't work but not 100%.
case "max-memory":
case "prof-startup":
case "inspect-extensions":
case "inspect-brk-extensions":
delete OPTIONS[key];
break;
}
}
const options = OPTIONS as OptionDescriptions<Required<Args>>;
options["base-path"] = { type: "string", cat: "o", description: "Base path of the URL at which code-server is hosted (used for login redirects)." };
options["cert"] = { type: "string", cat: "o", description: "Path to certificate. If the path is omitted, both this and --cert-key will be generated." };
options["cert-key"] = { type: "string", cat: "o", description: "Path to the certificate's key if one was provided." };
options["format"] = { type: "string", cat: "o", description: `Format for the version. ${buildAllowedMessage(FormatType)}.` };
options["host"] = { type: "string", cat: "o", description: "Host for the server." };
options["auth"] = { type: "string", cat: "o", description: `The type of authentication to use. ${buildAllowedMessage(AuthType)}.` };
options["open"] = { type: "boolean", cat: "o", description: "Open in the browser on startup." };
options["port"] = { type: "string", cat: "o", description: "Port for the main server." };
options["socket"] = { type: "string", cat: "o", description: "Listen on a socket instead of host:port." };
const args = parseMainProcessArgv(process.argv);
if (!args["user-data-dir"]) {
args["user-data-dir"] = path.join(process.env.XDG_DATA_HOME || path.join(os.homedir(), ".local/share"), "code-server");
}
if (!args["extensions-dir"]) {
args["extensions-dir"] = path.join(args["user-data-dir"], "extensions");
}
if (!args.verbose && !args.log && process.env.LOG_LEVEL) {
args.log = process.env.LOG_LEVEL;
}
return validatePaths(args);
};
const startVscode = async (): Promise<void | void[]> => {
const args = getArgs();
const extra = args["_"] || [];
const options = {
auth: args.auth,
basePath: args["base-path"],
cert: args.cert,
certKey: args["cert-key"],
folderUri: extra.length > 1 ? extra[extra.length - 1] : undefined,
host: args.host,
password: process.env.PASSWORD,
};
if (options.auth && enumToArray(AuthType).filter((t) => t === options.auth).length === 0) {
throw new Error(`'${options.auth}' is not a valid authentication type.`);
} else if (options.auth && !options.password) {
options.password = await generatePassword();
}
if (!options.certKey && typeof options.certKey !== "undefined") {
throw new Error(`--cert-key cannot be blank`);
} else if (options.certKey && !options.cert) {
throw new Error(`--cert-key was provided but --cert was not`);
} if (!options.cert && typeof options.cert !== "undefined") {
const { cert, certKey } = await generateCertificate();
options.cert = cert;
options.certKey = certKey;
}
enableCustomMarketplace();
const server = new MainServer({
...options,
port: typeof args.port !== "undefined" ? parseInt(args.port, 10) : 8080,
socket: args.socket,
}, args);
const [serverAddress, /* ignore */] = await Promise.all([
server.listen(),
unpackExecutables(),
]);
logger.info(`Server listening on ${serverAddress}`);
if (options.auth && !process.env.PASSWORD) {
logger.info(` - Password is ${options.password}`);
logger.info(" - To use your own password, set the PASSWORD environment variable");
} else if (options.auth) {
logger.info(" - Using custom password for authentication");
} else {
logger.info(" - No authentication");
}
if (server.protocol === "https") {
logger.info(
args.cert
? ` - Using provided certificate${args["cert-key"] ? " and key" : ""} for HTTPS`
: ` - Using generated certificate and key for HTTPS`,
);
} else {
logger.info(" - Not serving HTTPS");
}
if (!server.options.socket && args.open) {
// The web socket doesn't seem to work if browsing with 0.0.0.0.
const openAddress = serverAddress.replace(/:\/\/0.0.0.0/, "://localhost");
await open(openAddress).catch(console.error);
logger.info(` - Opened ${openAddress}`);
}
};
const startCli = (): boolean | Promise<void> => {
const args = getArgs();
if (args.help) {
const executable = `${product.applicationName}${os.platform() === "win32" ? ".exe" : ""}`;
console.log(buildHelpMessage(product.nameLong, executable, product.codeServerVersion, OPTIONS, false));
return true;
}
if (args.version) {
if (args.format === "json") {
console.log(JSON.stringify({
codeServerVersion: product.codeServerVersion,
commit: product.commit,
vscodeVersion: product.version,
}));
} else {
buildVersionMessage(product.codeServerVersion, product.commit).split("\n").map((line) => logger.info(line));
}
return true;
}
const shouldSpawnCliProcess = (): boolean => {
return !!args["install-source"]
|| !!args["list-extensions"]
|| !!args["install-extension"]
|| !!args["uninstall-extension"]
|| !!args["locate-extension"]
|| !!args["telemetry"];
};
if (shouldSpawnCliProcess()) {
enableCustomMarketplace();
return vsCli(args);
}
return false;
};
export class WrapperProcess {
private process?: cp.ChildProcess;
private started?: Promise<void>;
public constructor() {
ipcMain.onMessage(async (message) => {
switch (message) {
case "relaunch":
logger.info("Relaunching...");
this.started = undefined;
if (this.process) {
this.process.kill();
}
try {
await this.start();
} catch (error) {
logger.error(error.message);
process.exit(typeof error.code === "number" ? error.code : 1);
}
break;
default:
logger.error(`Unrecognized message ${message}`);
break;
}
});
}
public start(): Promise<void> {
if (!this.started) {
const child = this.spawn();
this.started = ipcMain.handshake(child);
this.process = child;
}
return this.started;
}
private spawn(): cp.ChildProcess {
return cp.spawn(process.argv[0], process.argv.slice(1), {
env: {
...process.env,
LAUNCH_VSCODE: "true",
},
stdio: ["inherit", "inherit", "inherit", "ipc"],
});
}
}
const main = async(): Promise<boolean | void | void[]> => {
if (process.env.LAUNCH_VSCODE) {
await ipcMain.handshake();
return startVscode();
}
return startCli() || new WrapperProcess().start();
};
const exit = process.exit;
process.exit = function (code?: number) {
const err = new Error(`process.exit() was prevented: ${code || "unknown code"}.`);
console.warn(err.stack);
} as (code?: number) => never;
// It's possible that the pipe has closed (for example if you run code-server
// --version | head -1). Assume that means we're done.
if (!process.stdout.isTTY) {
process.stdout.on("error", () => exit());
}
main().catch((error) => {
logger.error(error.message);
exit(typeof error.code === "number" ? error.code : 1);
});
| src/node/cli.ts | 0 | https://github.com/coder/code-server/commit/82e2b8a1698ece678f732a1d60f359997ac311ed | [
0.00017728879174683243,
0.0001712359517114237,
0.00016722788859624416,
0.00017033757467288524,
0.0000025131344045803417
]
|
{
"id": 0,
"code_window": [
"node_modules\n",
"build\n",
"release\n",
"binaries\n"
],
"labels": [
"keep",
"keep",
"keep",
"add"
],
"after_edit": [
"source"
],
"file_path": ".gitignore",
"type": "add",
"edit_start_line_idx": 4
} | import { DesktopDragAndDropData } from "vs/base/browser/ui/list/listView";
import { VSBuffer, VSBufferReadableStream } from "vs/base/common/buffer";
import { Disposable } from "vs/base/common/lifecycle";
import * as path from "vs/base/common/path";
import { URI } from "vs/base/common/uri";
import { generateUuid } from "vs/base/common/uuid";
import { IFileService } from "vs/platform/files/common/files";
import { createDecorator, IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { INotificationService, Severity } from "vs/platform/notification/common/notification";
import { IProgress, IProgressService, IProgressStep, ProgressLocation } from "vs/platform/progress/common/progress";
import { IWorkspaceContextService } from "vs/platform/workspace/common/workspace";
import { IWorkspacesService } from 'vs/platform/workspaces/common/workspaces';
import { ExplorerItem } from "vs/workbench/contrib/files/common/explorerModel";
import { IEditorGroup } from "vs/workbench/services/editor/common/editorGroupsService";
import { IEditorService } from "vs/workbench/services/editor/common/editorService";
export const IUploadService = createDecorator<IUploadService>("uploadService");
export interface IUploadService {
_serviceBrand: undefined;
handleDrop(event: DragEvent, resolveTargetGroup: () => IEditorGroup | undefined, afterDrop: (targetGroup: IEditorGroup | undefined) => void, targetIndex?: number): Promise<void>;
handleExternalDrop(data: DesktopDragAndDropData, target: ExplorerItem, originalEvent: DragEvent): Promise<void>;
}
export class UploadService extends Disposable implements IUploadService {
public _serviceBrand: undefined;
public upload: Upload;
public constructor(
@IInstantiationService instantiationService: IInstantiationService,
@IWorkspaceContextService private readonly contextService: IWorkspaceContextService,
@IWorkspacesService private readonly workspacesService: IWorkspacesService,
@IEditorService private readonly editorService: IEditorService,
) {
super();
this.upload = instantiationService.createInstance(Upload);
}
public async handleDrop(event: DragEvent, resolveTargetGroup: () => IEditorGroup | undefined, afterDrop: (targetGroup: IEditorGroup | undefined) => void, targetIndex?: number): Promise<void> {
// TODO: should use the workspace for the editor it was dropped on?
const target = this.contextService.getWorkspace().folders[0].uri;
const uris = (await this.upload.uploadDropped(event, target)).map((u) => URI.file(u));
if (uris.length > 0) {
await this.workspacesService.addRecentlyOpened(uris.map((u) => ({ fileUri: u })));
}
const editors = uris.map((uri) => ({
resource: uri,
options: {
pinned: true,
index: targetIndex,
},
}));
const targetGroup = resolveTargetGroup();
this.editorService.openEditors(editors, targetGroup);
afterDrop(targetGroup);
}
public async handleExternalDrop(_data: DesktopDragAndDropData, target: ExplorerItem, originalEvent: DragEvent): Promise<void> {
await this.upload.uploadDropped(originalEvent, target.resource);
}
}
/**
* There doesn't seem to be a provided type for entries, so here is an
* incomplete version.
*/
interface IEntry {
name: string;
isFile: boolean;
file: (cb: (file: File) => void) => void;
createReader: () => ({
readEntries: (cb: (entries: Array<IEntry>) => void) => void;
});
}
/**
* Handles file uploads.
*/
class Upload {
private readonly maxParallelUploads = 100;
private readonly uploadingFiles = new Map<string, Reader | undefined>();
private readonly fileQueue = new Map<string, File>();
private progress: IProgress<IProgressStep> | undefined;
private uploadPromise: Promise<string[]> | undefined;
private resolveUploadPromise: (() => void) | undefined;
private uploadedFilePaths = <string[]>[];
private _total = 0;
private _uploaded = 0;
private lastPercent = 0;
public constructor(
@INotificationService private notificationService: INotificationService,
@IProgressService private progressService: IProgressService,
@IFileService private fileService: IFileService,
) {}
/**
* Upload dropped files. This will try to upload everything it can. Errors
* will show via notifications. If an upload operation is ongoing, the files
* will be added to that operation.
*/
public async uploadDropped(event: DragEvent, uploadDir: URI): Promise<string[]> {
await this.queueFiles(event, uploadDir);
if (!this.uploadPromise) {
this.uploadPromise = this.progressService.withProgress({
cancellable: true,
location: ProgressLocation.Notification,
title: "Uploading files...",
}, (progress) => {
return new Promise((resolve): void => {
this.progress = progress;
this.resolveUploadPromise = (): void => {
const uploaded = this.uploadedFilePaths;
this.uploadPromise = undefined;
this.resolveUploadPromise = undefined;
this.uploadedFilePaths = [];
this.lastPercent = 0;
this._uploaded = 0;
this._total = 0;
resolve(uploaded);
};
});
}, () => this.cancel());
}
this.uploadFiles();
return this.uploadPromise;
}
/**
* Cancel all file uploads.
*/
public async cancel(): Promise<void> {
this.fileQueue.clear();
this.uploadingFiles.forEach((r) => r && r.abort());
}
private get total(): number { return this._total; }
private set total(total: number) {
this._total = total;
this.updateProgress();
}
private get uploaded(): number { return this._uploaded; }
private set uploaded(uploaded: number) {
this._uploaded = uploaded;
this.updateProgress();
}
private updateProgress(): void {
if (this.progress && this.total > 0) {
const percent = Math.floor((this.uploaded / this.total) * 100);
this.progress.report({ increment: percent - this.lastPercent });
this.lastPercent = percent;
}
}
/**
* Upload as many files as possible. When finished, resolve the upload
* promise.
*/
private uploadFiles(): void {
while (this.fileQueue.size > 0 && this.uploadingFiles.size < this.maxParallelUploads) {
const [path, file] = this.fileQueue.entries().next().value;
this.fileQueue.delete(path);
if (this.uploadingFiles.has(path)) {
this.notificationService.error(new Error(`Already uploading ${path}`));
} else {
this.uploadingFiles.set(path, undefined);
this.uploadFile(path, file).catch((error) => {
this.notificationService.error(error);
}).finally(() => {
this.uploadingFiles.delete(path);
this.uploadFiles();
});
}
}
if (this.fileQueue.size === 0 && this.uploadingFiles.size === 0) {
this.resolveUploadPromise!();
}
}
/**
* Upload a file, asking to override if necessary.
*/
private async uploadFile(filePath: string, file: File): Promise<void> {
const uri = URI.file(filePath);
if (await this.fileService.exists(uri)) {
const overwrite = await new Promise<boolean>((resolve): void => {
this.notificationService.prompt(
Severity.Error,
`${filePath} already exists. Overwrite?`,
[
{ label: "Yes", run: (): void => resolve(true) },
{ label: "No", run: (): void => resolve(false) },
],
{ onCancel: () => resolve(false) },
);
});
if (!overwrite) {
return;
}
}
const tempUri = uri.with({
path: path.join(
path.dirname(uri.path),
`.code-server-partial-upload-${path.basename(uri.path)}-${generateUuid()}`,
),
});
const reader = new Reader(file);
reader.on("data", (data) => {
if (data && data.byteLength > 0) {
this.uploaded += data.byteLength;
}
});
this.uploadingFiles.set(filePath, reader);
await this.fileService.writeFile(tempUri, reader);
if (reader.aborted) {
this.uploaded += (file.size - reader.offset);
await this.fileService.del(tempUri);
} else {
await this.fileService.move(tempUri, uri, true);
this.uploadedFilePaths.push(filePath);
}
}
/**
* Queue files from a drop event. We have to get the files first; we can't do
* it in tandem with uploading or the entries will disappear.
*/
private async queueFiles(event: DragEvent, uploadDir: URI): Promise<void> {
const promises: Array<Promise<void>> = [];
for (let i = 0; event.dataTransfer && event.dataTransfer.items && i < event.dataTransfer.items.length; ++i) {
const item = event.dataTransfer.items[i];
if (typeof item.webkitGetAsEntry === "function") {
promises.push(this.traverseItem(item.webkitGetAsEntry(), uploadDir.fsPath));
} else {
const file = item.getAsFile();
if (file) {
this.addFile(uploadDir.fsPath + "/" + file.name, file);
}
}
}
await Promise.all(promises);
}
/**
* Traverses an entry and add files to the queue.
*/
private async traverseItem(entry: IEntry, path: string): Promise<void> {
if (entry.isFile) {
return new Promise<void>((resolve): void => {
entry.file((file) => {
resolve(this.addFile(path + "/" + file.name, file));
});
});
}
path += "/" + entry.name;
await new Promise((resolve): void => {
const promises: Array<Promise<void>> = [];
const dirReader = entry.createReader();
// According to the spec, readEntries() must be called until it calls
// the callback with an empty array.
const readEntries = (): void => {
dirReader.readEntries((entries) => {
if (entries.length === 0) {
Promise.all(promises).then(resolve).catch((error) => {
this.notificationService.error(error);
resolve();
});
} else {
promises.push(...entries.map((c) => this.traverseItem(c, path)));
readEntries();
}
});
};
readEntries();
});
}
/**
* Add a file to the queue.
*/
private addFile(path: string, file: File): void {
this.total += file.size;
this.fileQueue.set(path, file);
}
}
class Reader implements VSBufferReadableStream {
private _offset = 0;
private readonly size = 32000; // ~32kb max while reading in the file.
private _aborted = false;
private readonly reader = new FileReader();
private paused = true;
private buffer?: VSBuffer;
private callbacks = new Map<string, Array<(...args: any[]) => void>>();
public constructor(private readonly file: File) {
this.reader.addEventListener("load", this.onLoad);
}
public get offset(): number { return this._offset; }
public get aborted(): boolean { return this._aborted; }
public on(event: "data" | "error" | "end", callback: (...args:any[]) => void): void {
if (!this.callbacks.has(event)) {
this.callbacks.set(event, []);
}
this.callbacks.get(event)!.push(callback);
if (this.aborted) {
return this.emit("error", new Error("stream has been aborted"));
} else if (this.done) {
return this.emit("error", new Error("stream has ended"));
} else if (event === "end") { // Once this is being listened to we can safely start outputting data.
this.resume();
}
}
public abort = (): void => {
this._aborted = true;
this.reader.abort();
this.reader.removeEventListener("load", this.onLoad);
this.emit("end");
}
public pause(): void {
this.paused = true;
}
public resume(): void {
if (this.paused) {
this.paused = false;
this.readNextChunk();
}
}
public destroy(): void {
this.abort();
}
private onLoad = (): void => {
this.buffer = VSBuffer.wrap(new Uint8Array(this.reader.result as ArrayBuffer));
if (!this.paused) {
this.readNextChunk();
}
}
private readNextChunk(): void {
if (this.buffer) {
this._offset += this.buffer.byteLength;
this.emit("data", this.buffer);
this.buffer = undefined;
}
if (!this.paused) { // Could be paused during the data event.
if (this.done) {
this.emit("end");
} else {
this.reader.readAsArrayBuffer(this.file.slice(this.offset, this.offset + this.size));
}
}
}
private emit(event: "data" | "error" | "end", ...args: any[]): void {
if (this.callbacks.has(event)) {
this.callbacks.get(event)!.forEach((cb) => cb(...args));
}
}
private get done(): boolean {
return this.offset >= this.file.size;
}
}
| src/browser/upload.ts | 0 | https://github.com/coder/code-server/commit/82e2b8a1698ece678f732a1d60f359997ac311ed | [
0.0001780818565748632,
0.00017170526552945375,
0.00016714754747226834,
0.0001715479011181742,
0.000002472958158250549
]
|
{
"id": 0,
"code_window": [
"node_modules\n",
"build\n",
"release\n",
"binaries\n"
],
"labels": [
"keep",
"keep",
"keep",
"add"
],
"after_edit": [
"source"
],
"file_path": ".gitignore",
"type": "add",
"edit_start_line_idx": 4
} | import { IDisposable } from "vs/base/common/lifecycle";
import { INodeProxyService } from "vs/server/src/common/nodeProxy";
import { ExtHostContext, IExtHostContext, MainContext, MainThreadNodeProxyShape } from "vs/workbench/api/common/extHost.protocol";
import { extHostNamedCustomer } from "vs/workbench/api/common/extHostCustomers";
@extHostNamedCustomer(MainContext.MainThreadNodeProxy)
export class MainThreadNodeProxy implements MainThreadNodeProxyShape {
private disposed = false;
private disposables = <IDisposable[]>[];
constructor(
extHostContext: IExtHostContext,
@INodeProxyService private readonly proxyService: INodeProxyService,
) {
if (!extHostContext.remoteAuthority) { // HACK: A terrible way to detect if running in the worker.
const proxy = extHostContext.getProxy(ExtHostContext.ExtHostNodeProxy);
this.disposables = [
this.proxyService.onMessage((message: string) => proxy.$onMessage(message)),
this.proxyService.onClose(() => proxy.$onClose()),
this.proxyService.onDown(() => proxy.$onDown()),
this.proxyService.onUp(() => proxy.$onUp()),
];
}
}
$send(message: string): void {
if (!this.disposed) {
this.proxyService.send(message);
}
}
dispose(): void {
this.disposables.forEach((d) => d.dispose());
this.disposables = [];
this.disposed = true;
}
}
| src/browser/mainThreadNodeProxy.ts | 0 | https://github.com/coder/code-server/commit/82e2b8a1698ece678f732a1d60f359997ac311ed | [
0.00017272564582526684,
0.00016945978859439492,
0.0001663627044763416,
0.00016937540203798562,
0.0000028667973310803063
]
|
{
"id": 1,
"code_window": [
"\n",
"cache:\n",
" yarn: true\n",
" directories:\n",
" - build/vscode-1.39.2-source\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace"
],
"after_edit": [
" - source"
],
"file_path": ".travis.yml",
"type": "replace",
"edit_start_line_idx": 78
} | import { Binary } from "@coder/nbin";
import * as cp from "child_process";
// import * as crypto from "crypto";
import * as fs from "fs-extra";
import * as os from "os";
import * as path from "path";
import * as util from "util";
enum Task {
/**
* Use before running anything that only works inside VS Code.
*/
EnsureInVscode = "ensure-in-vscode",
Binary = "binary",
Package = "package",
Build = "build",
}
class Builder {
private readonly rootPath = path.resolve(__dirname, "..");
private readonly outPath = process.env.OUT || this.rootPath;
private _target?: "darwin" | "alpine" | "linux";
private currentTask?: Task;
public run(task: Task | undefined, args: string[]): void {
this.currentTask = task;
this.doRun(task, args).catch((error) => {
console.error(error.message);
process.exit(1);
});
}
private async task<T>(message: string, fn: () => Promise<T>): Promise<T> {
const time = Date.now();
this.log(`${message}...`, true);
try {
const t = await fn();
process.stdout.write(`took ${Date.now() - time}ms\n`);
return t;
} catch (error) {
process.stdout.write("failed\n");
throw error;
}
}
/**
* Writes to stdout with an optional newline.
*/
private log(message: string, skipNewline: boolean = false): void {
process.stdout.write(`[${this.currentTask || "default"}] ${message}`);
if (!skipNewline) {
process.stdout.write("\n");
}
}
private async doRun(task: Task | undefined, args: string[]): Promise<void> {
if (!task) {
throw new Error("No task provided");
}
if (task === Task.EnsureInVscode) {
return process.exit(this.isInVscode(this.rootPath) ? 0 : 1);
}
// If we're inside VS Code assume we want to develop. In that case we should
// set an OUT directory and not build in this directory, otherwise when you
// build/watch VS Code the build directory will be included.
if (this.isInVscode(this.outPath)) {
throw new Error("Should not build inside VS Code; set the OUT environment variable");
}
this.ensureArgument("rootPath", this.rootPath);
this.ensureArgument("outPath", this.outPath);
const arch = this.ensureArgument("arch", os.arch().replace(/^x/, "x86_"));
const target = this.ensureArgument("target", await this.target());
const vscodeVersion = this.ensureArgument("vscodeVersion", args[0]);
const codeServerVersion = this.ensureArgument("codeServerVersion", args[1]);
const stagingPath = path.join(this.outPath, "build");
const vscodeSourcePath = path.join(stagingPath, `vscode-${vscodeVersion}-source`);
const binariesPath = path.join(this.outPath, "binaries");
const binaryName = `code-server${codeServerVersion}-vsc${vscodeVersion}-${target}-${arch}`;
const finalBuildPath = path.join(stagingPath, `${binaryName}-built`);
switch (task) {
case Task.Binary:
return this.binary(finalBuildPath, binariesPath, binaryName);
case Task.Package:
return this.package(vscodeSourcePath, binariesPath, binaryName);
case Task.Build:
return this.build(vscodeSourcePath, vscodeVersion, codeServerVersion, finalBuildPath);
default:
throw new Error(`No task matching "${task}"`);
}
}
/**
* Get the target of the system.
*/
private async target(): Promise<"darwin" | "alpine" | "linux"> {
if (!this._target) {
if (process.env.OSTYPE && /^darwin/.test(process.env.OSTYPE)) {
this._target = "darwin";
} else {
// Alpine's ldd doesn't have a version flag but if you use an invalid flag
// (like --version) it outputs the version to stderr and exits with 1.
const result = await util.promisify(cp.exec)("ldd --version")
.catch((error) => ({ stderr: error.message, stdout: "" }));
if (/^musl/.test(result.stderr) || /^musl/.test(result.stdout)) {
this._target = "alpine";
} else {
this._target = "linux";
}
}
}
return this._target;
}
/**
* Make sure the argument is set. Display the value if it is.
*/
private ensureArgument(name: string, arg?: string): string {
if (!arg) {
this.log(`${name} is missing`);
throw new Error("Usage: <vscodeVersion> <codeServerVersion>");
}
this.log(`${name} is "${arg}"`);
return arg;
}
/**
* Return true if it looks like we're inside VS Code. This is used to prevent
* accidentally building inside while developing or to prevent trying to run
* `yarn` in VS Code when we aren't in VS Code.
*/
private isInVscode(pathToCheck: string): boolean {
let inside = false;
const maybeVsCode = path.join(pathToCheck, "../../../");
try {
// If it has a package.json with the right name it's probably VS Code.
inside = require(path.join(maybeVsCode, "package.json")).name === "code-oss-dev";
} catch (error) {}
this.log(
inside
? `Running inside VS Code ([${maybeVsCode}]${path.relative(maybeVsCode, pathToCheck)})`
: "Not running inside VS Code"
);
return inside;
}
/**
* Build code-server within VS Code.
*/
private async build(vscodeSourcePath: string, vscodeVersion: string, codeServerVersion: string, finalBuildPath: string): Promise<void> {
// Install dependencies (should be cached by CI).
await this.task("Installing code-server dependencies", async () => {
await util.promisify(cp.exec)("yarn", { cwd: this.rootPath });
});
// Download and prepare VS Code if necessary (should be cached by CI).
const exists = fs.existsSync(vscodeSourcePath);
if (exists) {
this.log("Using existing VS Code directory");
} else {
await this.task("Cloning VS Code", () => {
return util.promisify(cp.exec)(
"git clone https://github.com/microsoft/vscode"
+ ` --quiet --branch "${vscodeVersion}"`
+ ` --single-branch --depth=1 "${vscodeSourcePath}"`);
});
await this.task("Installing VS Code dependencies", () => {
return util.promisify(cp.exec)("yarn", { cwd: vscodeSourcePath });
});
await this.task("Building default extensions", () => {
return util.promisify(cp.exec)(
"yarn gulp compile-extensions-build --max-old-space-size=32384",
{ cwd: vscodeSourcePath },
);
});
}
// Clean before patching or it could fail if already patched.
await this.task("Patching VS Code", async () => {
await util.promisify(cp.exec)("git reset --hard", { cwd: vscodeSourcePath });
await util.promisify(cp.exec)("git clean -fd", { cwd: vscodeSourcePath });
await util.promisify(cp.exec)(`git apply ${this.rootPath}/scripts/vscode.patch`, { cwd: vscodeSourcePath });
});
const serverPath = path.join(vscodeSourcePath, "src/vs/server");
await this.task("Copying code-server into VS Code", async () => {
await fs.remove(serverPath);
await fs.mkdirp(serverPath);
await Promise.all(["main.js", "node_modules", "src", "typings"].map((fileName) => {
return fs.copy(path.join(this.rootPath, fileName), path.join(serverPath, fileName));
}));
});
await this.task("Building VS Code", () => {
return util.promisify(cp.exec)("yarn gulp compile-build --max-old-space-size=32384", { cwd: vscodeSourcePath });
});
await this.task("Optimizing VS Code", async () => {
await fs.copyFile(path.join(this.rootPath, "scripts/optimize.js"), path.join(vscodeSourcePath, "coder.js"));
await util.promisify(cp.exec)(`yarn gulp optimize --max-old-space-size=32384 --gulpfile ./coder.js`, { cwd: vscodeSourcePath });
});
const { productJson, packageJson } = await this.task("Generating final package.json and product.json", async () => {
const merge = async (name: string, extraJson: { [key: string]: string } = {}): Promise<{ [key: string]: string }> => {
const [aJson, bJson] = (await Promise.all([
fs.readFile(path.join(vscodeSourcePath, `${name}.json`), "utf8"),
fs.readFile(path.join(this.rootPath, `scripts/${name}.json`), "utf8"),
])).map((raw) => {
const json = JSON.parse(raw);
delete json.scripts;
delete json.dependencies;
delete json.devDependencies;
delete json.optionalDependencies;
return json;
});
return { ...aJson, ...bJson, ...extraJson };
};
const date = new Date().toISOString();
const commit = require(path.join(vscodeSourcePath, "build/lib/util")).getVersion(this.rootPath);
const [productJson, packageJson] = await Promise.all([
merge("product", { commit, date }),
merge("package", { codeServerVersion: `${codeServerVersion}-vsc${vscodeVersion}` }),
]);
// We could do this before the optimization but then it'd be copied into
// three files and unused in two which seems like a waste of bytes.
const apiPath = path.join(vscodeSourcePath, "out-vscode/vs/workbench/workbench.web.api.js");
await fs.writeFile(apiPath, (await fs.readFile(apiPath, "utf8")).replace('{ /*BUILD->INSERT_PRODUCT_CONFIGURATION*/}', JSON.stringify({
version: packageJson.version,
codeServerVersion: packageJson.codeServerVersion,
...productJson,
})));
return { productJson, packageJson };
});
if (process.env.MINIFY) {
await this.task("Minifying VS Code", () => {
return util.promisify(cp.exec)("yarn gulp minify --max-old-space-size=32384 --gulpfile ./coder.js", { cwd: vscodeSourcePath });
});
}
const finalServerPath = path.join(finalBuildPath, "out/vs/server");
await this.task("Copying into final build directory", async () => {
await fs.remove(finalBuildPath);
await fs.mkdirp(finalBuildPath);
await Promise.all([
fs.copy(path.join(vscodeSourcePath, "remote/node_modules"), path.join(finalBuildPath, "node_modules")),
fs.copy(path.join(vscodeSourcePath, ".build/extensions"), path.join(finalBuildPath, "extensions")),
fs.copy(path.join(vscodeSourcePath, `out-vscode${process.env.MINIFY ? "-min" : ""}`), path.join(finalBuildPath, "out")).then(() => {
return Promise.all([
fs.remove(path.join(finalServerPath, "node_modules")).then(() => {
return fs.copy(path.join(serverPath, "node_modules"), path.join(finalServerPath, "node_modules"));
}),
fs.copy(path.join(serverPath, "src/browser/workbench-build.html"), path.join(finalServerPath, "src/browser/workbench.html")),
]);
}),
]);
});
if (process.env.MINIFY) {
await this.task("Restricting to production dependencies", async () => {
await Promise.all(["package.json", "yarn.lock"].map((fileName) => {
Promise.all([
fs.copy(path.join(this.rootPath, fileName), path.join(finalServerPath, fileName)),
fs.copy(path.join(path.join(vscodeSourcePath, "remote"), fileName), path.join(finalBuildPath, fileName)),
]);
}));
await Promise.all([finalServerPath, finalBuildPath].map((cwd) => {
return util.promisify(cp.exec)("yarn --production", { cwd });
}));
await Promise.all(["package.json", "yarn.lock"].map((fileName) => {
return Promise.all([
fs.remove(path.join(finalServerPath, fileName)),
fs.remove(path.join(finalBuildPath, fileName)),
]);
}));
});
}
await this.task("Writing final package.json and product.json", () => {
return Promise.all([
fs.writeFile(path.join(finalBuildPath, "package.json"), JSON.stringify(packageJson, null, 2)),
fs.writeFile(path.join(finalBuildPath, "product.json"), JSON.stringify(productJson, null, 2)),
]);
});
// This is so it doesn't get cached along with VS Code (no point).
await this.task("Removing copied server", () => fs.remove(serverPath));
// Prepend code to the target which enables finding files within the binary.
const prependLoader = async (relativeFilePath: string): Promise<void> => {
const filePath = path.join(finalBuildPath, relativeFilePath);
const shim = `
if (!global.NBIN_LOADED) {
try {
const nbin = require("nbin");
nbin.shimNativeFs("${finalBuildPath}");
global.NBIN_LOADED = true;
const path = require("path");
const rg = require("vscode-ripgrep");
rg.binaryRgPath = rg.rgPath;
rg.rgPath = path.join(require("os").tmpdir(), "code-server", path.basename(rg.binaryRgPath));
} catch (error) { /* Not in the binary. */ }
}
`;
await fs.writeFile(filePath, shim + (await fs.readFile(filePath, "utf8")));
};
await this.task("Prepending nbin loader", () => {
return Promise.all([
prependLoader("out/vs/server/main.js"),
prependLoader("out/bootstrap-fork.js"),
prependLoader("extensions/node_modules/typescript/lib/tsserver.js"),
]);
});
// TODO: fix onigasm dep
// # onigasm 2.2.2 has a bug that makes it broken for PHP files so use 2.2.1.
// # https://github.com/NeekSandhu/onigasm/issues/17
// function fix-onigasm() {
// local onigasmPath="${buildPath}/node_modules/onigasm-umd"
// rm -rf "${onigasmPath}"
// git clone "https://github.com/alexandrudima/onigasm-umd" "${onigasmPath}"
// cd "${onigasmPath}" && yarn && yarn add --dev [email protected] && yarn package
// mkdir "${onigasmPath}-temp"
// mv "${onigasmPath}/"{release,LICENSE} "${onigasmPath}-temp"
// rm -rf "${onigasmPath}"
// mv "${onigasmPath}-temp" "${onigasmPath}"
// }
this.log(`Final build: ${finalBuildPath}`);
}
/**
* Bundles the built code into a binary.
*/
private async binary(targetPath: string, binariesPath: string, binaryName: string): Promise<void> {
const bin = new Binary({
mainFile: path.join(targetPath, "out/vs/server/main.js"),
target: await this.target(),
});
bin.writeFiles(path.join(targetPath, "**"));
await fs.mkdirp(binariesPath);
const binaryPath = path.join(binariesPath, binaryName);
await fs.writeFile(binaryPath, await bin.build());
await fs.chmod(binaryPath, "755");
this.log(`Binary: ${binaryPath}`);
}
/**
* Package the binary into a release archive.
*/
private async package(vscodeSourcePath: string, binariesPath: string, binaryName: string): Promise<void> {
const releasePath = path.join(this.outPath, "release");
const archivePath = path.join(releasePath, binaryName);
await fs.remove(archivePath);
await fs.mkdirp(archivePath);
await fs.copyFile(path.join(binariesPath, binaryName), path.join(archivePath, "code-server"));
await fs.copyFile(path.join(this.rootPath, "README.md"), path.join(archivePath, "README.md"));
await fs.copyFile(path.join(vscodeSourcePath, "LICENSE.txt"), path.join(archivePath, "LICENSE.txt"));
await fs.copyFile(path.join(vscodeSourcePath, "ThirdPartyNotices.txt"), path.join(archivePath, "ThirdPartyNotices.txt"));
if ((await this.target()) === "darwin") {
await util.promisify(cp.exec)(`zip -r "${binaryName}.zip" "${binaryName}"`, { cwd: releasePath });
this.log(`Archive: ${archivePath}.zip`);
} else {
await util.promisify(cp.exec)(`tar -czf "${binaryName}.tar.gz" "${binaryName}"`, { cwd: releasePath });
this.log(`Archive: ${archivePath}.tar.gz`);
}
}
}
const builder = new Builder();
builder.run(process.argv[2] as Task, process.argv.slice(3));
| scripts/build.ts | 1 | https://github.com/coder/code-server/commit/82e2b8a1698ece678f732a1d60f359997ac311ed | [
0.01108997967094183,
0.0007662737043574452,
0.00016698123363312334,
0.00024241721257567406,
0.0017601586878299713
]
|
{
"id": 1,
"code_window": [
"\n",
"cache:\n",
" yarn: true\n",
" directories:\n",
" - build/vscode-1.39.2-source\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace"
],
"after_edit": [
" - source"
],
"file_path": ".travis.yml",
"type": "replace",
"edit_start_line_idx": 78
} | import { DesktopDragAndDropData } from "vs/base/browser/ui/list/listView";
import { VSBuffer, VSBufferReadableStream } from "vs/base/common/buffer";
import { Disposable } from "vs/base/common/lifecycle";
import * as path from "vs/base/common/path";
import { URI } from "vs/base/common/uri";
import { generateUuid } from "vs/base/common/uuid";
import { IFileService } from "vs/platform/files/common/files";
import { createDecorator, IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { INotificationService, Severity } from "vs/platform/notification/common/notification";
import { IProgress, IProgressService, IProgressStep, ProgressLocation } from "vs/platform/progress/common/progress";
import { IWorkspaceContextService } from "vs/platform/workspace/common/workspace";
import { IWorkspacesService } from 'vs/platform/workspaces/common/workspaces';
import { ExplorerItem } from "vs/workbench/contrib/files/common/explorerModel";
import { IEditorGroup } from "vs/workbench/services/editor/common/editorGroupsService";
import { IEditorService } from "vs/workbench/services/editor/common/editorService";
export const IUploadService = createDecorator<IUploadService>("uploadService");
export interface IUploadService {
_serviceBrand: undefined;
handleDrop(event: DragEvent, resolveTargetGroup: () => IEditorGroup | undefined, afterDrop: (targetGroup: IEditorGroup | undefined) => void, targetIndex?: number): Promise<void>;
handleExternalDrop(data: DesktopDragAndDropData, target: ExplorerItem, originalEvent: DragEvent): Promise<void>;
}
export class UploadService extends Disposable implements IUploadService {
public _serviceBrand: undefined;
public upload: Upload;
public constructor(
@IInstantiationService instantiationService: IInstantiationService,
@IWorkspaceContextService private readonly contextService: IWorkspaceContextService,
@IWorkspacesService private readonly workspacesService: IWorkspacesService,
@IEditorService private readonly editorService: IEditorService,
) {
super();
this.upload = instantiationService.createInstance(Upload);
}
public async handleDrop(event: DragEvent, resolveTargetGroup: () => IEditorGroup | undefined, afterDrop: (targetGroup: IEditorGroup | undefined) => void, targetIndex?: number): Promise<void> {
// TODO: should use the workspace for the editor it was dropped on?
const target = this.contextService.getWorkspace().folders[0].uri;
const uris = (await this.upload.uploadDropped(event, target)).map((u) => URI.file(u));
if (uris.length > 0) {
await this.workspacesService.addRecentlyOpened(uris.map((u) => ({ fileUri: u })));
}
const editors = uris.map((uri) => ({
resource: uri,
options: {
pinned: true,
index: targetIndex,
},
}));
const targetGroup = resolveTargetGroup();
this.editorService.openEditors(editors, targetGroup);
afterDrop(targetGroup);
}
public async handleExternalDrop(_data: DesktopDragAndDropData, target: ExplorerItem, originalEvent: DragEvent): Promise<void> {
await this.upload.uploadDropped(originalEvent, target.resource);
}
}
/**
* There doesn't seem to be a provided type for entries, so here is an
* incomplete version.
*/
interface IEntry {
name: string;
isFile: boolean;
file: (cb: (file: File) => void) => void;
createReader: () => ({
readEntries: (cb: (entries: Array<IEntry>) => void) => void;
});
}
/**
* Handles file uploads.
*/
class Upload {
private readonly maxParallelUploads = 100;
private readonly uploadingFiles = new Map<string, Reader | undefined>();
private readonly fileQueue = new Map<string, File>();
private progress: IProgress<IProgressStep> | undefined;
private uploadPromise: Promise<string[]> | undefined;
private resolveUploadPromise: (() => void) | undefined;
private uploadedFilePaths = <string[]>[];
private _total = 0;
private _uploaded = 0;
private lastPercent = 0;
public constructor(
@INotificationService private notificationService: INotificationService,
@IProgressService private progressService: IProgressService,
@IFileService private fileService: IFileService,
) {}
/**
* Upload dropped files. This will try to upload everything it can. Errors
* will show via notifications. If an upload operation is ongoing, the files
* will be added to that operation.
*/
public async uploadDropped(event: DragEvent, uploadDir: URI): Promise<string[]> {
await this.queueFiles(event, uploadDir);
if (!this.uploadPromise) {
this.uploadPromise = this.progressService.withProgress({
cancellable: true,
location: ProgressLocation.Notification,
title: "Uploading files...",
}, (progress) => {
return new Promise((resolve): void => {
this.progress = progress;
this.resolveUploadPromise = (): void => {
const uploaded = this.uploadedFilePaths;
this.uploadPromise = undefined;
this.resolveUploadPromise = undefined;
this.uploadedFilePaths = [];
this.lastPercent = 0;
this._uploaded = 0;
this._total = 0;
resolve(uploaded);
};
});
}, () => this.cancel());
}
this.uploadFiles();
return this.uploadPromise;
}
/**
* Cancel all file uploads.
*/
public async cancel(): Promise<void> {
this.fileQueue.clear();
this.uploadingFiles.forEach((r) => r && r.abort());
}
private get total(): number { return this._total; }
private set total(total: number) {
this._total = total;
this.updateProgress();
}
private get uploaded(): number { return this._uploaded; }
private set uploaded(uploaded: number) {
this._uploaded = uploaded;
this.updateProgress();
}
private updateProgress(): void {
if (this.progress && this.total > 0) {
const percent = Math.floor((this.uploaded / this.total) * 100);
this.progress.report({ increment: percent - this.lastPercent });
this.lastPercent = percent;
}
}
/**
* Upload as many files as possible. When finished, resolve the upload
* promise.
*/
private uploadFiles(): void {
while (this.fileQueue.size > 0 && this.uploadingFiles.size < this.maxParallelUploads) {
const [path, file] = this.fileQueue.entries().next().value;
this.fileQueue.delete(path);
if (this.uploadingFiles.has(path)) {
this.notificationService.error(new Error(`Already uploading ${path}`));
} else {
this.uploadingFiles.set(path, undefined);
this.uploadFile(path, file).catch((error) => {
this.notificationService.error(error);
}).finally(() => {
this.uploadingFiles.delete(path);
this.uploadFiles();
});
}
}
if (this.fileQueue.size === 0 && this.uploadingFiles.size === 0) {
this.resolveUploadPromise!();
}
}
/**
* Upload a file, asking to override if necessary.
*/
private async uploadFile(filePath: string, file: File): Promise<void> {
const uri = URI.file(filePath);
if (await this.fileService.exists(uri)) {
const overwrite = await new Promise<boolean>((resolve): void => {
this.notificationService.prompt(
Severity.Error,
`${filePath} already exists. Overwrite?`,
[
{ label: "Yes", run: (): void => resolve(true) },
{ label: "No", run: (): void => resolve(false) },
],
{ onCancel: () => resolve(false) },
);
});
if (!overwrite) {
return;
}
}
const tempUri = uri.with({
path: path.join(
path.dirname(uri.path),
`.code-server-partial-upload-${path.basename(uri.path)}-${generateUuid()}`,
),
});
const reader = new Reader(file);
reader.on("data", (data) => {
if (data && data.byteLength > 0) {
this.uploaded += data.byteLength;
}
});
this.uploadingFiles.set(filePath, reader);
await this.fileService.writeFile(tempUri, reader);
if (reader.aborted) {
this.uploaded += (file.size - reader.offset);
await this.fileService.del(tempUri);
} else {
await this.fileService.move(tempUri, uri, true);
this.uploadedFilePaths.push(filePath);
}
}
/**
* Queue files from a drop event. We have to get the files first; we can't do
* it in tandem with uploading or the entries will disappear.
*/
private async queueFiles(event: DragEvent, uploadDir: URI): Promise<void> {
const promises: Array<Promise<void>> = [];
for (let i = 0; event.dataTransfer && event.dataTransfer.items && i < event.dataTransfer.items.length; ++i) {
const item = event.dataTransfer.items[i];
if (typeof item.webkitGetAsEntry === "function") {
promises.push(this.traverseItem(item.webkitGetAsEntry(), uploadDir.fsPath));
} else {
const file = item.getAsFile();
if (file) {
this.addFile(uploadDir.fsPath + "/" + file.name, file);
}
}
}
await Promise.all(promises);
}
/**
* Traverses an entry and add files to the queue.
*/
private async traverseItem(entry: IEntry, path: string): Promise<void> {
if (entry.isFile) {
return new Promise<void>((resolve): void => {
entry.file((file) => {
resolve(this.addFile(path + "/" + file.name, file));
});
});
}
path += "/" + entry.name;
await new Promise((resolve): void => {
const promises: Array<Promise<void>> = [];
const dirReader = entry.createReader();
// According to the spec, readEntries() must be called until it calls
// the callback with an empty array.
const readEntries = (): void => {
dirReader.readEntries((entries) => {
if (entries.length === 0) {
Promise.all(promises).then(resolve).catch((error) => {
this.notificationService.error(error);
resolve();
});
} else {
promises.push(...entries.map((c) => this.traverseItem(c, path)));
readEntries();
}
});
};
readEntries();
});
}
/**
* Add a file to the queue.
*/
private addFile(path: string, file: File): void {
this.total += file.size;
this.fileQueue.set(path, file);
}
}
class Reader implements VSBufferReadableStream {
private _offset = 0;
private readonly size = 32000; // ~32kb max while reading in the file.
private _aborted = false;
private readonly reader = new FileReader();
private paused = true;
private buffer?: VSBuffer;
private callbacks = new Map<string, Array<(...args: any[]) => void>>();
public constructor(private readonly file: File) {
this.reader.addEventListener("load", this.onLoad);
}
public get offset(): number { return this._offset; }
public get aborted(): boolean { return this._aborted; }
public on(event: "data" | "error" | "end", callback: (...args:any[]) => void): void {
if (!this.callbacks.has(event)) {
this.callbacks.set(event, []);
}
this.callbacks.get(event)!.push(callback);
if (this.aborted) {
return this.emit("error", new Error("stream has been aborted"));
} else if (this.done) {
return this.emit("error", new Error("stream has ended"));
} else if (event === "end") { // Once this is being listened to we can safely start outputting data.
this.resume();
}
}
public abort = (): void => {
this._aborted = true;
this.reader.abort();
this.reader.removeEventListener("load", this.onLoad);
this.emit("end");
}
public pause(): void {
this.paused = true;
}
public resume(): void {
if (this.paused) {
this.paused = false;
this.readNextChunk();
}
}
public destroy(): void {
this.abort();
}
private onLoad = (): void => {
this.buffer = VSBuffer.wrap(new Uint8Array(this.reader.result as ArrayBuffer));
if (!this.paused) {
this.readNextChunk();
}
}
private readNextChunk(): void {
if (this.buffer) {
this._offset += this.buffer.byteLength;
this.emit("data", this.buffer);
this.buffer = undefined;
}
if (!this.paused) { // Could be paused during the data event.
if (this.done) {
this.emit("end");
} else {
this.reader.readAsArrayBuffer(this.file.slice(this.offset, this.offset + this.size));
}
}
}
private emit(event: "data" | "error" | "end", ...args: any[]): void {
if (this.callbacks.has(event)) {
this.callbacks.get(event)!.forEach((cb) => cb(...args));
}
}
private get done(): boolean {
return this.offset >= this.file.size;
}
}
| src/browser/upload.ts | 0 | https://github.com/coder/code-server/commit/82e2b8a1698ece678f732a1d60f359997ac311ed | [
0.00020045487326569855,
0.00017147176549769938,
0.0001662387076066807,
0.00016879875329323113,
0.0000076120572884974536
]
|
{
"id": 1,
"code_window": [
"\n",
"cache:\n",
" yarn: true\n",
" directories:\n",
" - build/vscode-1.39.2-source\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace"
],
"after_edit": [
" - source"
],
"file_path": ".travis.yml",
"type": "replace",
"edit_start_line_idx": 78
} | import * as cp from "child_process";
import { getPathFromAmdModule } from "vs/base/common/amd";
import { VSBuffer } from "vs/base/common/buffer";
import { Emitter } from "vs/base/common/event";
import { ISocket } from "vs/base/parts/ipc/common/ipc.net";
import { NodeSocket } from "vs/base/parts/ipc/node/ipc.net";
import { IEnvironmentService } from "vs/platform/environment/common/environment";
import { ILogService } from "vs/platform/log/common/log";
import { getNlsConfiguration } from "vs/server/src/node/nls";
import { Protocol } from "vs/server/src/node/protocol";
import { uriTransformerPath } from "vs/server/src/node/util";
import { IExtHostReadyMessage } from "vs/workbench/services/extensions/common/extensionHostProtocol";
export abstract class Connection {
private readonly _onClose = new Emitter<void>();
public readonly onClose = this._onClose.event;
private disposed = false;
private _offline: number | undefined;
public constructor(protected protocol: Protocol, public readonly token: string) {}
public get offline(): number | undefined {
return this._offline;
}
public reconnect(socket: ISocket, buffer: VSBuffer): void {
this._offline = undefined;
this.doReconnect(socket, buffer);
}
public dispose(): void {
if (!this.disposed) {
this.disposed = true;
this.doDispose();
this._onClose.fire();
}
}
protected setOffline(): void {
if (!this._offline) {
this._offline = Date.now();
}
}
/**
* Set up the connection on a new socket.
*/
protected abstract doReconnect(socket: ISocket, buffer: VSBuffer): void;
protected abstract doDispose(): void;
}
/**
* Used for all the IPC channels.
*/
export class ManagementConnection extends Connection {
public constructor(protected protocol: Protocol, token: string) {
super(protocol, token);
protocol.onClose(() => this.dispose()); // Explicit close.
protocol.onSocketClose(() => this.setOffline()); // Might reconnect.
}
protected doDispose(): void {
this.protocol.sendDisconnect();
this.protocol.dispose();
this.protocol.getSocket().end();
}
protected doReconnect(socket: ISocket, buffer: VSBuffer): void {
this.protocol.beginAcceptReconnection(socket, buffer);
this.protocol.endAcceptReconnection();
}
}
export class ExtensionHostConnection extends Connection {
private process?: cp.ChildProcess;
public constructor(
locale:string, protocol: Protocol, buffer: VSBuffer, token: string,
private readonly log: ILogService,
private readonly environment: IEnvironmentService,
) {
super(protocol, token);
this.protocol.dispose();
this.spawn(locale, buffer).then((p) => this.process = p);
this.protocol.getUnderlyingSocket().pause();
}
protected doDispose(): void {
if (this.process) {
this.process.kill();
}
this.protocol.getSocket().end();
}
protected doReconnect(socket: ISocket, buffer: VSBuffer): void {
// This is just to set the new socket.
this.protocol.beginAcceptReconnection(socket, null);
this.protocol.dispose();
this.sendInitMessage(buffer);
}
private sendInitMessage(buffer: VSBuffer): void {
const socket = this.protocol.getUnderlyingSocket();
socket.pause();
this.process!.send({ // Process must be set at this point.
type: "VSCODE_EXTHOST_IPC_SOCKET",
initialDataChunk: (buffer.buffer as Buffer).toString("base64"),
skipWebSocketFrames: this.protocol.getSocket() instanceof NodeSocket,
}, socket);
}
private async spawn(locale: string, buffer: VSBuffer): Promise<cp.ChildProcess> {
const config = await getNlsConfiguration(locale, this.environment.userDataPath);
const proc = cp.fork(
getPathFromAmdModule(require, "bootstrap-fork"),
[ "--type=extensionHost", `--uriTransformerPath=${uriTransformerPath}` ],
{
env: {
...process.env,
AMD_ENTRYPOINT: "vs/workbench/services/extensions/node/extensionHostProcess",
PIPE_LOGGING: "true",
VERBOSE_LOGGING: "true",
VSCODE_EXTHOST_WILL_SEND_SOCKET: "true",
VSCODE_HANDLES_UNCAUGHT_ERRORS: "true",
VSCODE_LOG_STACK: "false",
VSCODE_LOG_LEVEL: this.environment.verbose ? "trace" : this.environment.log,
VSCODE_NLS_CONFIG: JSON.stringify(config),
},
silent: true,
},
);
proc.on("error", () => this.dispose());
proc.on("exit", () => this.dispose());
proc.stdout.setEncoding("utf8").on("data", (d) => this.log.info("Extension host stdout", d));
proc.stderr.setEncoding("utf8").on("data", (d) => this.log.error("Extension host stderr", d));
proc.on("message", (event) => {
if (event && event.type === "__$console") {
const severity = (<any>this.log)[event.severity] ? event.severity : "info";
(<any>this.log)[severity]("Extension host", event.arguments);
}
if (event && event.type === "VSCODE_EXTHOST_DISCONNECTED") {
this.setOffline();
}
});
const listen = (message: IExtHostReadyMessage) => {
if (message.type === "VSCODE_EXTHOST_IPC_READY") {
proc.removeListener("message", listen);
this.sendInitMessage(buffer);
}
};
return proc.on("message", listen);
}
}
| src/node/connection.ts | 0 | https://github.com/coder/code-server/commit/82e2b8a1698ece678f732a1d60f359997ac311ed | [
0.0008817166090011597,
0.00021479418501257896,
0.00016615628555882722,
0.00016910454723984003,
0.00017223894246853888
]
|
{
"id": 1,
"code_window": [
"\n",
"cache:\n",
" yarn: true\n",
" directories:\n",
" - build/vscode-1.39.2-source\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace"
],
"after_edit": [
" - source"
],
"file_path": ".travis.yml",
"type": "replace",
"edit_start_line_idx": 78
} | import * as cp from "child_process";
import * as os from "os";
import * as path from "path";
import { Stream } from "stream";
import * as util from "util";
import { toVSBufferReadableStream } from "vs/base/common/buffer";
import { CancellationToken } from "vs/base/common/cancellation";
import { URI } from "vs/base/common/uri";
import * as pfs from "vs/base/node/pfs";
import { IConfigurationService } from "vs/platform/configuration/common/configuration";
import { IEnvironmentService } from "vs/platform/environment/common/environment";
import { IFileService } from "vs/platform/files/common/files";
import { ILogService } from "vs/platform/log/common/log";
import product from "vs/platform/product/common/product";
import { asJson, IRequestService } from "vs/platform/request/common/request";
import { AvailableForDownload, State, UpdateType } from "vs/platform/update/common/update";
import { AbstractUpdateService } from "vs/platform/update/electron-main/abstractUpdateService";
import { ipcMain } from "vs/server/src/node/ipc";
import { extract } from "vs/server/src/node/marketplace";
import { tmpdir } from "vs/server/src/node/util";
import * as zlib from "zlib";
interface IUpdate {
name: string;
}
export class UpdateService extends AbstractUpdateService {
_serviceBrand: any;
constructor(
@IConfigurationService configurationService: IConfigurationService,
@IEnvironmentService environmentService: IEnvironmentService,
@IRequestService requestService: IRequestService,
@ILogService logService: ILogService,
@IFileService private readonly fileService: IFileService,
) {
super(null, configurationService, environmentService, requestService, logService);
}
public async isLatestVersion(latest?: IUpdate | null): Promise<boolean | undefined> {
if (!latest) {
latest = await this.getLatestVersion();
}
if (latest) {
const latestMajor = parseInt(latest.name);
const currentMajor = parseInt(product.codeServerVersion);
return !isNaN(latestMajor) && !isNaN(currentMajor) &&
currentMajor <= latestMajor && latest.name === product.codeServerVersion;
}
return true;
}
protected buildUpdateFeedUrl(quality: string): string {
return `${product.updateUrl}/${quality}`;
}
public async doQuitAndInstall(): Promise<void> {
ipcMain.relaunch();
}
protected async doCheckForUpdates(context: any): Promise<void> {
this.setState(State.CheckingForUpdates(context));
try {
const update = await this.getLatestVersion();
if (!update || this.isLatestVersion(update)) {
this.setState(State.Idle(UpdateType.Archive));
} else {
this.setState(State.AvailableForDownload({
version: update.name,
productVersion: update.name,
}));
}
} catch (error) {
this.onRequestError(error, !!context);
}
}
private async getLatestVersion(): Promise<IUpdate | null> {
const data = await this.requestService.request({
url: this.url,
headers: { "User-Agent": "code-server" },
}, CancellationToken.None);
return asJson(data);
}
protected async doDownloadUpdate(state: AvailableForDownload): Promise<void> {
this.setState(State.Downloading(state.update));
const target = os.platform();
const releaseName = await this.buildReleaseName(state.update.version);
const url = "https://github.com/cdr/code-server/releases/download/"
+ `${state.update.version}/${releaseName}`
+ `.${target === "darwin" ? "zip" : "tar.gz"}`;
const downloadPath = path.join(tmpdir, `${state.update.version}-archive`);
const extractPath = path.join(tmpdir, state.update.version);
try {
await pfs.mkdirp(tmpdir);
const context = await this.requestService.request({ url }, CancellationToken.None);
// Decompress the gzip as we download. If the gzip encoding is set then
// the request service already does this.
// HACK: This uses knowledge of the internals of the request service.
if (target !== "darwin" && context.res.headers["content-encoding"] !== "gzip") {
const stream = (context.res as any as Stream);
stream.removeAllListeners();
context.stream = toVSBufferReadableStream(stream.pipe(zlib.createGunzip()));
}
await this.fileService.writeFile(URI.file(downloadPath), context.stream);
await extract(downloadPath, extractPath, undefined, CancellationToken.None);
const newBinary = path.join(extractPath, releaseName, "code-server");
if (!pfs.exists(newBinary)) {
throw new Error("No code-server binary in extracted archive");
}
await pfs.unlink(process.argv[0]); // Must unlink first to avoid ETXTBSY.
await pfs.move(newBinary, process.argv[0]);
this.setState(State.Ready(state.update));
} catch (error) {
this.onRequestError(error, true);
}
await Promise.all([downloadPath, extractPath].map((p) => pfs.rimraf(p)));
}
private onRequestError(error: Error, showNotification?: boolean): void {
this.logService.error(error);
this.setState(State.Idle(UpdateType.Archive, showNotification ? (error.message || error.toString()) : undefined));
}
private async buildReleaseName(release: string): Promise<string> {
let target: string = os.platform();
if (target === "linux") {
const result = await util.promisify(cp.exec)("ldd --version").catch((error) => ({
stderr: error.message,
stdout: "",
}));
if (/^musl/.test(result.stderr) || /^musl/.test(result.stdout)) {
target = "alpine";
}
}
let arch = os.arch();
if (arch === "x64") {
arch = "x86_64";
}
return `code-server${release}-${target}-${arch}`;
}
}
| src/node/update.ts | 0 | https://github.com/coder/code-server/commit/82e2b8a1698ece678f732a1d60f359997ac311ed | [
0.0001749730872688815,
0.00016945155221037567,
0.00016720141866244376,
0.00016923058137763292,
0.0000020081083675904665
]
|
{
"id": 2,
"code_window": [
"\t\tconst vscodeVersion = this.ensureArgument(\"vscodeVersion\", args[0]);\n",
"\t\tconst codeServerVersion = this.ensureArgument(\"codeServerVersion\", args[1]);\n",
"\n",
"\t\tconst stagingPath = path.join(this.outPath, \"build\");\n",
"\t\tconst vscodeSourcePath = path.join(stagingPath, `vscode-${vscodeVersion}-source`);\n",
"\t\tconst binariesPath = path.join(this.outPath, \"binaries\");\n",
"\t\tconst binaryName = `code-server${codeServerVersion}-vsc${vscodeVersion}-${target}-${arch}`;\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep"
],
"after_edit": [
"\t\tconst vscodeSourcePath = path.join(this.outPath, \"source\", `vscode-${vscodeVersion}-source`);\n"
],
"file_path": "scripts/build.ts",
"type": "replace",
"edit_start_line_idx": 79
} | import { Binary } from "@coder/nbin";
import * as cp from "child_process";
// import * as crypto from "crypto";
import * as fs from "fs-extra";
import * as os from "os";
import * as path from "path";
import * as util from "util";
enum Task {
/**
* Use before running anything that only works inside VS Code.
*/
EnsureInVscode = "ensure-in-vscode",
Binary = "binary",
Package = "package",
Build = "build",
}
class Builder {
private readonly rootPath = path.resolve(__dirname, "..");
private readonly outPath = process.env.OUT || this.rootPath;
private _target?: "darwin" | "alpine" | "linux";
private currentTask?: Task;
public run(task: Task | undefined, args: string[]): void {
this.currentTask = task;
this.doRun(task, args).catch((error) => {
console.error(error.message);
process.exit(1);
});
}
private async task<T>(message: string, fn: () => Promise<T>): Promise<T> {
const time = Date.now();
this.log(`${message}...`, true);
try {
const t = await fn();
process.stdout.write(`took ${Date.now() - time}ms\n`);
return t;
} catch (error) {
process.stdout.write("failed\n");
throw error;
}
}
/**
* Writes to stdout with an optional newline.
*/
private log(message: string, skipNewline: boolean = false): void {
process.stdout.write(`[${this.currentTask || "default"}] ${message}`);
if (!skipNewline) {
process.stdout.write("\n");
}
}
private async doRun(task: Task | undefined, args: string[]): Promise<void> {
if (!task) {
throw new Error("No task provided");
}
if (task === Task.EnsureInVscode) {
return process.exit(this.isInVscode(this.rootPath) ? 0 : 1);
}
// If we're inside VS Code assume we want to develop. In that case we should
// set an OUT directory and not build in this directory, otherwise when you
// build/watch VS Code the build directory will be included.
if (this.isInVscode(this.outPath)) {
throw new Error("Should not build inside VS Code; set the OUT environment variable");
}
this.ensureArgument("rootPath", this.rootPath);
this.ensureArgument("outPath", this.outPath);
const arch = this.ensureArgument("arch", os.arch().replace(/^x/, "x86_"));
const target = this.ensureArgument("target", await this.target());
const vscodeVersion = this.ensureArgument("vscodeVersion", args[0]);
const codeServerVersion = this.ensureArgument("codeServerVersion", args[1]);
const stagingPath = path.join(this.outPath, "build");
const vscodeSourcePath = path.join(stagingPath, `vscode-${vscodeVersion}-source`);
const binariesPath = path.join(this.outPath, "binaries");
const binaryName = `code-server${codeServerVersion}-vsc${vscodeVersion}-${target}-${arch}`;
const finalBuildPath = path.join(stagingPath, `${binaryName}-built`);
switch (task) {
case Task.Binary:
return this.binary(finalBuildPath, binariesPath, binaryName);
case Task.Package:
return this.package(vscodeSourcePath, binariesPath, binaryName);
case Task.Build:
return this.build(vscodeSourcePath, vscodeVersion, codeServerVersion, finalBuildPath);
default:
throw new Error(`No task matching "${task}"`);
}
}
/**
* Get the target of the system.
*/
private async target(): Promise<"darwin" | "alpine" | "linux"> {
if (!this._target) {
if (process.env.OSTYPE && /^darwin/.test(process.env.OSTYPE)) {
this._target = "darwin";
} else {
// Alpine's ldd doesn't have a version flag but if you use an invalid flag
// (like --version) it outputs the version to stderr and exits with 1.
const result = await util.promisify(cp.exec)("ldd --version")
.catch((error) => ({ stderr: error.message, stdout: "" }));
if (/^musl/.test(result.stderr) || /^musl/.test(result.stdout)) {
this._target = "alpine";
} else {
this._target = "linux";
}
}
}
return this._target;
}
/**
* Make sure the argument is set. Display the value if it is.
*/
private ensureArgument(name: string, arg?: string): string {
if (!arg) {
this.log(`${name} is missing`);
throw new Error("Usage: <vscodeVersion> <codeServerVersion>");
}
this.log(`${name} is "${arg}"`);
return arg;
}
/**
* Return true if it looks like we're inside VS Code. This is used to prevent
* accidentally building inside while developing or to prevent trying to run
* `yarn` in VS Code when we aren't in VS Code.
*/
private isInVscode(pathToCheck: string): boolean {
let inside = false;
const maybeVsCode = path.join(pathToCheck, "../../../");
try {
// If it has a package.json with the right name it's probably VS Code.
inside = require(path.join(maybeVsCode, "package.json")).name === "code-oss-dev";
} catch (error) {}
this.log(
inside
? `Running inside VS Code ([${maybeVsCode}]${path.relative(maybeVsCode, pathToCheck)})`
: "Not running inside VS Code"
);
return inside;
}
/**
* Build code-server within VS Code.
*/
private async build(vscodeSourcePath: string, vscodeVersion: string, codeServerVersion: string, finalBuildPath: string): Promise<void> {
// Install dependencies (should be cached by CI).
await this.task("Installing code-server dependencies", async () => {
await util.promisify(cp.exec)("yarn", { cwd: this.rootPath });
});
// Download and prepare VS Code if necessary (should be cached by CI).
const exists = fs.existsSync(vscodeSourcePath);
if (exists) {
this.log("Using existing VS Code directory");
} else {
await this.task("Cloning VS Code", () => {
return util.promisify(cp.exec)(
"git clone https://github.com/microsoft/vscode"
+ ` --quiet --branch "${vscodeVersion}"`
+ ` --single-branch --depth=1 "${vscodeSourcePath}"`);
});
await this.task("Installing VS Code dependencies", () => {
return util.promisify(cp.exec)("yarn", { cwd: vscodeSourcePath });
});
await this.task("Building default extensions", () => {
return util.promisify(cp.exec)(
"yarn gulp compile-extensions-build --max-old-space-size=32384",
{ cwd: vscodeSourcePath },
);
});
}
// Clean before patching or it could fail if already patched.
await this.task("Patching VS Code", async () => {
await util.promisify(cp.exec)("git reset --hard", { cwd: vscodeSourcePath });
await util.promisify(cp.exec)("git clean -fd", { cwd: vscodeSourcePath });
await util.promisify(cp.exec)(`git apply ${this.rootPath}/scripts/vscode.patch`, { cwd: vscodeSourcePath });
});
const serverPath = path.join(vscodeSourcePath, "src/vs/server");
await this.task("Copying code-server into VS Code", async () => {
await fs.remove(serverPath);
await fs.mkdirp(serverPath);
await Promise.all(["main.js", "node_modules", "src", "typings"].map((fileName) => {
return fs.copy(path.join(this.rootPath, fileName), path.join(serverPath, fileName));
}));
});
await this.task("Building VS Code", () => {
return util.promisify(cp.exec)("yarn gulp compile-build --max-old-space-size=32384", { cwd: vscodeSourcePath });
});
await this.task("Optimizing VS Code", async () => {
await fs.copyFile(path.join(this.rootPath, "scripts/optimize.js"), path.join(vscodeSourcePath, "coder.js"));
await util.promisify(cp.exec)(`yarn gulp optimize --max-old-space-size=32384 --gulpfile ./coder.js`, { cwd: vscodeSourcePath });
});
const { productJson, packageJson } = await this.task("Generating final package.json and product.json", async () => {
const merge = async (name: string, extraJson: { [key: string]: string } = {}): Promise<{ [key: string]: string }> => {
const [aJson, bJson] = (await Promise.all([
fs.readFile(path.join(vscodeSourcePath, `${name}.json`), "utf8"),
fs.readFile(path.join(this.rootPath, `scripts/${name}.json`), "utf8"),
])).map((raw) => {
const json = JSON.parse(raw);
delete json.scripts;
delete json.dependencies;
delete json.devDependencies;
delete json.optionalDependencies;
return json;
});
return { ...aJson, ...bJson, ...extraJson };
};
const date = new Date().toISOString();
const commit = require(path.join(vscodeSourcePath, "build/lib/util")).getVersion(this.rootPath);
const [productJson, packageJson] = await Promise.all([
merge("product", { commit, date }),
merge("package", { codeServerVersion: `${codeServerVersion}-vsc${vscodeVersion}` }),
]);
// We could do this before the optimization but then it'd be copied into
// three files and unused in two which seems like a waste of bytes.
const apiPath = path.join(vscodeSourcePath, "out-vscode/vs/workbench/workbench.web.api.js");
await fs.writeFile(apiPath, (await fs.readFile(apiPath, "utf8")).replace('{ /*BUILD->INSERT_PRODUCT_CONFIGURATION*/}', JSON.stringify({
version: packageJson.version,
codeServerVersion: packageJson.codeServerVersion,
...productJson,
})));
return { productJson, packageJson };
});
if (process.env.MINIFY) {
await this.task("Minifying VS Code", () => {
return util.promisify(cp.exec)("yarn gulp minify --max-old-space-size=32384 --gulpfile ./coder.js", { cwd: vscodeSourcePath });
});
}
const finalServerPath = path.join(finalBuildPath, "out/vs/server");
await this.task("Copying into final build directory", async () => {
await fs.remove(finalBuildPath);
await fs.mkdirp(finalBuildPath);
await Promise.all([
fs.copy(path.join(vscodeSourcePath, "remote/node_modules"), path.join(finalBuildPath, "node_modules")),
fs.copy(path.join(vscodeSourcePath, ".build/extensions"), path.join(finalBuildPath, "extensions")),
fs.copy(path.join(vscodeSourcePath, `out-vscode${process.env.MINIFY ? "-min" : ""}`), path.join(finalBuildPath, "out")).then(() => {
return Promise.all([
fs.remove(path.join(finalServerPath, "node_modules")).then(() => {
return fs.copy(path.join(serverPath, "node_modules"), path.join(finalServerPath, "node_modules"));
}),
fs.copy(path.join(serverPath, "src/browser/workbench-build.html"), path.join(finalServerPath, "src/browser/workbench.html")),
]);
}),
]);
});
if (process.env.MINIFY) {
await this.task("Restricting to production dependencies", async () => {
await Promise.all(["package.json", "yarn.lock"].map((fileName) => {
Promise.all([
fs.copy(path.join(this.rootPath, fileName), path.join(finalServerPath, fileName)),
fs.copy(path.join(path.join(vscodeSourcePath, "remote"), fileName), path.join(finalBuildPath, fileName)),
]);
}));
await Promise.all([finalServerPath, finalBuildPath].map((cwd) => {
return util.promisify(cp.exec)("yarn --production", { cwd });
}));
await Promise.all(["package.json", "yarn.lock"].map((fileName) => {
return Promise.all([
fs.remove(path.join(finalServerPath, fileName)),
fs.remove(path.join(finalBuildPath, fileName)),
]);
}));
});
}
await this.task("Writing final package.json and product.json", () => {
return Promise.all([
fs.writeFile(path.join(finalBuildPath, "package.json"), JSON.stringify(packageJson, null, 2)),
fs.writeFile(path.join(finalBuildPath, "product.json"), JSON.stringify(productJson, null, 2)),
]);
});
// This is so it doesn't get cached along with VS Code (no point).
await this.task("Removing copied server", () => fs.remove(serverPath));
// Prepend code to the target which enables finding files within the binary.
const prependLoader = async (relativeFilePath: string): Promise<void> => {
const filePath = path.join(finalBuildPath, relativeFilePath);
const shim = `
if (!global.NBIN_LOADED) {
try {
const nbin = require("nbin");
nbin.shimNativeFs("${finalBuildPath}");
global.NBIN_LOADED = true;
const path = require("path");
const rg = require("vscode-ripgrep");
rg.binaryRgPath = rg.rgPath;
rg.rgPath = path.join(require("os").tmpdir(), "code-server", path.basename(rg.binaryRgPath));
} catch (error) { /* Not in the binary. */ }
}
`;
await fs.writeFile(filePath, shim + (await fs.readFile(filePath, "utf8")));
};
await this.task("Prepending nbin loader", () => {
return Promise.all([
prependLoader("out/vs/server/main.js"),
prependLoader("out/bootstrap-fork.js"),
prependLoader("extensions/node_modules/typescript/lib/tsserver.js"),
]);
});
// TODO: fix onigasm dep
// # onigasm 2.2.2 has a bug that makes it broken for PHP files so use 2.2.1.
// # https://github.com/NeekSandhu/onigasm/issues/17
// function fix-onigasm() {
// local onigasmPath="${buildPath}/node_modules/onigasm-umd"
// rm -rf "${onigasmPath}"
// git clone "https://github.com/alexandrudima/onigasm-umd" "${onigasmPath}"
// cd "${onigasmPath}" && yarn && yarn add --dev [email protected] && yarn package
// mkdir "${onigasmPath}-temp"
// mv "${onigasmPath}/"{release,LICENSE} "${onigasmPath}-temp"
// rm -rf "${onigasmPath}"
// mv "${onigasmPath}-temp" "${onigasmPath}"
// }
this.log(`Final build: ${finalBuildPath}`);
}
/**
* Bundles the built code into a binary.
*/
private async binary(targetPath: string, binariesPath: string, binaryName: string): Promise<void> {
const bin = new Binary({
mainFile: path.join(targetPath, "out/vs/server/main.js"),
target: await this.target(),
});
bin.writeFiles(path.join(targetPath, "**"));
await fs.mkdirp(binariesPath);
const binaryPath = path.join(binariesPath, binaryName);
await fs.writeFile(binaryPath, await bin.build());
await fs.chmod(binaryPath, "755");
this.log(`Binary: ${binaryPath}`);
}
/**
* Package the binary into a release archive.
*/
private async package(vscodeSourcePath: string, binariesPath: string, binaryName: string): Promise<void> {
const releasePath = path.join(this.outPath, "release");
const archivePath = path.join(releasePath, binaryName);
await fs.remove(archivePath);
await fs.mkdirp(archivePath);
await fs.copyFile(path.join(binariesPath, binaryName), path.join(archivePath, "code-server"));
await fs.copyFile(path.join(this.rootPath, "README.md"), path.join(archivePath, "README.md"));
await fs.copyFile(path.join(vscodeSourcePath, "LICENSE.txt"), path.join(archivePath, "LICENSE.txt"));
await fs.copyFile(path.join(vscodeSourcePath, "ThirdPartyNotices.txt"), path.join(archivePath, "ThirdPartyNotices.txt"));
if ((await this.target()) === "darwin") {
await util.promisify(cp.exec)(`zip -r "${binaryName}.zip" "${binaryName}"`, { cwd: releasePath });
this.log(`Archive: ${archivePath}.zip`);
} else {
await util.promisify(cp.exec)(`tar -czf "${binaryName}.tar.gz" "${binaryName}"`, { cwd: releasePath });
this.log(`Archive: ${archivePath}.tar.gz`);
}
}
}
const builder = new Builder();
builder.run(process.argv[2] as Task, process.argv.slice(3));
| scripts/build.ts | 1 | https://github.com/coder/code-server/commit/82e2b8a1698ece678f732a1d60f359997ac311ed | [
0.9990197420120239,
0.42638811469078064,
0.00016213823982980102,
0.001848718267865479,
0.49094924330711365
]
|
{
"id": 2,
"code_window": [
"\t\tconst vscodeVersion = this.ensureArgument(\"vscodeVersion\", args[0]);\n",
"\t\tconst codeServerVersion = this.ensureArgument(\"codeServerVersion\", args[1]);\n",
"\n",
"\t\tconst stagingPath = path.join(this.outPath, \"build\");\n",
"\t\tconst vscodeSourcePath = path.join(stagingPath, `vscode-${vscodeVersion}-source`);\n",
"\t\tconst binariesPath = path.join(this.outPath, \"binaries\");\n",
"\t\tconst binaryName = `code-server${codeServerVersion}-vsc${vscodeVersion}-${target}-${arch}`;\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep"
],
"after_edit": [
"\t\tconst vscodeSourcePath = path.join(this.outPath, \"source\", `vscode-${vscodeVersion}-source`);\n"
],
"file_path": "scripts/build.ts",
"type": "replace",
"edit_start_line_idx": 79
} | Dockerfile
build
deployment
doc
.github
.gitignore
.node-version
.travis.yml
LICENSE
README.md
node_modules
release | .dockerignore | 0 | https://github.com/coder/code-server/commit/82e2b8a1698ece678f732a1d60f359997ac311ed | [
0.00017317815218120813,
0.00017175168613903224,
0.00017032523464877158,
0.00017175168613903224,
0.0000014264587662182748
]
|
{
"id": 2,
"code_window": [
"\t\tconst vscodeVersion = this.ensureArgument(\"vscodeVersion\", args[0]);\n",
"\t\tconst codeServerVersion = this.ensureArgument(\"codeServerVersion\", args[1]);\n",
"\n",
"\t\tconst stagingPath = path.join(this.outPath, \"build\");\n",
"\t\tconst vscodeSourcePath = path.join(stagingPath, `vscode-${vscodeVersion}-source`);\n",
"\t\tconst binariesPath = path.join(this.outPath, \"binaries\");\n",
"\t\tconst binaryName = `code-server${codeServerVersion}-vsc${vscodeVersion}-${target}-${arch}`;\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep"
],
"after_edit": [
"\t\tconst vscodeSourcePath = path.join(this.outPath, \"source\", `vscode-${vscodeVersion}-source`);\n"
],
"file_path": "scripts/build.ts",
"type": "replace",
"edit_start_line_idx": 79
} | {
"nameShort": "code-server",
"nameLong": "code-server",
"applicationName": "code-server",
"dataFolderName": ".code-server",
"win32MutexName": "codeserver",
"win32DirName": "Code Server",
"win32NameVersion": "Code Server",
"win32RegValueName": "CodeServer",
"win32AppId": "",
"win32x64AppId": "",
"win32UserAppId": "",
"win32x64UserAppId": "",
"win32AppUserModelId": "CodeServer",
"win32ShellNameShort": "C&ode Server",
"darwinBundleIdentifier": "com.code.server",
"linuxIconName": "com.code.server",
"urlProtocol": "code-server",
"updateUrl": "https://api.github.com/repos/cdr/code-server/releases",
"quality": "latest"
}
| scripts/product.json | 0 | https://github.com/coder/code-server/commit/82e2b8a1698ece678f732a1d60f359997ac311ed | [
0.00017442771058995277,
0.0001714747049845755,
0.00016945178504101932,
0.00017054463387466967,
0.0000021352188923629
]
|
{
"id": 2,
"code_window": [
"\t\tconst vscodeVersion = this.ensureArgument(\"vscodeVersion\", args[0]);\n",
"\t\tconst codeServerVersion = this.ensureArgument(\"codeServerVersion\", args[1]);\n",
"\n",
"\t\tconst stagingPath = path.join(this.outPath, \"build\");\n",
"\t\tconst vscodeSourcePath = path.join(stagingPath, `vscode-${vscodeVersion}-source`);\n",
"\t\tconst binariesPath = path.join(this.outPath, \"binaries\");\n",
"\t\tconst binaryName = `code-server${codeServerVersion}-vsc${vscodeVersion}-${target}-${arch}`;\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep"
],
"after_edit": [
"\t\tconst vscodeSourcePath = path.join(this.outPath, \"source\", `vscode-${vscodeVersion}-source`);\n"
],
"file_path": "scripts/build.ts",
"type": "replace",
"edit_start_line_idx": 79
} | import * as cp from "child_process";
import * as crypto from "crypto";
import * as fs from "fs";
import * as os from "os";
import * as path from "path";
import * as util from "util";
import * as rg from "vscode-ripgrep";
import { getPathFromAmdModule } from "vs/base/common/amd";
import { getMediaMime as vsGetMediaMime } from "vs/base/common/mime";
import { extname } from "vs/base/common/path";
import { URITransformer, IRawURITransformer } from "vs/base/common/uriIpc";
import { mkdirp } from "vs/base/node/pfs";
export enum AuthType {
Password = "password",
}
export enum FormatType {
Json = "json",
}
export const tmpdir = path.join(os.tmpdir(), "code-server");
export const generateCertificate = async (): Promise<{ cert: string, certKey: string }> => {
const paths = {
cert: path.join(tmpdir, "self-signed.cert"),
certKey: path.join(tmpdir, "self-signed.key"),
};
const exists = await Promise.all([
util.promisify(fs.exists)(paths.cert),
util.promisify(fs.exists)(paths.certKey),
]);
if (!exists[0] || !exists[1]) {
const pem = localRequire<typeof import("pem")>("pem/lib/pem");
const certs = await new Promise<import("pem").CertificateCreationResult>((resolve, reject): void => {
pem.createCertificate({ selfSigned: true }, (error, result) => {
if (error) {
return reject(error);
}
resolve(result);
});
});
await mkdirp(tmpdir);
await Promise.all([
util.promisify(fs.writeFile)(paths.cert, certs.certificate),
util.promisify(fs.writeFile)(paths.certKey, certs.serviceKey),
]);
}
return paths;
};
export const uriTransformerPath = getPathFromAmdModule(require, "vs/server/src/node/uriTransformer");
export const getUriTransformer = (remoteAuthority: string): URITransformer => {
const rawURITransformerFactory = <any>require.__$__nodeRequire(uriTransformerPath);
const rawURITransformer = <IRawURITransformer>rawURITransformerFactory(remoteAuthority);
return new URITransformer(rawURITransformer);
};
export const generatePassword = async (length: number = 24): Promise<string> => {
const buffer = Buffer.alloc(Math.ceil(length / 2));
await util.promisify(crypto.randomFill)(buffer);
return buffer.toString("hex").substring(0, length);
};
export const getMediaMime = (filePath?: string): string => {
return filePath && (vsGetMediaMime(filePath) || (<{[index: string]: string}>{
".css": "text/css",
".html": "text/html",
".js": "application/javascript",
".json": "application/json",
})[extname(filePath)]) || "text/plain";
};
export const isWsl = async (): Promise<boolean> => {
return process.platform === "linux"
&& os.release().toLowerCase().indexOf("microsoft") !== -1
|| (await util.promisify(fs.readFile)("/proc/version", "utf8"))
.toLowerCase().indexOf("microsoft") !== -1;
};
export const open = async (url: string): Promise<void> => {
const args = <string[]>[];
const options = <cp.SpawnOptions>{};
const platform = await isWsl() ? "wsl" : process.platform;
let command = platform === "darwin" ? "open" : "xdg-open";
if (platform === "win32" || platform === "wsl") {
command = platform === "wsl" ? "cmd.exe" : "cmd";
args.push("/c", "start", '""', "/b");
url = url.replace(/&/g, "^&");
}
const proc = cp.spawn(command, [...args, url], options);
await new Promise((resolve, reject) => {
proc.on("error", reject);
proc.on("close", (code) => {
return code !== 0
? reject(new Error(`Failed to open with code ${code}`))
: resolve();
});
});
};
/**
* Extract executables to the temporary directory. This is required since we
* can't execute binaries stored within our binary.
*/
export const unpackExecutables = async (): Promise<void> => {
const rgPath = (rg as any).binaryRgPath;
const destination = path.join(tmpdir, path.basename(rgPath || ""));
if (rgPath && !(await util.promisify(fs.exists)(destination))) {
await mkdirp(tmpdir);
await util.promisify(fs.writeFile)(destination, await util.promisify(fs.readFile)(rgPath));
await util.promisify(fs.chmod)(destination, "755");
}
};
export const enumToArray = (t: any): string[] => {
const values = <string[]>[];
for (const k in t) {
values.push(t[k]);
}
return values;
};
export const buildAllowedMessage = (t: any): string => {
const values = enumToArray(t);
return `Allowed value${values.length === 1 ? " is" : "s are"} ${values.map((t) => `'${t}'`).join(",")}`;
};
/**
* Require a local module. This is necessary since VS Code's loader only looks
* at the root for Node modules.
*/
export const localRequire = <T>(modulePath: string): T => {
return require.__$__nodeRequire(path.resolve(__dirname, "../../node_modules", modulePath));
};
| src/node/util.ts | 0 | https://github.com/coder/code-server/commit/82e2b8a1698ece678f732a1d60f359997ac311ed | [
0.0007814334821887314,
0.00021471628861036152,
0.0001671990321483463,
0.0001716710685286671,
0.00015719368821009994
]
|
{
"id": 3,
"code_window": [
"\t\tconst binariesPath = path.join(this.outPath, \"binaries\");\n",
"\t\tconst binaryName = `code-server${codeServerVersion}-vsc${vscodeVersion}-${target}-${arch}`;\n",
"\t\tconst finalBuildPath = path.join(stagingPath, `${binaryName}-built`);\n",
"\n",
"\t\tswitch (task) {\n",
"\t\t\tcase Task.Binary:\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tconst finalBuildPath = path.join(this.outPath, \"build\", `${binaryName}-built`);\n"
],
"file_path": "scripts/build.ts",
"type": "replace",
"edit_start_line_idx": 83
} | import { Binary } from "@coder/nbin";
import * as cp from "child_process";
// import * as crypto from "crypto";
import * as fs from "fs-extra";
import * as os from "os";
import * as path from "path";
import * as util from "util";
enum Task {
/**
* Use before running anything that only works inside VS Code.
*/
EnsureInVscode = "ensure-in-vscode",
Binary = "binary",
Package = "package",
Build = "build",
}
class Builder {
private readonly rootPath = path.resolve(__dirname, "..");
private readonly outPath = process.env.OUT || this.rootPath;
private _target?: "darwin" | "alpine" | "linux";
private currentTask?: Task;
public run(task: Task | undefined, args: string[]): void {
this.currentTask = task;
this.doRun(task, args).catch((error) => {
console.error(error.message);
process.exit(1);
});
}
private async task<T>(message: string, fn: () => Promise<T>): Promise<T> {
const time = Date.now();
this.log(`${message}...`, true);
try {
const t = await fn();
process.stdout.write(`took ${Date.now() - time}ms\n`);
return t;
} catch (error) {
process.stdout.write("failed\n");
throw error;
}
}
/**
* Writes to stdout with an optional newline.
*/
private log(message: string, skipNewline: boolean = false): void {
process.stdout.write(`[${this.currentTask || "default"}] ${message}`);
if (!skipNewline) {
process.stdout.write("\n");
}
}
private async doRun(task: Task | undefined, args: string[]): Promise<void> {
if (!task) {
throw new Error("No task provided");
}
if (task === Task.EnsureInVscode) {
return process.exit(this.isInVscode(this.rootPath) ? 0 : 1);
}
// If we're inside VS Code assume we want to develop. In that case we should
// set an OUT directory and not build in this directory, otherwise when you
// build/watch VS Code the build directory will be included.
if (this.isInVscode(this.outPath)) {
throw new Error("Should not build inside VS Code; set the OUT environment variable");
}
this.ensureArgument("rootPath", this.rootPath);
this.ensureArgument("outPath", this.outPath);
const arch = this.ensureArgument("arch", os.arch().replace(/^x/, "x86_"));
const target = this.ensureArgument("target", await this.target());
const vscodeVersion = this.ensureArgument("vscodeVersion", args[0]);
const codeServerVersion = this.ensureArgument("codeServerVersion", args[1]);
const stagingPath = path.join(this.outPath, "build");
const vscodeSourcePath = path.join(stagingPath, `vscode-${vscodeVersion}-source`);
const binariesPath = path.join(this.outPath, "binaries");
const binaryName = `code-server${codeServerVersion}-vsc${vscodeVersion}-${target}-${arch}`;
const finalBuildPath = path.join(stagingPath, `${binaryName}-built`);
switch (task) {
case Task.Binary:
return this.binary(finalBuildPath, binariesPath, binaryName);
case Task.Package:
return this.package(vscodeSourcePath, binariesPath, binaryName);
case Task.Build:
return this.build(vscodeSourcePath, vscodeVersion, codeServerVersion, finalBuildPath);
default:
throw new Error(`No task matching "${task}"`);
}
}
/**
* Get the target of the system.
*/
private async target(): Promise<"darwin" | "alpine" | "linux"> {
if (!this._target) {
if (process.env.OSTYPE && /^darwin/.test(process.env.OSTYPE)) {
this._target = "darwin";
} else {
// Alpine's ldd doesn't have a version flag but if you use an invalid flag
// (like --version) it outputs the version to stderr and exits with 1.
const result = await util.promisify(cp.exec)("ldd --version")
.catch((error) => ({ stderr: error.message, stdout: "" }));
if (/^musl/.test(result.stderr) || /^musl/.test(result.stdout)) {
this._target = "alpine";
} else {
this._target = "linux";
}
}
}
return this._target;
}
/**
* Make sure the argument is set. Display the value if it is.
*/
private ensureArgument(name: string, arg?: string): string {
if (!arg) {
this.log(`${name} is missing`);
throw new Error("Usage: <vscodeVersion> <codeServerVersion>");
}
this.log(`${name} is "${arg}"`);
return arg;
}
/**
* Return true if it looks like we're inside VS Code. This is used to prevent
* accidentally building inside while developing or to prevent trying to run
* `yarn` in VS Code when we aren't in VS Code.
*/
private isInVscode(pathToCheck: string): boolean {
let inside = false;
const maybeVsCode = path.join(pathToCheck, "../../../");
try {
// If it has a package.json with the right name it's probably VS Code.
inside = require(path.join(maybeVsCode, "package.json")).name === "code-oss-dev";
} catch (error) {}
this.log(
inside
? `Running inside VS Code ([${maybeVsCode}]${path.relative(maybeVsCode, pathToCheck)})`
: "Not running inside VS Code"
);
return inside;
}
/**
* Build code-server within VS Code.
*/
private async build(vscodeSourcePath: string, vscodeVersion: string, codeServerVersion: string, finalBuildPath: string): Promise<void> {
// Install dependencies (should be cached by CI).
await this.task("Installing code-server dependencies", async () => {
await util.promisify(cp.exec)("yarn", { cwd: this.rootPath });
});
// Download and prepare VS Code if necessary (should be cached by CI).
const exists = fs.existsSync(vscodeSourcePath);
if (exists) {
this.log("Using existing VS Code directory");
} else {
await this.task("Cloning VS Code", () => {
return util.promisify(cp.exec)(
"git clone https://github.com/microsoft/vscode"
+ ` --quiet --branch "${vscodeVersion}"`
+ ` --single-branch --depth=1 "${vscodeSourcePath}"`);
});
await this.task("Installing VS Code dependencies", () => {
return util.promisify(cp.exec)("yarn", { cwd: vscodeSourcePath });
});
await this.task("Building default extensions", () => {
return util.promisify(cp.exec)(
"yarn gulp compile-extensions-build --max-old-space-size=32384",
{ cwd: vscodeSourcePath },
);
});
}
// Clean before patching or it could fail if already patched.
await this.task("Patching VS Code", async () => {
await util.promisify(cp.exec)("git reset --hard", { cwd: vscodeSourcePath });
await util.promisify(cp.exec)("git clean -fd", { cwd: vscodeSourcePath });
await util.promisify(cp.exec)(`git apply ${this.rootPath}/scripts/vscode.patch`, { cwd: vscodeSourcePath });
});
const serverPath = path.join(vscodeSourcePath, "src/vs/server");
await this.task("Copying code-server into VS Code", async () => {
await fs.remove(serverPath);
await fs.mkdirp(serverPath);
await Promise.all(["main.js", "node_modules", "src", "typings"].map((fileName) => {
return fs.copy(path.join(this.rootPath, fileName), path.join(serverPath, fileName));
}));
});
await this.task("Building VS Code", () => {
return util.promisify(cp.exec)("yarn gulp compile-build --max-old-space-size=32384", { cwd: vscodeSourcePath });
});
await this.task("Optimizing VS Code", async () => {
await fs.copyFile(path.join(this.rootPath, "scripts/optimize.js"), path.join(vscodeSourcePath, "coder.js"));
await util.promisify(cp.exec)(`yarn gulp optimize --max-old-space-size=32384 --gulpfile ./coder.js`, { cwd: vscodeSourcePath });
});
const { productJson, packageJson } = await this.task("Generating final package.json and product.json", async () => {
const merge = async (name: string, extraJson: { [key: string]: string } = {}): Promise<{ [key: string]: string }> => {
const [aJson, bJson] = (await Promise.all([
fs.readFile(path.join(vscodeSourcePath, `${name}.json`), "utf8"),
fs.readFile(path.join(this.rootPath, `scripts/${name}.json`), "utf8"),
])).map((raw) => {
const json = JSON.parse(raw);
delete json.scripts;
delete json.dependencies;
delete json.devDependencies;
delete json.optionalDependencies;
return json;
});
return { ...aJson, ...bJson, ...extraJson };
};
const date = new Date().toISOString();
const commit = require(path.join(vscodeSourcePath, "build/lib/util")).getVersion(this.rootPath);
const [productJson, packageJson] = await Promise.all([
merge("product", { commit, date }),
merge("package", { codeServerVersion: `${codeServerVersion}-vsc${vscodeVersion}` }),
]);
// We could do this before the optimization but then it'd be copied into
// three files and unused in two which seems like a waste of bytes.
const apiPath = path.join(vscodeSourcePath, "out-vscode/vs/workbench/workbench.web.api.js");
await fs.writeFile(apiPath, (await fs.readFile(apiPath, "utf8")).replace('{ /*BUILD->INSERT_PRODUCT_CONFIGURATION*/}', JSON.stringify({
version: packageJson.version,
codeServerVersion: packageJson.codeServerVersion,
...productJson,
})));
return { productJson, packageJson };
});
if (process.env.MINIFY) {
await this.task("Minifying VS Code", () => {
return util.promisify(cp.exec)("yarn gulp minify --max-old-space-size=32384 --gulpfile ./coder.js", { cwd: vscodeSourcePath });
});
}
const finalServerPath = path.join(finalBuildPath, "out/vs/server");
await this.task("Copying into final build directory", async () => {
await fs.remove(finalBuildPath);
await fs.mkdirp(finalBuildPath);
await Promise.all([
fs.copy(path.join(vscodeSourcePath, "remote/node_modules"), path.join(finalBuildPath, "node_modules")),
fs.copy(path.join(vscodeSourcePath, ".build/extensions"), path.join(finalBuildPath, "extensions")),
fs.copy(path.join(vscodeSourcePath, `out-vscode${process.env.MINIFY ? "-min" : ""}`), path.join(finalBuildPath, "out")).then(() => {
return Promise.all([
fs.remove(path.join(finalServerPath, "node_modules")).then(() => {
return fs.copy(path.join(serverPath, "node_modules"), path.join(finalServerPath, "node_modules"));
}),
fs.copy(path.join(serverPath, "src/browser/workbench-build.html"), path.join(finalServerPath, "src/browser/workbench.html")),
]);
}),
]);
});
if (process.env.MINIFY) {
await this.task("Restricting to production dependencies", async () => {
await Promise.all(["package.json", "yarn.lock"].map((fileName) => {
Promise.all([
fs.copy(path.join(this.rootPath, fileName), path.join(finalServerPath, fileName)),
fs.copy(path.join(path.join(vscodeSourcePath, "remote"), fileName), path.join(finalBuildPath, fileName)),
]);
}));
await Promise.all([finalServerPath, finalBuildPath].map((cwd) => {
return util.promisify(cp.exec)("yarn --production", { cwd });
}));
await Promise.all(["package.json", "yarn.lock"].map((fileName) => {
return Promise.all([
fs.remove(path.join(finalServerPath, fileName)),
fs.remove(path.join(finalBuildPath, fileName)),
]);
}));
});
}
await this.task("Writing final package.json and product.json", () => {
return Promise.all([
fs.writeFile(path.join(finalBuildPath, "package.json"), JSON.stringify(packageJson, null, 2)),
fs.writeFile(path.join(finalBuildPath, "product.json"), JSON.stringify(productJson, null, 2)),
]);
});
// This is so it doesn't get cached along with VS Code (no point).
await this.task("Removing copied server", () => fs.remove(serverPath));
// Prepend code to the target which enables finding files within the binary.
const prependLoader = async (relativeFilePath: string): Promise<void> => {
const filePath = path.join(finalBuildPath, relativeFilePath);
const shim = `
if (!global.NBIN_LOADED) {
try {
const nbin = require("nbin");
nbin.shimNativeFs("${finalBuildPath}");
global.NBIN_LOADED = true;
const path = require("path");
const rg = require("vscode-ripgrep");
rg.binaryRgPath = rg.rgPath;
rg.rgPath = path.join(require("os").tmpdir(), "code-server", path.basename(rg.binaryRgPath));
} catch (error) { /* Not in the binary. */ }
}
`;
await fs.writeFile(filePath, shim + (await fs.readFile(filePath, "utf8")));
};
await this.task("Prepending nbin loader", () => {
return Promise.all([
prependLoader("out/vs/server/main.js"),
prependLoader("out/bootstrap-fork.js"),
prependLoader("extensions/node_modules/typescript/lib/tsserver.js"),
]);
});
// TODO: fix onigasm dep
// # onigasm 2.2.2 has a bug that makes it broken for PHP files so use 2.2.1.
// # https://github.com/NeekSandhu/onigasm/issues/17
// function fix-onigasm() {
// local onigasmPath="${buildPath}/node_modules/onigasm-umd"
// rm -rf "${onigasmPath}"
// git clone "https://github.com/alexandrudima/onigasm-umd" "${onigasmPath}"
// cd "${onigasmPath}" && yarn && yarn add --dev [email protected] && yarn package
// mkdir "${onigasmPath}-temp"
// mv "${onigasmPath}/"{release,LICENSE} "${onigasmPath}-temp"
// rm -rf "${onigasmPath}"
// mv "${onigasmPath}-temp" "${onigasmPath}"
// }
this.log(`Final build: ${finalBuildPath}`);
}
/**
* Bundles the built code into a binary.
*/
private async binary(targetPath: string, binariesPath: string, binaryName: string): Promise<void> {
const bin = new Binary({
mainFile: path.join(targetPath, "out/vs/server/main.js"),
target: await this.target(),
});
bin.writeFiles(path.join(targetPath, "**"));
await fs.mkdirp(binariesPath);
const binaryPath = path.join(binariesPath, binaryName);
await fs.writeFile(binaryPath, await bin.build());
await fs.chmod(binaryPath, "755");
this.log(`Binary: ${binaryPath}`);
}
/**
* Package the binary into a release archive.
*/
private async package(vscodeSourcePath: string, binariesPath: string, binaryName: string): Promise<void> {
const releasePath = path.join(this.outPath, "release");
const archivePath = path.join(releasePath, binaryName);
await fs.remove(archivePath);
await fs.mkdirp(archivePath);
await fs.copyFile(path.join(binariesPath, binaryName), path.join(archivePath, "code-server"));
await fs.copyFile(path.join(this.rootPath, "README.md"), path.join(archivePath, "README.md"));
await fs.copyFile(path.join(vscodeSourcePath, "LICENSE.txt"), path.join(archivePath, "LICENSE.txt"));
await fs.copyFile(path.join(vscodeSourcePath, "ThirdPartyNotices.txt"), path.join(archivePath, "ThirdPartyNotices.txt"));
if ((await this.target()) === "darwin") {
await util.promisify(cp.exec)(`zip -r "${binaryName}.zip" "${binaryName}"`, { cwd: releasePath });
this.log(`Archive: ${archivePath}.zip`);
} else {
await util.promisify(cp.exec)(`tar -czf "${binaryName}.tar.gz" "${binaryName}"`, { cwd: releasePath });
this.log(`Archive: ${archivePath}.tar.gz`);
}
}
}
const builder = new Builder();
builder.run(process.argv[2] as Task, process.argv.slice(3));
| scripts/build.ts | 1 | https://github.com/coder/code-server/commit/82e2b8a1698ece678f732a1d60f359997ac311ed | [
0.9985184073448181,
0.2740326523780823,
0.00016455879085697234,
0.001072907354682684,
0.4365232586860657
]
|
{
"id": 3,
"code_window": [
"\t\tconst binariesPath = path.join(this.outPath, \"binaries\");\n",
"\t\tconst binaryName = `code-server${codeServerVersion}-vsc${vscodeVersion}-${target}-${arch}`;\n",
"\t\tconst finalBuildPath = path.join(stagingPath, `${binaryName}-built`);\n",
"\n",
"\t\tswitch (task) {\n",
"\t\t\tcase Task.Binary:\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tconst finalBuildPath = path.join(this.outPath, \"build\", `${binaryName}-built`);\n"
],
"file_path": "scripts/build.ts",
"type": "replace",
"edit_start_line_idx": 83
} | import * as appInsights from "applicationinsights";
import * as https from "https";
import * as http from "http";
import * as os from "os";
export class TelemetryClient implements appInsights.TelemetryClient {
public config: any = {};
public channel = {
setUseDiskRetryCaching: (): void => undefined,
};
public trackEvent(options: appInsights.EventTelemetry): void {
if (!options.properties) {
options.properties = {};
}
if (!options.measurements) {
options.measurements = {};
}
try {
const cpus = os.cpus();
options.measurements.cores = cpus.length;
options.properties["common.cpuModel"] = cpus[0].model;
} catch (error) {}
try {
options.measurements.memoryFree = os.freemem();
options.measurements.memoryTotal = os.totalmem();
} catch (error) {}
try {
options.properties["common.shell"] = os.userInfo().shell;
options.properties["common.release"] = os.release();
options.properties["common.arch"] = os.arch();
} catch (error) {}
try {
const url = process.env.TELEMETRY_URL || "https://v1.telemetry.coder.com/track";
const request = (/^http:/.test(url) ? http : https).request(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
});
request.on("error", () => { /* We don't care. */ });
request.write(JSON.stringify(options));
request.end();
} catch (error) {}
}
public flush(options: appInsights.FlushOptions): void {
if (options.callback) {
options.callback("");
}
}
}
| src/node/insights.ts | 0 | https://github.com/coder/code-server/commit/82e2b8a1698ece678f732a1d60f359997ac311ed | [
0.0005439946544356644,
0.00023557468375656754,
0.00017004385881591588,
0.0001746472844388336,
0.00013795062841381878
]
|
{
"id": 3,
"code_window": [
"\t\tconst binariesPath = path.join(this.outPath, \"binaries\");\n",
"\t\tconst binaryName = `code-server${codeServerVersion}-vsc${vscodeVersion}-${target}-${arch}`;\n",
"\t\tconst finalBuildPath = path.join(stagingPath, `${binaryName}-built`);\n",
"\n",
"\t\tswitch (task) {\n",
"\t\t\tcase Task.Binary:\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tconst finalBuildPath = path.join(this.outPath, \"build\", `${binaryName}-built`);\n"
],
"file_path": "scripts/build.ts",
"type": "replace",
"edit_start_line_idx": 83
} | {
"compilerOptions": {
"module": "commonjs",
"moduleResolution": "node",
"noImplicitAny": true,
"experimentalDecorators": true,
"noImplicitReturns": true,
"noUnusedLocals": true,
"noImplicitThis": true,
"alwaysStrict": true,
"strictBindCallApply": true,
"strictNullChecks": true,
"forceConsistentCasingInFileNames": true,
"baseUrl": ".",
"target": "esnext"
}
}
| scripts/tsconfig.json | 0 | https://github.com/coder/code-server/commit/82e2b8a1698ece678f732a1d60f359997ac311ed | [
0.0001762708561727777,
0.00017489507445134223,
0.00017351930728182197,
0.00017489507445134223,
0.0000013757745591647108
]
|
{
"id": 3,
"code_window": [
"\t\tconst binariesPath = path.join(this.outPath, \"binaries\");\n",
"\t\tconst binaryName = `code-server${codeServerVersion}-vsc${vscodeVersion}-${target}-${arch}`;\n",
"\t\tconst finalBuildPath = path.join(stagingPath, `${binaryName}-built`);\n",
"\n",
"\t\tswitch (task) {\n",
"\t\t\tcase Task.Binary:\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\tconst finalBuildPath = path.join(this.outPath, \"build\", `${binaryName}-built`);\n"
],
"file_path": "scripts/build.ts",
"type": "replace",
"edit_start_line_idx": 83
} | ---
name: Feature Request
about: Suggest an idea for this project.
title: ''
labels: 'feature'
assignees: ''
---
<!-- Please search existing issues to avoid creating duplicates. -->
<!-- Describe the feature you'd like. --> | .github/ISSUE_TEMPLATE/feature_request.md | 0 | https://github.com/coder/code-server/commit/82e2b8a1698ece678f732a1d60f359997ac311ed | [
0.00017710243992041796,
0.00017470514285378158,
0.00017230783123522997,
0.00017470514285378158,
0.0000023973043425939977
]
|
{
"id": 0,
"code_window": [
"import { lastValueFrom } from 'rxjs';\n",
"\n",
"import { AbsoluteTimeRange, HistoryItem, LanguageProvider } from '@grafana/data';\n",
"import { CompletionItemGroup, SearchFunctionType, Token, TypeaheadInput, TypeaheadOutput } from '@grafana/ui';\n",
"import { getTemplateSrv } from 'app/features/templating/template_srv';\n",
"\n",
"import { CloudWatchDatasource } from '../../datasource';\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { BackendDataSourceResponse, FetchResponse } from '@grafana/runtime';\n"
],
"file_path": "public/app/plugins/datasource/cloudwatch/language/cloudwatch-logs/CloudWatchLogsLanguageProvider.ts",
"type": "add",
"edit_start_line_idx": 4
} | import { Observable, map } from 'rxjs';
import { DataSourceInstanceSettings, DataSourceRef, getDataSourceRef, ScopedVars } from '@grafana/data';
import { getBackendSrv } from '@grafana/runtime';
import { notifyApp } from 'app/core/actions';
import { createErrorNotification } from 'app/core/copy/appNotification';
import { TemplateSrv } from 'app/features/templating/template_srv';
import { store } from 'app/store/store';
import { AppNotificationTimeout } from 'app/types';
import memoizedDebounce from '../memoizedDebounce';
import { CloudWatchJsonData, Dimensions, MetricRequest, MultiFilters, TSDBResponse } from '../types';
export abstract class CloudWatchRequest {
templateSrv: TemplateSrv;
ref: DataSourceRef;
dsQueryEndpoint = '/api/ds/query';
debouncedCustomAlert: (title: string, message: string) => void = memoizedDebounce(
displayCustomError,
AppNotificationTimeout.Error
);
constructor(public instanceSettings: DataSourceInstanceSettings<CloudWatchJsonData>, templateSrv: TemplateSrv) {
this.templateSrv = templateSrv;
this.ref = getDataSourceRef(instanceSettings);
}
awsRequest(url: string, data: MetricRequest, headers: Record<string, string> = {}): Observable<TSDBResponse> {
const options = {
method: 'POST',
url,
data,
headers,
};
return getBackendSrv()
.fetch<TSDBResponse>(options)
.pipe(map((result) => result.data));
}
convertDimensionFormat(dimensions: Dimensions, scopedVars: ScopedVars): Dimensions {
return Object.entries(dimensions).reduce((result, [key, value]) => {
key = this.replaceVariableAndDisplayWarningIfMulti(key, scopedVars, true, 'dimension keys');
if (Array.isArray(value)) {
return { ...result, [key]: value };
}
if (!value) {
return { ...result, [key]: null };
}
const newValues = this.expandVariableToArray(value, scopedVars);
return { ...result, [key]: newValues };
}, {});
}
// get the value for a given template variable
expandVariableToArray(value: string, scopedVars: ScopedVars): string[] {
const variableName = this.templateSrv.getVariableName(value);
const valueVar = this.templateSrv.getVariables().find(({ name }) => {
return name === variableName;
});
if (variableName && valueVar) {
const isMultiVariable =
valueVar?.type === 'custom' || valueVar?.type === 'query' || valueVar?.type === 'datasource';
if (isMultiVariable && valueVar.multi) {
return this.templateSrv.replace(value, scopedVars, 'pipe').split('|');
}
return [this.templateSrv.replace(value, scopedVars)];
}
return [value];
}
convertMultiFilterFormat(multiFilters: MultiFilters, fieldName?: string) {
return Object.entries(multiFilters).reduce((result, [key, values]) => {
const interpolatedKey = this.replaceVariableAndDisplayWarningIfMulti(key, {}, true, fieldName);
if (!values) {
return { ...result, [interpolatedKey]: null };
}
const initialVal: string[] = [];
const newValues = values.reduce((result, value) => {
const vals = this.expandVariableToArray(value, {});
return [...result, ...vals];
}, initialVal);
return { ...result, [interpolatedKey]: newValues };
}, {});
}
replaceVariableAndDisplayWarningIfMulti(
target?: string,
scopedVars?: ScopedVars,
displayErrorIfIsMultiTemplateVariable?: boolean,
fieldName?: string
) {
if (displayErrorIfIsMultiTemplateVariable && !!target) {
const variables = this.templateSrv.getVariables();
const variable = variables.find(({ name }) => name === this.templateSrv.getVariableName(target));
const isMultiVariable =
variable?.type === 'custom' || variable?.type === 'query' || variable?.type === 'datasource';
if (isMultiVariable && variable.multi) {
this.debouncedCustomAlert(
'CloudWatch templating error',
`Multi template variables are not supported for ${fieldName || target}`
);
}
}
return this.templateSrv.replace(target, scopedVars);
}
getActualRegion(region?: string) {
if (region === 'default' || region === undefined || region === '') {
return this.instanceSettings.jsonData.defaultRegion ?? '';
}
return region;
}
getVariables() {
return this.templateSrv.getVariables().map((v) => `$${v.name}`);
}
}
const displayCustomError = (title: string, message: string) =>
store.dispatch(notifyApp(createErrorNotification(title, message)));
| public/app/plugins/datasource/cloudwatch/query-runner/CloudWatchRequest.ts | 1 | https://github.com/grafana/grafana/commit/96453c6e69caa37488cc44c844a754eaff56eea2 | [
0.002504754113033414,
0.0006393938092514873,
0.00017131210188381374,
0.00042727982508949935,
0.0006649246788583696
]
|
{
"id": 0,
"code_window": [
"import { lastValueFrom } from 'rxjs';\n",
"\n",
"import { AbsoluteTimeRange, HistoryItem, LanguageProvider } from '@grafana/data';\n",
"import { CompletionItemGroup, SearchFunctionType, Token, TypeaheadInput, TypeaheadOutput } from '@grafana/ui';\n",
"import { getTemplateSrv } from 'app/features/templating/template_srv';\n",
"\n",
"import { CloudWatchDatasource } from '../../datasource';\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { BackendDataSourceResponse, FetchResponse } from '@grafana/runtime';\n"
],
"file_path": "public/app/plugins/datasource/cloudwatch/language/cloudwatch-logs/CloudWatchLogsLanguageProvider.ts",
"type": "add",
"edit_start_line_idx": 4
} | package util
import (
"fmt"
"testing"
"github.com/stretchr/testify/assert"
)
func TestIsEmail(t *testing.T) {
t.Parallel()
emails := map[string]struct {
description string
valid bool
}{
"": {description: "the empty string", valid: false},
"@.": {description: "at dot", valid: false},
"me@": {description: "no domain", valid: false},
"abcdef.com": {description: "only a domain name", valid: false},
"@example.org": {description: "no recipient", valid: false},
"please\[email protected]": {description: "new line", valid: false},
"[email protected]": {description: "a simple valid email", valid: true},
"[email protected]": {description: "a gmail style alias", valid: true},
"ö[email protected]": {description: "non-ASCII characters", valid: true},
}
for input, testcase := range emails {
validity := "invalid"
if testcase.valid {
validity = "valid"
}
t.Run(fmt.Sprintf("validating that %s is %s", testcase.description, validity), func(t *testing.T) {
assert.Equal(t, testcase.valid, IsEmail(input))
})
}
}
| pkg/util/validation_test.go | 0 | https://github.com/grafana/grafana/commit/96453c6e69caa37488cc44c844a754eaff56eea2 | [
0.00017439677321817726,
0.00017292150005232543,
0.00016948053962551057,
0.00017390435095876455,
0.000002001146867769421
]
|
{
"id": 0,
"code_window": [
"import { lastValueFrom } from 'rxjs';\n",
"\n",
"import { AbsoluteTimeRange, HistoryItem, LanguageProvider } from '@grafana/data';\n",
"import { CompletionItemGroup, SearchFunctionType, Token, TypeaheadInput, TypeaheadOutput } from '@grafana/ui';\n",
"import { getTemplateSrv } from 'app/features/templating/template_srv';\n",
"\n",
"import { CloudWatchDatasource } from '../../datasource';\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { BackendDataSourceResponse, FetchResponse } from '@grafana/runtime';\n"
],
"file_path": "public/app/plugins/datasource/cloudwatch/language/cloudwatch-logs/CloudWatchLogsLanguageProvider.ts",
"type": "add",
"edit_start_line_idx": 4
} | package fsutil
import (
"fmt"
"io"
"log"
"os"
"path/filepath"
)
// CopyFile copies a file from src to dst.
//
// If src and dst files exist, and are the same, then return success. Otherwise, attempt to create a hard link
// between the two files. If that fails, copy the file contents from src to dst.
func CopyFile(src, dst string) (err error) {
absSrc, err := filepath.Abs(src)
if err != nil {
return fmt.Errorf("failed to get absolute path of source file %q: %w", src, err)
}
sfi, err := os.Stat(src)
if err != nil {
err = fmt.Errorf("couldn't stat source file %q: %w", absSrc, err)
return
}
if !sfi.Mode().IsRegular() {
// Cannot copy non-regular files (e.g., directories, symlinks, devices, etc.)
return fmt.Errorf("non-regular source file %s (%q)", absSrc, sfi.Mode().String())
}
dpath := filepath.Dir(dst)
exists, err := Exists(dpath)
if err != nil {
return err
}
if !exists {
err = fmt.Errorf("destination directory doesn't exist: %q", dpath)
return
}
var dfi os.FileInfo
dfi, err = os.Stat(dst)
if err != nil {
if !os.IsNotExist(err) {
return
}
} else {
if !(dfi.Mode().IsRegular()) {
return fmt.Errorf("non-regular destination file %s (%q)", dfi.Name(), dfi.Mode().String())
}
if os.SameFile(sfi, dfi) {
return copyPermissions(sfi.Name(), dfi.Name())
}
}
err = copyFileContents(src, dst)
return err
}
// copyFileContents copies the contents of the file named src to the file named
// by dst. The file will be created if it does not already exist. If the
// destination file exists, all it's contents will be replaced by the contents
// of the source file.
func copyFileContents(src, dst string) (err error) {
//nolint:gosec
in, err := os.Open(src)
if err != nil {
return
}
defer func() {
if err := in.Close(); err != nil {
log.Println("error closing file", err)
}
}()
//nolint:gosec
out, err := os.Create(dst)
if err != nil {
return
}
defer func() {
if cerr := out.Close(); cerr != nil && err == nil {
err = cerr
}
}()
if _, err = io.Copy(out, in); err != nil {
return
}
if err := out.Sync(); err != nil {
return err
}
return copyPermissions(src, dst)
}
func copyPermissions(src, dst string) error {
sfi, err := os.Lstat(src)
if err != nil {
return err
}
if err := os.Chmod(dst, sfi.Mode()); err != nil {
return err
}
return nil
}
| pkg/build/fsutil/copyfile.go | 0 | https://github.com/grafana/grafana/commit/96453c6e69caa37488cc44c844a754eaff56eea2 | [
0.00017567486793268472,
0.00017227279022336006,
0.00016616960056126118,
0.00017307019152212888,
0.000003136679652016028
]
|
{
"id": 0,
"code_window": [
"import { lastValueFrom } from 'rxjs';\n",
"\n",
"import { AbsoluteTimeRange, HistoryItem, LanguageProvider } from '@grafana/data';\n",
"import { CompletionItemGroup, SearchFunctionType, Token, TypeaheadInput, TypeaheadOutput } from '@grafana/ui';\n",
"import { getTemplateSrv } from 'app/features/templating/template_srv';\n",
"\n",
"import { CloudWatchDatasource } from '../../datasource';\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { BackendDataSourceResponse, FetchResponse } from '@grafana/runtime';\n"
],
"file_path": "public/app/plugins/datasource/cloudwatch/language/cloudwatch-logs/CloudWatchLogsLanguageProvider.ts",
"type": "add",
"edit_start_line_idx": 4
} | package searchV2
import (
"context"
"fmt"
"testing"
"time"
"github.com/stretchr/testify/require"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/infra/tracing"
"github.com/grafana/grafana/pkg/services/accesscontrol/actest"
"github.com/grafana/grafana/pkg/services/dashboards"
"github.com/grafana/grafana/pkg/services/featuremgmt"
"github.com/grafana/grafana/pkg/services/org"
"github.com/grafana/grafana/pkg/services/org/orgtest"
"github.com/grafana/grafana/pkg/services/sqlstore"
"github.com/grafana/grafana/pkg/services/store"
"github.com/grafana/grafana/pkg/services/user"
"github.com/grafana/grafana/pkg/setting"
)
// setupBenchEnv will set up a database with folderCount folders and dashboardsPerFolder dashboards per folder
// It will also set up and run the search service
// and create a signed in user object with explicit permissions on each dashboard and folder.
func setupBenchEnv(b *testing.B, folderCount, dashboardsPerFolder int) (*StandardSearchService, *user.SignedInUser, error) {
sqlStore := db.InitTestDB(b)
err := populateDB(folderCount, dashboardsPerFolder, sqlStore)
require.NoError(b, err, "error when populating the database")
// load all dashboards and folders
dbLoadingBatchSize := (dashboardsPerFolder + 1) * folderCount
cfg := &setting.Cfg{Search: setting.SearchSettings{DashboardLoadingBatchSize: dbLoadingBatchSize}}
features := featuremgmt.WithFeatures()
orgSvc := &orgtest.FakeOrgService{
ExpectedOrgs: []*org.OrgDTO{{ID: 1}},
}
searchService, ok := ProvideService(cfg, sqlStore, store.NewDummyEntityEventsService(), actest.FakeService{},
tracing.InitializeTracerForTest(), features, orgSvc, nil, nil).(*StandardSearchService)
require.True(b, ok)
err = runSearchService(searchService)
require.NoError(b, err, "error when running search service")
user := getSignedInUser(folderCount, dashboardsPerFolder)
return searchService, user, nil
}
// Returns a signed in user object with permissions on all dashboards and folders
func getSignedInUser(folderCount, dashboardsPerFolder int) *user.SignedInUser {
folderScopes := make([]string, folderCount)
for i := 1; i <= folderCount; i++ {
folderScopes[i-1] = dashboards.ScopeFoldersProvider.GetResourceScopeUID(fmt.Sprintf("folder%d", i))
}
dashScopes := make([]string, folderCount*dashboardsPerFolder)
for i := folderCount + 1; i <= (folderCount * (dashboardsPerFolder + 1)); i++ {
dashScopes[i-(folderCount+1)] = dashboards.ScopeDashboardsProvider.GetResourceScopeUID(fmt.Sprintf("dashboard%d", i))
}
user := &user.SignedInUser{
UserID: 1,
OrgID: 1,
Permissions: map[int64]map[string][]string{
1: {
dashboards.ActionDashboardsRead: dashScopes,
dashboards.ActionFoldersRead: folderScopes,
},
},
}
return user
}
// Runs initial indexing of search service
func runSearchService(searchService *StandardSearchService) error {
if err := searchService.dashboardIndex.buildInitialIndexes(context.Background(), []int64{int64(1)}); err != nil {
return err
}
searchService.dashboardIndex.initialIndexingComplete = true
// Required for sync that is called during dashboard search
go func() {
for {
doneCh := <-searchService.dashboardIndex.syncCh
close(doneCh)
}
}()
return nil
}
// Populates database with dashboards and folders
func populateDB(folderCount, dashboardsPerFolder int, sqlStore *sqlstore.SQLStore) error {
// Insert folders
offset := 1
if errInsert := actest.ConcurrentBatch(actest.Concurrency, folderCount, actest.BatchSize, func(start, end int) error {
n := end - start
folders := make([]dashboards.Dashboard, 0, n)
now := time.Now()
for u := start; u < end; u++ {
folderID := int64(u + offset)
folders = append(folders, dashboards.Dashboard{
ID: folderID,
UID: fmt.Sprintf("folder%v", folderID),
Title: fmt.Sprintf("folder%v", folderID),
IsFolder: true,
OrgID: 1,
Created: now,
Updated: now,
})
}
err := sqlStore.WithDbSession(context.Background(), func(sess *db.Session) error {
if _, err := sess.Insert(folders); err != nil {
return err
}
return nil
})
return err
}); errInsert != nil {
return errInsert
}
// Insert dashboards
offset += folderCount
if errInsert := actest.ConcurrentBatch(actest.Concurrency, dashboardsPerFolder*folderCount, actest.BatchSize, func(start, end int) error {
n := end - start
dbs := make([]dashboards.Dashboard, 0, n)
now := time.Now()
for u := start; u < end; u++ {
dashID := int64(u + offset)
folderID := int64((u+offset)%folderCount + 1)
dbs = append(dbs, dashboards.Dashboard{
ID: dashID,
UID: fmt.Sprintf("dashboard%v", dashID),
Title: fmt.Sprintf("dashboard%v", dashID),
IsFolder: false,
FolderID: folderID,
OrgID: 1,
Created: now,
Updated: now,
})
}
err := sqlStore.WithDbSession(context.Background(), func(sess *db.Session) error {
if _, err := sess.Insert(dbs); err != nil {
return err
}
return nil
})
return err
}); errInsert != nil {
return errInsert
}
return nil
}
func benchSearchV2(b *testing.B, folderCount, dashboardsPerFolder int) {
searchService, testUser, err := setupBenchEnv(b, folderCount, dashboardsPerFolder)
require.NoError(b, err)
b.ResetTimer()
expectedResultCount := (dashboardsPerFolder + 1) * folderCount
for n := 0; n < b.N; n++ {
result := searchService.doDashboardQuery(context.Background(), testUser, 1, DashboardQuery{Limit: expectedResultCount})
require.NoError(b, result.Error)
require.NotZero(b, len(result.Frames))
for _, field := range result.Frames[0].Fields {
if field.Name == "uid" {
require.Equal(b, expectedResultCount, field.Len())
break
}
}
}
}
// Test with some dashboards and some folders
func BenchmarkSearchV2_10_10(b *testing.B) {
benchSearchV2(b, 10, 10)
} // ~0.0002 s/op
func BenchmarkSearchV2_10_100(b *testing.B) {
benchSearchV2(b, 10, 100)
} // ~0.002 s/op
// Test with many dashboards and only one folder
func BenchmarkSearchV2_1_1k(b *testing.B) {
benchSearchV2(b, 1, 1000)
} // ~0.002 s/op
func BenchmarkSearchV2_1_10k(b *testing.B) {
benchSearchV2(b, 1, 10000)
} // ~0.019 s/op
// Test with a large number of dashboards and folders
func BenchmarkSearchV2_100_100(b *testing.B) {
benchSearchV2(b, 100, 100)
} // ~0.02 s/op
func BenchmarkSearchV2_100_1k(b *testing.B) {
benchSearchV2(b, 100, 1000)
} // ~0.22 s/op
func BenchmarkSearchV2_1k_100(b *testing.B) {
benchSearchV2(b, 1000, 100)
} // ~0.22 s/op
| pkg/services/searchV2/service_bench_test.go | 0 | https://github.com/grafana/grafana/commit/96453c6e69caa37488cc44c844a754eaff56eea2 | [
0.00017624866450205445,
0.0001707444025669247,
0.00016375925042666495,
0.00017157661204691976,
0.000004144663762417622
]
|
{
"id": 1,
"code_window": [
"import { CompletionItemGroup, SearchFunctionType, Token, TypeaheadInput, TypeaheadOutput } from '@grafana/ui';\n",
"import { getTemplateSrv } from 'app/features/templating/template_srv';\n",
"\n",
"import { CloudWatchDatasource } from '../../datasource';\n",
"import { CloudWatchQuery, LogGroup, TSDBResponse } from '../../types';\n",
"import { interpolateStringArrayUsingSingleOrMultiValuedVariable } from '../../utils/templateVariableUtils';\n",
"\n",
"import syntax, {\n",
" AGGREGATION_FUNCTIONS_STATS,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { CloudWatchQuery, LogGroup } from '../../types';\n"
],
"file_path": "public/app/plugins/datasource/cloudwatch/language/cloudwatch-logs/CloudWatchLogsLanguageProvider.ts",
"type": "replace",
"edit_start_line_idx": 8
} | import { set, uniq } from 'lodash';
import {
catchError,
concatMap,
finalize,
from,
lastValueFrom,
map,
mergeMap,
Observable,
repeat,
scan,
share,
takeWhile,
tap,
zip,
} from 'rxjs';
import {
DataFrame,
DataQueryError,
DataQueryErrorType,
DataQueryRequest,
DataQueryResponse,
DataSourceInstanceSettings,
LoadingState,
LogRowModel,
rangeUtil,
} from '@grafana/data';
import { BackendDataSourceResponse, config, FetchError, FetchResponse, toDataQueryResponse } from '@grafana/runtime';
import { TimeSrv } from 'app/features/dashboard/services/TimeSrv';
import { TemplateSrv } from 'app/features/templating/template_srv';
import { RowContextOptions } from '../../../../features/logs/components/LogRowContextProvider';
import {
CloudWatchJsonData,
CloudWatchLogsQuery,
CloudWatchLogsQueryStatus,
CloudWatchLogsRequest,
CloudWatchQuery,
GetLogEventsRequest,
LogAction,
QueryParam,
StartQueryRequest,
} from '../types';
import { addDataLinksToLogsResponse } from '../utils/datalinks';
import { runWithRetry } from '../utils/logsRetry';
import { increasingInterval } from '../utils/rxjs/increasingInterval';
import { interpolateStringArrayUsingSingleOrMultiValuedVariable } from '../utils/templateVariableUtils';
import { CloudWatchRequest } from './CloudWatchRequest';
export const LOG_IDENTIFIER_INTERNAL = '__log__grafana_internal__';
export const LOGSTREAM_IDENTIFIER_INTERNAL = '__logstream__grafana_internal__';
// This class handles execution of CloudWatch logs query data queries
export class CloudWatchLogsQueryRunner extends CloudWatchRequest {
logsTimeout: string;
logQueries: Record<string, { id: string; region: string; statsQuery: boolean }> = {};
tracingDataSourceUid?: string;
constructor(
instanceSettings: DataSourceInstanceSettings<CloudWatchJsonData>,
templateSrv: TemplateSrv,
private readonly timeSrv: TimeSrv
) {
super(instanceSettings, templateSrv);
this.tracingDataSourceUid = instanceSettings.jsonData.tracingDatasourceUid;
this.logsTimeout = instanceSettings.jsonData.logsTimeout || '30m';
}
/**
* Handle log query. The log query works by starting the query on the CloudWatch and then periodically polling for
* results.
* @param logQueries
* @param options
*/
handleLogQueries = (
logQueries: CloudWatchLogsQuery[],
options: DataQueryRequest<CloudWatchQuery>
): Observable<DataQueryResponse> => {
const validLogQueries = logQueries.filter(this.filterQuery);
const startQueryRequests: StartQueryRequest[] = validLogQueries.map((target: CloudWatchLogsQuery) => {
const interpolatedLogGroupArns = interpolateStringArrayUsingSingleOrMultiValuedVariable(
this.templateSrv,
(target.logGroups || this.instanceSettings.jsonData.logGroups || []).map((lg) => lg.arn),
options.scopedVars
);
// need to support legacy format variables too
const interpolatedLogGroupNames = interpolateStringArrayUsingSingleOrMultiValuedVariable(
this.templateSrv,
target.logGroupNames || this.instanceSettings.jsonData.defaultLogGroups || [],
options.scopedVars,
'text'
);
// if a log group template variable expands to log group that has already been selected in the log group picker, we need to remove duplicates.
// Otherwise the StartLogQuery API will return a permission error
const logGroups = uniq(interpolatedLogGroupArns).map((arn) => ({ arn, name: arn }));
const logGroupNames = uniq(interpolatedLogGroupNames);
return {
refId: target.refId,
region: this.templateSrv.replace(this.getActualRegion(target.region)),
queryString: this.templateSrv.replace(target.expression || '', options.scopedVars),
logGroups,
logGroupNames,
};
});
const startTime = new Date();
const timeoutFunc = () => {
return Date.now() >= startTime.valueOf() + rangeUtil.intervalToMs(this.logsTimeout);
};
return runWithRetry(
(targets: StartQueryRequest[]) => {
return this.makeLogActionRequest('StartQuery', targets, options);
},
startQueryRequests,
timeoutFunc
).pipe(
mergeMap(({ frames, error }: { frames: DataFrame[]; error?: DataQueryError }) =>
// This queries for the results
this.logsQuery(
frames.map((dataFrame) => ({
queryId: dataFrame.fields[0].values.get(0),
region: dataFrame.meta?.custom?.['Region'] ?? 'default',
refId: dataFrame.refId!,
statsGroups: logQueries.find((target) => target.refId === dataFrame.refId)?.statsGroups,
})),
timeoutFunc
).pipe(
map((response: DataQueryResponse) => {
if (!response.error && error) {
response.error = error;
}
return response;
})
)
),
mergeMap((dataQueryResponse) => {
return from(
(async () => {
await addDataLinksToLogsResponse(
dataQueryResponse,
options,
this.timeSrv.timeRange(),
this.replaceVariableAndDisplayWarningIfMulti.bind(this),
this.expandVariableToArray.bind(this),
this.getActualRegion.bind(this),
this.tracingDataSourceUid
);
return dataQueryResponse;
})()
);
})
);
};
/**
* Checks progress and polls data of a started logs query with some retry logic.
* @param queryParams
*/
logsQuery(queryParams: QueryParam[], timeoutFunc: () => boolean): Observable<DataQueryResponse> {
this.logQueries = {};
queryParams.forEach((param) => {
this.logQueries[param.refId] = {
id: param.queryId,
region: param.region,
statsQuery: (param.statsGroups?.length ?? 0) > 0 ?? false,
};
});
const dataFrames = increasingInterval({ startPeriod: 100, endPeriod: 1000, step: 300 }).pipe(
concatMap((_) => this.makeLogActionRequest('GetQueryResults', queryParams)),
repeat(),
share()
);
const initialValue: { failures: number; prevRecordsMatched: Record<string, number> } = {
failures: 0,
prevRecordsMatched: {},
};
const consecutiveFailedAttempts = dataFrames.pipe(
scan(({ failures, prevRecordsMatched }, frames) => {
failures++;
for (const frame of frames) {
const recordsMatched = frame.meta?.stats?.find((stat) => stat.displayName === 'Records scanned')?.value!;
if (recordsMatched > (prevRecordsMatched[frame.refId!] ?? 0)) {
failures = 0;
}
prevRecordsMatched[frame.refId!] = recordsMatched;
}
return { failures, prevRecordsMatched };
}, initialValue),
map(({ failures }) => failures),
share()
);
const queryResponse: Observable<DataQueryResponse> = zip(dataFrames, consecutiveFailedAttempts).pipe(
tap(([dataFrames]) => {
for (const frame of dataFrames) {
if (
[
CloudWatchLogsQueryStatus.Complete,
CloudWatchLogsQueryStatus.Cancelled,
CloudWatchLogsQueryStatus.Failed,
].includes(frame.meta?.custom?.['Status']) &&
this.logQueries.hasOwnProperty(frame.refId!)
) {
delete this.logQueries[frame.refId!];
}
}
}),
map(([dataFrames, failedAttempts]) => {
if (timeoutFunc()) {
for (const frame of dataFrames) {
set(frame, 'meta.custom.Status', CloudWatchLogsQueryStatus.Cancelled);
}
}
return {
data: dataFrames,
key: 'test-key',
state: dataFrames.every((dataFrame) =>
[
CloudWatchLogsQueryStatus.Complete,
CloudWatchLogsQueryStatus.Cancelled,
CloudWatchLogsQueryStatus.Failed,
].includes(dataFrame.meta?.custom?.['Status'])
)
? LoadingState.Done
: LoadingState.Loading,
error: timeoutFunc()
? {
message: `error: query timed out after ${failedAttempts} attempts`,
type: DataQueryErrorType.Timeout,
}
: undefined,
};
}),
takeWhile(({ state }) => state !== LoadingState.Error && state !== LoadingState.Done, true)
);
return withTeardown(queryResponse, () => this.stopQueries());
}
stopQueries() {
if (Object.keys(this.logQueries).length > 0) {
this.makeLogActionRequest(
'StopQuery',
Object.values(this.logQueries).map((logQuery) => ({
queryId: logQuery.id,
region: logQuery.region,
queryString: '',
refId: '',
}))
).pipe(
finalize(() => {
this.logQueries = {};
})
);
}
}
makeLogActionRequest(
subtype: LogAction,
queryParams: CloudWatchLogsRequest[],
options?: DataQueryRequest<CloudWatchQuery>
): Observable<DataFrame[]> {
const range = options?.range || this.timeSrv.timeRange();
const requestParams = {
from: range.from.valueOf().toString(),
to: range.to.valueOf().toString(),
queries: queryParams.map((param: CloudWatchLogsRequest) => ({
// eslint-ignore-next-line
refId: (param as StartQueryRequest).refId || 'A',
intervalMs: 1, // dummy
maxDataPoints: 1, // dummy
datasource: this.ref,
type: 'logAction',
subtype: subtype,
...param,
})),
};
const resultsToDataFrames = (
val:
| { data: BackendDataSourceResponse | undefined }
| FetchResponse<BackendDataSourceResponse | undefined>
| DataQueryError
): DataFrame[] => toDataQueryResponse(val).data || [];
return this.awsRequest(this.dsQueryEndpoint, requestParams, {
'X-Cache-Skip': 'true',
}).pipe(
map((response) => resultsToDataFrames({ data: response })),
catchError((err: FetchError) => {
if (config.featureToggles.datasourceQueryMultiStatus && err.status === 207) {
throw err;
}
if (err.status === 400) {
throw err;
}
if (err.data?.error) {
throw err.data.error;
} else if (err.data?.message) {
// In PROD we do not supply .error
throw err.data.message;
}
throw err;
})
);
}
getLogRowContext = async (
row: LogRowModel,
{ limit = 10, direction = 'BACKWARD' }: RowContextOptions = {},
query?: CloudWatchLogsQuery
): Promise<{ data: DataFrame[] }> => {
let logStreamField = null;
let logField = null;
for (const field of row.dataFrame.fields) {
if (field.name === LOGSTREAM_IDENTIFIER_INTERNAL) {
logStreamField = field;
if (logField !== null) {
break;
}
} else if (field.name === LOG_IDENTIFIER_INTERNAL) {
logField = field;
if (logStreamField !== null) {
break;
}
}
}
const requestParams: GetLogEventsRequest = {
limit,
startFromHead: direction !== 'BACKWARD',
region: query?.region,
logGroupName: parseLogGroupName(logField!.values.get(row.rowIndex)),
logStreamName: logStreamField!.values.get(row.rowIndex),
};
if (direction === 'BACKWARD') {
requestParams.endTime = row.timeEpochMs;
} else {
requestParams.startTime = row.timeEpochMs;
}
const dataFrames = await lastValueFrom(this.makeLogActionRequest('GetLogEvents', [requestParams]));
return {
data: dataFrames,
};
};
private filterQuery(query: CloudWatchLogsQuery) {
const hasMissingLegacyLogGroupNames = !query.logGroupNames?.length;
const hasMissingLogGroups = !query.logGroups?.length;
const hasMissingQueryString = !query.expression?.length;
if ((hasMissingLogGroups && hasMissingLegacyLogGroupNames) || hasMissingQueryString) {
return false;
}
return true;
}
}
function withTeardown<T = DataQueryResponse>(observable: Observable<T>, onUnsubscribe: () => void): Observable<T> {
return new Observable<T>((subscriber) => {
const innerSub = observable.subscribe({
next: (val) => subscriber.next(val),
error: (err) => subscriber.next(err),
complete: () => subscriber.complete(),
});
return () => {
innerSub.unsubscribe();
onUnsubscribe();
};
});
}
function parseLogGroupName(logIdentifier: string): string {
const colonIndex = logIdentifier.lastIndexOf(':');
return logIdentifier.slice(colonIndex + 1);
}
| public/app/plugins/datasource/cloudwatch/query-runner/CloudWatchLogsQueryRunner.ts | 1 | https://github.com/grafana/grafana/commit/96453c6e69caa37488cc44c844a754eaff56eea2 | [
0.014603085815906525,
0.00082374521298334,
0.00016393688565585762,
0.00017512998601887375,
0.002359942300245166
]
|
{
"id": 1,
"code_window": [
"import { CompletionItemGroup, SearchFunctionType, Token, TypeaheadInput, TypeaheadOutput } from '@grafana/ui';\n",
"import { getTemplateSrv } from 'app/features/templating/template_srv';\n",
"\n",
"import { CloudWatchDatasource } from '../../datasource';\n",
"import { CloudWatchQuery, LogGroup, TSDBResponse } from '../../types';\n",
"import { interpolateStringArrayUsingSingleOrMultiValuedVariable } from '../../utils/templateVariableUtils';\n",
"\n",
"import syntax, {\n",
" AGGREGATION_FUNCTIONS_STATS,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { CloudWatchQuery, LogGroup } from '../../types';\n"
],
"file_path": "public/app/plugins/datasource/cloudwatch/language/cloudwatch-logs/CloudWatchLogsLanguageProvider.ts",
"type": "replace",
"edit_start_line_idx": 8
} | import React, { useCallback, useState } from 'react';
import { DataSourceRef, SelectableValue } from '@grafana/data';
import { t } from 'app/core/internationalization';
import { AdHocVariableFilter } from 'app/features/variables/types';
import { AdHocFilterKey, REMOVE_FILTER_KEY } from './AdHocFilterKey';
import { AdHocFilterRenderer } from './AdHocFilterRenderer';
interface Props {
datasource: DataSourceRef;
onCompleted: (filter: AdHocVariableFilter) => void;
appendBefore?: React.ReactNode;
getTagKeysOptions?: any;
}
export const AdHocFilterBuilder = ({ datasource, appendBefore, onCompleted, getTagKeysOptions }: Props) => {
const [key, setKey] = useState<string | null>(null);
const [operator, setOperator] = useState<string>('=');
const onKeyChanged = useCallback(
(item: SelectableValue<string | null>) => {
if (item.value !== REMOVE_FILTER_KEY) {
setKey(item.value ?? '');
return;
}
setKey(null);
},
[setKey]
);
const onOperatorChanged = useCallback(
(item: SelectableValue<string>) => setOperator(item.value ?? ''),
[setOperator]
);
const onValueChanged = useCallback(
(item: SelectableValue<string>) => {
onCompleted({
value: item.value ?? '',
operator: operator,
condition: '',
key: key!,
});
setKey(null);
setOperator('=');
},
[onCompleted, operator, key]
);
if (key === null) {
return (
<AdHocFilterKey
datasource={datasource}
filterKey={key}
onChange={onKeyChanged}
getTagKeysOptions={getTagKeysOptions}
/>
);
}
return (
<React.Fragment key="filter-builder">
{appendBefore}
<AdHocFilterRenderer
datasource={datasource}
filter={{ key, value: '', operator, condition: '' }}
placeHolder={t('variable.adhoc.placeholder', 'Select value')}
onKeyChange={onKeyChanged}
onOperatorChange={onOperatorChanged}
onValueChange={onValueChanged}
getTagKeysOptions={getTagKeysOptions}
/>
</React.Fragment>
);
};
| public/app/features/variables/adhoc/picker/AdHocFilterBuilder.tsx | 0 | https://github.com/grafana/grafana/commit/96453c6e69caa37488cc44c844a754eaff56eea2 | [
0.0001755897974362597,
0.00017136103997472674,
0.0001667505275690928,
0.00017178914276883006,
0.000002803304823828512
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.